Compare commits

..

604 Commits
0.0.3 ... main

Author SHA1 Message Date
Brett McBride 4274371493
update DebugScope error message (#1688)
Make the scope id in error messages consistent between the detached-with-error and not-detached cases,
by using spl_object_id($this) in the latter to match the former.
2025-08-13 11:12:00 +10:00
dependabot[bot] 49aca4a36f
Bump github/codeql-action from 3.29.7 to 3.29.8 (#1686)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.29.7 to 3.29.8.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](51f77329af...76621b61de)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.29.8
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-11 09:47:15 -04:00
Brett McBride 87a145a3b6
stabilize LocalRootSpan (#1683) 2025-08-08 09:07:38 +10:00
Brett McBride 9fb9e549bf
adding network semantic conventions (#1682) 2025-08-08 09:07:04 +10:00
Brett McBride d5fd499752
update collector to listen on all interfaces (#1685)
by default, the collector only listens on localhost now, and so is not reachable from
dev containers when running examples
2025-08-08 09:04:16 +10:00
Brett McBride d4c16332af
adding pgsql to developer docker image (#1684) 2025-08-08 09:03:53 +10:00
Chris Lightfoot-Wild 99a35dadf2
Fix psalm regressions. (#1680) 2025-08-06 13:07:06 +10:00
Evan 7981956060
feat(carreirs): implement environment context getter setter (#1668)
* feat(carreirs): implement environment context getter setter

Closes #1566

* tests(carrier): add EnvironmentGetterSetter missing test

* fix(carrier): modify keys empty env condition

* test: use OpenTelemetry\Tests\TestState trait to handle environment

* docs: add trace context and baggage environment carrier example

* refactor: clean up baggage and trace context examples by removing unused span logic

* test: fix Psalm static analysis failures
2025-08-04 13:25:06 +10:00
Brett McBride 9d68afb238
refactor semantic conventions (#1659)
Align with how the spec advises SemConv should be organised, and break unstable
semconvs out into their own directory.
I played around with generating values as enums, but I could only get this to work
if the output was in the same file as the attributes (which would not work well with
composer autoloading), so I've used <attribute>_VALUE_<name>, similar to what we have
now except all in the same file.

* fix linting, broken values containing '.'

* fix incubating namespace

* update semconv readme

* restore ResourceAttributeValues

* adding DNS semconv

* adding db metrics
2025-08-04 13:22:08 +10:00
dependabot[bot] 4afe0aad8a
Bump github/codeql-action from 3.29.3 to 3.29.5 (#1675)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.29.3 to 3.29.5.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](d6bbdef45e...51f77329af)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.29.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-04 13:21:30 +10:00
OpenTelemetry Bot 6d14251299
Add subscript to issue templates (#1677)
Co-authored-by: otelbot <197425009+otelbot@users.noreply.github.com>
2025-08-02 09:06:53 +10:00
Chris Lightfoot-Wild a54f48bbb9
Configuration\CompositeResolver and SPI discovery (#1523)
* Configuration\CompositeResolver can discover additional configuration resolvers via SPI.

* Apply suggestions from code review

Co-authored-by: Tobias Bachert <git@b-privat.de>

* Fix imports.

* Porting EnvSourceProvider changes from Nevay.

* Moved VlucasPhpdotenvProvider to sdk-configuration.

* Added SdkConfigurationResolver.

* Added SymfonyDotenvProvider.

* Removed vlucas/phpdotenv dev package.

* make style 😎

* Update deptrac for dotenv providers.

* Suppress Psalm errors for optional packages.

* Added phpstan ignoreErrors rules for optional dependency behavior.

* Added test for SPI-backed configuration loading via EnvSourceProvider

* Restructure SPI based test for EnvSourceProvider.

* Bumped SPI dependency.

* Added implied mixed return type to ResolverInterface::retrieveValue

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2025-08-01 11:37:37 +10:00
Trask Stalnaker e54a43d262
Fix scorecard checks (#1674) 2025-07-29 21:51:48 +10:00
dependabot[bot] 9c3ae60164
Bump phpDocumentor/phpDocumentor from 3.8.0 to 3.8.1 (#1669)
Bumps [phpDocumentor/phpDocumentor](https://github.com/phpdocumentor/phpdocumentor) from 3.8.0 to 3.8.1.
- [Release notes](https://github.com/phpdocumentor/phpdocumentor/releases)
- [Changelog](https://github.com/phpDocumentor/phpDocumentor/blob/master/CHANGELOG.md)
- [Commits](https://github.com/phpdocumentor/phpdocumentor/compare/v3.8.0...v3.8.1)

---
updated-dependencies:
- dependency-name: phpDocumentor/phpDocumentor
  dependency-version: 3.8.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-07-22 09:39:38 -04:00
dependabot[bot] 776bed563b
Bump github/codeql-action from 3.29.2 to 3.29.3 (#1670)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.29.2 to 3.29.3.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](181d5eefc2...d6bbdef45e)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.29.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-07-22 09:39:19 -04:00
Brett McBride 2d9097492c
fixing CI complaints (#1666)
* fixing psalm complaints
use rector (and psalm) to add Override attributes, and add symfony polyfill to
provide Override in earlier php versions

* fixing more psalm complaints

* more fixes

* adding stubs for deptrac
there are some things in our code that deptrac doesn't understand or are missing
for some php versions. stub them to quieten all those violation warnings

* why not cache invalid :(

* display tools versions

* fix tools cache key

* changing cache key

* dont complain about unused psalm suppressions

* suppress invalid attribute

* quieten phpstan php8.5 complaints

* revert previous commit...now other php versions complain about an unused ignore :(

* revert typecasting in metrics aggregators

* Update src/Contrib/Otlp/ProtobufSerializer.php

Co-authored-by: Chris Lightfoot-Wild <github-clw@wild.me.uk>

* remove override stub and use the polyfill from deptrac

---------

Co-authored-by: Chris Lightfoot-Wild <github-clw@wild.me.uk>
2025-07-22 11:02:18 +10:00
Brett McBride 2421c64c51
build base image from debian (#1662) 2025-07-11 07:11:46 -04:00
OpenTelemetry Bot dc52549640
Sort contributor listings and remove affiliation from emeriti (#1665)
Co-authored-by: otelbot <197425009+otelbot@users.noreply.github.com>
2025-07-10 09:43:36 +10:00
OpenTelemetry Bot 7033191a74
Add minimum token permissions for all github workflow files (#1655)
* Add minimum token permissions for all github workflow files

* Update .github/workflows/phpdoc-to-github-pages.yml

---------

Co-authored-by: otelbot <197425009+otelbot@users.noreply.github.com>
Co-authored-by: Trask Stalnaker <trask.stalnaker@gmail.com>
2025-07-07 11:29:47 +10:00
dependabot[bot] e27aac84f6
Bump github/codeql-action from 3.29.0 to 3.29.2 (#1656) 2025-07-01 09:00:03 -04:00
Trask Stalnaker 3968f7459a
Update community member listings (#1650)
* Update community member listings

* Update CONTRIBUTING.md

Co-authored-by: Brett McBride <brett.a.mcbride@gmail.com>

* Update CONTRIBUTING.md

Co-authored-by: Brett McBride <brett.a.mcbride@gmail.com>

* Update CONTRIBUTING.md

Co-authored-by: Brett McBride <brett.a.mcbride@gmail.com>

---------

Co-authored-by: Brett McBride <brett.a.mcbride@gmail.com>
2025-06-27 15:06:58 +10:00
Brett McBride 33715fddc1
adding metrics semconv (#1633) 2025-06-23 22:32:27 -04:00
Brett McBride 768c387068
add Logger.Enabled event name parameter (#1632)
extra parameter added in spec 1.45.0, which is optional and development stability
2025-06-20 09:36:51 +10:00
dependabot[bot] 526b8eb33d
Bump phpDocumentor/phpDocumentor from 3.7.1 to 3.8.0 (#1639)
Bumps [phpDocumentor/phpDocumentor](https://github.com/phpdocumentor/phpdocumentor) from 3.7.1 to 3.8.0.
- [Release notes](https://github.com/phpdocumentor/phpdocumentor/releases)
- [Changelog](https://github.com/phpDocumentor/phpDocumentor/blob/master/CHANGELOG.md)
- [Commits](https://github.com/phpdocumentor/phpdocumentor/compare/v3.7.1...v3.8.0)

---
updated-dependencies:
- dependency-name: phpDocumentor/phpDocumentor
  dependency-version: 3.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-06-18 09:44:45 -04:00
Brett McBride 443c662653
Psr transport network exception test (#1635)
* add test for NetworkException in PsrTransport

* remove unneeded exception expectation
2025-06-18 08:06:04 -04:00
Brett McBride 5ed1ec09db
fixing psalm+phpstan protobuf complaints (#1636) 2025-06-16 21:11:54 +10:00
Tobias Bachert 5451d57dbf
Allows API packages to specify file-based and env-based config (#1621)
* Move `ComponentProvider` and related classes to API

* Use API `ComponentProvider`

* Use API `ComponentProvider` in tests

* Add `EnvComponentLoader` API

* Add `EnvComponentLoader` example

* Ignore deptrac violations

* Remove namespace from `ComponentProvider` BC layer

* Add API requirement to config package

* Fix/suppress unrelated phpstan errors caused by `google/protobuf` `^4.31`
2025-06-16 10:24:51 +10:00
Brett McBride 95229b7bf8
skip segfaulting test on more xdebug versions (#1634)
verified that the bug we experience still exists in xdebug 3.4.4 so lets assume
it will be live for some more releases, and un-skip the test in the future
2025-06-13 20:54:15 +10:00
dependabot[bot] 04acb40874
Bump github/codeql-action from 3.28.19 to 3.29.0 (#1631)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.19 to 3.29.0.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](fca7ace96b...ce28f5bb42)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.29.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-06-13 13:47:56 +10:00
Brett McBride dcf96ddf96
update weaver to 0.15.2 (#1629) 2025-06-13 09:36:21 +10:00
Bob Strecansky 873a39c4fd
Update Dockerfile (#1625)
chore: Made the update from https://github.com/open-telemetry/opentelemetry-php/pull/1624 strictly for PHP 8.4
2025-06-10 12:12:14 +10:00
Tobias Bachert 07d1da976a
Mark `.instrumentation` as experimental (#1620) 2025-06-10 11:32:38 +10:00
dependabot[bot] 78bd695c02
Bump github/codeql-action from 3.28.18 to 3.28.19 (#1619)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.18 to 3.28.19.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](ff0a06e83c...fca7ace96b)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.28.19
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-06-04 12:42:55 -04:00
dependabot[bot] 65c2979523
Bump ossf/scorecard-action from 2.4.1 to 2.4.2 (#1616) 2025-06-02 07:03:16 -04:00
Tobias Bachert 38351980a6
Update ratio based sampler threshold algorithm (#1391)
See OTEP 235, Threshold = (1 - Probability) * 2**56.
2025-05-22 12:33:34 +10:00
Shawn Maddock 23c3cdae61
fixes #1600 (#1603) 2025-05-21 08:02:20 -04:00
dependabot[bot] acf6dc7e5b
Bump github/codeql-action from 3.28.17 to 3.28.18 (#1601)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.17 to 3.28.18.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](60168efe1c...ff0a06e83c)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.28.18
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-20 12:27:55 +10:00
dependabot[bot] 691c0d43ae
Bump fossas/fossa-action from 1.6.0 to 1.7.0 (#1594)
Bumps [fossas/fossa-action](https://github.com/fossas/fossa-action) from 1.6.0 to 1.7.0.
- [Release notes](https://github.com/fossas/fossa-action/releases)
- [Commits](c0a7d013f8...3ebcea1862)

---
updated-dependencies:
- dependency-name: fossas/fossa-action
  dependency-version: 1.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-19 16:34:55 +10:00
Tobias Bachert 2fcafabc81
Catch `TypeError` if `google/protobuf` `^4.31` and `ext-protobuf` `<4.31` are installed (#1598) 2025-05-17 14:39:11 +10:00
Brett McBride 389fa3fd50
support config 0.4 (#1562)
* support opentelemetry/configuration 0.4

* implement resource detectors

* green checks

* implement configurators

* implement resources and detectors

* tidy

* fix include/exclude pattern matching, fix todo

* move attribute processing into a class, add unit tests

* allow null includes, treat as 'include all'

* remove useless noop propagator

* fix cardinality_limits config

* dont reference config in closure

* remove env detector component
per review feedback, we can achieve this with env var substitution in the yaml document

* add memory exporters

* rework composite_list

* improve test

* fix unstable test

* composite_list is string

* revert configurator changes

* enforce mandatory resource attributes

* remove mandatory detector component providers

* remove null attributes + array values

* disabled is required, remove no-op normalization

* rector

* remove duplicate propagators from composite_list

* update semconv schema versions

* fix test

* Apply suggestions from code review

Co-authored-by: Tobias Bachert <git@b-privat.de>

* dont allow attribute removal from mandatory detectors

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2025-05-14 08:46:38 -04:00
Tobias Bachert 5fdfac284a
Use protobuf `PrintOptions` if available (#1593)
Resolves #978
2025-05-12 10:36:35 +10:00
Bob Strecansky f0f5a2a83f
update docker container versions (#1590) 2025-05-12 10:30:54 +10:00
Tobias Bachert b5a5ac79ff
Allow immediate gc of `ContextStorageNode`s after `::detach()` (#1585)
Use dummy object instead of self references as detached-marker to avoid relying on gc cycle collection.

Resolves #1584.
2025-05-08 09:36:50 +10:00
Brett McBride 4851a4e03b
stabilize logger.enabled (#1580)
- update Logger.isEnabled signature to include context and severity number, per spec
- accept event_name on a LogRecord
- add event name to otlp logs payload
- update or remove some comments that were based on the old logs-bridge specification
2025-05-07 08:32:21 -04:00
dependabot[bot] 3679ada34e
Bump github/codeql-action from 3.28.16 to 3.28.17 (#1581)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.16 to 3.28.17.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](28deaeda66...60168efe1c)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.28.17
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-05 10:01:19 -04:00
Brett McBride 91e05d9f1f
Semconv 1.32.0 (#1577)
* update semconv to 1.32.0
* don't generate semconv for android, cpython, ios
2025-05-05 13:58:53 +10:00
Evan 351aa18abe
implement getAll function in TextMap Extract (#1570)
* implement getAll function in TextMap Extract

* refactor propagation interfaces to introduce ExtendedPropagationGetterInterface

* Refactor getAll method in SanitizeCombinedHeadersPropagationGetter to streamline conditional logic for getter instance check
2025-05-02 11:57:57 +10:00
Bartosz Tomczak 39cd6e2f09
Use timeout to set max_duration on symfony http client (#1575) 2025-05-02 09:20:43 +10:00
Brett McBride ab05329ffe
update resource detectors to align with spec changes (#1573)
PR https://github.com/open-telemetry/opentelemetry-specification/pull/4461 clarifies that some
attributes (service.name, telemetry.*) are mandatory. It also reserves a couple of well-known
detectors names (container, host, process, service) and the attributes they should populate.
Consolidate some of our resource detectors into the built-in ones:
- process-runtime into process, and deprecate
- os into host, and deprecate
- sdk-provided into sdk, and deprecate
- service.name attribute from environment into service detector

Add "mandatory attributes", which is currently service.name, and initially set this to "unknown_service:php"
similar to Java's implementation. Ensure that the composite detector starts with mandatory attributes.

Ensure that "sdk" and "service" detectors are always included from ResourceInfoFactory.

The deprecated detectors are still available, but do not do anything.
2025-05-01 13:37:15 +10:00
dependabot[bot] 821b7543c9
Bump github/codeql-action from 3.28.15 to 3.28.16 (#1571)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.15 to 3.28.16.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](45775bd823...28deaeda66)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.28.16
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-24 07:37:04 -04:00
Evan e2f24eb494
remove FilteredAttributes and related references (#1565) 2025-04-17 09:39:10 +10:00
Grzegorz Drozd 39a2b486b1
Refactor InMemory exporters to use shared storage manager (#1559)
Introduced `InMemoryStorageManager` to centralize storage management for spans, metrics, and logs. Updated InMemory exporters and their factory classes to utilize this shared storage.

* Add integration test for InMemoryExporter

- add integration test that shows that storage contains metrics
- because of src/SDK/Metrics/MetricReader/ExportingReader.php:148 I had to add `PushMetricExporterInterface` to InMemoryExporter class

* Add integration test for InMemoryExporter
2025-04-15 17:02:07 +10:00
dependabot[bot] e253da3e8b
Bump github/codeql-action from 3.28.12 to 3.28.15 (#1561)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.12 to 3.28.15.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](5f8171a638...45775bd823)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.28.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-11 09:20:20 +10:00
OpenTelemetry Bot 64821d89a5
Add ossf-scorecard scanning workflow (#1543)
* Add ossf-scorecard scanning workflow

* Add end of file newline

---------

Co-authored-by: otelbot <197425009+otelbot@users.noreply.github.com>
2025-04-09 23:09:50 +10:00
Grzegorz Drozd fadec4c8da
Fix missing metrics attributes in console exporter (#1558)
This PR fixes a case that when using console exporter for metrics, attributes are not included in the export.
2025-04-08 19:55:41 +10:00
dependabot[bot] d084288a12
Update monolog/monolog requirement from ^2.3 to ^2.3 || ^3.0 (#1551)
* Update monolog/monolog requirement from ^2.3 to ^2.3 || ^3.0

Updates the requirements on [monolog/monolog](https://github.com/Seldaek/monolog) to permit the latest version.
- [Release notes](https://github.com/Seldaek/monolog/releases)
- [Changelog](https://github.com/Seldaek/monolog/blob/main/CHANGELOG.md)
- [Commits](https://github.com/Seldaek/monolog/compare/2.3.0...3.9.0)

---
updated-dependencies:
- dependency-name: monolog/monolog
  dependency-version: 3.9.0
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>

* update monolog example

* style

* drop monolog 2.3 from example

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Brett McBride <brett@deakin.edu.au>
2025-04-08 11:19:29 +10:00
dependabot[bot] 1413c3470e
Bump fossas/fossa-action from 1.5.0 to 1.6.0 (#1549)
Bumps [fossas/fossa-action](https://github.com/fossas/fossa-action) from 1.5.0 to 1.6.0.
- [Release notes](https://github.com/fossas/fossa-action/releases)
- [Commits](93a52ecf7c...c0a7d013f8)

---
updated-dependencies:
- dependency-name: fossas/fossa-action
  dependency-version: 1.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-03 12:12:34 +11:00
Brett McBride 68b6d4f6ee
skip segfault-inducing test (#1555)
this test triggers a bug that surfaced in xdebug 3.4.2, see https://bugs.xdebug.org/view.php?id=2332
2025-04-03 09:34:15 +11:00
dependabot[bot] 5c0004b515
Bump phpDocumentor/phpDocumentor from 3.5.3 to 3.7.1 (#1550)
Bumps [phpDocumentor/phpDocumentor](https://github.com/phpdocumentor/phpdocumentor) from 3.5.3 to 3.7.1.
- [Release notes](https://github.com/phpdocumentor/phpdocumentor/releases)
- [Changelog](https://github.com/phpDocumentor/phpDocumentor/blob/master/CHANGELOG.md)
- [Commits](https://github.com/phpdocumentor/phpdocumentor/compare/v3.5.3...v3.7.1)

---
updated-dependencies:
- dependency-name: phpDocumentor/phpDocumentor
  dependency-version: 3.7.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-02 22:53:18 +11:00
dependabot[bot] 6ed191498e
Bump docker/build-push-action from 5 to 6 (#1548)
Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 5 to 6.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v5...v6)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-02 22:52:36 +11:00
dependabot[bot] 59a4f7730b
Bump codecov/codecov-action from 4 to 5 (#1547)
Bumps [codecov/codecov-action](https://github.com/codecov/codecov-action) from 4 to 5.
- [Release notes](https://github.com/codecov/codecov-action/releases)
- [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codecov/codecov-action/compare/v4...v5)

---
updated-dependencies:
- dependency-name: codecov/codecov-action
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-02 22:51:58 +11:00
Cedric Ziel 2b5ce6c611
fix: bump timeout for building images (#1553)
Bumps the timeout to 500 (default 360) minutes.
2025-04-02 22:47:06 +11:00
Cedric Ziel 8028f9715f
chore: build images dynamically (#1545)
* chore: build images dynamically

* fix: only push on main

* chore: build on PR with path change

* chore: align casing

* fix: add missing 8.0 alias

* fix: declare arg before all others
2025-04-02 09:04:31 +11:00
Cedric Ziel 5899a9e287
chore: auto-update dependencies via dependabot (#1544) 2025-04-02 09:02:04 +11:00
Cedric Ziel a354f46612
chore: publish base image for 8.4 as well (#1539) 2025-03-30 20:51:14 +11:00
Tobias Bachert 015da800aa
Fix `YamlSymfonyFileLoader` if locator uses directory besides `getcwd()` (#1526) 2025-03-12 10:55:57 +11:00
Sergey Kleyman 968083597f
Fix IS_REMOTE flag (#1522)
* Fixed span's is_remote flag computation
* Added testing for cases without parent and with local parent span
2025-03-07 10:21:56 +11:00
Tobias Bachert 08c88605b4
Fix `LateBindingMeter::createObservable{Instrument}()` (#1524) 2025-03-06 08:42:54 +11:00
Bartosz Tomczak 68462e0bb2
Check max retry on grpc transport (#1516)
* Check max retry on grpc transport
* Skip retry policy when maxRetries is 0
2025-03-05 09:35:49 +11:00
OpenTelemetry Bot 88c79091ca
Add FOSSA scanning workflow (#1511)
Co-authored-by: otelbot <197425009+otelbot@users.noreply.github.com>
2025-02-27 07:59:13 -05:00
Richard Chukwu 656f5db415
Update development guide to contributing guide (#1513)
* Update CONTRIBUTING.md
2025-02-25 15:59:05 +11:00
Brett McBride 8316c50e93
use a local const for grpc time conversions (#1505)
using a newly-added const in ClockInterface breaks things for some older PHP versions, so
lets use a local const for now
2025-02-10 09:37:38 +11:00
Brett McBride 66c8ce8059
Semconv 1.30 (#1495)
* generate semconv 1.30
NB that v1.29 contained a bug, and the recommendation was to skip this version

* reduce minimum php version to 8.0
we still have a bunch of auto-instrumentations that work with 8.0
2025-02-06 11:21:48 +11:00
Jon Bates 5d24db8fca
A couple of code tidies left over from PR #1499 (#1502) 2025-02-06 09:26:24 +11:00
Jon Bates 31d902b6c6
fix gRPC timeout (#1498) (#1499) 2025-02-04 08:49:11 +11:00
Brett McBride 96ce422b6a
generate semconv 1.28 (#1491) 2025-01-30 10:41:46 +11:00
Brett McBride 3e8ae81e35
handle empty meter observers (#1490)
* if no observers are registered for a meter's instruments, some tests were emitting php warnings:
- foreach() argument must be of type array|object, null given
- Undefined array key XXX

null coalesce to an empty array to make the test happy.

* handle empty writers
2025-01-30 08:40:28 +11:00
Brett McBride 420b5ef6df
disallow empty string for baggage name (#1484)
spec 1.36.0 clarifies that empty string is not a valid baggage name
2025-01-30 08:38:08 +11:00
Brett McBride e3f77b7ada
remove todo for logging dropped attributes (#1485)
this is already implemented for logs and traces as required by spec
2025-01-30 08:37:19 +11:00
Brett McBride b24a30c31a
yaml config env var spec conformance (#1486)
* add support for env: prefix in yaml config
* align test to example in spec
* do not recursively replace env vars
  - fix env substitution normalization so that it doesn't apply 2 replacement normalizers for string nodes
2025-01-28 12:37:53 +11:00
Brett McBride 7eb3abb276
adding otlp/file exporter (#1481)
* otlp_file config support
* handle otlp_file scheme://path format
* update kitchen-sink
2025-01-23 10:12:34 +11:00
Brett McBride a4119f9e32
support refactored otlp export config (#1477)
upstream config now splits otlp exporters into otlp_http and otlp_grpc

* use const, remove insecure from otlp_http config

* Apply suggestions from code review

Co-authored-by: Tobias Bachert <git@b-privat.de>

* set default endpoints, fix review feedback

* move endpoint out of yaml anchor

* convert timeouts from millis to seconds

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2025-01-21 10:35:16 +11:00
Brett McBride 29b7da48c4
generate proto 1.5.0 (#1478) 2025-01-16 10:07:07 +11:00
Brett McBride 83cddd9157
declarative config 0.3+ support (#1452)
This brings declarative config support up to 0.3 plus some of the unreleased 0.4 features:

* porting code from Nevay/otel-sdk-configuration
* support 0.4 metric reader config
* allow empty keys
since https://github.com/open-telemetry/opentelemetry-specification/pull/4269 empty keys are allows, and NULL is no longer equivalent to unset
* update config example to remove empty objects
* remove moved component providers from composer.json
* add ComponentProviderRegistry::componentMap for instrumentation configuration
2025-01-10 10:17:14 +11:00
Brett McBride 4b575e6b6c
deprecate event logger (#1466)
The event logger was a Development-status component of the logging signal. It has been
removed in favour of adding emitEvent to the logger interface,
see https://github.com/open-telemetry/opentelemetry-specification/pull/4319
2025-01-09 10:50:34 +11:00
Brett McBride 32e301ea6a
adding otlp/file exporter (#1465)
the spec has added in-development otlp file/stdout exporter. We already supported this programmatically, so
add some factories and sdk config to allow configuration from environment (only for stdout, per spec)
2025-01-09 10:50:03 +11:00
Brett McBride 7aa3e02eb0
remove blank lines after class opening (#1468)
add the php-cs-fixer no_blank_lines_after_class_opening rule and apply to codebase
2025-01-07 21:18:52 +11:00
Brett McBride b515b6b6ff
handle host detector with custom error handler and open_basedir (#1454)
if open_basedir is configured such that files that it tries to open are denied with a php warning, and
a custom error handler is installed which converts warnings to exceptions, an unhandled exception occurs.
add a test for this, suppress error handling around the code that can trigger this.
2024-12-20 19:29:15 +11:00
Brett McBride f73bcfa22c
ignore platform reqs for 8.4 install (#1460)
psalm is not yet compatible with 8.4, so force it
2024-12-20 18:57:57 +11:00
Brett McBride 4a021fbaec
adding php 8.5 to build matrix (#1439)
- build against 8.5 (nightly)
- make 8.4 non-experimental
2024-11-27 21:03:40 +11:00
Brett McBride f1c982734b
add sdk-config 0.3 support for key/value headers and attributes (#1428)
- headers and attributes are now arrays with `key` and `value` elements
- headers can optionally contain a `headers_list` element which supports a lower-priority CSV of key/value entries
- attributes can optionally contain an `attributes_list` element which supports a lower-priority CSV of key/value/data-type entries
2024-11-26 11:48:31 +11:00
Chris Lightfoot-Wild 8857b0c103
Added \Attribute::TARGET_PARAMETER to \OpenTelemetry\API\Instrumentation\SpanAttribute (#1433)
Fixes #1429.
2024-11-16 15:32:30 +11:00
John Spaetzel 7b5cbb5078
guard against possible false value from file_get_contents in Host.php (#1430) 2024-11-15 16:42:53 +11:00
Bob Strecansky 38633fba0e
Update README.md (#1427)
Adding API Documentation Link
2024-11-06 11:15:52 -05:00
Severin Neumann ea908b161d
Rename phpdoc-to-github-pages to phpdoc-to-github-pages.yml (#1425)
- follow up to #1418, where I named the file without the required YML suffix
- Do not run on pull requests
2024-11-05 20:38:15 +11:00
Aleksei Gagarin 39cc549f04
Support google protobuf v4 (#1421) 2024-10-30 22:49:49 +11:00
Severin Neumann 1aae9dd619
Workflow to publish phpdoc to github pages (#1418) 2024-10-28 08:27:02 +11:00
znerol 93f2068d0b
fix start timestamp in auto root span (#1413) 2024-10-19 08:01:35 +11:00
Mark van Duijker fd654b99c7
fix: Guzzle version 6 error in Http Client Discovery (#1409) 2024-10-17 20:58:13 +11:00
Brett McBride d2b15077df
use weaver to generate semconv (#1398)
update semconv generation to use the new tooling. This is fairly close to a 1:1 of what we have now,
although I noted a couple of TODOs which we might consider in future to align with what Java is
doing: split attribute up into file-per-type, and split stable/unstable.
2024-10-17 20:57:37 +11:00
Brett McBride 01d0fd3618
ensure zipkin tags and attributes are cast to strings (#1406) 2024-10-16 08:03:20 -04:00
Tobias Bachert 2c1da9aaec
Add `TextMapPropagator` to instrumentation context (#1401) 2024-10-16 09:42:37 +11:00
Brett McBride c632d960a5
check for readable host id files before read (#1400)
* check for readable host id files before read
* reset vfs between tests
2024-10-16 09:42:15 +11:00
Tobias Bachert f29277abc0
Move hook manager registration to API package (#1402)
Keeping registration in SDK to not break API >1.1.0 w/ SDK 1.1.0.
2024-10-14 09:16:24 +11:00
Chris Lightfoot-Wild cd8c0e3124
Fix HookManagerInterface annotation (#1395)
* Align OpenTelemetry\API\Instrumentation\AutoInstrumentation\HookManagerInterface::hook signatures with OpenTelemetry\Instrumentation\hook.

Co-authored-by: Tobias Bachert <git@b-privat.de>
2024-10-05 16:00:52 +10:00
Brett McBride 0ae272373d
84 implicit null (#1394)
* 8.4: fixing some implicit nullable params

* fix withspan handler nullable + example (#1377)

- class is nullable for pre hooks
- add phpt tests for withspan and its interaction with auto root span

* fix: update references to logging exporter (#1383)

This exporter has been replaced by the debug exporter and will be removed soon. Related to https://github.com/open-telemetry/opentelemetry-collector/pull/11037

Signed-off-by: Alex Boten <223565+codeboten@users.noreply.github.com>

* fix: Update collector tag in example to latest (#1384)

Follow-up from #1383. Debug exporter isn't available until v0.86.0, so this new configuration throws an error when trying to run the collector. `Error: cannot unmarshal the configuration: unknown exporters type "debug" for "debug"` Instead of setting to v0.86.0, I noticed the other docker files omitted the tag (so latest is pulled). I just updated this to match.

* Remove `MeterInterface::isEnabled()` and fix meter config re-enabling (#1387)

* Update SPI dependency to v1. (#1388)

* Fix README badges. (#1389)

* add phpDocumentor instructions to Makefile (#1385)

* add phpDocumentor instructions to Makefile

Signed-off-by: svrnm <neumanns@cisco.com>

* update DEVELOPMENT.md

Signed-off-by: svrnm <neumanns@cisco.com>

---------

Signed-off-by: svrnm <neumanns@cisco.com>

* Update README.md (#1344)

* Fix `IncompatibleReturnValueException` in `MessageFactoryTest` (#1392)

PSR7 `RequestInterface::getUri()` must return `UriInterface`, not `string`; explicit typehint was added in `2.0`.

* more implicit nulls

---------

Signed-off-by: Alex Boten <223565+codeboten@users.noreply.github.com>
Signed-off-by: svrnm <neumanns@cisco.com>
Co-authored-by: Alex Boten <223565+codeboten@users.noreply.github.com>
Co-authored-by: Jamie Danielson <jamieedanielson@gmail.com>
Co-authored-by: Tobias Bachert <git@b-privat.de>
Co-authored-by: Chris Lightfoot-Wild <github-clw@wild.me.uk>
Co-authored-by: Severin Neumann <neumanns@cisco.com>
Co-authored-by: Oleg <142805497+devactivity-team@users.noreply.github.com>
2024-10-02 08:06:03 -04:00
Tobias Bachert fd24607c10
Fix `IncompatibleReturnValueException` in `MessageFactoryTest` (#1392)
PSR7 `RequestInterface::getUri()` must return `UriInterface`, not `string`; explicit typehint was added in `2.0`.
2024-09-29 22:12:53 +10:00
Oleg 20bf3cff3e
Update README.md (#1344) 2024-09-25 14:40:03 -04:00
Severin Neumann 91f4735b3a
add phpDocumentor instructions to Makefile (#1385)
* add phpDocumentor instructions to Makefile

Signed-off-by: svrnm <neumanns@cisco.com>

* update DEVELOPMENT.md

Signed-off-by: svrnm <neumanns@cisco.com>

---------

Signed-off-by: svrnm <neumanns@cisco.com>
2024-09-25 14:39:36 -04:00
Chris Lightfoot-Wild 7d744e0086
Fix README badges. (#1389) 2024-09-25 21:59:48 +10:00
Chris Lightfoot-Wild 439447b286
Update SPI dependency to v1. (#1388) 2024-09-25 21:54:21 +10:00
Tobias Bachert 6a2242d46a
Remove `MeterInterface::isEnabled()` and fix meter config re-enabling (#1387) 2024-09-25 09:58:09 +10:00
Jamie Danielson 8ed62b1e43
fix: Update collector tag in example to latest (#1384)
Follow-up from #1383. Debug exporter isn't available until v0.86.0, so this new configuration throws an error when trying to run the collector. `Error: cannot unmarshal the configuration: unknown exporters type "debug" for "debug"` Instead of setting to v0.86.0, I noticed the other docker files omitted the tag (so latest is pulled). I just updated this to match.
2024-09-24 08:35:18 +10:00
Alex Boten 3be58cff57
fix: update references to logging exporter (#1383)
This exporter has been replaced by the debug exporter and will be removed soon. Related to https://github.com/open-telemetry/opentelemetry-collector/pull/11037

Signed-off-by: Alex Boten <223565+codeboten@users.noreply.github.com>
2024-09-22 17:42:55 +10:00
Brett McBride 068086347b
fix withspan handler nullable + example (#1377)
- class is nullable for pre hooks
- add phpt tests for withspan and its interaction with auto root span
2024-09-07 08:51:46 +10:00
Brett McBride bee9c64ae9
adding auto-instrumentation attribute to API (#1371)
adding WithSpan and SpanAttribute attributes to the API. These attributes
are used by an upcoming feature in auto-instrumentation which allows users
to add attributes to their code to enable auto-instrumentation.
2024-08-31 09:17:53 +10:00
Brett McBride 4fc170002d
re-adding removed trace attribute values (#1368)
the MESSAGING_OPERATION_* attribute values were removed in semconv 1.26.0,
so update our generation to put them back, marking as deprecated
2024-08-28 19:20:31 +10:00
Brett McBride 653e453f95
adding config provider (#1366)
implement recent additions to the otel spec re: config provider. Config provider should return a
ConfigProperties, but we were already returning a ConfigurationRegistry. Added a ConfigProperties
interface for ConfigurationRegistry to implement, which gets us pretty close to spec.
We don't make ConfigProvider globally available, instead passing the ConfigurationRegistry in to
each instrumentation as we register it. The spec allows for this.
2024-08-27 09:28:08 +10:00
Brett McBride f4b52c4b49
add minimal auto-instrumentation hook functions (#1358)
add OpenTelemetry\API\Instrumentation\WithSpanHandler, which will be the default pre/post
hook callbacks for attribute-based auto-instrumentation.
2024-08-26 11:17:16 +10:00
Brett McBride 5276df3171
auto root span creation (#1354)
* auto root span creation
proof of concept for automatically creating a root span on startup.
the obvious deficiencies are:
- no idea of response values (status code etc)
- does not capture exceptions

* deptrac
2024-08-23 09:15:18 -04:00
Brett McBride 69825d395a
fix implicit null usage (#1362)
php8.4 deprecates implicit null (now checked by phan)
2024-08-21 10:29:20 +10:00
Luc 80e97da6eb
Allow 'google/protobuf' '^4.0' to be used. (#1361) 2024-08-18 21:02:08 +10:00
Brett McBride 41dd113030
implement scope configuration (#1353) 2024-08-18 20:52:43 +10:00
Brett McBride 382331e062
semconv 1.27.0 (#1356)
* generate semconv 1.27.0

* improve attribute values brief and deprecation display

* remove duplicate trace attribute, ignore deprecated attributes

* fix tests
2024-08-06 11:17:39 -04:00
Brett McBride d2ec5e6d0b
add enabled to late binding logger and tracer (#1357) 2024-08-06 07:58:59 -04:00
Brett McBride 10b8d9732b
adding LocalRootSpan (#1310)
* adding LocalRootSpan class
this is based on Java's implementation, https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/v2.3.0/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/LocalRootSpan.java
and adds the ability to identify and locate the "local root span" in a trace. The local root span is the top-level active span which has either
an invalid or remote parent.
It's tracked automatically as part of making a span active, either via `Span::activate()` or `Span::storeInContext()`, and can be retrieved in
a couple of ways, but most easily via `LocalRootSpan::current()`.

* remove redundant local root span check

* move context key to api

* internal

* adding example

* mark LocalRootSpan as experimental

* adding an example of local root span usage

* style, fix broken build
2024-08-06 07:58:33 -04:00
Brett McBride 68b1b43cab
auto-instrumentation registration (#1304)
* [WIP] Add instrumentation configuration

* add autoloading for auto-instrumentations using SPI

* allow autoloading and non-autoloading to work

* fix attribute

* experimental config file

* fixing invalid dependencies
- deptrac was rightly complaining that API (indirectly) depended on SDK through config/sdk. For now,
remove usage of Config\SDK\Configuration\Context
- update deptrac config to allow some new dependencies

* dont register hook manager globally or in sdk

* remove unused function, psalm ignore missing extension function

* possibly fixing type-hint
psalm doesn't complain now, so that should be good

* load config files relative to cwd

* fixing hook manager enable/disable + psalm complaints

* fixing 8.1 psalm error

* use context to pass providers to instrumentations
- make "register global" a function of Sdk, but keep the sdk builder's interface intact
- invent an API instrumentation context, similar to the one in config/sdk, to pass providers
  to instrumentations
- add an initial test of autoloading from a config file

* adding tests for sdk::registerGlobal
in passing, remove some dead code for handling invalid booleans - config already handles this correctly

* linting

* test coverage for globals

* add opentelemetry extension to developer image and actions

* always register instrumentations via SPI

* register globals initializer for file-config sdk
allow SDK created from config file to coexist with components using globals initializer

* linting

* remove globals init function

* fix phan warning

* simplify hook manager
- drop storage from hook manager: can't guarantee that something else, eg swoole, won't modify storage
- drop context from hook manager: we must lazy-load globals via initializers, because not all instrumentations use SPI (although that may change in future)
- default hook manager to enabled

* add todo to deprecate Registry in future

* autoload instrumentations without config
if no config provided, still try to load them. wrap registration in a try/catch/log

* fixing phan ref, update doc

* remove phan suppress

* fix example

* bump SPI to 0.2.1

* adding late-binding tracer+provider
per review from Nevay, this will allow instrumentations to get things from Globals as late as possible

* adding late binding logger and meter providers

* more late binding test coverage

* tidy

* dont use CoversMethod yet
not available in phpunit 10, so comment out and leave a todo

* kitchen sink, remove unused var

* instrumentation config as a map, per config file spec

* adding general config

* move general config into sdk

* test config caching

* move general instrumentation config to api

* avoid bad version of sebastian/exporter

* bump config yaml files to 0.3

* fix tests

* disable hook manager during file-based init

* cleanup

* support multiple config files in autoloader

* move hook manager enable/disable out of extension hook manager
The most obvious place to do this is in a class named HookManager, which _was_ an
interface for hook managers. Rename existing HookManager to HookManagerInterface,
then re-purpose HookManager for globally enabling/disabling hook managers as well
as determining the disabled status.

* update spi config

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2024-07-22 10:40:34 -04:00
Brett McBride 4ed0d870f7
add enabled functions (#1350)
* add enabled function
spec 1.34 requires logger, tracer, and instrument to have an enabled function

* Update src/API/Metrics/Instrument.php

Co-authored-by: Tobias Bachert <git@b-privat.de>

* adjust instrument enabled logic

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2024-07-19 10:28:32 -04:00
Brett McBride 1271f1ed69
add return type hints (#1351)
now that 7.4 and 8.0 support is dropped, we can add correct return type-hints
to these functions, and remove the ReturnTypeWillChange attribute.
2024-07-19 09:33:49 -04:00
Brett McBride e4f9604411
remove deprecated rector rule (#1352)
this silences a rector warning which was breaking local build
2024-07-19 09:30:29 -04:00
Cedric Ziel 17ad56a3f3
Add linux/arm64 to base images support M3 devices (#1343) 2024-07-05 17:14:50 -04:00
Brett McBride a822c455a4
update semconv to 1.26.0 (#1316)
note that `messaging.client_id` was renamed to `messaging.client.id`, which causes a conflict in const name.
The recommendation from semconv maintainers is to replace the old value, `messaging.client_id`.
2024-06-28 11:51:36 +10:00
Brett McBride 36f29a37cb
fixing implicit nullable deprecations, bump GH actions (#1340)
* implicit nullable parameters are deprecated in 8.4, so make them explicit
* update github actions versions
2024-06-28 11:44:08 +10:00
Brett McBride b6f9afb5af
log discarded span+log attributes (#1336)
The SDK should log a warning once if there are any dropped span attributes, links, link attributes, events or event attributes.
The SDK should log a warning once if there are any dropped LogRecord attributes.
2024-06-27 08:52:30 +10:00
Brett McBride a90f18cc72
event logger spec compliance (#1335)
update event logger to conform to spec 1.34.0:
- implement ForceFlush, which delegates to the LoggerProvider
- rename event payload to body
2024-06-26 15:34:36 +10:00
Brett McBride fc28032748
handle empty encoded responses (#1337)
at least one otel backend product sends an empty response with a gzip encoding, which we fail to decode (because
an empty string is not valid). Work around this by not trying to decode an empty value.
2024-06-20 09:44:40 +10:00
Matt Hensley 6bf422c0f1
Adds experimental service.instance.id resource detector (#1309)
* implement experimental service.instance.id attribute
2024-06-15 12:09:33 +10:00
Bart Reunes eebf23a21d
Add return types for ArrayAccess in docblocks (#1319) 2024-06-05 08:04:47 -04:00
David Grayston 600d8a5f53
Fix logs exporter factory exception message (#1318) 2024-06-03 09:14:46 -04:00
Chris Lightfoot-Wild 39f81a3cc6
Updated link to 3musketeers site. (#1315) 2024-05-22 09:40:03 +10:00
Brett McBride eaba9e3228
conflict with mockery 1.6.12 (#1313) 2024-05-21 14:27:12 +10:00
Brett McBride fbdb103590
upgrade to phpunit 11 (#1308)
* run unit tests in random order
running in random order highlights some interference between tests (mostly logging being enabled), and is a requirement for
mutation testing (ie, all tests must pass when executed in a random order).
* adding infection mutation testing
this adds the ability to run infection. It generates a lot of output, which is an exercise for another PR...
* replace assertwell/phpunit-global-state
the package was not compatible with phpunit 11. create out own test Trait, which handles
env vars, as well as general cleanup of the usual suspects of state that our tests mess up
* remove redundant tearDown functions
there's an after annotation on the trait to handle this
* use rector to upgrade tests for phpunit 11
* fixing CoversFunction for namespaced functions
* use FQNs in test attributes
2024-05-16 09:21:28 +10:00
Brett McBride 4f32817065
Add infection test tool (#1306)
* run unit tests in random order
running in random order highlights some interference between tests (mostly logging being enabled), and is a requirement for
mutation testing (ie, all tests must pass when executed in a random order).
* adding infection mutation testing
this adds the ability to run infection. It generates a lot of output, which is an exercise for another PR...
* infection max threads
2024-05-15 20:46:42 +10:00
Brett McBride 500f6ee1bd
implement events v1.32 (#1291)
* implement events v1.32
implement the events api + sdk per spec v1.32:
- event logger is now only retrievable via an event logger provider
- domain attribute for events is removed
- events accept a subset of logrecord params, rather than an entire logrecord

* convert severity to a backed enum

* lint

* remove instead of deprecating logEvent, mark Logger constructor as internal

* make severity an enum only

* event attributes to iterable

* inject ClockInterface, add CachedInstrumentation, update examples

* set correct defaults for events

* test coverage

* Revert "make severity an enum only"

This reverts commit 710822907b.
Also, move PSR-3 mapping into the Severity enum.

* event attributes to iterable

* apply review feedback
2024-05-05 18:35:19 -04:00
Brett McBride 8031c78512
move test tools into vendor-bin (#1302)
* move test tools into vendor-bin
To reduce (hopefully, eliminate) the situations where our testing tools have conflicting
dependencies, use bamarni/composer-bin-plugin to manage them as separate vendored dirs.
Add symlinks under tools/, and update Makefile to use the self-contained versions.
Remove the dependencies from root composer.json
Rejigger dockerfile to add opcache, and some config required for latest version of grpc

* update action tools locations

* revert phpstan from vendor-bin
the phpstan plugins do not work. phpstan has no dependencies anyway, so it's safe enough to keep in vendor

* remove tools symlinks, update makefile
2024-05-05 18:34:52 -04:00
Brett McBride 8e810c6598
adding enum for semconv versions (#1301) 2024-05-05 10:19:13 +10:00
Tobias Bachert 82b191b984
Fix `weaken` for PHP8.4 closure names (#1303) 2024-05-03 09:14:33 +10:00
Brett McBride 100e593bd6
fix deptrac config to allow http clients (#1293)
* fix deptrac config to allow http clients

* Update deptrac.yaml

Co-authored-by: Chris Lightfoot-Wild <github-clw@wild.me.uk>

---------

Co-authored-by: Chris Lightfoot-Wild <github-clw@wild.me.uk>
2024-04-30 14:28:45 -04:00
Tobias Bachert 80114317f8
Set OTLP 1.2.0 span parent/link remote flags (#1298)
* Generate protobuf 1.3.0

* Set otlp exporter proto 1.2.0 remote flags
2024-04-30 14:28:30 -04:00
Dalibor Karlović 5747fac40c
fix: correct path to autoloader in metrics/getting-started (#1299) 2024-04-30 20:51:20 +10:00
Andy Postnikov f2cba82c28
[PHP 8.4] Fixes for implicit nullability deprecation (#1297) 2024-04-29 15:24:44 +10:00
Brett McBride fc161a8548
migrate Clock classes to API (#1281)
* migrate Clock classes to API
- move Clock* + Util into API
- add a deprecated wrapper for ClockFactory and Util
- remove unused StopWatch* classes

* review feedback

* replace ClockFactory with Clock
It's not really a factory, and really only provides access to a system clock. Create a
Clock class which is more clear in its purpose.

* remove time Util class
per review feedback, it's only used in Zipkin. Removed some unused consts from ClockInterface

* Apply suggestions from code review

Co-authored-by: Tobias Bachert <git@b-privat.de>

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2024-04-29 10:28:06 +10:00
Paul 9fe6aa0cd7
Include schema_url in FriendlySpanConverter (#1292) 2024-04-29 10:22:58 +10:00
Brett McBride cea2d7c4cb
use codecov action (#1294)
our previous method of uploading to codecov.io is suffering from throttling and taking 5+ hours,
a post in the opentelemetry maintainers channel suggests this is the way to do it now
2024-04-29 09:51:57 +10:00
Tobias Bachert 8a6dd4750d
Add `Span::addLink()` and `Meter::createGauge()` (#1289)
* Add `Span::addLink()`

https://opentelemetry.io/docs/specs/otel/trace/api/#add-link

* Bump API version to `1.1.x-dev`

* Add experimental `Meter::createGauge()`

https://opentelemetry.io/docs/specs/otel/metrics/api/#gauge
2024-04-27 14:59:15 +10:00
Brett McBride 5a395e09da
enable timeout for http transports (#1275)
* enable timeout for http transports
Attempt to do our own discovery for some well-known PSR-18 clients, which allows
for configuring timeout (and in future certificates, keys etc).
This is not complete and a prototype for feedback, but I've updated an example to
show that it works for Guzzle and Symfony http clients

* improve client discovery

* refactor, test, add more implementations

* add timeout for logs and metrics
2024-04-25 16:21:00 +10:00
Brett McBride 5019361068
fixing warnings from local build (#1277)
A couple of warnings have popped up recently:
- docker compose 'version' is deprecated
- BSD host id test was running a command that doesn't exist, which was visible in test output (removed test case)
- synchronous metric stream test was triggering a warnings which was visible in test output (changed to use LogsMessagesTrait)
- resource merging with different schema URLs was triggering a warnings from Config test (updated yaml schema_url and documented)
2024-04-19 09:04:57 +10:00
Brett McBride 43339294f5
port Nevay/otel-sdk-configuration into opentelemetry-php (#1276)
* port Nevay/otel-sdk-configuration into opentelemetry-php
This is a lift-and-shift, except for:
- changing namespaces
- fixes or ignore rules required to make static analysis tools happy
- commenting out one part of yaml test (unquoted hex value from env var)

* fix psalm on php81
2024-04-15 09:15:37 -04:00
Kevin Mian Kraiker fda522a90b
Update SemConv to 1.25.0 (#1271)
* generate semconv 1.25.0
* Tweak template `deprecated` attributes behavior and regen
* Use is_deprecated filter
2024-04-10 09:31:35 +10:00
Tobias Bachert 6cd7a8af2c
Improve fiber bound context storage (#1270)
* Improve fiber bound context storage

Now works properly in fibers once initial context is attached.

* Change `Context::storage()` return type to `ContextStorageInterface`

`ExecutionContextAwareInterface` should not be relevant for end-users / it was mainly exposed for the FFI fiber handler; calling any of its method with enabled fiber handler would have broken the storage.
Swoole context storage README creates a new storage instead of wrapping `Context::storage()`: `Context::setStorage(new SwooleContextStorage(new ContextStorage()));`.

* Add BC layer for execution context aware fiber storage

* Fix BC layer inactive execution context detection for {main}
2024-04-09 09:11:29 +10:00
John Bley e44f5a97d9
Clean up shell scripts (#1269)
* Clean up shell scripts
* Add shellcheck CI step
2024-04-03 10:54:21 +11:00
Matt Hensley bb9eb40a50
Add host.id for non-containerized systems (#1266)
Co-authored-by: Tobias Bachert <git@b-privat.de>
Co-authored-by: Chris Lightfoot-Wild <github-clw@wild.me.uk>
2024-04-02 09:20:09 +11:00
Tobias Bachert 7ec0e90402
File configuration (#1249)
* Add configuration model
* Add metrics and logs configuration model
* Remove accidentally added package dependency
* Fix `$properties` typehint to match config
Default value available -> cannot be null.
* Add configuration example that utilizes env substitution
* Fix/suppress config psalm issues
* Fix/suppress config phpstan issues
* Suppress config phan issues
* Apply cs-fixer
* Change config package version to development version 0.x
* Add README
* Add basic test
* Fix psalm and cs
* Fix composer requirement for PRs
* gitsplit, copy spi config to root composer.json
2024-04-01 18:13:01 +11:00
Tobias Bachert 6dd255deac
Fix tracestate implementation (#1267)
* Port tracestate tests
* Fix tracestate implementation
* Fix W3C test service
* Fix style
* Move tests into `TraceStateTest`
* Assert that warning is triggered when parsing invalid tracestate
* Add additional tests for valid/invalid keys/values
2024-04-01 17:05:09 +11:00
Brett McBride a1489d3081
upgrade to phpunit 10 (#1258)
* upgrade to phpunit 10

* removing unintended commented code
2024-03-18 21:02:39 -04:00
Tobias Bachert 639d8e2561
Update docker compose default php version to 8.1 (#1259)
* Update default php version for docker compose
* Use docker compose v2
> From July 2023 Compose V1 stopped receiving updates.
2024-03-16 10:50:25 +11:00
Brett McBride 4cb04999d9
drop php 8.0 support (#1256)
* bump php to 8.1, apply rector
* readonly and typehints
* suppress a dodgy readonly property conversion
* remove some redundant readonly phpdocs
* dont run workflows against 8.0
* more readonly and typehints
* phpdoc reformat
* typehints
* remove php81 polyfill
* revert a rector BC breaking change, and disable that rector for ParentBased
2024-03-15 10:14:21 +11:00
Tobias Bachert 1753fbe32b
Fix conversion of non-utf8 sequences to `AnyValue` (#1253)
String values which are not valid Unicode sequences SHOULD be converted to AnyValue's bytes_value with the bytes representing the string in the original order and format of the source string.
2024-03-14 09:30:50 +11:00
Alexandre Choura 01c46a2350
perf: Re-use empty resource instance (#1251) 2024-03-12 14:49:02 +11:00
Brett McBride bb07aca7a2
upgrade psalm to v5 (#1246) 2024-03-04 06:58:09 -05:00
Brett McBride f798bb6f01
Drop PHP 7.4 support (#1244)
* drop php 7.4 support
update composer.json minimums, and run rector over the code to update what it can. changed some static analysis
config to fix some rector-induced failures.

* adding union typehints

* reformat constructor property promotions

* updating/removing phpdoc

* suppress protobuf extension complaint
submitted a PR upstream to fix phan stubs

* don't validate packages against 7.4

* remove php8 polyfill

* fix readonly comments

* apply trailing commas to multiline fixer
upgrade php-cs-fixer, and apply a new rule for multiline comments

* remove unreachable default match arms for protobuf serializer

* adding more union types to vars

* use weakmap directly

* remove handling for not-supported WeakMap

* spacing
2024-03-03 20:21:16 -05:00
Alexandre Choura cc56628c4d
feat: Allow OTEL_PHP_DEBUG_SCOPES_DISABLED as en environment variable (#1237)
* fix: Allow OTEL_PHP_DEBUG_SCOPES_DISABLED env var + use of null-coalescing operator
* refactor: Check order & env reset
* refactor: Use class constant
* fix: Respect order and value if it is set
* style: Lint
* tests: Falsey behavior
2024-03-01 10:04:41 +11:00
Brett McBride 258e58644a
support url-encoded OTEL_EXPORTER_OTLP_HEADERS values (#1242)
Per a recent spec clarification in https://github.com/open-telemetry/opentelemetry-specification/issues/3832 OTLP
headers should support url-encoded header values.

Co-authored-by: Tobias Bachert <git@b-privat.de>
2024-02-29 08:57:02 +11:00
Brett McBride b20c45df10
log previous exception message from error writer (#1231)
it's not always clear from an exception message what the underlying issue was, so
also print out the previous exception's message, if available.
2024-02-06 12:32:25 +11:00
Brett McBride 1f187c7837
update image build actions to latest versions (#1229)
this should resolve some deprecation warnings for some things that will soon break
2024-02-05 14:09:57 +11:00
Brett McBride e522d9d81f
improve excluded urls code (#1227)
improve code and add more tests to the OTEL_PHP_EXCLUDED_URLS feature
2024-02-02 14:42:40 +11:00
Brett McBride 36e2b7f613
adding OTEL_PHP_EXCLUDED_URLS (#1226)
Modeled on python's feature to turn off all instrumentation for specific URLs,
https://opentelemetry.io/docs/languages/python/automatic/agent-config/#excluded-urls
this feature will effectively disable SDK autoloading if there is a request URI that
matches one of the provided excluded URLs, and no-op implementations will be used
for tracer/logger/meter providers.
2024-02-01 08:21:30 -05:00
Brett McBride 91f5e20ffc
document when we drop support for end of life PHP versions (#1222) 2024-01-31 07:57:34 -05:00
安正超 84cf0a5635
Add required $contentType arguments (#1225) 2024-01-27 18:23:12 +11:00
Joao Jacome f2ab3c5e1d
Adding 'all' as an option for disabling auto instrumentations (#1220) 2024-01-24 23:00:22 +11:00
Brett McBride 810aa2f95a
generate semconv 1.24.0 (#1219)
* generate semconv 1.24.0
generate latest semconv version, and add back Trace and Resource attribute values which
seem to have been dropped in a previous change.

* document source repo release urls

* remove redundant semconv deprecations
two trace attributes were deleted then added back to upstream semconv, so remove our ones.
2024-01-24 08:47:17 +11:00
Tobias Bachert 1af83342f7
Fix proto 1.1.0 trace flags (#1216) 2024-01-17 23:46:01 +11:00
Brett McBride 102f5dc187
update proto to 1.1.0 (#1215)
updates generated protobuf files to 1.1.0, and adds trace flags to OTLP-encoded spans and span links
2024-01-17 08:54:57 +11:00
Brett McBride 2390dc07b0
cache php extensions (#1213)
Optimize build times by caching php extensions for one week, particularly for 8.4/nightly which otherwise builds extensions from source each time.
This ended up being a little convoluted, since caching extensions does not run on failure. So, make all steps continue-on-failure for experimental builds, and add a final post job which checks the status of the steps and does a final fail.
2024-01-17 08:32:21 +11:00
Brett McBride 521940d988
optimize resource merging (#1214)
- do not revalidate/normalize resource attributes on merge, since they have already been validated/normalized
- string concat is about 10x faster than sprintf, so use it in ClassConstantAccessor since it's called many times
2024-01-16 08:33:18 +11:00
Brett McBride 3928b13152
optimize resource creation (#1210)
* reduce resource creation from sdk autoloader
- instead of creating new resources from various factories, create them once from sdk autoloader and
pass them to the factories (most of which already supported this).
- check env before php.ini for config, since this is the more popular approach and saves some cycles
- cache header from OtlpUtil, to save a couple of calls to Sdk detector
* adding benchmark for resource creation
2024-01-13 16:52:09 +11:00
Brett McBride 25726f6cb9
fixing deptrac complaints (#1211) 2024-01-13 16:51:17 +11:00
Tobias Bachert 925ae9b12f
Handle out-of-order destruction of Fibers/DebugScopes during final shutdown (#1209)
* Handle DebugScope out-of-order destruction during final shutdown
* Move debug traces from local scope storage to debug scope properties
* Fix phpstan error
2024-01-13 16:50:44 +11:00
Tobias Bachert 596d4a2cea
Add support for multi-instrument callbacks (#1202)
* Add support for multi-instrument callbacks

https://opentelemetry.io/docs/specs/otel/metrics/api/#multiple-instrument-callbacks

* Fix undefined offset on detach of batch callback with repeated instrument

* Unify BatchObservableCallback and ObservableCallback

* Add missing typehint

* Do not bump API dependency

Not required, SDK will continue to work with lower API versions, only `::batchObserve()` won't be usable.
2024-01-10 08:04:59 -05:00
Tobias Bachert 82c0f8ed59
Add option to disable debug scopes (#1205) 2024-01-09 11:33:41 +11:00
Tobias Bachert a196c13425
Fix delta storage failing to merge node under rare circumstances (#1201)
Only fails if a node that was created after exceeding 63 readers should be merged with a node that was created before exceeding 63 readers, resulting in an `GMP===int` comparison. Affected nodes were still merged on the next `::collect()` call -> solely internal change.
2023-12-29 09:10:34 +11:00
Brett McBride 7c45db059d
adding 8.3 to build matrix (#1189)
* adding 8.3 to build matrix

* add experimental 8.4
2023-12-25 12:58:29 +11:00
Tobias Bachert bf8119c420
Prevent propagator packages from throwing fatal error if sdk not installed (#1198)
* Prevent propagator extensions from failing if sdk not installed

* Remove KnownValues dependency

Also prevents failing for cloudtrace: sdk < 1.0.1 and jaeger: sdk < 1.0.3.
2023-12-25 10:31:33 +11:00
Przemyslaw Delewski 4ff6ae4dbe
Updating CONTRIBUTING.md (#1194) 2023-12-19 10:14:38 +11:00
Tobias Bachert d4149990a3
Serialize protobuf enums as integer (#1192)
Spec: "Values of enum fields MUST be encoded as integer values."
2023-12-18 10:25:22 +11:00
Weslen Teche d8827f9681
Add Jaeger Propagator (#1188)
* jaeger propagator

* adjust readme

* add baggage and debug flag

* add units tests

* code review fixs and baggage separator

* update readme and register

* improve more tests

* fix php ci

* fix knowvalues jaeger baggage
2023-12-16 10:12:26 +11:00
Tobias Bachert d3765662f9
Add instrument advisory parameter (#1186)
* Add instrument advisory parameter

* Undo bucket boundaries change to preserve BC

"SDKs SHOULD use the default value when boundaries are not explicitly provided, unless they have good reasons to use something different (e.g. for backward compatibility reasons in a stable SDK release)."

* Add note that passing callback instead of advisory is deprecated
2023-12-13 13:03:10 +11:00
Tobias Bachert a6d15cf26e
Fix typo and deptrac rule (#1156)
* Fix typo "interal" -> "internal"
* Remove semconv from API deptrac ruleset
Removed in https://github.com/open-telemetry/opentelemetry-php/pull/965.
2023-12-08 09:54:20 +11:00
Jeremy Nikitin a568dde3f3
Rename XCloudTrace to CloudTrace (#1142) 2023-11-27 15:26:07 +11:00
Brett McBride 28657a9ec1
generate semconv for 1.23.1 (#1145)
a bug in 1.23.0 meant that cloud, container and oci resource attributes were incorrectly published under trace attributes.
sort the attributes, so that future diffs are easier to read.
2023-11-22 09:12:22 +11:00
Jeremy Nikitin d6c4c89bf4
Implement GCP X-Cloud-Trace-Context Propagator (#1132) 2023-11-14 09:04:22 +11:00
Brett McBride 30b73d948c
generate semantic conventions for 1.23.0 (#1137) 2023-11-08 10:26:31 +11:00
Brett McBride 42a8b95501
adding 1.19->1.22 semconv traceattributes deprecations (#1129) 2023-10-20 07:10:44 +11:00
Brett McBride a325a8f0bd
update semconv to 1.22.0 (#1126)
* update semver to 1.22.0
Since 1.19.0, the source has been split out of opentelemetry-specifiction into semantic-conventions. Update the build script accordingly.
Update to latest generator.
Add 2 new deprecations for semconvs which were renamed since 1.19
* update telemetry semconv
2023-10-19 07:53:08 +11:00
Brett McBride 842aa4121d
update SemConv readme (#1128)
mention that tags align with the upstream semantic conventions repo
2023-10-19 07:49:03 +11:00
Weslen Teche f22ffa0137
improving more tests (#1127) 2023-10-15 12:06:52 +11:00
Weslen Teche ea86fe1891
fix: documentations links (#1125) 2023-10-13 11:48:23 +11:00
Roman Kovalev b5170bf202
chore: fix broken link to env specs (#1122) 2023-10-05 16:29:42 +11:00
Brett McBride 75bb45fa71
adding 8.2 + 8.3 to build matrix (#1107)
8.3 is in RC, so add it to the matrix.
bump 8.2 to non-experimental, which should have happened some time ago.
remove deprecated assert_options call from test bootstrap
2023-10-05 12:45:08 +11:00
Brett McBride 8809c2a0b5
remove global configuration resolver (#1118)
Exposing it through Globals can cause a race condition. If something (eg, a contrib module)
retrieves the configuration resolver from Globals too early during autoloading, then it
causes the rest of the objects from Globals to be initialized. This can happen before all
required modules have been registered (depending on autoload->files execution order, which
is variable). Instead, create a simple API config resolver which does the basics of what the
SDK one does (without all the type checking and validation).
2023-09-28 09:15:51 +10:00
Greg Pinnington 3032304c3b
Add 'Contributing' message (#1108)
Co-authored-by: RoBorg <roborg@gmail.com>
2023-09-05 13:38:44 +10:00
Brett McBride 1852d514ca
fixing some psalm 5 complaints (#1110)
Whilst investigating upgrading to psalm 5, I notice that it generates a lot of new complaints. This fixes the ones that looked legit and
require an API change, or were trivial. Does not upgrade to psalm 5 yet, though. That's a bigger job for another day.
2023-09-05 08:56:24 +10:00
Brett McBride 73ff5adcb8
refactor sdk/api logging (#1105)
send errors/warnings/etc by default through PHP's error_log. This gives more control to administrators, since error_log can
be configured to write to any stream (file, stderr, etc). I think it's also less surprising for people trying out otel (particularly
with development PHP settings, where trigger_error often breaks an application).
Adding a configuration value to control where logs go: OTEL_PHP_LOG_DESTINATION.
2023-08-31 09:39:33 +10:00
Brett McBride 197a7a4c2c
optional internal metrics (#1106)
adding a configuration option OTEL_PHP_INTERNAL_METRICS_ENABLED which
controls whether the SDK will emit its own metrics (eg batch processor
state).
2023-08-31 09:23:20 +10:00
Brett McBride 62a14d1c20
remove deprecated code and BC hacks (#1099)
in preparation for RC, removing deprecations and BC hacks so that we have a clean slate for 1.0.0
2023-08-16 21:51:46 +10:00
Brett McBride 82f0c4477e
move temporality into own interface (#1098)
per TC review, temporality is not part of MetricExporterInterface. Riffing on Java's solution, this moves
`temporality` into `AggregationTemporalitySelectorInterface`, and adds that interface to MetricExporter instances
that use it (everything except `NoopMetricExporter`).
2023-08-10 08:11:34 +10:00
Brett McBride 55c08f3f44
adding PushMetricExporterInterface (#1097)
https://github.com/open-telemetry/opentelemetry-specification/pull/3563 clarifies the behaviour of
forceFlush with push/non-push metric exporters.
Break forceFlush out into a PushMetricExporterInterface, and update ExportingReader to only collect/flush
if exporter is a push metric exporter.
2023-08-10 07:47:46 +10:00
Greg Pinnington 9f358617f1
Fix for maxRetries < 1 (#1094)
* Fix for maxRetries=0
* Don't loop infinitely for negative maxRetries
2023-08-08 14:12:26 +10:00
Greg Pinnington c61f148d64
OtlpHttpTransportFactory should pass all arguments to PsrTransportFactory (#1093)
Co-authored-by: RoBorg <roborg@gmail.com>
2023-08-02 21:26:10 +10:00
Brett McBride ff15cc7037
document that examplars are not stable (#1091)
noted in TC review. Java moved their examplar code into an internal package, and
documented that it may change. We don't have an internal package, so document
the warning in a few places.
2023-08-01 08:09:07 +10:00
Brett McBride 7b8daff5ef
adding configuration resolver (#1083)
adding a configuration resolver interface, and api+sdk implementations. the resolver is globally configured.
this allows contrib modules to fetch config if an SDK is installed, without directly using the SDK (per spec).
2023-07-31 13:43:09 +10:00
Levi Morrison 1905dbfcd5
fix: fiber observers by FFI are not safe on ZTS (#1090)
They aren't _truly_ safe on NTS builds either, as the functions used
are only expected to be set at certain times of the lifecycle, but in
practice it's safe enough on NTS.

However, for ZTS, these APIs are not safe to call at runtime at all.
2023-07-26 09:47:28 +10:00
Brett McBride 4d9720f19e
improving test coverage (#1084) 2023-07-20 09:31:32 +10:00
Brett McBride 29cff8b991
fixing minor static analysis complaints (#1080)
fixing static analysis complaints, most of which were from psalm
when run with --show-info
remove deprecated httplug discovery
static data providers (phpunit10 requirement)
2023-07-20 09:30:31 +10:00
Tobias Bachert 926f6e5583
Always weaken asynchronous callbacks (#1081)
* Always weaken asynchronous callbacks
* Update comment regarding weak callbacks
2023-07-17 08:42:06 +10:00
Tobias Bachert cf8be76463
Remove workaround for php GH-8995 (#1082) 2023-07-17 08:38:33 +10:00
Brett McBride a60d0ad80c
rename log record processors (#1073)
per TC review, align log record processor names with those used in the spec
2023-07-11 09:37:28 +10:00
Brett McBride da219a9829
handle KeyValue otlp attributes (#1077)
if an array is non-simple (has keys), it should be represented as a KeyValue in the generated
protobuf-encoded output.
Since we also need to support simple arrays of primitives, I've added a basic check so that
those are still represented as ArrayValue.
2023-07-11 09:36:39 +10:00
Brett McBride 5853adabf1
phpdocs and example of weakening metric observer (#1078) 2023-07-11 09:36:04 +10:00
Brett McBride c9c83117e7
refactor attribute validation (#1072)
moving private method into a testable class, introduce attribute validation class
which applies to most attribute. LogRecord attributes are allowed to be complex,
so introduce a validator for these which lets everything through.
2023-07-11 09:35:24 +10:00
Brett McBride 3246ca8e4d
set schemaUrl for logs output (#1071) 2023-07-11 09:26:40 +10:00
Brett McBride cc92a07eac
update proto files to 1.0.0 (#1070)
no change from 0.20.0 (which was a release candidate)
2023-07-05 08:02:44 -04:00
Brett McBride 638799275c
require google/protobuf (native) (#1067)
We made protobuf implementation optional back in #949 however it seems to be tripping up
a number of developers. Since native + extension can be installed at the same time (with
extension taking priority), I think that users will be less surprised when starting out
if there is a working implementation by default.
2023-07-04 14:47:34 +10:00
Brett McBride 5e827ab7fc
improve logs console output (#1060)
support multiple scopes in console log output, and update batch example to illustrate
2023-07-04 14:46:57 +10:00
Brett McBride cb45b4a75d
fixing homogenous check for attributes with non-numeric keys (#1057)
use reset() instead of trying to get zero array key
2023-06-28 08:25:27 +02:00
Brett McBride d6e0689604
readme badges and cleanup (#1053)
* adding badges to the various readme files to make more obvious the current versions
* list all packages and versions in main readme
* remove old README documentation (excluding development-specific), and direct users to opentelemetry.io
* link to opentelemetry.io where possible in package readme
* adding a badge to link to releases
releases are not easy to find, since they exist only in the subtree split repository
2023-06-26 21:10:20 +10:00
Brett McBride a0601c41ec
adding sdk console metrics exporter (#1055)
to make getting started easier (in opentelemetry.io docs), create an sdk-based metrics
exporter. this means we can export all signals without needing a protobuf implementation.
since console export is only useful for playing around, the change in format to a
simpler human-readable output seems reasonable.
2023-06-26 20:59:08 +10:00
Brett McBride dc9501e8a9
adding support info to composer.json files (#1054) 2023-06-26 20:57:52 +10:00
Brett McBride 49638eae02
deprecate sdk/common/dsn (#1037)
I can't find any usage of these classes anywhere in main or contrib repo. rather than delete, lets deprecate and remove closer to release candidate
2023-06-23 21:02:56 +10:00
Brett McBride 58e19760e3
fixing broken links (#1052)
* fixing broken link in logs readme
* typo
* another broken link
2023-06-23 21:00:17 +10:00
Brett McBride 51137bfea6
adding support info to sdk composer (#1036)
* adding some links to try to make it easier for users to find the right support/repositories etc
just doing one composer file to see if it works, and will follow-up with more in a later PR
* change forum to chat
2023-06-23 17:49:28 +10:00
Brett McBride fed6413a76
moving some otlp code out of sdk (#1039)
otlp exporter code belongs in contrib/otlp
2023-06-23 10:31:32 +10:00
Brett McBride 4913926ec1
error log backtrace and OTEL_LOG_LEVEL support (#1043)
* Adding a backtrace to the errors reported via error_log (which is the default)
* Implement OTEL_LOG_LEVEL, which can be used to control which errors are reported via error_log. Note that
this doesn't use configuration code from the SDK, as the usage is in the API (because messages are logged
from many packages) and deptrac rightly complains about the dependency on SDK.
2023-06-23 10:30:46 +10:00
Brett McBride 29dc1a414f
fixing http client implementation (#1041)
We do not actually require an async http client, so use psr/http-client-implementation instead.
We depend on the psr/http-client interface, so require it (which has a side-effect of un-breaking
the symfony http client which is frequently auto-installed by php-http/discovery's plugin)
2023-06-23 10:24:12 +10:00
Brett McBride 8fe898bdb4
adding batch span processor builder (#1046) 2023-06-23 10:22:49 +10:00
Brett McBride 1caf77b436
fixing backwards-compatibility (#1044)
- sdk BC was not being loaded at all in the sdk package (only in the monorepo), so add it to autoload->files
- fixing api/common BC layer (removing .php and fixing one of the FQCNs)
2023-06-20 16:43:03 +10:00
Brett McBride 1aea1f23b9
moving api/common classes up to api (#1033)
- apply TC review feedback to move Globals to top-level.
it was suggested to move Instrumentation into its own package, but I chose instead to just move that dir
up to the top level of API
- added a BC layer to alias the moved classes
- added some more examples
2023-06-16 08:51:03 +10:00
Brett McBride d81874ed11
allow http/message 2 (#1034) 2023-06-15 16:35:51 +02:00
Brett McBride ea09e53519
drop attributes with non-homogenous array values (#1023)
per spec, arrays MUST contain only the same types. I've allowed for numeric types
(integer + double) to be treated as equivalent.
2023-06-09 09:34:20 +10:00
Brett McBride 22542528af
adding meter provider builder example (#1026)
adding an example using the meter provider builder, and deprecating a redundant method, `registerMetricReader`
2023-06-09 09:32:18 +10:00
Brett McBride e8ee4363e7
update proto to 0.20.0 (#1029) 2023-06-09 09:25:59 +10:00
Brett McBride 2601eaafe8
move trace flags consts into TraceFlags interface (#1028) 2023-06-07 22:34:13 +10:00
Brett McBride 32c161b167
rename span builder parameter (#1024)
TC feedback suggested to rename param to hint at the type (nano seconds)
2023-06-07 13:51:31 +02:00
Brett McBride 6a77cf5ba4
improve documented scope return values (#1025)
TC review suggests that DETACHED and INACTIVE responses need clarification
2023-06-07 13:49:12 +02:00
Brett McBride 23cc194da1
psalm check examples (#1006)
Configure psalm to run over all examples, and fixing the issues it identified.
2023-05-31 08:13:35 +02:00
Brett McBride 1b63a3b1c3
adding console metric exporter (#1005)
allow the existing metric exporter to be created from env vars, by creating a factory
and registering it against 'console'. Now, OTEL_METRICS_EXPORTER=console will create
a metrics provider with console output. Note that it lives in contrib/otlp, since it
uses the existing otlp converters.
2023-05-17 10:41:55 +10:00
Brett McBride 82b30dc437
remove container detector (#1004)
per spec, container detector has been moved into contrib and is published as a composer package
2023-05-17 08:34:51 +10:00
Brett McBride 65491ab66b
adding resource detectors to registry (#999)
To enable registering non-SDK resource detectors within the SDK, extend the SDK Registry.
Detectors will be looked up by name and applied as part of 'all', or as part of a list
of detectors
2023-05-10 09:16:45 +10:00
Brett McBride 5d35c998e7
remove proprietary new relic exporters (#998)
New Relic now fully supports OTLP ingestion, and having proprietary exporters is no longer their strategy. The proprietary exporters have been marked as abandoned in packagist, and suggest exporter-otlp as a replacement.
2023-05-09 20:20:50 +10:00
Brett McBride 593fa344bc
removing prometheus example (#996)
the example is very old, does not work, and it doesn't look like the capability
is in the spec these days. Remove the code so that it doesn't cause confusion.
2023-05-08 19:51:22 +10:00
Tobias Bachert e7be05c73e
Fix `weaken()` scope not preserved for first class callables when scope not equals target class (#995) 2023-05-08 09:17:00 +10:00
Brett McBride bd02259089
resourceinfo spec compliance, instrumentation attribute (#989)
Introduce spec-compliant ResourceInfo::merge, and deprecate our current implementation.
When merging resources, later (updating) keys should override existing keys, per spec.
Reorganise detectors so that environment has highest priority (per spec, OTEL_SERVICE_NAME should be the highest priority built-in way of setting service name)
Adding the experimental telemetry.auto.version attribute, if the auto-instrumentation extension is installed.
2023-05-08 09:15:45 +10:00
Brett McBride efe696f285
temporality preference from env (#990)
Implement OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE, which controls the temporality of meters when creating from environment vars.
Add OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION to variables, although we do not yet have anything that uses it.
2023-05-05 09:32:14 +10:00
Brett McBride c701693c25
remove 'include context' parameter from logging examples (#992)
the param was removed from spec, and our API implementation recently, but
I missed these examples.
2023-05-04 16:35:24 +02:00
Brett McBride 952c069792
adding batch LogRecord processor env config (#991)
Adding new spec variables for configuring batch LogRecord processor from environment.
2023-05-04 10:58:07 +10:00
Tobias Bachert 1976f53f92
Add branch aliases (#988) 2023-05-03 08:59:57 +10:00
Brett McBride 4890bd4a27
dotenv file plus rector (#983)
use docker compose 'env_file' to include all .env file vars in container env
make the default rector action dry-run, which allows developers to inspect code changes
before applying them (and therefore giving the option to disable new rules before they
are applied to WIP).
2023-05-02 19:53:04 +10:00
Tobias Bachert 77da9503fb
Use noop staleness handler factory by default (#987) 2023-04-30 20:06:59 +10:00
Tobias Bachert a7a28616b2
Move metric collection to `MeterProvider`-wide registry (#979)
* Add metric registry
* Use metric registry to record and collect metrics
* Minor cleanup
2023-04-27 08:15:20 +10:00
Brett McBride 6fd6a3c180
adding local dev prefer-lowest (#976)
Adding some make targets which will install composer dependencies with the lowest
package versions. This highlights some small issues with older versions, so bump up
the minimums of a few dev dependencies.

Adding more make targets:
- all-lowest (run all checks after updating with --prefer-lowest)
- all-checks (run all checks without first running a composer update)
- update-lowest (update dependencies to lowest installable versions)

Quieten unit test output (the previous testdox output is available via `make test-verbose`)
2023-04-27 08:14:56 +10:00
Brett McBride 9bccde9f03
update semantic conventions to v1.19 (#965)
* update semantic conventions to v1.19
* updating semconv readme
* dropping attribute values
I can't find any usage of the various AttributeValues being used, and other SIGs
no longer generate them, so removing them
* removing semconv usage from API
allow deprecations of moved/removed attributes so that we don't break things across different
semconv versions (similar to how java does it, except I moved them into a file which is
imported
2023-04-27 08:13:26 +10:00
Brett McBride 80ac91fddd
fixing symfony link in readme (#982) 2023-04-26 07:13:23 +02:00
Brett McBride 659a705d95
relax default logging levels (#975)
without a psr-3 logger, we use trigger_error. Using this with E_USER_ERROR is fatal, so adjust the level down.
2023-04-19 17:21:16 +02:00
Brett McBride 8f70a6d19f
apply logging spec updates (#977)
Removing include_trace_context parameter
Set ObservedTimestamp on emit if not already set
Rename logRecord to emit
2023-04-18 14:43:09 +02:00
Tobias Bachert 0e61e95f3c
Fix otlp json trace id and span id (#973)
* Fix otlp json trace id and span id format

* Ignore unknown fields in otlp json response

* Suppress incorrect phan error
2023-04-18 14:08:20 +02:00
Tobias Bachert 23762dbbd3
Split metric collection from metric streams (#972)
Split metric collection from metric streams
2023-04-15 22:09:43 +10:00
Brett McBride a06e5e4e45
Multiple log processors (#967)
adding support for multiple log processors
2023-04-15 09:27:50 +10:00
Brett McBride c687df160d
report dropped counts in non-otel exporters (#966)
per spec, exporters MUST report on dropped attributes/links/events using keys defined in spec
2023-04-15 09:25:44 +10:00
Brett McBride e22007a98e
documenting logs bridge api, adding memory exporter (#959)
* implement bridge api

* adding logs memory exporter

* clarify bridge api not for developers

* adding logger provider builder

* review feedback

* removing Bridge and documenting what a bridge is
2023-04-12 08:06:41 -04:00
Brett McBride 653a726959
new rector rules (#964)
apply one new rector rule, and disable FlipTypeControlToUseExclusiveTypeRector (which changes about 40 files, and IMO makes it harder to comprehend)
2023-04-07 12:36:40 +10:00
Cedric Ziel ca2df9f307
Update publish-otel-php-base-docker-image.yml (#961)
Use correct arm64 platform for building docker images.

My previous PR in #960 used the wrong platform for M1/Apple silicon
2023-04-05 18:55:19 -04:00
Cedric Ziel 72e9f56fbb
Build arm64 base images (#960) 2023-04-05 14:58:02 -04:00
Brett McBride 502df0eded
adding LogRecord phpdocs (#956)
clarify that timestamps expect timestamp in nanoseconds, plus minor logging example fixes.
2023-04-05 22:42:42 +10:00
Piotr Antosik a3abdcdb0d
add composer resource detector defaults (#952)
- add composer to defaults
- update readme: missing info about container & composer
2023-04-05 12:18:57 +10:00
Brett McBride 0a6d7cb8e4
fail if no protobuf implementation found (#958)
the otlp exporters (logs, metrics, traces) will fail to export if there is no protobuf implementation (which we have
just made optional, to allow users to choose between extension and native). Add a check to
the constructors which will throw a runtime exception.
If creating the exporter directly, it will be uncaught. If using a factory, it will report a
warning and return a no-op exporter.
2023-04-05 10:02:44 +10:00
Brett McBride dd23c8d0ea
pre-GA doco cleanup (#946)
moving lots of documentation into opentelemetry.io, which is
the official source and where we should send people in the
first instance.
2023-04-02 21:00:34 +10:00
Sem Schilder 711ebf98c6
Rename extension (#955) 2023-04-01 12:48:42 +02:00
Sem Schilder 4544cbd94a
Make protobuf implementation optional (#949)
* Make google/protobuf an optional dependency
* Update the README with more information on installing protobuf implementation
* Add some extra documentation in the OTLP exporter library
* Update proto/otel/README.md
2023-03-30 20:16:18 +11:00
Brett McBride 83bacc9d40
remove create_releases script (#945)
create_releases has been replaced by an improved version in https://github.com/opentelemetry-php/dev-tools
2023-03-29 08:02:36 -04:00
Cedric Ziel a2a4d4d0a1
Ensure base64 encoded values can be used as headers from env (#943)
This change instructs explode to extract at most 2 parts.

Given an example value of 
```
OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic bla64=
```

The config parser would have created the elements, where only two are required. The trailing `=` in base64 headers would then have been effectively discarded, leading to invalid configuration.
2023-03-27 09:16:47 +11:00
Brett McBride c899f08dc1
adding brettmc company affiliation (#942) 2023-03-25 08:16:07 -04:00
Brett McBride 41945220b9
do not gitsplit sdk-contrib or tags (#939)
sdk-contrib is abandoned in packagist, because we publish the packages individually
and at independent versions. for the same reason, do not gitsplit tags, only main
as we do the tagging in the read-only repos now
2023-03-23 20:56:35 +11:00
Przemyslaw Delewski ac1d03784f
open stream failure (#940)
* open stream failure

* Update src/SDK/Resource/Detectors/Container.php

Co-authored-by: Tobias Bachert <git@b-privat.de>

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2023-03-22 19:31:01 +01:00
Brett McBride 615917f5d4
adding logs signal (#934)
* initial work on logs signal

* supressing psalm error

* "fixing" 7.4 segfault
through trial and error, I found that it was consistently segfaulting in the sdk autoloader
tests, but by running them in a different order, the failures went away.

* adding logs tests

* rename example per feedback

* move log context injection into processors, per spec

* correctly set context on logs

* update logger name per feedback

* adding variables, map psr3 to otel severity, fix timestamp

* psr-3 loggers

* tests, psr3 v3 fix

* remove LogRecordDate and refactor SDK log record classes

* tests, tidy, improvements

* remove todos

* documentation

* check for valid span context

* removing psr-3 compatibility, per spec and feedback

* use InstrumentationScopeFactoryInterface

* apply attribute limits on readablelogrecord creation
per feedback, this should be more memory efficient for the processors

* group log record by resource/scope

* remove psr3 references from readme

* ignoring psalm error

* add trace context in Logger rather than processors
per feedback, and following the example in java and python SIGs, we
can add trace context to logs once, in the logger, rather than having
processors do it. The Context passed to processors is no longer used,
but retained for spec compliance.
2023-03-22 08:11:51 -04:00
Brett McBride c058a646f6
upgrade rector (#938)
use latest version, and apply suggested updates
2023-03-21 13:35:20 +11:00
Brett McBride 0538a5a7c7
fixing empty tracestate header handling (#936)
if an empty tracestate header was passed, we were emitting a warning (discovered in the demo app after enabling logging).
to fix this, check for empty string as well as null.
2023-03-16 18:45:15 +11:00
Piotr Antosik 640b6f53a0
Update exporter path in docs & makefile (#935) 2023-03-13 17:52:28 +01:00
Brett McBride 88ea7c3024
adding container detector (#933)
detect container id from cgroup or mountinfo
2023-03-03 09:18:42 +11:00
Piotr Antosik 746d25a7d1
Move grpc/grpc to dev dependency (#930) 2023-02-28 07:44:41 -05:00
Brett McBride 20f39b6a74
script to identify required releases (#928)
a script to identify which of our git-split repos have changes which are not in a release.
also creates release notes for the release, which can be dropped into the github UI
* print new release url
* relax symfony/yaml requirement
* warn about rate limiting if no token provided
2023-02-28 19:55:23 +11:00
Brett McBride da05ab83ce
fixing otlp+json example (#927)
fixing otlp+json example
2023-02-27 21:38:51 +11:00
Brett McBride 2a0a9e33e6
fixes and tests for MetricExporterFactory (#926)
Fixing grpc path and allowing compression from MetricExporerFactory
2023-02-16 10:00:14 +11:00
Brett McBride 19b9326751
relax composer version requirements (#918)
using self.version does not work when we have different components being released individually. ^1.0 seems like a sensible initial setting now that we have reached beta.
2023-02-16 00:44:20 +11:00
Przemyslaw Delewski 5f3e9cae9d
Update CONTRIBUTING.md (#925) 2023-02-14 12:44:41 -05:00
Brett McBride c6b0be7c89
remove older BC implementations (#923)
These BC features have been in place for multiple releases, it's time for them to retire.
2023-02-14 10:56:50 +11:00
Brett McBride e59f2c3cff
fixing phpunit 9.6 deprecations (#922)
phpunit v9.6 introduces a bunch of deprecations for things that will break in v10. This fixes the tests that are currently complaining.
2023-02-13 18:43:57 +11:00
Piotr Antosik 24af6ac173
fix PHP 7.4 preload error (#919) 2023-02-05 21:59:01 +11:00
Ricardo Fontanelli c4161a0ebe
Add scheme to collector endpoint on traces example (#913)
Add scheme to collector endpoint on traces example docker-composer file
2023-01-20 08:20:51 +11:00
Brett McBride 4b9f1200bf
adding a configuration for disabling auto-instrumentations (#909)
* adding a configuration for disabling auto-instrumentations
addressing review feedback from pdelewski, provide a mechanism that can be used to disable auto-instrumentation packages
without actually uninstalling them.
A new variable, OTEL_PHP_DISABLED_INSTRUMENTATIONS, has been added which accepts a list of instrumentation names to be disabled.
Each instrumentation can call Instrumentation::isDisabled to determine if they should bail without registering hooks.

* moving instrumentation disabled into Sdk class
2023-01-12 10:55:48 +01:00
Brett McBride 7b5ca0ce97
allow OTEL_SDK_DISABLED to disable sdk autoloading (#902)
* allow OTEL_SDK_DISABLED to disable sdk autoloading
* review feedback
- test for sdk disabled in initializer
- sdk disabled does not disable propagator, per spec
2023-01-11 10:05:28 +11:00
Przemyslaw Delewski ee26eaa5d8
Remove JaegerExporter and update interface (#908) 2023-01-10 09:25:34 +11:00
Brett McBride 2bd6bc5ff7
do not export empty metrics (#907)
If no metrics have been generated, do not send an empty export request (except via forceFlush())

Closes 905
2023-01-10 09:23:54 +11:00
Brett McBride 558e7ce30e
default logging to console (#899)
Rather than log nothing by default, log warnings and greater to console.
By providing a psr-3 logger, users can gain greater control over logging, including disabling it (via NullLogger)
2022-12-22 09:39:27 +11:00
Brett McBride c98866b3fa
update gitsplit regex to match beta releases (#898) 2022-12-13 11:42:17 +11:00
Brett McBride 425ebaf4f9
doco updates for beta (#895) 2022-12-12 09:05:21 -05:00
Brett McBride 02c1782667
adding php8.2 to build matrix (#896)
* adding 8.2 to build matrix

* 8.2 experimental

* relax deptrac

* allow style check to fail if experimental

* bump checkout action version
2022-12-12 09:05:09 -05:00
Brett McBride 616b356b83
tracestate + baggage todos (#894)
- remove baggage TODOs which have since been done.
- implement TODOs from tracestate to log warnings.
- tidy up tracestate code, simplify some const names.
2022-12-12 14:16:41 +11:00
Brett McBride 602ea8539f
move LoggerHolder to API (#893)
there is a requirement (and some outstanding todo's) to log errors and warnings from the API, so move
logger setup into API to facilitate this.
2022-12-12 09:01:17 +11:00
Brett McBride 0073d6dfe6
create text map propagators from registry (#885)
* create text map propagators from registry
removing undocumented dependency between sdk and extension by adding text map propagators to a registry
as part of composer autoloading, similar to how exporters, transports etc are treated.
* remove TextMapPropagatorFactory instances and register the singletons directly
* rename FactoryRegistry to just Registry
2022-12-10 08:42:47 +11:00
Brett McBride 5a51249c6b
removing jaeger exporters (#890)
Jaeger has dropped support for the jaeger exporter in favour of opentelemetry exporter. The upstream repos are now archived.
Support has been dropped from the opentelemetry collector, and other SIGs should follow soon.
ref: https://github.com/open-telemetry/opentelemetry-specification/pull/2858 and https://github.com/open-telemetry/opentelemetry-specification/issues/2859
2022-12-09 14:25:42 +11:00
Brett McBride f5698c8864
implement retrieve span and trace id as binary (#883)
per spec, https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#retrieving-the-traceid-and-spanid allow retrieving span and trace id in binary form
remove hex2bin calls from otlp span converter and use new binary accessor
2022-12-08 12:55:29 +11:00
Przemyslaw Delewski 7bfc1218d6
allow setting service name from auto instrumentation context (#881) 2022-12-07 23:23:19 +01:00
Brett McBride 02d94216e1
span status compliance (#884)
implement spec-compliance for span status:
- Ok is final
- Unset should be ignored
- Error can be updated to Ok

ref: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#set-status
2022-12-07 14:07:33 +11:00
Brett McBride 311afa265a
fixing default service name (#887)
* fixing some sdk/default resource values
- default service name should contain runtime name if available; java just appends ":java" so I did the same

Co-authored-by: Tobias Bachert <git@b-privat.de>
2022-12-07 09:58:33 +11:00
Brett McBride dc5ef24bd3
adding baggage example usage (#888)
adding a baggage example
2022-12-07 09:52:21 +11:00
Brett McBride a1e8aff01e
move exporter examples (#886)
moving exporter examples up one directory, where I think they are more obvious to find.
remove some old and broken grpc examples.
remove unused interface.
2022-12-07 09:00:09 +11:00
Brett McBride 587bc5aaf0
fix stream transport factory creation (#882)
when creating a stream from an endpoint string, the factory wasn't returning the stream. fix and add tests.
Co-authored-by: Tobias Bachert <git@b-privat.de>
2022-12-05 22:02:12 +11:00
Tobias Bachert fd8ac30f07
Run exports with the `Context` the `SpanProcessor` was created in (#880)
* Run exports in spanprocessor construction context

* Resolve psalm issues
2022-12-02 13:31:42 -05:00
Przemyslaw Delewski 0ce2fda813
fixing typo in name (#877) 2022-12-01 09:08:50 +11:00
Brett McBride 2e96621b0f
allow 16 char b3 trace id (#869)
b3 spec allows trace id to be 16 or 32 char. other SIGs left-pad with zero to resolve this.
2022-11-30 14:03:18 +11:00
Brett McBride 80afb1d948
updating membership lists (#876)
adding pdelewski, our newest maintainer
moving some past members into a new 'emeritus' section
2022-11-30 13:39:00 +11:00
Brett McBride 017c3e1c76
update contrib autoloading and gitsplit (#875)
* update grpc gitsplit destination
match the gitsplit destination repo to match package name: 'transport-grpc'
* adding missing autoload files for exporters
2022-11-30 09:54:23 +11:00
Brett McBride c735471aef
improve and expand otlp benchmark (#874)
- remove Mocker mocks, which were contributing extra time, and replace with no-op implementations
- adding extra benchmarks (batch vs simple, protobuf vs json)
2022-11-30 09:53:28 +11:00
Brett McBride 1ffd7e80eb
migrate/remove swoole (#871)
contrib/swoole has been moved into the contrib repo: https://github.com/open-telemetry/opentelemetry-php-contrib
2022-11-29 14:36:58 +11:00
Brett McBride 17f2fac397
tests and benchmark for baggage parsing (#873)
* tests and benchmark for baggage parsing
* adding percent-encoded test case
2022-11-29 14:33:40 +11:00
Brett McBride d37d4490d9
decode OTEL_RESOURCE_ATTRIBUTES values (#872)
per spec, resource attributes coming from environment should be decoded in
the same way that they would be if coming from a header
2022-11-29 14:32:26 +11:00
Brett McBride 01378ecf8a
disallow non-standard boolean config values (#870)
per spec, only 'true', 'false' are valid boolean values. anything else should be
interpreted as false and a warning emitted.
2022-11-29 14:31:09 +11:00
Marcos Passos 22c78cfd3b
Remove internal tag from Context::setStorage (#867)
This allows custom storage (eg for Swoole) to be used.
2022-11-26 07:26:34 +11:00
Brett McBride 904da75ee6
adding exporter + transport registry (#862)
* adding exporter + transport registry
to remove the hidden dependency between SDK and contrib, move all of the exporter knowledge out of
exporter factory, and invent a registry to hold those values. The registry can be added to by contrib
modules as part of composer autoloading.
This also allows users to override things like transports (eg, provide their own grpc transport).
Remove exporter's fromConnectionString as it's not in spec, and I couldn't get it to work nicely with the
registry idea.

* fixing up examples

* allow callables to be registered as factories
adding an example of replacing a registered transport factory with another implementation

* Registry to FactoryRegistry

* new relic exporter factory, tests

* review suggestions

* tidy

* change fromEnvironment() to create() in factories
2022-11-23 14:39:24 -05:00
Brett McBride 116e46d964
sdk autoloading (#854)
* sdk autoloading
* use instrumentation initializers
* basic sdk + autoloading documentation
* exampler filter from config
* configuration default types
2022-11-14 08:52:35 +11:00
Brett McBride f083b10909
refactor environment configuration (#859)
refactoring Environment access to allow configuration from multiple sources. Initially, the sources are env ($_SERVER) and php.ini, but this should allow us to add more sources in future without changing the API.
do not modify OTEL_EXPORTER_OTLP_TRACES_PROTOCOL
allow resolvers to return mixed
2022-11-10 09:48:17 +11:00
Erdem Köse 92e7a0d070
Fix OTLP GRPC example (#856) 2022-11-05 09:10:14 +11:00
Brett McBride 0b43fac729
refactor otlp exporter (#838)
* merge otlp exporters
continuing on from Nevay's work, this removes the individual OtlpHttp and OtlpGrpc exporters, and replaces with
Otlp\Exporter using a transport to manage grpc and http/protobuf complexity.

* tidy

* use mockery overload instead of prototype clone

* making all smoke-test examples work

* removing startBatch
verified that the call attributes have the same values when using TraceServiceClient

* tidy

* tidy

* Revert "use mockery overload instead of prototype clone"

This reverts commit bbb685b4d1.
Mocking proto-generated files segfaults with ext-protobuf (which is harder to diagnose when running in a child process, which
was required for fancy mockery mocking of "new". So, back to the prototype approach, and skip the tests if ext-protobuf enabled.

* tests without mocking protobuf

* test

* typo

* reverting FromConnectionStringInterface

* grpc headers

* revert to dumb transports, handle multiple protocols

* tidy, adding initial otlp json support

* self-review

* linting

* remove redundant interface

* Revert "remove redundant interface"

This reverts commit 350d40cdfe.

* fix getFloat

Co-authored-by: Tobias Bachert <git@b-privat.de>

* move withSignal into otlp-specific interface

* moving exporter/transport env handling into a new factory

* linting

* remove unused code

* tidy

* moving OtlpHttp into Otlp

* removing OtlpTransportFactoryInterface

* fix style

* fixing psalm error

* addressing review feedback

* replacing removed code

* fixing example

Co-authored-by: Tobias Bachert <git@b-privat.de>
2022-11-02 08:31:48 -04:00
Brett McBride ba9899278f
Sdk builder (#845)
Adding an SDK builder and example usage.
2022-10-31 08:09:01 +11:00
Tom Carrio 87989731ed
refactor: static access for EnvironmentVariablesTrait methods (#850)
* refactor: provide EnvironmentVariables static class for friendly-typed access
utilizes Accessor and Variables under the hood to provide consistent default values
2022-10-27 10:29:24 +11:00
Tobias Bachert 32d04f6a1d
Add support for global instrumentation initializer (#849)
* Add support for global instrumentation initializer

* Add `Configurator::createNoop()` to simplify disabling instrumentation
2022-10-26 08:09:33 -04:00
Brett McBride 4489eeca2e
removing event dispatcher (#848)
* removing event dispatcher
discussed in SIG to remove this unused code. It was going to be infrastructure for emitting metrics from other parts of the code, but that's been done in a better way now.

* remove EventContextIntegrationTest
2022-10-26 08:07:14 -04:00
Reiley Yang f6777575de
Update README.md (#847) 2022-10-19 21:24:07 -04:00
Tobias Bachert f6671ddd79
Add alternative instrumentation abstraction (#822)
* Add alternative instrumentation abstraction
* Provide global access to providers
Remove logs for now, will be replaced with `LoggerProvider` in the future.
2022-10-17 08:57:57 +11:00
Tobias Bachert f73a835ed2
Add self-diagnostic metrics to `BatchSpanProcessor` (#828)
* Add self-diagnostic metrics to `BatchSpanProcessor`

* Removing unnecessary import

Co-authored-by: Bob Strecansky <bob.strecansky@gmail.com>
2022-10-12 11:02:34 -04:00
Brett McBride 10830f2683
resolve deptrac baseline (#844)
* resolve deptrac baseline
Nevay found that an @internal annotation in NonRecordingSpan was the cause of the violation, so
remove it.

* make psalm happy
2022-10-12 09:06:29 -04:00
Tobias Bachert 3866a82d92
Refactor transport layer (#831)
- move content type from `::send()` to transport property
- move otlp exporter to `Otlp\` namespace
2022-10-12 10:01:20 +11:00
Tobias Bachert a167add2df
Drop general identity attributes by default (#843) 2022-10-12 09:12:54 +11:00
Tobias Bachert 47f8ab977d
Add `trace` convenience function that encapsulates `try-catch-finally` boilerplate code (#841)
* Add `trace` convenience function that encapsulates common boilerplate code
2022-10-11 09:32:35 +11:00
Tobias Bachert 7940773a31
Fix process resource detector triggers warning if running with unknown uid (#840) 2022-10-10 09:18:32 +11:00
leo108 8562d0d510
Grpc metadata value must be an array (#839) 2022-10-10 09:17:43 +11:00
Brett McBride a3a47a6ba4
adding OTEL_SDK_DISABLED support (#833) 2022-10-07 16:47:54 +11:00
Brett McBride 0e0c67d326
docker compose v2 support (#834)
adding the ability to use compose v2 (via .env), and adding a makefile target to locally build dev image
2022-10-05 09:54:12 +11:00
Tobias Bachert 215731f639
Improve `open-telemetry/context` documentation (#830) 2022-09-23 14:15:46 -04:00
Amber c0a62795e4
Refactor span context (#801)
* Otel-php:632 Move stack trace formatting out of Span class

* added function usages

* fix linting errors

* Added documentation for adding Span Attributes

* removing TracingUtl class

* Refactor TraceState's __toString method

* Added path with @covers to remove warnings

* Added @coversDefaultClass annotation

* fix to check if iterable is empty

* fixed for faling test case

* unit test

* Resolved review Comments

* reverting changes

* removing check for empty iterable span list

* review changes for SpanProcessor incorrect calls to SpanExporter::forceFlush()

* updated test case

* resolved review comments

* reverted changes for batch span processors

* reverting changes for batch span proccessor

* merge upstream and changes

* updating changes

* Refactoring SpanContext

* updating changes

* updated test cases

* updated changes suggested after review

* Revert "Reverting back to previous commit"

This reverts commit 941f368da3.

* updating changes after review

* unused use statement

* added unit test and resolved review comments

* Removed Double underscores from constant variables

* Removed constants from SpanContext.php to remove duplicacy

* updated failing test

* Moving Factory Methods back into SpanContext.php

* modified constructor of SpanContext

* updated SpanContext

* Modified use of additional if statement

* corrected parsing error
2022-09-21 10:37:19 -04:00
Tobias Bachert be3f88fa6c
Fix fiber support not loaded in `open-telemetry/context` (#829)
* Add missing autoload entry
* Fix fiber tests
* Trigger error if fiber support cannot be loaded
2022-09-20 09:31:33 +10:00
Tobias Bachert deeb07a890
Add interfaces for `Context` and `ContextKey` (#820)
* Add `ContextKeyInterface`
* Add `ContextInterface`
* Combine `SpanBuilderInterface::setParent()` and `::setNoParent()`
* Remove `NullPropagator`
* Fix `Context::with()` typehint
* Remove `Context::withContextValue()` suggestion
2022-09-19 09:40:32 +10:00
Tobias Bachert 15ebaeb98c
Change `SpanExporter::export()` return value to boolean (#827) 2022-09-19 07:27:51 +10:00
Brett McBride b551294d3f
export otlp InstrumentationScope attributes (#825)
* export otlp InstrumentationScope attributes

* remove redundant setting of dropped attributes count
2022-09-14 20:59:51 -04:00
Tobias Bachert 84142d35e9
Rename `AbstractSpan` to `Span` for consistent access to static methods (#824)
* Rename `AbstractSpan` to `Span` for consistent access to static methods
* Add BC layer for `AbstractSpan`
2022-09-15 09:07:52 +10:00
Tobias Bachert c000590a53
Add intermediate transport layer between http/grpc client and exporter (#809)
* Add `Future::map()` to allow async processing without explicit async dependency

* Add `TransportInterface` abstraction

* Fix style

* Add transport and future tests

* Replace `HttpSpanExporterTrait` with `PsrTransport`

* Update transports

- ignore invalid compression
- add stream transport

* Handle partial success response
2022-09-14 08:36:49 -04:00
Tobias Bachert 6196d7a809
Use array lookup instead of recursion in `Context` (#821)
* Use array instead of recursion in `Context`

* Move span and baggage context key to context package

* Add additional context tests
2022-09-14 08:36:11 -04:00
Tobias Bachert ad3ccd8139
Add debug scope to warn on incorrect scope usage (#823)
* Add debug scope to warn on incorrect scope usage

* Enable assertions in unit tests
2022-09-12 22:34:52 -04:00
Brett McBride f5e66e91dd
require protobuf extension for otlp exporters (#818)
* require protobuf extension for otlp exporters
* adding grpc native library dependency
2022-09-12 10:11:10 +10:00
Tobias Bachert 776273ca8a
Remove scope bound example implementations (#819)
Removes ScopeBound... classes to reduce the API surface.

- ScopeBoundCallable: Was intended for event loops. Event loop decorators should instead implement this in a way that fits the specific loop API the best with regard to avoiding unnecessary references to arguments and error handling.
(The implementation was (mostly) sufficient for react/event-loop but shouldn't be used for revolt/event-loop.)
- ScopeBoundPromise: Was only intended as very basic example implementation. An actual implementation has to hook into the specific promise implementation to capture the context of the initial promise.
(I'm not sure how useful promise/future support is in general, there are scenarios where we cannot preserve the context association, e.g. when extracting/awaiting the value.)
2022-09-10 13:26:11 +10:00
Brett McBride 6e385b96f9
document exporters as installable packages (#817) 2022-09-08 16:18:56 +10:00
Brett McBride ac3a35d85c
fixing php8.2 string usage (#810)
This resolves some deprecation warnings in php 8.2:
Deprecated: Using ${var} in strings is deprecated, use {$var} instead
2022-09-07 23:03:20 +10:00
Kishan Sangani 651f949cd8
Updated readme (#816) 2022-09-07 09:01:54 -04:00
Brett McBride 2cb5d6b0df
ignore phpstan false positive (#813) 2022-09-07 22:42:38 +10:00
Bob Strecansky e6e13b2561
Update CODEOWNERS to use the @open-telemetry/php-approvers (#814) 2022-09-07 22:42:09 +10:00
Kishan Sangani c3170e3bd2
Update README to include extension packages (#812)
* Added extension packages search link on packagist
2022-09-07 13:50:46 +10:00
Brett McBride 9c8ce2fa91
gitsplit contrib components (#804)
* gitsplit exporters
* gitsplit swoole context
2022-09-06 22:51:24 +10:00
Brett McBride ea83a0cff3
bump protobuf to 0.19, handle grpc partial success (#806)
bump protobuf to 0.19, handle partial success for otlp+grpc (otlp+http to follow)
2022-09-06 22:50:17 +10:00
Tobias Bachert 77838b3b9c
Fix `Future<T>` should be covariant (#808) 2022-08-28 21:49:45 +10:00
Kishan Sangani 0f308492a1
Added B3Propagator for B3 Single Header (#691)
* Added B3Propagator Class to handle two configurations and storing debug flag in the returned context
* Updated B3Propagator extract according to the clarification in the specs; updated test cases
2022-08-24 22:56:49 +10:00
Tobias Bachert 2457c76015
Prevent concurrent `::export()` calls in span processor (#788)
* Prevent concurrent `::export()` calls in batch span processor
* Prevent concurrent `::export()` calls in simple span processor
* Allow disabling auto-flush in batch processor `::onEnd()`
* Include in-flight batches in queue limit
* Handle exporter exceptions to prevent termination of worker
* Use `LogsMessagesTrait`
2022-08-24 22:52:04 +10:00
Brett McBride 74eda3d89d
adding runkit to developer docker image (#800)
runkit7 is used by AWS instrumentation over in -contrib
in passing, bump ast to latest stable version
2022-08-19 10:22:03 -04:00
Brett McBride cb002a80b1
adding getTracerProvider to Instrumentation (#797) 2022-08-13 10:48:35 +10:00
Sumit Kashyap d05ea65186
Restructure contrib directory (#793)
* Restructure contrib directory
2022-08-13 10:37:42 +10:00
Brett McBride 4dd375fdb8
removing psalm security analysis workflow (#799)
we already run psalm in the php workflow. this one doesn't add much, and is more flaky. we have decided that the serif uploading is not very important since we have good makefile-based ability for devs to run this all locally before pushing
2022-08-12 20:10:39 -04:00
Tobias Bachert 3ac64f6a28
Add metrics implementation (#750)
* Add metrics implementation

* Apply cs-fixer

* Downgrade to php 7.4

* [TODO] Suppress phan for now

* Add basic example

* [TODO] Remove outdated prometheus example for now

* Add otlp metric converter

* Add metric stream tests

* Downgrade to php 7.4 - fix asynchronous counter instrument type

* Add missing psalm-suppress annotations

* Add `ext-gmp` to composer suggest

* Fix `Sdk` -> `SDK`

* Remove `_bridge.php`

* Add array typehints

* Add `Interface` suffix to interfaces

* Add aggregation / attribute processor / staleness handler tests

* Apply rector

* Simplify filtered attribute processor

* Move instrument deduplication to meter

Allows removing view registry dependency from `MetricFactory`.
Should ideally turn of staleness handling for asynchronous instruments with permanently registered callbacks (drop all `::onStale()` callbacks and prevent addition of new callbacks).

* Allow injecting metric factory

* Release `::onStale()` callbacks if permanent observer callback registered

* Add `MultiObserver` tests

* Add php-doc for exporter temporality

* Resolve phan issues

* Add note about forward compatibility

* Add exemplar tests

* Remove special handling for callbacks being registered multiple times

Was mainly a side-effect of using `spl_object_id()`; lead to inconsistent behavior between providing same and identical callbacks; reverting back to incrementing index, keyspace is large enough.

* Add basic `Meter` / `MeterProvider` tests

* Add view `SelectionCriteria` tests

* Allow `MetricReader`s to configure default aggregation

- move default aggregation handling to metric reader / metric exporter
- move view registration to meter provider constructor
- move exemplar reservoir creation to aggregation to support user implementations
- remove `AttributeProcessor` from view as baggage access was dropped from spec
- deduplicate metric streams

* Add support for weakening `$this` reference of asynchronous callbacks

* Minor improvements

- add missing `Interface` suffix
- move callback destructors to metric observer to not detach if meter and meter provider are out of scope
- simplify `::viewRegistrationRequests()` by readding fallback view

* Add OTLP metric exporter

* Log export failure

* Minor improvements

- rename `MetricObserver::weakMap()` to `::destructors()` to better reflect usage`
- move `ReferenceCounter::acquire()` call to corresponding `MetricObserver::observe()` call for consistency
- cache instrumentation scope id in `Meter` to avoid repeated calls to `serialize()`
- remove obsolete instrument type check from `ViewProjection`, leftover from supporting aggregation per type

* Suppress `PhanAccessMethodInternal` due to being too strict for our usecase

* Add workaround for observer segfault if destruct is initiated by `WeakMap` key going out of scope

* Mark internal classes as internal

* Add in-memory and stream exporter

* Add metric converter test

* Add metric observer tests

* Add view registry tests

* Add metric reader tests

* Improve stream test coverage

* Improve meter test coverage

* Apply rector

* Add delayed staleness handler
2022-08-10 08:12:47 -04:00
Tobias Bachert d0a600fb68
Add support for concurrent exports (#790)
* Add support for concurrent exports

* Remove cancellation support from `::await()`
2022-08-10 08:11:47 -04:00
Brett McBride 0013e472a0
Documentation + shutdown handling in examples (#792)
* documentation tidy

* fixing links

* more doco

* more readme work

* adding span processor shutdown handling to examples

* reorg

* bump heading level

* wordsmithing readme

* simplify fqn

* call tracer provider directly in examples
2022-08-10 08:06:44 -04:00
Tobias Bachert c62d443c74
Fix incorrect autoload path (#791) 2022-08-06 20:28:36 +10:00
Tobias Bachert e946dc7b9d
Add cancellation support for async implementations (#782) 2022-08-03 08:43:23 +10:00
Tobias Bachert 2f6658f101
Remove `null` default value from parameters that are never `null` (#779)
* Make `SpanProcessor::onStart()` `$parentContext` non-nullable
* Make `Sampler::shouldSample()` `$attributes` non-nullable
* Don't reset `SpanBuilder::$links` on `::startSpan()`
Not needed / resetting is inconsistent with other span builder values.
2022-08-01 12:25:57 +10:00
Amber 73f5106fd3
removing isEmpty 2022-08-01 12:15:09 +10:00
Amber bf912ed7bd
Use of "iterable" Type May Need Re-Evaluation Across the Repo (#783)
* Otel-php:632 Move stack trace formatting out of Span class

* added function usages

* fix linting errors

* Added documentation for adding Span Attributes

* removing TracingUtl class

* Refactor TraceState's __toString method

* Added path with @covers to remove warnings

* Added @coversDefaultClass annotation

* fix to check if iterable is empty

* fixed for faling test case
2022-07-20 08:13:02 -04:00
Timo Michna 32c43840f7
Add basic coding guidelines section in DEVELOPMENT (#781)
* Move 'examples' section back to main README

* Add 'coding guidelines' section to DEVELOPMENT
2022-07-19 15:08:54 -04:00
Brett McBride 08c9180b6d
store root dispatcher in a static var (#780)
* store root dispatcher in a static var
This seems to be the safest way to store the main dispatcher. Using context to store the main event dispatcher causes a scope to be created: activating the newly-created context which stores dispatcher causes a new scope, and that can break things.
I also looked at storing dispatcher in the root context, but that can't work because contexts are immutable.

* remove useless test

* linting
2022-07-19 06:07:51 +02:00
Timo Michna 5a64c0d000
Add DsnParser + Otlp/HttpEndpointResolver and remove dependency on nyholm/dsn (#767)
* Add FactoryDecoratorTrait

* Add RequestFactoryDecoratorTrait

* Add RequestFactoryDecorator

* Add ServerRequestFactoryDecorator

* Add ResponseFactoryDecorator

* Add MessageFactory

* Finalize

* Make Phan happy

* Make Psalm happy

* Make Phpstan happy

* Remove decorators for now

* Add Newrelic\Factory

* Fix CS

* Add signal lookup

* Add Dsn

* Add Dsn Factory

* Add Dsn Parser

* Use Dsn Parser

* Add OTLP HttpEndpointResolver

* Use OTLP HttpEndpointResolver

* Remove nyholm/dsn dependency

* Fix CS

* Remove nyholm/dsn from phan config

* Fix scheme and protocol naming

* Add Dsn Parser

* Revert "Add Dsn Parser"

This reverts commit 2b3f16773a3e69325f208227c0ac13dc1298768e.

* Fix Exporter

* Remove accidentally added GenericExporterFactory

* Make Psalm happy

* Add test for correct constant references

* Fix constants

* Make Phan happy
2022-07-18 08:18:35 +02:00
Brett McBride 7f2e974972
Adding event dispatcher (#763)
* extract events from previous branch

* merging dispatcher and listener

* tests

* use CloudEvents

* remove event-dispatcher

* tidy

* deptrac

* removing singleton in favour of storing in context

* adding cloudevents to api's composer.json

* review feedback
- add dispatcher interface
- remove singleton
- move some logic into methods
- make generator-returning method private

* more review feedback and tidying
2022-07-18 07:07:19 +02:00
Brett McBride ea5b7c153e
return no-op span builder after shutdown (#765)
* return no-op span builder after shutdown
this completes a todo in code comments: when tracer shared state has shutdown, getting a span builder should return a no-op implementation

* adding unit test for post-shared-state-shutdown
2022-07-17 15:27:20 +02:00
Timo Michna d3facad7b5
Add Span InMemoryExporter (#775)
* Add InMemoryExporter
2022-07-17 20:46:05 +10:00
Timo Michna 90036b1c7e
Add symfony/polyfill-php80 + symfony/polyfill-php81 + symfony/polyfill-php82 (#768) 2022-07-17 20:43:43 +10:00
Tobias Bachert ae6b620489
Remove automatic `::shutdown()`, add `ShutdownHandler::register()` (#760)
* Remove automatic shutdown handling, add `ShutdownHandler::register()`

* Clear `WeakMap` values on destruct
2022-07-16 10:56:52 +02:00
Brett McBride 37a8c8efa1
logging more errors (#764) 2022-07-13 10:16:18 -04:00
Amber 82b0135695
Invalid @covers annotations in SpanTest create warning in PHPunit runs (#752)
* Added path with @covers to remove warnings
* Added @coversDefaultClass annotation
2022-07-13 21:47:09 +10:00
Brett McBride f33b623683
adding help to makefile (#762)
* adding help to makefile
this makes the makefile a little easier to grok: now 'make' or 'make help' will list make targets and a brief description of what they do

* document make help
2022-07-12 07:14:01 -04:00
Calin Bolea 24ada8c270
Remove deprecated ResourceConstants (#761) 2022-07-11 15:21:31 -04:00
Brett McBride 6a14cf9e28
Tracer references tests (#759)
* adding tests for tracer provider behaviour
a recent bug highlighted that if there is no reference to a tracer provider, then the shared state will shutdown, even if that shared state is being used by active tracers. Adding a phpdoc comment explaining this behavior, and some tests to demonstrate it

* moving tests into integration

* removing accidental covers annotation
2022-07-11 07:38:49 -04:00
Tobias Bachert 305c1c7a12
Add SDK `TracerProviderInterface` to expose `::shutdown()` and `::forceFlush()` (#756) 2022-07-08 16:09:28 -04:00
Tobias Bachert 8e30ea0762
Fix examples/traces/demo (#755) 2022-07-08 10:41:43 -04:00
Bob Strecansky 19e09f53ca
Note about code coverage (#753) 2022-07-07 12:34:40 -04:00
Grunet aaa93eed7a
Cleaning up the examples a little (#741)
* Rename examples to snake case

* Move examples into signal specific folders

* Moving the exporter-specific examples into their own directory

* Update import paths for autoload.php

* Move the rest into a dedicated features folder

* Renaming the distributed-tracing folder to be slightly more self-explanatory

* Move exporters folder underneath features folder

* Woops forgot to update the Makefile too

* clarify the catch is not for otel-php but app code people might fill in the example with

* Removing sampling from examples that don't need to involve it

* Simplify names of the exporter example files

* Point back to the right vendor folder for the tracing demo

* Try get the demo a little closer back to actually working

* Add in a make target for smoke testing more of the examples

* clarify how to speed up one of the slow smoke tests
2022-07-03 11:58:47 +02:00
Timo Michna b973c52162
Refactor Context (#746) 2022-07-02 14:52:47 -04:00
Timo Michna 5f318cdb7a
Add HTTP Dependency Resolvers (#744)
* Add FactoryDecoratorTrait

* Add RequestFactoryDecoratorTrait

* Add RequestFactoryDecorator

* Add ServerRequestFactoryDecorator

* Add ResponseFactoryDecorator

* Add MessageFactory

* Add FactoryResolverInterface

* Add PsrClientResolverInterface

* Add HttpPlugClientResolverInterface

* add DependencyResolverInterface

* Add HttpDiscovery\MessageFactoryResolver

* Add HttpDiscovery\PsrClientResolver

* Add HttpDiscovery\HttpPlugClientResolver

* Add HttpDiscovery\DependencyResolver

* Finalize

* Make Phan happy

* Make Psalm happy

* Make Phpstan happy

* Fix dependency

* Remove decorators for now
2022-07-02 14:49:41 -04:00
Timo Michna 47ee3e9e80
Apply rector Code Quality rules (#743)
* Add rector Code Quality rule

* Apply rector Code Quality rule
2022-07-02 12:48:10 -04:00
Timo Michna e3564e2fe9
Add link to development doc in to main README (#745) 2022-07-02 12:45:32 -04:00
Tobias Bachert 4c10268162
Group otlp spans by resource (#740)
* Group spans by resource

* Use proto methods instead of array constructor

* Use consistent naming for methods

* Suppress `InvalidArgument` false positives

Caused by `RepeatedField` being not generic.
2022-07-01 12:45:26 -04:00
Timo Michna 7c0c71ccab
Add Rector and PHP 7.4 rules (#739)
* Add rector as dev dependency

* Add rector config

* Add rector make targets

* Add intl extension to dev image to support rector

* Add rector make targets

* Apply rector PHP_74 rules

* Fix CS

* Make Phan happy
2022-06-30 14:59:09 -04:00
Tobias Bachert 739f212ba9
Add instrumentation scope attributes (#735)
* Add attributes to instrumentation scope

* Remove `::getDefaultTracer()`

Instrumentation should use dedicated tracers.

* Remove SDK `::getTracer()` default name

Instrumentation should use API `TracerProvider` which requires providing a name.
2022-06-30 12:30:14 +02:00
Timo Michna 409dd52c40
Set indent size for all yaml files to 2 (#737) 2022-06-29 20:51:21 -04:00
Bob Strecansky 79ff159c94
Correct error in DEVELOPMENT.md/README.md (#736) 2022-06-29 18:52:31 -04:00
Kishan Sangani 13ce2da243
Updated Laravel and Symfony quickstarts (#696)
* Updated laravel-quickstart.md

* Updated symfony-quickstart.md

* Replaced setStatus with recordException in the child span

* Removed TODO comment

* Changes from PR 701 by DrLuke
2022-06-29 15:41:08 +02:00
Amber 06d74a737e
Refactor TraceState's __toString method #727 Span Attributes Documentation#704 (#729)
* Otel-php:632 Move stack trace formatting out of Span class

* added function usages

* fix linting errors

* Added documentation for adding Span Attributes

* removing TracingUtl class

* Refactor TraceState's __toString method
2022-06-29 09:07:31 -04:00
ashmeet-chhabra b2a7b62b2a
Move development information from the main README into a dedicated DEVELOPMENT.md (#734)
* removed Development section

* Create DEVELOPMENT.md

* linked DEVELOPMENT.md to README.md
2022-06-29 08:05:30 -04:00
Yukti 5c3109ae4d
Transition W3C Trace Context Test Service to Vanilla PHP (#695)
* test: Transition W3C trace-context test to vanilla PHP

* chore: Rename trace context test script

* chore: Improve symfony-cli setup

* chore: Cleanup

* fix: Add executable perm to trace ctx test setup
2022-06-24 06:25:52 -04:00
Timo Michna 0e4ad525c4
Add basic InstrumentationInterface and InstrumentationTrait (#726)
* Add instrumentation draft

* Add NoopMeter

* Add NullPropagator

* Rework InstrumentationTrait

* Fix CS

* Fix PsrLog dependency

* Make Phan happy

* Fix CS
2022-06-24 10:54:02 +02:00
Tobias Bachert 41f74d2aff
Make `AttributesInterface` immutable (#724)
* Cleanup `AttributesInterface`
- remove not required methods
- rename `::hasAttribute()` to `::has()` for consistency with `::get()`
* Remove public usage of `new Attributes()`
* Split `Attributes` into immutable attributes and mutable builder
* Remove `AttributesLimits`
* Remove `::incrementDroppedAttributesCount()` for now
Mainly useful for metrics sdk that has to rebuild filtered attributes.
* Remove obsolete cloning of attributes
* Update covers annotation
* Revert optional changes that might be controversial
2022-06-23 20:54:03 +10:00
Timo Michna 025b239adc
Update Semantic Conventions to version 1.12.0 (#725)
* Update Semantic Convention Generator script

* Update Semantic Conventions to version 1.12.0
2022-06-23 20:49:49 +10:00
dependabot[bot] 8f7f399f12
Bump guzzlehttp/guzzle in /examples/distributed-tracing/src (#722)
Bumps [guzzlehttp/guzzle](https://github.com/guzzle/guzzle) from 7.4.4 to 7.4.5.
- [Release notes](https://github.com/guzzle/guzzle/releases)
- [Changelog](https://github.com/guzzle/guzzle/blob/master/CHANGELOG.md)
- [Commits](https://github.com/guzzle/guzzle/compare/7.4.4...7.4.5)

---
updated-dependencies:
- dependency-name: guzzlehttp/guzzle
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-22 20:32:58 +10:00
Tobias Bachert 122aff0c74
Prevent leaking `TracerProvider` references in `register_shutdown_function` (#716) 2022-06-21 10:32:31 +10:00
Timo Michna ac95256062
Add package information to README (#719) 2022-06-21 09:41:02 +10:00
Timo Michna 6b80fd1340
Upgrade deptrac (#717) 2022-06-20 16:05:26 +02:00
Timo Michna 31bdeaa8f1
Add package validate call to CI (#714)
* Add package validate call

* Fix WF

* Touch composer.json to burst cache

* Fix job name

* Add PHP version to Psalm call

* Make package job depend on php job

* Fix base TestCase

* Add install directory

* Touch composer.json to burst cache

* Add install directory

* Fix install directory

* Temporarily remove job dependency

* Touch composer.json to bust cache

* Touch composer.json to bust cache

* Touch composer.json to bust cache

* Touch composer.json to bust cache

* Fix extensions

* Make package job depend on QA job

* Use PHP QA in CI badge
2022-06-17 19:15:59 -04:00
Tobias Bachert a22f9f1077
Cleanup/fix context package (#711)
* Remove `Context::withValue()`

Creates a hidden `Scope` when called without `$parent`.

* Remove `Context::detach(Scope)`

* Remove static `Context::attach()`

* Add missing typehints

* Use loop instead of recursion

* Fix `MultiTextMapPropagator::extract()` clearing context

* Fix `TextMapPropagator::composite()` for named arguments

* Make `Context` constructor non-public

* Make `Context` and `ContextKey` final

* Fix `ArrayAccessGetterSetter`

Resolves inconsistencies in case-insensitive handling.

* Fix psalm

* Fix cannot mock final class `Context`

Revert after introducing ContextInterface?

* Apply feedback and remove obsolete parentheses

* Use psalm-suppress instead of assert
2022-06-16 08:17:59 -04:00
Tobias Bachert 345f8bf35b
Return null instead of provided attributes (#713)
"A set of span Attributes that will also be added to the Span"
2022-06-16 08:17:29 -04:00
Tobias Bachert 3c6c53bf2f
Fix overriding attribute increases total count (#710) 2022-06-16 19:57:50 +10:00
Yukti 90edbd3a58
Fix W3C test service (#686)
Attempts to fix the W3C test service by updating usage patterns to
match the refactorings and functional changes that have been applied
since it was last updated.
2022-06-15 22:25:18 +10:00
dependabot[bot] f3e9bdbe7c
Bump guzzlehttp/guzzle in /examples/distributed-tracing/src (#707)
Bumps [guzzlehttp/guzzle](https://github.com/guzzle/guzzle) from 7.4.3 to 7.4.4.
- [Release notes](https://github.com/guzzle/guzzle/releases)
- [Changelog](https://github.com/guzzle/guzzle/blob/master/CHANGELOG.md)
- [Commits](https://github.com/guzzle/guzzle/compare/7.4.3...7.4.4)

---
updated-dependencies:
- dependency-name: guzzlehttp/guzzle
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-10 08:12:05 -04:00
Brett McBride 3fb033d86b
fixing BC alias for InstrumentationLibrary (#706)
* fixing BC alias for InstrumentationLibrary
2022-06-10 10:30:52 +10:00
Tobias Bachert 3ca87a8878
Prevent creation of invalid trace id / span id (#699) 2022-06-06 15:58:30 +10:00
Tobias Bachert 7dda601851
Improve StackTraceFormatter (#697)
* Refactor stacktrace formatter

- fixes "... n more" to fold only identical frames
- fixes exception class names not being converted to dotted format
- fixes functions being shown as `main`
- fixes out-of-memory on circular exception

* Rename stacktrace formatter
2022-06-06 15:57:56 +10:00
Alan West 60f7045c1f
Fix spelling of OpenTelemetry in readme (#698) 2022-06-03 21:42:36 +02:00
Amber e728c53065
#632 : Move stack trace formatting out of Span class (#694)
* Otel-php:632 Move stack trace formatting out of Span class

* added function usages

* fix linting errors
2022-06-03 15:13:56 +02:00
Yukti 88db9039fa
Update framework integration docs (#689)
* Update framework integration docs

* Apply suggestions from review

- Avoid multiple constructor calls.
- Grammar regression.
- Fix type `s/jaegar/jaeger`.

* Update exporters + sampling to the new API (per review)

* Fix setup instructions and improve consistency and style

* Update span status handling and current span fetch

* Introduce warnings and demote to "Exploration guides"

* chore: rename framework "guides"
2022-06-01 21:53:21 -04:00
Brett McBride 2070be6116
adding scope detach to examples (#693)
it's important to detach scope for any activated span (especially in async runtimes), so ensure
that the examples show it being done where possible.
In passing, fix some broken examples.
2022-06-01 21:52:46 -04:00
Timo Michna a8a6025382
Remove invalid dependency in contrib composer config (#692) 2022-05-30 08:30:03 -04:00
Timo Michna e3736450d4
Add validation for package composer files (#687)
* Add validation for package composer files

* Fix CI step order

* Exclude duplicate Composer Installed Version class

* Add packages-composer make target to 'all'

* Use PHP version in composer cache
2022-05-28 06:54:58 -04:00
Timo Michna f3aedcdb60
Fix composer package replacements (#684) 2022-05-28 06:53:10 -04:00
dependabot[bot] 40775bc61f
Bump guzzlehttp/guzzle in /examples/distributed-tracing/src (#685)
Bumps [guzzlehttp/guzzle](https://github.com/guzzle/guzzle) from 7.4.0 to 7.4.3.
- [Release notes](https://github.com/guzzle/guzzle/releases)
- [Changelog](https://github.com/guzzle/guzzle/blob/master/CHANGELOG.md)
- [Commits](https://github.com/guzzle/guzzle/compare/7.4.0...7.4.3)

---
updated-dependencies:
- dependency-name: guzzlehttp/guzzle
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-05-25 18:15:39 -04:00
Kishan Sangani 499c58adab
Added B3MultiPropagater (#680)
* Added B3MultiPropagater

* Added static self and removed case insensitive getter function

* Added unit tests for B3MultiPropagator class

* Refactored B3MultiPropagator and added tests in B3MultiPropagatorTest

* Added description for B3MultiPropagator
2022-05-25 11:49:12 -04:00
Timo Michna 17264f7caa
Add initial setup for splitting composer packages (#682)
* Fix package name

* Add composer config for jaeger thrift

* Fix autoload path

* Add dependency on generated packages

* Add gitsplit config

* Add gitsplit action

* Add make target for gitsplit
2022-05-24 18:58:51 +02:00
Tobias Bachert 1326f17eb6
Support async php runtimes (#675)
* Remove implicit root scope

* Provide access to active scope and context of scope

* Add local storage to scope

* Trigger fiber error only when crossing fiber boundaries

* Split ContextStorage into two interfaces

* Add swoole context storage

Implementation currently incompatible with fibers.

* Fix cs

* Make default context storage execution context aware

* Add scope bound callable and promise for async user implementations

* Resolve/suppress phan/psalm/phpstan issues

* Improve ContextStorage test coverage

Adds tests for newly added features and fixes covers annotations.

* Apply feedback

- move Swoole context storage to Contrib/Context/Swoole
- use self instead of classname
2022-05-24 09:17:01 -04:00
Brett McBride 8b63849da4
fixing psr4 warnings in BC layer (#681) 2022-05-24 08:32:47 -04:00
Erdem Köse 2e4c849b2f
Allow custom counters implementing CounterInterface to be exported (#676)
Signed-off-by: Erdem Köse <erdemkose@gmail.com>
2022-05-17 22:10:08 -04:00
Yukti 85282b5af4
Add the base docker image to w3c context validation tests (#673)
Use the base docker image in the docker-compose file of the W3C context
validation tests to speed up the test set up
2022-05-07 09:03:42 +10:00
Yukti 25cfcfb6e9
Add phpunit annotations for compliance tests (#670)
* Add phpunit annotations
2022-05-07 09:02:29 +10:00
Yukti 8ae46f20e1
Add compliance test and annotate existing ones (#669)
* Add compliance test and annotate existing ones
2022-05-06 22:46:47 +10:00
Brett McBride 4592a27cdf
fixing w3c-tracecontext test startup (#668)
* fixing w3c-tracecontext test startup
make w3c-trace-context was suffering from some bitrot, so this change gets it building and
running again. The tests themselves still fail due to further code-related bitrot.

* silence new phpstan error
2022-04-30 21:26:24 -04:00
Brett McBride 4e3264578b
Fixing protobuf generation and InstrumentationScope (#665)
* updating proto generation
switching over to using opentelemetry-proto's own mechanism for generating protobuf interfaces, and
updating interfaces to latest version

* downgrade protobuf interfaces to 0.14.0
this is the latest version that seems to work with out grpc exporter, further
investigation required for 0.15.0+

* tidy up script

* renaming InstrumentationLibrary to InstrumentationScope and bumping protobuf
InstrumentationLibrary is now deprecated in favour of InstrumentationScope. Making this change
resolves issues with grpc+protobuf exports being ignored by the otel collector, so we now
can update the proto interfaces to latest.

* rename collector docker-compose file
2022-04-27 08:09:42 -04:00
Christian Daguerre 9138d78b8f
Allow decoration of zipkin span converter (#608) 2022-04-21 11:36:21 +10:00
Kishan Sangani 5de0986f86
Refactored ResourceInfo and ResourceInfoFactory Unit and Integration tests (#664) 2022-04-20 13:47:52 -04:00
Yukti 1d5283b9e4
Add integration tests for tracing compliance (#662)
* Add integration tests for span builder

* Space fixed

* Add more descriptive names and @group annotation

Modified the names of the tests to be more descriptive and added the
`@group compliance` notation.
Additionally, I commented out one of the tests that I was not totally
sure of. (unsure if `setAttribute()` should work with empty string `''`
values.

* Fixed test name

* Check for specific attributes and not just count

Removed `$span->end()` calls as they shouldn't be necessary

* Remove redundant `end()` calls

* Add test for getting default tracer

Test to get default tracer. Also, added `@group` php unit annotation for
tests to check specification compliance

* Fixed warning

* Fixed style warning
2022-04-17 13:15:34 +02:00
Tushar 6d993586b0
Move InstrumentationLibrary key generation logic out of TracerProvider/SpanConverter [#619] (#663)
* Extract InstrumentationLibrary key generation logic

Factors key generation logic for InstrumentationLibrary instances
out to a helper method in a utils class.

* Remove @see PHP annotation

Phan doesn't like it, couldn't see an acceptable workaround.

* Change key generator namespace and class

Changes the key generator's namespace to Util\Instrumentation and classname to
KeyGenerator, refactoring usages.

* Add unit tests for Instrumentation key generator

* Add test case for non-null version and null schema

Also renames the other 2 tests for descriptiveness.
2022-04-15 14:16:12 +02:00
Yukti 7ce599bab1
Fixed formatting (#661) 2022-04-14 22:01:13 +10:00
Yukti c242c37db0
Readme tidy (#654)
* Fix typos and some redundancy

Fixed a few typos and removed mentions of "from your bash compatible
shell" (we use make so these commands are compatible with all clis)
2022-04-14 19:10:05 +10:00
Timo Michna 99fba0d720
Make Error level of BC messages configurable and add info to README. (#657)
* Make BC error level configurable

* Add information about BC errors to README

* Make CS happy

* Silence Psalm

* Add missing test

* Remove unused data annotation
2022-04-05 21:53:49 +02:00
Brett McBride 57076b50d5
bump protobuf extension to 3.20.0 (#656)
this should make the build green for 8.1, finally. We can now consider 8.1 supported,
and so it moves out of experimental - future 8.1 breaks will fail the pipeline.
2022-04-04 13:20:23 -04:00
Brett McBride e096e529bb
Revert "replace E_USER_NOTICE with E_USER_DEPRECATED (#647)" (#655)
This reverts commit 72816bb324.
2022-04-03 21:22:16 +10:00
Ivo Bathke 72816bb324
replace E_USER_NOTICE with E_USER_DEPRECATED (#647)
* replace E_USER_NOTICE with E_USER_DEPRECATED since it is a notice about a deprecation

* fixed tests
2022-04-02 11:30:23 -04:00
Brett McBride 80a6d63f51
static logging methods (#651)
allow logging methods in LogsMessagesTrait to be called from within either a static or non-static method.
in passing, adding a missing coversNothing annotation on a complaining integration test
2022-04-02 09:55:45 -04:00
Timo Michna 5f71d3cfe3
Add example of how to create a new trace in same process (#650) 2022-04-02 16:56:56 +11:00
lalex 445e932ee0
Extract a Resource schemaUrl merging method (#627) 2022-04-02 07:01:52 +02:00
Yukti f2ad2fcb5b
Add compliance tests for environment variables (#648)
* Add compliance tests for environment variables

* Add tests to verify compliance

* Add Makefile task for testing compliance
2022-04-02 05:41:31 +02:00
Brett McBride 0bc3731ca6
removing brick/math from phan config (#646)
was not removed in #642 along with the rest of the library
2022-03-31 08:50:30 -04:00
Yukti 169bdbee57
Add @group annotation to compliance tests for environment variables (#611)
* Add @group annotation to compliance tests

Marked tests for environment variables with phpunit @group annotations to identify
compliance tests. This enables for a way to run just those specific
test and will serve as a useful form of documentation.

* Add trace signal specific notation
2022-03-31 08:49:33 -04:00
Grunet ca05f51481
Add test based on the Jaeger spec (#645)
* Add test based on the spec
* Fix the other tests which appear flaky
* Clarify the randomness in these tests
* Add concrete example from Go for the trace id splitting
* Fix style
2022-03-31 20:46:40 +11:00
Brett McBride 178cc9e292
adding new contributor welcome message (#644)
welcome-bot has been installed in our repo, this is config to make it do something on a first PR
2022-03-30 15:03:46 -04:00
Bob Strecansky 8f0b522bd3
Updating .github workflow for psalm-security-analysis based on output from action run (#643) 2022-03-30 14:04:07 -04:00
dependabot[bot] 8b488b384d
Bump guzzlehttp/psr7 in /examples/distributed-tracing/src (#640)
Bumps [guzzlehttp/psr7](https://github.com/guzzle/psr7) from 2.1.0 to 2.2.1.
- [Release notes](https://github.com/guzzle/psr7/releases)
- [Changelog](https://github.com/guzzle/psr7/blob/master/CHANGELOG.md)
- [Commits](https://github.com/guzzle/psr7/compare/2.1.0...2.2.1)

---
updated-dependencies:
- dependency-name: guzzlehttp/psr7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-03-31 04:30:25 +11:00
Sakti Behera aadcb1218d
[#641] Fixed issue related to traceId & spanId mismatch between otel lib and jager collector (#642) 2022-03-30 12:16:54 -04:00
Brett McBride e62cd5e831
honour grpc exporter provided endpoint url (#639)
a bug when fetching settings from environment was causing the grpc exporter to always use our default
value, rather than the one provided to the exporter's constructor
2022-03-29 10:37:53 +02:00
Grunet 54066eb3eb
Fix span and trace ids to be the correct unsigned ints they need to be when converted for Thrift (#635)
* Factor a class out for handling the id conversion

* Remove remaining direct intval references

* Further isolating the soon-to-be-replaced use of intval

* Use brick\math to fix the issue and update the existing tests

* Adding brick\math to composer.json because I missed it in the previous commit?

* Adding some edge case unit tests around the id conversion

* Move explanatory comments into the data provider itself

* Add new package to phan config

* Fix style

* Try clarify comment

* Extract constant

* Remove comments

* Try quick manual merge to fix merge conflicts
2022-03-28 21:35:31 -04:00
Grunet 39c99e5a2f
Map OTEL Resources to Jaeger Process Tags (#636)
* Commit in progress work because Gitpod is weird

* Finish initial stab at the changes

* Forgot to update the exporter

* Add in proper handling of serialization of ResourceInfo

* ksort doesn't return the array...

* Only PHP 8.1 supports key-ed array destructuring

* Creating some adapters to break the hard dependency on Batch to make testing easier

* Refactoring to break the hard dependency on Batch

* Add initial unit tests around the new logic in HttpSender

* Some refactoring of the test's helpers

* Another small refactor

* Some more refactoring

* Rename ResourceInfo's test file to match it's file name

* Move a test our of REsourceInfoTest into a more appropriate file

* Add some basic conformance tests around the new ResourceInfo::serialize method

* Add a test to try and catch future properties that aren't added to ResourceInfo::serialize

* CLean up comments

* Replace string with constant

* Improve variable names

* Cleaning up comment

* Split out tag creation into a helper class

* Phan didn't like the type docs

* Fix style

* Fix tests after merge from main

* Fix coverage reporting issues on 2 of the new files

* Fix style

* Rename vals to values

* Shortening the batch adapter factory method name to create

* Inline a method call

* Inline some method calls

* Shorten factory method to just "create"

* Inline some code

* Split assertions into 3 tests

* Rename parameter in interface implementation for psalm + update the rest of the file to match

Co-authored-by: Timo Michna <timomichna@yahoo.de>
2022-03-28 03:18:32 +02:00
Timo Michna a2f64053da
Add Backward Compatibility layer (#637)
* Add Attributes BC layer

* Add AttributeLimits BC layer

* Add InstrumentationLibrary BC layer

* Add GlobalLoggerHolder BC layer

* Add triggerMethodDeprecationNotice

* Move Clock BC layer

* Add ResourceInfo BC notices

* Add missing return statement

* Add BC class directory to coverage ignore

* Fix code coverage annotations
2022-03-28 03:11:01 +02:00
Timo Michna 8e1e912c92
Move and refactor clock components (#633)
* Move Clock classes to SDK\Common\Time namespace

* Move conversion methods to Util class

* Implement StopWatch

* Implement ClockFactory

* Fix StopwatchInterface

* Finalize ClockFactory

* Implement StopWatchFactory

* Deprecate AbstractClock

* Add BC alias

* Add initial start time to StopWatch

* Unify and optimize SystemClock methods

* Use ClockFactory in Span

* Use ClockFactory in BatchSpanProcessor

* Use ClockInterface in BatchSpanProcessorTest

* Use ClockFactory in SpanData

* Use ClockFactory in examples

* Add millisToNanos Util method

* Use StopWatch in BatchSpanProcessor

* Make Phan happy

* Make Psalm happy

* Make PHPUnit happy

* Remove sllh/composer-versions-check from allowed composer plugins

* Use correct assertion

* Use correct assertion

* Assert difference
2022-03-25 23:26:39 +01:00
Kishan Sangani 2b72c92fcb
Created ResouceInfoFactory class (#628) 2022-03-24 13:54:42 +11:00
Kishan Sangani 3856d4df06
Resource Detector Unit Tests (#626)
* Added Resource Detector Unit Tests

* Modified test

* Resolved review messages
2022-03-21 18:59:04 +01:00
Timo Michna f96756ba10
Refactor and move InstrumentationLibrary (#624)
* Refactor and move InstrumentationLibrary
2022-03-20 21:36:18 +11:00
Timo Michna 6e7a650c4b
Fix Exception Message (#620) 2022-03-19 23:52:08 -04:00
Timo Michna 940f67f1c7
Refactor Attributes (#623)
* Move Attribute classes to Common namespace

* refactor AttributesTest

* Move Attribute classes to Common namespace in examples

* Introduce AttributeLimitsInterface

* Fix bug in total added values calculation

* Move compare test to correct test-class

* Apply CS

* Refactor Attributes

* Fix attributes in Benchmark

* Move AttributeLimits defaults to interface
2022-03-19 23:51:47 -04:00
Timo Michna 1d6d717e0d
Refactor LoggerHolder (#617) 2022-03-19 12:52:06 -04:00
Timo Michna 33958e03a4
Update dependency checks (#616) 2022-03-19 11:03:38 -04:00
Timo Michna fd0c270c08
Fix env var resolution (#615) 2022-03-19 11:02:57 -04:00
Timo Michna 3c5f9fc5ae
Support Env Var injection (#614) 2022-03-18 08:22:33 -04:00
Kishan Sangani 7b26ce1260
Updated Members and Contributors (#612)
* Updated Members and Contributors

* Updated header size for contributors
2022-03-16 14:42:54 -04:00
lalex 3445917252
Add support for schemaUrl in TracerProvider and OTLP SpanConverter (#607)
* Add support for schemaUrl in TracerProvider and OTLP SpanConverter
2022-03-16 10:18:40 +11:00
Brett McBride 78e43b0918
ignoring some new phpstan failures (#604)
phpstan has just started to fail on a couple of test assertions based on their phpdoc return type:
Call to method PHPUnit\Framework\Assert::assertNotSame() with mixed and mixed will always evaluate to false
This doesn't consider that assert<Not>Same will also check for whether two objects are the same instance, so
ignore the error.
2022-03-08 09:03:27 +11:00
Kumar Pratyush 0732418071
Refactoring to use known values (#601) 2022-03-07 12:10:12 +11:00
Bob Strecansky b9920a5d32
Updating CONTRIBUTING.md (#602) 2022-03-02 23:12:13 +01:00
Kishan Sangani 5dd8f967cf
Added OTEL_PHP_DETECTORS environment variable (#600)
* Added OTEL_PHP_DETECTORS environment variable to configure detectors from environment

* Added unit tests for defaultResource

* Review comment: Added exapmle

* Refactoring to keep the syntax same across examples

* Review comment: Using static method instead creating instance and using constants
2022-03-02 16:23:09 +01:00
Kishan Sangani be15243441
Refactored Environment.php to use EnvironmentVariablesTrait::hasEnvironmentVariable function (#598) 2022-03-01 12:45:53 +01:00
Grunet 6a50c55f48
Scaffold Jaeger Thrift Http Exporter (#576)
* Scaffold the new exporter and helper class

* Make the SpanConverter compliant to the interface the others are

* Removing check already covered by SpanExporterTrait

* Adding in scaffolding for a happy path test through the new code

* Fix bugs when path is present or endpoint scheme is https

* Remove type doc to fix psalm errors

* Comment out doc type to fix phan issue

* Fix style

* Add missing type in constructor

* Shorten ternary

* Inline function calls in doExport

* Inline function calls in doExport

* Revert ternary condensation commit from earlier

* Not requiring a port be set in the endpoint URL and inferring it from the scheme when it's missing

* Try adjusting thttpclient with a subclass instead of adapter (#2)

* Setup the exporter for injecting a psr-18 client

* Switch to using a subclass of THttpCLient

* Getting the psr-18 client into the subclass

* Copy verbatim from THttpCLient the method that needs working

* Getting the request and stream factories in there too

* Migrating the headers over to use the psr18 and psr7 things

* Migrating over the body

* Commenting out some more things Otel doesn't need

* Commenting out the rest as it seems accounted for

* Removing the last of the old implementation

* Fix to undefined variable from previous commit

* Actually otel isn't using any custom headers so we don't need to handle those either

* Remove all the commented out code

* Updating fromConnectionString to use the discovery helpers to find and inject the PSR-18 and PSR-7 classes HttpCollectorExporter needs

* Reworking happy path test to use mocks of the PSR-18/PSR-7 interfaces

* Turning TODO in to comment

* Adjust line breaks

* Fix style

* Fix potential array key access error Phan noticed

* Ignore psalm false positives in the test file

* Workaround odd psalm bug/behavior of surfacing errors in THttpClient after it's been subclassed

* Switch to correct shortening of ternaries this time

* Minimal changes needed to drop dependence on THttpClient

* Moving some of the setters into the constructor now that the THttpClient superclass is gone

* Cleaning up endpointURL duplication and removing host_ member that's not really needed anymore

* Naming the copied over buf_ member a little more explicitly

* Naming the main test object in the span converter test class more clearly

* Renaming 2 of the files/classes to be more clear

* Remove inaccurate copy pasta leftover from THttpClient

* Fix style

* Factor out a helper object for parsing the endpoints to help satisfy Phan

* Have codecov pick up on the hlper class for code coverage

* Refactor the UDP exporter to also use the new ParsedEndpointUrl helper class

* Fix style

* Psalm makes a good point that the defaults for host/port in the UDP exporter can never be hit since the entry point requires them to be present in the endpoint URL
2022-02-28 12:42:31 +01:00
Yukti ccc3f8db96
Add support for OTLP signal specific environment overrides [#590] (#595)
* Add support for OTLP signal specific environment overrides

Modified the OTLP gPRC and HTTP trace exporters to allow for
configuration options overrides by signal specific options to comply
with OpenTelemetry specs.

* Revert overrides for the INSECURE variable

* Add check method to EnvironmentVariableTrait

For better code readabilty, added a hasEnvironmentVariable() to
EnvironmentVariableTrait.

* Add check for empty certificate file

* Fix style and add check for endpoint variable
2022-02-28 12:38:34 +01:00
Timo Michna b7093b57c1
Adjust stale-bot config (#596)
* Adjust stale-bot config
2022-02-28 06:58:13 +11:00
Kishan Sangani 8a362215fd
Refactored SpanProcessorFactory and updated corresponding unit tests (#594) 2022-02-24 09:43:53 +11:00
Kishan Sangani e50a827704
Exporting ResourceInfo in SpanConverter (#591)
* Exported ResourceInfo attributes in SpanConverter

* Updated Unit tests
2022-02-23 18:17:50 +01:00
Kishan Sangani 08d3fe8d0d
Refactored Environment.php to use Environment constants and accessor (#592) 2022-02-23 10:31:54 -05:00
Patrice Chalin 061adadafd
Delete website_docs (#585) 2022-02-17 18:46:54 -05:00
Bob Strecansky a02868f26d
Stale bot setup (#583) 2022-02-16 20:03:37 +01:00
Timo Michna 3a7f7f71bb
Update SemConv (#581) 2022-02-16 08:32:22 +01:00
Yukti e0f012fb1f
Update insecure environment variables as per spec (#580)
Renamed the 'insecure' environment variables to match the naming of all
other OTLP environment variables.
2022-02-15 16:08:49 +01:00
Patrice Chalin 15785689ab
[website_docs] Fix page meta links and rename file (#578) 2022-02-11 09:48:32 +11:00
Bob Strecansky 09cecbee7c
Making a note about the contrib repo (#575) 2022-02-03 13:52:54 +11:00
Timo Michna d2a9023632
Refactor Environment Variable Handling (#561)
* Move EnvironmentVariablesTrait

* Add env var constants

* Move EnvironmentVariablesTrait

* Set default to empty string

* Add ClassConstantAccessor

* Use Env Var constants

* Fix naming

* Add Env Var parsers

* Fix boolean values

* Add Resolver

* Fix covers annotation

* Add Accessor

* Allow unknown env vars

* Add test for empty var

* Filter correct types

* Allow empty lists and maps

* Add 'none' to known compressions

* Use inline constants

* Use Env Accessor

* Fix CS

* Make TraceIdRatioBasedSampler construction safe

* Supress wrong Psalm error

* Remove redundant checks

* Remove redundant checks

* Add additional getters to trait

* Remove redundant metadadata handling

* Fix CS

* Fix insecure gRPC credential creation

* Test for cert file
2022-02-02 09:54:32 -05:00
Grunet 7335c4183f
Bring Jaeger Thrift Span Converter up to Spec (#556)
* Add in the span kind mapping

* Improve colocation of the 64 bit check

* Make the order of the helper functions better match the usage in the entry method

* Rename otlp to otel since that was tripping me up a little

* Initial work for events conversion

* Making the previous commit functional and adding tests

* Factoring out a chunk of code from the entrypoint

* Fixing style

* Extract confusing constants

* Uncommenting the handling for tags of non-string types

* Making the string tag type the default fallback, matching the sanitiseTagValue method

* Moving the array serialization into the buildTag method

* Opening up the tag creation to arbitrary types, not just strings

* Moving the array serialization method to be more colocated

* Fix existing tests

* Removing hard to reach branch that should already be covered by the default case

* Extending existing test to cover the new number cases

* Refactor to avoid possibly mutating argument reference

* Implement error flag section of the spec

* Implement the Links section from the spec

* Refactoring the span id conversion for better colocation

* Fix assertion parameter order in a few tests

* Fix style

* Fix style post manual merge from main

* Inline helper method call

* Remove elseif branches

* Re-cover bool to string conversion line and remove less-than-helpful comment nearby
2022-01-29 07:41:12 +01:00
Brett McBride 82eb382379
fixing psalm error (#560)
psalm has started to complain that random_bytes must receive a positive integer. We always
provide a positive integer, so suppress the warning. In passing, make randomHex method
private, since it is not called from anywhere that I can find.
2022-01-29 14:15:52 +11:00
Grunet 13717d367c
Some incremental progress on Jaeger spec compliance (#555)
* Add in the span kind mapping

* Improve colocation of the 64 bit check

* Make the order of the helper functions better match the usage in the entry method

* Rename otlp to otel since that was tripping me up a little

* Initial work for events conversion

* Making the previous commit functional and adding tests

* Factoring out a chunk of code from the entrypoint

* Fixing style

* Extract confusing constants
2022-01-26 05:16:23 +01:00
Timo Michna 61c8465196
Add PhpMetrics (#554) 2022-01-23 22:54:13 +01:00
Tobias Bachert 0f17e55824
Move resource detection out of `ResourceInfo` (#537)
* Move resource detection out of `ResourceInfo`

* Apply feedback
2022-01-21 15:41:25 -05:00
Timo Michna 15c03f80b8
Replace apache/thrift with packaged/thrift (#548)
* Replace apache/thrift with packaged/thrift
* Fix phan config
2022-01-20 10:11:48 +11:00
Bart Reunes 794b387fbd
Fix the port environment variable (#551)
After reading a few open GitHub issues, I'm aware that it is known that the Symfony/Laravel examples as a whole are not up-to-date with the sdk code, but the docker-compose tutorial is on point. So if it's okay, I want to update it to the latest Jaeger version.

https://github.com/jaegertracing/jaeger/releases/tag/v1.22.0

> --collector.zipkin.http-port is replaced by --collector.zipkin.host-port
2022-01-18 10:11:40 -05:00
Grunet 9d1d0c5e49
Satisfy base spec for Jaeger Thrift span conversion (#547)
* Include library name and version in the jaeger span
* Implementing the span status conversion part of the base spec
* Add test now instead of later to pass coverage requirements
* Trying to clarify how the mapped statuses are distinct from the input ones with constant names
* Update namings of constants to be more flexible
2022-01-17 16:23:02 +11:00
Brett McBride b1a095d120
fixing otlp span converter with ext-protobuf (#544)
* fixing otlp span converter with ext-protobuf
There looks to be a bug in ext-protobuf, where an array with any empty string top-level values cause an error. A workaround for this is to strip out entries with empty values.
Adding ext-protobuf to the test matrix, and in passing fixing a mis-named test class
* document and suggest protobuf extension
2022-01-13 15:32:55 +11:00
Grunet 015907c2f2
Revamped PR for Jaeger Agent Support (#545)
* Moving the files to what I think are their correct new location
* Initial resolution of some of the parsing and intellisense errors
* Installing apache/thrift to solve more of the parsing issues
* Updating AgentExporter to conform to the updated SpanExporterInterface
* Switching to the new method names on SpanDataInterface
* Make the thrift generation script executable
* Fixing the last intellisense issue in AgentExporter
* Generating these thrift IDL files seems to have resolved the remaining parsing/intellisense errors
* Update thrift generation script to change target directory
* Generate the thrift idl files in the new directory
* Clean up conflicts with SpanExporterTrait's declaration of isRunning
* initial scaffolding for a happy path
* Fix lookup for socket functions to not look in the Jaeger declared namespace
* Setting up the autoloader so auto-generated thrift files can be found
* Switching to use the static method for creating the object under test
* Add a method and assertions to the happy path
* Doing some more exercise by passing in a shell span to export
* Clean up the socket at the end of the test
* Extend the happy path's coverage slightly
* Move exertion of the tag generation logic into a unit test
* Commenting out apparently dead code
* Adding a unit test exercising the happy path of the SpanConverter in more detail
* Ordering assertSame parameters correctly
* Cleaning up the 2 new tests a little
* Updating tests to match the new naming convention upstream
* Run make style
* Fix psalm errors
* Fixing most of the phpstan errors
* Fix test broken by psalm changes
* Fix phan config issues
* Fix phpstan issues
* Preventing installations on non-64 bit systems that won't work with Jaeger ids
* Manually merge changes to composer.json
* Fix 64 bit requirement setup
* Some more manual merging to try and resolve composer.json conflicts
* Update namespace for SpanData test helper to fix psalm issues
* Move the test files to what appear to be their new locations
* Fix failing test around getValue call on attributes (not exactly sure how this was passing before, but now it matches the zipkin version)
* Add @covers attributes to the test files
* Moving AgentExporterTest under the Unit folder because tests under the integration folder don't have their coverage reported
* Commenting out CodecUtility to see how that affects the coverage
* Adding in requirements and suggestions for ext-sockets into the composer.json's
* Switch to self when invoking the static method
* Rename Transport to TransportInterface
* Switch to using the logging trait instead of calling error_log directly
* Removing 64-bit install requirement
* Refactor anything needing to use intval into 1 function
* Adding a runtime check for 64-bit integer support
* Adding missing return types on methods
* Moving ext-sockets to be a suggest in the contrib composer.json too
* Remove extraneous comments in tests
* Switch to use shared time unit conversion method
* Clarify what the pre-existing commented out code should be used for
* Run style fixer
* Move 64bit check into a constructor
* Deleting the unused CodecUtility file
* Converting the TODO to a NOTE for the 2nd commented out block in SpanConverter
2022-01-13 15:22:53 +11:00
Brett McBride 86ed4cff87
adding covers annotations to all tests (#540)
* adding covers annotations to all tests
* clock tests
* adding unit tests
* feedback
- cleaning up ValueRecorder tests
- ints are floats, so type-hint ValueRecorder::record and remove some checks
2022-01-07 09:33:08 +11:00
Brett McBride c7f3361bdc
fixing jaeger example (#541)
* fixing jaeger example

* tidy
2022-01-06 11:56:57 +01:00
Brett McBride 56cf2db141
Separate integration and unit tests (#538)
* reorganise tests
moving tests under tests/Unit and tests/Integration, and updating namespaces
changing 'make test' to just run unit tests, and generate coverage off that
adding a 'make test-integration' to run integration tests (without coverage)
adding test-integration to 'make all'
adding a separate github action to run integration tests

* tidy 'make test'
make test is now a combination of test-unit and test-integration

* fixing 'make all'

* adding unit tests for TraceIdRatioBasedSampler
I grabbed a couple of the more unit-tests tests from the integration tests. Also starting to add some @covers
annotations to start to remove false coverage
2022-01-05 14:22:12 +01:00
Timo Michna 0c1fd9915a
Add PHP version flag to codecoverage upload (#536) 2022-01-04 12:43:46 +01:00
lalex 53eed095bd
Enforce snake_case for test method names (#535) 2022-01-04 22:08:42 +11:00
Christopher Morton 777ea9bf19
Unify test method's coding style (#533)
* Rename test methods

Ensure all test methods:
 - are snake_case
 - have "test" prefix

Private methods, data providers, setUp/tearDown and external functions
remain camelCase.

* Add return type to test methods

Ensure all test methods have return type "void".

* Remove extraneous @test from test method docblocks

Where it is the only entry, remove the docblock entirely.

* Fix missing test prefix

Add test prefix and fix mixed snake_case and camelCase test name.
2022-01-04 11:07:42 +01:00
Timo Michna 6bc7050e6d
Allow psr/log ^2.0 and ^3.0 (#532)
* Allow psr/log ^2.0 and ^3.0

* Fix type-hint
2022-01-03 10:37:43 +11:00
Tobias Bachert 6ff577b417
Restructure API / SDK components (Attributes, Clock, Trace) (#521)
* Move Attributes and Clock out of /Trace namespace

Also needed for other components (metrics).

* Move Event and Link to SDK

* Move NoopTracer to API

* Remove `Attribute` abstraction

* Move `Attributes` to SDK by widening API attributes types to `iterable`

* Move `Clockinterface` to SDK

* Fix fqcn usage

* Readd `AttributesInterface` mock

* Move `TraceState` and W3C `TraceContextPropagator` to API
2022-01-01 18:51:36 +11:00
Timo Michna 2d365e6443
Initial package-split setup (#531)
* Rename protobuf make target to "make protobuf"

* Move otel protobuf files to 'otel' subdirectory

* Add composer/package-versions-deprecated as allowed plugin

* Report uncovered files in dependency check

* Move PrometheusExporter to contrib package

* Add missing dependency checks

* Fix API dependency

* Add package specific composer files

* Fix wording

* Add use-statement for PrometheusExporter class
2021-12-31 03:19:23 +01:00
Timo Michna 4ace6c1b66
Fix dependency violations in exporter factory (#525)
* Relax fromConnectionString requirements

* Remove contrib dependencies from exporter factory

* Add SemConv to dependency check

* Add SemConv as required CI check

* Remove dependency from ZendObserverFiber on SDK

* Fix syntax error

* Fix style

* Cast scheme to string to avoid nullable argument

* Make up for removing false positive code coverage.

* Fix CS

* Fix assertions

* Remove unused method
2021-12-29 15:47:47 +01:00
Grunet 645754a104
Add sockets to the list of extensions (#526) 2021-12-29 03:25:25 +01:00
Tobias Bachert fb00203a59
Fix noop SpanContext propagation (#522)
* Add tests for noop `SpanContext` propagation

* Fix noop `SpanContext` propagation

* Remove global context usage in `NoopSpanBuilder`

* Make `Context` non-final until `ContextInterface` is introduced

Workaround for mocking failure on php8.1.
2021-12-28 13:17:15 +01:00
Tobias Bachert 2038e99351
Add FFI Fiber support preload example (#524) 2021-12-25 10:47:56 -05:00
Brett McBride 191d4bc9ca
fixing fiber test crash (#517)
* fixing fiber test crash
instead of serializing FFI into a const, stash it in a static as suggested by @nevay
* update comment on FFI reference
* review feedback
moving ffi+fiber code into a class, and protecting it behind a new env var
replacing class with a mock in ArrayAccessGetterSetterTest
* review feedback
putting back FFI::scope which is required for other SAPIs, and starting to document preloading
2021-12-24 10:23:23 +11:00
Timo Michna 04ba5c953b
PHP 8.1 compatibility (#489)
* Add PHP 8.1 to test matrix

* Fix composer package versions

* Set the php-cs-fixer version to 'dev-master'

* Reset the php-cs-fixer version to stable one

* Set friendsofphp/php-cs-fixer version to 3.4

* Fix PHPStan covariant error in PHP8.1

* Fix optional parameter declared before required parameter error

* fix the matrix

* more matrix fixing
2021-12-17 00:10:10 +01:00
Brett McBride 597a811243
adding php8.1 as an experimental build (#514)
a failing experimental job no longer stops the whole build, although we will see a red X. There is a feature request to be able to set jobs as "allowed-to-fail", but until that feature exists this looks like the best github actions can do.
2021-12-17 08:37:51 +11:00
Brett McBride e0b2d7da65
creating a global logger holder (#495)
* creating a global logger holder
since logging errors can live in all parts of the sdk (logs, metrics, traces), creating a singleton
in the top-level SDK namespace seems the best place. This commit just gets the mechanism in place
and implements a couple of log messages to get feedback on whether this is a good way to go
* adding a trait for accessing logger
* logging example, improve logged messages
2021-12-16 10:32:05 +11:00
Brett McBride 6fff7a07a6
build base image for multiple php versions (#512)
* build for multiple php versions
allow building for multiple php versions by making Dockerfile php version an argument, and
relaxing extension location (by using find instead of hard-coded location).
Relax a couple of dev dependencies so they can install for 7.4->8.1.
Adding an example .env file, and allow configurating xdebug via environment.
Adding a couple of whitespace-related php-cs-fixer rules.

* run image build to schedule (midnight sunday UTC)
instead or rebuilding on each push to main, just rebuild weekly. The workflow can also be manually triggered
by a maintainer if required

* review feedback - wordsmithing supported versions
2021-12-15 10:48:03 +11:00
Timo Michna 77a103b38c
Fix formatting (#511) 2021-12-10 05:10:17 +01:00
Timo Michna ec9387c256
Add installation requirements to README (#510) 2021-12-10 04:51:44 +01:00
lalex df3c719317
Add semantic conventions for Resource and Trace attributes (#502)
* Add semantic conventions for Resource and Trace attributes

* Add SCHEMA_URL pointing to the scheme used for code generation

* Fix setting of SERVICE_NAME in default Resource instance

* Add information about semantic conventions to README.md
2021-12-08 20:51:13 -05:00
Timo Michna 52d46fdad5
Update protocol buffers (#506) 2021-12-09 02:24:39 +01:00
Brett McBride 747bda2df4
adding new maintainers to CODEOWNERS (#505) 2021-12-08 19:04:47 -05:00
PauliusB 4a30272f6e
Convert and send zipkin span kind in string format (#493)
* Convert and send zipkin span kind in string format

* Rename zipkin span kind constants and remove unused class methods
2021-12-09 00:49:04 +01:00
Brett McBride 44575d74e6
combining otlp span converters (#494)
* span converter rework
- combine otlp's grpc and http span converters into one
- adjust UsesSpanConverterTrait to always deal with arrays of spans, since span processors only accept arrays
Still to do:
- combine duplicated grpc/http span converter tests

* tidy

* make internal otlp span converted methods private
2021-12-06 23:24:34 -05:00
Timo Michna d490dd2447
Add typed properties (#503)
* Add typed properties

* Remove unused import
2021-12-06 09:16:47 -05:00
Timo Michna 4f65bb90e4
Optimize base PHP Dockerfile (#487)
* Optimize docker file

* Add system user

* Remove debug build in docker-compose
2021-12-06 08:56:24 -05:00
Timo Michna 63737623b0
Move ext-grpc to require-dev (#501) 2021-12-06 08:54:13 -05:00
Brett McBride 8649206eaa
switching span processor selection to language-specific (#497)
see https://github.com/open-telemetry/opentelemetry-specification/pull/2172#issuecomment-982312473
2021-12-01 18:55:55 -05:00
Brett McBride 2c1eb54946
Revert "Otlp centralised config (#488)" (#491)
This reverts commit 70d4dc25df.
2021-11-28 18:45:13 -05:00
Brett McBride 70d4dc25df
Otlp centralised config (#488)
* WIP

* Return Opts object so chain config

* More WIP

* combining otlp and grpc config
based on SeanHood's initial work for #383, I've fleshed out ConfigOpts, and used it to
simplify the configuration of the http and grpc exporters

* tidy

* changing compression to string, per spec

* update example - insecure defaults to false per spec

* moving more config into ConfigOpts
now both http and grpc exporters have almost the same constructor (todo Grpc accepts a SpanConverter
but http does not)

* removing unused SpanConverter param

* remove unused function

* test coverage for grpc exporter

Co-authored-by: Sean Hood <me@seanhood.co.uk>
2021-11-28 18:27:00 -05:00
Brett McBride 278f07525d
benchmark (#486)
* benchmark setup
some initial benchmarking tests, based loosely on the spec and with some inspiration from the python-otlp tests

* link to extensive go benchmarks for inspiration

* style

* psalm + phpstan

* remove accidental commit

* style fix

* more benchmarks

* undo accidental commit
2021-11-23 21:50:22 -05:00
Brett McBride e0211b9e84
de-duplicating resources from multiple spans (#485) 2021-11-23 21:49:43 -05:00
Grunet 8008b1c366
Finish Off Zipkin Spec Updates (#474)
* Initial stab at implementing the event attributes logic

* In-progress work on the Remote Endpoint logic

* Partial progress on the ip portion of this

* Finish adapting the Go code

* Adding a check for if ipv6 support is enabled

* Add happy path test through remote endpoint code + fix comparison bug it uncovered too

* Add test through the ipv4 and port handling + fix bug with the preferred attribute key selection

* Partial progress on test through ipv6 handling code

* Switching the expected/actual for the new tests

* Fix up the ipv6 test

* Dropping back to assertSame since it's just a string comparison now

* Removing a piece of currently dead code

* Factoring out the Zipkin annotation generation

* Add return type

* Extract remote endpoint logic out into a function

* Factoring out the ranking logic into its own function

* Extracting the constant array into a class constant

* Flattening out 1 level of the nested ifs

* De-dup and flatten ifs some more

* Switch to a switch statement

* Factor out the ip address specific piece

* Flattening some more ifs

* Factoring out the port number lookup into its own function

* Composing the port number calculation in

* Cleaning out some comments + adding validation that the found port number is a real port

* Removing some more comments

* Another minor cleanup

* Adding a test for an else branch

* Updating the test to match the spec and fixing the code

* Refactoring and cleaning up toAnnotation

* Fix to Psalm noticing the ip methods only take strings but the attributes can have more general values

* Fix Phan recommendations on return types

* Fix style issues

* Don't recall what I changed in this file, but hopefully this gets rid of the merge conflicts

* Extract out a constant

* Restrict code coverage to the class under test

* Stregthen a comparison against null

* Swap string interpolation for sprintf
2021-11-22 12:10:59 -05:00
Brett McBride d9e2f5238b
distributed tracing example (#483)
* distributed trace example

* screenshots

* remove xdebug settings

* style fixes

* fixing composer.json ref

* clean up collector config

* fix typo

* code review feedback

* fixing psalm platform reqs
the bug was fixed upstream, so revert our workaround

* install otel lib from github, commit lock file
2021-11-22 12:10:26 -05:00
Timo Michna cb92ba4d91
Exporter Refactoring (#476)
* Add dg/bypass-finals to allow mocking final classes/methods

* Fix CS

* Consolidate exporter tests

* Fix method semantics

* Implement SpanConverterInterface

* Refactor exporter classes

* Change endpoint validation to always throw exceptions on error (quick fix for CI)

* Comment import of Throwable out (for now)

* Fix CS

* Add dg/bypass-finals to allow mocking final classes/methods

* Fix CS

* Consolidate exporter tests

* Fix method semantics

* Implement SpanConverterInterface

* Refactor exporter classes

* Change endpoint validation to always throw exceptions on error (quick fix for CI)

* Comment import of Throwable out (for now)

* Fix CS

* Streamline request creation
2021-11-21 14:12:06 -05:00
Brett McBride c464706ff4
default tracer (#479)
* set/get default tracer

* adding a default tracer example
2021-11-21 14:11:31 -05:00
Brett McBride 88e5750e68
makefile improvements (#480)
adding 'make all', which runs the important parts of CI process
ensuring xdebug mode is set correctly for make targets
2021-11-21 14:11:06 -05:00
Patrice Chalin 75dc41ee5f
Getting started: add front matter so page will display (#478) 2021-11-18 15:24:56 -05:00
Timo Michna 8bc117e62f
Add make target to create HTML code coverage report (#477)
* Add make target to create HTML code coverage report

* Add XDEBUG_MODE env var
2021-11-17 19:47:35 -05:00
Brett McBride 6b2acca0ec
Configuration from environment variables. (#469)
* Configuration from environment variables.
Allow configuring resources, (some) exporters, samplers, and span processors from environment.
Add a TraceProviderFactory as a top-level method of creating a span processor from environment variables.
I think that other span exporters can be made to be env-configurable, but holding off until an upcoming improvement to use psr-7 discovery lands, which should simplify
most of the exporters.

* setting io.opentelemetry.contrib.php as the default tracer name

* review feedback
- Throwing InvalidArgumentExceptions from some factories.
- Removing guzzle client from ExporterFactory.

* magic values to consts

* moving queue init to property

* adding root sampler to parentbased sampler description
this makes parent-based description more meaningful, and also useful for test assertions

* fixing tracer provider factory tests

* improving span processor factory tests

* use ReflectionObject in test

* Adding a trait for retrieving and processing environment variables

* empty value must be treated as unset

* fixing default service name
2021-11-17 17:23:41 -05:00
Patrice Chalin fbfcbd7464
[website_docs] Link to latest release (#475)
Contributes to https://github.com/open-telemetry/opentelemetry.io/issues/905. /cc @austinlparker
2021-11-16 15:40:07 -05:00
Timo Michna b6a081bf2b
Fix Exporters` fromConnectionString method (#472)
* Add php-http packages

* Use HTTP discovery

* Fix ExporterFactoryTest

* Fix argument validation
2021-11-15 11:51:56 -05:00
Timo Michna e4f0e85431
Move SpanContextTest to API (#471) 2021-11-15 10:13:35 -05:00
Timo Michna 6660a5cac7
Move TraceContextPropagator to SDK (#470)
* Move TraceContextPropagator to SDK

* Move TraceContextPropagatorTest to SDK tests

* Fix CS

* Fix (wrong) Phan errors
2021-11-15 08:32:49 -05:00
Timo Michna c24b6eb0e9
Move KeyedArrayAccessInterface to Context (#468) 2021-11-13 10:28:16 -05:00
Timo Michna 2c00772cad
Move SpanContext and SpanContextKey to API (#467) 2021-11-13 10:27:47 -05:00
Timo Michna 8145f990fa
Add mbstring extension polyfill (#466)
* Add symfony/polyfill-mbstring

* Replace StringUtil with multibyte calls
2021-11-13 01:24:19 -05:00
Timo Michna 1511c73987
Add Deptrac as a dependency testing/linting tool (#465)
* Add deptrac package as dev dependency

* Add minimal deptrac configuration

* Ignore deptrac cache

* Add deptrac
2021-11-12 14:26:55 -05:00
Timo Michna 3f56af97ce
Upgrade phpstan packages to stable versions (#463)
* Upgrade phpstan packages to stable versions

* Fix phpstan errors

* Add ContextKeyTest

* Fix CS
2021-11-11 11:26:38 -05:00
Timo Michna d497f4e745
Add Logger SpanExporter, Logger ExporterDecorator and other logging related components. (#460)
* Add psr/log as dependency

* Add monolog as dev dependency

* Depend on AttributesInterface

* Add StatusDataInterface

* Change psr/log to PHP7.4 compatible version

* Add vfsstream to mock filesystem

* Move ConsoleSpanExporter

* Add PSR severity mapping

* Add SpanConverterInterface

* Add FriendlySpanConverter

* Add NullSpanConverter

* Add UsesSpanConverterTrait

* Add SpanExporterDecoratorTrait

* Add SpanExporterTrait

* Add LoggerAwareTrait

* Add SimplePsrFileLogger

* Use FriendlySpanConverter

* Add AbstractDecorator

* Add LoggerExporter

* Add LoggerDecorator

* Fix line breaks in log formatting

* Change accessibility of granularity setter to public

* Add trace logging examples

* Fix CS

* Add EventTest

* Add loggerName parameter

* Paint it green

* Fix CS

* Activate native PHP asserts for tests
2021-11-08 19:48:27 -05:00
Tobias Bachert 4663ad57bc
Add context detach out-of-order detection and support for execution context switching (#456)
* Add scope out-of-order detection and support for execution context switching

* Remove Scope in favor of ScopeInterface

* Add fiber support

* Resolve/suppress phan/psalm/phpstan errors

Suppresses errors related to not available classes Fiber/FFI in code that is written for php ^8.1.

* Add missing test annotations
2021-11-01 06:19:39 -04:00
Brett McBride fd33eb580a
Bugfix/batch processor (#459)
* updating BatchSpanProcessor to spec
The spec for SpanProcessor::shutdown() says 'MUST include the effects of ForceFlush', so implement that logic and add a test (also updated a couple of other tests to add a new expectation on forceFlush)
The spec for SpanProcessor::forceFlush() also says that built-in span processors MUST call forceFlush() on the exporter.
Bugfix: SpanInterface::scheduledDelayMillis clearly accepts milliseconds, but time checking arithmetic uses nanoseconds. Adding a constant to convert between the two (todo, write a test?)

* renaming const, adding batch example

* style fix

* unit tests for batch span processor delay

* improving code coverage of BatchSpanProcessor
2021-11-01 06:17:54 -04:00
Sean Hood bfb15c6efa
Fixes OtlpHttp Endpoint validation/parsing (#457)
* Now appends /v1/traces to the endpoint if missing
* Now prepends https:// if either http or https missing
2021-10-31 08:18:36 -04:00
Brett McBride 08916531be
docs/updated examples (#455)
* span resources example
example code for setting span resource attribute, which are sent as part of the payload of each span. also adds to ConsoleSpanExporter a
representation of each span's resources

* concurrent spans example

* linting, updating ConsoleSpanExporter tests

* adding some stable resource constants

* update span name
span-n should be more obvious when reading a trace
2021-10-30 13:57:56 -04:00
Sean Hood c972954aa4
Add docs + ConsoleSpanExporter (#442)
* Add docs + ConsoleSpanExporter

- [ ] Add tests
- [ ] Support Events/Attributes/Status
- [ ] Kind should return friendly string not int

* Update ConsoleSpanExporter to match SpanExporterInterface

* Tests! and more

* Tests!
* Kind now returns the API name rather than the integer
* Added attributes
* Added status
* Added events

* Fix trace parent id

* Update docs + examples

* Make phan/phpstan/psalm/style happy

* Make palm happy on PHP 7.4?

* Document more functions
2021-10-28 17:15:16 -05:00
Grunet bbd99c2c4c
Update OTEL-to-Zipkin Span Converter to be a Little More Spec Compliant (#453)
* Adding in the 'kind' attribute

* Add in the instrumentation library attributes and extend the happy path test

* Add conditional logic around status and description tags

* Don't add parentId to row when it's not valid

* Drop kind from payload if null

* Omitting tags if there aren't any
2021-10-25 12:25:04 -04:00
Patrice Chalin 57a219156a
Website: support GH page links to canonical src (#454) 2021-10-22 12:41:37 -04:00
George Dietrich f5f57f729d
Make span exporters spec compliant (#450)
* Update `SpanExporterInterface` Status constants to better leverage psalm

Implement `forceFlush` for all exporters

* Make CI happy

* Spec said Export not Shutdown
2021-10-13 09:50:41 -04:00
Grunet ef2ccc4768
Update OTLP/HTTP Default Port Per Changes to the Spec (#438)
* Update OtlpHttp port in Exporter to be 4318 per most recent edition of spec

* Update old collector port to new one for Otlp/Http (and HTTP!?!)

* Fix typo. Yay tests!

* Also made that mistake here
2021-10-11 08:51:10 -04:00
George Dietrich 8d61da2057
Span processor exporter updates (#439)
* Make `shutdown` and `forceFlush` return `bool`

Rename `Exporter` to `SpanExporterInterface`
Update docs to include links to spec

* Return a noop tracer if the provider has been shutdown

* Make CI happy

Revamp `SimpleSpanProcessorTest`
2021-10-09 14:36:10 -04:00
Sean Hood c8756f1296
cleanup: Remove old Otlp Class (#440)
This commit removes the old Otlp Exporter which wasn't to spec. I feel it's causing confusion about it being there.

On a side note, I was going to put common parts of OtlpGrpc and OtlpHttp into this namespace but haven't got around to it yet. So small clean up commit, until I find the time.
2021-10-08 07:25:31 -04:00
George Dietrich 1109aa5628
Baggage propagation (#437)
* Move `Baggage` logic into the API namespace

Make `TextMapPropagator` methods non-static
First pass at adding `BaggagePropagator`
Create no-op and multiple text map propagator implementations

* Move `Baggage` tests to API test namespace

Modernize `TraceContextPropagator`

* More test coverage

Move some tests into a `Propagation` namespace

* Properly encode/decode baggage values

* Don't use PHP8 only method

* Make CI happy

* Expose helper method to get a composite propagator

* Move field extraction logic into private method
2021-10-06 14:39:33 -04:00
George Dietrich 5400e0669b
Move Context related logic into the API (#436) 2021-10-03 09:43:48 -07:00
Patrice Chalin f4124e0859
Delete docs-update.yml (#435) 2021-10-03 06:33:10 -04:00
George Dietrich 01c388e02c
Reorganize types (#434)
* Create and move namespaces into `src/` directory

* Update `composer.json`

Move test helpers outside of `SDK` namespace into `Tests`

* Follow PSR naming conventions for interfaces

* Follow PSR naming conventions for abstract classes and traits

* Do a pass on CI configs

* Add examples directory to cs-fixer config

* Fix some erroneously renamed type names
2021-10-03 06:32:46 -04:00
Grunet b5a89523f5
Add 2 More Tests through OtlpGrpc\Exporter (#430)
* Return empty object if no spans are passed for OTLPGrpc

* Return empty object if no spans are passed for OtlpHttp

* Remove trailing whitespace

* Remove extra whitespace

* Adding a test to hit line 150 of OtlpGrpc/Exporter.php

* Adding a test through line 162 of OtlpGrpc/Exporter.php

* Updating testExporter's test name to be more specific to what it seems to be doing

* Switching to the normal Mockery syntax to enable argument matching

* Add argument expectations to the 2 new tests

* Fixes after running "make style"

* Fix after running "make psalm"

* Switch out assertEquals for assertSame

* De-duplicate mock client setup

* Forgot to run "make style" on the recent changes

* Fix to PHP 7.4 using non-strict comparison to an integer
2021-10-01 09:53:14 -04:00
George Dietrich 98c97289d9
`BatchSpanProcessor` clock fixes (#433)
* Allow `BatchSpanProcessor` to use any `API\Clock`

Clarify and update batch processor to use `nanoTime` since it is calculating elapsed time
Update unit test to make use of `TestClock`
Add default timestamp to `TestClock`

* Fix lint errors
2021-10-01 09:00:36 -04:00
George Dietrich d08d9581b3
Events & Links improvements (#432)
* Replace `Links` and `Events` types with `array`

Apply limits to links and event attribute lengths
Some minor changes to `API\Event`

* Move `$events` property to non readonly section

Update `.gitignore`
2021-10-01 09:00:23 -04:00
George Dietrich 6cffcbe5a0
Span Refactor (#422)
* First pass at updating Span API

* First pass at updated Span implementation

* Update SDK Span return types to `ReadWriteSpan`

Drop support for PHP 7.3

* Finish initial implementation

* Implement `SpanData`

* Implement `StatusData`

* Re-implement and rename `NoopSpan` to `NonRecordingSpan`

* Updates to support `SpanData` in exporters/span processors

* Add timestamp conversion helper methods

Update Exporters to use `SpanData`
Start updating Exporter tests
Implement non immutable `SpanData` test helper class

* Finish updating exporters/converters

* Fix next batch of tests

* First pass at `Tracer` refactor

Leverage a `SpanBuilder` to create the span
Use a dedicated object to share state

* Just use `NonRecordingSpan` constructor versus `create`

Start of adding tests for new Tracer implementation

* Remove some unneeded `max`

Make `Sampler` the 2nd arg to `TraceProvider`
Fix Integration tests

* Add `NoopSpanProcessor`

Continue updating/adding tests

* Install mockery

Ensure span processor is called with expected contexts/spans

* Update `SpanData` to directly return dropped amounts

Make `SpanProcessor#onStart` take a `ReadWriteSpan`
Update empty span fallback name

* Revamp `Clock` interface/implementation

* Add some additional doc comments

Continued work on updating test coverage

* Add more `Span` tests

* Get tests to a passing state

* Fix type errors

* Make CI happy

* Apply limits within `Span` constructor and `SpanBuilder` logic

Add test coverage for these cases
2021-09-29 19:10:07 -04:00
Bob Strecansky 0be91c2cf4
Add .yml extension, update the base docker-compose image (#421) 2021-09-20 19:53:41 -04:00
Bob Strecansky 86bc64c6cb
Publish OpenTelemetry PHP Base Docker Image (#420) 2021-09-20 19:01:08 -04:00
lalex 45362dec23
Add AttributeLimits, SpanLimits and dropped event/links counting (#417)
* Add AttributeLimits, SpanLimits and dropped event/links counting

* Increase code coverage for SpanLimitsBuilder
2021-09-20 10:20:08 -04:00
George Dietrich b44df6db29
Refactor `Baggage` (#416)
* Scaffold out initial `Baggage` implementation

Do some reorganizing of `Context`

* Implement `BaggageBuilder`

* Add some additional docs/tests
2021-09-18 19:25:13 -04:00
Grunet 1cfd72accf
Return empty objects when no spans are passed in OTLP/GRPC exporter implementation (#412)
* Return empty object if no spans are passed for OTLPGrpc

* Return empty object if no spans are passed for OtlpHttp

* Remove trailing whitespace

* Remove extra whitespace
2021-09-15 15:05:23 -04:00
George Dietrich 500ff88cdb
Context propagation refactor (#410)
* Update `TextMapPropagator` interface

* Update trace context propagator

* Implement `ImplicitContextKeyed`

First pass at moving span activation outside of `Tracer`

* Set span as current when activating in `Tracer`

Fix some tests

* Make CI happy

* Use single method to get context

Add doc comments where needed
Update spec links to use specific version

* Normalize `Link` to use `getContext` as well

Reintroduce `getContext` to `ReadableSpan`
Make CI happy

* Update/Rename getter/setter type to be spec compliant

* Revert `Link` method name change

Makes it more clear you're getting a `SpanContext` not some sort of`LinkContext`

* Rename `makeCurrent` to `activate`

* Rename `Context` methods to better reflect their purpose

* Make carrier the 2nd arg

Implement `KeyedArrayAccess` and rename the propagation getter/setter to `ArrayAccessGetterSetter`

* Fix typing issues
2021-09-14 20:46:35 -04:00
Amber Sistla b33ed1505b
Update otel-collector-config.yml (#413) 2021-09-13 15:04:14 -04:00
George Dietrich 4dc072524e
Update Phan to latest version (#411) 2021-09-13 08:46:42 -04:00
George Dietrich 92feca4ae8
Update link API to be spec compliant (#408)
* Update link API to be spec compliant

Remove `addLink` from `Span`
Rename `addLinks` to `addLink` in `SpanOptions`
Add settings attributes and links on `Span` creation

* Update tests and refine API changes

* Fix some psalm errors
2021-09-10 09:38:56 -04:00
George Dietrich 2a800d8bc0
Run psalm in single threaded mode (#409)
* Manually stub grpc to fix psalm errors

Can remove the stub once the root cause is determined

* Add `ext-grpc` to `composer.json`

* Fix psalm security action

* Remove stub in favor of running psalm in single threaded mode
2021-09-09 08:56:31 -04:00
George Dietrich 17d0ca7666
Use Clock to get timestamp for events (#407)
* Use Clock to get timestamp for events

* Fix style
2021-09-07 20:05:18 -04:00
George Dietrich 897049a956
Implement links (#406)
* Implement Link & Links types

Include links when exporting via Otlp Grpc or Protobuf
Use `__toString` instead of `build` to get a string representation of a TraceState

* Assert links are propagated to span created via a tracer

* Fix psalm error

* Fix unit tests

* Add SpanConverter test coverage
2021-09-06 12:17:54 -04:00
1432 changed files with 93181 additions and 18054 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@ -12,5 +12,10 @@ trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.yaml]
indent_size = 2
[*.yml]
indent_size = 2
[Makefile]
indent_style = tab

5
.env.dist Normal file
View File

@ -0,0 +1,5 @@
PHP_USER=php
XDEBUG_MODE=debug
PHP_CS_FIXER_IGNORE_ENV=true
#docker-compose or "docker compose" for v1/v2 respectively, note that v1 support ends 06/2023
DOCKER_COMPOSE=docker compose

View File

@ -17,3 +17,5 @@ What did you see instead?
**Additional context**
Add any other context about the problem here.
<sub>**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/).</sub>

View File

@ -17,3 +17,5 @@ Which alternative solutions or features have you considered?
**Additional context**
Add any other context about the feature request here.
<sub>**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/).</sub>

5
.github/config.yml vendored Normal file
View File

@ -0,0 +1,5 @@
# configuration for new-issue-welcome bot https://github.com/behaviorbot/new-issue-welcome
newPRWelcomeComment: >
Thanks for opening your first pull request! If you haven't yet signed our Contributor License Agreement (CLA),
then please do so that we can accept your contribution.
A link should appear shortly in this PR if you have not already signed one.

22
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,22 @@
---
version: 2
updates:
- package-ecosystem: "composer"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "docker"
directory: "/docker"
schedule:
interval: "daily"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "docker-compose"
directory: "/"
schedule:
interval: "daily"

21
.github/stale.yml vendored Normal file
View File

@ -0,0 +1,21 @@
---
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 30
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- 'pinned'
- 'security'
- 'help wanted'
# Label to use when marking an issue as stale
staleLabel: 'stale'
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
closeComment: >
This issue has been automatically closed because it has not had
recent activity, but it can be reopened.
Thank you for your contributions.

View File

@ -1,35 +0,0 @@
name: Update OpenTelemetry Website Docs
on:
# triggers only on a manual dispatch
workflow_dispatch:
jobs:
update-docs:
runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v2
- name: make-pr
env:
API_TOKEN_GITHUB: ${{secrets.GITHUB_PAT_TOKEN}}
# Destination repo should always be 'open-telemetry/opentelemetry.io'
DESTINATION_REPO: open-telemetry/opentelemetry.io
# Destination path should be the absolute path to your language's friendly name in the docs tree (i.e, 'content/en/docs/java')
DESTINATION_PATH: content/en/docs/php
# Source path should be 'website_docs', all files and folders are copied from here to dest
SOURCE_PATH: website_docs
run: |
TARGET_DIR=$(mktemp -d)
export GITHUB_TOKEN=$API_TOKEN_GITHUB
git config user.name github-actions
git config user.email github-actions@github.com
git clone "https://$API_TOKEN_GITHUB@github.com/$DESTINATION_REPO.git" "$TARGET_DIR"
cp -r $SOURCE_PATH/* "$TARGET_DIR/$DESTINATION_PATH"
cd "$TARGET_DIR"
git checkout -b docs-$GITHUB_REPOSITORY-$GITHUB_SHA
git add .
git commit -m "Docs update from $GITHUB_REPOSITORY"
git push -u origin HEAD:docs-$GITHUB_REPOSITORY-$GITHUB_SHA
gh pr create -t "Docs Update from $GITHUB_REPOSITORY" -b "This is an automated pull request." -B main -H docs-$GITHUB_REPOSITORY-$GITHUB_SHA
echo "done"

20
.github/workflows/fossa.yml vendored Normal file
View File

@ -0,0 +1,20 @@
name: FOSSA scanning
on:
push:
branches:
- main
permissions:
contents: read
jobs:
fossa:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: fossas/fossa-action@3ebcea1862c6ffbd5cf1b4d0bd6b3fe7bd6f2cac # v1.7.0
with:
api-key: ${{secrets.FOSSA_API_KEY}}
team: OpenTelemetry

50
.github/workflows/ossf-scorecard.yml vendored Normal file
View File

@ -0,0 +1,50 @@
name: OSSF Scorecard
on:
push:
branches:
- main
schedule:
- cron: "17 0 * * 1" # once a week
workflow_dispatch:
permissions: read-all
jobs:
analysis:
runs-on: ubuntu-latest
permissions:
# Needed for Code scanning upload
security-events: write
# Needed for GitHub OIDC token if publish_results is true
id-token: write
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: ossf/scorecard-action@05b42c624433fc40578a4040d5cf5e36ddca8cde # v2.4.2
with:
results_file: results.sarif
results_format: sarif
publish_results: true
# file_mode is needed in this repo because .gitattributes excludes the .github directory
# (see https://github.com/ossf/scorecard/issues/4679#issuecomment-3013550752)
file_mode: git
# Upload the results as artifacts (optional). Commenting out will disable
# uploads of run results in SARIF format to the repository Actions tab.
# https://docs.github.com/en/actions/advanced-guides/storing-workflow-data-as-artifacts
- name: "Upload artifact"
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: SARIF file
path: results.sarif
retention-days: 5
# Upload the results to GitHub's code scanning dashboard (optional).
# Commenting out will disable upload of results to your repo's Code Scanning dashboard
- name: "Upload to code-scanning"
uses: github/codeql-action/upload-sarif@76621b61decf072c1cee8dd1ce2d2a82d33c17ed # v3.29.5
with:
sarif_file: results.sarif

View File

@ -1,5 +1,4 @@
name: PHP Composer
name: PHP QA
on:
push:
@ -7,61 +6,170 @@ on:
pull_request:
branches: [ main ]
jobs:
build:
permissions:
contents: read
jobs:
php:
runs-on: ubuntu-latest
continue-on-error: ${{ matrix.experimental }}
strategy:
fail-fast: false
matrix:
operating-system: [ubuntu-latest]
php-versions: ['7.3', '7.4', '8.0']
php-version: ['8.1', '8.2', '8.3']
experimental: [false]
composer_args: [""]
include:
- php-version: 8.4
experimental: false
composer_args: "--ignore-platform-reqs"
- php-version: 8.5
experimental: true
composer_args: "--ignore-platform-reqs"
env:
extensions: ast, grpc, opentelemetry, protobuf
steps:
- uses: actions/checkout@v2
- name: Set cache key
id: key
run: |
echo "key=$(date +'%Y-%U')" >> $GITHUB_ENV
- uses: actions/checkout@v4
- uses: gacts/run-and-post-run@v1
id: post-run-command
with:
post: |
echo "::group::Steps"
echo "composer=${{steps.composer.outcome}}"
echo "style=${{steps.style.outcome}}"
echo "deps=${{steps.deps.outcome}}"
echo "phan=${{steps.phan.outcome}}"
echo "psalm=${{steps.psalm.outcome}}"
echo "phpstan=${{steps.phpstan.outcome}}"
echo "unit=${{steps.unit.outcome}}"
echo "integration=${{steps.integration.outcome}}"
echo "::endgroup::"
if [ ${{ steps.composer.outcome == 'failure' || steps.style.outcome == 'failure' || steps.deps.outcome == 'failure' || steps.phan.outcome == 'failure' || steps.psalm.outcome == 'failure' || steps.phpstan.outcome == 'failure' || steps.unit.outcome == 'failure' || steps.integration.outcome == 'failure' }} == true ]; then \
echo "::error::One or more steps failed"; \
fi
- name: Setup cache environment
id: extcache
uses: shivammathur/cache-extensions@v1
with:
php-version: ${{ matrix.php-version }}
extensions: ${{ env.extensions }}
key: ${{ env.key }}
- name: Cache extensions
uses: actions/cache@v4
with:
path: ${{ steps.extcache.outputs.dir }}
key: ${{ steps.extcache.outputs.key }}
restore-keys: ${{ steps.extcache.outputs.key }}
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-versions }}
php-version: ${{ matrix.php-version }}
coverage: xdebug
tools: php-cs-fixer
extensions: ast, grpc
extensions: ${{ env.extensions }}
- name: Validate composer.json and composer.lock
- name: Validate composer.json
run: composer validate
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v2
uses: actions/cache@v4
with:
path: vendor
key: ${{ runner.os }}-php-${{ hashFiles('**/composer.json') }}
key: ${{ runner.os }}-${{ matrix.php-version }}-vendor-${{ hashFiles('composer.json') }}
restore-keys: |
${{ runner.os }}-php-
${{ runner.os }}-${{ matrix.php-version }}-vendor-
- name: Cache test tools
id: test-tools-cache
uses: actions/cache@v4
with:
path: vendor-bin
key: ${{ runner.os }}-${{ matrix.php-version }}-vendor-bin-${{ hashFiles('vendor-bin/*/composer.json') }}
restore-keys: |
${{ runner.os }}-${{ matrix.php-version }}-vendor-bin-
- name: Install dependencies
id: composer
if: steps.composer-cache.outputs.cache-hit != 'true'
run: composer install --prefer-dist --no-progress --no-suggest
- name: Update Composer
run: composer update
run: |
composer --version
composer install --prefer-dist --no-progress ${{ matrix.composer_args }}
- name: Check Style
run: vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --dry-run --stop-on-violation --using-cache=no -vvv
id: style
continue-on-error: ${{ matrix.experimental }}
env:
PHP_CS_FIXER_IGNORE_ENV: 1
run: |
vendor-bin/php-cs-fixer/vendor/bin/php-cs-fixer --version
vendor-bin/php-cs-fixer/vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --dry-run --stop-on-violation --using-cache=no -vvv
- name: Check Dependencies
id: deps
continue-on-error: ${{ matrix.experimental }}
run: |
vendor-bin/deptrac/vendor/bin/deptrac --version
vendor-bin/deptrac/vendor/bin/deptrac --formatter=github-actions --report-uncovered
- name: Run Phan
id: phan
continue-on-error: ${{ matrix.experimental }}
env:
XDEBUG_MODE: off
PHAN_DISABLE_XDEBUG_WARN: 1
run: vendor/bin/phan
run: |
vendor-bin/phan/vendor/bin/phan --version
vendor-bin/phan/vendor/bin/phan
- name: Run Psalm
run: vendor/bin/psalm --output-format=github
id: psalm
continue-on-error: ${{ matrix.experimental }}
run: |
vendor-bin/psalm/vendor/bin/psalm --version
vendor-bin/psalm/vendor/bin/psalm --output-format=github
- name: Run Phpstan
run: vendor/bin/phpstan analyse --error-format=github
id: phpstan
continue-on-error: ${{ matrix.experimental }}
run: |
vendor/bin/phpstan --version
vendor/bin/phpstan analyse --error-format=github
- name: Run PHPUnit
run: vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover
- name: Run PHPUnit (unit tests)
id: unit
continue-on-error: ${{ matrix.experimental }}
run: |
vendor/bin/phpunit --version
php -dzend.assertions=1 vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover --testsuite unit
- name: Run PHPUnit (integration tests)
id: integration
continue-on-error: ${{ matrix.experimental }}
run: vendor/bin/phpunit --testsuite integration
- name: Code Coverage
run: bash <(curl -s https://codecov.io/bash)
uses: codecov/codecov-action@v5
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./coverage.clover
flags: ${{ matrix.php-version }}
verbose: false
packages:
uses: opentelemetry-php/gh-workflows/.github/workflows/validate-packages.yml@main
needs: php
with:
matrix_extension: '["ast, json, grpc"]'
matrix_php_version: '["8.1", "8.2", "8.3"]'
install_directory: '~/.test/.packages'

View File

@ -0,0 +1,34 @@
name: "Generate API Documentation"
on:
push:
branches:
- "main"
workflow_dispatch:
permissions:
contents: read
jobs:
documentation:
permissions:
pages: write # required for GitHub Pages deployment
id-token: write # required for GitHub Pages deployment
name: "Documentation"
runs-on: "ubuntu-latest"
steps:
- name: "Checkout"
uses: "actions/checkout@v4"
- name: "Build"
uses: "phpDocumentor/phpDocumentor@v3.8.1"
with:
target: "docs/build"
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: 'docs/build'
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4

View File

@ -1,24 +0,0 @@
name: Psalm Security Analysis
on: [push, pull_request]
jobs:
psalm:
name: Psalm
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Psalm
uses: docker://vimeo/psalm-github-actions
with:
composer_require_dev: true
composer_ignore_platform_reqs: true
security_analysis: true
report_file: results.sarif
- name: Upload Security Analysis results to GitHub
uses: github/codeql-action/upload-sarif@v1
with:
sarif_file: results.sarif

View File

@ -0,0 +1,59 @@
name: publish-otel-php-base-docker-image
on:
schedule:
- cron: "0 0 * * 0"
workflow_dispatch:
push:
paths:
- docker/Dockerfile
- .github/workflows/publish-otel-php-base-docker-image.yml
pull_request:
paths:
- docker/Dockerfile
- .github/workflows/publish-otel-php-base-docker-image.yml
permissions:
contents: read
jobs:
push_to_registry:
name: OpenTelemetry PHP base docker image creation
strategy:
matrix:
php-version: ['8.1', '8.2', '8.3', '8.4']
runs-on: ubuntu-latest
permissions:
packages: write
contents: read
timeout-minutes: 500
steps:
- name: check out the repo
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push ${{ matrix.php-version }} to ghcr.io
uses: docker/build-push-action@v6
if: github.ref != 'refs/heads/main'
with:
push: false
file: docker/Dockerfile
build-args: PHP_VERSION=${{ matrix.php-version }}
platforms: linux/amd64,linux/arm/v8,linux/arm64
- name: Build and push ${{ matrix.php-version }} to ghcr.io
uses: docker/build-push-action@v6
if: github.ref == 'refs/heads/main'
with:
push: true
file: docker/Dockerfile
build-args: PHP_VERSION=${{ matrix.php-version }}
platforms: linux/amd64,linux/arm/v8,linux/arm64
tags: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${{ matrix.php-version }}

22
.github/workflows/shellcheck.yml vendored Normal file
View File

@ -0,0 +1,22 @@
name: Shellcheck
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
permissions:
contents: read
jobs:
shellcheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install shellcheck
run: sudo apt update && sudo apt install --assume-yes shellcheck
- name: Run shellcheck
run: find . -name \*.sh | xargs shellcheck --severity=warning

26
.github/workflows/split-monorepo.yaml vendored Normal file
View File

@ -0,0 +1,26 @@
name: gitsplit
on:
push:
branches:
- main
- split
release:
types: [published]
create:
workflow_dispatch:
permissions:
contents: read
jobs:
gitsplit:
runs-on: ubuntu-latest
steps:
- name: checkout
run: git clone "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY" "$GITHUB_WORKSPACE" && cd "$GITHUB_WORKSPACE" && git checkout $GITHUB_SHA
- name: Split repositories
uses: docker://jderusse/gitsplit:latest
with:
args: gitsplit
env:
GH_TOKEN: ${{ secrets.GITSPLIT_TOKEN }}

34
.gitignore vendored
View File

@ -1,12 +1,38 @@
composer.phar
composer.lock
var
vendor
.idea/
var/
vendor/
vendor-bin/**/vendor/
vendor-bin/**/composer.lock
coverage.clover
tests/coverage
.php_cs.cache
.php-cs-fixer.cache
.phpbench
!tests/coverage/html/.gitkeep
var/metrics/
!var/metrics/.gitkeep
junit.xml
.env
# IntelliJ IDEA
.idea
*.iml
# VS Code
.vscode
# OS X
.DS_Store
# W3C Test Service build artifacts
tests/TraceContext/W3CTestService/test_app
tests/TraceContext/W3CTestService/trace-context
# deptrac cache
/.deptrac.cache
# output from phpdoc
docs/build
# cache from phpdoc
.phpdoc

37
.gitsplit.yml Normal file
View File

@ -0,0 +1,37 @@
# Path to a cache directory Used to speed up the split over time by reusing git's objects
cache_url: "/cache/gitsplit"
# Path to the repository to split (default = current path)
project_url: "https://github.com/open-telemetry/opentelemetry-php.git"
# List of splits.
splits:
- prefix: "proto/otel"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/gen-otlp-protobuf.git"
- prefix: "src/Context"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/context.git"
- prefix: "src/SemConv"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/sem-conv.git"
- prefix: "src/API"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/api.git"
- prefix: "src/SDK"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/sdk.git"
- prefix: "src/Config/SDK"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/config-sdk.git"
- prefix: "src/Contrib/Otlp"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/exporter-otlp.git"
- prefix: "src/Contrib/Grpc"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/transport-grpc.git"
- prefix: "src/Contrib/Zipkin"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/exporter-zipkin.git"
- prefix: "src/Extension/Propagator/B3"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/extension-propagator-b3.git"
- prefix: "src/Extension/Propagator/CloudTrace"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/extension-propagator-cloudtrace.git"
- prefix: "src/Extension/Propagator/Jaeger"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/extension-propagator-jaeger.git"
# List of references to split (defined as regexp)
origins:
- ^main$
- ^split$

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
use Phan\Issue;
/**
@ -42,7 +44,7 @@ return [
//
// Note that the **only** effect of choosing `'5.6'` is to infer that functions removed in php 7.0 exist.
// (See `backward_compatibility_checks` for additional options)
'target_php_version' => '7.3',
'target_php_version' => '8.1',
// If enabled, missing properties will be created when
// they are first seen. If false, we'll report an
@ -278,7 +280,14 @@ return [
// Add any issue types (such as `'PhanUndeclaredMethod'`)
// to this deny-list to inhibit them from being reported.
'suppress_issue_types' => [],
'suppress_issue_types' => [
'PhanAccessClassInternal',
'PhanAccessMethodInternal',
'PhanAccessPropertyInternal',
'PhanTypeMismatchPropertyReal',
'PhanTemplateTypeNotUsedInFunctionReturn',
'PhanUndeclaredClassAttribute',
],
// A regular expression to match files to be excluded
// from parsing and analysis and will not be read at all.
@ -294,7 +303,9 @@ return [
//
// This is useful for excluding hopelessly unanalyzable
// files that can't be removed for whatever reason.
'exclude_file_list' => [],
'exclude_file_list' => [
'vendor/composer/composer/src/Composer/InstalledVersions.php',
],
// A directory list that defines files that will be excluded
// from static analysis, but whose class and method
@ -310,6 +321,7 @@ return [
'exclude_analysis_directory_list' => [
'vendor/',
'proto/',
'src/Config/SDK',
],
// Enable this to enable checks of require/include statements referring to valid paths.
@ -357,19 +369,20 @@ return [
// Thus, both first-party and third-party code being used by
// your application should be included in this list.
'directory_list' => [
'api',
'Context',
'sdk',
'contrib',
'proto',
'vendor/composer/xdebug-handler/src',
'src',
'proto/otel/GPBMetadata',
'proto/otel/Opentelemetry',
'vendor/composer',
'vendor/grpc/grpc/src/lib',
'vendor/guzzlehttp',
'vendor/tbachert/spi/src',
'vendor/psr',
'vendor/php-http',
'vendor/phan/phan/src/Phan',
'vendor/phpunit/phpunit/src',
'vendor/promphp/prometheus_client_php/src',
'vendor/google/protobuf/src'
'vendor/google/protobuf/src',
'vendor/ramsey/uuid/src',
'vendor/nyholm/psr7-server/src',
'vendor/symfony/config',
],
// A list of individual files to include in analysis

View File

@ -1,11 +1,14 @@
<?php
declare(strict_types=1);
$finder = PhpCsFixer\Finder::create()
->exclude('vendor')
->exclude('var/cache')
->exclude('proto')
->in(__DIR__);
->in('examples/')
->in('tests/')
->in('src/');
$config = new PhpCsFixer\Config();
return $config->setRules([
'concat_space' => ['spacing' => 'one'],
'declare_equal_normalize' => ['space' => 'none'],
@ -13,6 +16,7 @@ return $config->setRules([
'modernize_types_casting' => true,
'ordered_imports' => true,
'php_unit_construct' => true,
'php_unit_method_casing' => ['case' => 'snake_case'],
'single_line_comment_style' => true,
'yoda_style' => false,
'@PSR2' => true,
@ -21,12 +25,15 @@ return $config->setRules([
'blank_line_before_statement' => true,
'cast_spaces' => true,
'declare_strict_types' => true,
'function_typehint_space' => true,
'type_declaration_spaces' => true,
'include' => true,
'lowercase_cast' => true,
'new_with_braces' => true,
'new_with_parentheses' => true,
'no_blank_lines_after_class_opening' => true,
'no_extra_blank_lines' => true,
'no_leading_import_slash' => true,
'no_trailing_whitespace' => true,
'no_whitespace_in_blank_line' => true,
'echo_tag_syntax' => true,
'no_unused_imports' => true,
'no_useless_else' => true,
@ -35,9 +42,9 @@ return $config->setRules([
'phpdoc_scalar' => true,
'phpdoc_types' => true,
'short_scalar_cast' => true,
'single_blank_line_before_namespace' => true,
'blank_lines_before_namespace' => true,
'single_quote' => true,
'trailing_comma_in_multiline' => true,
'trailing_comma_in_multiline' => ['elements' => ['arrays', 'parameters', 'match']],
])
->setRiskyAllowed(true)
->setFinder($finder);

View File

@ -12,4 +12,4 @@
# https://help.github.com/en/articles/about-code-owners
#
* @bobstrecansky @beniamin @zsistla
* @open-telemetry/php-approvers

View File

@ -1,19 +1,319 @@
Maintainers ([@open-telemetry/php-maintainers](https://github.com/orgs/open-telemetry/teams/php-maintainers)):
# Contributing Guide
- [Bob Strecansky](https://github.com/bobstrecansky), Mailchimp
## Introduction
Find more about the maintainer role in [community repository](https://github.com/open-telemetry/community/blob/master/community-membership.md#maintainer)
Welcome to the OpenTelemetry PHP repository! We appreciate your interest in contributing and helping improve this project. No contribution is too small—whether you're fixing a typo, improving documentation, or implementing a major feature, we value your help.
Approvers ([@open-telemetry/php-approvers](https://github.com/orgs/open-telemetry/teams/php-approvers)):
This repository is part of the larger OpenTelemetry ecosystem, aimed at providing observability solutions for PHP applications. If you have any questions, feel free to ask in our community channels (See further help below). Your contributions make a difference!
- [Levi Morrison](https://github.com/morrisonlevi), Datadog
- [Austin Schoen](https://github.com/AustinSchoen), Mailchimp
- [Beniamin Calota](https://github.com/beniamin), eMag
## Pre-requisites
Find more information about the approver role in the [community repository](https://github.com/open-telemetry/community/blob/master/community-membership.md#approver)
To contribute effectively, ensure you have the following tools installed:
Triagers ([@open-telemetry/php-triagers](https://github.com/orgs/open-telemetry/teams/php-triagers)):
* PHP 8.1 or higher (Check supported PHP versions)
- [Jodee Varney](https://github.com/jodeev), Splunk
We aim to support officially supported PHP versions, according to https://www.php.net/supported-versions.php. The
developer image `ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base` is tagged as `8.1`, `8.2` and `8.3`
respectively, with `8.1` being the default. You can execute the test suite against other PHP versions by running the
following command:
Find more information about the triager role in the [community repository](https://github.com/open-telemetry/community/blob/master/community-membership.md#triager)
```bash
PHP_VERSION=8.1 make all
#or
PHP_VERSION=8.3 make all
```
For repeatability and consistency across different operating systems, we use the [3 Musketeers pattern](https://3musketeers.pages.dev/). If you're on Windows, it might be a good idea to use Git bash for following the steps below.
**Note: After cloning the repository, copy `.env.dist` to `.env`.**
Skipping the step above would result in a "`The "PHP_USER" variable is not set. Defaulting to a blank string`" warning
We use `docker` and `docker compose` to perform a lot of our static analysis and testing. If you're planning to develop for this library, it'll help to install
[docker engine](https://docs.docker.com/engine/install/) and the [compose plugin](https://docs.docker.com/compose/install/).
Development tasks are generally run through a `Makefile`. Running `make` or `make help` will list available targets.
## Workflow
### Pull Requests
To propose changes to the codebase, you need
to [open a pull request](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request)
to the opentelemetry-php project.
After you open the pull request, the CI will run all the
associated [github actions](https://github.com/open-telemetry/opentelemetry-php/actions/workflows/php.yml).
To ensure your PR doesn't emit a failure with GitHub actions, it's recommended that you run the important CI tests locally with the following command:
```bash
make all # composer update, then run all checks
make all-lowest # composer update to lowest dependencies, then run all checks
```
This does the following things:
* Installs/updates all the required dependencies for the project
* Uses [Rector](https://github.com/rectorphp/rector) to refactor your code according to our standards.
* Uses [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) to style your code using our style preferences.
* Uses [Deptrac](https://github.com/qossmic/deptrac) to check for dependency violations inside our code base
* Makes sure the composer files for the different components are valid
* Runs all of our [phpunit](https://phpunit.de/) unit tests.
* Performs static analysis with [Phan](https://github.com/phan/phan), [Psalm](https://psalm.dev/)
and [PHPStan](https://phpstan.org/user-guide/getting-started)
## Local Run/Build
To ensure you have all the correct packages installed locally in your dev environment, you can run
```bash
make install
```
This will install all the library dependencies to
the `/vendor` directory.
To update these dependencies, you can run
```bash
make update
```
To downgrade to the lowest dependencies, you can run
```shell
make update-lowest
```
To run all checks without doing a composer update:
```shell
make all-checks
```
## Testing
To make sure the tests in this repo work as you expect, you can use the included docker test wrapper.
To run the test suite, execute
```bash
make test
```
This will output the test output as well as a test coverage analysis (text + html - see `tests/coverage/html`). Code
that doesn't pass our currently defined tests will emit a failure in CI
## Contributing Rules
Even though it may not be reflected everywhere in the codebase yet, we aim to provide software which is easy to read and change.
The methods described in Clean Code book(s) by Robert C. Martin (Uncle Bob) are a de facto industry standards nowadays.
Reading those books is highly recommended, however you can take a look at the examples given at [Clean Code PHP](https://github.com/jupeter/clean-code-php).
While we have no rule to strictly follow said methods and patterns, they are highly recommended as an orientation for
your pull requests and to be referenced in reviews.
We might add additional guidelines regarding for example testing in the future.
## Additional Information
### Automatic Refactoring and Upgrading
We use [Rector](https://github.com/rectorphp/rector) to automatically refactor our code according to given standards
and upgrade the code to supported PHP versions.
The associated configuration can be found [here](./.rector.php)
If you want to check what changes would be applied by rector, you can run:
```bash
make rector
```
This command will simply print out the changes `rector` would make without actually changing any code.
To refactor your code following our given standards, you can run:
```bash
make rector-write
```
This command applies the changes to the code base.
Make sure to run `make style` (see below) after running the `rector`command as the changes might not follow our coding standard.
### Styling
We use [PHP-CS-Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) for our code linting and standards fixer. The
associated configuration can be found [here](./.php-cs-fixer.php)
To ensure that your code follows our coding standards, you can run:
```bash
make style
```
This command executes a required check that also runs during CI. This process performs the required fixes and prints them
out. Code that doesn't meet the style pattern will emit a failure with GitHub actions.
### Static Analysis
We use [Phan](https://github.com/phan/phan/) for static analysis. Currently, our phan configuration is just a standard
default analysis configuration. You can use our phan docker wrapper to easily perform static analysis on your changes.
To run Phan, one can run the following command:
```bash
make phan
```
This process will return 0 on success. Usually this process is performed as part of a code checkin. This process runs
during CI and is a required check. Code that doesn't match the standards that we have defined in
our [phan config](https://github.com/open-telemetry/opentelemetry-php/blob/master/.phan/config.php) will emit a failure
in CI.
We also use [Psalm](https://psalm.dev/) as a second static analysis tool.
You can use our psalm docker wrapper to easily perform static analysis on your changes.
To run Psalm, one can run the following command:
```bash
make psalm
```
This process will return 0 on success. Usually this process is performed as part of a code checkin. This process runs
during CI and is a required check. Code that doesn't match the standards that we have defined in
our [psalm config](https://github.com/open-telemetry/opentelemetry-php/blob/main/psalm.xml.dist) will emit a failure in
CI.
We use [PHPStan](https://github.com/phpstan/phpstan) as our third tool for static analysis. You can use our PHPStan
docker wrapper to easily perform static analysis on your changes.
To perform static analysis with PHPStan run:
```bash
make phpstan
```
This process will return 0 on success. Usually this process is performed as part of a code checkin. This process runs
during CI and is a required check. Code that doesn't match the standards that we have defined in
our [PHPStan config](https://github.com/open-telemetry/opentelemetry-php/blob/main/phpstan.neon.dist) will emit a
failure in CI.
### Code Coverage
We use [codecov.io](https://about.codecov.io/) to track code coverage for this repo. This is configured in the [php.yaml github action](https://github.com/open-telemetry/opentelemetry-php/blob/main/.github/workflows/php.yml#L71-L72). We don't require a specific level of code coverage for PRs to pass - we just use this tool in order to understand how a PR will potentially change the amount of code coverage we have across the code base. This tool isn't perfect - sometimes we'll see small deltas in code coverage where there shouldn't be any - this is nothing to fret about.
If code coverage does decrease on a pull request, you will see a red X in the CI for the repo, but that's ok - the reviewer will use their judgement to determine whether or not we have sufficient code coverage for the change.
### Dependency Validation
To make sure the different components of the library are distributable as separate packages, we have to check
for dependency violations inside the code base. Dependencies must create a [DAC](https://en.wikipedia.org/wiki/Directed_acyclic_graph) in order to not create recursive dependencies.
For this purpose we use [Deptrac](https://github.com/qossmic/deptrac) and the respective configuration can be found
[here](./deptrac.yaml)
To validate the dependencies inside the code base, you can run:
```bash
make deptrac
```
This command will create an error for any violation of the defined dependencies. If you add new dependencies to the code base,
please configure them in the rector configuration.
## PhpMetrics
To generate a report showing a variety of metrics for the library and its classes, you can run:
```bash
make phpmetrics
```
This will generate a HTML PhpMetrics report in the `var/metrics` directory. Make sure to run `make test` before to
create the test log-file, used by the metrics report.
### Proto Generation
Our protobuf files are committed to the repository into the `/proto` folder. These are used in gRPC connections to the
upstream. These get updated when the [opentelemetry-proto](https://github.com/open-telemetry/opentelemetry-proto)
repo has a meaningful update. The maintainer SIG is discussing a way to make this more automatic in the future.
To generate protobuf files for use with this repository, you can run the following command:
```bash
make protobuf
```
This will replace `proto/otel/Opentelemetry` and `proto/otel/GPBMetadata` with freshly generated code based on the
latest tag from `opentelemetry-proto`, which can then be committed.
### Semantic Conventions Generation
Autogenerated semantic convention files are committed to the repository in the `/src/SemConv` directory. These files are
updated manually when a new version of [semantic-conventions](https://github.com/open-telemetry/semantic-conventions) is
released.
```bash
SEMCONV_VERSION=1.8.0 make semconv
```
Run this command in the root of this repository.
### API Documentation
We use [phpDocumentor](https://phpdoc.org/) to automatically generate API documentation from DocBlocks in the code.
To generate a recent version of the API documentation, you can run:
```bash
make phpdoc
```
To preview the documentation and changes you might expect, you can run:
```bash
make phpdoc-preview
```
This will start a HTTP server running at <http://localhost:8080> serving the updated documentation files.
## Maintainers
- [Bob Strecansky](https://github.com/bobstrecansky), Intuit
- [Brett McBride](https://github.com/brettmc/), Deakin University
For more information about the maintainer role, see the [community repository](https://github.com/open-telemetry/community/blob/main/community-membership.md#maintainer).
## Approvers
- [Ago Allikmaa](https://github.com/agoallikmaa)
- [Cedriz Ziel](https://github.com/cedricziel)
- [Chris Lightfoot-Wild](https://github.com/ChrisLightfootWild)
For more information about the approver role, see the [community repository](https://github.com/open-telemetry/community/blob/main/community-membership.md#approver).
## Triagers
For more information about the triager role, see the [community repository](https://github.com/open-telemetry/community/blob/main/community-membership.md#triagers).
## Emeritus maintainers/approvers/triagers
- [Amber Zsistla](https://github.com/zsistla)
- [Beniamin Calota](https://github.com/beniamin)
- [Fahmy Mohammed](https://github.com/Fahmy-Mohammed)
- [Jodee Varney](https://github.com/jodeev)
- [Levi Morrison](https://github.com/morrisonlevi)
- [Przemek Delewski](https://github.com/pdelewski)
- [Timo Michna](https://github.com/tidal/)
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).
## Further Help
Most of our communication is done on CNCF Slack in the channel [otel-php](https://cloud-native.slack.com/archives/C01NFPCV44V).
To sign up, create a CNCF Slack account [here](http://slack.cncf.io/)
Our meetings are held weekly on zoom on Wednesdays at 10:30am PST / 1:30pm EST.
A Google calendar invite with the included zoom link can be found [here](https://calendar.google.com/event?action=TEMPLATE&tmeid=N2VtZXZmYnVmbzZkYjZkbTYxdjZvYTdxN21fMjAyMDA5MTZUMTczMDAwWiBrYXJlbnlyeHVAbQ&tmsrc=google.com_b79e3e90j7bbsa2n2p5an5lf60%40group.calendar.google.com&scp=ALL)
Our open issues can all be found in the [GitHub issues tab](https://github.com/open-telemetry/opentelemetry-php/issues). Feel free to reach out on Slack if you have any additional questions about these issues; we are always happy to talk through implementation details.
#### Thanks to all the people who already contributed!
<a href="https://github.com/open-telemetry/opentelemetry-php/graphs/contributors">
<img src="https://contributors-img.web.app/image?repo=open-telemetry/opentelemetry-php" />
</a>

View File

@ -1,180 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Context;
/**
* @template TContext of Context
*/
class Context
{
/**
* @var ContextKey|null
*/
protected $key;
/**
* @var mixed|null
*/
protected $value;
/**
* @var TContext|null
*/
protected $parent;
protected static $current_context = null;
/**
* This is a general purpose read-only key-value store. Read-only in the sense that adding a new value does not
* mutate the existing context, but returns a new Context which has the new value added.
*
* In practical terms, this is implemented as a linked list of Context instances, with each one holding a reference
* to the key object, the value that corresponds to the key, and an optional reference to the parent Context
* (i.e. the next link in the linked list chain)
*
* If you inherit from this class, you should "shadow" $parent into your subclass so that all operations give
* you back an instance of the same type that you are interacting with and different subclasses should NOT be
* treated as interoperable. i.e. you should NOT have a Context object chain with both Context instances interleaved
* with Baggage instances.
*
* @param ContextKey|null $key The key object. Should only be null when creating an "empty" context
* @param mixed|null $value
* @param TContext|null $parent Reference to the parent object
*/
final public function __construct(?ContextKey $key=null, $value=null, $parent=null)
{
$this->key = $key;
$this->value = $value;
$this->parent = $parent;
}
/**
* This adds a k/v pair to this Context. We do this by instantiating a new Context instance with the k/v and pass
* a reference to $this as the "parent" creating the linked list chain.
*
* @param ContextKey $key
* @param mixed $value
*
* @return Context a new Context containing the k/v
*/
public function set(ContextKey $key, $value)
{
return new static($key, $value, $this);
}
/**
* This is a static version of set().
* This is primarily useful when the caller doesn't already have a reference to a Context that they want to mutate.
*
* There are two ways to call this function.
* 1) With a $parent parameter:
* Context::setValue($key, $value, $ctx) is functionally equivalent to $ctx->set($key, $value)
* 2) Without a $parent parameter:
* In this scenario, setValue() will use the `$current_context` reference as supplied by `getCurrent()`
* `getCurrent()` will always return a valid Context. If one does not exist at the global scope,
* an "empty" context will be created.
*
* @param ContextKey $key
* @param mixed $value
* @param Context|null $parent
*
* @return Context a new Context containing the k/v
*/
public static function setValue(ContextKey $key, $value, $parent=null)
{
if (null === $parent) {
return static::$current_context = new static($key, $value, static::getCurrent());
}
return new static($key, $value, $parent);
}
/**
* Fetch a value from the Context given a key value.
*
* @param ContextKey $key
*
* @throws ContextValueNotFoundException
* @return mixed
* @suppress PhanUndeclaredClassMethod
*/
public function get(ContextKey $key)
{
if ($this->key === $key) {
return $this->value;
}
if (null === $this->parent) {
throw new ContextValueNotFoundException();
}
return $this->parent->get($key);
}
/**
* Static version of get()
* This is primarily useful when the caller doesn't already have a reference to the Context that they want to mutate.
* This will operate on the "current" global context in that scenario.
*
* There are two ways to call this function:
* 1) With a $ctx value:
* Context::getValue($key, $ctx) is functionally equivalent to $ctx->get($key)
* 2) Without a $ctx value:
* This will fetch the "current" Context if one exists or create one if not, then attempt to get the value from it.
*
* @param ContextKey $key
* @param Context|null $ctx
*
* @throws ContextValueNotFoundException
* @return mixed
*/
public static function getValue(ContextKey $key, $ctx=null)
{
$ctx = $ctx ?? static::getCurrent();
return $ctx->get($key);
}
/**
* @return Context
*/
public static function getCurrent()
{
if (null === static::$current_context) {
static::$current_context = new static();
}
return static::$current_context;
}
/**
* This will set the given Context to be the "current" one. We return a token which can be passed to `detach()` to
* reset the Current Context back to the previous one.
*
* @param Context $ctx
*
* @return callable token for resetting the $current_context back
*/
public static function attach($ctx): callable
{
$former_ctx = static::$current_context;
static::$current_context = $ctx;
return function () use ($former_ctx) {
return $former_ctx;
};
}
/**
* Given a token, the current context will be set back to the one prior to the token being generated.
*
* @param callable $token
*
* @return Context
*/
public static function detach(callable $token)
{
return static::$current_context = call_user_func($token);
}
}

View File

@ -1,23 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Context;
class ContextKey
{
/**
* @var string|null
*/
private $name;
public function __construct(?string $name=null)
{
$this->name = $name;
}
public function name(): ?string
{
return $this->name;
}
}

View File

@ -1,60 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Context;
trait ContextValueTrait
{
/**
* @param Context $context
* @return mixed|null
* @phan-suppress PhanAbstractStaticMethodCallInTrait
*/
public static function extract(Context $context)
{
try {
return $context->get(static::getContextKey());
} catch (ContextValueNotFoundException $e) {
return null;
}
}
/**
* @param mixed $value
* @param Context $context
* @return Context
* @phan-suppress PhanAbstractStaticMethodCallInTrait
*/
public static function insert($value, Context $context): Context
{
return $context->set(static::getContextKey(), $value);
}
/**
* @param mixed $value
* @return Scope
* @phan-suppress PhanAbstractStaticMethodCallInTrait
*/
public static function setCurrent($value): Scope
{
$context = Context::getCurrent()->set(static::getContextKey(), $value);
return new Scope(Context::attach($context));
}
/**
* @return mixed|null
* @phan-suppress PhanAbstractStaticMethodCallInTrait
*/
public static function getCurrent()
{
try {
return Context::getCurrent()->get(static::getContextKey());
} catch (ContextValueNotFoundException $e) {
return null;
}
}
abstract protected static function getContextKey(): ContextKey;
}

View File

@ -1,21 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Context;
class Scope
{
/** @var callable Context token, result of Context::attach() */
private $contextToken;
public function __construct(callable $contextToken)
{
$this->contextToken = $contextToken;
}
public function close(): void
{
Context::detach($this->contextToken);
}
}

144
Makefile
View File

@ -1,44 +1,114 @@
DC_RUN_PHP = docker-compose run --rm php
include .env
install:
$(DC_RUN_PHP) composer install
update:
$(DC_RUN_PHP) composer update
test:
$(DC_RUN_PHP) php ./vendor/bin/phpunit --colors=always --coverage-text --testdox --coverage-clover coverage.clover
phan:
$(DC_RUN_PHP) env PHAN_DISABLE_XDEBUG_WARN=1 php ./vendor/bin/phan
psalm:
$(DC_RUN_PHP) php ./vendor/bin/psalm
psalm-info:
$(DC_RUN_PHP) php ./vendor/bin/psalm --show-info=true
phpstan:
$(DC_RUN_PHP) php ./vendor/bin/phpstan analyse
trace examples: FORCE
docker-compose up -d --remove-orphans
$(DC_RUN_PHP) php ./examples/AlwaysOnZipkinExample.php
$(DC_RUN_PHP) php ./examples/AlwaysOffTraceExample.php
$(DC_RUN_PHP) php ./examples/AlwaysOnJaegerExample.php
# The following examples do not use the DC_RUN_PHP global because they need environment variables.
docker-compose run -e NEW_RELIC_ENDPOINT -e NEW_RELIC_INSERT_KEY --rm php php ./examples/AlwaysOnNewrelicExample.php
docker-compose run -e NEW_RELIC_ENDPOINT -e NEW_RELIC_INSERT_KEY --rm php php ./examples/AlwaysOnZipkinToNewrelicExample.php
docker-compose stop
collector:
docker-compose -f docker-compose-collector.yaml up -d --remove-orphans
docker-compose -f docker-compose-collector.yaml run -e OTEL_EXPORTER_OTLP_ENDPOINT=otel-collector:4317 --rm php php ./examples/AlwaysOnOTLPGrpcExample2.php
docker-compose -f docker-compose-collector.yaml stop
PHP_VERSION ?= 8.1
DOCKER_COMPOSE ?= docker compose
DC_RUN_PHP = $(DOCKER_COMPOSE) run --rm php
.DEFAULT_GOAL : help
.PHONY: deptrac
help: ## Show this help
@printf "\033[33m%s:\033[0m\n" 'Available commands'
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z0-9_-]+:.*?## / {printf " \033[32m%-18s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
all: update all-checks ## Update to latest and run all checks
all-lowest: update-lowest all-checks ## Update to lowest dependencies and run all checks
all-checks: rector style deptrac packages-composer phan psalm phpstan test ## Run all checks
pull: ## Pull latest developer image
$(DOCKER_COMPOSE) pull php
build: ## Build developer image locally
docker build docker/ --build-arg PHP_VERSION=${PHP_VERSION} -t ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION}
install: ## Install dependencies
$(DC_RUN_PHP) env XDEBUG_MODE=off composer install
update: ## Update dependencies
$(DC_RUN_PHP) env XDEBUG_MODE=off composer update
update-lowest: ## Update dependencies to lowest supported versions
$(DC_RUN_PHP) env XDEBUG_MODE=off composer update --prefer-lowest
test: test-unit test-integration ## Run unit and integration tests
test-unit: ## Run unit tests
$(DC_RUN_PHP) env XDEBUG_MODE=coverage vendor/bin/phpunit --testsuite unit --colors=always
test-integration: ## Run integration tests
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/phpunit --testsuite integration --colors=always
test-verbose: ## Run unit tests with verbose (testdox) output
$(DC_RUN_PHP) env XDEBUG_MODE=coverage vendor/bin/phpunit --testsuite unit --colors=always --testdox --coverage-clover coverage.clover --coverage-html=tests/coverage/html --log-junit=junit.xml
test-coverage: ## Run units tests and generate code coverage
$(DC_RUN_PHP) env XDEBUG_MODE=coverage vendor/bin/phpunit --testsuite unit --coverage-html=tests/coverage/html
test-compliance: ## Run compliance tests
$(DC_RUN_PHP) env XDEBUG_MODE=coverage vendor/bin/phpunit --group compliance
test-trace-compliance: ## Run trace compliance tests
$(DC_RUN_PHP) env XDEBUG_MODE=coverage vendor/bin/phpunit --group trace-compliance
phan: ## Run phan
$(DC_RUN_PHP) env XDEBUG_MODE=off env PHAN_DISABLE_XDEBUG_WARN=1 vendor-bin/phan/vendor/bin/phan
psalm: ## Run psalm
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/psalm/vendor/bin/psalm --threads=1 --no-cache
psalm-info: ## Run psalm and show info
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/psalm/vendor/bin/psalm --show-info=true --threads=1
phpdoc: ## Run phpdoc
$(DOCKER_COMPOSE) -f docker-compose.phpDocumentor.yaml run --rm phpdoc
phpdoc-preview:
$(DOCKER_COMPOSE) -f docker-compose.phpDocumentor.yaml run --service-ports --rm preview
phpstan: ## Run phpstan
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/phpstan analyse --memory-limit=256M
infection: ## Run infection (mutation testing)
$(DC_RUN_PHP) env XDEBUG_MODE=coverage php -d memory_limit=1024M vendor-bin/infection/vendor/bin/infection --threads=max
packages-composer: ## Validate composer packages
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/otel packages:composer:validate
benchmark: ## Run phpbench
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/phpbench/vendor/bin/phpbench run --report=default
phpmetrics: ## Run php metrics
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/phpmetrics/vendor/bin/phpmetrics --config=./phpmetrics.json --junit=junit.xml
smoke-test-examples: smoke-test-isolated-examples smoke-test-exporter-examples smoke-test-collector-integration smoke-test-prometheus-example ## Run smoke test examples
smoke-test-isolated-examples: ## Run smoke test isolated examples
$(DC_RUN_PHP) php ./examples/traces/getting_started.php
$(DC_RUN_PHP) php ./examples/traces/features/batch_exporting.php
$(DC_RUN_PHP) php ./examples/traces/features/concurrent_spans.php
$(DC_RUN_PHP) php ./examples/traces/features/configuration_from_environment.php
$(DC_RUN_PHP) php ./examples/traces/features/creating_a_new_trace_in_the_same_process.php
$(DC_RUN_PHP) php ./examples/traces/features/resource_detectors.php
$(DC_RUN_PHP) php ./examples/traces/features/span_resources.php
$(DC_RUN_PHP) php ./examples/traces/troubleshooting/air_gapped_trace_debugging.php
$(DC_RUN_PHP) php ./examples/traces/troubleshooting/logging_of_span_data.php
$(DC_RUN_PHP) php ./examples/traces/troubleshooting/setting_up_logging.php
smoke-test-exporter-examples: FORCE ## Run (some) exporter smoke test examples
# Note this does not include every exporter at the moment
$(DOCKER_COMPOSE) up -d --remove-orphans
$(DC_RUN_PHP) php ./examples/traces/exporters/zipkin.php
$(DC_RUN_PHP) php ./examples/traces/features/parent_span_example.php
smoke-test-collector-integration: ## Run smoke test collector integration
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml up -d --remove-orphans
sleep 5
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml run --rm php php ./examples/traces/exporters/otlp_grpc.php
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml run --rm php php ./examples/traces/exporters/otlp_http.php
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml stop
smoke-test-collector-metrics-integration:
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml up -d --force-recreate collector
COMPOSE_IGNORE_ORPHANS=TRUE $(DOCKER_COMPOSE) -f docker-compose.yaml run --rm php php ./examples/metrics/features/exporters/otlp_http.php
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml logs collector
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml stop collector
smoke-test-prometheus-example: metrics-prometheus-example stop-prometheus
metrics-prometheus-example:
@docker-compose -f docker-compose.prometheus.yaml up -d web
@docker-compose -f docker-compose.prometheus.yaml run php-prometheus php /var/www/public/examples/prometheus/PrometheusMetricsExample.php
@$(DOCKER_COMPOSE) -f docker-compose.prometheus.yaml -p opentelemetry-php_metrics-prometheus-example up -d web
# This is slow because it's building the image from scratch (and parts of that, like installing the gRPC extension, are slow)
@$(DOCKER_COMPOSE) -f docker-compose.prometheus.yaml -p opentelemetry-php_metrics-prometheus-example run --rm php php examples/metrics/prometheus/prometheus_metrics_example.php
stop-prometheus:
@docker-compose -f docker-compose.prometheus.yaml stop
proto:
@docker-compose -f docker-compose.proto.yaml up proto
bash:
@$(DOCKER_COMPOSE) -f docker-compose.prometheus.yaml -p opentelemetry-php_metrics-prometheus-example stop
fiber-ffi-example:
@$(DOCKER_COMPOSE) -f docker-compose.fiber-ffi.yaml -p opentelemetry-php_fiber-ffi-example up -d web
protobuf: ## Generate protobuf files
./script/proto_gen.sh
bash: ## bash shell into container
$(DC_RUN_PHP) bash
style:
$(DC_RUN_PHP) php ./vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --stop-on-violation --using-cache=no -vvv
style: ## Run style check/fix
$(DC_RUN_PHP) env XDEBUG_MODE=off env PHP_CS_FIXER_IGNORE_ENV=1 vendor-bin/php-cs-fixer/vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --using-cache=no -vvv
rector-write: ## Run rector
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/rector/vendor/bin/rector process
rector: ## Run rector (dry-run)
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/rector/vendor/bin/rector process --dry-run
deptrac: ## Run deptrac
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/deptrac/vendor/bin/deptrac --formatter=table --report-uncovered --no-cache
w3c-test-service:
@docker-compose -f docker-compose.w3cTraceContext.yaml run --rm php ./tests/TraceContext/W3CTestService/symfony-setup
@$(DOCKER_COMPOSE) -f docker-compose.w3cTraceContext.yaml run --rm php ./tests/TraceContext/W3CTestService/trace-context-test.sh
semconv: ## Generate semconv files
./script/semantic-conventions/semconv.sh
split: ## Run git split
$(DOCKER_COMPOSE) -f docker/gitsplit/docker-compose.yaml --env-file ./.env up
FORCE:

201
README.md
View File

@ -1,189 +1,56 @@
# OpenTelemetry php library
# OpenTelemetry for PHP
![CI Build](https://github.com/open-telemetry/opentelemetry-php/workflows/PHP%20Composer/badge.svg)
![CI Build](https://github.com/open-telemetry/opentelemetry-php/workflows/PHP%20QA/badge.svg)
[![codecov](https://codecov.io/gh/open-telemetry/opentelemetry-php/branch/master/graph/badge.svg)](https://codecov.io/gh/open-telemetry/opentelemetry-php)
[![Slack](https://img.shields.io/badge/slack-@cncf/otel--php-brightgreen.svg?logo=slack)](https://cloud-native.slack.com/archives/D03FAB6GN0K)
## Current Project Status
![Current Version](https://img.shields.io/github/v/tag/open-telemetry/opentelemetry-php)
This is the **[monorepo](https://en.wikipedia.org/wiki/Monorepo)** for the **main** components of [OpenTelemetry](https://opentelemetry.io/) for PHP.
This project currently lives in a pre-alpha status. Our current release is not production ready; it has been created in order to receive feedback from the community.
## Documentation
We attempt to keep the [OpenTelemetry Specification Matrix](https://github.com/open-telemetry/opentelemetry-specification/blob/master/spec-compliance-matrix.md) up to date in order to show which features are available and which have not yet been implemented.
Please read the official documentation: https://opentelemetry.io/docs/instrumentation/php/
If you find an inconsistency in the data in the matrix vs. the data in this repository, please let us know in our slack channel and we'll get it rectified.
## Communication
Most of our communication is done on CNCF Slack, in the [otel-php](https://cloud-native.slack.com/archives/C01NFPCV44V) channel. To sign up, create a CNCF slack account here http://slack.cncf.io/
API Documentation is available here: https://open-telemetry.github.io/opentelemetry-php/
Our meetings are held weekly on zoom on Wednesdays at 10:30am PST / 1:30pm EST.
A Google calendar invite with the included zoom link can be found [here](https://calendar.google.com/event?action=TEMPLATE&tmeid=N2VtZXZmYnVmbzZkYjZkbTYxdjZvYTdxN21fMjAyMDA5MTZUMTczMDAwWiBrYXJlbnlyeHVAbQ&tmsrc=google.com_b79e3e90j7bbsa2n2p5an5lf60%40group.calendar.google.com&scp=ALL)
## Packages and versions
Our open issues can all be found in the [github issues tab](https://github.com/open-telemetry/opentelemetry-php/issues). Feel free to reach out on Slack if you have any additional questions about these issues; we are always happy to talk through implementation details.
| Package | Latest |
|----------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| API | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/api/v/stable)](https://packagist.org/packages/open-telemetry/api/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/api/v/unstable)](https://packagist.org/packages/open-telemetry/api/) |
| SDK | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/sdk/v/stable)](https://packagist.org/packages/open-telemetry/sdk/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/sdk/v/unstable)](https://packagist.org/packages/open-telemetry/sdk/) |
| Context | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/context/v/stable)](https://packagist.org/packages/open-telemetry/context/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/context/v/unstable)](https://packagist.org/packages/open-telemetry/context/) |
| Semantic Conventions | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/sem-conv/v/stable)](https://packagist.org/packages/open-telemetry/sem-conv/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/sem-conv/v/unstable)](https://packagist.org/packages/open-telemetry/sem-conv/) |
| OTLP Exporter | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/exporter-otlp/v/stable)](https://packagist.org/packages/open-telemetry/exporter-otlp/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/exporter-otlp/v/unstable)](https://packagist.org/packages/open-telemetry/exporter-otlp/) |
| gRPC Transport | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/transport-grpc/v/stable)](https://packagist.org/packages/open-telemetry/transport-grpc/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/transport-grpc/v/unstable)](https://packagist.org/packages/open-telemetry/transport-grpc/) |
| OTLP Protobuf Files | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/gen-otlp-protobuf/v/stable)](https://packagist.org/packages/open-telemetry/gen-otlp-protobuf/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/gen-otlp-protobuf/v/unstable)](https://packagist.org/packages/open-telemetry/gen-otlp-protobuf/) |
| B3 Propagator | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/extension-propagator-b3/v/stable)](https://packagist.org/packages/open-telemetry/extension-propagator-b3/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/extension-propagator-b3/v/unstable)](https://packagist.org/packages/open-telemetry/extension-propagator-b3/) |
## Installation
The recommended way to install the library is through [Composer](http://getcomposer.org):
Releases for both this repository and [contrib](https://github.com/open-telemetry/opentelemetry-php-contrib) are
based on read-only [git subtree splits](https://github.com/splitsh/lite) from our monorepo. You should refer to
[packagist.org](https://packagist.org/packages/open-telemetry/) for all packages, their versions and details.
1.) Install the composer package using [Composer's installation instructions](https://getcomposer.org/doc/00-intromd#installation-linux-unix-macos).
You can also look at the read-only repositories, which live in the
[opentelemetry-php](https://github.com/opentelemetry-php) organization.
2.) Add
```bash
"minimum-stability": "dev"
```
## Contributing
To your project's `composer.json` file, as this utility has not reached a stable release status yet.
[![GitHub repo Good Issues for newbies](https://img.shields.io/github/issues/open-telemetry/opentelemetry-php/good%20first%20issue?style=flat&logo=github&logoColor=green&label=Good%20First%20issues)](https://github.com/open-telemetry/opentelemetry-php/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) [![GitHub Help Wanted issues](https://img.shields.io/github/issues/open-telemetry/opentelemetry-php/help%20wanted?style=flat&logo=github&logoColor=b545d1&label=%22Help%20Wanted%22%20issues)](https://github.com/open-telemetry/opentelemetry-php/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) [![GitHub Help Wanted PRs](https://img.shields.io/github/issues-pr/open-telemetry/opentelemetry-php/help%20wanted?style=flat&logo=github&logoColor=b545d1&label=%22Help%20Wanted%22%20PRs)](https://github.com/open-telemetry/opentelemetry-php/pulls?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) [![GitHub repo Issues](https://img.shields.io/github/issues/open-telemetry/opentelemetry-php?style=flat&logo=github&logoColor=red&label=Issues)](https://github.com/open-telemetry/opentelemetry-php/issues?q=is%3Aopen)
2.) Install the dependency with composer:
We would love to have you on board, please see our [Contributing README](./CONTRIBUTING.md)
```bash
$ composer require open-telemetry/opentelemetry
```
## Specification conformance
## Development
We use `docker` and `docker-compose` to perform a lot of our static analysis and testing.
We attempt to keep the [OpenTelemetry Specification Matrix](https://github.com/open-telemetry/opentelemetry-specification/blob/master/spec-compliance-matrix.md) up to date in order to show which features are available and which have not yet been implemented.
If you're planning to develop for this library, it'll help to install `docker engine` and `docker-compose`.
If you find an inconsistency in the data in the matrix, please let us know in our slack channel and we'll get it rectified.
You can find installation instructions for these packages can be found [here](https://docs.docker.com/install/), under the `Docker Engine` and `Docker Compose` submenus respectively.
## Backwards compatibility
To ensure you have all the correct packages installed locally in your dev environment, you can run
See [compatibility readme](src/SDK/Common/Dev/Compatibility/README.md).
```bash
make install
```
From your bash compatible shell. This will install all of the necessary vendored libraries that the project uses to
the
`/vendor` directory.
To update these dependencies, you can run
```bash
make update
```
In order to update all the vendored libraries in the `/vendor` directory.
## Pull Requests
Once you've made the update to the codebase that you'd like to submit, you may [create a pull request](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) to the opentelemetry-php project.
After you open the pull request, the CI/CD pipeline will run all of the associated [github actions](https://github.com/open-telemetry/opentelemetry-php/actions/workflows/php.yml).
You can simulate the important github actions locally before you submit your PR by running the following command:
```bash
make install && make update && make style && make test && make phan && make psalm && make phpstan
```
from your bash compatible shell. This does the following things:
* Installs all the required dependencies for the project and ensures they are up to date
* Uses [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) to style your code using our style preferences.
* Runs all of our [phpunit](https://phpunit.de/) unit tests.
* Performs static analysis with [Phan](https://github.com/phan/phan), [Psalm](https://psalm.dev/) and [PHPStan](https://phpstan.org/user-guide/getting-started)
## Proto Generation
Our proto files are committed to the repository into the `/proto` folder. These are used in gRPC connections to the
upstream. These get updated when the [opentelemetry-proto](https://github.com/open-telemetry/opentelemetry-proto)
repo has a meaningful update. The maintainer SIG is discussing a way to make this more automatic in the future.
If you'd like to generate proto files for use with this repository, one can run the following command:
```bash
make proto
```
From your bash compatible shell in the root of this directory. This wil create a `/proto` folder in the root
directory of the
repository.
## Styling
We use [PHP-CS-Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) for our code linting and standards fixer. The associated configuration for this standards fixer can be found in the root of the repository [here](https://github.com/open-telemetry/opentelemetry-php/blob/master/.php_cs)
To ensure that your code is stylish, you can run the follwing command:
```bash
make style
```
from your bash compatible shell. This process will print out the fixes that it is making to your
associated files. Usually this process is performed as part of a code checkin. This process runs during CI and is a required check. Code that doesn't follow this style pattern will emit a failure in CI.
## Static Analysis
We use [Phan](https://github.com/phan/phan/) for static analysis. Currently our phan configuration is just a standard default analysis configuration. You can use our phan docker wrapper to easily perform static analysis on your changes.
To run Phan, one can run the following command:
```bash
make phan
```
from your bash compatible shell.
This process will return 0 on success.
Usually this process is performed as part of a code checkin. This process runs during CI and is a required check. Code that doesn't match the standards that we have defined in our [phan config](https://github.com/open-telemetry/opentelemetry-php/blob/master/.phan/config.php) will emit a failure in CI.
We also use [Psalm](https://psalm.dev/) as a second static analysis tool.
You can use our psalm docker wrapper to easily perform static analysis on your changes.
To run Psalm, one can run the following command:
```bash
make psalm
```
from your bash compatible shell. This process will return 0 on success. Usually this process is performed as part of a code checkin. This process runs during CI and is a required check. Code that doesn't match the standards that we have defined in our [psalm config](https://github.com/open-telemetry/opentelemetry-php/blob/main/psalm.xml.dist) will emit a failure in CI.
We use [PHPStan](https://github.com/phpstan/phpstan) as our third tool for static analysis.
You can use our PHPStan docker wrapper to easily perform static analysis on your changes.
Execute `make phpstan` from your bash compatible shell. This process will return 0 on success. Usually this process is
performed as part of a code checkin. This process runs during CI and is a required check. Code that doesn't match the
standards that we have defined in
our [PHPStan config](https://github.com/open-telemetry/opentelemetry-php/blob/main/phpstan.neon.dist) will emit a failure
in CI.
## Testing
To make sure the tests in this repo work as you expect, you can use the included docker test wrapper.
To run the test suite, execute
```bash
make test
```
from your bash compatible shell. This will output the test output as well
as a test coverage analysis. Code that doesn't pass our currently defined tests will emit a failure in CI
## Examples
### Trace
You can use the [examples/AlwaysOnZipkinExample.php](/examples/AlwaysOnZipkinExample.php) file to test out the reference implementation we have for zipkin. This example perfoms a sample trace with a grouping of 5 spans and POSTs the result to a local zipkin instance.
You can also use the [examples/AlwaysOnJaegerExample.php](/examples/AlwaysOnJaegerExample.php) file to test out the reference implementation we have for jaegar. This example perfoms a sample trace with a grouping of 5 spans and POSTs the result to a local jaegar instance.
You can use the [examples/AlwaysOnZipkinToNewrelicExample.php](/examples/AlwaysOnZipkinToNewrelicExample.php) file to test out the reference implementation we have for zipkin to Newrelic. This example perfoms a sample trace with spans and POSTs the result to a Newrelic endpoint. This requires a license key (free accounts available) to be set in the environment (NEW_RELIC_INSERT_KEY) to authenticate to the backend.
You can use the [examples/AlwaysOnNewrelicExample.php](/examples/AlwaysOnNewrelicExample.php) file to test out the reference implementation we have for Newrelic. This example perfoms a sample trace with spans and POSTs the result to a Newrelic endpoint. This requires a license key (free accounts available) set in the environment (NEW_RELIC_INSERT_KEY) to authenticate to the backend.
The PHP for all examples should execute by itself (if you have a zipkin or jaegar instance running on localhost), but if you'd like a no-fuss way to test this out with docker and docker-compose, you can perform the following simple steps:
1.) Install the necessary dependencies by running `make install`. This will install the composer dependencies and store them in `/vendor`
2.) Execute the example trace using `make trace examples`.
Exported spans can be seen in zipkin at [http://127.0.0.1:9411](http://127.0.0.1:9411)
Exported spans can also be seen in jaeger at [http://127.0.0.1:16686](http://127.0.0.1:16686)
### Metrics
You can use the [examples/prometheus/PrometheusMetricsExample.php](/examples/prometheus/PrometheusMetricsExample.php) file to test out the reference implementation we have. This example will create a counter that will be scraped by local Prometheus instance.
The easy way to test the example out with docker and docker-compose is:
1.) Run `make metrics-prometheus-example`. Make sure that local ports 8080, 6379 and 9090 are available.
2.) Open local Prometheus instance: http://localhost:9090
3.) Go to Graph section, type "opentelemetry_prometheus_counter" in the search field or select it in the dropdown menu. You will see the counter value. Every other time you run `make metrics-prometheus-example` will increment the counter but remember that Prometheus scrapes values once in 10 seconds.
4.) In order to stop docker containers for this example just run `make stop-prometheus`
## User Integration Guides
* [Integrating OpenTelemetry PHP into Laravel Applications](./docs/laravel-integration.md)
* [Integrating OpenTelemetry PHP into Symfony Applications](./docs/symfony-integration.md)
## Versioning
OpenTelemetry for PHP aims to support all officially supported PHP versions according to https://www.php.net/supported-versions.php, and
support will be dropped for PHP versions within 12 months of that version going _End of life_.
Versioning rationale can be found in the [Versioning Documentation](/docs/versioning.md)

View File

@ -1,24 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry;
use OpenTelemetry\Context\ContextKey;
interface Baggage
{
public function getCorrelations(); // TODO
public function get(ContextKey $key);
public static function getValue(ContextKey $key, ?Baggage $ctx);
public function set(ContextKey $key, $value): Baggage;
public static function setValue(ContextKey $key, $value, ?Baggage $parent = null): Baggage;
public function removeCorrelation(): Baggage;
public function clearCorrelations(); // TODO
}

View File

@ -1,33 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Metrics;
interface Counter extends Metric
{
/**
* Adds value to the counter
*
* @access public
* @param int $value
* @return self
*/
public function add(int $value): Counter;
/**
* Increments value
*
* @access public
* @return self
*/
public function increment(): Counter;
/**
* Gets the value
*
* @access public
* @return int
*/
public function getValue(): int;
}

View File

@ -1,26 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Metrics;
interface Exporter
{
/**
* Possible return values as outlined in the OpenTelemetry spec
*/
const SUCCESS = 0;
const FAILED_NOT_RETRYABLE = 1;
const FAILED_RETRYABLE = 2;
/**
* export.
*
* @access public
* @param iterable<Metric> $metrics
* @return int
*
* todo Should we pass a result callback in the 2nd parameter like in JavaScript implementation?
*/
public function export(iterable $metrics): int;
}

View File

@ -1,32 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Metrics;
interface LabelableMetric extends Metric
{
/**
* Get $labels
* todo: we will probably need a class Label and a typed collection for labels
*
* @return array<string>
*/
public function getLabels(): array;
/**
* Set $labels
*
* @param array<string> $labels
* @return self
*/
public function setLabels(array $labels);
/**
* Set $labels
*
* @param string $label
* @return self
*/
public function addLabel(string $label);
}

View File

@ -1,52 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Metrics;
interface Meter
{
/**
* Returns the meter name.
*
* @return string
*/
public function getName(): string;
/**
* Returns the meter version.
*
* @return string Metric version
*/
public function getVersion(): string;
/**
* Creates a Counter metric instrument.
*
* @param string $name (required) - Counter name
* @param string $description (optional) - Counter description
*
* @return Counter
*/
public function newCounter(string $name, string $description): Counter;
/**
* Creates an UpDownCounter metric instrument.
*
* @param string $name (required) - UpDownCounter name
* @param string $description (optional) - UpDownCounter description
*
* @return UpDownCounter
*/
public function newUpDownCounter(string $name, string $description): UpDownCounter;
/**
* Creates a ValueRecorder metric instrument.
*
* @param string $name (required) - ValueRecorder name
* @param string $description (optional) - ValueRecorder description
*
* @return ValueRecorder
*/
public function newValueRecorder(string $name, string $description): ValueRecorder;
}

View File

@ -1,21 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Metrics;
interface MeterProvider
{
/**
* @access public
* @param string $name - (required) - This name must identify the instrumentation library
* (e.g. io.opentelemetry.contrib.mongodb) and not the instrumented library.
* In case an invalid name (null or empty string) is specified, a working default Meter implementation is returned
* as a fallback rather than returning null or throwing an exception.
* A MeterProvider could also return a no-op Meter here if application owners configure the SDK to suppress
* telemetry produced by this library.
* @param ?string $version - (optional) - Specifies the version of the instrumentation library (e.g. semver:1.0.0)
* @return Meter
*/
public function getMeter(string $name, ?string $version = null): Meter;
}

View File

@ -1,32 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Metrics;
interface Metric
{
/**
* Returns metric's name
*
* @access public
* @return string
*/
public function getName(): string;
/**
* Returns metric's description
*
* @access public
* @return string
*/
public function getDescription(): string;
/**
* Returns metric's type
*
* @access public
* @return int
*/
public function getType(): int;
}

View File

@ -1,29 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Metrics;
interface MetricKind
{
public const COUNTER = 1;
public const UP_DOWN_COUNTER = 2;
public const VALUE_RECORDER = 3;
public const SUM_OBSERVER = 4;
public const UP_DOWN_SUM_OBSERVER = 4;
public const VALUE_OBSERVER = 5;
public const TYPES = [
self::COUNTER,
self::UP_DOWN_COUNTER,
self::VALUE_RECORDER,
self::SUM_OBSERVER,
self::UP_DOWN_SUM_OBSERVER,
self::VALUE_OBSERVER,
];
}

View File

@ -1,31 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Metrics;
/*
* Name: UpDownCounter
* Instrument kind : Synchronous additive
* Function(argument) : Add(increment) where increment is a numeric value
* Default aggregation : Sum
* Notes : Per-request, part of a non-monotonic sum
*
* UpDownCounter supports negative increments. This makes UpDownCounter
* not useful for computing a rate aggregation. It aggregates a Sum,
* only the sum is non-monotonic. It is generally useful for capturing changes
* in an amount of resources used, or any quantity that rises and falls during
* a request.
*
*/
interface UpDownCounter
{
/**
* Updates counter value with the positive or negative int that is passed in.
*
* @access public
* @param int|float $increment
* @return int returns the non-monotonic sum
*/
public function add($increment) : int;
}

View File

@ -1,32 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Metrics;
/*
* Name: UpDownSumObserver
* Instrument kind : Asynchronous additive
* Function(argument) : Observe(sum) where sum is a numeric value
* Default aggregation : Sum
* Notes : Captures only one value per Measurement Interval, part of a non-monotonic sum
*
* UpDownSumObserver is the asynchronous instrument corresponding to UpDownCounter,
* used to capture a non-monotonic count with Observe(sum).
* "Sum" appears in the name to remind users that it is used to capture sums directly.
* Use a UpDownSumObserver to capture any value that starts at zero and rises
* or falls throughout the process lifetime.
*
*/
interface UpDownSumObserver
{
/**
* Updates sum value with the positive or negative int that is passed in.
*
* @access public
* @param int|float $value
* @return int returns the non-monotonic sum
*/
public function observe($value) : int;
}

View File

@ -1,49 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Metrics;
interface ValueRecorder extends Metric
{
/**
* records the given value to this ValueRecorder.
*
* @access public
* @param int|float $value
* @return void
*/
public function record($value) : void;
/**
* Returns the sum of the values
*
* @access public
* @return float
*/
public function getSum(): float;
/**
* Returns the min of the values
*
* @access public
* @return float
*/
public function getMin(): float;
/**
* Returns the max of the values
*
* @access public
* @return float
*/
public function getMax(): float;
/**
* Returns the count of the values
*
* @access public
* @return int
*/
public function getCount(): int;
}

View File

@ -1,17 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface Attribute
{
public function getKey(): string;
/**
*
* @return bool|int|float|string|list<bool>|list<int>|list<float>|list<string>
*
*/
public function getValue();
}

View File

@ -1,19 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface Attributes extends \IteratorAggregate, \Countable
{
/**
* Setting event should not invalidate nor change any existing iterators.
* @param string $name
* @param mixed $value
* @return Attributes
*/
public function setAttribute(string $name, $value): Attributes;
public function count(): int;
public function getIterator(): AttributesIterator;
}

View File

@ -1,19 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface AttributesIterator extends \Iterator
{
public function key(): string;
public function current(): Attribute;
/**
* Should be valid to call rewind as many times as desired UNTIL next() has been called; then it is implementation
* defined whether it is valid or not. The implementation should throw if it cannot be rewound.
*/
public function rewind(): void;
public function valid(): bool;
public function next(): void;
}

View File

@ -1,16 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface Clock
{
/**
* A combination of the Monotonic and Realtime Clocks
* Monotonic time value in the first slot, as it'll get accessed more frequently in duration calculations.
* @return array
*/
public function moment(): array;
public function now(): int;
}

View File

@ -1,12 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface Event
{
public function getName(): string;
public function getAttributes(): Attributes;
public function getTimestamp(): int;
}

View File

@ -1,20 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface Events extends \IteratorAggregate, \Countable
{
/**
* Adding an event should not invalidate nor change any existing iterators.
* @param string $name
* @param Attributes|null $attributes
* @param int|null $timestamp
* @return Events Must return $this to allow setting multiple attributes at once in a chain.
*/
public function addEvent(string $name, ?Attributes $attributes = null, ?int $timestamp = null): Events;
public function count(): int;
public function getIterator(): EventsIterator;
}

View File

@ -1,19 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface EventsIterator extends \Iterator
{
public function key(): int;
public function current(): Event;
/**
* Should be valid to call rewind as many times as desired UNTIL next() has been called; then it is implementation
* defined whether it is valid or not. The implementation should throw if it cannot be rewound.
*/
public function rewind(): void;
public function valid(): bool;
public function next(): void;
}

View File

@ -1,11 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface Link
{
public function getSpanContext(): SpanContext;
public function getAttributes(): Attributes;
}

View File

@ -1,19 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface Links extends \IteratorAggregate, \Countable
{
public function count(): int;
public function getIterator(): LinksIterator;
/**
* Adding a link should not invalidate nor change any existing iterators.
* @param SpanContext $context
* @param Attributes|null $attributes
* @return Links Return $this to allow setting multiple links at once in a chain.
*/
public function addLink(SpanContext $context, ?Attributes $attributes = null): Links;
}

View File

@ -1,29 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface LinksIterator extends \Iterator
{
/**
* Should be valid to call rewind as many times as desired UNTIL next() has been called; then it is implementation
* defined whether it is valid or not. The implementation should throw if it cannot be rewound.
*/
public function rewind(): void;
public function valid(): bool;
/**
* @return int The order the link was added.
*/
public function key(): int;
/**
* @return Link Should throw if the iterator is !valid().
*/
public function current(): Link;
public function next(): void;
}

View File

@ -1,28 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
/**
* The API Specification says:
* OpenTelemetry can operate on time values up to nanosecond (ns) precision.
* The representation of those values is language specific.
* A duration is the elapsed time between two events.
* - The minimal precision is milliseconds.
* - The maximal precision is nanoseconds.
*
* In the PHP standard library, the best suited function for measuring elapsed
* time is `hrtime`, available since PHP 7.3. In other words, callers can
* reasonably expect to have nanosecond resolution (nsec) on PHP 7.3 and newer.
*/
interface MonotonicClock
{
/**
* Represents the amount of time in nanoseconds since an unspecified point
* in the past (for example, system start-up time, or the Epoch). This point
* does not change after system start-up time.
* @return int
*/
public function now(): int;
}

View File

@ -1,17 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface PropagationGetter
{
/**
* Gets the value of a given key from a carrier.
*
* @param mixed $carrier
* @param string $key
* @return string|null
*/
public function get($carrier, string $key) : ?string;
}

View File

@ -1,18 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface PropagationSetter
{
/**
* Set the value for a given key on the associated carrier.
*
* @param mixed $carrier
* @param string $key
* @param string $value
* @return void
*/
public function set(&$carrier, string $key, string $value) : void;
}

View File

@ -1,28 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
/**
* The API specification says:
* OpenTelemetry can operate on time values up to nanosecond (ns) precision.
* The representation of those values is language specific.
* A timestamp is the time elapsed since the Unix epoch.
* - The minimal precision is milliseconds.
* - The maximal precision is nanoseconds.
*
* In the PHP standard library, the best suited function for time since the
* Unix epoch is `microtime`, which uses microseconds or usecs. This interface
* uses nanosecond resolution so it can represent nanoseconds as per
* OpenTelemetry specification, but keep this mind as most implementations will
* probably use `microtime` so don't expect nanosecond accuracy for a
* RealtimeClock.
*/
interface RealtimeClock
{
/**
* @return int Number of nanoseconds since the Unix epoch
*/
public function now(): int;
}

View File

@ -1,66 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
use Throwable;
interface Span extends SpanStatus, SpanKind
{
/**
* Attributes SHOULD preserve the order in which they're set. Setting an attribute with the same key as an existing
* attribute SHOULD overwrite the existing attribute's value.
* @param string $key
* @param bool|int|float|string|array $value Note: the array MUST be homogeneous, i.e. it MUST NOT contain values
* of different types.
* @return Span Must return $this to allow setting multiple attributes at once in a chain
*/
public function setAttribute(string $key, $value): Span;
/**
* @param string $name
* @param int $timestamp
* @param Attributes|null $attributes
* @return Span Must return $this to allow setting multiple attributes at once in a chain.
*/
public function addEvent(string $name, int $timestamp, ?Attributes $attributes = null): Span;
/**
* @param SpanContext $context
* @param Attributes|null $attributes
* @return Span Must return $this to allow setting multiple links at once in a chain.
*/
public function addLink(SpanContext $context, ?Attributes $attributes = null): Span;
/**
*
* @param Throwable $exception
* @return Span Must return $this to allow setting multiple attributes at once in a chain.
*/
public function recordException(Throwable $exception, ?Attributes $attributes = null): Span;
/**
* Calling this method is highly discouraged; the name should be set on creation and left alone.
* @param string $name
* @return Span Must return $this
*/
public function updateName(string $name): Span;
/**
* Sets the Status of the Span. If used, this will override the default Span status, which is OK.
* Only the value of the last call will be recorded, and implementations are free to ignore previous calls.
* @param string $code
* @param string|null $description
* @return Span Must return $this
*/
public function setSpanStatus(string $code, ?string $description = null): Span;
/**
* @param int|null $timestamp
* @return Span Must return $this
*/
public function end(int $timestamp = null): Span;
public function isRecording(): bool;
}

View File

@ -1,18 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface SpanContext
{
const TRACE_FLAG_SAMPLED = 1;
public function getTraceId(): string;
public function getSpanId(): string;
public function getTraceFlags(): int;
public function getTraceState(): ?TraceState;
public function isValid(): bool;
public function isRemote(): bool;
public function isSampled(): bool;
}

View File

@ -1,24 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface SpanKind
{
const KIND_INTERNAL = 0;
const KIND_CLIENT = 1;
const KIND_SERVER = 2;
const KIND_PRODUCER = 3;
const KIND_CONSUMER = 4;
const TYPES = [
self::KIND_INTERNAL,
self::KIND_CLIENT,
self::KIND_SERVER,
self::KIND_PRODUCER,
self::KIND_CONSUMER,
];
public function getSpanKind(): int;
}

View File

@ -1,40 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
use OpenTelemetry\Context\Context;
/**
* The SpanOptions implementation is intended to be tightly coupled with the Span and Tracer implementations.
* Hopefully the Span object can implement SpanOptions so that the toSpan() call is almost a no-op, but prevents
* the rest of the SpanOptions API from being used after toSpan() is called.
*/
interface SpanOptions
{
public function setSpanName(string $name): SpanOptions;
/** should default to INTERNAL if not called */
public function setSpanKind(int $spanKind): SpanOptions;
public function setParent(Context $parentContext): SpanOptions;
public function addAttributes(Attributes $attributes): SpanOptions;
public function addLinks(Links $links): SpanOptions;
/**
* This should only be used if the creation time has already passed; will set timestamp to current time by default
* @param int $timestamp
* @return SpanOptions
*/
public function addStartTimestamp(int $timestamp): SpanOptions;
/**
* This should only be used if the creation time has already passed; will set to current monotonic clock
* value by default
* @param int $now
* @return SpanOptions
*/
public function addStart(int $now): SpanOptions;
public function toSpan(): Span;
// todo: how do we want to optionally let people make these spans active? bool arg, setActive, or toActiveSpan?
public function toActiveSpan(): Span;
}

View File

@ -1,23 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface SpanStatus
{
const UNSET = 'Unset';
const OK = 'Ok';
const ERROR = 'Error';
const DESCRIPTION = [
self::UNSET => 'The default unset status.',
self::OK => 'Not an error; returned on success.',
self::ERROR => 'The operation contains an error.',
];
public function getCanonicalStatusCode(): string;
public function getStatusDescription(): string;
public function isStatusOk(): bool;
// public function setStatus(string $code = self::UNSET, string $description = null): void;
}

View File

@ -1,35 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface TextMapFormatPropagator
{
/**
* Returns list of fields that will be used by this formatter.
*
* @return array
*/
public static function fields() : array;
/**
* Encodes the given SpanContext into propagator specific format and injects
* the encoded SpanContext using Setter into it's associated carrier.
*
* @param SpanContext $context
* @param mixed $carrier
* @param PropagationSetter $setter
* @return void
*/
public static function inject(SpanContext $context, &$carrier, PropagationSetter $setter) : void;
/**
* Retrieves encoded SpanContext using Getter from the associated carrier.
*
* @param mixed $carrier
* @param PropagationGetter $getter
* @return SpanContext
*/
public static function extract($carrier, PropagationGetter $getter): SpanContext;
}

View File

@ -1,27 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
use OpenTelemetry\Context\Context;
interface Tracer
{
public function startSpan(
string $name,
?Context $parentContext = null,
int $spanKind = SpanKind::KIND_INTERNAL,
?Attributes $attributes = null,
?Links $links = null,
?int $startTimestamp = null
): Span;
public function getActiveSpan(): Span;
public function startActiveSpan(string $name, SpanContext $parentContext, bool $isRemote = false, int $spanKind = SpanKind::KIND_INTERNAL): Span;
public function startAndActivateSpan(string $name, int $spanKind = SpanKind::KIND_INTERNAL): Span;
public function startSpanWithOptions(string $name): SpanOptions;
public function setActiveSpan(Span $span): void;
}

View File

@ -1,10 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Trace;
interface TracerProvider
{
public function getTracer(string $name, ?string $version = null): Tracer;
}

View File

@ -1,65 +1,208 @@
{
"name": "open-telemetry/opentelemetry",
"description": "OpenTelemetry makes robust, portable telemetry a built-in feature of cloud-native software.",
"keywords": ["opentelemetry", "otel", "open-telemetry", "tracing", "logging", "metrics"],
"type": "library",
"homepage": "https://opentelemetry.io/docs/php",
"readme": "./README.md",
"license": "Apache-2.0",
"require": {
"php": "^7.3 || ^8.0",
"ext-json": "*",
"promphp/prometheus_client_php": "^2.2.1",
"grpc/grpc": "^1.30",
"google/protobuf": "^v3.3.0",
"php": "^8.1",
"google/protobuf": "^3.22 || ^4.0",
"nyholm/psr7-server": "^1.1",
"php-http/discovery": "^1.14",
"psr/http-client": "^1.0",
"psr/http-client-implementation": "^1.0",
"psr/http-factory-implementation": "^1.0",
"nyholm/dsn": "^2.0.0"
"psr/http-message": "^1.0.1|^2.0",
"psr/log": "^1.1|^2.0|^3.0",
"ramsey/uuid": "^3.0 || ^4.0",
"symfony/config": "^5.4 || ^6.4 || ^7.0",
"symfony/polyfill-mbstring": "^1.23",
"symfony/polyfill-php82": "^1.26",
"symfony/polyfill-php83": "^1.32",
"symfony/polyfill-php84": "^1.32",
"tbachert/spi": "^1.0.1"
},
"config": {
"sort-packages": true,
"allow-plugins": {
"bamarni/composer-bin-plugin": true,
"composer/package-versions-deprecated": true,
"php-http/discovery": true,
"symfony/runtime": true,
"tbachert/spi": true
}
},
"authors": [
{
"name": "Bob Strecansky",
"email": "bob.strecansky@gmail.com"
},
{
"name": "Dmitry Krokhin",
"email": "nekufa@gmail.com"
},
{
"name": "Levi Morrison",
"email": "levim@php.net"
"name": "opentelemetry-php contributors",
"homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors"
}
],
"replace": {
"open-telemetry/api": "1.0.x-dev",
"open-telemetry/context": "1.0.x-dev",
"open-telemetry/exporter-otlp": "1.0.x-dev",
"open-telemetry/exporter-zipkin": "1.0.x-dev",
"open-telemetry/extension-propagator-b3": "1.0.x-dev",
"open-telemetry/extension-propagator-cloudtrace": "1.0.x-dev",
"open-telemetry/extension-propagator-jaeger": "0.0.2",
"open-telemetry/gen-otlp-protobuf": "1.0.x-dev",
"open-telemetry/sdk": "1.0.x-dev",
"open-telemetry/sdk-configuration": "0.1.x-dev",
"open-telemetry/sdk-contrib": "1.0.x-dev",
"open-telemetry/sem-conv": "1.0.x-dev",
"open-telemetry/transport-grpc": "1.0.x-dev"
},
"autoload": {
"psr-4": {
"OpenTelemetry\\Context\\": "Context",
"OpenTelemetry\\": "api",
"OpenTelemetry\\Sdk\\": "sdk",
"OpenTelemetry\\Contrib\\": "contrib",
"Opentelemetry\\Proto\\Collector\\Trace\\V1\\": "proto/Opentelemetry/Proto/Collector/Trace/V1",
"Opentelemetry\\Proto\\Trace\\V1\\":"proto/Opentelemetry/Proto/Trace/V1",
"Opentelemetry\\Proto\\Common\\V1\\":"proto/Opentelemetry/Proto/Common/V1",
"Opentelemetry\\Proto\\Resource\\V1\\":"proto/Opentelemetry/Proto/Resource/V1",
"GPBMetadata\\Opentelemetry\\Proto\\Collector\\Trace\\V1\\": "proto/GPBMetadata/Opentelemetry/Proto/Collector/Trace/V1",
"GPBMetadata\\Opentelemetry\\Proto\\Trace\\V1\\":"proto/GPBMetadata/Opentelemetry/Proto/Trace/V1",
"GPBMetadata\\Opentelemetry\\Proto\\Common\\V1\\":"proto/GPBMetadata/Opentelemetry/Proto/Common/V1",
"GPBMetadata\\Opentelemetry\\Proto\\Resource\\V1\\":"proto/GPBMetadata/Opentelemetry/Proto/Resource/V1"
}
"OpenTelemetry\\": "src/",
"Opentelemetry\\Proto\\": "proto/otel/Opentelemetry/Proto/",
"GPBMetadata\\Opentelemetry\\": "proto/otel/GPBMetadata/Opentelemetry/"
},
"files": [
"src/Context/fiber/initialize_fiber_handler.php",
"src/API/Trace/functions.php",
"src/Contrib/Otlp/_register.php",
"src/Contrib/Grpc/_register.php",
"src/Contrib/Zipkin/_register.php",
"src/Extension/Propagator/B3/_register.php",
"src/Extension/Propagator/CloudTrace/_register.php",
"src/Extension/Propagator/Jaeger/_register.php",
"src/SDK/Logs/Exporter/_register.php",
"src/SDK/Metrics/MetricExporter/_register.php",
"src/SDK/Propagation/_register.php",
"src/SDK/Trace/SpanExporter/_register.php",
"src/SDK/Common/Dev/Compatibility/_load.php",
"src/SDK/Common/Util/functions.php",
"src/SDK/_autoload.php"
]
},
"autoload-dev": {
"psr-4": {
"OpenTelemetry\\Tests\\": "tests/"
"OpenTelemetry\\Tests\\": "tests/",
"OpenTelemetry\\Example\\": "examples/src/",
"ExampleSDK\\ComponentProvider\\": "tests/Unit/Config/SDK/Configuration/ExampleSdk/"
}
},
"require-dev": {
"phpunit/phpunit": "^9.3",
"composer/xdebug-handler": "^2.0",
"phan/phan": "^4.1",
"friendsofphp/php-cs-fixer": "^3.0",
"vimeo/psalm": "^4.0",
"phpstan/phpstan": "^0.12.50",
"phpstan/phpstan-phpunit": "^0.12.16",
"psalm/plugin-phpunit": "^0.13.0",
"guzzlehttp/guzzle": "^7.3",
"guzzlehttp/psr7": "^2.0@RC",
"ext-grpc": "*",
"bamarni/composer-bin-plugin": "^1.8",
"dg/bypass-finals": "^1.4",
"grpc/grpc": "^1.30",
"guzzlehttp/guzzle": "^7.4",
"guzzlehttp/psr7": "^2.1",
"mikey179/vfsstream": "^1.6.11",
"mockery/mockery": "^1.5.1",
"monolog/monolog": "^3.0",
"nyholm/psr7": "^1.4",
"open-telemetry/dev-tools": "dev-main",
"php-http/mock-client": "^1.5",
"phpdocumentor/reflection-docblock": "^5.3",
"phpspec/prophecy": "^1.22",
"phpspec/prophecy-phpunit": "^2",
"phpstan/phpstan": "^1.10.13",
"phpstan/phpstan-mockery": "^1.1",
"phpstan/phpstan-phpunit": "^1.3",
"phpunit/phpunit": "^10 || ^11",
"sebastian/exporter": "<= 6.0.1 || >= 6.1.3",
"symfony/http-client": "^5.2",
"nyholm/psr7": "^1.4"
"symfony/var-exporter": "^5.4 || ^6.4 || ^7.0",
"symfony/yaml": "^5.4 || ^6.4 || ^7.0"
},
"conflict": {
"mockery/mockery": "1.6.12"
},
"suggest": {
"ext-gmp": "To support unlimited number of synchronous metric readers",
"ext-grpc": "To use the OTLP GRPC Exporter",
"ext-protobuf": "For more performant protobuf/grpc exporting",
"ext-yaml": "Allows loading config from yaml files",
"symfony/yaml": "Allows loading config from yaml files"
},
"extra": {
"bamarni-bin": {
"bin-links": false,
"target-directory": "vendor-bin",
"forward-command": true
},
"spi": {
"OpenTelemetry\\API\\Configuration\\Config\\ComponentProvider": [
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Propagator\\TextMapPropagatorB3",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Propagator\\TextMapPropagatorB3Multi",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Propagator\\TextMapPropagatorBaggage",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Propagator\\TextMapPropagatorComposite",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Propagator\\TextMapPropagatorJaeger",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Propagator\\TextMapPropagatorTraceContext",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SamplerAlwaysOff",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SamplerAlwaysOn",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SamplerParentBased",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SamplerTraceIdRatioBased",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanExporterConsole",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanExporterMemory",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanExporterOtlpFile",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanExporterOtlpGrpc",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanExporterOtlpHttp",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanExporterZipkin",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanProcessorBatch",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanProcessorSimple",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\AggregationResolverDefault",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\MetricExporterConsole",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\MetricExporterMemory",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\MetricExporterOtlpFile",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\MetricExporterOtlpGrpc",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\MetricExporterOtlpHttp",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\MetricReaderPeriodic",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordExporterConsole",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordExporterMemory",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordExporterOtlpFile",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordExporterOtlpGrpc",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordExporterOtlpHttp",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordProcessorBatch",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordProcessorSimple",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Detector\\Composer",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Detector\\Host",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Detector\\Process",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Instrumentation\\General\\HttpConfigProvider",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Instrumentation\\General\\PeerConfigProvider",
"OpenTelemetry\\Example\\ExampleConfigProvider",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Detector\\Container",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Detector\\Os",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Metrics\\AggregationResolverExplicitBucketHistogram",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Metrics\\MetricExporterPrometheus",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Metrics\\MetricReaderPull",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Propagator\\TextMapPropagatorXray",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Propagator\\TextMapPropagatorOtTrace"
],
"OpenTelemetry\\API\\Configuration\\ConfigEnv\\EnvComponentLoader": [
"OpenTelemetry\\API\\Instrumentation\\Configuration\\General\\ConfigEnv\\EnvComponentLoaderHttpConfig",
"OpenTelemetry\\API\\Instrumentation\\Configuration\\General\\ConfigEnv\\EnvComponentLoaderPeerConfig",
"OpenTelemetry\\Example\\ExampleConfigLoader"
],
"OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\HookManagerInterface": [
"OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\ExtensionHookManager"
],
"OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\Instrumentation": [
"OpenTelemetry\\Example\\ExampleInstrumentation"
],
"OpenTelemetry\\SDK\\Common\\Configuration\\Resolver\\ResolverInterface": [
"OpenTelemetry\\SDK\\Common\\Configuration\\Resolver\\SdkConfigurationResolver"
],
"OpenTelemetry\\Config\\SDK\\Configuration\\Environment\\EnvSourceProvider": [
"OpenTelemetry\\Config\\SDK\\Configuration\\Environment\\Adapter\\SymfonyDotenvProvider",
"OpenTelemetry\\Config\\SDK\\Configuration\\Environment\\Adapter\\VlucasPhpdotenvProvider",
"OpenTelemetry\\Tests\\Integration\\SDK\\Common\\Configuration\\TestEnvSourceProvider"
]
}
}
}
}

View File

@ -1,27 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\Jaeger;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use OpenTelemetry\Contrib\Zipkin;
use OpenTelemetry\Sdk\Trace;
class Exporter extends Zipkin\Exporter implements Trace\Exporter
{
public static function fromConnectionString(string $endpointUrl, string $name, $args = null)
{
$factory = new HttpFactory();
$exporter = new Exporter(
$name,
$endpointUrl,
new Client(),
$factory,
$factory
);
return $exporter;
}
}

View File

@ -1,182 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\Newrelic;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use InvalidArgumentException;
use OpenTelemetry\Sdk\Trace;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Client\RequestExceptionInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
/**
* Class NewrelicExporter - implements the export interface for data transfer via Newrelic protocol
* @package OpenTelemetry\Exporter
*
* This is an experimental, non-supported exporter.
* It will send PHP Otel trace data end to end across the internet to a functional backend.
* Needs a license key to connect. For a free account/key, go to: https://newrelic.com/signup/
*/
class Exporter implements Trace\Exporter
{
private const DATA_FORMAT = 'newrelic';
private const DATA_FORMAT_VERSION_DEFAULT = '1';
/**
* @var string
*/
private $endpointUrl;
/**
* @var string
*/
private $licenseKey;
/**
* @var string
*/
private $name;
/**
* @var SpanConverter
*/
private $spanConverter;
/**
* @var bool
*/
private $running = true;
/**
* @var ClientInterface
*/
private $client;
/**
* @var RequestFactoryInterface
*/
private $requestFactory;
/**
* @var StreamFactoryInterface
*/
private $streamFactory;
private $dataFormatVersion;
public function __construct(
$name,
string $endpointUrl,
string $licenseKey,
ClientInterface $client,
RequestFactoryInterface $requestFactory,
StreamFactoryInterface $streamFactory,
SpanConverter $spanConverter = null,
string $dataFormatVersion = Exporter::DATA_FORMAT_VERSION_DEFAULT
) {
$parsedDsn = parse_url($endpointUrl);
if (!is_array($parsedDsn)) {
throw new InvalidArgumentException('Unable to parse provided DSN');
}
if (
!isset($parsedDsn['scheme'])
|| !isset($parsedDsn['host'])
|| !isset($parsedDsn['path'])
) {
throw new InvalidArgumentException('Endpoint should have scheme, host, port and path');
}
$this->name = $name;
$this->endpointUrl = $endpointUrl;
$this->licenseKey = $licenseKey;
$this->client = $client;
$this->requestFactory = $requestFactory;
$this->streamFactory = $streamFactory;
$this->spanConverter = $spanConverter ?? new SpanConverter($name);
$this->dataFormatVersion = $dataFormatVersion;
}
/**
* Exports the provided Span data via the Newrelic protocol
*
* @param iterable<Trace\ReadableSpan> $spans Array of Spans
* @return int return code, defined on the Exporter interface
*/
public function export(iterable $spans): int
{
if (!$this->running) {
return Exporter::FAILED_NOT_RETRYABLE;
}
if (empty($spans)) {
return Trace\Exporter::SUCCESS;
}
$convertedSpans = [];
foreach ($spans as $span) {
array_push($convertedSpans, $this->spanConverter->convert($span));
}
$commonAttributes = ['attributes' => [ 'service.name' => $this->name,
'host' => $this->endpointUrl, ]];
$payload = [[ 'common' => $commonAttributes,
'spans' => $convertedSpans, ]];
try {
$body = $this->streamFactory->createStream(json_encode($payload));
$request = $this->requestFactory
->createRequest('POST', $this->endpointUrl)
->withBody($body)
->withHeader('content-type', 'application/json')
->withAddedHeader('Api-Key', $this->licenseKey)
->withAddedHeader('Data-Format', Exporter::DATA_FORMAT)
->withAddedHeader('Data-Format-Version', $this->dataFormatVersion);
$response = $this->client->sendRequest($request);
} catch (RequestExceptionInterface $e) {
return Trace\Exporter::FAILED_NOT_RETRYABLE;
} catch (NetworkExceptionInterface | ClientExceptionInterface $e) {
return Trace\Exporter::FAILED_RETRYABLE;
}
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) {
return Trace\Exporter::FAILED_NOT_RETRYABLE;
}
if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) {
return Trace\Exporter::FAILED_RETRYABLE;
}
return Trace\Exporter::SUCCESS;
}
public function shutdown(): void
{
$this->running = false;
}
public static function fromConnectionString(string $endpointUrl, string $name, $args)
{
if ($args == false) {
throw new Exception('Invalid license key.');
}
$factory = new HttpFactory();
$exporter = new Exporter(
$name,
$endpointUrl,
$args,
new Client(),
$factory,
$factory
);
return $exporter;
}
}

View File

@ -1,58 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\Newrelic;
use OpenTelemetry\Sdk\Trace\ReadableSpan;
class SpanConverter
{
const STATUS_CODE_TAG_KEY = 'otel.status_code';
const STATUS_DESCRIPTION_TAG_KEY = 'otel.status_description';
/**
* @var string
*/
private $serviceName;
public function __construct(string $serviceName)
{
$this->serviceName = $serviceName;
}
public function convert(ReadableSpan $span)
{
$spanParent = $span->getParent();
$row = [
'id' => $span->getContext()->getSpanId(),
'trace.id' => $span->getContext()->getTraceId(),
'attributes' => [
'name' => $span->getSpanName(),
'service.name' => $this->serviceName,
'parent.id' => $spanParent ? $spanParent->getSpanId() : null,
'timestamp' => ($span->getStartEpochTimestamp() / 1e6), // RealtimeClock in milliseconds
'duration.ms' => (($span->getEnd() - $span->getStart()) / 1e6), // Diff in milliseconds
self::STATUS_CODE_TAG_KEY => $span->getStatus()->getCanonicalStatusCode(),
self::STATUS_DESCRIPTION_TAG_KEY => $span->getStatus()->getStatusDescription(),
],
];
foreach ($span->getAttributes() as $k => $v) {
$row['attributes'][$k] = $v->getValue();
}
/*
foreach ($span->getEvents() as $event) {
if (!array_key_exists('annotations', $row)) {
$row['annotations'] = [];
}
$row['annotations'][] = [
'timestamp' => (int) ($event->getTimestamp() / 1e6), // RealtimeClock in milliseconds
'value' => $event->getName(),
];
}
*/
return $row;
}
}

View File

@ -1,181 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\Otlp;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use OpenTelemetry\Contrib\OtlpGrpc\Exporter as OtlpGrpcExporter;
use OpenTelemetry\Contrib\OtlpHttp\Exporter as OtlpHttpExporter;
use OpenTelemetry\Sdk\Trace;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Client\RequestExceptionInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
class Exporter implements Trace\Exporter
{
/**
* @var string
*/
private $endpointUrl;
/**
* @var string
*/
private $protocol;
/**
* @var string
*/
private $insecure;
/**
* @var string
*/
private $certificateFile;
/**
* @var array
*/
private $headers;
/**
* @var string
*/
private $compression;
/**
* @var int
*/
private $timeout;
/**
* @var SpanConverter
*/
private $spanConverter;
/**
* @var bool
*/
private $running = true;
/**
* @var ClientInterface
*/
private $client;
/**
* @var RequestFactoryInterface
*/
private $requestFactory;
/**
* @var StreamFactoryInterface
*/
private $streamFactory;
/**
* Exporter constructor.
* @param string $serviceName
*/
public function __construct(
$serviceName,
ClientInterface $client,
RequestFactoryInterface $requestFactory,
StreamFactoryInterface $streamFactory,
SpanConverter $spanConverter = null
) {
// Set default values based on presence of env variable
$this->endpointUrl = getenv('OTEL_EXPORTER_OTLP_ENDPOINT') ?: 'localhost:55681';
$this->protocol = getenv('OTEL_EXPORTER_OTLP_PROTOCOL') ?: 'json';
$this->insecure = getenv('OTEL_EXPORTER_OTLP_INSECURE') ?: 'false';
$this->certificateFile = getenv('OTEL_EXPORTER_OTLP_CERTIFICATE') ?: 'none';
$this->headers[] = getenv('OTEL_EXPORTER_OTLP_HEADERS') ?: 'none';
$this->compression = getenv('OTEL_EXPORTER_OTLP_COMPRESSION') ?: 'none';
$this->timeout =(int) getenv('OTEL_EXPORTER_OTLP_TIMEOUT') ?: 10;
$this->client = $client;
$this->requestFactory = $requestFactory;
$this->streamFactory = $streamFactory;
$this->spanConverter = $spanConverter ?? new SpanConverter($serviceName);
}
/**
* Exports the provided Span data via the OTLP protocol
*
* @param iterable<Trace\ReadableSpan> $spans Array of Spans
* @return int return code, defined on the Exporter interface
*/
public function export(iterable $spans): int
{
if (!$this->running) {
return Exporter::FAILED_NOT_RETRYABLE;
}
if (empty($spans)) {
return Trace\Exporter::SUCCESS;
}
$convertedSpans = [];
foreach ($spans as $span) {
array_push($convertedSpans, $this->spanConverter->convert($span));
}
try {
$body = $this->streamFactory->createStream(json_encode($convertedSpans));
$request = $this->requestFactory
->createRequest('POST', $this->endpointUrl)
->withBody($body);
if ($this->protocol == 'json') {
$request->withHeader('content-type', 'application/json');
}
$response = $this->client->sendRequest($request);
} catch (RequestExceptionInterface $e) {
return Trace\Exporter::FAILED_NOT_RETRYABLE;
} catch (NetworkExceptionInterface | ClientExceptionInterface $e) {
return Trace\Exporter::FAILED_RETRYABLE;
}
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) {
return Trace\Exporter::FAILED_NOT_RETRYABLE;
}
if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) {
return Trace\Exporter::FAILED_RETRYABLE;
}
return Trace\Exporter::SUCCESS;
}
public function shutdown(): void
{
$this->running = false;
}
public static function fromConnectionString(string $endpointUrl, string $name, $args)
{
// @phan-suppress-next-line PhanUndeclaredFunction
if ($args !== '' && str_contains($args, 'grpc')) {
return OtlpGrpcExporter::fromConnectionString();
}
// @phan-suppress-next-line PhanUndeclaredFunction
if ($args !== '' && str_contains($args, 'http')) {
return OtlpHttpExporter::fromConnectionString();
}
$factory = new HttpFactory();
$exporter = new Exporter(
$name,
new Client(),
$factory,
$factory
);
return $exporter;
}
}

View File

@ -1,77 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\Otlp;
use OpenTelemetry\Sdk\Trace\ReadableSpan;
class SpanConverter
{
/**
* @var string
*/
private $serviceName;
public function __construct(string $serviceName)
{
$this->serviceName = $serviceName;
}
private function sanitiseTagValue($value)
{
// Casting false to string makes an empty string
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
// OTLP tags must be strings, but opentelemetry
// accepts strings, booleans, numbers, and lists of each.
if (is_array($value)) {
return join(',', array_map([$this, 'sanitiseTagValue'], $value));
}
// Floats will lose precision if their string representation
// is >=14 or >=17 digits, depending on PHP settings.
// Can also throw E_RECOVERABLE_ERROR if $value is an object
// without a __toString() method.
// This is possible because OpenTelemetry\Trace\Span does not verify
// setAttribute() $value input.
return (string) $value;
}
public function convert(ReadableSpan $span)
{
$spanParent = $span->getParent();
$row = [
'id' => $span->getContext()->getSpanId(),
'traceId' => $span->getContext()->getTraceId(),
'parentId' => $spanParent ? $spanParent->getSpanId() : null,
'localEndpoint' => [
'serviceName' => $this->serviceName,
],
'name' => $span->getSpanName(),
'timestamp' => (int) ($span->getStartEpochTimestamp() / 1e3), // RealtimeClock in microseconds
'duration' => (int) (($span->getEnd() - $span->getStart()) / 1e3), // Diff in microseconds
];
foreach ($span->getAttributes() as $k => $v) {
if (!array_key_exists('tags', $row)) {
$row['tags'] = [];
}
$row['tags'][$k] = $this->sanitiseTagValue($v->getValue());
}
foreach ($span->getEvents() as $event) {
if (!array_key_exists('annotations', $row)) {
$row['annotations'] = [];
}
$row['annotations'][] = [
'timestamp' => (int) ($event->getTimestamp() / 1e3), // RealtimeClock in microseconds
'value' => $event->getName(),
];
}
return $row;
}
}

View File

@ -1,217 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\OtlpGrpc;
use grpc;
use InvalidArgumentException;
use Opentelemetry\Proto\Collector\Trace\V1\ExportTraceServiceRequest;
use Opentelemetry\Proto\Collector\Trace\V1\TraceServiceClient;
use OpenTelemetry\Sdk\Trace;
class Exporter implements Trace\Exporter
{
/**
* @var string
*/
private $endpointURL;
/**
* @var string
*/
private $protocol;
/**
* @var bool|string
*/
private $insecure;
/**
* @var string
*/
private $certificateFile;
/**
* @var string
*/
private $headers;
/**
* @var bool|string
*/
private $compression;
/**
* @var int
*/
private $timeout;
/**
* @var SpanConverter
*/
private $spanConverter;
private $metadata;
/**
* @var bool
*/
private $running = true;
/**
* @var TraceServiceClient
*/
private $client;
/**
* OTLP GRPC Exporter Constructor
*/
public function __construct(
string $endpointURL = 'localhost:4317',
bool $insecure = true,
string $certificateFile = '',
string $headers = '',
bool $compression = false,
int $timeout = 10,
TraceServiceClient $client = null
) {
// Set default values based on presence of env variable
$this->endpointURL = getenv('OTEL_EXPORTER_OTLP_ENDPOINT') ?: $endpointURL;
$this->protocol = getenv('OTEL_EXPORTER_OTLP_PROTOCOL') ?: 'grpc'; // I guess this is redundant?
$this->insecure = getenv('OTEL_EXPORTER_OTLP_INSECURE') ? filter_var(getenv('OTEL_EXPORTER_OTLP_INSECURE'), FILTER_VALIDATE_BOOLEAN): $insecure;
$this->certificateFile = getenv('OTEL_EXPORTER_OTLP_CERTIFICATE') ?: $certificateFile;
$this->headers = getenv('OTEL_EXPORTER_OTLP_HEADERS') ?: $headers;
$this->compression = getenv('OTEL_EXPORTER_OTLP_COMPRESSION') ?: $compression;
$this->timeout =(int) getenv('OTEL_EXPORTER_OTLP_TIMEOUT') ?: $timeout;
$this->spanConverter = new SpanConverter();
$this->metadata = $this->metadataFromHeaders($this->headers);
$opts = $this->getClientOptions();
$this->client = $client ?? new TraceServiceClient($this->endpointURL, $opts);
}
public function getClientOptions(): array
{
$opts = [
'update_metadata' => function () {
return $this->metadata;
},
'timeout' => $this->timeout,
];
if (!$this->insecure && !$this->certificateFile) {
// Assumed default
$opts['credentials'] = Grpc\ChannelCredentials::createSsl('');
} elseif (!$this->insecure && $this->certificateFile !== '') {
// Should we validate more?
$opts['credentials'] = Grpc\ChannelCredentials::createSsl(file_get_contents($this->certificateFile));
} else {
$opts['credentials'] = Grpc\ChannelCredentials::createInsecure();
}
if ($this->compression) {
// gzip is the only specified compression method for now
$opts['grpc.default_compression_algorithm'] = 2;
}
return $opts;
}
/**
* Exports the provided Span data via the OTLP protocol
*
* @param iterable<Trace\ReadableSpan> $spans Array of Spans
* @return int return code, defined on the Exporter interface
*/
public function export(iterable $spans): int
{
if (!$this->running) {
return Exporter::FAILED_NOT_RETRYABLE;
}
if (empty($spans)) {
return Trace\Exporter::SUCCESS;
}
$resourcespans = [$this->spanConverter->as_otlp_resource_span($spans)];
$request = new ExportTraceServiceRequest([
'resource_spans' => $resourcespans,
]);
list($response, $status) = $this->client->Export($request)->wait();
if ($status->code == \Grpc\STATUS_OK) {
return Trace\Exporter::SUCCESS;
}
if (in_array($status->code, [
\Grpc\STATUS_CANCELLED,
\Grpc\STATUS_DEADLINE_EXCEEDED,
\Grpc\STATUS_PERMISSION_DENIED,
\Grpc\STATUS_RESOURCE_EXHAUSTED,
\Grpc\STATUS_ABORTED,
\Grpc\STATUS_OUT_OF_RANGE,
\Grpc\STATUS_UNAVAILABLE,
\Grpc\STATUS_DATA_LOSS,
\Grpc\STATUS_UNAUTHENTICATED,
])) {
return Trace\Exporter::FAILED_RETRYABLE;
}
return Trace\Exporter::FAILED_NOT_RETRYABLE;
}
public function setHeader($key, $value)
{
$this->metadata[$key] = [$value];
}
public function getHeaders()
{
return $this->metadata;
}
public function metadataFromHeaders($headers): array
{
if (is_array($headers)) {
throw new InvalidArgumentException('Configuring Headers Via');
}
if (strlen($headers) <= 0) {
return [];
}
$pairs = explode(',', $headers);
$metadata = [];
foreach ($pairs as $pair) {
if (!strpos($pair, '=')) {
continue;
}
list($key, $value) = explode('=', $pair, 2);
$metadata[$key] = [$value];
}
return $metadata;
}
public function shutdown(): void
{
$this->running = false;
}
public static function fromConnectionString(string $endpointUrl = null, string $name = null, $args = null)
{
return new Exporter();
}
// public function getHeaders()
// {
// return $this->metadataFromHeaders($this->headers);
// }
}

View File

@ -1,189 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\OtlpGrpc;
use Opentelemetry\Proto;
use Opentelemetry\Proto\Common\V1\AnyValue;
use Opentelemetry\Proto\Common\V1\ArrayValue;
use Opentelemetry\Proto\Common\V1\InstrumentationLibrary;
use Opentelemetry\Proto\Common\V1\KeyValue;
use Opentelemetry\Proto\Trace\V1\InstrumentationLibrarySpans;
use Opentelemetry\Proto\Trace\V1\ResourceSpans;
use Opentelemetry\Proto\Trace\V1\Span as CollectorSpan;
use Opentelemetry\Proto\Trace\V1\Span\Event;
use Opentelemetry\Proto\Trace\V1\Span\SpanKind;
use Opentelemetry\Proto\Trace\V1\Status;
use Opentelemetry\Proto\Trace\V1\Status\StatusCode;
use OpenTelemetry\Sdk\Trace\ReadableSpan;
use OpenTelemetry\Sdk\Trace\SpanStatus;
class SpanConverter
{
public function as_otlp_key_value($key, $value): KeyValue
{
return new KeyValue([
'key' => $key,
'value' => $this->as_otlp_any_value($value),
]);
}
public function as_otlp_any_value($value): AnyValue
{
$result = new AnyValue();
switch (true) {
case is_array($value):
$values = [];
foreach ($value as $element) {
$this->as_otlp_any_value($element);
}
$result->setArrayValue(new ArrayValue($values));
break;
case is_int($value):
$result->setIntValue($value);
break;
case is_bool($value):
$result->setBoolValue($value);
break;
case is_double($value):
$result->setDoubleValue($value);
break;
case is_string($value):
$result->setStringValue($value);
break;
}
return $result;
}
public function as_otlp_span_kind($kind): int
{
switch ($kind) {
case 0: return SpanKind::SPAN_KIND_INTERNAL;
case 1: return SpanKind::SPAN_KIND_CLIENT;
case 2: return SpanKind::SPAN_KIND_SERVER;
case 3: return SpanKind::SPAN_KIND_PRODUCER;
case 4: return SpanKind::SPAN_KIND_CONSUMER;
}
return SpanKind::SPAN_KIND_UNSPECIFIED;
}
public function as_otlp_span(ReadableSpan $span): CollectorSpan
{
$end_timestamp = ($span->getStartEpochTimestamp() + $span->getDuration());
$parent_span = $span->getParent();
$parent_span_id = $parent_span ? $parent_span->getSpanId() : false;
$row = [
'trace_id' => hex2bin($span->getContext()->getTraceId()),
'span_id' => hex2bin($span->getContext()->getSpanId()),
'parent_span_id' => $parent_span_id ? hex2bin($parent_span_id) : null,
'name' => $span->getSpanName(),
'start_time_unix_nano' => $span->getStartEpochTimestamp(),
'end_time_unix_nano' => $end_timestamp,
'kind' => $this->as_otlp_span_kind($span->getSpanKind()),
// 'trace_state' => $span->getContext()
// 'links' =>
];
foreach ($span->getEvents() as $event) {
if (!array_key_exists('events', $row)) {
$row['events'] = [];
}
$attrs = [];
foreach ($event->getAttributes() as $k => $v) {
array_push($attrs, $this->as_otlp_key_value($k, $v->getValue()));
}
$row['events'][] = new Event([
'time_unix_nano' => $event->getTimestamp(),
'name' => $event->getName(),
'attributes' => $attrs,
]);
}
foreach ($span->getAttributes() as $k => $v) {
if (!array_key_exists('attributes', $row)) {
$row['attributes'] = [];
}
array_push($row['attributes'], $this->as_otlp_key_value($k, $v->getValue()));
}
$status = new Status();
switch ($span->getStatus()->getCanonicalStatusCode()) {
case SpanStatus::OK:
$status->setCode(StatusCode::STATUS_CODE_OK);
break;
case SpanStatus::ERROR:
$status->setCode(StatusCode::STATUS_CODE_ERROR)->setMessage($span->getStatus()->getStatusDescription());
break;
default:
$status->setCode(StatusCode::STATUS_CODE_UNSET);
}
$row['status'] = $status;
return new CollectorSpan($row);
}
// @return KeyValue[]
public function as_otlp_resource_attributes(iterable $spans): array
{
$attrs = [];
foreach ($spans as $span) {
foreach ($span->getResource()->getAttributes() as $k => $v) {
array_push($attrs, $this->as_otlp_key_value($k, $v->getValue()));
}
}
return $attrs;
}
public function as_otlp_resource_span(iterable $spans): ResourceSpans
{
// TODO: Should return an empty ResourceSpans when $spans is empty
// At the minute it returns an semi populated ResourceSpan
$ils = $convertedSpans = [];
foreach ($spans as $span) {
/** @var \OpenTelemetry\Sdk\InstrumentationLibrary $il */
$il = $span->getInstrumentationLibrary();
$ilKey = sprintf('%s@%s', $il->getName(), $il->getVersion()??'');
if (!isset($ils[$ilKey])) {
$convertedSpans[$ilKey] = [];
$ils[$ilKey] = new InstrumentationLibrary(['name' => $il->getName(), 'version' => $il->getVersion()??'']);
}
$convertedSpans[$ilKey][] = $this->as_otlp_span($span);
}
$ilSpans = [];
foreach ($ils as $ilKey => $il) {
$ilSpans[] = new InstrumentationLibrarySpans([
'instrumentation_library' => $il,
'spans' => $convertedSpans[$ilKey],
]);
}
return new Proto\Trace\V1\ResourceSpans([
'resource' => new Proto\Resource\V1\Resource([
'attributes' => $this->as_otlp_resource_attributes($spans),
]),
'instrumentation_library_spans' => $ilSpans,
]);
}
}

View File

@ -1,227 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\OtlpHttp;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use InvalidArgumentException;
use Opentelemetry\Proto\Collector\Trace\V1\ExportTraceServiceRequest;
use OpenTelemetry\Sdk\Trace;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Client\RequestExceptionInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
class Exporter implements Trace\Exporter
{
/**
* @var string
*/
private $endpointUrl;
/**
* @var string
*/
private $protocol;
/**
* @var string
*/
private $insecure;
/**
* @var string
*/
private $certificateFile;
/**
* @var array
*/
private $headers;
/**
* @var string
*/
private $compression;
/**
* @var int
*/
private $timeout;
/**
* @var SpanConverter
*/
private $spanConverter;
/**
* @var bool
*/
private $running = true;
/**
* @var ClientInterface
*/
private $client;
/**
* @var RequestFactoryInterface
*/
private $requestFactory;
/**
* @var StreamFactoryInterface
*/
private $streamFactory;
/**
* Exporter constructor.
*/
public function __construct(
ClientInterface $client,
RequestFactoryInterface $requestFactory,
StreamFactoryInterface $streamFactory,
SpanConverter $spanConverter = null
) {
// Set default values based on presence of env variable
$this->endpointUrl = getenv('OTEL_EXPORTER_OTLP_ENDPOINT') ?: 'https://localhost:55681/v1/traces';
$this->protocol = getenv('OTEL_EXPORTER_OTLP_PROTOCOL') ?: 'http/protobuf';
$this->certificateFile = getenv('OTEL_EXPORTER_OTLP_CERTIFICATE') ?: 'none';
$this->headers = $this->processHeaders(getenv('OTEL_EXPORTER_OTLP_HEADERS'));
$this->compression = getenv('OTEL_EXPORTER_OTLP_COMPRESSION') ?: 'none';
$this->timeout =(int) getenv('OTEL_EXPORTER_OTLP_TIMEOUT') ?: 10;
$this->client = $client;
$this->requestFactory = $requestFactory;
$this->streamFactory = $streamFactory;
$this->spanConverter = $spanConverter ?? new SpanConverter();
if ($this->protocol != 'http/protobuf') {
throw new InvalidArgumentException('Invalid OTLP Protocol Specified');
}
$parsedDsn = parse_url($this->endpointUrl);
if (!is_array($parsedDsn)) {
throw new InvalidArgumentException('Unable to parse provided DSN');
}
if (
!isset($parsedDsn['scheme'])
|| !isset($parsedDsn['host'])
|| !isset($parsedDsn['port'])
|| !isset($parsedDsn['path'])
) {
throw new InvalidArgumentException('Endpoint should have scheme, host, port and path');
}
}
/**
* Exports the provided Span data via the OTLP protocol
*
* @param iterable<Trace\ReadableSpan> $spans Array of Spans
* @return int return code, defined on the Exporter interface
*/
public function export(iterable $spans): int
{
if (!$this->running) {
return Exporter::FAILED_NOT_RETRYABLE;
}
if (empty($spans)) {
return Trace\Exporter::SUCCESS;
}
$resourcespans = [$this->spanConverter->as_otlp_resource_span($spans)];
$exportrequest = new ExportTraceServiceRequest([
'resource_spans' => $resourcespans,
]);
$bytes = $exportrequest->serializeToString();
try {
$request = $this->requestFactory
->createRequest('POST', $this->endpointUrl)
->withHeader('content-type', 'application/x-protobuf');
foreach ($this->headers as $header => $value) {
$request = $request->withHeader($header, $value);
}
if ($this->compression === 'gzip') {
// TODO: Add Tests
$body = $this->streamFactory->createStream(gzencode($bytes));
$request = $request->withHeader('Content-Encoding', 'gzip');
} else {
$body = $this->streamFactory->createStream($bytes);
}
$request = $request->withBody($body);
$response = $this->client->sendRequest($request);
} catch (RequestExceptionInterface $e) {
return Trace\Exporter::FAILED_NOT_RETRYABLE;
} catch (NetworkExceptionInterface | ClientExceptionInterface $e) {
return Trace\Exporter::FAILED_RETRYABLE;
}
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) {
return Trace\Exporter::FAILED_NOT_RETRYABLE;
}
if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) {
return Trace\Exporter::FAILED_RETRYABLE;
}
return Trace\Exporter::SUCCESS;
}
/**
* processHeaders converts comma separated headers into an array
*/
public function processHeaders($headers): array
{
if (empty($headers)) {
return [];
}
$pairs = explode(',', $headers);
$metadata = [];
foreach ($pairs as $pair) {
$kv = explode('=', $pair, 2);
if (count($kv) !== 2) {
throw new InvalidArgumentException('Invalid headers passed');
}
list($key, $value) = $kv;
$metadata[$key] = $value;
}
return $metadata;
}
public function shutdown(): void
{
$this->running = false;
}
public static function fromConnectionString(string $endpointUrl = null, string $name = null, $args = null)
{
$factory = new HttpFactory();
$exporter = new Exporter(
new Client(),
$factory,
$factory
);
return $exporter;
}
}

View File

@ -1,187 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\OtlpHttp;
use Opentelemetry\Proto;
use Opentelemetry\Proto\Common\V1\AnyValue;
use Opentelemetry\Proto\Common\V1\ArrayValue;
use Opentelemetry\Proto\Common\V1\InstrumentationLibrary;
use Opentelemetry\Proto\Common\V1\KeyValue;
use Opentelemetry\Proto\Trace\V1\InstrumentationLibrarySpans;
use Opentelemetry\Proto\Trace\V1\ResourceSpans;
use Opentelemetry\Proto\Trace\V1\Span as CollectorSpan;
use Opentelemetry\Proto\Trace\V1\Span\Event;
use Opentelemetry\Proto\Trace\V1\Span\SpanKind;
use Opentelemetry\Proto\Trace\V1\Status;
use Opentelemetry\Proto\Trace\V1\Status\StatusCode;
use OpenTelemetry\Sdk\Trace\ReadableSpan;
use OpenTelemetry\Sdk\Trace\SpanStatus;
class SpanConverter
{
public function as_otlp_key_value($key, $value): KeyValue
{
return new KeyValue([
'key' => $key,
'value' => $this->as_otlp_any_value($value),
]);
}
public function as_otlp_any_value($value): AnyValue
{
$result = new AnyValue();
switch (true) {
case is_array($value):
$values = [];
foreach ($value as $element) {
array_push($values, $this->as_otlp_any_value($element));
}
$result->setArrayValue(new ArrayValue(['values' => $values]));
break;
case is_int($value):
$result->setIntValue($value);
break;
case is_bool($value):
$result->setBoolValue($value);
break;
case is_double($value):
$result->setDoubleValue($value);
break;
case is_string($value):
$result->setStringValue($value);
break;
}
return $result;
}
public function as_otlp_span_kind($kind): int
{
switch ($kind) {
case 0: return SpanKind::SPAN_KIND_INTERNAL;
case 1: return SpanKind::SPAN_KIND_CLIENT;
case 2: return SpanKind::SPAN_KIND_SERVER;
case 3: return SpanKind::SPAN_KIND_PRODUCER;
case 4: return SpanKind::SPAN_KIND_CONSUMER;
}
return SpanKind::SPAN_KIND_UNSPECIFIED;
}
public function as_otlp_span(ReadableSpan $span): CollectorSpan
{
$end_timestamp = ($span->getStartEpochTimestamp() + $span->getDuration());
$parent_span = $span->getParent();
$parent_span_id = $parent_span ? $parent_span->getSpanId() : false;
$row = [
'trace_id' => hex2bin($span->getContext()->getTraceId()),
'span_id' => hex2bin($span->getContext()->getSpanId()),
'parent_span_id' => $parent_span_id ? hex2bin($parent_span_id) : null,
'name' => $span->getSpanName(),
'start_time_unix_nano' => $span->getStartEpochTimestamp(),
'end_time_unix_nano' => $end_timestamp,
'kind' => $this->as_otlp_span_kind($span->getSpanKind()),
// 'trace_state' => $span->getContext()
// 'links' =>
];
foreach ($span->getEvents() as $event) {
if (!array_key_exists('events', $row)) {
$row['events'] = [];
}
$attrs = [];
foreach ($event->getAttributes() as $k => $v) {
array_push($attrs, $this->as_otlp_key_value($k, $v->getValue()));
}
$row['events'][] = new Event([
'time_unix_nano' => $event->getTimestamp(),
'name' => $event->getName(),
'attributes' => $attrs,
]);
}
foreach ($span->getAttributes() as $k => $v) {
if (!array_key_exists('attributes', $row)) {
$row['attributes'] = [];
}
array_push($row['attributes'], $this->as_otlp_key_value($k, $v->getValue()));
}
$status = new Status();
switch ($span->getStatus()->getCanonicalStatusCode()) {
case SpanStatus::OK:
$status->setCode(StatusCode::STATUS_CODE_OK);
break;
case SpanStatus::ERROR:
$status->setCode(StatusCode::STATUS_CODE_ERROR)->setMessage($span->getStatus()->getStatusDescription());
break;
default:
$status->setCode(StatusCode::STATUS_CODE_UNSET);
}
$row['status'] = $status;
return new CollectorSpan($row);
}
// @return KeyValue[]
public function as_otlp_resource_attributes(iterable $spans): array
{
$attrs = [];
foreach ($spans as $span) {
foreach ($span->getResource()->getAttributes() as $k => $v) {
array_push($attrs, $this->as_otlp_key_value($k, $v->getValue()));
}
}
return $attrs;
}
public function as_otlp_resource_span(iterable $spans): ResourceSpans
{
// TODO: Should return an empty ResourceSpans when $spans is empty
// At the minute it returns an semi populated ResourceSpan
$ils = $convertedSpans = [];
foreach ($spans as $span) {
/** @var \OpenTelemetry\Sdk\InstrumentationLibrary $il */
$il = $span->getInstrumentationLibrary();
$ilKey = sprintf('%s@%s', $il->getName(), $il->getVersion()??'');
if (!isset($ils[$ilKey])) {
$convertedSpans[$ilKey] = [];
$ils[$ilKey] = new InstrumentationLibrary(['name' => $il->getName(), 'version' => $il->getVersion()??'']);
}
$convertedSpans[$ilKey][] = $this->as_otlp_span($span);
}
$ilSpans = [];
foreach ($ils as $ilKey => $il) {
$ilSpans[] = new InstrumentationLibrarySpans([
'instrumentation_library' => $il,
'spans' => $convertedSpans[$ilKey],
]);
}
return new Proto\Trace\V1\ResourceSpans([
'resource' => new Proto\Resource\V1\Resource([
'attributes' => $this->as_otlp_resource_attributes($spans),
]),
'instrumentation_library_spans' => $ilSpans,
]);
}
}

View File

@ -1,141 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\Zipkin;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use InvalidArgumentException;
use OpenTelemetry\Sdk\Trace;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Client\RequestExceptionInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
/**
* Class ZipkinExporter - implements the export interface for data transfer via Zipkin protocol
* @package OpenTelemetry\Exporter
*/
class Exporter implements Trace\Exporter
{
/**
* @var string
*/
private $endpointUrl;
/**
* @var SpanConverter
*/
private $spanConverter;
/**
* @var bool
*/
private $running = true;
/**
* @var ClientInterface
*/
private $client;
private $requestFactory;
private $streamFactory;
public function __construct(
$name,
string $endpointUrl,
ClientInterface $client,
RequestFactoryInterface $requestFactory,
StreamFactoryInterface $streamFactory,
SpanConverter $spanConverter = null
) {
$parsedDsn = parse_url($endpointUrl);
if (!is_array($parsedDsn)) {
throw new InvalidArgumentException('Unable to parse provided DSN');
}
if (
!isset($parsedDsn['scheme'])
|| !isset($parsedDsn['host'])
|| !isset($parsedDsn['port'])
|| !isset($parsedDsn['path'])
) {
throw new InvalidArgumentException('Endpoint should have scheme, host, port and path');
}
$this->endpointUrl = $endpointUrl;
$this->client = $client;
$this->requestFactory = $requestFactory;
$this->streamFactory = $streamFactory;
$this->spanConverter = $spanConverter ?? new SpanConverter($name);
}
/**
* Exports the provided Span data via the Zipkin protocol
*
* @param iterable<Trace\ReadableSpan> $spans Array of Spans
* @return int return code, defined on the Exporter interface
*/
public function export(iterable $spans): int
{
if (!$this->running) {
return Exporter::FAILED_NOT_RETRYABLE;
}
if (empty($spans)) {
return Trace\Exporter::SUCCESS;
}
$convertedSpans = [];
foreach ($spans as $span) {
array_push($convertedSpans, $this->spanConverter->convert($span));
}
try {
$body = $this->streamFactory->createStream(json_encode($convertedSpans));
$request = $this->requestFactory
->createRequest('POST', $this->endpointUrl)
->withBody($body)
->withHeader('content-type', 'application/json');
$response = $this->client->sendRequest($request);
} catch (RequestExceptionInterface $e) {
return Trace\Exporter::FAILED_NOT_RETRYABLE;
} catch (NetworkExceptionInterface | ClientExceptionInterface $e) {
return Trace\Exporter::FAILED_RETRYABLE;
}
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) {
return Trace\Exporter::FAILED_NOT_RETRYABLE;
}
if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) {
return Trace\Exporter::FAILED_RETRYABLE;
}
return Trace\Exporter::SUCCESS;
}
public function shutdown(): void
{
$this->running = false;
}
public static function fromConnectionString(string $endpointUrl, string $name, $args = null)
{
$factory = new HttpFactory();
$exporter = new Exporter(
$name,
$endpointUrl,
new Client(),
$factory,
$factory
);
return $exporter;
}
}

View File

@ -1,80 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\Zipkin;
use OpenTelemetry\Sdk\Trace\ReadableSpan;
class SpanConverter
{
const STATUS_CODE_TAG_KEY = 'op.status_code';
const STATUS_DESCRIPTION_TAG_KEY = 'op.status_description';
/**
* @var string
*/
private $serviceName;
public function __construct(string $serviceName)
{
$this->serviceName = $serviceName;
}
private function sanitiseTagValue($value)
{
// Casting false to string makes an empty string
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
// Zipkin tags must be strings, but opentelemetry
// accepts strings, booleans, numbers, and lists of each.
if (is_array($value)) {
return join(',', array_map([$this, 'sanitiseTagValue'], $value));
}
// Floats will lose precision if their string representation
// is >=14 or >=17 digits, depending on PHP settings.
// Can also throw E_RECOVERABLE_ERROR if $value is an object
// without a __toString() method.
// This is possible because OpenTelemetry\Trace\Span does not verify
// setAttribute() $value input.
return (string) $value;
}
public function convert(ReadableSpan $span)
{
$spanParent = $span->getParent();
$row = [
'id' => $span->getContext()->getSpanId(),
'traceId' => $span->getContext()->getTraceId(),
'parentId' => $spanParent ? $spanParent->getSpanId() : null,
'localEndpoint' => [
'serviceName' => $this->serviceName,
],
'name' => $span->getSpanName(),
'timestamp' => (int) ($span->getStartEpochTimestamp() / 1e3), // RealtimeClock in microseconds
'duration' => (int) (($span->getEnd() - $span->getStart()) / 1e3), // Diff in microseconds
'tags' => [
self::STATUS_CODE_TAG_KEY => $span->getStatus()->getCanonicalStatusCode(),
self::STATUS_DESCRIPTION_TAG_KEY => $span->getStatus()->getStatusDescription(),
],
];
foreach ($span->getAttributes() as $k => $v) {
$row['tags'][$k] = $this->sanitiseTagValue($v->getValue());
}
foreach ($span->getEvents() as $event) {
if (!array_key_exists('annotations', $row)) {
$row['annotations'] = [];
}
$row['annotations'][] = [
'timestamp' => (int) ($event->getTimestamp() / 1e3), // RealtimeClock in microseconds
'value' => $event->getName(),
];
}
return $row;
}
}

View File

@ -1,171 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\ZipkinToNewrelic;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use InvalidArgumentException;
use OpenTelemetry\Sdk\Trace;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Client\RequestExceptionInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
/**
* Class ZipkinExporter - implements the export interface for data transfer via Zipkin protocol
* @package OpenTelemetry\Exporter
*
* This is an experimental, non-supported exporter.
* It will send PHP Otel trace data end to end across the internet to a functional backend.
* Needs a license key to connect. For a free account/key, go to: https://newrelic.com/signup/
*/
class Exporter implements Trace\Exporter
{
/**
* @var string
*/
private $endpointUrl;
/**
* @var string
*/
private $licenseKey;
/**
* @var SpanConverter
*/
private $spanConverter;
/**
* @var bool
*/
private $running = true;
/**
* @var ClientInterface
*/
private $client;
/**
* @var RequestFactoryInterface
*/
private $requestFactory;
/**
* @var StreamFactoryInterface
*/
private $streamFactory;
/**
* @var string
*/
private $name;
public function __construct(
$name,
string $endpointUrl,
string $licenseKey,
ClientInterface $client,
RequestFactoryInterface $requestFactory,
StreamFactoryInterface $streamFactory,
SpanConverter $spanConverter = null
) {
$parsedDsn = parse_url($endpointUrl);
if (!is_array($parsedDsn)) {
throw new InvalidArgumentException('Unable to parse provided DSN');
}
if (
!isset($parsedDsn['scheme'])
|| !isset($parsedDsn['host'])
|| !isset($parsedDsn['path'])
) {
throw new InvalidArgumentException('Endpoint should have scheme, host, port and path');
}
$this->name = $name;
$this->endpointUrl = $endpointUrl;
$this->licenseKey = $licenseKey;
$this->client = $client;
$this->requestFactory = $requestFactory;
$this->streamFactory = $streamFactory;
$this->spanConverter = $spanConverter ?? new SpanConverter($name);
}
/**
* Exports the provided Span data via the Zipkin protocol
*
* @param iterable<Trace\ReadableSpan> $spans Array of Spans
* @return int return code, defined on the Exporter interface
*/
public function export(iterable $spans): int
{
if (!$this->running) {
return Exporter::FAILED_NOT_RETRYABLE;
}
if (empty($spans)) {
return Trace\Exporter::SUCCESS;
}
$convertedSpans = [];
foreach ($spans as $span) {
array_push($convertedSpans, $this->spanConverter->convert($span));
}
try {
$body = $this->streamFactory->createStream(json_encode($convertedSpans));
$request = $this->requestFactory
->createRequest('POST', $this->endpointUrl)
->withBody($body)
->withHeader('content-type', 'application/json')
->withAddedHeader('Api-Key', $this->licenseKey)
->withAddedHeader('Data-Format', 'zipkin')
->withAddedHeader('Data-Format-Version', '2');
$response = $this->client->sendRequest($request);
} catch (RequestExceptionInterface $e) {
return Trace\Exporter::FAILED_NOT_RETRYABLE;
} catch (NetworkExceptionInterface | ClientExceptionInterface $e) {
return Trace\Exporter::FAILED_RETRYABLE;
}
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) {
return Trace\Exporter::FAILED_NOT_RETRYABLE;
}
if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) {
return Trace\Exporter::FAILED_RETRYABLE;
}
return Trace\Exporter::SUCCESS;
}
public function shutdown(): void
{
$this->running = false;
}
public static function fromConnectionString(string $endpointUrl, string $name, $args)
{
if ($args == false) {
throw new Exception('Invalid license key.');
}
$factory = new HttpFactory();
$exporter = new Exporter(
$name,
$endpointUrl,
$args,
new Client(),
$factory,
$factory
);
return $exporter;
}
}

View File

@ -1,80 +0,0 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\ZipkinToNewrelic;
use OpenTelemetry\Sdk\Trace\ReadableSpan;
class SpanConverter
{
const STATUS_CODE_TAG_KEY = 'otel.status_code';
const STATUS_DESCRIPTION_TAG_KEY = 'otel.status_description';
/**
* @var string
*/
private $serviceName;
public function __construct(string $serviceName)
{
$this->serviceName = $serviceName;
}
private function sanitiseTagValue($value)
{
// Casting false to string makes an empty string
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
// Zipkin tags must be strings, but opentelemetry
// accepts strings, booleans, numbers, and lists of each.
if (is_array($value)) {
return join(',', array_map([$this, 'sanitiseTagValue'], $value));
}
// Floats will lose precision if their string representation
// is >=14 or >=17 digits, depending on PHP settings.
// Can also throw E_RECOVERABLE_ERROR if $value is an object
// without a __toString() method.
// This is possible because OpenTelemetry\Trace\Span does not verify
// setAttribute() $value input.
return (string) $value;
}
public function convert(ReadableSpan $span)
{
$spanParent = $span->getParent();
$row = [
'id' => $span->getContext()->getSpanId(),
'traceId' => $span->getContext()->getTraceId(),
'parentId' => $spanParent ? $spanParent->getSpanId() : null,
'localEndpoint' => [
'serviceName' => $this->serviceName,
],
'name' => $span->getSpanName(),
'timestamp' => (int) ($span->getStartEpochTimestamp() / 1e3), // RealtimeClock in microseconds
'duration' => (int) (($span->getEnd() - $span->getStart()) / 1e3), // Diff in microseconds
'tags' => [
self::STATUS_CODE_TAG_KEY => $span->getStatus()->getCanonicalStatusCode(),
self::STATUS_DESCRIPTION_TAG_KEY => $span->getStatus()->getStatusDescription(),
],
];
foreach ($span->getAttributes() as $k => $v) {
$row['tags'][$k] = $this->sanitiseTagValue($v->getValue());
}
foreach ($span->getEvents() as $event) {
if (!array_key_exists('annotations', $row)) {
$row['annotations'] = [];
}
$row['annotations'][] = [
'timestamp' => (int) ($event->getTimestamp() / 1e3), // RealtimeClock in microseconds
'value' => $event->getName(),
];
}
return $row;
}
}

14
deptrac.baseline.yaml Normal file
View File

@ -0,0 +1,14 @@
deptrac:
skip_violations:
/src/Extension/Propagator/B3/_register.php:
- OpenTelemetry\SDK\Registry
/src/Extension/Propagator/CloudTrace/_register.php:
- OpenTelemetry\SDK\Registry
/src/Extension/Propagator/Jaeger/_register.php:
- OpenTelemetry\SDK\Registry
OpenTelemetry\API\Configuration\Config\ComponentProvider:
- Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition
- Symfony\Component\Config\Definition\Builder\NodeBuilder
OpenTelemetry\API\Configuration\Config\ComponentProviderRegistry:
- Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition
- Symfony\Component\Config\Definition\Builder\NodeDefinition

168
deptrac.yaml Normal file
View File

@ -0,0 +1,168 @@
imports:
- deptrac.baseline.yaml
deptrac:
analyser:
types:
- class
- class_superglobal
- use
- file
- function
- function_superglobal
paths:
- ./src
- ./proto
- ./tests
- ./deptrac/polyfills
- ./vendor/symfony/polyfill-php83/Resources/stubs
exclude_files:
- '#.*test.*#'
layers:
- name: API
collectors:
- type: directory
value: src/API/.*
- name: SDK
collectors:
- type: directory
value: src/SDK/.*
- name: ConfigSDK
collectors:
- type: directory
value: src/Config/SDK/.*
- name: Context
collectors:
- type: directory
value: src/Context/.*
- name: SemConv
collectors:
- type: directory
value: src/SemConv/.*
- name: Contrib
collectors:
- type: directory
value: src/Contrib/.*
- name: Extension
collectors:
- type: directory
value: src/Extension/.*
- name: OtelProto
collectors:
- type: directory
value: proto/otel/.*
- name: GoogleProtobuf
collectors:
- type: className
regex: ^Google\\Protobuf\\*
- name: Grpc
collectors:
- type: className
regex: ^Grpc\\*
- name: PsrLog
collectors:
- type: className
regex: ^Psr\\Log\\*
- name: PsrHttp
collectors:
- type: className
regex: ^Psr\\Http\\*
- name: HttpPlug
collectors:
- type: className
regex: ^Http\\*
- name: Prometheus
collectors:
- type: className
regex: ^Prometheus\\*
- name: FFI
collectors:
- type: className
regex: ^FFI\\*
- name: Composer
collectors:
- type: className
regex: ^Composer\\*
- name: HttpClients
collectors:
- type: className
value: ^Symfony\\Component\\HttpClient\\*
- type: className
value: ^GuzzleHttp\\*
- type: className
value: ^Buzz\\*
- name: SPI
collectors:
- type: className
value: ^Nevay\\SPI\\*
- name: SymfonyConfig
collectors:
- type: className
value: ^Symfony\\Component\\Config\\*
- type: className
value: ^Symfony\\Component\\Yaml\\*
- type: className
value: ^Symfony\\Component\\VarExporter\\*
- name: RamseyUuid
collectors:
- type: className
regex: ^Ramsey\\Uuid\\*
- name: NyholmPsr7Server
collectors:
- type: className
regex: ^Nyholm\\Psr7Server\\*
- name: Polyfills
collectors:
- type: directory
value: deptrac/polyfills/.*
- type: directory
value: vendor/symfony/polyfill-php83
- name: DotenvProvider
collectors:
- type: className
regex: ^Symfony\\Component\\Dotenv\\*
- type: className
regex: ^Dotenv\\*
ruleset:
Context:
- FFI
- Polyfills
SemConv: ~
ConfigSDK:
- SymfonyConfig
- API
- SDK
- SPI
- PsrLog
- Composer
- Context
- Contrib
- Extension
- Polyfills
- DotenvProvider
API:
- Context
- PsrLog
- SPI
- Polyfills
SDK:
- +API
- ConfigSDK
- SemConv
- PsrHttp
- HttpPlug
- Composer
- HttpClients
- SPI
- RamseyUuid
- NyholmPsr7Server
Contrib:
- +SDK
- +OtelProto
- Grpc
- Prometheus
Extension:
- +API
OtelProto:
- GoogleProtobuf
- Grpc

View File

@ -0,0 +1,5 @@
<?php
namespace OpenTelemetry\Config\SDK\Configuration;
class ComponentPlugin {}

View File

@ -0,0 +1,5 @@
<?php
namespace OpenTelemetry\Config\SDK\Configuration;
class ComponentProvider {}

View File

@ -0,0 +1,5 @@
<?php
namespace OpenTelemetry\Config\SDK\Configuration;
class ComponentProviderRegistry {}

View File

@ -0,0 +1,5 @@
<?php
namespace OpenTelemetry\Config\SDK\Configuration;
class Context {}

View File

@ -0,0 +1,3 @@
Polyfills for deptrac, which represent classes missing from some PHP versions, or classes
that deptrac does not understand.
We also use some symfony polyfills for deptrac, under `vendor/symfony/polyfill-*`.

View File

@ -1,13 +1,11 @@
version: '3.7'
services:
php:
build:
context: .
dockerfile: docker/Dockerfile
image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-8.1}
volumes:
- ./:/usr/src/myapp
depends_on:
- otel-collector
- collector
zipkin:
image: openzipkin/zipkin-slim
ports:
@ -19,8 +17,7 @@ services:
ports:
- 9412:9412
- 16686:16686
otel-collector:
platform: linux/amd64
collector:
image: otel/opentelemetry-collector-contrib
command: ["--config=/etc/otel-collector-config.yml"]
volumes:
@ -32,5 +29,5 @@ services:
- "13133:13133" # health_check extension
- "9411" # Zipkin receiver
- "4317:4317" # OTLP gRPC receiver
- "55681:55681" # Legacy OTLP/HTTP Port
- "4318:4318" # OTLP/HTTP receiver
- "55680:55679" # zpages extension

View File

@ -0,0 +1,26 @@
version: '3.8'
services:
web:
image: nginx:alpine
ports:
- '8080:80'
depends_on:
- php
volumes:
- ./docker/examples/nginx.conf:/etc/nginx/conf.d/default.conf:ro
php:
build:
context: .
dockerfile: docker/examples/Dockerfile
args:
- PHP_VERSION=8.1-fpm
- EXT_ENABLE=ffi
environment:
- OTEL_PHP_FIBERS_ENABLED=true
command:
- php-fpm
- -d
- opcache.preload=/php/vendor/autoload.php
volumes:
- ./tests/Context/Fiber/test_context_switching_ffi_observer.phpt:/var/www/public/index.php
- ./:/php

View File

@ -0,0 +1,11 @@
services:
phpdoc:
image: phpdoc/phpdoc:3
volumes:
- ./:/data
preview:
image: nginx:alpine
ports:
- 8080:80
volumes:
- ./docs/build:/usr/share/nginx/html

View File

@ -15,16 +15,19 @@ services:
ports:
- 8080:80
depends_on:
- php-prometheus
- php
volumes:
- ./docker/prometheus/nginx.conf:/etc/nginx/conf.d/default.conf
- ./docker/prometheus/index.php:/var/www/public/index.php
php-prometheus:
- ./docker/examples/nginx.conf:/etc/nginx/conf.d/default.conf:ro
php:
build:
context: .
dockerfile: docker/prometheus/Dockerfile
dockerfile: docker/examples/Dockerfile
args:
- PHP_VERSION=8.0-fpm
- EXT_ENABLE=redis
volumes:
- ./:/var/www/public
- ./examples/prometheus/index.php:/var/www/public/index.php
- ./:/php
depends_on:
- redis
- prometheus
- prometheus

View File

@ -1,7 +0,0 @@
version: '3.7'
services:
proto:
image: socialpoint/protobuf-tools
volumes:
- ./:/mnt
command: sh -c "/mnt/script/proto_gen.sh"

View File

@ -1,9 +1,11 @@
version: '3.7'
services:
php:
build:
context: .
dockerfile: docker/Dockerfile
image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-8.1}
volumes:
- ./:/usr/src/myapp
- ./:/usr/src/open-telemetry/
user: "${PHP_USER}:root"
environment:
XDEBUG_MODE: ${XDEBUG_MODE:-off}
XDEBUG_CONFIG: ${XDEBUG_CONFIG:-''}

View File

@ -1,11 +1,11 @@
version: '3.7'
services:
php:
build:
context: .
dockerfile: docker/Dockerfile
image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-8.1}
volumes:
- ./:/usr/src/myapp
user: "${PHP_USER}:root"
env_file:
- .env
zipkin:
image: openzipkin/zipkin-slim
ports:
@ -17,3 +17,8 @@ services:
ports:
- 9412:9412
- 16686:16686
collector:
image: otel/opentelemetry-collector-contrib
command: [ "--config=/etc/otel-collector-config.yml" ]
volumes:
- ./files/collector/otel-collector-config.yml:/etc/otel-collector-config.yml

View File

@ -1,17 +1,46 @@
FROM php:8-buster
RUN apt-get -y update && apt-get -y install git zip && \
curl -sS https://getcomposer.org/installer | php && \
mv composer.phar /usr/local/bin/composer && \
chmod +x /usr/local/bin/composer && \
pecl install ast-1.0.10 xdebug && \
docker-php-ext-enable ast xdebug && \
# The pcntl extension is used for speeding up `make phan`
docker-php-ext-install pcntl
# install GRPC
RUN apt install -y --no-install-recommends zlib1g-dev && \
pecl install grpc && \
docker-php-ext-enable grpc
FROM composer:2.8 AS composer
FROM debian:bullseye
WORKDIR /usr/src/myapp
RUN apt-get update \
&& apt-get install -y --no-install-recommends git wget gnupg2 \
&& rm -rf /var/lib/apt/lists/* \
&& groupadd --gid 1000 php \
&& useradd --system --uid 1000 --gid php --shell /bin/bash --create-home php
RUN apt-get update && apt-get install -y lsb-release apt-transport-https ca-certificates \
&& echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list \
&& wget -qO - https://packages.sury.org/php/apt.gpg | apt-key add - \
&& apt-get update
ARG PHP_VERSION=8.3
RUN apt-get install -y \
php${PHP_VERSION}-ast \
php${PHP_VERSION}-cli \
php${PHP_VERSION}-curl \
php${PHP_VERSION}-dev \
php${PHP_VERSION}-grpc \
php${PHP_VERSION}-intl \
php${PHP_VERSION}-mbstring \
php${PHP_VERSION}-opcache \
php${PHP_VERSION}-opentelemetry \
php${PHP_VERSION}-protobuf \
php${PHP_VERSION}-simplexml \
php${PHP_VERSION}-sockets \
php${PHP_VERSION}-xdebug \
php${PHP_VERSION}-zip \
php${PHP_VERSION}-mongodb \
php${PHP_VERSION}-amqp \
php${PHP_VERSION}-rdkafka \
php${PHP_VERSION}-mysqli \
php${PHP_VERSION}-pgsql \
unzip
COPY --from=composer /usr/bin/composer /usr/local/bin/composer
RUN echo "grpc.enable_fork_support = 1" > $(php-config --ini-dir)/40-otel-dev.ini \
&& echo "grpc.poll_strategy = epoll1" >> $(php-config --ini-dir)/40-otel-dev.ini \
&& echo "zend.assertions = 1" >> $(php-config --ini-dir)/40-otel-dev.ini
USER php

View File

@ -0,0 +1,34 @@
ARG PHP_VERSION
ARG PHP_ALPINE_VERSION
FROM php:${PHP_VERSION:+${PHP_VERSION}-}alpine${PHP_ALPINE_VERSION} AS php
ENV PROJECT_ROOT=/php
RUN set -eux; \
apk add --no-cache \
bash \
; \
adduser -u 1000 -DSh /php php php
ARG EXT_INSTALL
ARG EXT_ENABLE=''
RUN --mount=from=mlocati/php-extension-installer,dst=/build/extension-installer,src=/usr/bin/install-php-extensions \
set -eux; \
/build/extension-installer \
opcache \
${EXT_INSTALL:-${EXT_ENABLE}} \
; \
docker-php-ext-enable \
opcache \
${EXT_ENABLE} \
;
RUN set eux; \
mkdir -p /usr/local/lib/php/vendor; \
echo "<?php file_exists('/php/vendor/autoload.php') and require '/php/vendor/autoload.php';" > /usr/local/lib/php/vendor/autoload.php; \
echo 'auto_prepend_file=vendor/autoload.php' > "$PHP_INI_DIR/conf.d/99-autoload.ini"
USER php
WORKDIR /php

View File

@ -0,0 +1,12 @@
server {
listen 80;
server_name _;
root /var/www/public;
location / {
fastcgi_pass php:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}

View File

@ -0,0 +1,9 @@
version: '3.7'
services:
gitsplit:
image: jderusse/gitsplit
volumes:
- ../../:/srv
- ../../var/cache/gitsplit:/cache/gitsplit
environment:
GH_TOKEN: ${GITSPLIT_TOKEN:-''}

View File

@ -1,11 +0,0 @@
FROM php:7.3-fpm-alpine
RUN apk update && apk add --no-cache \
$PHPIZE_DEPS
RUN pecl channel-update pecl.php.net && \
pecl install redis \
&& docker-php-ext-enable redis
# Clean
RUN rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /var/cache/*

View File

@ -1,25 +0,0 @@
server {
listen 80;
index index.php index.html;
server_name 127.0.0.1 localhost;
root /var/www/public/examples/prometheus;
access_log /dev/stdout;
error_log /dev/stdout debug;
underscores_in_headers on;
location / {
try_files $uri /index.php?$args;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass php-prometheus:9000;
fastcgi_index index.php;
fastcgi_read_timeout 1000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}

View File

@ -1,256 +0,0 @@
# Integrating Opentelemetry PHP into Laravel Applications
## Introduction
Distributed tracing helps developers and management gain insights into how well applications perform in terms of traces, metrics, and logs. This guide shows how developers can integrate OpenTelemetry PHP into their Laravel applications for the above benefits. Our example application visualizes exceptions from a Laravel application using both Jaeger and Zipkin.
To follow this guide you will need:
* PHP Installed; this example uses PHP 7.4.
* [Composer](https://getcomposer.org/download/ ) for dependency management.
* [Docker](https://docs.docker.com/get-docker/) for bundling our visualization tools. We have setup instructions for docker on this project's [readme](https://github.com/open-telemetry/opentelemetry-php#development).
This example uses Laravel version 8.40 .
## Step 1 - Creating a Laravel Application
The Laravel framework supports creating applications using composer. To do that, run `composer create-project <project-name>` . We are naming our project `otel-php-laravel-basic-example`, so the command is as follows:
`composer create-project laravel/laravel otel-php-laravel-basic-example`
To confirm that our application works, we can move to the application directory using `cd otel-php-laravel-basic-example` , then serve the application with `php artisan serve` .
![image](https://user-images.githubusercontent.com/22311928/115635306-5585e600-a303-11eb-8943-f50846b293b3.png)
Let's navigate to `http://127.0.0.1:8000` on our browser to see the default Laravel welcome page.
![image](https://user-images.githubusercontent.com/22311928/115635309-56b71300-a303-11eb-97bc-7c64e3f4da97.png)
## Step 2 - Require OpenTelemetry PHP Package
Starting from version `v.0.0.2`, the open-telemetry php package allows users to use their preferred HTTP layers for exporting traces. The benefit of this is that users can reuse already existing HTTP configurations for their applications. Hence, there is need to require packages that satisfy both `psr/http-client-implementation` and `psr/http-factory-implementation` before requiring the opentelemetry-php package.
By default, the Laravel framework utilizes `guzzlehttp/guzzle` and this satisfies `psr/http-client-implementation`, so we need to require the `guzzlehttp/psr7` to meet the `psr/http-factory-implementation` requirement. Let's run `composer require guzzlehttp/psr7:2.0.0-rc1`.
Note: We are specifying `2.0.0-rc1` as that is the release for `guzzlehttp/psr7` that includes HTTP factories as at the time of writing this guide.
Next, let's run `composer require open-telemetry/opentelemetry` to pull in the openTelemetry-php package.
## Step 3 - Bundle Zipkin and Jaeger into the Application
To visualize traces exported from our application, we need to integrate open source tracing tools [Zipkin](https://zipkin.io/) and [Jaeger](https://www.jaegertracing.io/) into our setup using docker.
First, we create a `docker-compose.yaml` file in the root of our project, with content as follows:
```yaml
version: '3.7'
services:
zipkin:
image: openzipkin/zipkin-slim
ports:
- 9411:9411
jaeger:
image: jaegertracing/all-in-one
environment:
COLLECTOR_ZIPKIN_HOST_PORT: 9412
ports:
- 9412:9412
- 16686:16686
```
Next, we pull in Zipkin and Jaeger by running `docker-compose up -d`. This might take some time, depending on your internet connection speed.
![image](https://user-images.githubusercontent.com/22311928/115635312-5880d680-a303-11eb-9f55-bcd80115abc9.png)
We can confirm that Zipkin is up by navigating to `http://localhost:9411/` on our browser. For Jaeger, navigating to `http://localhost:16686/` on our browser should display the Jaeger home page.
![image](https://user-images.githubusercontent.com/22311928/115635313-59196d00-a303-11eb-817c-37f4f6416fe1.png)
![image](https://user-images.githubusercontent.com/22311928/115635316-59b20380-a303-11eb-86e4-e15d0efd04d7.png)
## Step 5 - Instrument Laravel Application
For this step, we will utilize our OpenTelemetry PHP Library to export traces to both Zipkin and Jaeger.
The default entry point for Laravel applications is the `index.php` file located in the `public` folder. If we navigate to `public\index.php` we can see that the index file autoloads classes from packages within our vendor folder, making them easily useable within our application.
```php
require __DIR__.'/../vendor/autoload.php';
```
The other parts of the `index.php` file enable request and response resolution using the application kernel.
```php
$app = require_once __DIR__.'/../bootstrap/app.php';
$kernel = $app->make(Kernel::class);
$response = tap($kernel->handle(
$request = Request::capture()
))->send();
$kernel->terminate($request, $response);
```
It is worthy of note that resources(namespaces, classes, variables) created within the `index.php` file are available within the entire application.
To use open-telemetry specific classes within our application we have to import them at the top of our index file, using the `use` keyword. This is what our list of open-telemetry imported classes should look like:
```php
use OpenTelemetry\Contrib\Jaeger\Exporter as JaegerExporter;
use OpenTelemetry\Contrib\Zipkin\Exporter as ZipkinExporter;
use OpenTelemetry\Sdk\Trace\Clock;
use OpenTelemetry\Context\Context;
use OpenTelemetry\Sdk\Trace\Sampler\AlwaysOnSampler;
use OpenTelemetry\Sdk\Trace\SamplingResult;
use OpenTelemetry\Sdk\Trace\SpanProcessor\BatchSpanProcessor;
use OpenTelemetry\Sdk\Trace\TracerProvider;
use OpenTelemetry\Trace as API;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
```
Remember that these imports should go side by side with the default class imports that come with the `index.php` file.
Next, we create a sample recording trace using the [AlwaysOnSampler](https://github.com/open-telemetry/opentelemetry-php/blob/main/sdk/Trace/Sampler/AlwaysOnSampler.php) class, just before the app instance is created like below:
```php
$sampler = new AlwaysOnSampler();
$samplingResult = $sampler->shouldSample(
new Context(),
md5((string) microtime(true)),
'io.opentelemetry.example',
API\SpanKind::KIND_INTERNAL
);
```
Since we are looking to export traces to both Zipkin and Jaeger we have to make use of their exporters;
```php
$jaegerExporter = new JaegerExporter(
'Hello World Web Server Jaeger',
'http://localhost:9412/api/v2/spans',
new Client(),
new HttpFactory(),
new HttpFactory()
);
$zipkinExporter = new ZipkinExporter(
'Hello World Web Server Zipkin',
'http://localhost:9411/api/v2/spans',
new Client(),
new HttpFactory(),
new HttpFactory()
);
```
Next, we create a trace then add processors for each trace(One for Jaeger and another for Zipkin). Then we proceed to start and activate a span for each trace. We create a trace only if the RECORD AND SAMPLED sampling result condition passes as follows;
```php
if (SamplingResult::RECORD_AND_SAMPLE === $samplingResult->getDecision()) {
$jaegerTracer = (new TracerProvider(null, $sampler))
->addSpanProcessor(new BatchSpanProcessor($jaegerExporter, Clock::get()))
->getTracer('io.opentelemetry.contrib.php');
$zipkinTracer = (new TracerProvider(null, $sampler))
->addSpanProcessor(new BatchSpanProcessor($zipkinExporter, Clock::get()))
->getTracer('io.opentelemetry.contrib.php');
$request = Request::createFromGlobals();
$jaegerSpan = $jaegerTracer->startAndActivateSpan($request->getUri());
$zipkinSpan = $zipkinTracer->startAndActivateSpan($request->getUri());
}
```
Finally, we end the active spans if sampling is complete, by adding the following block at the end of the `index.php` file;
```php
if (SamplingResult::RECORD_AND_SAMPLE === $samplingResult->getDecision()) {
$zipkinSpan->end();
$jaegerSpan->end();
}
```
Let's confirm that we can see exported traces on both Zipkin and Jaeger. To do that, we need to reload `http://127.0.0.1:8000` on our browser;
We also need reload both Zipkin and Jaeger on our browser, using the URLs `http://localhost:9411/` and `http://localhost:16686/`. Do ensure that both your Laravel server and docker instance are running for this step.
For Jaeger under service, you should see a `Hello World Web Server Jaeger` service. Go ahead and click find traces to see exported traces.
![image](https://user-images.githubusercontent.com/22311928/115635317-5a4a9a00-a303-11eb-9840-2dba0e6475d8.png)
Once we click on `Find Traces`, you should be able to see traces like below:
![image](https://user-images.githubusercontent.com/22311928/115635318-5a4a9a00-a303-11eb-9d4e-69e45a3b810c.png)
We can click on a trace to get more information about the trace.
![image](https://user-images.githubusercontent.com/22311928/115635320-5ae33080-a303-11eb-8956-97d9f1ce0073.png)
For Zipkin, we can visualize our trace by clicking on `Run Query`
![image](https://user-images.githubusercontent.com/22311928/115635321-5b7bc700-a303-11eb-9d9d-19168e50445e.png)
Since resources in Laravel's `public\index.php` file are available to the entire application, we can use any of the already instantiated tracers to further instrument controllers or any other parts of our application.
Let's create a `Hello` controller to check this out. Run the command `php artisan make:controller HelloController`
![image](https://user-images.githubusercontent.com/22311928/115635322-5c145d80-a303-11eb-8071-1453edbaca14.png)
Next we need to add a route for accessing the controller. To do this we need to utilize the `HelloController` class within our web routes file located in the `routes\web.php` as follows:
```php
use App\Http\Controllers\HelloController;
```
Next we need to add a route and method for the controller.
```php
Route::get('/hello', [HelloController::class, 'index']);
```
The above snippet routes every GET request from the `/hello` route on the browser to an index method within the `HelloController` class. For now, this method does not exist, so we have to add it to our controller as follows
```php
public function index(){
return "hello";
}
```
Let's confirm that everything works well by visiting the `/hello` route on our browser.
![](https://user-images.githubusercontent.com/22311928/115635323-5c145d80-a303-11eb-869f-6fe18f7f01a4.png)
Now that we have the `index` method working, we can simulate adding an exception event to our Zipkin trace as follows:
```php
global $zipkinTracer;
if ($zipkinTracer) {
/** @var Span $span */
$span = $zipkinTracer->getActiveSpan();
$span->setAttribute('foo', 'bar');
$span->updateName('New name');
$childSpan = $zipkinTracer->startAndActivateSpan('Child span');
try {
throw new \Exception('Exception Example');
} catch (\Exception $exception) {
$span->setSpanStatus($exception->getCode(), $exception->getMessage());
}
$childSpan->end();
}
```
In the above snippet we change the span name and attributes for our Zipkin trace, we also add an exception event to the span.
We need to reload our `http://127.0.0.1:8000/hello` route, then navigate to Zipkin like before, to see that our span name gets updated to `new name` and our `Exception Example` is visible.
![image](https://user-images.githubusercontent.com/22311928/115635324-5cacf400-a303-11eb-947d-cf8205c0e93b.png)
## Summary
With the above example we have been able to instrument a Laravel application using the OpenTelemetry PHP library. You can fork the example project [here](https://github.com/prondubuisi/otel-php-laravel-basic-example).

291
docs/laravel-quickstart.md Normal file
View File

@ -0,0 +1,291 @@
# Exploring Opentelemetry in Laravel Applications
## Introduction
Distributed tracing helps developers and management gain insights into how well applications perform in terms of traces,
metrics, and logs. This guide shows how developers can integrate OpenTelemetry PHP into their Laravel applications for
the above benefits. Our example application visualizes exceptions from a Laravel application using both Jaeger and
Zipkin.
To follow this guide you will need:
* PHP Installed; this example uses PHP 7.4.
* [Composer](https://getcomposer.org/download/ ) for dependency management.
* [Docker](https://docs.docker.com/get-docker/) for bundling our visualization tools. We have setup instructions for
docker on this project's [readme](https://github.com/open-telemetry/opentelemetry-php#development).
This example uses Laravel version `9.1` and OpenTelemetry PHP SDK version `0.0.11`.
> ⚠ This example is only intended to introduce how OpenTelemetry can be used in a Laravel application. The
> example code is not suited for production applications, and must not be consulted for any code that goes into
> production.
## Step 1 - Creating a Laravel Application
The Laravel framework supports creating applications using composer. To do that,
run `composer create-project <project-name>`. We are naming our project `otel-php-laravel-basic-example`, so the
command is as follows:
`composer create-project laravel/laravel otel-php-laravel-basic-example`
To confirm that our application works, we can move to the application directory
using `cd otel-php-laravel-basic-example` , then serve the application with `php artisan serve` .
![image](https://user-images.githubusercontent.com/22311928/115635306-5585e600-a303-11eb-8943-f50846b293b3.png)
Let's navigate to `http://127.0.0.1:8000` on our browser to see the default Laravel welcome page.
![image](https://user-images.githubusercontent.com/22311928/115635309-56b71300-a303-11eb-97bc-7c64e3f4da97.png)
## Step 2 - Require OpenTelemetry PHP Package
Starting from version `v.0.0.2`, the open-telemetry php package allows users to use their preferred HTTP layers for
exporting traces. The benefit of this is that users can reuse already existing HTTP configurations for their
applications. Hence, there is need to require packages that satisfy both `psr/http-client-implementation`
and `psr/http-factory-implementation` before requiring the opentelemetry-php package.
By default, the Laravel framework utilizes `guzzlehttp/guzzle` and this satisfies `psr/http-client-implementation`, so
we need to require the `guzzlehttp/psr7` to meet the `psr/http-factory-implementation` requirement. Let's
run `composer require guzzlehttp/psr7:2.1`.
Note: We are specifying `2.1` as that is the release for `guzzlehttp/psr7` that includes HTTP factories as at the
time of writing this guide.
Starting from version `v.0.0.4`, opentelemetry-php package also requires `php-http/async-client-implementation`. Any
client implementation would work, but for this example, let's go ahead with `php-http/guzzle7-adapter`. Run
`composer require php-http/guzzle7-adapter` to install `php-http/guzzle7-adapter`.
Next, let's run `composer require open-telemetry/opentelemetry` to pull in the openTelemetry-php package. It is worthy
of note that this command pulls in the last stable release for the library.
## Step 3 - Bundle Zipkin and Jaeger into the Application
To visualize traces exported from our application, we need to integrate open source tracing
tools [Zipkin](https://zipkin.io/) and [Jaeger](https://www.jaegertracing.io/) into our setup using docker.
First, we create a `docker-compose.yaml` file in the root of our project, with content as follows:
```yaml
version: '3.7'
services:
zipkin:
image: openzipkin/zipkin-slim
ports:
- "9411:9411"
jaeger:
image: jaegertracing/all-in-one
environment:
COLLECTOR_ZIPKIN_HOST_PORT: 9412
ports:
- "9412:9412"
- "16686:16686"
```
Next, we pull in Zipkin and Jaeger by running `docker-compose up -d`. This might take some time, depending on your
internet connection speed.
![image](https://user-images.githubusercontent.com/22311928/115635312-5880d680-a303-11eb-9f55-bcd80115abc9.png)
We can confirm that Zipkin is up by navigating to `http://localhost:9411/` on our browser. For Jaeger, navigating
to `http://localhost:16686/` on our browser should display the Jaeger home page.
![image](https://user-images.githubusercontent.com/22311928/115635313-59196d00-a303-11eb-817c-37f4f6416fe1.png)
![image](https://user-images.githubusercontent.com/22311928/115635316-59b20380-a303-11eb-86e4-e15d0efd04d7.png)
## Step 5 - Instrument Laravel Application
For this step, we will utilize our OpenTelemetry PHP Library to export traces to both Zipkin and Jaeger.
The default entry point for Laravel applications is the `index.php` file located in the `public` folder. If we navigate
to `public\index.php` we can see that the index file autoloads classes from packages within our vendor folder, making
them easily usable within our application.
```php
require __DIR__.'/../vendor/autoload.php';
```
The other parts of the `index.php` file enable request and response resolution using the application kernel.
```php
$app = require_once __DIR__.'/../bootstrap/app.php';
$kernel = $app->make(Kernel::class);
$response = tap($kernel->handle(
$request = Request::capture()
))->send();
$kernel->terminate($request, $response);
```
It is worthy of note that resources(namespaces, classes, variables) created within the `index.php` file are available
within the entire application.
To use open-telemetry specific classes within our application we have to import them at the top of our index file, using
the `use` keyword. This is what our list of open-telemetry imported classes should look like:
```php
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use OpenTelemetry\API\Trace\Span;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\API\Trace\TracerInterface;
use OpenTelemetry\Contrib\Zipkin\Exporter as ZipkinExporter;
use OpenTelemetry\SDK\Common\Export\Http\PsrTransportFactory;
use OpenTelemetry\SDK\Trace\Sampler\AlwaysOnSampler;
use OpenTelemetry\SDK\Trace\SpanProcessor\BatchSpanProcessor;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
```
Remember that these imports should go side by side with the default class imports that come with the `index.php` file.
Next, we create a sample recording trace using
the [AlwaysOnSampler](https://github.com/open-telemetry/opentelemetry-php/blob/main/sdk/Trace/Sampler/AlwaysOnSampler.php)
class, which is default. Since we are looking to export traces to both Zipkin and Jaeger, we configure a tracer with exporters for both the
services just before the app instance is created like below;
```php
$httpClient = new Client();
$httpFactory = new HttpFactory();
$tracer = (new TracerProvider(
[
new SimpleSpanProcessor(
new OpenTelemetry\Contrib\Zipkin\Exporter(
PsrTransportFactory::discover()->create('http://zipkin:9411/api/v2/spans', 'application/json')
),
),
],
new AlwaysOnSampler(),
))->getTracer('Hello World Laravel Web Server');
```
Next we create a span from our tracer;
```php
$request = Request::capture();
$span = $tracer->spanBuilder($request->url())->startSpan();
$spanScope = $span->activate();
```
Finally, we end the active spans once and detach the span scope by adding the following block at the end of
the `index.php` file;
```php
$span->end();
$spanScope->detach();
```
Let's confirm that we can see exported traces on both Zipkin and Jaeger. To do that, we need to
reload `http://127.0.0.1:8000` on our browser;
We also need reload both Zipkin and Jaeger on our browser, using the URLs `http://localhost:9411/`
and `http://localhost:16686/`. Do ensure that both your Laravel server and docker instance are running for this step.
For Jaeger under service, you should see a `Hello World Web Server Jaeger` service. Go ahead and click find traces to
see exported traces.
![image](https://user-images.githubusercontent.com/22311928/115635317-5a4a9a00-a303-11eb-9840-2dba0e6475d8.png)
Once we click on `Find Traces`, you should be able to see traces like below:
![image](https://user-images.githubusercontent.com/22311928/115635318-5a4a9a00-a303-11eb-9d4e-69e45a3b810c.png)
We can click on a trace to get more information about the trace.
![image](https://user-images.githubusercontent.com/22311928/115635320-5ae33080-a303-11eb-8956-97d9f1ce0073.png)
For Zipkin, we can visualize our trace by clicking on `Run Query`
![image](https://user-images.githubusercontent.com/22311928/115635321-5b7bc700-a303-11eb-9d9d-19168e50445e.png)
Since resources in Laravel's `public\index.php` file are available to the entire application, we can use any of the
already instantiated tracers to further instrument controllers or any other parts of our application.
Let's create a `Hello` controller to check this out. Run the command `php artisan make:controller HelloController`
![image](https://user-images.githubusercontent.com/22311928/115635322-5c145d80-a303-11eb-8071-1453edbaca14.png)
Next we need to add a route for accessing the controller. To do this we need to utilize the `HelloController` class
within our web routes file located in the `routes\web.php` as follows:
```php
use App\Http\Controllers\HelloController;
```
Next we need to add a route and method for the controller.
```php
Route::get('/hello', [HelloController::class, 'index']);
```
The above snippet routes every GET request from the `/hello` route on the browser to an index method within
the `HelloController` class. For now, this method does not exist, so we have to add it to our controller in
`app\Http\Controllers\HelloController.php` as follows:
```php
public function index(){
return "hello";
}
```
Let's confirm that everything works well by visiting the `/hello` route on our browser.
![](https://user-images.githubusercontent.com/22311928/115635323-5c145d80-a303-11eb-869f-6fe18f7f01a4.png)
Now that we have the `index` method working, let's make changes to the existing rootSpan and create an exception in a
child span of the rootSpan. We can do the same as follows:
- Import the required functions on top of the file:
```php
use OpenTelemetry\API\Trace\Span;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\SDK\Trace\TracerProvider;
```
- Put the below snippet in `index()` function before the `return` statement:
```php
/** @var TracerProvider $tracer */
$tracer = TracerProvider::getDefaultTracer();
if ($tracer) {
/** @var Span $span */
$span = Span::getCurrent();
$span->setAttribute('foo', 'bar');
$span->setAttribute('Application', 'Laravel');
$span->setAttribute('foo', 'bar1');
$span->updateName('New name');
$childSpan = $tracer->spanBuilder('Child span')->startSpan();
$childScope = $childSpan->activate();
try {
throw new \Exception('Exception Example');
} catch (\Exception $exception) {
$childSpan->recordException($exception);
}
$childSpan->end();
$childScope->detach();
}
```
In the above snippet, we set two new attributes for the current span, and then change the value for one of the attribute
and the trace reflects the latest value. We also change the name of our current span and add an exception event to the
child span.
* Point to note: all the variables in `index.php` are available in this file. But we use inbuilt functions to get `$tracer`
rather than using the global variables.
We need to reload our `http://127.0.0.1:8000/hello` route, then navigate to Zipkin and Jaeger like before, to see that our
span name gets updated to `new name` and our `Exception Example` is visible.
![image](https://user-images.githubusercontent.com/22311928/115635324-5cacf400-a303-11eb-947d-cf8205c0e93b.png)
## Summary
With the above example we have been able to instrument a Laravel application using the OpenTelemetry PHP library. You
can fork the example project [here](https://github.com/prondubuisi/otel-php-laravel-basic-example).

View File

@ -1,240 +0,0 @@
# Integrating Opentelemetry PHP into Symfony Applications
## Introduction
As a developer, you might be wondering how OpenTelemetry could be beneficial to you. Without practical examples, the usefulness of distributed tracing can be difficult to grasp for persons without a cloud or site reliability engineering background. This user guide shows how OpenTelemetry could be useful to gain insights into exceptions happening within an application. This example uses the OpenTelemtry PHP library integrated into a Symfony application, bundled with Jaeger and Zipkin, for visualizing data.
## Prerequisites
To follow this guide you will need:
* PHP Installed, this example uses PHP 7.4.
* [Composer](https://getcomposer.org/download/ ) for dependency management.
* [Symfony CLI](https://symfony.com/download) for managing your Symfony application.
* [Docker](https://docs.docker.com/get-docker/) for bundling our visualization tools. We have setup instructions for docker on this project's [readme](https://github.com/open-telemetry/opentelemetry-php#development).
This example uses Symfony version 5.2 .
## Step 1 - Creating a Symfony Application
Create a Symfony application by running the command `symfony new my_project_name`. We are calling this example `otel-php-symfony-basic-example`, so the command is as follows;
`symfony new otel-php-symfony-basic-example` .
## Step 2 - Require and Test Symfony Dependencies
To define our routes within our controller methods, let's require the Doctrine annotation library by running the command `composer require doctrine/annotations`.
We can test that routes defined within Controllers work by creating a `HelloController.php` file within the `src\Controller` folder as follows:
```php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class HelloController extends AbstractController
{
/**
* @Route("/hello", name="hello")
*/
public function index(): Response
{
return new Response('Hello World');
}
}
```
To check out the routes available in our current project run `php bin/console debug:router`.
![image](https://user-images.githubusercontent.com/22311928/115637047-3e48f780-a307-11eb-9f75-2a5d033b572a.png)
Let's confirm that our application works by running the command `symfony server:start`.
![image](https://user-images.githubusercontent.com/22311928/115637051-4012bb00-a307-11eb-93b4-703b766f6324.png)
You can navigate to `http://127.0.0.1:8000/hello` route to see the `Hello world` response returned from the HelloController index method above.
![image](https://user-images.githubusercontent.com/22311928/115637055-4143e800-a307-11eb-8bb3-44060e5661fc.png)
## Step 3 - Require the OpenTelemetry PHP Library
For this step, we require the OpenTelemetry PHP Library by running the command `composer require open-telemetry/opentelemetry`. It is worthy of note that this command pulls in the last stable release for the library.
## Step 4 - Bundle Zipkin and Jaeger into the Application
To visualize traces from our application, we have to bundle open source tracing tools [Zipkin](https://zipkin.io/) and [Jaeger](https://www.jaegertracing.io/) into our application using docker.
Let's add a `docker-compose.yaml` file in the root of our project with the content as follows:
```yaml
version: '3.7'
services:
zipkin:
image: openzipkin/zipkin-slim
ports:
- 9411:9411
jaeger:
image: jaegertracing/all-in-one
environment:
COLLECTOR_ZIPKIN_HTTP_PORT: 9412
ports:
- 9412:9412
- 16686:16686
```
To confirm that docker is installed and running on our system, we can run the hello world docker example using the command `docker run -it --rm hello-world`. If everything works well, run `docker-compose up -d` to pull in Zipkin and Jaeger. This might take some time, depending on your internet connection speed.
![image](https://user-images.githubusercontent.com/22311928/115637058-41dc7e80-a307-11eb-9315-d188d2b84682.png)
We can confirm that Zipkin is up by navigating to `http://localhost:9411/` on our browser. For Jaeger, navigating to `http://localhost:16686/` on our browser should display the Jaeger home page.
![image](https://user-images.githubusercontent.com/22311928/115637059-42751500-a307-11eb-9b99-d5bbfec54df2.png)
![image](https://user-images.githubusercontent.com/22311928/115637065-430dab80-a307-11eb-8d7b-90d425b32454.png)
Now it is time to utilize our OpenTelemetry PHP Library to export traces to both Zipkin and Jaeger.
## Step 5 - Instrument Symfony Application
The entry point for all Symfony applications is the `index.php` file located in the `public` folder. Let's navigate to `public\index.php` to see what is happening. It is worthy of note that resources(namespaces, classes, variables) created within the `index.php` file are available within the entire application, by default the index file imports all auto loaded classes within the vendor folder. It also imports contents of the `.env` file. The other parts of the `index.php` file enable debugging as well as support request and response resolution using the application kernel.
To use open-telemetry specific classes we have to import them at the top of our index file, using the `use` keyword. This is what our imports look like:
```php
use App\Kernel;
use OpenTelemetry\Contrib\Jaeger\Exporter as JaegerExporter;
use OpenTelemetry\Contrib\Zipkin\Exporter as ZipkinExporter;
use OpenTelemetry\Sdk\Trace\Clock;
use OpenTelemetry\Sdk\Trace\Sampler\AlwaysOnSampler;
use OpenTelemetry\Sdk\Trace\SamplingResult;
use OpenTelemetry\Sdk\Trace\SpanProcessor\BatchSpanProcessor;
use OpenTelemetry\Sdk\Trace\TracerProvider;
use OpenTelemetry\Trace as API;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\ErrorHandler\Debug;
use Symfony\Component\HttpFoundation\Request;
```
Next, we create a sample recording trace using the [AlwaysOnSampler](https://github.com/open-telemetry/opentelemetry-php/blob/main/sdk/Trace/Sampler/AlwaysOnSampler.php) class, just before the Kernel instance is created like below:
```php
$sampler = new AlwaysOnSampler();
$samplingResult = $sampler->shouldSample(
null,
md5((string) microtime(true)),
substr(md5((string) microtime(true)), 16),
'io.opentelemetry.example',
API\SpanKind::KIND_INTERNAL
);
```
Since we are looking to export traces to both Zipkin and Jaeger we have to make use of their individual exporters;
```php
$jaegerExporter = new JaegerExporter(
'Hello World Web Server Jaeger',
'http://localhost:9412/api/v2/spans'
);
$zipkinExporter = new ZipkinExporter(
'Hello World Web Server Zipkin',
'http://localhost:9411/api/v2/spans'
);
```
Next we create a trace, and add processors for each trace(One for Jaeger and another for Zipkin). Then we proceed to start and activate a span for each trace. We create a trace only if the RECORD AND SAMPLED sampling result condition passes as follows;
```php
if (SamplingResult::RECORD_AND_SAMPLED === $samplingResult->getDecision()) {
$jaegerTracer = (new TracerProvider(null, $sampler))
->addSpanProcessor(new BatchSpanProcessor($jaegerExporter, Clock::get()))
->getTracer('io.opentelemetry.contrib.php');
$zipkinTracer = (new TracerProvider(null, $sampler))
->addSpanProcessor(new BatchSpanProcessor($zipkinExporter, Clock::get()))
->getTracer('io.opentelemetry.contrib.php');
$request = Request::createFromGlobals();
$jaegerSpan = $jaegerTracer->startAndActivateSpan($request->getUri());
$zipkinSpan = $zipkinTracer->startAndActivateSpan($request->getUri());
}
```
Finally we end the active spans if sampling is complete, by adding the following block at the end of the `index.php` file;
```php
if (SamplingResult::RECORD_AND_SAMPLED === $samplingResult->getDecision()) {
$zipkinSpan->end();
$jaegerSpan->end();
}
```
lets confirm that we can see exported traces on both Zipkin and Jaeger. To do that we need to reload `http://127.0.0.1:8000/hello` or any other route on our symfony server;
![image](https://user-images.githubusercontent.com/22311928/115637070-43a64200-a307-11eb-8abb-80f19285ef01.png)
We also need reload both Zipkin and Jaeger on our browser, using the URLs `http://localhost:9411/` and `http://localhost:16686/`. Do ensure that both your symfony server and docker instance are running for this step.
For Jaeger under service, you should see a `Hello World Web Server Jaeger` service, go ahead and click find traces to see exported traces.
)
![image](https://user-images.githubusercontent.com/22311928/115637071-443ed880-a307-11eb-8521-78c803dcd623.png)
Once we click on `Find Traces` you should be able to see traces like below:
![image](https://user-images.githubusercontent.com/22311928/115637073-44d76f00-a307-11eb-9e80-aa8f152577a8.png)
We can click on a trace to get more information about the trace.
![image](https://user-images.githubusercontent.com/22311928/115637075-44d76f00-a307-11eb-8d8e-5bf559bd2bf6.png)
For Zipkin, we can visualize our trace by clicking on `Run Query`
![image](https://user-images.githubusercontent.com/22311928/115637078-45700580-a307-11eb-9867-aa0c1a69f9fe.png)
Since resources in Symfony's `public\index.php` file are available to the entire application, we can use any of the already instantiated tracers within `HelloController`. In addition to the tracers, we can also utilize associated properties, methods and events.
Lets try using the `addEvent` method, to capture errors within our controller as follows:
```php
global $zipkinTracer;
if ($zipkinTracer) {
/** @var Span $span */
$span = $zipkinTracer->getActiveSpan();
$span->setAttribute('foo', 'bar');
$span->updateName('New name');
$zipkinTracer->startAndActivateSpan('Child span');
try {
throw new \Exception('Exception Example');
} catch (\Exception $exception) {
$span->setSpanStatus($exception->getCode(), $exception->getMessage());
}
$span->end();
}
```
In the above snippet we change the span name and attributes for our Zipkin trace, we also add an exception event to the span.
We need to reload our `http://127.0.0.1:8000/hello` route, then navigate to Zipkin like before to see that our span name gets updated to `new name` and our `Exception Example` is visible
![image](https://user-images.githubusercontent.com/22311928/115637079-46089c00-a307-11eb-9d9d-b5c0f941baeb.png)
## Summary
With the above example we have been able to instrument a Symfony application using the OpenTelemetry php library. You can fork the example project [here](https://github.com/prondubuisi/otel-php-symfony-basic-example). You can also checkout the original test application [here](https://github.com/dkarlovi/opentelemetry-php-user-test).

View File

@ -1,46 +0,0 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use OpenTelemetry\Context\Context;
use OpenTelemetry\Sdk\Trace\Attributes;
use OpenTelemetry\Sdk\Trace\Clock;
use OpenTelemetry\Sdk\Trace\Sampler\AlwaysOffSampler;
use OpenTelemetry\Sdk\Trace\SamplingResult;
use OpenTelemetry\Sdk\Trace\TracerProvider;
use OpenTelemetry\Trace as API;
$sampler = new AlwaysOffSampler();
$samplingResult = $sampler->shouldSample(
Context::getCurrent(),
md5((string) microtime(true)),
'io.opentelemetry.example',
API\SpanKind::KIND_INTERNAL
);
if (SamplingResult::RECORD_AND_SAMPLE === $samplingResult->getDecision()) {
$tracer = (new TracerProvider())
->getTracer('io.opentelemetry.contrib.php');
// start a span, register some events
$span = $tracer->startAndActivateSpan('session.generate');
$span->setAttribute('remote_ip', '1.2.3.4');
$span->setAttribute('country', 'USA');
$timestamp = Clock::get()->timestamp();
$span->addEvent('found_login', $timestamp, new Attributes([
'id' => 12345,
'username' => 'otuser',
]));
$span->addEvent('generated_session', $timestamp, new Attributes([
'id' => md5((string) microtime(true)),
]));
$span->end(); // pass status as an optional argument
print_r($span); // print the span as a resulting output
} else {
echo PHP_EOL . 'Sampling is not enabled';
}
echo PHP_EOL;

Some files were not shown because too many files have changed in this diff Show More