Backed out 3 changesets (bug 1923143) for causing hazard bustages

Backed out changeset 7510845c07da (bug 1923143)
Backed out changeset 45e612b7d4b6 (bug 1923143)
Backed out changeset fb3772f8a616 (bug 1923143)
This commit is contained in:
Alexandru Marc
2024-12-16 16:50:13 +02:00
parent 59aa9460bb
commit f90439f811
139 changed files with 0 additions and 26099 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,123 +0,0 @@
# OpenTelemetry C++
[![Slack](https://img.shields.io/badge/slack-@cncf/otel/cpp-brightgreen.svg?logo=slack)](https://cloud-native.slack.com/archives/C01N3AT62SJ)
[![codecov.io](https://codecov.io/gh/open-telemetry/opentelemetry-cpp/branch/main/graphs/badge.svg?)](https://codecov.io/gh/open-telemetry/opentelemetry-cpp/)
[![Build
Status](https://github.com/open-telemetry/opentelemetry-cpp/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/open-telemetry/opentelemetry-cpp/actions)
[![Release](https://img.shields.io/github/v/release/open-telemetry/opentelemetry-cpp?include_prereleases&style=)](https://github.com/open-telemetry/opentelemetry-cpp/releases/)
The C++ [OpenTelemetry](https://opentelemetry.io/) client.
## Project Status
**Stable** across all 3 signals i.e. `Logs`, `Metrics`, and `Traces`.
See [Spec Compliance
Matrix](https://github.com/open-telemetry/opentelemetry-specification/blob/main/spec-compliance-matrix.md)
to understand which portions of the specification has been implemented in this
repo.
## Supported C++ Versions
Code shipped from this repository generally supports the following versions of
C++ standards:
* ISO/IEC 14882:2014 (C++14)
* ISO/IEC 14882:2017 (C++17)
* ISO/IEC 14882:2020 (C++20)
Any exceptions to this are noted in the individual `README.md` files.
Please note that supporting the [C Programming
Language](https://en.wikipedia.org/wiki/C_(programming_language)) is not a goal
of the current project.
## Supported Development Platforms
Our CI pipeline builds and tests on following `x86-64` platforms:
| Platform | Build type |
|---------------------------------------------------------------------|---------------|
| ubuntu-22.04 (GCC 10, GCC 12, Clang 14) | CMake, Bazel |
| ubuntu-20.04 (GCC 9.4.0 - default compiler) | CMake, Bazel |
| ubuntu-20.04 (GCC 9.4.0 with -std=c++14/17/20 flags) | CMake, Bazel |
| macOS 12.7 (Xcode 14.2) | Bazel |
| Windows Server 2019 (Visual Studio Enterprise 2019) | CMake, Bazel |
| Windows Server 2022 (Visual Studio Enterprise 2022) | CMake |
In general, the code shipped from this repository should build on all platforms
having C++ compiler with [supported C++ standards](#supported-c-versions).
## Dependencies
Please refer to [Dependencies.md](docs/dependencies.md) for OSS Dependencies and
license requirements.
## Installation
Please refer to [INSTALL.md](./INSTALL.md).
## Getting Started
As an application owner or the library author, you can find the getting started
guide and reference documentation on
[opentelemetry-cpp.readthedocs.io](https://opentelemetry-cpp.readthedocs.io/en/latest/)
The `examples/simple` directory contains a minimal program demonstrating how to
instrument a small library using a simple `processor` and console `exporter`,
along with build files for CMake and Bazel.
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md)
We meet weekly, and the time of the meeting alternates between Monday at 13:00
PT and Wednesday at 9:00 PT. The meeting is subject to change depending on
contributors' availability. Check the [OpenTelemetry community
calendar](https://github.com/open-telemetry/community#calendar)
for specific dates and Zoom meeting links.
Meeting notes are available as a public [Google
doc](https://docs.google.com/document/d/1i1E4-_y4uJ083lCutKGDhkpi3n4_e774SBLi9hPLocw/edit?usp=sharing).
For edit access, get in touch on
[Slack](https://cloud-native.slack.com/archives/C01N3AT62SJ).
[Maintainers](https://github.com/open-telemetry/community/blob/main/community-membership.md#maintainer)
([@open-telemetry/cpp-maintainers](https://github.com/orgs/open-telemetry/teams/cpp-maintainers)):
* [Ehsan Saei](https://github.com/esigo)
* [Lalit Kumar Bhasin](https://github.com/lalitb), Microsoft
* [Marc Alff](https://github.com/marcalff), Oracle
* [Tom Tan](https://github.com/ThomsonTan), Microsoft
[Approvers](https://github.com/open-telemetry/community/blob/main/community-membership.md#approver)
([@open-telemetry/cpp-approvers](https://github.com/orgs/open-telemetry/teams/cpp-approvers)):
* [Josh Suereth](https://github.com/jsuereth), Google
* [WenTao Ou](https://github.com/owent), Tencent
[Emeritus
Maintainer/Approver/Triager](https://github.com/open-telemetry/community/blob/main/community-membership.md#emeritus-maintainerapprovertriager):
* [Alolita Sharma](https://github.com/alolita)
* [Emil Mikulic](https://github.com/g-easy)
* [Jodee Varney](https://github.com/jodeev)
* [Johannes Tax](https://github.com/pyohannes)
* [Max Golovanov](https://github.com/maxgolov)
* [Reiley Yang](https://github.com/reyang)
* [Ryan Burn](https://github.com/rnburn)
### Thanks to all the people who have contributed
[![contributors](https://contributors-img.web.app/image?repo=open-telemetry/opentelemetry-cpp)](https://github.com/open-telemetry/opentelemetry-cpp/graphs/contributors)
## Release Schedule
See the [release
notes](https://github.com/open-telemetry/opentelemetry-cpp/releases) for
existing releases.
See the [project
milestones](https://github.com/open-telemetry/opentelemetry-cpp/milestones) for
details on upcoming releases. The dates and features described in issues and
milestones are estimates, and subject to change.

View File

@@ -1,82 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <cstdint>
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/nostd/variant.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace common
{
/// OpenTelemetry signals can be enriched by adding attributes. The
/// \c AttributeValue type is defined as a variant of all attribute value
/// types the OpenTelemetry C++ API supports.
///
/// The following attribute value types are supported by the OpenTelemetry
/// specification:
/// - Primitive types: string, boolean, double precision floating point
/// (IEEE 754-1985) or signed 64 bit integer.
/// - Homogenous arrays of primitive type values.
///
/// \warning
/// \parblock The OpenTelemetry C++ API currently supports several attribute
/// value types that are not covered by the OpenTelemetry specification:
/// - \c uint64_t
/// - \c nostd::span<const uint64_t>
/// - \c nostd::span<uint8_t>
///
/// Those types are reserved for future use and currently should not be
/// used. There are no guarantees around how those values are handled by
/// exporters.
/// \endparblock
using AttributeValue =
nostd::variant<bool,
int32_t,
int64_t,
uint32_t,
double,
const char *,
nostd::string_view,
nostd::span<const bool>,
nostd::span<const int32_t>,
nostd::span<const int64_t>,
nostd::span<const uint32_t>,
nostd::span<const double>,
nostd::span<const nostd::string_view>,
// Not currently supported by the specification, but reserved for future use.
// Added to provide support for all primitive C++ types.
uint64_t,
// Not currently supported by the specification, but reserved for future use.
// Added to provide support for all primitive C++ types.
nostd::span<const uint64_t>,
// Not currently supported by the specification, but reserved for future use.
// See https://github.com/open-telemetry/opentelemetry-specification/issues/780
nostd::span<const uint8_t>>;
enum AttributeType
{
kTypeBool,
kTypeInt,
kTypeInt64,
kTypeUInt,
kTypeDouble,
kTypeCString,
kTypeString,
kTypeSpanBool,
kTypeSpanInt,
kTypeSpanInt64,
kTypeSpanUInt,
kTypeSpanDouble,
kTypeSpanString,
kTypeUInt64,
kTypeSpanUInt64,
kTypeSpanByte
};
} // namespace common
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,64 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/common/attribute_value.h"
#include "opentelemetry/nostd/function_ref.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace common
{
/**
* Supports internal iteration over a collection of key-value pairs.
*/
class KeyValueIterable
{
public:
virtual ~KeyValueIterable() = default;
/**
* Iterate over key-value pairs
* @param callback a callback to invoke for each key-value. If the callback returns false,
* the iteration is aborted.
* @return true if every key-value pair was iterated over
*/
virtual bool ForEachKeyValue(nostd::function_ref<bool(nostd::string_view, common::AttributeValue)>
callback) const noexcept = 0;
/**
* @return the number of key-value pairs
*/
virtual size_t size() const noexcept = 0;
};
/**
* Supports internal iteration over a collection of key-value pairs.
*/
class NoopKeyValueIterable : public KeyValueIterable
{
public:
~NoopKeyValueIterable() override = default;
/**
* Iterate over key-value pairs
* @param callback a callback to invoke for each key-value. If the callback returns false,
* the iteration is aborted.
* @return true if every key-value pair was iterated over
*/
bool ForEachKeyValue(
nostd::function_ref<bool(nostd::string_view, common::AttributeValue)>) const noexcept override
{
return true;
}
/**
* @return the number of key-value pairs
*/
size_t size() const noexcept override { return 0; }
};
} // namespace common
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,146 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <stddef.h>
#include <initializer_list>
#include <iterator>
#include <type_traits>
#include <utility>
#include <vector>
#include "opentelemetry/common/attribute_value.h"
#include "opentelemetry/common/key_value_iterable.h"
#include "opentelemetry/nostd/function_ref.h"
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/nostd/type_traits.h"
#include "opentelemetry/nostd/utility.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace common
{
// NOTE - code within `detail` namespace implements internal details, and not part
// of the public interface.
namespace detail
{
inline void take_key_value(nostd::string_view, common::AttributeValue) {}
template <class T>
auto is_key_value_iterable_impl(T iterable)
-> decltype(take_key_value(std::begin(iterable)->first, std::begin(iterable)->second),
nostd::size(iterable),
std::true_type{});
std::false_type is_key_value_iterable_impl(...);
template <class T>
struct is_key_value_iterable
{
static const bool value = decltype(detail::is_key_value_iterable_impl(std::declval<T>()))::value;
};
} // namespace detail
/**
* @brief Container for key-value pairs that can transform every value in it to one of types
* listed in common::AttributeValue. It may contain value types that are not directly map'able
* to primitive value types. In that case the `ForEachKeyValue` method acts as a transform to
* convert the value type to one listed under AtributeValue (bool, int32_t, int64_t, uint32_t,
* uint64_t, double, nostd::string_view, or arrays of primite types). For example, if UUID,
* GUID, or UTF-16 string type is passed as one of values stored inside this container, the
* container itself may provide a custom implementation of `ForEachKeyValue` to transform the
* 'non-standard' type to one of the standard types.
*/
template <class T>
class KeyValueIterableView final : public KeyValueIterable
{
public:
explicit KeyValueIterableView(const T &container) noexcept : container_{&container} {}
// KeyValueIterable
bool ForEachKeyValue(nostd::function_ref<bool(nostd::string_view, common::AttributeValue)>
callback) const noexcept override
{
auto iter = std::begin(*container_);
auto last = std::end(*container_);
for (; iter != last; ++iter)
{
if (!callback(iter->first, iter->second))
{
return false;
}
}
return true;
}
size_t size() const noexcept override { return nostd::size(*container_); }
private:
const T *container_;
};
template <class T, nostd::enable_if_t<detail::is_key_value_iterable<T>::value> * = nullptr>
KeyValueIterableView<T> MakeKeyValueIterableView(const T &container) noexcept
{
return KeyValueIterableView<T>(container);
}
/**
* Utility function to help to make a attribute view from initializer_list
*
* @param attributes
* @return nostd::span<const std::pair<nostd::string_view, common::AttributeValue>>
*/
inline static nostd::span<const std::pair<nostd::string_view, common::AttributeValue>>
MakeAttributes(std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>>
attributes) noexcept
{
return nostd::span<const std::pair<nostd::string_view, common::AttributeValue>>{
attributes.begin(), attributes.end()};
}
/**
* Utility function to help to make a attribute view from a span
*
* @param attributes
* @return nostd::span<const std::pair<nostd::string_view, common::AttributeValue>>
*/
inline static nostd::span<const std::pair<nostd::string_view, common::AttributeValue>>
MakeAttributes(
nostd::span<const std::pair<nostd::string_view, common::AttributeValue>> attributes) noexcept
{
return attributes;
}
/**
* Utility function to help to make a attribute view from a KeyValueIterable
*
* @param attributes
* @return common::KeyValueIterable
*/
inline static const common::KeyValueIterable &MakeAttributes(
const common::KeyValueIterable &attributes) noexcept
{
return attributes;
}
/**
* Utility function to help to make a attribute view from a key-value iterable object
*
* @param attributes
* @return nostd::span<const std::pair<nostd::string_view, common::AttributeValue>>
*/
template <
class ArgumentType,
nostd::enable_if_t<common::detail::is_key_value_iterable<ArgumentType>::value> * = nullptr>
inline static common::KeyValueIterableView<ArgumentType> MakeAttributes(
const ArgumentType &arg) noexcept
{
return common::KeyValueIterableView<ArgumentType>(arg);
}
} // namespace common
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,272 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/common/key_value_iterable_view.h"
#include "opentelemetry/common/string_util.h"
#include "opentelemetry/nostd/function_ref.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/nostd/unique_ptr.h"
#include "opentelemetry/version.h"
#include <cstring>
#include <string>
#include <type_traits>
OPENTELEMETRY_BEGIN_NAMESPACE
namespace common
{
// Constructor parameter for KeyValueStringTokenizer
struct KeyValueStringTokenizerOptions
{
char member_separator = ',';
char key_value_separator = '=';
bool ignore_empty_members = true;
};
// Tokenizer for key-value headers
class KeyValueStringTokenizer
{
public:
KeyValueStringTokenizer(
nostd::string_view str,
const KeyValueStringTokenizerOptions &opts = KeyValueStringTokenizerOptions()) noexcept
: str_(str), opts_(opts), index_(0)
{}
static nostd::string_view GetDefaultKeyOrValue()
{
static std::string default_str = "";
return default_str;
}
// Returns next key value in the string header
// @param valid_kv : if the found kv pair is valid or not
// @param key : key in kv pair
// @param key : value in kv pair
// @returns true if next kv pair was found, false otherwise.
bool next(bool &valid_kv, nostd::string_view &key, nostd::string_view &value) noexcept
{
valid_kv = true;
while (index_ < str_.size())
{
bool is_empty_pair = false;
size_t end = str_.find(opts_.member_separator, index_);
if (end == std::string::npos)
{
end = str_.size() - 1;
}
else if (end == index_) // empty pair. do not update end
{
is_empty_pair = true;
}
else
{
end--;
}
auto list_member = StringUtil::Trim(str_, index_, end);
if (list_member.size() == 0 || is_empty_pair)
{
// empty list member
index_ = end + 2 - is_empty_pair;
if (opts_.ignore_empty_members)
{
continue;
}
valid_kv = true;
key = GetDefaultKeyOrValue();
value = GetDefaultKeyOrValue();
return true;
}
auto key_end_pos = list_member.find(opts_.key_value_separator);
if (key_end_pos == std::string::npos)
{
// invalid member
valid_kv = false;
}
else
{
key = list_member.substr(0, key_end_pos);
value = list_member.substr(key_end_pos + 1);
}
index_ = end + 2;
return true;
}
// no more entries remaining
return false;
}
// Returns total number of tokens in header string
size_t NumTokens() const noexcept
{
size_t cnt = 0, begin = 0;
while (begin < str_.size())
{
++cnt;
size_t end = str_.find(opts_.member_separator, begin);
if (end == std::string::npos)
{
break;
}
begin = end + 1;
}
return cnt;
}
// Resets the iterator
void reset() noexcept { index_ = 0; }
private:
nostd::string_view str_;
KeyValueStringTokenizerOptions opts_;
size_t index_;
};
// Class to store fixed size array of key-value pairs of string type
class KeyValueProperties
{
// Class to store key-value pairs of string types
public:
class Entry
{
public:
Entry() : key_(nullptr), value_(nullptr) {}
// Copy constructor
Entry(const Entry &copy)
{
key_ = CopyStringToPointer(copy.key_.get());
value_ = CopyStringToPointer(copy.value_.get());
}
// Copy assignment operator
Entry &operator=(Entry &other)
{
key_ = CopyStringToPointer(other.key_.get());
value_ = CopyStringToPointer(other.value_.get());
return *this;
}
// Move contructor and assignment operator
Entry(Entry &&other) = default;
Entry &operator=(Entry &&other) = default;
// Creates an Entry for a given key-value pair.
Entry(nostd::string_view key, nostd::string_view value)
{
key_ = CopyStringToPointer(key);
value_ = CopyStringToPointer(value);
}
// Gets the key associated with this entry.
nostd::string_view GetKey() const noexcept { return key_.get(); }
// Gets the value associated with this entry.
nostd::string_view GetValue() const noexcept { return value_.get(); }
// Sets the value for this entry. This overrides the previous value.
void SetValue(nostd::string_view value) noexcept { value_ = CopyStringToPointer(value); }
private:
// Store key and value as raw char pointers to avoid using std::string.
nostd::unique_ptr<const char[]> key_;
nostd::unique_ptr<const char[]> value_;
// Copies string into a buffer and returns a unique_ptr to the buffer.
// This is a workaround for the fact that memcpy doesn't accept a const destination.
nostd::unique_ptr<const char[]> CopyStringToPointer(nostd::string_view str)
{
char *temp = new char[str.size() + 1];
memcpy(temp, str.data(), str.size());
temp[str.size()] = '\0';
return nostd::unique_ptr<const char[]>(temp);
}
};
// Maintain the number of entries in entries_.
size_t num_entries_;
// Max size of allocated array
size_t max_num_entries_;
// Store entries in a C-style array to avoid using std::array or std::vector.
nostd::unique_ptr<Entry[]> entries_;
public:
// Create Key-value list of given size
// @param size : Size of list.
KeyValueProperties(size_t size) noexcept
: num_entries_(0), max_num_entries_(size), entries_(new Entry[size])
{}
// Create Empty Key-Value list
KeyValueProperties() noexcept : num_entries_(0), max_num_entries_(0), entries_(nullptr) {}
template <class T, class = typename std::enable_if<detail::is_key_value_iterable<T>::value>::type>
KeyValueProperties(const T &keys_and_values) noexcept
: num_entries_(0),
max_num_entries_(keys_and_values.size()),
entries_(new Entry[max_num_entries_])
{
for (auto &e : keys_and_values)
{
Entry entry(e.first, e.second);
(entries_.get())[num_entries_++] = std::move(entry);
}
}
// Adds new kv pair into kv properties
void AddEntry(nostd::string_view key, nostd::string_view value) noexcept
{
if (num_entries_ < max_num_entries_)
{
Entry entry(key, value);
(entries_.get())[num_entries_++] = std::move(entry);
}
}
// Returns all kv pair entries
bool GetAllEntries(
nostd::function_ref<bool(nostd::string_view, nostd::string_view)> callback) const noexcept
{
for (size_t i = 0; i < num_entries_; i++)
{
auto &entry = (entries_.get())[i];
if (!callback(entry.GetKey(), entry.GetValue()))
{
return false;
}
}
return true;
}
// Return value for key if exists, return false otherwise
bool GetValue(nostd::string_view key, std::string &value) const noexcept
{
for (size_t i = 0; i < num_entries_; i++)
{
auto &entry = (entries_.get())[i];
if (entry.GetKey() == key)
{
const auto &entry_value = entry.GetValue();
value = std::string(entry_value.data(), entry_value.size());
return true;
}
}
return false;
}
size_t Size() const noexcept { return num_entries_; }
};
} // namespace common
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,523 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
/*
OPENTELEMETRY_HAVE_BUILTIN&OPENTELEMETRY_HAVE_FEATURE
Checks whether the compiler supports a Clang Feature Checking Macro, and if
so, checks whether it supports the provided builtin function "x" where x
is one of the functions noted in
https://clang.llvm.org/docs/LanguageExtensions.html
Note: Use this macro to avoid an extra level of #ifdef __has_builtin check.
http://releases.llvm.org/3.3/tools/clang/docs/LanguageExtensions.html
*/
#if !defined(OPENTELEMETRY_HAVE_BUILTIN)
# ifdef __has_builtin
# define OPENTELEMETRY_HAVE_BUILTIN(x) __has_builtin(x)
# else
# define OPENTELEMETRY_HAVE_BUILTIN(x) 0
# endif
#endif
#if !defined(OPENTELEMETRY_HAVE_FEATURE)
# ifdef __has_feature
# define OPENTELEMETRY_HAVE_FEATURE(f) __has_feature(f)
# else
# define OPENTELEMETRY_HAVE_FEATURE(f) 0
# endif
#endif
/*
has feature
OPENTELEMETRY_HAVE_ATTRIBUTE
A function-like feature checking macro that is a wrapper around
`__has_attribute`, which is defined by GCC 5+ and Clang and evaluates to a
nonzero constant integer if the attribute is supported or 0 if not.
It evaluates to zero if `__has_attribute` is not defined by the compiler.
GCC: https://gcc.gnu.org/gcc-5/changes.html
Clang: https://clang.llvm.org/docs/LanguageExtensions.html
*/
#if !defined(OPENTELEMETRY_HAVE_ATTRIBUTE)
# ifdef __has_attribute
# define OPENTELEMETRY_HAVE_ATTRIBUTE(x) __has_attribute(x)
# else
# define OPENTELEMETRY_HAVE_ATTRIBUTE(x) 0
# endif
#endif
/*
OPENTELEMETRY_HAVE_CPP_ATTRIBUTE
A function-like feature checking macro that accepts C++11 style attributes.
It's a wrapper around `__has_cpp_attribute`, defined by ISO C++ SD-6
(https://en.cppreference.com/w/cpp/experimental/feature_test). If we don't
find `__has_cpp_attribute`, will evaluate to 0.
*/
#if !defined(OPENTELEMETRY_HAVE_CPP_ATTRIBUTE)
# if defined(__cplusplus) && defined(__has_cpp_attribute)
// NOTE: requiring __cplusplus above should not be necessary, but
// works around https://bugs.llvm.org/show_bug.cgi?id=23435.
# define OPENTELEMETRY_HAVE_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
# else
# define OPENTELEMETRY_HAVE_CPP_ATTRIBUTE(x) 0
# endif
#endif
/*
Expected usage pattern:
if OPENTELEMETRY_LIKELY_CONDITION (ptr != nullptr)
{
do_something_likely();
} else {
do_something_unlikely();
}
This pattern works with gcc/clang and __builtin_expect(),
as well as with C++20.
It is unclear if __builtin_expect() will be deprecated
in favor of C++20 [[likely]] or not.
OPENTELEMETRY_LIKELY_CONDITION is preferred over OPENTELEMETRY_LIKELY,
to be revisited when C++20 is required.
*/
#if !defined(OPENTELEMETRY_LIKELY_CONDITION) && defined(__cplusplus)
// Only use likely with C++20
# if __cplusplus >= 202002L
// GCC 9 has likely attribute but do not support declare it at the beginning of statement
# if defined(__has_cpp_attribute) && (defined(__clang__) || !defined(__GNUC__) || __GNUC__ > 9)
# if __has_cpp_attribute(likely)
# define OPENTELEMETRY_LIKELY_CONDITION(C) (C) [[likely]]
# endif
# endif
# endif
#endif
#if !defined(OPENTELEMETRY_LIKELY_CONDITION) && (defined(__clang__) || defined(__GNUC__))
// Only use if supported by the compiler
# define OPENTELEMETRY_LIKELY_CONDITION(C) (__builtin_expect(!!(C), true))
#endif
#ifndef OPENTELEMETRY_LIKELY_CONDITION
// Do not use likely annotations
# define OPENTELEMETRY_LIKELY_CONDITION(C) (C)
#endif
#if !defined(OPENTELEMETRY_UNLIKELY_CONDITION) && defined(__cplusplus)
// Only use unlikely with C++20
# if __cplusplus >= 202002L
// GCC 9 has unlikely attribute but do not support declare it at the beginning of statement
# if defined(__has_cpp_attribute) && (defined(__clang__) || !defined(__GNUC__) || __GNUC__ > 9)
# if __has_cpp_attribute(unlikely)
# define OPENTELEMETRY_UNLIKELY_CONDITION(C) (C) [[unlikely]]
# endif
# endif
# endif
#endif
#if !defined(OPENTELEMETRY_UNLIKELY_CONDITION) && (defined(__clang__) || defined(__GNUC__))
// Only use if supported by the compiler
# define OPENTELEMETRY_UNLIKELY_CONDITION(C) (__builtin_expect(!!(C), false))
#endif
#ifndef OPENTELEMETRY_UNLIKELY_CONDITION
// Do not use unlikely annotations
# define OPENTELEMETRY_UNLIKELY_CONDITION(C) (C)
#endif
/*
Expected usage pattern:
if (ptr != nullptr)
OPENTELEMETRY_LIKELY
{
do_something_likely();
} else {
do_something_unlikely();
}
This pattern works starting with C++20.
See https://en.cppreference.com/w/cpp/language/attributes/likely
Please use OPENTELEMETRY_LIKELY_CONDITION instead for now.
*/
#if !defined(OPENTELEMETRY_LIKELY) && defined(__cplusplus)
// Only use likely with C++20
# if __cplusplus >= 202002L
// GCC 9 has likely attribute but do not support declare it at the beginning of statement
# if defined(__has_cpp_attribute) && (defined(__clang__) || !defined(__GNUC__) || __GNUC__ > 9)
# if __has_cpp_attribute(likely)
# define OPENTELEMETRY_LIKELY [[likely]]
# endif
# endif
# endif
#endif
#ifndef OPENTELEMETRY_LIKELY
# define OPENTELEMETRY_LIKELY
#endif
#if !defined(OPENTELEMETRY_UNLIKELY) && defined(__cplusplus)
// Only use unlikely with C++20
# if __cplusplus >= 202002L
// GCC 9 has unlikely attribute but do not support declare it at the beginning of statement
# if defined(__has_cpp_attribute) && (defined(__clang__) || !defined(__GNUC__) || __GNUC__ > 9)
# if __has_cpp_attribute(unlikely)
# define OPENTELEMETRY_UNLIKELY [[unlikely]]
# endif
# endif
# endif
#endif
#ifndef OPENTELEMETRY_UNLIKELY
# define OPENTELEMETRY_UNLIKELY
#endif
/// \brief Declare variable as maybe unused
/// usage:
/// OPENTELEMETRY_MAYBE_UNUSED int a;
/// class OPENTELEMETRY_MAYBE_UNUSED a;
/// OPENTELEMETRY_MAYBE_UNUSED int a();
///
#if defined(__cplusplus) && __cplusplus >= 201703L
# define OPENTELEMETRY_MAYBE_UNUSED [[maybe_unused]]
#elif defined(__clang__)
# define OPENTELEMETRY_MAYBE_UNUSED __attribute__((unused))
#elif defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
# define OPENTELEMETRY_MAYBE_UNUSED __attribute__((unused))
#elif (defined(_MSC_VER) && _MSC_VER >= 1910) && (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
# define OPENTELEMETRY_MAYBE_UNUSED [[maybe_unused]]
#else
# define OPENTELEMETRY_MAYBE_UNUSED
#endif
#ifndef OPENTELEMETRY_RTTI_ENABLED
# if defined(__clang__)
# if __has_feature(cxx_rtti)
# define OPENTELEMETRY_RTTI_ENABLED
# endif
# elif defined(__GNUG__)
# if defined(__GXX_RTTI)
# define OPENTELEMETRY_RTTI_ENABLED
# endif
# elif defined(_MSC_VER)
# if defined(_CPPRTTI)
# define OPENTELEMETRY_RTTI_ENABLED
# endif
# endif
#endif
#if defined(__cplusplus) && __cplusplus >= 201402L
# define OPENTELEMETRY_DEPRECATED [[deprecated]]
#elif defined(__clang__)
# define OPENTELEMETRY_DEPRECATED __attribute__((deprecated))
#elif defined(__GNUC__)
# define OPENTELEMETRY_DEPRECATED __attribute__((deprecated))
#elif defined(_MSC_VER)
# if _MSC_VER >= 1910 && defined(_MSVC_LANG) && _MSVC_LANG >= 201703L
# define OPENTELEMETRY_DEPRECATED [[deprecated]]
# else
# define OPENTELEMETRY_DEPRECATED __declspec(deprecated)
# endif
#else
# define OPENTELEMETRY_DEPRECATED
#endif
#if defined(__cplusplus) && __cplusplus >= 201402L
# define OPENTELEMETRY_DEPRECATED_MESSAGE(msg) [[deprecated(msg)]]
#elif defined(__clang__)
# define OPENTELEMETRY_DEPRECATED_MESSAGE(msg) __attribute__((deprecated(msg)))
#elif defined(__GNUC__)
# define OPENTELEMETRY_DEPRECATED_MESSAGE(msg) __attribute__((deprecated(msg)))
#elif defined(_MSC_VER)
# if _MSC_VER >= 1910 && defined(_MSVC_LANG) && _MSVC_LANG >= 201703L
# define OPENTELEMETRY_DEPRECATED_MESSAGE(msg) [[deprecated(msg)]]
# else
# define OPENTELEMETRY_DEPRECATED_MESSAGE(msg) __declspec(deprecated(msg))
# endif
#else
# define OPENTELEMETRY_DEPRECATED_MESSAGE(msg)
#endif
// Regex support
#if (__GNUC__ == 4 && (__GNUC_MINOR__ == 8 || __GNUC_MINOR__ == 9))
# define OPENTELEMETRY_HAVE_WORKING_REGEX 0
#else
# define OPENTELEMETRY_HAVE_WORKING_REGEX 1
#endif
/* clang-format off */
/**
@page HEADER_ONLY_SINGLETON Header only singleton.
@section ELF_SINGLETON
For clang and gcc, the desired coding pattern is as follows.
@verbatim
class Foo
{
// (a)
__attribute__((visibility("default")))
// (b)
T& get_singleton()
{
// (c)
static T singleton;
return singleton;
}
};
@endverbatim
(a) is needed when the code is build with
@code -fvisibility="hidden" @endcode
to ensure that all instances of (b) are visible to the linker.
What is duplicated in the binary is @em code, in (b).
The linker will make sure only one instance
of all the (b) methods is used.
(c) is a singleton implemented inside a method.
This is very desirable, because:
- the C++ compiler guarantees that construction
of the variable (c) is thread safe.
- constructors for (c) singletons are executed in code path order,
or not at all if the singleton is never used.
@section OTHER_SINGLETON
For other platforms, header only singletons are not supported at this
point.
@section CODING_PATTERN
The coding pattern to use in the source code is as follows
@verbatim
class Foo
{
OPENTELEMETRY_API_SINGLETON
T& get_singleton()
{
static T singleton;
return singleton;
}
};
@endverbatim
*/
/* clang-format on */
#if defined(__clang__)
# define OPENTELEMETRY_API_SINGLETON __attribute__((visibility("default")))
# define OPENTELEMETRY_LOCAL_SYMBOL __attribute__((visibility("hidden")))
#elif defined(__GNUC__)
# define OPENTELEMETRY_API_SINGLETON __attribute__((visibility("default")))
# define OPENTELEMETRY_LOCAL_SYMBOL __attribute__((visibility("hidden")))
#else
/* Add support for other compilers here. */
# define OPENTELEMETRY_API_SINGLETON
# define OPENTELEMETRY_LOCAL_SYMBOL
#endif
//
// Atomic wrappers based on compiler intrinsics for memory read/write.
// The tailing number is read/write length in bits.
//
// N.B. Compiler instrinsic is used because the usage of C++ standard library is restricted in the
// OpenTelemetry C++ API.
//
#if defined(__GNUC__)
# define OPENTELEMETRY_ATOMIC_READ_8(ptr) __atomic_load_n(ptr, __ATOMIC_SEQ_CST)
# define OPENTELEMETRY_ATOMIC_WRITE_8(ptr, value) __atomic_store_n(ptr, value, __ATOMIC_SEQ_CST)
#elif defined(_MSC_VER)
# include <intrin.h>
# define OPENTELEMETRY_ATOMIC_READ_8(ptr) \
static_cast<uint8_t>(_InterlockedCompareExchange8(reinterpret_cast<char *>(ptr), 0, 0))
# define OPENTELEMETRY_ATOMIC_WRITE_8(ptr, value) \
_InterlockedExchange8(reinterpret_cast<char *>(ptr), static_cast<char>(value))
#else
# error port atomics read/write for the current platform
#endif
/* clang-format on */
//
// The if/elif order matters here. If both OPENTELEMETRY_BUILD_IMPORT_DLL and
// OPENTELEMETRY_BUILD_EXPORT_DLL are defined, the former takes precedence.
//
// TODO: consider define OPENTELEMETRY_EXPORT for cygwin/gcc, see below link.
// https://gcc.gnu.org/wiki/Visibility#How_to_use_the_new_C.2B-.2B-_visibility_support
//
#if defined(_MSC_VER) && defined(OPENTELEMETRY_BUILD_IMPORT_DLL)
# define OPENTELEMETRY_EXPORT __declspec(dllimport)
#elif defined(_MSC_VER) && defined(OPENTELEMETRY_BUILD_EXPORT_DLL)
# define OPENTELEMETRY_EXPORT __declspec(dllexport)
#else
//
// build OpenTelemetry as static library or not on Windows.
//
# define OPENTELEMETRY_EXPORT
#endif
// OPENTELEMETRY_HAVE_EXCEPTIONS
//
// Checks whether the compiler both supports and enables exceptions. Many
// compilers support a "no exceptions" mode that disables exceptions.
//
// Generally, when OPENTELEMETRY_HAVE_EXCEPTIONS is not defined:
//
// * Code using `throw` and `try` may not compile.
// * The `noexcept` specifier will still compile and behave as normal.
// * The `noexcept` operator may still return `false`.
//
// For further details, consult the compiler's documentation.
#ifndef OPENTELEMETRY_HAVE_EXCEPTIONS
# if defined(__clang__) && ((__clang_major__ * 100) + __clang_minor__) < 306
// Clang < 3.6
// http://releases.llvm.org/3.6.0/tools/clang/docs/ReleaseNotes.html#the-exceptions-macro
# if defined(__EXCEPTIONS) && OPENTELEMETRY_HAVE_FEATURE(cxx_exceptions)
# define OPENTELEMETRY_HAVE_EXCEPTIONS 1
# endif // defined(__EXCEPTIONS) && OPENTELEMETRY_HAVE_FEATURE(cxx_exceptions)
# elif OPENTELEMETRY_HAVE_FEATURE(cxx_exceptions)
# define OPENTELEMETRY_HAVE_EXCEPTIONS 1
// Handle remaining special cases and default to exceptions being supported.
# elif !(defined(__GNUC__) && !defined(__EXCEPTIONS) && !defined(__cpp_exceptions)) && \
!(defined(_MSC_VER) && !defined(_CPPUNWIND))
# define OPENTELEMETRY_HAVE_EXCEPTIONS 1
# endif
#endif
#ifndef OPENTELEMETRY_HAVE_EXCEPTIONS
# define OPENTELEMETRY_HAVE_EXCEPTIONS 0
#endif
/*
OPENTELEMETRY_ATTRIBUTE_LIFETIME_BOUND indicates that a resource owned by a function
parameter or implicit object parameter is retained by the return value of the
annotated function (or, for a parameter of a constructor, in the value of the
constructed object). This attribute causes warnings to be produced if a
temporary object does not live long enough.
When applied to a reference parameter, the referenced object is assumed to be
retained by the return value of the function. When applied to a non-reference
parameter (for example, a pointer or a class type), all temporaries
referenced by the parameter are assumed to be retained by the return value of
the function.
See also the upstream documentation:
https://clang.llvm.org/docs/AttributeReference.html#lifetimebound
*/
#ifndef OPENTELEMETRY_ATTRIBUTE_LIFETIME_BOUND
# if OPENTELEMETRY_HAVE_CPP_ATTRIBUTE(clang::lifetimebound)
# define OPENTELEMETRY_ATTRIBUTE_LIFETIME_BOUND [[clang::lifetimebound]]
# elif OPENTELEMETRY_HAVE_ATTRIBUTE(lifetimebound)
# define OPENTELEMETRY_ATTRIBUTE_LIFETIME_BOUND __attribute__((lifetimebound))
# else
# define OPENTELEMETRY_ATTRIBUTE_LIFETIME_BOUND
# endif
#endif
// OPENTELEMETRY_HAVE_MEMORY_SANITIZER
//
// MemorySanitizer (MSan) is a detector of uninitialized reads. It consists of
// a compiler instrumentation module and a run-time library.
#ifndef OPENTELEMETRY_HAVE_MEMORY_SANITIZER
# if !defined(__native_client__) && OPENTELEMETRY_HAVE_FEATURE(memory_sanitizer)
# define OPENTELEMETRY_HAVE_MEMORY_SANITIZER 1
# else
# define OPENTELEMETRY_HAVE_MEMORY_SANITIZER 0
# endif
#endif
#if OPENTELEMETRY_HAVE_MEMORY_SANITIZER && OPENTELEMETRY_HAVE_ATTRIBUTE(no_sanitize_memory)
# define OPENTELEMETRY_SANITIZER_NO_MEMORY \
__attribute__((no_sanitize_memory)) // __attribute__((no_sanitize("memory")))
#else
# define OPENTELEMETRY_SANITIZER_NO_MEMORY
#endif
// OPENTELEMETRY_HAVE_THREAD_SANITIZER
//
// ThreadSanitizer (TSan) is a fast data race detector.
#ifndef OPENTELEMETRY_HAVE_THREAD_SANITIZER
# if defined(__SANITIZE_THREAD__)
# define OPENTELEMETRY_HAVE_THREAD_SANITIZER 1
# elif OPENTELEMETRY_HAVE_FEATURE(thread_sanitizer)
# define OPENTELEMETRY_HAVE_THREAD_SANITIZER 1
# else
# define OPENTELEMETRY_HAVE_THREAD_SANITIZER 0
# endif
#endif
#if OPENTELEMETRY_HAVE_THREAD_SANITIZER && OPENTELEMETRY_HAVE_ATTRIBUTE(no_sanitize_thread)
# define OPENTELEMETRY_SANITIZER_NO_THREAD \
__attribute__((no_sanitize_thread)) // __attribute__((no_sanitize("thread")))
#else
# define OPENTELEMETRY_SANITIZER_NO_THREAD
#endif
// OPENTELEMETRY_HAVE_ADDRESS_SANITIZER
//
// AddressSanitizer (ASan) is a fast memory error detector.
#ifndef OPENTELEMETRY_HAVE_ADDRESS_SANITIZER
# if defined(__SANITIZE_ADDRESS__)
# define OPENTELEMETRY_HAVE_ADDRESS_SANITIZER 1
# elif OPENTELEMETRY_HAVE_FEATURE(address_sanitizer)
# define OPENTELEMETRY_HAVE_ADDRESS_SANITIZER 1
# else
# define OPENTELEMETRY_HAVE_ADDRESS_SANITIZER 0
# endif
#endif
// OPENTELEMETRY_HAVE_HWADDRESS_SANITIZER
//
// Hardware-Assisted AddressSanitizer (or HWASAN) is even faster than asan
// memory error detector which can use CPU features like ARM TBI, Intel LAM or
// AMD UAI.
#ifndef OPENTELEMETRY_HAVE_HWADDRESS_SANITIZER
# if defined(__SANITIZE_HWADDRESS__)
# define OPENTELEMETRY_HAVE_HWADDRESS_SANITIZER 1
# elif OPENTELEMETRY_HAVE_FEATURE(hwaddress_sanitizer)
# define OPENTELEMETRY_HAVE_HWADDRESS_SANITIZER 1
# else
# define OPENTELEMETRY_HAVE_HWADDRESS_SANITIZER 0
# endif
#endif
#if OPENTELEMETRY_HAVE_ADDRESS_SANITIZER && OPENTELEMETRY_HAVE_ATTRIBUTE(no_sanitize_address)
# define OPENTELEMETRY_SANITIZER_NO_ADDRESS \
__attribute__((no_sanitize_address)) // __attribute__((no_sanitize("address")))
#elif OPENTELEMETRY_HAVE_ADDRESS_SANITIZER && defined(_MSC_VER) && _MSC_VER >= 1928
# define OPENTELEMETRY_SANITIZER_NO_ADDRESS __declspec(no_sanitize_address)
#elif OPENTELEMETRY_HAVE_HWADDRESS_SANITIZER && OPENTELEMETRY_HAVE_ATTRIBUTE(no_sanitize)
# define OPENTELEMETRY_SANITIZER_NO_ADDRESS __attribute__((no_sanitize("hwaddress")))
#else
# define OPENTELEMETRY_SANITIZER_NO_ADDRESS
#endif

View File

@@ -1,133 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <atomic>
#include <chrono>
#include <thread>
#include "opentelemetry/version.h"
#if defined(_MSC_VER)
# define _WINSOCKAPI_ // stops including winsock.h
# include <windows.h>
#elif defined(__i386__) || defined(__x86_64__)
# if defined(__clang__)
# include <emmintrin.h>
# elif defined(__INTEL_COMPILER)
# include <immintrin.h>
# endif
#endif
OPENTELEMETRY_BEGIN_NAMESPACE
namespace common
{
constexpr int SPINLOCK_FAST_ITERATIONS = 100;
constexpr int SPINLOCK_SLEEP_MS = 1;
/**
* A Mutex which uses atomic flags and spin-locks instead of halting threads.
*
* This mutex uses an incremental back-off strategy with the following phases:
* 1. A tight spin-lock loop (pending: using hardware PAUSE/YIELD instructions)
* 2. A loop where the current thread yields control after checking the lock.
* 3. Issuing a thread-sleep call before starting back in phase 1.
*
* This is meant to give a good balance of perofrmance and CPU consumption in
* practice.
*
* This mutex uses an incremental back-off strategy with the following phases:
* 1. A tight spin-lock loop (pending: using hardware PAUSE/YIELD instructions)
* 2. A loop where the current thread yields control after checking the lock.
* 3. Issuing a thread-sleep call before starting back in phase 1.
*
* This is meant to give a good balance of perofrmance and CPU consumption in
* practice.
*
* This class implements the `BasicLockable` specification:
* https://en.cppreference.com/w/cpp/named_req/BasicLockable
*/
class SpinLockMutex
{
public:
SpinLockMutex() noexcept {}
~SpinLockMutex() noexcept = default;
SpinLockMutex(const SpinLockMutex &) = delete;
SpinLockMutex &operator=(const SpinLockMutex &) = delete;
static inline void fast_yield() noexcept
{
// Issue a Pause/Yield instruction while spinning.
#if defined(_MSC_VER)
YieldProcessor();
#elif defined(__i386__) || defined(__x86_64__)
# if defined(__clang__) || defined(__INTEL_COMPILER)
_mm_pause();
# else
__builtin_ia32_pause();
# endif
#elif defined(__armel__) || defined(__ARMEL__)
asm volatile("nop" ::: "memory");
#elif defined(__arm__) || defined(__aarch64__) // arm big endian / arm64
__asm__ __volatile__("yield" ::: "memory");
#else
// TODO: Issue PAGE/YIELD on other architectures.
#endif
}
/**
* Attempts to lock the mutex. Return immediately with `true` (success) or `false` (failure).
*/
bool try_lock() noexcept
{
return !flag_.load(std::memory_order_relaxed) &&
!flag_.exchange(true, std::memory_order_acquire);
}
/**
* Blocks until a lock can be obtained for the current thread.
*
* This mutex will spin the current CPU waiting for the lock to be available. This can have
* decent performance in scenarios where there is low lock contention and lock-holders achieve
* their work quickly. It degrades in scenarios where locked tasks take a long time.
*/
void lock() noexcept
{
for (;;)
{
// Try once
if (!flag_.exchange(true, std::memory_order_acquire))
{
return;
}
// Spin-Fast (goal ~10ns)
for (std::size_t i = 0; i < SPINLOCK_FAST_ITERATIONS; ++i)
{
if (try_lock())
{
return;
}
fast_yield();
}
// Yield then try again (goal ~100ns)
std::this_thread::yield();
if (try_lock())
{
return;
}
// Sleep and then start the whole process again. (goal ~1000ns)
std::this_thread::sleep_for(std::chrono::milliseconds(SPINLOCK_SLEEP_MS));
}
return;
}
/** Releases the lock held by the execution agent. Throws no exceptions. */
void unlock() noexcept { flag_.store(false, std::memory_order_release); }
private:
std::atomic<bool> flag_{false};
};
} // namespace common
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,42 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace common
{
class StringUtil
{
public:
static nostd::string_view Trim(nostd::string_view str, size_t left, size_t right) noexcept
{
while (left <= right && isspace(str[left]))
{
left++;
}
while (left <= right && isspace(str[right]))
{
right--;
}
return str.substr(left, 1 + right - left);
}
static nostd::string_view Trim(nostd::string_view str) noexcept
{
if (str.empty())
{
return str;
}
return Trim(str, 0, str.size() - 1);
}
};
} // namespace common
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,206 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <chrono>
#include <cstdint>
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace common
{
/**
* @brief A timepoint relative to the system clock epoch.
*
* This is used for marking the beginning and end of an operation.
*/
class SystemTimestamp
{
public:
/**
* @brief Initializes a system timestamp pointing to the start of the epoch.
*/
SystemTimestamp() noexcept : nanos_since_epoch_{0} {}
/**
* @brief Initializes a system timestamp from a duration.
*
* @param time_since_epoch Time elapsed since the beginning of the epoch.
*/
template <class Rep, class Period>
explicit SystemTimestamp(const std::chrono::duration<Rep, Period> &time_since_epoch) noexcept
: nanos_since_epoch_{static_cast<int64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(time_since_epoch).count())}
{}
/**
* @brief Initializes a system timestamp based on a point in time.
*
* @param time_point A point in time.
*/
/*implicit*/ SystemTimestamp(const std::chrono::system_clock::time_point &time_point) noexcept
: SystemTimestamp{time_point.time_since_epoch()}
{}
/**
* @brief Returns a time point for the time stamp.
*
* @return A time point corresponding to the time stamp.
*/
operator std::chrono::system_clock::time_point() const noexcept
{
return std::chrono::system_clock::time_point{
std::chrono::duration_cast<std::chrono::system_clock::duration>(
std::chrono::nanoseconds{nanos_since_epoch_})};
}
/**
* @brief Returns the nanoseconds since the beginning of the epoch.
*
* @return Elapsed nanoseconds since the beginning of the epoch for this timestamp.
*/
std::chrono::nanoseconds time_since_epoch() const noexcept
{
return std::chrono::nanoseconds{nanos_since_epoch_};
}
/**
* @brief Compare two steady time stamps.
*
* @return true if the two time stamps are equal.
*/
bool operator==(const SystemTimestamp &other) const noexcept
{
return nanos_since_epoch_ == other.nanos_since_epoch_;
}
/**
* @brief Compare two steady time stamps for inequality.
*
* @return true if the two time stamps are not equal.
*/
bool operator!=(const SystemTimestamp &other) const noexcept
{
return nanos_since_epoch_ != other.nanos_since_epoch_;
}
private:
int64_t nanos_since_epoch_;
};
/**
* @brief A timepoint relative to the monotonic clock epoch
*
* This is used for calculating the duration of an operation.
*/
class SteadyTimestamp
{
public:
/**
* @brief Initializes a monotonic timestamp pointing to the start of the epoch.
*/
SteadyTimestamp() noexcept : nanos_since_epoch_{0} {}
/**
* @brief Initializes a monotonic timestamp from a duration.
*
* @param time_since_epoch Time elapsed since the beginning of the epoch.
*/
template <class Rep, class Period>
explicit SteadyTimestamp(const std::chrono::duration<Rep, Period> &time_since_epoch) noexcept
: nanos_since_epoch_{static_cast<int64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(time_since_epoch).count())}
{}
/**
* @brief Initializes a monotonic timestamp based on a point in time.
*
* @param time_point A point in time.
*/
/*implicit*/ SteadyTimestamp(const std::chrono::steady_clock::time_point &time_point) noexcept
: SteadyTimestamp{time_point.time_since_epoch()}
{}
/**
* @brief Returns a time point for the time stamp.
*
* @return A time point corresponding to the time stamp.
*/
operator std::chrono::steady_clock::time_point() const noexcept
{
return std::chrono::steady_clock::time_point{
std::chrono::duration_cast<std::chrono::steady_clock::duration>(
std::chrono::nanoseconds{nanos_since_epoch_})};
}
/**
* @brief Returns the nanoseconds since the beginning of the epoch.
*
* @return Elapsed nanoseconds since the beginning of the epoch for this timestamp.
*/
std::chrono::nanoseconds time_since_epoch() const noexcept
{
return std::chrono::nanoseconds{nanos_since_epoch_};
}
/**
* @brief Compare two steady time stamps.
*
* @return true if the two time stamps are equal.
*/
bool operator==(const SteadyTimestamp &other) const noexcept
{
return nanos_since_epoch_ == other.nanos_since_epoch_;
}
/**
* @brief Compare two steady time stamps for inequality.
*
* @return true if the two time stamps are not equal.
*/
bool operator!=(const SteadyTimestamp &other) const noexcept
{
return nanos_since_epoch_ != other.nanos_since_epoch_;
}
private:
int64_t nanos_since_epoch_;
};
class DurationUtil
{
public:
template <class Rep, class Period>
static std::chrono::duration<Rep, Period> AdjustWaitForTimeout(
std::chrono::duration<Rep, Period> timeout,
std::chrono::duration<Rep, Period> indefinite_value) noexcept
{
// Do not call now() when this duration is max value, now() may have a expensive cost.
if (timeout == (std::chrono::duration<Rep, Period>::max)())
{
return indefinite_value;
}
// std::future<T>::wait_for, std::this_thread::sleep_for, and std::condition_variable::wait_for
// may use steady_clock or system_clock.We need make sure now() + timeout do not overflow.
auto max_timeout = std::chrono::duration_cast<std::chrono::duration<Rep, Period>>(
(std::chrono::steady_clock::time_point::max)() - std::chrono::steady_clock::now());
if (timeout >= max_timeout)
{
return indefinite_value;
}
max_timeout = std::chrono::duration_cast<std::chrono::duration<Rep, Period>>(
(std::chrono::system_clock::time_point::max)() - std::chrono::system_clock::now());
if (timeout >= max_timeout)
{
return indefinite_value;
}
return timeout;
}
};
} // namespace common
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,14 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifndef __has_include
# define OPENTELEMETRY_HAS_INCLUDE(x) 0
#else
# define OPENTELEMETRY_HAS_INCLUDE(x) __has_include(x)
#endif
#if !defined(__GLIBCXX__) || OPENTELEMETRY_HAS_INCLUDE(<codecvt>) // >= libstdc++-5
# define OPENTELEMETRY_TRIVIALITY_TYPE_TRAITS
#endif

View File

@@ -1,165 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <cstring>
#include <utility>
#include "opentelemetry/context/context_value.h"
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/nostd/variant.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace context
{
// The context class provides a context identifier. Is built as a linked list
// of DataList nodes and each context holds a shared_ptr to a place within
// the list that determines which keys and values it has access to. All that
// come before and none that come after.
class Context
{
public:
Context() = default;
// Creates a context object from a map of keys and identifiers, this will
// hold a shared_ptr to the head of the DataList linked list
template <class T>
Context(const T &keys_and_values) noexcept
{
head_ = nostd::shared_ptr<DataList>{new DataList(keys_and_values)};
}
// Creates a context object from a key and value, this will
// hold a shared_ptr to the head of the DataList linked list
Context(nostd::string_view key, ContextValue value) noexcept
{
head_ = nostd::shared_ptr<DataList>{new DataList(key, value)};
}
// Accepts a new iterable and then returns a new context that
// contains the new key and value data. It attaches the
// exisiting list to the end of the new list.
template <class T>
Context SetValues(T &values) noexcept
{
Context context = Context(values);
nostd::shared_ptr<DataList> last = context.head_;
while (last->next_ != nullptr)
{
last = last->next_;
}
last->next_ = head_;
return context;
}
// Accepts a new iterable and then returns a new context that
// contains the new key and value data. It attaches the
// exisiting list to the end of the new list.
Context SetValue(nostd::string_view key, ContextValue value) noexcept
{
Context context = Context(key, value);
context.head_->next_ = head_;
return context;
}
// Returns the value associated with the passed in key.
context::ContextValue GetValue(const nostd::string_view key) const noexcept
{
for (DataList *data = head_.get(); data != nullptr; data = data->next_.get())
{
if (key.size() == data->key_length_)
{
if (std::memcmp(key.data(), data->key_, data->key_length_) == 0)
{
return data->value_;
}
}
}
return ContextValue{};
}
// Checks for key and returns true if found
bool HasKey(const nostd::string_view key) const noexcept
{
return !nostd::holds_alternative<nostd::monostate>(GetValue(key));
}
bool operator==(const Context &other) const noexcept { return (head_ == other.head_); }
private:
// A linked list to contain the keys and values of this context node
class DataList
{
public:
char *key_;
nostd::shared_ptr<DataList> next_;
size_t key_length_;
ContextValue value_;
DataList() { next_ = nullptr; }
// Builds a data list off of a key and value iterable and returns the head
template <class T>
DataList(const T &keys_and_vals) : key_{nullptr}, next_(nostd::shared_ptr<DataList>{nullptr})
{
bool first = true;
auto *node = this;
for (auto &iter : keys_and_vals)
{
if (first)
{
*node = DataList(iter.first, iter.second);
first = false;
}
else
{
node->next_ = nostd::shared_ptr<DataList>(new DataList(iter.first, iter.second));
node = node->next_.get();
}
}
}
// Builds a data list with just a key and value, so it will just be the head
// and returns that head.
DataList(nostd::string_view key, const ContextValue &value)
{
key_ = new char[key.size()];
key_length_ = key.size();
memcpy(key_, key.data(), key.size() * sizeof(char));
value_ = value;
next_ = nostd::shared_ptr<DataList>{nullptr};
}
DataList &operator=(DataList &&other) noexcept
{
key_length_ = other.key_length_;
value_ = std::move(other.value_);
next_ = std::move(other.next_);
key_ = other.key_;
other.key_ = nullptr;
return *this;
}
~DataList()
{
if (key_ != nullptr)
{
delete[] key_;
}
}
};
// Head of the list which holds the keys and values of this context
nostd::shared_ptr<DataList> head_;
};
} // namespace context
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,35 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <cstdint>
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/nostd/variant.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace baggage
{
class Baggage;
} // namespace baggage
namespace trace
{
class Span;
class SpanContext;
} // namespace trace
namespace context
{
using ContextValue = nostd::variant<nostd::monostate,
bool,
int64_t,
uint64_t,
double,
nostd::shared_ptr<trace::Span>,
nostd::shared_ptr<trace::SpanContext>,
nostd::shared_ptr<baggage::Baggage>>;
} // namespace context
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,339 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <stddef.h>
#include <algorithm>
#include "opentelemetry/common/macros.h"
#include "opentelemetry/context/context.h"
#include "opentelemetry/context/context_value.h"
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/nostd/unique_ptr.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace context
{
// The Token object provides is returned when attaching objects to the
// RuntimeContext object and is associated with a context object, and
// can be provided to the RuntimeContext Detach method to remove the
// associated context from the RuntimeContext.
class Token
{
public:
bool operator==(const Context &other) const noexcept { return context_ == other; }
~Token() noexcept;
private:
friend class RuntimeContextStorage;
// A constructor that sets the token's Context object to the
// one that was passed in.
Token(const Context &context) : context_(context) {}
const Context context_;
};
/**
* RuntimeContextStorage is used by RuntimeContext to store Context frames.
*
* Custom context management strategies can be implemented by deriving from
* this class and passing an initialized RuntimeContextStorage object to
* RuntimeContext::SetRuntimeContextStorage.
*/
class OPENTELEMETRY_EXPORT RuntimeContextStorage
{
public:
/**
* Return the current context.
* @return the current context
*/
virtual Context GetCurrent() noexcept = 0;
/**
* Set the current context.
* @param the new current context
* @return a token for the new current context. This never returns a nullptr.
*/
virtual nostd::unique_ptr<Token> Attach(const Context &context) noexcept = 0;
/**
* Detach the context related to the given token.
* @param token a token related to a context
* @return true if the context could be detached
*/
virtual bool Detach(Token &token) noexcept = 0;
virtual ~RuntimeContextStorage() {}
protected:
nostd::unique_ptr<Token> CreateToken(const Context &context) noexcept
{
return nostd::unique_ptr<Token>(new Token(context));
}
};
/**
* Construct and return the default RuntimeContextStorage
* @return a ThreadLocalContextStorage
*/
static RuntimeContextStorage *GetDefaultStorage() noexcept;
// Provides a wrapper for propagating the context object globally.
//
// By default, a thread-local runtime context storage is used.
class OPENTELEMETRY_EXPORT RuntimeContext
{
public:
// Return the current context.
static Context GetCurrent() noexcept { return GetRuntimeContextStorage()->GetCurrent(); }
// Sets the current 'Context' object. Returns a token
// that can be used to reset to the previous Context.
static nostd::unique_ptr<Token> Attach(const Context &context) noexcept
{
return GetRuntimeContextStorage()->Attach(context);
}
// Resets the context to a previous value stored in the
// passed in token. Returns true if successful, false otherwise
static bool Detach(Token &token) noexcept { return GetRuntimeContextStorage()->Detach(token); }
// Sets the Key and Value into the passed in context or if a context is not
// passed in, the RuntimeContext.
// Should be used to SetValues to the current RuntimeContext, is essentially
// equivalent to RuntimeContext::GetCurrent().SetValue(key,value). Keep in
// mind that the current RuntimeContext will not be changed, and the new
// context will be returned.
static Context SetValue(nostd::string_view key,
const ContextValue &value,
Context *context = nullptr) noexcept
{
Context temp_context;
if (context == nullptr)
{
temp_context = GetCurrent();
}
else
{
temp_context = *context;
}
return temp_context.SetValue(key, value);
}
// Returns the value associated with the passed in key and either the
// passed in context* or the runtime context if a context is not passed in.
// Should be used to get values from the current RuntimeContext, is
// essentially equivalent to RuntimeContext::GetCurrent().GetValue(key).
static ContextValue GetValue(nostd::string_view key, Context *context = nullptr) noexcept
{
Context temp_context;
if (context == nullptr)
{
temp_context = GetCurrent();
}
else
{
temp_context = *context;
}
return temp_context.GetValue(key);
}
/**
* Provide a custom runtime context storage.
*
* This provides a possibility to override the default thread-local runtime
* context storage. This has to be set before any spans are created by the
* application, otherwise the behavior is undefined.
*
* @param storage a custom runtime context storage
*/
static void SetRuntimeContextStorage(nostd::shared_ptr<RuntimeContextStorage> storage) noexcept
{
GetStorage() = storage;
}
/**
* Provide a pointer to const runtime context storage.
*
* The returned pointer can only be used for extending the lifetime of the runtime context
* storage.
*
*/
static nostd::shared_ptr<const RuntimeContextStorage> GetConstRuntimeContextStorage() noexcept
{
return GetRuntimeContextStorage();
}
private:
static nostd::shared_ptr<RuntimeContextStorage> GetRuntimeContextStorage() noexcept
{
return GetStorage();
}
OPENTELEMETRY_API_SINGLETON static nostd::shared_ptr<RuntimeContextStorage> &GetStorage() noexcept
{
static nostd::shared_ptr<RuntimeContextStorage> context(GetDefaultStorage());
return context;
}
};
inline Token::~Token() noexcept
{
context::RuntimeContext::Detach(*this);
}
// The ThreadLocalContextStorage class is a derived class from
// RuntimeContextStorage and provides a wrapper for propagating context through
// cpp thread locally. This file must be included to use the RuntimeContext
// class if another implementation has not been registered.
class ThreadLocalContextStorage : public RuntimeContextStorage
{
public:
ThreadLocalContextStorage() noexcept = default;
// Return the current context.
Context GetCurrent() noexcept override { return GetStack().Top(); }
// Resets the context to the value previous to the passed in token. This will
// also detach all child contexts of the passed in token.
// Returns true if successful, false otherwise.
bool Detach(Token &token) noexcept override
{
// In most cases, the context to be detached is on the top of the stack.
if (token == GetStack().Top())
{
GetStack().Pop();
return true;
}
if (!GetStack().Contains(token))
{
return false;
}
while (!(token == GetStack().Top()))
{
GetStack().Pop();
}
GetStack().Pop();
return true;
}
// Sets the current 'Context' object. Returns a token
// that can be used to reset to the previous Context.
nostd::unique_ptr<Token> Attach(const Context &context) noexcept override
{
GetStack().Push(context);
return CreateToken(context);
}
private:
// A nested class to store the attached contexts in a stack.
class Stack
{
friend class ThreadLocalContextStorage;
Stack() noexcept : size_(0), capacity_(0), base_(nullptr) {}
// Pops the top Context off the stack.
void Pop() noexcept
{
if (size_ == 0)
{
return;
}
// Store empty Context before decrementing `size`, to ensure
// the shared_ptr object (if stored in prev context object ) are released.
// The stack is not resized, and the unused memory would be reutilised
// for subsequent context storage.
base_[size_ - 1] = Context();
size_ -= 1;
}
bool Contains(const Token &token) const noexcept
{
for (size_t pos = size_; pos > 0; --pos)
{
if (token == base_[pos - 1])
{
return true;
}
}
return false;
}
// Returns the Context at the top of the stack.
Context Top() const noexcept
{
if (size_ == 0)
{
return Context();
}
return base_[size_ - 1];
}
// Pushes the passed in context pointer to the top of the stack
// and resizes if necessary.
void Push(const Context &context) noexcept
{
size_++;
if (size_ > capacity_)
{
Resize(size_ * 2);
}
base_[size_ - 1] = context;
}
// Reallocates the storage array to the pass in new capacity size.
void Resize(size_t new_capacity) noexcept
{
size_t old_size = size_ - 1;
if (new_capacity == 0)
{
new_capacity = 2;
}
Context *temp = new Context[new_capacity];
if (base_ != nullptr)
{
// vs2015 does not like this construct considering it unsafe:
// - std::copy(base_, base_ + old_size, temp);
// Ref.
// https://stackoverflow.com/questions/12270224/xutility2227-warning-c4996-std-copy-impl
for (size_t i = 0; i < (std::min)(old_size, new_capacity); i++)
{
temp[i] = base_[i];
}
delete[] base_;
}
base_ = temp;
capacity_ = new_capacity;
}
~Stack() noexcept { delete[] base_; }
size_t size_;
size_t capacity_;
Context *base_;
};
OPENTELEMETRY_API_SINGLETON Stack &GetStack()
{
static thread_local Stack stack_ = Stack();
return stack_;
}
};
static RuntimeContextStorage *GetDefaultStorage() noexcept
{
return new ThreadLocalContextStorage();
}
} // namespace context
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,13 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// NOTE - code within detail namespace implements internal details, and not part
// of the public interface.
#pragma once
#define OPENTELEMETRY_STRINGIFY(S) OPENTELEMETRY_STRINGIFY_(S)
#define OPENTELEMETRY_STRINGIFY_(S) #S
#define OPENTELEMETRY_CONCAT(A, B) OPENTELEMETRY_CONCAT_(A, B)
#define OPENTELEMETRY_CONCAT_(A, B) A##B

View File

@@ -1,94 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <iosfwd>
#include <memory> // IWYU pragma: keep
#include <type_traits>
#include <utility>
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace nostd
{
template <class Sig>
class function_ref; // IWYU pragma: keep
/**
* Non-owning function reference that can be used as a more performant
* replacement for std::function when ownership sematics aren't needed.
*
* See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0792r0.html
*
* Based off of https://stackoverflow.com/a/39087660/4447365
*/
template <class R, class... Args>
class function_ref<R(Args...)>
{
void *callable_ = nullptr;
R (*invoker_)(void *, Args...) = nullptr;
template <class F>
using FunctionPointer = decltype(std::addressof(std::declval<F &>()));
template <class F>
void BindTo(F &f) noexcept
{
callable_ = static_cast<void *>(std::addressof(f));
invoker_ = [](void *callable, Args... args) -> R {
return (*static_cast<FunctionPointer<F>>(callable))(std::forward<Args>(args)...);
};
}
template <class R_in, class... Args_in>
void BindTo(R_in (*f)(Args_in...)) noexcept
{
using F = decltype(f);
if (f == nullptr)
{
return BindTo(nullptr);
}
callable_ = reinterpret_cast<void *>(f);
invoker_ = [](void *callable, Args... args) -> R {
return (F(callable))(std::forward<Args>(args)...);
};
}
void BindTo(std::nullptr_t) noexcept
{
callable_ = nullptr;
invoker_ = nullptr;
}
public:
template <
class F,
typename std::enable_if<!std::is_same<function_ref, typename std::decay<F>::type>::value,
int>::type = 0,
typename std::enable_if<
#if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && (_MSVC_LANG > 201402))
// std::result_of deprecated in C++17, removed in C++20
std::is_convertible<typename std::invoke_result<F, Args...>::type, R>::value,
#else
// std::result_of since C++11
std::is_convertible<typename std::result_of<F &(Args...)>::type, R>::value,
#endif
int>::type = 0>
function_ref(F &&f)
{
BindTo(f); // not forward
}
function_ref(std::nullptr_t) {}
function_ref(const function_ref &) noexcept = default;
function_ref(function_ref &&) noexcept = default;
R operator()(Args... args) const { return invoker_(callable_, std::forward<Args>(args)...); }
explicit operator bool() const { return invoker_; }
};
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,210 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#if defined(OPENTELEMETRY_STL_VERSION)
# if OPENTELEMETRY_STL_VERSION >= 2011
# include "opentelemetry/std/shared_ptr.h"
# define OPENTELEMETRY_HAVE_STD_SHARED_PTR
# endif
#endif
#if !defined(OPENTELEMETRY_HAVE_STD_SHARED_PTR)
# include <cstdlib>
# include <memory>
# include <utility>
# include "opentelemetry/nostd/unique_ptr.h"
# include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace nostd
{
/**
* Provide a type-erased version of std::shared_ptr that has ABI stability.
*/
template <class T>
class shared_ptr
{
public:
using element_type = T;
using pointer = element_type *;
private:
static constexpr size_t kMaxSize = 32;
static constexpr size_t kAlignment = 8;
struct alignas(kAlignment) PlacementBuffer
{
char data[kMaxSize];
};
class shared_ptr_wrapper
{
public:
shared_ptr_wrapper() noexcept = default;
shared_ptr_wrapper(std::shared_ptr<T> &&ptr) noexcept : ptr_{std::move(ptr)} {}
virtual ~shared_ptr_wrapper() {}
virtual void CopyTo(PlacementBuffer &buffer) const noexcept
{
new (buffer.data) shared_ptr_wrapper{*this};
}
virtual void MoveTo(PlacementBuffer &buffer) noexcept
{
new (buffer.data) shared_ptr_wrapper{std::move(this->ptr_)};
}
template <class U,
typename std::enable_if<std::is_convertible<pointer, U *>::value>::type * = nullptr>
void MoveTo(typename shared_ptr<U>::PlacementBuffer &buffer) noexcept
{
using other_shared_ptr_wrapper = typename shared_ptr<U>::shared_ptr_wrapper;
new (buffer.data) other_shared_ptr_wrapper{std::move(this->ptr_)};
}
virtual pointer Get() const noexcept { return ptr_.get(); }
virtual void Reset() noexcept { ptr_.reset(); }
private:
std::shared_ptr<T> ptr_;
};
static_assert(sizeof(shared_ptr_wrapper) <= kMaxSize, "Placement buffer is too small");
static_assert(alignof(shared_ptr_wrapper) <= kAlignment, "Placement buffer not properly aligned");
public:
shared_ptr() noexcept { new (buffer_.data) shared_ptr_wrapper{}; }
explicit shared_ptr(pointer ptr)
{
std::shared_ptr<T> ptr_(ptr);
new (buffer_.data) shared_ptr_wrapper{std::move(ptr_)};
}
shared_ptr(std::shared_ptr<T> ptr) noexcept
{
new (buffer_.data) shared_ptr_wrapper{std::move(ptr)};
}
shared_ptr(shared_ptr &&other) noexcept { other.wrapper().MoveTo(buffer_); }
template <class U,
typename std::enable_if<std::is_convertible<U *, pointer>::value>::type * = nullptr>
shared_ptr(shared_ptr<U> &&other) noexcept
{
other.wrapper().template MoveTo<T>(buffer_);
}
shared_ptr(const shared_ptr &other) noexcept { other.wrapper().CopyTo(buffer_); }
shared_ptr(unique_ptr<T> &&other) noexcept
{
std::shared_ptr<T> ptr_(other.release());
new (buffer_.data) shared_ptr_wrapper{std::move(ptr_)};
}
shared_ptr(std::unique_ptr<T> &&other) noexcept
{
std::shared_ptr<T> ptr_(other.release());
new (buffer_.data) shared_ptr_wrapper{std::move(ptr_)};
}
~shared_ptr() { wrapper().~shared_ptr_wrapper(); }
shared_ptr &operator=(shared_ptr &&other) noexcept
{
wrapper().~shared_ptr_wrapper();
other.wrapper().MoveTo(buffer_);
return *this;
}
shared_ptr &operator=(std::nullptr_t) noexcept
{
wrapper().Reset();
return *this;
}
shared_ptr &operator=(const shared_ptr &other) noexcept
{
wrapper().~shared_ptr_wrapper();
other.wrapper().CopyTo(buffer_);
return *this;
}
element_type &operator*() const noexcept { return *wrapper().Get(); }
pointer operator->() const noexcept { return wrapper().Get(); }
operator bool() const noexcept { return wrapper().Get() != nullptr; }
pointer get() const noexcept { return wrapper().Get(); }
void swap(shared_ptr<T> &other) noexcept
{
shared_ptr<T> tmp{std::move(other)};
wrapper().MoveTo(other.buffer_);
tmp.wrapper().MoveTo(buffer_);
}
template <typename U>
friend class shared_ptr;
private:
PlacementBuffer buffer_;
shared_ptr_wrapper &wrapper() noexcept
{
return *reinterpret_cast<shared_ptr_wrapper *>(buffer_.data);
}
const shared_ptr_wrapper &wrapper() const noexcept
{
return *reinterpret_cast<const shared_ptr_wrapper *>(buffer_.data);
}
};
template <class T1, class T2>
bool operator!=(const shared_ptr<T1> &lhs, const shared_ptr<T2> &rhs) noexcept
{
return lhs.get() != rhs.get();
}
template <class T1, class T2>
bool operator==(const shared_ptr<T1> &lhs, const shared_ptr<T2> &rhs) noexcept
{
return lhs.get() == rhs.get();
}
template <class T>
inline bool operator==(const shared_ptr<T> &lhs, std::nullptr_t) noexcept
{
return lhs.get() == nullptr;
}
template <class T>
inline bool operator==(std::nullptr_t, const shared_ptr<T> &rhs) noexcept
{
return nullptr == rhs.get();
}
template <class T>
inline bool operator!=(const shared_ptr<T> &lhs, std::nullptr_t) noexcept
{
return lhs.get() != nullptr;
}
template <class T>
inline bool operator!=(std::nullptr_t, const shared_ptr<T> &rhs) noexcept
{
return nullptr != rhs.get();
}
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE
#endif /* OPENTELEMETRY_HAVE_STD_SHARED_PTR */

View File

@@ -1,274 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
// Try to use either `std::span` or `gsl::span`
#if defined(OPENTELEMETRY_STL_VERSION)
# if OPENTELEMETRY_STL_VERSION >= 2020
# include <array>
# include <cstddef>
# include <iterator>
# include <type_traits>
/**
* @brief Clang 14.0.0 with libc++ do not support implicitly construct a span
* for a range. We just use our fallback version.
*
*/
# if !defined(OPENTELEMETRY_OPTION_USE_STD_SPAN) && defined(_LIBCPP_VERSION)
# if _LIBCPP_VERSION <= 14000
# define OPENTELEMETRY_OPTION_USE_STD_SPAN 0
# endif
# endif
# ifndef OPENTELEMETRY_OPTION_USE_STD_SPAN
# define OPENTELEMETRY_OPTION_USE_STD_SPAN 1
# endif
# if OPENTELEMETRY_OPTION_USE_STD_SPAN
# include "opentelemetry/std/span.h"
# endif
# endif /* OPENTELEMETRY_STL_VERSION >= 2020 */
#endif /* OPENTELEMETRY_STL_VERSION */
// Fallback to `nostd::span` if necessary
#if !defined(OPENTELEMETRY_HAVE_SPAN)
# include <array>
# include <cassert>
# include <cstddef>
# include <exception>
# include <iterator>
# include <type_traits>
# include "opentelemetry/nostd/utility.h"
# include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace nostd
{
constexpr size_t dynamic_extent = static_cast<size_t>(-1);
template <class T, size_t Extent = dynamic_extent>
class span;
namespace detail
{
/**
* Helper class to resolve overloaded constructors
*/
template <class T>
struct is_specialized_span_convertible : std::false_type
{};
template <class T, size_t N>
struct is_specialized_span_convertible<std::array<T, N>> : std::true_type
{};
template <class T, size_t N>
struct is_specialized_span_convertible<T[N]> : std::true_type
{};
template <class T, size_t Extent>
struct is_specialized_span_convertible<span<T, Extent>> : std::true_type
{};
} // namespace detail
/**
* Back port of std::span.
*
* See https://en.cppreference.com/w/cpp/container/span for interface documentation.
*
* Note: This provides a subset of the methods available on std::span.
*
* Note: The std::span API specifies error cases to have undefined behavior, so this implementation
* chooses to terminate or assert rather than throw exceptions.
*/
template <class T, size_t Extent>
class span
{
public:
static constexpr size_t extent = Extent;
// This arcane code is how we make default-construction result in an SFINAE error
// with C++11 when Extent != 0 as specified by the std::span API.
//
// See https://stackoverflow.com/a/10309720/4447365
template <bool B = Extent == 0, typename std::enable_if<B>::type * = nullptr>
span() noexcept : data_{nullptr}
{}
span(T *data, size_t count) noexcept : data_{data}
{
if (count != Extent)
{
std::terminate();
}
}
span(T *first, T *last) noexcept : data_{first}
{
if (std::distance(first, last) != Extent)
{
std::terminate();
}
}
template <size_t N, typename std::enable_if<Extent == N>::type * = nullptr>
span(T (&array)[N]) noexcept : data_{array}
{}
template <size_t N, typename std::enable_if<Extent == N>::type * = nullptr>
span(std::array<T, N> &array) noexcept : data_{array.data()}
{}
template <size_t N, typename std::enable_if<Extent == N>::type * = nullptr>
span(const std::array<T, N> &array) noexcept : data_{array.data()}
{}
template <
class C,
typename std::enable_if<!detail::is_specialized_span_convertible<C>::value &&
std::is_convertible<typename std::remove_pointer<decltype(nostd::data(
std::declval<C &>()))>::type (*)[],
T (*)[]>::value &&
std::is_convertible<decltype(nostd::size(std::declval<const C &>())),
size_t>::value>::type * = nullptr>
span(C &c) noexcept(noexcept(nostd::data(c), nostd::size(c))) : data_{nostd::data(c)}
{
if (nostd::size(c) != Extent)
{
std::terminate();
}
}
template <
class C,
typename std::enable_if<!detail::is_specialized_span_convertible<C>::value &&
std::is_convertible<typename std::remove_pointer<decltype(nostd::data(
std::declval<const C &>()))>::type (*)[],
T (*)[]>::value &&
std::is_convertible<decltype(nostd::size(std::declval<const C &>())),
size_t>::value>::type * = nullptr>
span(const C &c) noexcept(noexcept(nostd::data(c), nostd::size(c))) : data_{nostd::data(c)}
{
if (nostd::size(c) != Extent)
{
std::terminate();
}
}
template <class U,
size_t N,
typename std::enable_if<N == Extent &&
std::is_convertible<U (*)[], T (*)[]>::value>::type * = nullptr>
span(const span<U, N> &other) noexcept : data_{other.data()}
{}
span(const span &) noexcept = default;
span &operator=(const span &) noexcept = default;
bool empty() const noexcept { return Extent == 0; }
T *data() const noexcept { return data_; }
size_t size() const noexcept { return Extent; }
T &operator[](size_t index) const noexcept
{
assert(index < Extent);
return data_[index];
}
T *begin() const noexcept { return data_; }
T *end() const noexcept { return data_ + Extent; }
private:
T *data_;
};
template <class T>
class span<T, dynamic_extent>
{
public:
static constexpr size_t extent = dynamic_extent;
span() noexcept : extent_{0}, data_{nullptr} {}
span(T *data, size_t count) noexcept : extent_{count}, data_{data} {}
span(T *first, T *last) noexcept
: extent_{static_cast<size_t>(std::distance(first, last))}, data_{first}
{
assert(first <= last);
}
template <size_t N>
span(T (&array)[N]) noexcept : extent_{N}, data_{array}
{}
template <size_t N>
span(std::array<T, N> &array) noexcept : extent_{N}, data_{array.data()}
{}
template <size_t N>
span(const std::array<T, N> &array) noexcept : extent_{N}, data_{array.data()}
{}
template <
class C,
typename std::enable_if<!detail::is_specialized_span_convertible<C>::value &&
std::is_convertible<typename std::remove_pointer<decltype(nostd::data(
std::declval<C &>()))>::type (*)[],
T (*)[]>::value &&
std::is_convertible<decltype(nostd::size(std::declval<const C &>())),
size_t>::value>::type * = nullptr>
span(C &c) noexcept(noexcept(nostd::data(c), nostd::size(c)))
: extent_{nostd::size(c)}, data_{nostd::data(c)}
{}
template <
class C,
typename std::enable_if<!detail::is_specialized_span_convertible<C>::value &&
std::is_convertible<typename std::remove_pointer<decltype(nostd::data(
std::declval<const C &>()))>::type (*)[],
T (*)[]>::value &&
std::is_convertible<decltype(nostd::size(std::declval<const C &>())),
size_t>::value>::type * = nullptr>
span(const C &c) noexcept(noexcept(nostd::data(c), nostd::size(c)))
: extent_{nostd::size(c)}, data_{nostd::data(c)}
{}
template <class U,
size_t N,
typename std::enable_if<std::is_convertible<U (*)[], T (*)[]>::value>::type * = nullptr>
span(const span<U, N> &other) noexcept : extent_{other.size()}, data_{other.data()}
{}
span(const span &) noexcept = default;
span &operator=(const span &) noexcept = default;
bool empty() const noexcept { return extent_ == 0; }
T *data() const noexcept { return data_; }
size_t size() const noexcept { return extent_; }
T &operator[](size_t index) const noexcept
{
assert(index < extent_);
return data_[index];
}
T *begin() const noexcept { return data_; }
T *end() const noexcept { return data_ + extent_; }
private:
size_t extent_;
T *data_;
};
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE
#endif

View File

@@ -1,226 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#if defined(OPENTELEMETRY_STL_VERSION)
# if OPENTELEMETRY_STL_VERSION >= 2017
# include "opentelemetry/std/string_view.h"
# define OPENTELEMETRY_HAVE_STD_STRING_VIEW
# endif
#endif
#if !defined(OPENTELEMETRY_HAVE_STD_STRING_VIEW)
# include <algorithm>
# include <cstring>
# include <functional>
# include <ostream>
# include <stdexcept>
# include <string>
# include <type_traits>
# include <utility>
# include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace nostd
{
using Traits = std::char_traits<char>;
/**
* Back port of std::string_view to work with pre-cpp-17 compilers.
*
* Note: This provides a subset of the methods available on std::string_view but
* tries to be as compatible as possible with the std::string_view interface.
*/
class string_view
{
public:
typedef std::size_t size_type;
static constexpr size_type npos = static_cast<size_type>(-1);
string_view() noexcept : length_(0), data_(nullptr) {}
string_view(const char *str) noexcept : length_(std::strlen(str)), data_(str) {}
string_view(const std::basic_string<char> &str OPENTELEMETRY_ATTRIBUTE_LIFETIME_BOUND) noexcept
: length_(str.length()), data_(str.c_str())
{}
string_view(const char *str, size_type len) noexcept : length_(len), data_(str) {}
explicit operator std::string() const { return {data_, length_}; }
const char *data() const noexcept { return data_; }
bool empty() const noexcept { return length_ == 0; }
size_type length() const noexcept { return length_; }
size_type size() const noexcept { return length_; }
const char *begin() const noexcept { return data(); }
const char *end() const noexcept { return data() + length(); }
const char &operator[](size_type i) { return *(data() + i); }
string_view substr(size_type pos, size_type n = npos) const
{
if (pos > length_)
{
# if __EXCEPTIONS
throw std::out_of_range{"opentelemetry::nostd::string_view"};
# else
std::terminate();
# endif
}
n = (std::min)(n, length_ - pos);
return string_view(data_ + pos, n);
}
int compare(string_view v) const noexcept
{
size_type len = (std::min)(size(), v.size());
int result = Traits::compare(data(), v.data(), len);
if (result == 0)
result = size() == v.size() ? 0 : (size() < v.size() ? -1 : 1);
return result;
}
int compare(size_type pos1, size_type count1, string_view v) const
{
return substr(pos1, count1).compare(v);
}
int compare(size_type pos1,
size_type count1,
string_view v,
size_type pos2,
size_type count2) const
{
return substr(pos1, count1).compare(v.substr(pos2, count2));
}
int compare(const char *s) const { return compare(string_view(s)); }
int compare(size_type pos1, size_type count1, const char *s) const
{
return substr(pos1, count1).compare(string_view(s));
}
int compare(size_type pos1, size_type count1, const char *s, size_type count2) const
{
return substr(pos1, count1).compare(string_view(s, count2));
}
size_type find(char ch, size_type pos = 0) const noexcept
{
size_type res = npos;
if (pos < length())
{
auto found = Traits::find(data() + pos, length() - pos, ch);
if (found)
{
res = found - data();
}
}
return res;
}
bool operator<(const string_view v) const noexcept { return compare(v) < 0; }
bool operator>(const string_view v) const noexcept { return compare(v) > 0; }
private:
// Note: uses the same binary layout as libstdc++'s std::string_view
// See
// https://github.com/gcc-mirror/gcc/blob/e0c554e4da7310df83bb1dcc7b8e6c4c9c5a2a4f/libstdc%2B%2B-v3/include/std/string_view#L466-L467
size_type length_;
const char *data_;
};
inline bool operator==(string_view lhs, string_view rhs) noexcept
{
return lhs.length() == rhs.length() &&
# if defined(_MSC_VER)
# if _MSC_VER >= 1900 && _MSC_VER <= 1911
// Avoid SCL error in Visual Studio 2015, VS2017 update 1 to update 4
(std::memcmp(lhs.data(), rhs.data(), lhs.length()) == 0);
# else
std::equal(lhs.data(), lhs.data() + lhs.length(), rhs.data());
# endif
# else
std::equal(lhs.data(), lhs.data() + lhs.length(), rhs.data());
# endif
}
inline bool operator==(string_view lhs, const std::string &rhs) noexcept
{
return lhs == string_view(rhs);
}
inline bool operator==(const std::string &lhs, string_view rhs) noexcept
{
return string_view(lhs) == rhs;
}
inline bool operator==(string_view lhs, const char *rhs) noexcept
{
return lhs == string_view(rhs);
}
inline bool operator==(const char *lhs, string_view rhs) noexcept
{
return string_view(lhs) == rhs;
}
inline bool operator!=(string_view lhs, string_view rhs) noexcept
{
return !(lhs == rhs);
}
inline bool operator!=(string_view lhs, const std::string &rhs) noexcept
{
return !(lhs == rhs);
}
inline bool operator!=(const std::string &lhs, string_view rhs) noexcept
{
return !(lhs == rhs);
}
inline bool operator!=(string_view lhs, const char *rhs) noexcept
{
return !(lhs == rhs);
}
inline bool operator!=(const char *lhs, string_view rhs) noexcept
{
return !(lhs == rhs);
}
inline std::ostream &operator<<(std::ostream &os, string_view s)
{
return os.write(s.data(), static_cast<std::streamsize>(s.length()));
}
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE
namespace std
{
template <>
struct hash<OPENTELEMETRY_NAMESPACE::nostd::string_view>
{
std::size_t operator()(const OPENTELEMETRY_NAMESPACE::nostd::string_view &k) const
{
// TODO: for C++17 that has native support for std::basic_string_view it would
// be more performance-efficient to provide a zero-copy hash.
auto s = std::string(k.data(), k.size());
return std::hash<std::string>{}(s);
}
};
} // namespace std
#endif /* OPENTELEMETRY_HAVE_STD_STRING_VIEW */

View File

@@ -1,162 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#if defined(OPENTELEMETRY_STL_VERSION)
# if OPENTELEMETRY_STL_VERSION >= 2011
# include "opentelemetry/std/type_traits.h"
# define OPENTELEMETRY_HAVE_STD_TYPE_TRAITS
# endif
#endif
#if !defined(OPENTELEMETRY_HAVE_STD_TYPE_TRAITS)
# include <array>
# include <type_traits>
# include "opentelemetry/config.h"
# include "opentelemetry/nostd/detail/void.h" // IWYU pragma: export
# include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace nostd
{
/**
* Back port of std::add_pointer_t
*/
template <class T>
using add_pointer_t = typename std::add_pointer<T>::type;
/**
* Back port of std::enable_if_t
*/
template <bool B, class T = void>
using enable_if_t = typename std::enable_if<B, T>::type;
/**
* Back port of std::remove_const_t
*/
template <typename T>
using remove_const_t = typename std::remove_const<T>::type;
/**
* Back port of std::remove_reference_t
*/
template <typename T>
using remove_reference_t = typename std::remove_reference<T>::type;
/**
* Back port of std::remove_cvref_t
*/
template <typename T>
using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type;
/**
* Back port of std::remove_all_extents
*/
template <typename T>
struct remove_all_extents
{
using type = T;
};
template <typename T, std::size_t N>
struct remove_all_extents<std::array<T, N>> : remove_all_extents<T>
{};
/**
* Back port of std::remove_all_extents_t
*/
template <typename T>
using remove_all_extents_t = typename remove_all_extents<T>::type;
/**
* Back port of std::is_swappable
*/
namespace detail
{
namespace swappable
{
using std::swap;
template <typename T>
struct is_swappable
{
private:
template <typename U, typename = decltype(swap(std::declval<U &>(), std::declval<U &>()))>
inline static std::true_type test(int);
template <typename U>
inline static std::false_type test(...);
public:
static constexpr bool value = decltype(test<T>(0))::value;
};
} // namespace swappable
} // namespace detail
using detail::swappable::is_swappable;
/**
* Back port of std::is_swappable
*/
namespace detail
{
namespace swappable
{
template <bool IsSwappable, typename T>
struct is_nothrow_swappable
{
static constexpr bool value = noexcept(swap(std::declval<T &>(), std::declval<T &>()));
};
template <typename T>
struct is_nothrow_swappable<false, T> : std::false_type
{};
} // namespace swappable
} // namespace detail
template <typename T>
using is_nothrow_swappable = detail::swappable::is_nothrow_swappable<is_swappable<T>::value, T>;
/**
* Back port of
* std::is_trivialy_copy_constructible
* std::is_trivialy_move_constructible
* std::is_trivialy_copy_assignable
* std::is_trivialy_move_assignable
*/
# ifdef OPENTELEMETRY_TRIVIALITY_TYPE_TRAITS
using std::is_trivially_copy_assignable;
using std::is_trivially_copy_constructible;
using std::is_trivially_move_assignable;
using std::is_trivially_move_constructible;
# else
template <typename T>
struct is_trivially_copy_constructible
{
static constexpr bool value = std::is_copy_constructible<T>::value && __has_trivial_copy(T);
};
template <typename T>
struct is_trivially_move_constructible
{
static constexpr bool value = __is_trivial(T);
};
template <typename T>
struct is_trivially_copy_assignable
{
static constexpr bool value = std::is_copy_assignable<T>::value && __has_trivial_assign(T);
};
template <typename T>
struct is_trivially_move_assignable
{
static constexpr bool value = __is_trivial(T);
};
# endif
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE
#endif /* OPENTELEMETRY_HAVE_STD_TYPE_TRAITS */

View File

@@ -1,180 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#if defined(OPENTELEMETRY_STL_VERSION)
# if OPENTELEMETRY_STL_VERSION >= 2011
# include "opentelemetry/std/unique_ptr.h"
# define OPENTELEMETRY_HAVE_STD_UNIQUE_PTR
# endif
#endif
#if !defined(OPENTELEMETRY_HAVE_STD_UNIQUE_PTR)
# include <cstddef>
# include <memory>
# include <type_traits>
# include <utility>
# include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace nostd
{
namespace detail
{
template <class T>
struct unique_ptr_element_type
{
using type = T;
};
template <class T>
struct unique_ptr_element_type<T[]>
{
using type = T;
};
} // namespace detail
/**
* Provide a simplified port of std::unique_ptr that has ABI stability.
*
* Note: This implementation doesn't allow for a custom deleter.
*/
template <class T>
class unique_ptr
{
public:
using element_type = typename detail::unique_ptr_element_type<T>::type;
using pointer = element_type *;
unique_ptr() noexcept : ptr_{nullptr} {}
unique_ptr(std::nullptr_t) noexcept : ptr_{nullptr} {}
explicit unique_ptr(pointer ptr) noexcept : ptr_{ptr} {}
unique_ptr(unique_ptr &&other) noexcept : ptr_{other.release()} {}
template <class U,
typename std::enable_if<std::is_convertible<U *, pointer>::value>::type * = nullptr>
unique_ptr(unique_ptr<U> &&other) noexcept : ptr_{other.release()}
{}
template <class U,
typename std::enable_if<std::is_convertible<U *, pointer>::value>::type * = nullptr>
unique_ptr(std::unique_ptr<U> &&other) noexcept : ptr_{other.release()}
{}
~unique_ptr() { reset(); }
unique_ptr &operator=(unique_ptr &&other) noexcept
{
reset(other.release());
return *this;
}
unique_ptr &operator=(std::nullptr_t) noexcept
{
reset();
return *this;
}
template <class U,
typename std::enable_if<std::is_convertible<U *, pointer>::value>::type * = nullptr>
unique_ptr &operator=(unique_ptr<U> &&other) noexcept
{
reset(other.release());
return *this;
}
template <class U,
typename std::enable_if<std::is_convertible<U *, pointer>::value>::type * = nullptr>
unique_ptr &operator=(std::unique_ptr<U> &&other) noexcept
{
reset(other.release());
return *this;
}
operator std::unique_ptr<T>() && noexcept { return std::unique_ptr<T>{release()}; }
operator bool() const noexcept { return ptr_ != nullptr; }
element_type &operator*() const noexcept { return *ptr_; }
pointer operator->() const noexcept { return get(); }
pointer get() const noexcept { return ptr_; }
void reset(pointer ptr = nullptr) noexcept
{
if (ptr_ != nullptr)
{
this->delete_ptr();
}
ptr_ = ptr;
}
pointer release() noexcept
{
auto result = ptr_;
ptr_ = nullptr;
return result;
}
void swap(unique_ptr &other) noexcept { std::swap(ptr_, other.ptr_); }
private:
pointer ptr_;
void delete_ptr() noexcept
{
if (std::is_array<T>::value)
{
delete[] ptr_;
}
else
{
delete ptr_;
}
}
};
template <class T1, class T2>
bool operator==(const unique_ptr<T1> &lhs, const unique_ptr<T2> &rhs) noexcept
{
return lhs.get() == rhs.get();
}
template <class T>
bool operator==(const unique_ptr<T> &lhs, std::nullptr_t) noexcept
{
return lhs.get() == nullptr;
}
template <class T>
bool operator==(std::nullptr_t, const unique_ptr<T> &rhs) noexcept
{
return nullptr == rhs.get();
}
template <class T1, class T2>
bool operator!=(const unique_ptr<T1> &lhs, const unique_ptr<T2> &rhs) noexcept
{
return lhs.get() != rhs.get();
}
template <class T>
bool operator!=(const unique_ptr<T> &lhs, std::nullptr_t) noexcept
{
return lhs.get() != nullptr;
}
template <class T>
bool operator!=(std::nullptr_t, const unique_ptr<T> &rhs) noexcept
{
return nullptr != rhs.get();
}
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE
#endif /* OPENTELEMETRY_HAVE_STD_UNIQUE_PTR */

View File

@@ -1,160 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#if defined(OPENTELEMETRY_STL_VERSION)
# if OPENTELEMETRY_STL_VERSION >= 2014
# include "opentelemetry/std/utility.h"
# define OPENTELEMETRY_HAVE_STD_UTILITY
# endif
#endif
#if !defined(OPENTELEMETRY_HAVE_STD_UTILITY)
# include <cstddef>
# include <initializer_list>
# include <type_traits>
# include "opentelemetry/nostd/detail/decay.h" // IWYU pragma: export
# include "opentelemetry/nostd/detail/invoke.h" // IWYU pragma: export
# include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace nostd
{
/**
* Back port of std::data
*
* See https://en.cppreference.com/w/cpp/iterator/data
*/
template <class C>
auto data(C &c) noexcept(noexcept(c.data())) -> decltype(c.data())
{
return c.data();
}
template <class C>
auto data(const C &c) noexcept(noexcept(c.data())) -> decltype(c.data())
{
return c.data();
}
template <class T, size_t N>
T *data(T (&array)[N]) noexcept
{
return array;
}
template <class E>
const E *data(std::initializer_list<E> list) noexcept
{
return list.begin();
}
/**
* Back port of std::size
*
* See https://en.cppreference.com/w/cpp/iterator/size
*/
template <class C>
auto size(const C &c) noexcept(noexcept(c.size())) -> decltype(c.size())
{
return c.size();
}
template <class T, size_t N>
size_t size(T (& /* array */)[N]) noexcept
{
return N;
}
/**
* Back port of std::bool_constant
*/
template <bool B>
using bool_constant = std::integral_constant<bool, B>;
/**
* Back port of std::integer_sequence
*/
template <typename T, T... Is>
struct integer_sequence
{
using value_type = T;
static constexpr std::size_t size() noexcept { return sizeof...(Is); }
};
/**
* Back port of std::index_sequence
*/
template <std::size_t... Is>
using index_sequence = integer_sequence<std::size_t, Is...>;
/**
* Back port of std::make_index_sequence
*/
namespace detail
{
template <class, size_t>
struct index_sequence_push_back
{};
template <size_t... Indexes, size_t I>
struct index_sequence_push_back<index_sequence<Indexes...>, I>
{
using type = index_sequence<Indexes..., I>;
};
template <class T, size_t I>
using index_sequence_push_back_t = typename index_sequence_push_back<T, I>::type;
template <size_t N>
struct make_index_sequence_impl
{
using type = index_sequence_push_back_t<typename make_index_sequence_impl<N - 1>::type, N - 1>;
};
template <>
struct make_index_sequence_impl<0>
{
using type = index_sequence<>;
};
} // namespace detail
template <size_t N>
using make_index_sequence = typename detail::make_index_sequence_impl<N>::type;
/**
* Back port of std::index_sequence_for
*/
template <class... Ts>
using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
/**
* Back port of std::in_place_t
*/
struct in_place_t
{
explicit in_place_t() = default;
};
/**
* Back port of std::in_place_index_t
*/
template <std::size_t I>
struct in_place_index_t
{
explicit in_place_index_t() = default;
};
/**
* Back port of std::in_place_type_t
*/
template <typename T>
struct in_place_type_t
{
explicit in_place_type_t() = default;
};
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE
#endif /* OPENTELEMETRY_HAVE_STD_UTILITY */

View File

@@ -1,90 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/version.h"
#if defined(OPENTELEMETRY_STL_VERSION)
# if OPENTELEMETRY_STL_VERSION >= 2017
# include "opentelemetry/std/variant.h"
# define OPENTELEMETRY_HAVE_STD_VARIANT
# endif
#endif
#if !defined(OPENTELEMETRY_HAVE_STD_VARIANT)
# ifndef HAVE_ABSEIL
// We use a LOCAL snapshot of Abseil that is known to compile with Visual Studio 2015.
// Header-only. Without compiling the actual Abseil binary. As Abseil moves on to new
// toolchains, it may drop support for Visual Studio 2015 in future versions.
# if defined(__EXCEPTIONS)
# include <exception>
OPENTELEMETRY_BEGIN_NAMESPACE
namespace nostd
{
class bad_variant_access : public std::exception
{
public:
virtual const char *what() const noexcept override { return "bad_variant_access"; }
};
[[noreturn]] inline void throw_bad_variant_access()
{
throw bad_variant_access{};
}
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE
# define THROW_BAD_VARIANT_ACCESS opentelemetry::nostd::throw_bad_variant_access()
# else
# define THROW_BAD_VARIANT_ACCESS std::terminate()
# endif
# endif
# ifdef _MSC_VER
// Abseil variant implementation contains some benign non-impacting warnings
// that should be suppressed if compiling with Visual Studio 2017 and above.
# pragma warning(push)
# pragma warning(disable : 4245) // conversion from int to const unsigned _int64
# pragma warning(disable : 4127) // conditional expression is constant
# endif
# ifdef HAVE_ABSEIL
# include "absl/types/variant.h"
# else
# include "opentelemetry/nostd/internal/absl/types/variant.h"
# endif
# ifdef _MSC_VER
# pragma warning(pop)
# endif
OPENTELEMETRY_BEGIN_NAMESPACE
namespace nostd
{
# ifdef HAVE_ABSEIL
using absl::bad_variant_access;
using absl::get;
using absl::get_if;
using absl::holds_alternative;
using absl::monostate;
using absl::variant;
using absl::variant_alternative_t;
using absl::variant_size;
using absl::visit;
# else
using absl::OTABSL_OPTION_NAMESPACE_NAME::get;
using absl::OTABSL_OPTION_NAMESPACE_NAME::get_if;
using absl::OTABSL_OPTION_NAMESPACE_NAME::holds_alternative;
using absl::OTABSL_OPTION_NAMESPACE_NAME::monostate;
using absl::OTABSL_OPTION_NAMESPACE_NAME::variant;
using absl::OTABSL_OPTION_NAMESPACE_NAME::variant_alternative_t;
using absl::OTABSL_OPTION_NAMESPACE_NAME::variant_size;
using absl::OTABSL_OPTION_NAMESPACE_NAME::visit;
# endif
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE
#endif /* OPENTELEMETRY_HAVE_STD_VARIANT */

View File

@@ -1,264 +0,0 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/*
* DO NOT EDIT, this is an Auto-generated file from:
* buildscripts/semantic-convention/templates/registry/semantic_attributes-h.j2
*/
#pragma once
#include "opentelemetry/common/macros.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace semconv
{
namespace process
{
/**
* Length of the process.command_args array
* <p>
* This field can be useful for querying or performing bucket analysis on how many arguments were
* provided to start a process. More arguments may be an indication of suspicious activity.
*/
static constexpr const char *kProcessArgsCount = "process.args_count";
/**
* The command used to launch the process (i.e. the command name). On Linux based systems, can be
* set to the zeroth string in @code proc/[pid]/cmdline @endcode. On Windows, can be set to the
* first parameter extracted from @code GetCommandLineW @endcode.
*/
static constexpr const char *kProcessCommand = "process.command";
/**
* All the command arguments (including the command/executable itself) as received by the process.
* On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according
* to the list of null-delimited strings extracted from @code proc/[pid]/cmdline @endcode. For
* libc-based executables, this would be the full argv vector passed to @code main @endcode.
*/
static constexpr const char *kProcessCommandArgs = "process.command_args";
/**
* The full command used to launch the process as a single string representing the full command. On
* Windows, can be set to the result of @code GetCommandLineW @endcode. Do not set this if you have
* to assemble it just for monitoring; use @code process.command_args @endcode instead.
*/
static constexpr const char *kProcessCommandLine = "process.command_line";
/**
* Specifies whether the context switches for this data point were voluntary or involuntary.
*/
static constexpr const char *kProcessContextSwitchType = "process.context_switch_type";
/**
* Deprecated, use @code cpu.mode @endcode instead.
* <p>
* @deprecated
* Replaced by @code cpu.mode @endcode
*/
OPENTELEMETRY_DEPRECATED
static constexpr const char *kProcessCpuState = "process.cpu.state";
/**
* The date and time the process was created, in ISO 8601 format.
*/
static constexpr const char *kProcessCreationTime = "process.creation.time";
/**
* The GNU build ID as found in the @code .note.gnu.build-id @endcode ELF section (hex string).
*/
static constexpr const char *kProcessExecutableBuildIdGnu = "process.executable.build_id.gnu";
/**
* The Go build ID as retrieved by @code go tool buildid <go executable> @endcode.
*/
static constexpr const char *kProcessExecutableBuildIdGo = "process.executable.build_id.go";
/**
* Profiling specific build ID for executables. See the OTel specification for Profiles for more
* information.
*/
static constexpr const char *kProcessExecutableBuildIdProfiling =
"process.executable.build_id.profiling";
/**
* The name of the process executable. On Linux based systems, can be set to the @code Name @endcode
* in @code proc/[pid]/status @endcode. On Windows, can be set to the base name of @code
* GetProcessImageFileNameW @endcode.
*/
static constexpr const char *kProcessExecutableName = "process.executable.name";
/**
* The full path to the process executable. On Linux based systems, can be set to the target of
* @code proc/[pid]/exe @endcode. On Windows, can be set to the result of @code
* GetProcessImageFileNameW @endcode.
*/
static constexpr const char *kProcessExecutablePath = "process.executable.path";
/**
* The exit code of the process.
*/
static constexpr const char *kProcessExitCode = "process.exit.code";
/**
* The date and time the process exited, in ISO 8601 format.
*/
static constexpr const char *kProcessExitTime = "process.exit.time";
/**
* The PID of the process's group leader. This is also the process group ID (PGID) of the process.
*/
static constexpr const char *kProcessGroupLeaderPid = "process.group_leader.pid";
/**
* Whether the process is connected to an interactive shell.
*/
static constexpr const char *kProcessInteractive = "process.interactive";
/**
* The username of the user that owns the process.
*/
static constexpr const char *kProcessOwner = "process.owner";
/**
* The type of page fault for this data point. Type @code major @endcode is for major/hard page
* faults, and @code minor @endcode is for minor/soft page faults.
*/
static constexpr const char *kProcessPagingFaultType = "process.paging.fault_type";
/**
* Parent Process identifier (PPID).
*/
static constexpr const char *kProcessParentPid = "process.parent_pid";
/**
* Process identifier (PID).
*/
static constexpr const char *kProcessPid = "process.pid";
/**
* The real user ID (RUID) of the process.
*/
static constexpr const char *kProcessRealUserId = "process.real_user.id";
/**
* The username of the real user of the process.
*/
static constexpr const char *kProcessRealUserName = "process.real_user.name";
/**
* An additional description about the runtime of the process, for example a specific vendor
* customization of the runtime environment.
*/
static constexpr const char *kProcessRuntimeDescription = "process.runtime.description";
/**
* The name of the runtime of this process.
*/
static constexpr const char *kProcessRuntimeName = "process.runtime.name";
/**
* The version of the runtime of this process, as returned by the runtime without modification.
*/
static constexpr const char *kProcessRuntimeVersion = "process.runtime.version";
/**
* The saved user ID (SUID) of the process.
*/
static constexpr const char *kProcessSavedUserId = "process.saved_user.id";
/**
* The username of the saved user.
*/
static constexpr const char *kProcessSavedUserName = "process.saved_user.name";
/**
* The PID of the process's session leader. This is also the session ID (SID) of the process.
*/
static constexpr const char *kProcessSessionLeaderPid = "process.session_leader.pid";
/**
* Process title (proctitle)
* <p>
* In many Unix-like systems, process title (proctitle), is the string that represents the name or
* command line of a running process, displayed by system monitoring tools like ps, top, and htop.
*/
static constexpr const char *kProcessTitle = "process.title";
/**
* The effective user ID (EUID) of the process.
*/
static constexpr const char *kProcessUserId = "process.user.id";
/**
* The username of the effective user of the process.
*/
static constexpr const char *kProcessUserName = "process.user.name";
/**
* Virtual process identifier.
* <p>
* The process ID within a PID namespace. This is not necessarily unique across all processes on the
* host but it is unique within the process namespace that the process exists within.
*/
static constexpr const char *kProcessVpid = "process.vpid";
/**
* The working directory of the process.
*/
static constexpr const char *kProcessWorkingDirectory = "process.working_directory";
namespace ProcessContextSwitchTypeValues
{
/**
* none
*/
static constexpr const char *kVoluntary = "voluntary";
/**
* none
*/
static constexpr const char *kInvoluntary = "involuntary";
} // namespace ProcessContextSwitchTypeValues
namespace ProcessCpuStateValues
{
/**
* none
*/
static constexpr const char *kSystem = "system";
/**
* none
*/
static constexpr const char *kUser = "user";
/**
* none
*/
static constexpr const char *kWait = "wait";
} // namespace ProcessCpuStateValues
namespace ProcessPagingFaultTypeValues
{
/**
* none
*/
static constexpr const char *kMajor = "major";
/**
* none
*/
static constexpr const char *kMinor = "minor";
} // namespace ProcessPagingFaultTypeValues
} // namespace process
} // namespace semconv
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,41 +0,0 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/*
* DO NOT EDIT, this is an Auto-generated file from:
* buildscripts/semantic-convention/templates/registry/semantic_attributes-h.j2
*/
#pragma once
#include "opentelemetry/common/macros.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace semconv
{
namespace service
{
/**
* Logical name of the service.
* <p>
* MUST be the same for all instances of horizontally scaled services. If the value was not
* specified, SDKs MUST fallback to @code unknown_service: @endcode concatenated with <a
* href="process.md">@code process.executable.name @endcode</a>, e.g. @code unknown_service:bash
* @endcode. If @code process.executable.name @endcode is not available, the value MUST be set to
* @code unknown_service @endcode.
*/
static constexpr const char *kServiceName = "service.name";
/**
* The version string of the service API or implementation. The format is not defined by these
* conventions.
*/
static constexpr const char *kServiceVersion = "service.version";
} // namespace service
} // namespace semconv
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,111 +0,0 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/*
* DO NOT EDIT, this is an Auto-generated file from:
* buildscripts/semantic-convention/templates/registry/semantic_attributes-h.j2
*/
#pragma once
#include "opentelemetry/common/macros.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace semconv
{
namespace telemetry
{
/**
* The language of the telemetry SDK.
*/
static constexpr const char *kTelemetrySdkLanguage = "telemetry.sdk.language";
/**
* The name of the telemetry SDK as defined above.
* <p>
* The OpenTelemetry SDK MUST set the @code telemetry.sdk.name @endcode attribute to @code
* opentelemetry @endcode. If another SDK, like a fork or a vendor-provided implementation, is used,
* this SDK MUST set the
* @code telemetry.sdk.name @endcode attribute to the fully-qualified class or module name of this
* SDK's main entry point or another suitable identifier depending on the language. The identifier
* @code opentelemetry @endcode is reserved and MUST NOT be used in this case. All custom
* identifiers SHOULD be stable across different versions of an implementation.
*/
static constexpr const char *kTelemetrySdkName = "telemetry.sdk.name";
/**
* The version string of the telemetry SDK.
*/
static constexpr const char *kTelemetrySdkVersion = "telemetry.sdk.version";
namespace TelemetrySdkLanguageValues
{
/**
* none
*/
static constexpr const char *kCpp = "cpp";
/**
* none
*/
static constexpr const char *kDotnet = "dotnet";
/**
* none
*/
static constexpr const char *kErlang = "erlang";
/**
* none
*/
static constexpr const char *kGo = "go";
/**
* none
*/
static constexpr const char *kJava = "java";
/**
* none
*/
static constexpr const char *kNodejs = "nodejs";
/**
* none
*/
static constexpr const char *kPhp = "php";
/**
* none
*/
static constexpr const char *kPython = "python";
/**
* none
*/
static constexpr const char *kRuby = "ruby";
/**
* none
*/
static constexpr const char *kRust = "rust";
/**
* none
*/
static constexpr const char *kSwift = "swift";
/**
* none
*/
static constexpr const char *kWebjs = "webjs";
} // namespace TelemetrySdkLanguageValues
} // namespace telemetry
} // namespace semconv
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,22 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
// IWYU pragma: private, include "opentelemetry/nostd/shared_ptr.h"
#include <memory> // IWYU pragma: export
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
// Standard Type aliases in nostd namespace
namespace nostd
{
// nostd::shared_ptr<T...>
template <class... _Types>
using shared_ptr = std::shared_ptr<_Types...>;
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,71 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
// IWYU pragma: private, include "opentelemetry/nostd/span.h"
#include "opentelemetry/version.h"
// Standard library implementation requires at least C++17 compiler.
// Older C++14 compilers may provide support for __has_include as a
// conforming extension.
#if defined __has_include
# if __has_include(<version>) // Check for __cpp_{feature}
# include <version>
# if defined(__cpp_lib_span) && __cplusplus > 201703L
# define OPENTELEMETRY_HAVE_SPAN
# endif
# endif
# if !defined(OPENTELEMETRY_HAVE_SPAN)
# // Check for Visual Studio span
# if defined(_MSVC_LANG) && _HAS_CXX20
# define OPENTELEMETRY_HAVE_SPAN
# endif
# // Check for other compiler span implementation
# if !defined(_MSVC_LANG) && __has_include(<span>) && __cplusplus > 201703L
// This works as long as compiler standard is set to C++20
# define OPENTELEMETRY_HAVE_SPAN
# endif
# endif
# if !__has_include(<gsl/gsl>)
# undef HAVE_GSL
# endif
#endif
#if !defined(OPENTELEMETRY_HAVE_SPAN)
# if defined(HAVE_GSL)
# include <type_traits>
// Guidelines Support Library provides an implementation of std::span
# include <gsl/gsl>
OPENTELEMETRY_BEGIN_NAMESPACE
namespace nostd
{
using gsl::dynamic_extent;
template <class ElementType, std::size_t Extent = gsl::dynamic_extent>
using span = gsl::span<ElementType, Extent>;
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE
# define OPENTELEMETRY_HAVE_SPAN
# else
// No `gsl::span`, no `std::span`, fallback to `nostd::span`
# endif
#else // OPENTELEMETRY_HAVE_SPAN
// Using std::span (https://wg21.link/P0122R7) from Standard Library available in C++20 :
// - GCC libstdc++ 10+
// - Clang libc++ 7
// - MSVC Standard Library 19.26*
// - Apple Clang 10.0.0*
# include <limits>
# include <span>
OPENTELEMETRY_BEGIN_NAMESPACE
namespace nostd
{
constexpr std::size_t dynamic_extent = (std::numeric_limits<std::size_t>::max)();
template <class ElementType, std::size_t Extent = nostd::dynamic_extent>
using span = std::span<ElementType, Extent>;
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE
#endif // if OPENTELEMETRY_HAVE_SPAN

View File

@@ -1,21 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
// IWYU pragma: private, include "opentelemetry/nostd/string_view.h"
#include <string_view>
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
// Standard Type aliases in nostd namespace
namespace nostd
{
// nostd::string_view
using string_view = std::string_view;
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,22 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
// IWYU pragma: private, include "opentelemetry/nostd/type_traits.h"
#include <type_traits>
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
// Standard Type aliases in nostd namespace
namespace nostd
{
// nostd::enable_if_t<...>
template <bool B, class T = void>
using enable_if_t = typename std::enable_if<B, T>::type;
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,22 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
// IWYU pragma: private, include "opentelemetry/nostd/unique_ptr.h"
#include <memory> // IWYU pragma: export
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
// Standard Type aliases in nostd namespace
namespace nostd
{
// nostd::unique_ptr<T...>
template <class... _Types>
using unique_ptr = std::unique_ptr<_Types...>;
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,71 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
// IWYU pragma: private, include "opentelemetry/nostd/utility.h"
#include <cstddef>
#include <utility>
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
// Standard Type aliases in nostd namespace
namespace nostd
{
//
// Backport of std::data
//
// See https://en.cppreference.com/w/cpp/iterator/data
//
template <class C>
auto data(C &c) noexcept(noexcept(c.data())) -> decltype(c.data())
{
return c.data();
}
template <class C>
auto data(const C &c) noexcept(noexcept(c.data())) -> decltype(c.data())
{
return c.data();
}
template <class T, std::size_t N>
T *data(T (&array)[N]) noexcept
{
return array;
}
template <class E>
const E *data(std::initializer_list<E> list) noexcept
{
return list.begin();
}
//
// Backport of std::size
//
// See https://en.cppreference.com/w/cpp/iterator/size
//
template <class C>
auto size(const C &c) noexcept(noexcept(c.size())) -> decltype(c.size())
{
return c.size();
}
template <class T, std::size_t N>
std::size_t size(T (& /* array */)[N]) noexcept
{
return N;
}
template <std::size_t N>
using make_index_sequence = std::make_index_sequence<N>;
template <std::size_t... Ints>
using index_sequence = std::index_sequence<Ints...>;
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,234 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
// IWYU pragma: private, include "opentelemetry/nostd/variant.h"
#include "opentelemetry/version.h"
#include <cstddef>
#include <memory>
#include <utility>
#include <variant>
OPENTELEMETRY_BEGIN_NAMESPACE
// Standard Type aliases in nostd namespace
namespace nostd
{
using std::get_if;
using std::monostate;
using std::variant_alternative_t;
// nostd::variant<...>
template <class... _Types>
using variant = std::variant<_Types...>;
template <class... _Types>
using variant_size = std::variant_size<_Types...>;
using monostate = std::monostate;
#if defined(__APPLE__) && defined(_LIBCPP_USE_AVAILABILITY_APPLE)
// Apple Platforms provide std::bad_variant_access only in newer versions of OS.
// To keep API compatible with any version of OS - we are providing our own
// implementation of nostd::bad_variant_access exception.
# if __EXCEPTIONS
// nostd::bad_variant_access
class bad_variant_access : public std::exception
{
public:
virtual const char *what() const noexcept override { return "bad_variant_access"; }
};
[[noreturn]] inline void throw_bad_variant_access()
{
throw bad_variant_access{};
}
# endif
# if __EXCEPTIONS
# define THROW_BAD_VARIANT_ACCESS throw_bad_variant_access()
# else
# define THROW_BAD_VARIANT_ACCESS std::terminate()
# endif
//
// nostd::get<...> for Apple Clang
//
template <typename T, class... Types>
constexpr auto get_type = [](auto &&t) constexpr -> decltype(auto) {
auto v = t;
auto result = std::get_if<T>(&v); // TODO: optimize with std::forward(t) if t is not rvalue
if (result)
{
return *result;
}
THROW_BAD_VARIANT_ACCESS;
return *result;
};
template <std::size_t I, class... Types>
constexpr auto get_index = [](auto &&t) constexpr -> decltype(auto) {
auto v = t;
auto result = std::get_if<I>(&v); // TODO: optimize with std::forward(t) if t is not rvalue
if (result)
{
return *result;
}
THROW_BAD_VARIANT_ACCESS;
return *result;
};
template <std::size_t I, class... Types>
constexpr std::variant_alternative_t<I, std::variant<Types...>> &get(std::variant<Types...> &v)
{
return get_index<I, Types...>(v);
};
template <std::size_t I, class... Types>
constexpr std::variant_alternative_t<I, std::variant<Types...>> &&get(std::variant<Types...> &&v)
{
return get_index<I, Types...>(std::forward<decltype(v)>(v));
};
template <std::size_t I, class... Types>
constexpr const std::variant_alternative_t<I, std::variant<Types...>> &get(
const std::variant<Types...> &v)
{
return get_index<I, Types...>(v);
};
template <std::size_t I, class... Types>
constexpr const std::variant_alternative_t<I, std::variant<Types...>> &&get(
const std::variant<Types...> &&v)
{
return get_index<I, Types...>(std::forward<decltype(v)>(v));
};
template <class T, class... Types>
constexpr T &get(std::variant<Types...> &v)
{
return get_type<T, Types...>(v);
};
template <class T, class... Types>
constexpr T /*&&*/ get(std::variant<Types...> &&v)
{
return get_type<T, Types...>(v);
};
template <class T, class... Types>
constexpr const T &get(const std::variant<Types...> &v)
{
return get_type<T, Types...>(v);
};
template <class T, class... Types>
constexpr const T &&get(const std::variant<Types...> &&v)
{
return get_type<T, Types...>(std::forward<decltype(v)>(v));
};
template <class _Callable, class... _Variants>
constexpr auto visit(_Callable &&_Obj, _Variants &&..._Args)
{
// Ref:
// https://stackoverflow.com/questions/52310835/xcode-10-call-to-unavailable-function-stdvisit
return std::__variant_detail::__visitation::__variant::__visit_value(_Obj, _Args...);
};
#else
using std::bad_variant_access;
template <std::size_t I, class... Types>
constexpr std::variant_alternative_t<I, std::variant<Types...>> &get(std::variant<Types...> &v)
{
return std::get<I, Types...>(v);
}
template <std::size_t I, class... Types>
constexpr std::variant_alternative_t<I, std::variant<Types...>> &&get(std::variant<Types...> &&v)
{
return std::get<I, Types...>(std::forward<decltype(v)>(v));
}
template <std::size_t I, class... Types>
constexpr const std::variant_alternative_t<I, std::variant<Types...>> &get(
const std::variant<Types...> &v)
{
return std::get<I, Types...>(v);
}
template <std::size_t I, class... Types>
constexpr const std::variant_alternative_t<I, std::variant<Types...>> &&get(
const std::variant<Types...> &&v)
{
return std::get<I, Types...>(std::forward<decltype(v)>(v));
}
template <class T, class... Types>
constexpr T &get(std::variant<Types...> &v)
{
return std::get<T, Types...>(v);
}
template <class T, class... Types>
constexpr T &&get(std::variant<Types...> &&v)
{
return std::get<T, Types...>(std::forward<decltype(v)>(v));
}
template <class T, class... Types>
constexpr const T &get(const std::variant<Types...> &v)
{
return std::get<T, Types...>(v);
}
template <class T, class... Types>
constexpr const T &&get(const std::variant<Types...> &&v)
{
return std::get<T, Types...>(std::forward<decltype(v)>(v));
}
template <class _Callable, class... _Variants>
constexpr auto visit(_Callable &&_Obj, _Variants &&..._Args)
{
return std::visit<_Callable, _Variants...>(static_cast<_Callable &&>(_Obj),
static_cast<_Variants &&>(_Args)...);
}
#endif
/*
# if _HAS_CXX20
template <class _Ret, class _Callable, class... _Variants>
constexpr _Ret visit(_Callable &&_Obj, _Variants &&... _Args)
{
return std::visit<_Ret, _Callable, _Variants...>(
static_cast<_Callable &&>(_Obj),
static_cast<_Variants &&>(_Args)...);
};
# endif
*/
// nostd::holds_alternative
template <std::size_t I, typename... Ts>
inline constexpr bool holds_alternative(const variant<Ts...> &v) noexcept
{
return v.index() == I;
}
template <typename T, template<typename...> typename U, typename... Ts>
inline constexpr bool holds_alternative(const U<Ts...> &v) noexcept
{
// Clang 18.1.7 on Ubuntu 24.04 does not disambiguate between this
// and std::holds_alternative if argument type is std::variant<Ts...>
static_assert(std::is_same_v<U<Ts...>, std::variant<Ts...>>,
"Unsupported argument type");
return std::holds_alternative<T, Ts...>(v);
}
} // namespace nostd
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,43 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/context/context.h"
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/trace/default_span.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
// Get Span from explicit context
inline nostd::shared_ptr<Span> GetSpan(const context::Context &context) noexcept
{
context::ContextValue span = context.GetValue(kSpanKey);
if (nostd::holds_alternative<nostd::shared_ptr<Span>>(span))
{
return nostd::get<nostd::shared_ptr<Span>>(span);
}
return nostd::shared_ptr<Span>(new DefaultSpan(SpanContext::GetInvalid()));
}
inline bool IsRootSpan(const context::Context &context) noexcept
{
context::ContextValue is_root_span = context.GetValue(kIsRootSpanKey);
if (nostd::holds_alternative<bool>(is_root_span))
{
return nostd::get<bool>(is_root_span);
}
return false;
}
// Set Span into explicit context
inline context::Context SetSpan(context::Context &context, nostd::shared_ptr<Span> span) noexcept
{
return context.SetValue(kSpanKey, span);
}
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,77 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/common/attribute_value.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/trace/span.h"
#include "opentelemetry/trace/span_context.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
/**
* DefaultSpan provides a non-operational Span that propagates
* the tracer context by wrapping it inside the Span object.
*/
class DefaultSpan : public Span
{
public:
// Returns an invalid span.
static DefaultSpan GetInvalid() { return DefaultSpan(SpanContext::GetInvalid()); }
trace::SpanContext GetContext() const noexcept override { return span_context_; }
bool IsRecording() const noexcept override { return false; }
void SetAttribute(nostd::string_view /* key */,
const common::AttributeValue & /* value */) noexcept override
{}
void AddEvent(nostd::string_view /* name */) noexcept override {}
void AddEvent(nostd::string_view /* name */,
common::SystemTimestamp /* timestamp */) noexcept override
{}
void AddEvent(nostd::string_view /* name */,
const common::KeyValueIterable & /* attributes */) noexcept override
{}
void AddEvent(nostd::string_view /* name */,
common::SystemTimestamp /* timestamp */,
const common::KeyValueIterable & /* attributes */) noexcept override
{}
#if OPENTELEMETRY_ABI_VERSION_NO >= 2
void AddLink(const SpanContext & /* target */,
const common::KeyValueIterable & /* attrs */) noexcept override
{}
void AddLinks(const SpanContextKeyValueIterable & /* links */) noexcept override {}
#endif
void SetStatus(StatusCode /* status */, nostd::string_view /* description */) noexcept override {}
void UpdateName(nostd::string_view /* name */) noexcept override {}
void End(const EndSpanOptions & /* options */) noexcept override {}
nostd::string_view ToString() const noexcept { return "DefaultSpan"; }
DefaultSpan(SpanContext span_context) noexcept : span_context_(span_context) {}
// movable and copiable
DefaultSpan(DefaultSpan &&spn) noexcept : Span(), span_context_(spn.GetContext()) {}
DefaultSpan(const DefaultSpan &spn) noexcept : Span(), span_context_(spn.GetContext()) {}
private:
SpanContext span_context_;
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,152 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
// Please refer to provider.h for documentation on how to obtain a Tracer object.
//
// This file is part of the internal implementation of OpenTelemetry. Nothing in this file should be
// used directly. Please refer to span.h and tracer.h for documentation on these interfaces.
#include <stdint.h>
#include <utility>
#include "opentelemetry/common/attribute_value.h"
#include "opentelemetry/common/key_value_iterable.h"
#include "opentelemetry/common/timestamp.h"
#include "opentelemetry/context/context_value.h"
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/nostd/unique_ptr.h"
#include "opentelemetry/trace/span.h"
#include "opentelemetry/trace/span_context.h"
#include "opentelemetry/trace/span_context_kv_iterable.h"
#include "opentelemetry/trace/span_metadata.h"
#include "opentelemetry/trace/span_startoptions.h"
#include "opentelemetry/trace/tracer.h"
#include "opentelemetry/trace/tracer_provider.h"
#include "opentelemetry/version.h"
namespace trace_api = opentelemetry::trace;
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
/**
* No-op implementation of Span. This class should not be used directly.
*/
class OPENTELEMETRY_EXPORT NoopSpan final : public Span
{
public:
explicit NoopSpan(const std::shared_ptr<Tracer> &tracer) noexcept
: tracer_{tracer}, span_context_{new SpanContext(false, false)}
{}
explicit NoopSpan(const std::shared_ptr<Tracer> &tracer,
nostd::unique_ptr<SpanContext> span_context) noexcept
: tracer_{tracer}, span_context_{std::move(span_context)}
{}
void SetAttribute(nostd::string_view /*key*/,
const common::AttributeValue & /*value*/) noexcept override
{}
void AddEvent(nostd::string_view /*name*/) noexcept override {}
void AddEvent(nostd::string_view /*name*/,
common::SystemTimestamp /*timestamp*/) noexcept override
{}
void AddEvent(nostd::string_view /* name */,
const common::KeyValueIterable & /* attributes */) noexcept override
{}
void AddEvent(nostd::string_view /*name*/,
common::SystemTimestamp /*timestamp*/,
const common::KeyValueIterable & /*attributes*/) noexcept override
{}
#if OPENTELEMETRY_ABI_VERSION_NO >= 2
void AddLink(const SpanContext & /* target */,
const common::KeyValueIterable & /* attrs */) noexcept override
{}
void AddLinks(const SpanContextKeyValueIterable & /* links */) noexcept override {}
#endif
void SetStatus(StatusCode /*code*/, nostd::string_view /*description*/) noexcept override {}
void UpdateName(nostd::string_view /*name*/) noexcept override {}
void End(const EndSpanOptions & /*options*/) noexcept override {}
bool IsRecording() const noexcept override { return false; }
SpanContext GetContext() const noexcept override { return *span_context_.get(); }
private:
std::shared_ptr<Tracer> tracer_;
nostd::unique_ptr<SpanContext> span_context_;
};
/**
* No-op implementation of Tracer.
*/
class OPENTELEMETRY_EXPORT NoopTracer final : public Tracer,
public std::enable_shared_from_this<NoopTracer>
{
public:
// Tracer
nostd::shared_ptr<Span> StartSpan(nostd::string_view /*name*/,
const common::KeyValueIterable & /*attributes*/,
const SpanContextKeyValueIterable & /*links*/,
const StartSpanOptions & /*options*/) noexcept override
{
// Don't allocate a no-op span for every StartSpan call, but use a static
// singleton for this case.
static nostd::shared_ptr<trace::Span> noop_span(new trace::NoopSpan{this->shared_from_this()});
return noop_span;
}
#if OPENTELEMETRY_ABI_VERSION_NO == 1
void ForceFlushWithMicroseconds(uint64_t /*timeout*/) noexcept override {}
void CloseWithMicroseconds(uint64_t /*timeout*/) noexcept override {}
#endif /* OPENTELEMETRY_ABI_VERSION_NO */
};
/**
* No-op implementation of a TracerProvider.
*/
class OPENTELEMETRY_EXPORT NoopTracerProvider final : public trace::TracerProvider
{
public:
NoopTracerProvider() noexcept
: tracer_{nostd::shared_ptr<trace::NoopTracer>(new trace::NoopTracer)}
{}
#if OPENTELEMETRY_ABI_VERSION_NO >= 2
nostd::shared_ptr<trace::Tracer> GetTracer(
nostd::string_view /* name */,
nostd::string_view /* version */,
nostd::string_view /* schema_url */,
const common::KeyValueIterable * /* attributes */) noexcept override
{
return tracer_;
}
#else
nostd::shared_ptr<trace::Tracer> GetTracer(nostd::string_view /* name */,
nostd::string_view /* version */,
nostd::string_view /* schema_url */) noexcept override
{
return tracer_;
}
#endif
private:
nostd::shared_ptr<trace::Tracer> tracer_;
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,60 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <mutex>
#include "opentelemetry/common/spin_lock_mutex.h"
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/trace/noop.h"
#include "opentelemetry/trace/tracer_provider.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
/**
* Stores the singleton global TracerProvider.
*/
class OPENTELEMETRY_EXPORT Provider
{
public:
/**
* Returns the singleton TracerProvider.
*
* By default, a no-op TracerProvider is returned. This will never return a
* nullptr TracerProvider.
*/
static nostd::shared_ptr<TracerProvider> GetTracerProvider() noexcept
{
std::lock_guard<common::SpinLockMutex> guard(GetLock());
return nostd::shared_ptr<TracerProvider>(GetProvider());
}
/**
* Changes the singleton TracerProvider.
*/
static void SetTracerProvider(nostd::shared_ptr<TracerProvider> tp) noexcept
{
std::lock_guard<common::SpinLockMutex> guard(GetLock());
GetProvider() = tp;
}
private:
OPENTELEMETRY_API_SINGLETON static nostd::shared_ptr<TracerProvider> &GetProvider() noexcept
{
static nostd::shared_ptr<TracerProvider> provider(new NoopTracerProvider);
return provider;
}
OPENTELEMETRY_API_SINGLETON static common::SpinLockMutex &GetLock() noexcept
{
static common::SpinLockMutex lock;
return lock;
}
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,42 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/context/context.h"
#include "opentelemetry/context/runtime_context.h"
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/nostd/unique_ptr.h"
#include "opentelemetry/trace/span.h"
#include "opentelemetry/trace/span_metadata.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
/**
* Controls how long a span is active.
*
* On creation of the Scope object, the given span is set to the currently
* active span. On destruction, the given span is ended and the previously
* active span will be the currently active span again.
*/
class Scope final
{
public:
/**
* Initialize a new scope.
* @param span the given span will be set as the currently active span.
*/
Scope(const nostd::shared_ptr<Span> &span) noexcept
: token_(context::RuntimeContext::Attach(
context::RuntimeContext::GetCurrent().SetValue(kSpanKey, span)))
{}
private:
nostd::unique_ptr<context::Token> token_;
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,259 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <cstdint>
#include "opentelemetry/common/attribute_value.h"
#include "opentelemetry/common/key_value_iterable_view.h"
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/nostd/type_traits.h"
#include "opentelemetry/trace/span_context.h"
#include "opentelemetry/trace/span_context_kv_iterable.h"
#include "opentelemetry/trace/span_context_kv_iterable_view.h"
#include "opentelemetry/trace/span_metadata.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
class Tracer;
/**
* A Span represents a single operation within a Trace.
*
* Span attributes can be provided:
* - at span creation time, using Tracer::StartSpan(),
* - during the span lifetime, using Span::SetAttribute()
*
* Please note that head samplers,
* in the SDK (@ref opentelemetry::sdk::trace::Sampler),
* can only make sampling decisions based on data known
* at span creation time.
*
* When attributes are known early, adding attributes
* with @ref opentelemetry::trace::Tracer::StartSpan() is preferable.
*
* Attributes added or changed with Span::SetAttribute()
* can not change a sampler decision.
*
* Likewise, links can be provided:
* - at span creation time, using Tracer::StartSpan(),
* - during the span lifetime, using Span::AddLink() or Span::AddLinks().
*
* When links are known early, adding links
* with @ref opentelemetry::trace::Tracer::StartSpan() is preferable.
*
* Links added with Span::AddLink() or Span::AddLinks()
* can not change a sampler decision.
*/
class Span
{
public:
// Note that Spans should be created using the Tracer class. Please refer to
// tracer.h for documentation.
Span() = default;
// The Span destructor End()s the Span, if it hasn't been ended already.
virtual ~Span() = default;
// Not copiable or movable.
Span(const Span &) = delete;
Span(Span &&) = delete;
Span &operator=(const Span &) = delete;
Span &operator=(Span &&) = delete;
/**
* Sets an attribute on the Span (ABI).
*
* If the Span previously contained a mapping for the key,
* the old value is replaced.
*
* See comments about sampling in @ref opentelemetry::trace::Span
*/
virtual void SetAttribute(nostd::string_view key,
const common::AttributeValue &value) noexcept = 0;
// Adds an event to the Span.
virtual void AddEvent(nostd::string_view name) noexcept = 0;
// Adds an event to the Span, with a custom timestamp.
virtual void AddEvent(nostd::string_view name, common::SystemTimestamp timestamp) noexcept = 0;
// Adds an event to the Span, with a custom timestamp, and attributes.
virtual void AddEvent(nostd::string_view name,
common::SystemTimestamp timestamp,
const common::KeyValueIterable &attributes) noexcept = 0;
virtual void AddEvent(nostd::string_view name,
const common::KeyValueIterable &attributes) noexcept
{
this->AddEvent(name, std::chrono::system_clock::now(), attributes);
}
template <class T,
nostd::enable_if_t<common::detail::is_key_value_iterable<T>::value> * = nullptr>
void AddEvent(nostd::string_view name,
common::SystemTimestamp timestamp,
const T &attributes) noexcept
{
this->AddEvent(name, timestamp, common::KeyValueIterableView<T>{attributes});
}
template <class T,
nostd::enable_if_t<common::detail::is_key_value_iterable<T>::value> * = nullptr>
void AddEvent(nostd::string_view name, const T &attributes) noexcept
{
this->AddEvent(name, common::KeyValueIterableView<T>{attributes});
}
void AddEvent(nostd::string_view name,
common::SystemTimestamp timestamp,
std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>>
attributes) noexcept
{
this->AddEvent(name, timestamp,
nostd::span<const std::pair<nostd::string_view, common::AttributeValue>>{
attributes.begin(), attributes.end()});
}
void AddEvent(nostd::string_view name,
std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>>
attributes) noexcept
{
this->AddEvent(name, std::chrono::system_clock::now(),
nostd::span<const std::pair<nostd::string_view, common::AttributeValue>>{
attributes.begin(), attributes.end()});
}
#if OPENTELEMETRY_ABI_VERSION_NO >= 2
/**
* Add link (ABI).
*
* See comments about sampling in @ref opentelemetry::trace::Span
*
* @since ABI_VERSION 2
*/
virtual void AddLink(const SpanContext &target,
const common::KeyValueIterable &attrs) noexcept = 0;
/**
* Add links (ABI).
*
* See comments about sampling in @ref opentelemetry::trace::Span
*
* @since ABI_VERSION 2
*/
virtual void AddLinks(const SpanContextKeyValueIterable &links) noexcept = 0;
/**
* Add link (API helper).
*
* See comments about sampling in @ref opentelemetry::trace::Span
*
* @since ABI_VERSION 2
*/
template <class U,
nostd::enable_if_t<common::detail::is_key_value_iterable<U>::value> * = nullptr>
void AddLink(const SpanContext &target, const U &attrs)
{
common::KeyValueIterableView<U> view(attrs);
this->AddLink(target, view);
}
/**
* Add link (API helper).
*
* See comments about sampling in @ref opentelemetry::trace::Span
*
* @since ABI_VERSION 2
*/
void AddLink(const SpanContext &target,
std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>> attrs)
{
/* Build a container from std::initializer_list. */
nostd::span<const std::pair<nostd::string_view, common::AttributeValue>> container{
attrs.begin(), attrs.end()};
/* Build a view on the container. */
common::KeyValueIterableView<
nostd::span<const std::pair<nostd::string_view, common::AttributeValue>>>
view(container);
return this->AddLink(target, view);
}
/**
* Add links (API helper).
*
* See comments about sampling in @ref opentelemetry::trace::Span
*
* @since ABI_VERSION 2
*/
template <class U, nostd::enable_if_t<detail::is_span_context_kv_iterable<U>::value> * = nullptr>
void AddLinks(const U &links)
{
SpanContextKeyValueIterableView<U> view(links);
this->AddLinks(view);
}
/**
* Add links (API helper).
*
* See comments about sampling in @ref opentelemetry::trace::Span
*
* @since ABI_VERSION 2
*/
void AddLinks(
std::initializer_list<
std::pair<SpanContext,
std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>>>>
links)
{
/* Build a container from std::initializer_list. */
nostd::span<const std::pair<
SpanContext, std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>>>>
container{links.begin(), links.end()};
/* Build a view on the container. */
SpanContextKeyValueIterableView<nostd::span<const std::pair<
SpanContext, std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>>>>>
view(container);
return this->AddLinks(view);
}
#endif /* OPENTELEMETRY_ABI_VERSION_NO */
// Sets the status of the span. The default status is Unset. Only the value of
// the last call will be
// recorded, and implementations are free to ignore previous calls.
virtual void SetStatus(StatusCode code, nostd::string_view description = "") noexcept = 0;
// Updates the name of the Span. If used, this will override the name provided
// during creation.
virtual void UpdateName(nostd::string_view name) noexcept = 0;
/**
* Mark the end of the Span.
* Only the timing of the first End call for a given Span will be recorded,
* and implementations are free to ignore all further calls.
* @param options can be used to manually define span properties like the end
* timestamp
*/
virtual void End(const trace::EndSpanOptions &options = {}) noexcept = 0;
virtual trace::SpanContext GetContext() const noexcept = 0;
// Returns true if this Span is recording tracing events (e.g. SetAttribute,
// AddEvent).
virtual bool IsRecording() const noexcept = 0;
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,96 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <stdint.h>
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/trace/span_id.h"
#include "opentelemetry/trace/trace_flags.h"
#include "opentelemetry/trace/trace_id.h"
#include "opentelemetry/trace/trace_state.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
/* SpanContext contains the state that must propagate to child Spans and across
* process boundaries. It contains TraceId and SpanId, TraceFlags, TraceState
* and whether it was propagated from a remote parent.
*/
class SpanContext final
{
public:
/* A temporary constructor for an invalid SpanContext.
* Trace id and span id are set to invalid (all zeros).
*
* @param sampled_flag a required parameter specifying if child spans should be
* sampled
* @param is_remote true if this context was propagated from a remote parent.
*/
SpanContext(bool sampled_flag, bool is_remote) noexcept
: trace_id_(),
span_id_(),
trace_flags_(trace::TraceFlags(static_cast<uint8_t>(sampled_flag))),
is_remote_(is_remote),
trace_state_(TraceState::GetDefault())
{}
SpanContext(TraceId trace_id,
SpanId span_id,
TraceFlags trace_flags,
bool is_remote,
nostd::shared_ptr<TraceState> trace_state = TraceState::GetDefault()) noexcept
: trace_id_(trace_id),
span_id_(span_id),
trace_flags_(trace_flags),
is_remote_(is_remote),
trace_state_(trace_state)
{}
SpanContext(const SpanContext &ctx) = default;
// @returns whether this context is valid
bool IsValid() const noexcept { return trace_id_.IsValid() && span_id_.IsValid(); }
// @returns the trace_flags associated with this span_context
const trace::TraceFlags &trace_flags() const noexcept { return trace_flags_; }
// @returns the trace_id associated with this span_context
const trace::TraceId &trace_id() const noexcept { return trace_id_; }
// @returns the span_id associated with this span_context
const trace::SpanId &span_id() const noexcept { return span_id_; }
// @returns the trace_state associated with this span_context
const nostd::shared_ptr<trace::TraceState> trace_state() const noexcept { return trace_state_; }
/*
* @param that SpanContext for comparing.
* @return true if `that` equals the current SpanContext.
* N.B. trace_state is ignored for the comparison.
*/
bool operator==(const SpanContext &that) const noexcept
{
return trace_id() == that.trace_id() && span_id() == that.span_id() &&
trace_flags() == that.trace_flags();
}
SpanContext &operator=(const SpanContext &ctx) = default;
bool IsRemote() const noexcept { return is_remote_; }
static SpanContext GetInvalid() noexcept { return SpanContext(false, false); }
bool IsSampled() const noexcept { return trace_flags_.IsSampled(); }
private:
trace::TraceId trace_id_;
trace::SpanId span_id_;
trace::TraceFlags trace_flags_;
bool is_remote_;
nostd::shared_ptr<trace::TraceState> trace_state_;
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,54 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/common/attribute_value.h"
#include "opentelemetry/common/key_value_iterable_view.h"
#include "opentelemetry/nostd/function_ref.h"
#include "opentelemetry/trace/span_context.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
/**
* Supports internal iteration over a collection of SpanContext/key-value pairs.
*/
class SpanContextKeyValueIterable
{
public:
virtual ~SpanContextKeyValueIterable() = default;
/**
* Iterate over SpanContext/key-value pairs
* @param callback a callback to invoke for each key-value for each SpanContext.
* If the callback returns false, the iteration is aborted.
* @return true if every SpanContext/key-value pair was iterated over
*/
virtual bool ForEachKeyValue(
nostd::function_ref<bool(SpanContext, const common::KeyValueIterable &)> callback)
const noexcept = 0;
/**
* @return the number of key-value pairs
*/
virtual size_t size() const noexcept = 0;
};
/**
* @brief Null Span context that does not carry any information.
*/
class NullSpanContext : public SpanContextKeyValueIterable
{
public:
bool ForEachKeyValue(nostd::function_ref<bool(SpanContext, const common::KeyValueIterable &)>
/* callback */) const noexcept override
{
return true;
}
size_t size() const noexcept override { return 0; }
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,119 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <iterator>
#include <type_traits>
#include <utility>
#include "opentelemetry/common/key_value_iterable_view.h"
#include "opentelemetry/nostd/function_ref.h"
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/nostd/utility.h"
#include "opentelemetry/trace/span_context.h"
#include "opentelemetry/trace/span_context_kv_iterable.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
// NOTE - code within `detail` namespace implements internal details, and not part
// of the public interface.
namespace detail
{
template <class T>
inline void take_span_context_kv(SpanContext, opentelemetry::common::KeyValueIterableView<T>)
{}
template <class T, nostd::enable_if_t<common::detail::is_key_value_iterable<T>::value> * = nullptr>
inline void take_span_context_kv(SpanContext, T &)
{}
inline void take_span_context_kv(
SpanContext,
std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>>)
{}
template <class T>
auto is_span_context_kv_iterable_impl(T iterable)
-> decltype(take_span_context_kv(std::begin(iterable)->first, std::begin(iterable)->second),
nostd::size(iterable),
std::true_type{});
std::false_type is_span_context_kv_iterable_impl(...);
template <class T>
struct is_span_context_kv_iterable
{
static const bool value =
decltype(detail::is_span_context_kv_iterable_impl(std::declval<T>()))::value;
};
} // namespace detail
template <class T>
class SpanContextKeyValueIterableView final : public SpanContextKeyValueIterable
{
static_assert(detail::is_span_context_kv_iterable<T>::value,
"Must be a context/key-value iterable");
public:
explicit SpanContextKeyValueIterableView(const T &links) noexcept : container_{&links} {}
bool ForEachKeyValue(nostd::function_ref<bool(SpanContext, const common::KeyValueIterable &)>
callback) const noexcept override
{
auto iter = std::begin(*container_);
auto last = std::end(*container_);
for (; iter != last; ++iter)
{
if (!this->do_callback(iter->first, iter->second, callback))
{
return false;
}
}
return true;
}
size_t size() const noexcept override { return nostd::size(*container_); }
private:
const T *container_;
bool do_callback(SpanContext span_context,
const common::KeyValueIterable &attributes,
nostd::function_ref<bool(SpanContext, const common::KeyValueIterable &)>
callback) const noexcept
{
if (!callback(span_context, attributes))
{
return false;
}
return true;
}
template <class U,
nostd::enable_if_t<common::detail::is_key_value_iterable<U>::value> * = nullptr>
bool do_callback(SpanContext span_context,
const U &attributes,
nostd::function_ref<bool(SpanContext, const common::KeyValueIterable &)>
callback) const noexcept
{
return do_callback(span_context, common::KeyValueIterableView<U>(attributes), callback);
}
bool do_callback(
SpanContext span_context,
std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>> attributes,
nostd::function_ref<bool(SpanContext, const common::KeyValueIterable &)> callback)
const noexcept
{
return do_callback(span_context,
nostd::span<const std::pair<nostd::string_view, common::AttributeValue>>{
attributes.begin(), attributes.end()},
callback);
}
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,67 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <cstdint>
#include <cstring>
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
class SpanId final
{
public:
// The size in bytes of the SpanId.
static constexpr int kSize = 8;
// An invalid SpanId (all zeros).
SpanId() noexcept : rep_{0} {}
// Creates a SpanId with the given ID.
explicit SpanId(nostd::span<const uint8_t, kSize> id) noexcept { memcpy(rep_, id.data(), kSize); }
// Populates the buffer with the lowercase base16 representation of the ID.
void ToLowerBase16(nostd::span<char, 2 * kSize> buffer) const noexcept
{
constexpr char kHex[] = "0123456789abcdef";
for (int i = 0; i < kSize; ++i)
{
buffer[i * 2 + 0] = kHex[(rep_[i] >> 4) & 0xF];
buffer[i * 2 + 1] = kHex[(rep_[i] >> 0) & 0xF];
}
}
// Returns a nostd::span of the ID.
nostd::span<const uint8_t, kSize> Id() const noexcept
{
return nostd::span<const uint8_t, kSize>(rep_);
}
bool operator==(const SpanId &that) const noexcept { return memcmp(rep_, that.rep_, kSize) == 0; }
bool operator!=(const SpanId &that) const noexcept { return !(*this == that); }
// Returns false if the SpanId is all zeros.
bool IsValid() const noexcept
{
static constexpr uint8_t kEmptyRep[kSize] = {0};
return memcmp(rep_, kEmptyRep, kSize) != 0;
}
// Copies the opaque SpanId data to dest.
void CopyBytesTo(nostd::span<uint8_t, kSize> dest) const noexcept
{
memcpy(dest.data(), rep_, kSize);
}
private:
uint8_t rep_[kSize];
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,45 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/common/timestamp.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
enum class SpanKind
{
kInternal,
kServer,
kClient,
kProducer,
kConsumer,
};
// The key identifies the active span in the current context.
constexpr char kSpanKey[] = "active_span";
constexpr char kIsRootSpanKey[] = "is_root_span";
// StatusCode - Represents the canonical set of status codes of a finished Span.
enum class StatusCode
{
kUnset, // default status
kOk, // Operation has completed successfully.
kError // The operation contains an error
};
/**
* EndSpanOptions provides options to set properties of a Span when it is
* ended.
*/
struct EndSpanOptions
{
// Optionally sets the end time of a Span.
common::SteadyTimestamp end_steady_time;
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,71 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/common/timestamp.h"
#include "opentelemetry/context/context.h"
#include "opentelemetry/nostd/variant.h"
#include "opentelemetry/trace/span_context.h"
#include "opentelemetry/trace/span_metadata.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
/**
* StartSpanOptions provides options to set properties of a Span at the time of
* its creation
*/
struct StartSpanOptions
{
// Optionally sets the start time of a Span.
//
// If the start time of a Span is set, timestamps from both the system clock
// and steady clock must be provided.
//
// Timestamps from the steady clock can be used to most accurately measure a
// Span's duration, while timestamps from the system clock can be used to most
// accurately place a Span's
// time point relative to other Spans collected across a distributed system.
common::SystemTimestamp start_system_time;
common::SteadyTimestamp start_steady_time;
// Explicitly set the parent of a Span.
//
// The `parent` field is designed to establish parent-child relationships
// in tracing spans. It can be set to either a `SpanContext` or a
// `context::Context` object.
//
// - When set to valid `SpanContext`, it directly assigns a specific Span as the parent
// of the newly created Span.
//
// - Alternatively, setting the `parent` field to a `context::Context` allows for
// more nuanced parent identification:
// 1. If the `Context` contains a Span object, this Span is treated as the parent.
// 2. If the `Context` contains the boolean flag `is_root_span` set to `true`,
// it indicates that the new Span should be treated as a root Span, i.e., it
// does not have a parent Span.
// Example Usage:
// ```cpp
// trace_api::StartSpanOptions options;
// opentelemetry::context::Context root;
// root = root.SetValue(kIsRootSpanKey, true);
// options.parent = root;
// auto root_span = tracer->StartSpan("span root", options);
// ```
//
// - If the `parent` field is not set, the newly created Span will inherit the
// parent of the currently active Span (if any) in the current context.
//
nostd::variant<SpanContext, context::Context> parent = SpanContext::GetInvalid();
// TODO:
// SpanContext remote_parent;
// Links
SpanKind kind = SpanKind::kInternal;
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,66 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <cstdint>
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
// TraceFlags represents options for a Trace. These options are propagated to all child Spans
// and determine features such as whether a Span should be traced. TraceFlags
// are implemented as a bitmask.
class TraceFlags final
{
public:
static constexpr uint8_t kIsSampled = 1;
static constexpr uint8_t kIsRandom = 2;
/**
* Valid flags in W3C Trace Context version 1.
* See https://www.w3.org/TR/trace-context-1/#trace-flags
*/
static constexpr uint8_t kAllW3CTraceContext1Flags = kIsSampled;
/**
* Valid flags in W3C Trace Context version 2.
* See https://www.w3.org/TR/trace-context-1/#trace-flags
*/
static constexpr uint8_t kAllW3CTraceContext2Flags = kIsSampled | kIsRandom;
TraceFlags() noexcept : rep_{0} {}
explicit TraceFlags(uint8_t flags) noexcept : rep_(flags) {}
bool IsSampled() const noexcept { return rep_ & kIsSampled; }
bool IsRandom() const noexcept { return rep_ & kIsRandom; }
// Populates the buffer with the lowercase base16 representation of the flags.
void ToLowerBase16(nostd::span<char, 2> buffer) const noexcept
{
constexpr char kHex[] = "0123456789ABCDEF";
buffer[0] = kHex[(rep_ >> 4) & 0xF];
buffer[1] = kHex[(rep_ >> 0) & 0xF];
}
uint8_t flags() const noexcept { return rep_; }
bool operator==(const TraceFlags &that) const noexcept { return rep_ == that.rep_; }
bool operator!=(const TraceFlags &that) const noexcept { return !(*this == that); }
// Copies the TraceFlags to dest.
void CopyBytesTo(nostd::span<uint8_t, 1> dest) const noexcept { dest[0] = rep_; }
private:
uint8_t rep_;
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,72 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <cstdint>
#include <cstring>
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
// TraceId represents an opaque 128-bit trace identifier. The trace identifier
// remains constant across the trace. A valid trace identifier is a 16-byte array with at
// least one non-zero byte.
class TraceId final
{
public:
// The size in bytes of the TraceId.
static constexpr int kSize = 16;
// An invalid TraceId (all zeros).
TraceId() noexcept : rep_{0} {}
// Creates a TraceId with the given ID.
explicit TraceId(nostd::span<const uint8_t, kSize> id) noexcept
{
memcpy(rep_, id.data(), kSize);
}
// Populates the buffer with the lowercase base16 representation of the ID.
void ToLowerBase16(nostd::span<char, 2 * kSize> buffer) const noexcept
{
constexpr char kHex[] = "0123456789abcdef";
for (int i = 0; i < kSize; ++i)
{
buffer[i * 2 + 0] = kHex[(rep_[i] >> 4) & 0xF];
buffer[i * 2 + 1] = kHex[(rep_[i] >> 0) & 0xF];
}
}
// Returns a nostd::span of the ID.
nostd::span<const uint8_t, kSize> Id() const noexcept
{
return nostd::span<const uint8_t, kSize>(rep_);
}
bool operator==(const TraceId &that) const noexcept
{
return memcmp(rep_, that.rep_, kSize) == 0;
}
bool operator!=(const TraceId &that) const noexcept { return !(*this == that); }
// Returns false if the TraceId is all zeros.
bool IsValid() const noexcept { return *this != TraceId(); }
// Copies the opaque TraceId data to dest.
void CopyBytesTo(nostd::span<uint8_t, kSize> dest) const noexcept
{
memcpy(dest.data(), rep_, kSize);
}
private:
uint8_t rep_[kSize];
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,323 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <ctype.h>
#include <cstddef>
#include <string>
#include <vector>
#include "opentelemetry/common/kv_properties.h"
#include "opentelemetry/nostd/function_ref.h"
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/nostd/unique_ptr.h"
#include "opentelemetry/version.h"
#if OPENTELEMETRY_HAVE_WORKING_REGEX
# include <regex>
#endif
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
/**
* TraceState carries tracing-system specific context in a list of key-value pairs. TraceState
* allows different vendors to propagate additional information and inter-operate with their legacy
* id formats.
*
* For more information, see the W3C Trace Context specification:
* https://www.w3.org/TR/trace-context
*/
class OPENTELEMETRY_EXPORT TraceState
{
public:
static constexpr int kKeyMaxSize = 256;
static constexpr int kValueMaxSize = 256;
static constexpr int kMaxKeyValuePairs = 32;
static constexpr auto kKeyValueSeparator = '=';
static constexpr auto kMembersSeparator = ',';
OPENTELEMETRY_API_SINGLETON static nostd::shared_ptr<TraceState> GetDefault()
{
static nostd::shared_ptr<TraceState> ts{new TraceState()};
return ts;
}
/**
* Returns shared_ptr to a newly created TraceState parsed from the header provided.
* @param header Encoding of the tracestate header defined by
* the W3C Trace Context specification https://www.w3.org/TR/trace-context/
* @return TraceState A new TraceState instance or DEFAULT
*/
static nostd::shared_ptr<TraceState> FromHeader(nostd::string_view header) noexcept
{
common::KeyValueStringTokenizer kv_str_tokenizer(header);
size_t cnt = kv_str_tokenizer.NumTokens(); // upper bound on number of kv pairs
if (cnt > kMaxKeyValuePairs)
{
// trace state should be discarded if count exceeds
return GetDefault();
}
nostd::shared_ptr<TraceState> ts(new TraceState(cnt));
bool kv_valid;
nostd::string_view key, value;
while (kv_str_tokenizer.next(kv_valid, key, value) && ts->kv_properties_->Size() < cnt)
{
if (kv_valid == false)
{
return GetDefault();
}
if (!IsValidKey(key) || !IsValidValue(value))
{
// invalid header. return empty TraceState
ts->kv_properties_.reset(new common::KeyValueProperties());
break;
}
ts->kv_properties_->AddEntry(key, value);
}
return ts;
}
/**
* Creates a w3c tracestate header from TraceState object
*/
std::string ToHeader() const noexcept
{
std::string header_s;
bool first = true;
kv_properties_->GetAllEntries(
[&header_s, &first](nostd::string_view key, nostd::string_view value) noexcept {
if (!first)
{
header_s.append(1, kMembersSeparator);
}
else
{
first = false;
}
header_s.append(std::string(key.data(), key.size()));
header_s.append(1, kKeyValueSeparator);
header_s.append(std::string(value.data(), value.size()));
return true;
});
return header_s;
}
/**
* Returns `value` associated with `key` passed as argument
* Returns empty string if key is invalid or not found
*/
bool Get(nostd::string_view key, std::string &value) const noexcept
{
if (!IsValidKey(key))
{
return false;
}
return kv_properties_->GetValue(key, value);
}
/**
* Returns shared_ptr of `new` TraceState object with following mutations applied to the existing
* instance: Update Key value: The updated value must be moved to beginning of List Add : The new
* key-value pair SHOULD be added to beginning of List
*
* If the provided key-value pair is invalid, or results in transtate that violates the
* tracecontext specification, empty TraceState instance will be returned.
*
* If the existing object has maximum list members, it's copy is returned.
*/
nostd::shared_ptr<TraceState> Set(const nostd::string_view &key,
const nostd::string_view &value) noexcept
{
auto curr_size = kv_properties_->Size();
if (!IsValidKey(key) || !IsValidValue(value))
{
// max size reached or invalid key/value. Returning empty TraceState
return TraceState::GetDefault();
}
auto allocate_size = curr_size;
if (curr_size < kMaxKeyValuePairs)
{
allocate_size += 1;
}
nostd::shared_ptr<TraceState> ts(new TraceState(allocate_size));
if (curr_size < kMaxKeyValuePairs)
{
// add new field first
ts->kv_properties_->AddEntry(key, value);
}
// add rest of the fields.
kv_properties_->GetAllEntries([&ts](nostd::string_view key, nostd::string_view value) {
ts->kv_properties_->AddEntry(key, value);
return true;
});
return ts;
}
/**
* Returns shared_ptr to a `new` TraceState object after removing the attribute with given key (
* if present )
* @returns empty TraceState object if key is invalid
* @returns copy of original TraceState object if key is not present (??)
*/
nostd::shared_ptr<TraceState> Delete(const nostd::string_view &key) noexcept
{
if (!IsValidKey(key))
{
return TraceState::GetDefault();
}
auto curr_size = kv_properties_->Size();
auto allocate_size = curr_size;
std::string unused;
if (kv_properties_->GetValue(key, unused))
{
allocate_size -= 1;
}
nostd::shared_ptr<TraceState> ts(new TraceState(allocate_size));
kv_properties_->GetAllEntries(
[&ts, &key](nostd::string_view e_key, nostd::string_view e_value) {
if (key != e_key)
ts->kv_properties_->AddEntry(e_key, e_value);
return true;
});
return ts;
}
// Returns true if there are no keys, false otherwise.
bool Empty() const noexcept { return kv_properties_->Size() == 0; }
// @return all key-values entris by repeatedly invoking the function reference passed as argument
// for each entry
bool GetAllEntries(
nostd::function_ref<bool(nostd::string_view, nostd::string_view)> callback) const noexcept
{
return kv_properties_->GetAllEntries(callback);
}
/** Returns whether key is a valid key. See https://www.w3.org/TR/trace-context/#key
* Identifiers MUST begin with a lowercase letter or a digit, and can only contain
* lowercase letters (a-z), digits (0-9), underscores (_), dashes (-), asterisks (*),
* and forward slashes (/).
* For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the vendor name.
*
*/
static bool IsValidKey(nostd::string_view key)
{
#if OPENTELEMETRY_HAVE_WORKING_REGEX
return IsValidKeyRegEx(key);
#else
return IsValidKeyNonRegEx(key);
#endif
}
/** Returns whether value is a valid value. See https://www.w3.org/TR/trace-context/#value
* The value is an opaque string containing up to 256 printable ASCII (RFC0020)
* characters ((i.e., the range 0x20 to 0x7E) except comma , and equal =)
*/
static bool IsValidValue(nostd::string_view value)
{
#if OPENTELEMETRY_HAVE_WORKING_REGEX
return IsValidValueRegEx(value);
#else
return IsValidValueNonRegEx(value);
#endif
}
private:
TraceState() : kv_properties_(new common::KeyValueProperties()) {}
TraceState(size_t size) : kv_properties_(new common::KeyValueProperties(size)) {}
static nostd::string_view TrimString(nostd::string_view str, size_t left, size_t right)
{
while (str[static_cast<std::size_t>(right)] == ' ' && left < right)
{
right--;
}
while (str[static_cast<std::size_t>(left)] == ' ' && left < right)
{
left++;
}
return str.substr(left, right - left + 1);
}
#if OPENTELEMETRY_HAVE_WORKING_REGEX
static bool IsValidKeyRegEx(nostd::string_view key)
{
static std::regex reg_key("^[a-z0-9][a-z0-9*_\\-/]{0,255}$");
static std::regex reg_key_multitenant(
"^[a-z0-9][a-z0-9*_\\-/]{0,240}(@)[a-z0-9][a-z0-9*_\\-/]{0,13}$");
std::string key_s(key.data(), key.size());
if (std::regex_match(key_s, reg_key) || std::regex_match(key_s, reg_key_multitenant))
{
return true;
}
return false;
}
static bool IsValidValueRegEx(nostd::string_view value)
{
// Hex 0x20 to 0x2B, 0x2D to 0x3C, 0x3E to 0x7E
static std::regex reg_value(
"^[\\x20-\\x2B\\x2D-\\x3C\\x3E-\\x7E]{0,255}[\\x21-\\x2B\\x2D-\\x3C\\x3E-\\x7E]$");
// Need to benchmark without regex, as a string object is created here.
return std::regex_match(std::string(value.data(), value.size()), reg_value);
}
#else
static bool IsValidKeyNonRegEx(nostd::string_view key)
{
if (key.empty() || key.size() > kKeyMaxSize || !IsLowerCaseAlphaOrDigit(key[0]))
{
return false;
}
int ats = 0;
for (const char c : key)
{
if (!IsLowerCaseAlphaOrDigit(c) && c != '_' && c != '-' && c != '@' && c != '*' && c != '/')
{
return false;
}
if ((c == '@') && (++ats > 1))
{
return false;
}
}
return true;
}
static bool IsValidValueNonRegEx(nostd::string_view value)
{
if (value.empty() || value.size() > kValueMaxSize)
{
return false;
}
for (const char c : value)
{
if (c < ' ' || c > '~' || c == ',' || c == '=')
{
return false;
}
}
return true;
}
#endif
static bool IsLowerCaseAlphaOrDigit(char c) { return isdigit(c) || islower(c); }
private:
// Store entries in a C-style array to avoid using std::array or std::vector.
nostd::unique_ptr<common::KeyValueProperties> kv_properties_;
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,202 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <chrono>
#include "opentelemetry/context/context.h"
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/trace/default_span.h"
#include "opentelemetry/trace/scope.h"
#include "opentelemetry/trace/span.h"
#include "opentelemetry/trace/span_context_kv_iterable_view.h"
#include "opentelemetry/trace/span_startoptions.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
/**
* Handles span creation and in-process context propagation.
*
* This class provides methods for manipulating the context, creating spans, and controlling spans'
* lifecycles.
*/
class Tracer
{
public:
virtual ~Tracer() = default;
/**
* Starts a span.
*
* Optionally sets attributes at Span creation from the given key/value pairs.
*
* Attributes will be processed in order, previous attributes with the same
* key will be overwritten.
*/
virtual nostd::shared_ptr<Span> StartSpan(nostd::string_view name,
const common::KeyValueIterable &attributes,
const SpanContextKeyValueIterable &links,
const StartSpanOptions &options = {}) noexcept = 0;
nostd::shared_ptr<Span> StartSpan(nostd::string_view name,
const StartSpanOptions &options = {}) noexcept
{
return this->StartSpan(name, {}, {}, options);
}
template <class T,
nostd::enable_if_t<common::detail::is_key_value_iterable<T>::value> * = nullptr>
nostd::shared_ptr<Span> StartSpan(nostd::string_view name,
const T &attributes,
const StartSpanOptions &options = {}) noexcept
{
return this->StartSpan(name, attributes, {}, options);
}
nostd::shared_ptr<Span> StartSpan(nostd::string_view name,
const common::KeyValueIterable &attributes,
const StartSpanOptions &options = {}) noexcept
{
return this->StartSpan(name, attributes, NullSpanContext(), options);
}
template <class T,
class U,
nostd::enable_if_t<common::detail::is_key_value_iterable<T>::value> * = nullptr,
nostd::enable_if_t<detail::is_span_context_kv_iterable<U>::value> * = nullptr>
nostd::shared_ptr<Span> StartSpan(nostd::string_view name,
const T &attributes,
const U &links,
const StartSpanOptions &options = {}) noexcept
{
return this->StartSpan(name, common::KeyValueIterableView<T>(attributes),
SpanContextKeyValueIterableView<U>(links), options);
}
nostd::shared_ptr<Span> StartSpan(
nostd::string_view name,
std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>> attributes,
const StartSpanOptions &options = {}) noexcept
{
return this->StartSpan(name, attributes, {}, options);
}
template <class T,
nostd::enable_if_t<common::detail::is_key_value_iterable<T>::value> * = nullptr>
nostd::shared_ptr<Span> StartSpan(
nostd::string_view name,
const T &attributes,
std::initializer_list<
std::pair<SpanContext,
std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>>>>
links,
const StartSpanOptions &options = {}) noexcept
{
return this->StartSpan(
name, attributes,
nostd::span<const std::pair<SpanContext, std::initializer_list<std::pair<
nostd::string_view, common::AttributeValue>>>>{
links.begin(), links.end()},
options);
}
template <class T,
nostd::enable_if_t<common::detail::is_key_value_iterable<T>::value> * = nullptr>
nostd::shared_ptr<Span> StartSpan(
nostd::string_view name,
std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>> attributes,
const T &links,
const StartSpanOptions &options = {}) noexcept
{
return this->StartSpan(name,
nostd::span<const std::pair<nostd::string_view, common::AttributeValue>>{
attributes.begin(), attributes.end()},
links, options);
}
nostd::shared_ptr<Span> StartSpan(
nostd::string_view name,
std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>> attributes,
std::initializer_list<
std::pair<SpanContext,
std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>>>>
links,
const StartSpanOptions &options = {}) noexcept
{
return this->StartSpan(
name,
nostd::span<const std::pair<nostd::string_view, common::AttributeValue>>{attributes.begin(),
attributes.end()},
nostd::span<const std::pair<SpanContext, std::initializer_list<std::pair<
nostd::string_view, common::AttributeValue>>>>{
links.begin(), links.end()},
options);
}
/**
* Set the active span. The span will remain active until the returned Scope
* object is destroyed.
* @param span the span that should be set as the new active span.
* @return a Scope that controls how long the span will be active.
*/
static Scope WithActiveSpan(nostd::shared_ptr<Span> &span) noexcept { return Scope{span}; }
/**
* Get the currently active span.
* @return the currently active span, or an invalid default span if no span
* is active.
*/
static nostd::shared_ptr<Span> GetCurrentSpan() noexcept
{
context::ContextValue active_span = context::RuntimeContext::GetValue(kSpanKey);
if (nostd::holds_alternative<nostd::shared_ptr<Span>>(active_span))
{
return nostd::get<nostd::shared_ptr<Span>>(active_span);
}
else
{
return nostd::shared_ptr<Span>(new DefaultSpan(SpanContext::GetInvalid()));
}
}
#if OPENTELEMETRY_ABI_VERSION_NO == 1
/*
* The following is removed from the API in ABI version 2.
* It belongs to the SDK.
*/
/**
* Force any buffered spans to flush.
* @param timeout to complete the flush
*/
template <class Rep, class Period>
void ForceFlush(std::chrono::duration<Rep, Period> timeout) noexcept
{
this->ForceFlushWithMicroseconds(static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::microseconds>(timeout).count()));
}
virtual void ForceFlushWithMicroseconds(uint64_t timeout) noexcept = 0;
/**
* ForceFlush any buffered spans and stop reporting spans.
* @param timeout to complete the flush
*/
template <class Rep, class Period>
void Close(std::chrono::duration<Rep, Period> timeout) noexcept
{
this->CloseWithMicroseconds(static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::microseconds>(timeout).count()));
}
virtual void CloseWithMicroseconds(uint64_t timeout) noexcept = 0;
#endif /* OPENTELEMETRY_ABI_VERSION_NO */
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,127 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/common/key_value_iterable.h"
#include "opentelemetry/common/key_value_iterable_view.h"
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
class Tracer;
/**
* Creates new Tracer instances.
*/
class OPENTELEMETRY_EXPORT TracerProvider
{
public:
virtual ~TracerProvider() = default;
#if OPENTELEMETRY_ABI_VERSION_NO >= 2
/**
* Gets or creates a named Tracer instance (ABI).
*
* @since ABI_VERSION 2
*
* @param[in] name Tracer instrumentation scope
* @param[in] version Instrumentation scope version
* @param[in] schema_url Instrumentation scope schema URL
* @param[in] attributes Instrumentation scope attributes (optional, may be nullptr)
*/
virtual nostd::shared_ptr<Tracer> GetTracer(
nostd::string_view name,
nostd::string_view version,
nostd::string_view schema_url,
const common::KeyValueIterable *attributes) noexcept = 0;
/**
* Gets or creates a named Tracer instance (API helper).
*
* @since ABI_VERSION 2
*
* @param[in] name Tracer instrumentation scope
* @param[in] version Instrumentation scope version, optional
* @param[in] schema_url Instrumentation scope schema URL, optional
*/
nostd::shared_ptr<Tracer> GetTracer(nostd::string_view name,
nostd::string_view version = "",
nostd::string_view schema_url = "")
{
return GetTracer(name, version, schema_url, nullptr);
}
/**
* Gets or creates a named Tracer instance (API helper).
*
* @since ABI_VERSION 2
*
* @param[in] name Tracer instrumentation scope
* @param[in] version Instrumentation scope version
* @param[in] schema_url Instrumentation scope schema URL
* @param[in] attributes Instrumentation scope attributes
*/
nostd::shared_ptr<Tracer> GetTracer(
nostd::string_view name,
nostd::string_view version,
nostd::string_view schema_url,
std::initializer_list<std::pair<nostd::string_view, common::AttributeValue>> attributes)
{
/* Build a container from std::initializer_list. */
nostd::span<const std::pair<nostd::string_view, common::AttributeValue>> attributes_span{
attributes.begin(), attributes.end()};
/* Build a view on the container. */
common::KeyValueIterableView<
nostd::span<const std::pair<nostd::string_view, common::AttributeValue>>>
iterable_attributes{attributes_span};
/* Add attributes using the view. */
return GetTracer(name, version, schema_url, &iterable_attributes);
}
/**
* Gets or creates a named Tracer instance (API helper).
*
* @since ABI_VERSION 2
*
* @param[in] name Tracer instrumentation scope
* @param[in] version Instrumentation scope version
* @param[in] schema_url Instrumentation scope schema URL
* @param[in] attributes Instrumentation scope attributes container
*/
template <class T,
nostd::enable_if_t<common::detail::is_key_value_iterable<T>::value> * = nullptr>
nostd::shared_ptr<Tracer> GetTracer(nostd::string_view name,
nostd::string_view version,
nostd::string_view schema_url,
const T &attributes)
{
/* Build a view on the container. */
common::KeyValueIterableView<T> iterable_attributes(attributes);
/* Add attributes using the view. */
return GetTracer(name, version, schema_url, &iterable_attributes);
}
#else
/**
* Gets or creates a named tracer instance.
*
* Optionally a version can be passed to create a named and versioned tracer
* instance.
*/
virtual nostd::shared_ptr<Tracer> GetTracer(nostd::string_view name,
nostd::string_view version = "",
nostd::string_view schema_url = "") noexcept = 0;
#endif
};
} // namespace trace
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,29 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/common/macros.h" // IWYU pragma: export
#include "opentelemetry/detail/preprocessor.h"
#ifndef OPENTELEMETRY_ABI_VERSION_NO
# define OPENTELEMETRY_ABI_VERSION_NO 1
#endif
#define OPENTELEMETRY_VERSION "1.18.0"
#define OPENTELEMETRY_VERSION_MAJOR 1
#define OPENTELEMETRY_VERSION_MINOR 18
#define OPENTELEMETRY_VERSION_PATCH 0
#define OPENTELEMETRY_ABI_VERSION OPENTELEMETRY_STRINGIFY(OPENTELEMETRY_ABI_VERSION_NO)
// clang-format off
#define OPENTELEMETRY_BEGIN_NAMESPACE \
namespace opentelemetry { inline namespace OPENTELEMETRY_CONCAT(v, OPENTELEMETRY_ABI_VERSION_NO) {
#define OPENTELEMETRY_END_NAMESPACE \
}}
#define OPENTELEMETRY_NAMESPACE opentelemetry :: OPENTELEMETRY_CONCAT(v, OPENTELEMETRY_ABI_VERSION_NO)
// clang-format on

View File

@@ -1,131 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#include <sstream>
#include <string>
#include <vector>
#include "opentelemetry/nostd/variant.h"
#include "opentelemetry/sdk/common/attribute_utils.h"
#pragma once
OPENTELEMETRY_BEGIN_NAMESPACE
namespace exporter
{
namespace ostream_common
{
/*
print_value is used to print out the value of an attribute within a vector.
These values are held in a variant which makes the process of printing them much more
complicated.
*/
template <typename T>
void print_value(const T &item, std::ostream &sout)
{
sout << item;
}
template <typename T>
void print_value(const std::vector<T> &vec, std::ostream &sout)
{
sout << '[';
size_t i = 1;
size_t sz = vec.size();
for (auto v : vec)
{
sout << v;
if (i != sz)
sout << ',';
i++;
};
sout << ']';
}
template <typename T>
void print_value(const nostd::span<T> &vec, std::ostream &sout)
{
sout << '[';
size_t i = 1;
size_t sz = vec.size();
for (auto v : vec)
{
sout << v;
if (i != sz)
sout << ',';
i++;
};
sout << ']';
}
// Prior to C++14, generic lambda is not available so fallback to functor.
#if (!defined(_MSVC_LANG) && (__cplusplus < 201402L)) || \
(defined(_MSVC_LANG) && (_MSVC_LANG < 201402L))
class OwnedAttributeValueVisitor
{
public:
OwnedAttributeValueVisitor(std::ostream &sout) : sout_(sout) {}
template <typename T>
void operator()(T &&arg)
{
print_value(arg, sout_);
}
private:
std::ostream &sout_;
};
class AttributeValueVisitor
{
public:
AttributeValueVisitor(std::ostream &sout) : sout_(sout) {}
template <typename T>
void operator()(T &&arg)
{
print_value(arg, sout_);
}
void operator()(nostd::string_view &&arg) { sout_.write(arg.data(), arg.size()); }
private:
std::ostream &sout_;
};
#endif
inline void print_value(const opentelemetry::sdk::common::OwnedAttributeValue &value,
std::ostream &sout)
{
#if (!defined(_MSVC_LANG) && (__cplusplus < 201402L)) || \
(defined(_MSVC_LANG) && (_MSVC_LANG < 201402L))
opentelemetry::nostd::visit(OwnedAttributeValueVisitor(sout), value);
#else
opentelemetry::nostd::visit(
[&sout](auto &&arg) {
/* explicit this is needed by some gcc versions (observed with v5.4.0)*/
print_value(arg, sout);
},
value);
#endif
}
inline void print_value(const opentelemetry::common::AttributeValue &value, std::ostream &sout)
{
#if (!defined(_MSVC_LANG) && (__cplusplus < 201402L)) || \
(defined(_MSVC_LANG) && (_MSVC_LANG < 201402L))
opentelemetry::nostd::visit(AttributeValueVisitor(sout), value);
#else
opentelemetry::nostd::visit(
[&sout](auto &&arg) {
/* explicit this is needed by some gcc versions (observed with v5.4.0)*/
print_value(arg, sout);
},
value);
#endif
}
} // namespace ostream_common
} // namespace exporter
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,85 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <atomic>
#include <chrono>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/sdk/common/attribute_utils.h"
#include "opentelemetry/sdk/common/exporter_utils.h"
#include "opentelemetry/sdk/instrumentationscope/instrumentation_scope.h"
#include "opentelemetry/sdk/resource/resource.h"
#include "opentelemetry/sdk/trace/exporter.h"
#include "opentelemetry/sdk/trace/recordable.h"
#include "opentelemetry/sdk/trace/span_data.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace exporter
{
namespace trace
{
/**
* The OStreamSpanExporter exports span data through an ostream
*/
class OStreamSpanExporter final : public opentelemetry::sdk::trace::SpanExporter
{
public:
/**
* Create an OStreamSpanExporter. This constructor takes in a reference to an ostream that the
* export() function will send span data into.
* The default ostream is set to stdout
*/
explicit OStreamSpanExporter(std::ostream &sout = std::cout) noexcept;
std::unique_ptr<opentelemetry::sdk::trace::Recordable> MakeRecordable() noexcept override;
sdk::common::ExportResult Export(
const opentelemetry::nostd::span<std::unique_ptr<opentelemetry::sdk::trace::Recordable>>
&spans) noexcept override;
/**
* Force flush the exporter.
* @param timeout an option timeout, default to max.
* @return return true when all data are exported, and false when timeout
*/
bool ForceFlush(
std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept override;
bool Shutdown(
std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept override;
private:
std::ostream &sout_;
std::atomic<bool> is_shutdown_{false};
bool isShutdown() const noexcept;
// Mapping status number to the string from api/include/opentelemetry/trace/span_metadata.h
std::map<int, std::string> statusMap{{0, "Unset"}, {1, "Ok"}, {2, "Error"}};
// various print helpers
void printAttributes(
const std::unordered_map<std::string, opentelemetry::sdk::common::OwnedAttributeValue> &map,
const std::string &prefix = "\n\t");
void printEvents(const std::vector<opentelemetry::sdk::trace::SpanDataEvent> &events);
void printLinks(const std::vector<opentelemetry::sdk::trace::SpanDataLink> &links);
void printResources(const opentelemetry::sdk::resource::Resource &resources);
void printInstrumentationScope(
const opentelemetry::sdk::instrumentationscope::InstrumentationScope &instrumentation_scope);
};
} // namespace trace
} // namespace exporter
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,37 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <iostream>
#include <memory>
#include "opentelemetry/sdk/trace/exporter.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace exporter
{
namespace trace
{
/**
* Factory class for OStreamSpanExporter.
*/
class OPENTELEMETRY_EXPORT OStreamSpanExporterFactory
{
public:
/**
* Creates an OStreamSpanExporter writing to the default location.
*/
static std::unique_ptr<opentelemetry::sdk::trace::SpanExporter> Create();
/**
* Creates an OStreamSpanExporter writing to the given location.
*/
static std::unique_ptr<opentelemetry::sdk::trace::SpanExporter> Create(std::ostream &sout);
};
} // namespace trace
} // namespace exporter
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,14 +0,0 @@
# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
include("/third_party/opentelemetry-cpp/opentelemetry-config.mozbuild")
UNIFIED_SOURCES += [
"src/span_exporter.cc",
"src/span_exporter_factory.cc",
]
FINAL_LIBRARY = "xul"

View File

@@ -1,200 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#include <atomic>
#include <chrono>
#include <iostream>
#include <map>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "opentelemetry/common/timestamp.h"
#include "opentelemetry/exporters/ostream/common_utils.h"
#include "opentelemetry/exporters/ostream/span_exporter.h"
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/sdk/common/attribute_utils.h"
#include "opentelemetry/sdk/common/exporter_utils.h"
#include "opentelemetry/sdk/common/global_log_handler.h"
#include "opentelemetry/sdk/instrumentationscope/instrumentation_scope.h"
#include "opentelemetry/sdk/resource/resource.h"
#include "opentelemetry/sdk/trace/recordable.h"
#include "opentelemetry/sdk/trace/span_data.h"
#include "opentelemetry/trace/span_context.h"
#include "opentelemetry/trace/span_id.h"
#include "opentelemetry/trace/span_metadata.h"
#include "opentelemetry/trace/trace_id.h"
#include "opentelemetry/trace/trace_state.h"
#include "opentelemetry/version.h"
namespace trace_sdk = opentelemetry::sdk::trace;
namespace trace_api = opentelemetry::trace;
namespace sdkcommon = opentelemetry::sdk::common;
OPENTELEMETRY_BEGIN_NAMESPACE
namespace exporter
{
namespace trace
{
std::ostream &operator<<(std::ostream &os, trace_api::SpanKind span_kind)
{
switch (span_kind)
{
case trace_api::SpanKind::kClient:
return os << "Client";
case trace_api::SpanKind::kInternal:
return os << "Internal";
case trace_api::SpanKind::kServer:
return os << "Server";
case trace_api::SpanKind::kProducer:
return os << "Producer";
case trace_api::SpanKind::kConsumer:
return os << "Consumer";
};
return os << "";
}
OStreamSpanExporter::OStreamSpanExporter(std::ostream &sout) noexcept : sout_(sout) {}
std::unique_ptr<trace_sdk::Recordable> OStreamSpanExporter::MakeRecordable() noexcept
{
return std::unique_ptr<trace_sdk::Recordable>(new trace_sdk::SpanData);
}
sdk::common::ExportResult OStreamSpanExporter::Export(
const opentelemetry::nostd::span<std::unique_ptr<trace_sdk::Recordable>> &spans) noexcept
{
if (isShutdown())
{
OTEL_INTERNAL_LOG_ERROR("[Ostream Trace Exporter] Exporting "
<< spans.size() << " span(s) failed, exporter is shutdown");
return sdk::common::ExportResult::kFailure;
}
for (auto &recordable : spans)
{
auto span = std::unique_ptr<trace_sdk::SpanData>(
static_cast<trace_sdk::SpanData *>(recordable.release()));
if (span != nullptr)
{
char trace_id[32] = {0};
char span_id[16] = {0};
char parent_span_id[16] = {0};
span->GetTraceId().ToLowerBase16(trace_id);
span->GetSpanId().ToLowerBase16(span_id);
span->GetParentSpanId().ToLowerBase16(parent_span_id);
sout_ << "{" << "\n name : " << span->GetName()
<< "\n trace_id : " << std::string(trace_id, 32)
<< "\n span_id : " << std::string(span_id, 16)
<< "\n tracestate : " << span->GetSpanContext().trace_state()->ToHeader()
<< "\n parent_span_id: " << std::string(parent_span_id, 16)
<< "\n start : " << span->GetStartTime().time_since_epoch().count()
<< "\n duration : " << span->GetDuration().count()
<< "\n description : " << span->GetDescription()
<< "\n span kind : " << span->GetSpanKind()
<< "\n status : " << statusMap[static_cast<int>(span->GetStatus())]
<< "\n attributes : ";
printAttributes(span->GetAttributes());
sout_ << "\n events : ";
printEvents(span->GetEvents());
sout_ << "\n links : ";
printLinks(span->GetLinks());
sout_ << "\n resources : ";
printResources(span->GetResource());
sout_ << "\n instr-lib : ";
printInstrumentationScope(span->GetInstrumentationScope());
sout_ << "\n}\n";
}
}
return sdk::common::ExportResult::kSuccess;
}
bool OStreamSpanExporter::ForceFlush(std::chrono::microseconds /* timeout */) noexcept
{
sout_.flush();
return true;
}
bool OStreamSpanExporter::Shutdown(std::chrono::microseconds /* timeout */) noexcept
{
is_shutdown_ = true;
return true;
}
bool OStreamSpanExporter::isShutdown() const noexcept
{
return is_shutdown_;
}
void OStreamSpanExporter::printAttributes(
const std::unordered_map<std::string, sdkcommon::OwnedAttributeValue> &map,
const std::string &prefix)
{
for (const auto &kv : map)
{
sout_ << prefix << kv.first << ": ";
opentelemetry::exporter::ostream_common::print_value(kv.second, sout_);
}
}
void OStreamSpanExporter::printEvents(const std::vector<trace_sdk::SpanDataEvent> &events)
{
for (const auto &event : events)
{
sout_ << "\n\t{" << "\n\t name : " << event.GetName()
<< "\n\t timestamp : " << event.GetTimestamp().time_since_epoch().count()
<< "\n\t attributes : ";
printAttributes(event.GetAttributes(), "\n\t\t");
sout_ << "\n\t}";
}
}
void OStreamSpanExporter::printLinks(const std::vector<trace_sdk::SpanDataLink> &links)
{
for (const auto &link : links)
{
char trace_id[32] = {0};
char span_id[16] = {0};
link.GetSpanContext().trace_id().ToLowerBase16(trace_id);
link.GetSpanContext().span_id().ToLowerBase16(span_id);
sout_ << "\n\t{" << "\n\t trace_id : " << std::string(trace_id, 32)
<< "\n\t span_id : " << std::string(span_id, 16)
<< "\n\t tracestate : " << link.GetSpanContext().trace_state()->ToHeader()
<< "\n\t attributes : ";
printAttributes(link.GetAttributes(), "\n\t\t");
sout_ << "\n\t}";
}
}
void OStreamSpanExporter::printResources(const opentelemetry::sdk::resource::Resource &resources)
{
const auto &attributes = resources.GetAttributes();
if (attributes.size())
{
printAttributes(attributes, "\n\t");
}
}
void OStreamSpanExporter::printInstrumentationScope(
const opentelemetry::sdk::instrumentationscope::InstrumentationScope &instrumentation_scope)
{
sout_ << instrumentation_scope.GetName();
const auto &version = instrumentation_scope.GetVersion();
if (version.size())
{
sout_ << "-" << version;
}
}
} // namespace trace
} // namespace exporter
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,30 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#include "opentelemetry/exporters/ostream/span_exporter_factory.h"
#include "opentelemetry/exporters/ostream/span_exporter.h"
#include "opentelemetry/sdk/trace/recordable.h"
#include "opentelemetry/version.h"
namespace trace_sdk = opentelemetry::sdk::trace;
OPENTELEMETRY_BEGIN_NAMESPACE
namespace exporter
{
namespace trace
{
std::unique_ptr<trace_sdk::SpanExporter> OStreamSpanExporterFactory::Create()
{
return Create(std::cout);
}
std::unique_ptr<trace_sdk::SpanExporter> OStreamSpanExporterFactory::Create(std::ostream &sout)
{
std::unique_ptr<trace_sdk::SpanExporter> exporter(new OStreamSpanExporter(sout));
return exporter;
}
} // namespace trace
} // namespace exporter
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,15 +0,0 @@
# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
DIRS += [
"sdk/src",
]
if CONFIG["MOZ_DEBUG"]:
DIRS += [ "exporters/ostream" ]
with Files("**"):
BUG_COMPONENT = ("Toolkit", "Gecko Trace")

View File

@@ -1,73 +0,0 @@
schema: 1
bugzilla:
product: "Firefox"
component: "Toolkit: Gecko Trace"
origin:
name: opentelemetry-cpp
description: The OpenTelemetry C++ Client
url: https://opentelemetry.io/
release: v1.18.0 (2024-11-26T00:19:04+01:00).
revision: v1.18.0
license: Apache-2.0
license-file: LICENSE
vendoring:
url: https://github.com/open-telemetry/opentelemetry-cpp
source-hosting: github
tracking: tag
exclude:
- "**"
include:
- CHANGELOG.md
- LICENSE
- README.md
- api/include/opentelemetry/*.h
- api/include/opentelemetry/common/*.h
- api/include/opentelemetry/context/*.h
- api/include/opentelemetry/detail/*.h
- api/include/opentelemetry/nostd/*.h
- api/include/opentelemetry/semconv/incubating/process_attributes.h
- api/include/opentelemetry/semconv/service_attributes.h
- api/include/opentelemetry/semconv/telemetry_attributes.h
- api/include/opentelemetry/std/*.h
- api/include/opentelemetry/trace/*.h
- exporters/ostream/include/opentelemetry/exporters/ostream/common_utils.h
- exporters/ostream/include/opentelemetry/exporters/ostream/span_exporter.h
- exporters/ostream/include/opentelemetry/exporters/ostream/span_exporter_factory.h
- exporters/ostream/src/span_exporter.cc
- exporters/ostream/src/span_exporter_factory.cc
- sdk/include/opentelemetry/*.h
- sdk/include/opentelemetry/sdk/common/*.h
- sdk/include/opentelemetry/sdk/instrumentationscope/*.h
- sdk/include/opentelemetry/sdk/resource/*.h
- sdk/include/opentelemetry/sdk/trace/*.h
- sdk/include/opentelemetry/sdk/trace/samplers/always_on.h
- sdk/include/opentelemetry/sdk/trace/samplers/always_on_factory.h
- sdk/include/opentelemetry/sdk/version/*.h
- sdk/src/common/**/*.cc
- sdk/src/common/**/*.h
- sdk/src/resource/*.cc
- sdk/src/trace/*.cc
- sdk/src/trace/*.h
- sdk/src/trace/samplers/always_on_factory.cc
- sdk/src/version/*.cc
keep:
- opentelemetry-config.mozbuild
patches:
- patches/fix-ambiguous-holds_alternative.patch # Maybe we should upstream this
updatebot:
maintainer-phab: mvanstraten
maintainer-bz: mvanstraten@mozilla.com
tasks:
- type: vendoring
enabled: true
frequency: release

View File

@@ -1,13 +0,0 @@
# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
LOCAL_INCLUDES += [
"/third_party/opentelemetry-cpp/api/include",
"/third_party/opentelemetry-cpp/exporters/ostream/include",
"/third_party/opentelemetry-cpp/sdk/include",
]
DEFINES["OPENTELEMETRY_STL_VERSION"] = 2017

View File

@@ -1,20 +0,0 @@
diff --git a/third_party/opentelemetry-cpp/api/include/opentelemetry/std/variant.h b/third_party/opentelemetry-cpp/api/include/opentelemetry/std/variant.h
index 58bc510c5f622..c665c7945f4f7 100644
--- a/third_party/opentelemetry-cpp/api/include/opentelemetry/std/variant.h
+++ b/third_party/opentelemetry-cpp/api/include/opentelemetry/std/variant.h
@@ -220,9 +220,13 @@ inline constexpr bool holds_alternative(const variant<Ts...> &v) noexcept
return v.index() == I;
}
-template <typename T, typename... Ts>
-inline constexpr bool holds_alternative(const variant<Ts...> &v) noexcept
+template <typename T, template<typename...> typename U, typename... Ts>
+inline constexpr bool holds_alternative(const U<Ts...> &v) noexcept
{
+ // Clang 18.1.7 on Ubuntu 24.04 does not disambiguate between this
+ // and std::holds_alternative if argument type is std::variant<Ts...>
+ static_assert(std::is_same_v<U<Ts...>, std::variant<Ts...>>,
+ "Unsupported argument type");
return std::holds_alternative<T, Ts...>(v);
}

View File

@@ -1,63 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <atomic>
#include <memory>
#include <mutex>
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace common
{
/**
* A wrapper to provide atomic shared pointers.
*
* This wrapper relies on a mutex for gcc 4.8, and specializations of
* std::atomic_store and std::atomic_load for all other instances.
*/
#if (__GNUC__ == 4 && (__GNUC_MINOR__ >= 8))
template <class T>
class AtomicSharedPtr
{
public:
explicit AtomicSharedPtr(std::shared_ptr<T> ptr) noexcept : ptr_{std::move(ptr)} {}
void store(const std::shared_ptr<T> &other) noexcept
{
std::lock_guard<std::mutex> lock_guard{mu_};
ptr_ = other;
}
std::shared_ptr<T> load() const noexcept
{
std::lock_guard<std::mutex> lock_guard{mu_};
return ptr_;
}
private:
std::shared_ptr<T> ptr_;
mutable std::mutex mu_;
};
#else
template <class T>
class AtomicSharedPtr
{
public:
explicit AtomicSharedPtr(std::shared_ptr<T> ptr) noexcept : ptr_{std::move(ptr)} {}
void store(const std::shared_ptr<T> &other) noexcept { std::atomic_store(&ptr_, other); }
std::shared_ptr<T> load() const noexcept { return std::atomic_load(&ptr_); }
private:
std::shared_ptr<T> ptr_;
};
#endif
} // namespace common
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,87 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <atomic>
#include <memory>
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace common
{
/**
* An owning pointer similar to std::unique_ptr but with methods for atomic
* operations.
*/
template <class T>
class AtomicUniquePtr
{
public:
AtomicUniquePtr() noexcept {}
explicit AtomicUniquePtr(std::unique_ptr<T> &&other) noexcept : ptr_(other.release()) {}
~AtomicUniquePtr() noexcept { Reset(); }
T &operator*() const noexcept { return *Get(); }
T *operator->() const noexcept { return Get(); }
/**
* @return the underly pointer managed.
*/
T *Get() const noexcept { return ptr_; }
/**
* @return true if the pointer is null
*/
bool IsNull() const noexcept { return ptr_.load() == nullptr; }
/**
* Atomically swap the pointer only if it's null.
* @param owner the pointer to swap with
* @return true if the swap was successful
*/
bool SwapIfNull(std::unique_ptr<T> &owner) noexcept
{
auto ptr = owner.get();
T *expected = nullptr;
auto was_successful = ptr_.compare_exchange_weak(expected, ptr, std::memory_order_release,
std::memory_order_relaxed);
if (was_successful)
{
owner.release();
return true;
}
return false;
}
/**
* Atomically swap the pointer with another.
* @param ptr the pointer to swap with
*/
void Swap(std::unique_ptr<T> &other) noexcept { other.reset(ptr_.exchange(other.release())); }
/**
* Set the pointer to a new value and delete the current value if non-null.
* @param ptr the new pointer value to set
*/
void Reset(T *ptr = nullptr) noexcept
{
ptr = ptr_.exchange(ptr);
if (ptr != nullptr)
{
delete ptr;
}
}
private:
std::atomic<T *> ptr_{nullptr};
};
} // namespace common
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,220 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <cstdint>
#include <initializer_list>
#include <map>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "opentelemetry/common/attribute_value.h"
#include "opentelemetry/common/key_value_iterable.h"
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/nostd/variant.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace common
{
/**
* A counterpart to AttributeValue that makes sure a value is owned. This
* replaces all non-owning references with owned copies.
*
* The following types are not currently supported by the OpenTelemetry
* specification, but reserved for future use:
* - uint64_t
* - std::vector<uint64_t>
* - std::vector<uint8_t>
*/
using OwnedAttributeValue = nostd::variant<bool,
int32_t,
uint32_t,
int64_t,
double,
std::string,
std::vector<bool>,
std::vector<int32_t>,
std::vector<uint32_t>,
std::vector<int64_t>,
std::vector<double>,
std::vector<std::string>,
uint64_t,
std::vector<uint64_t>,
std::vector<uint8_t>>;
enum OwnedAttributeType
{
kTypeBool,
kTypeInt,
kTypeUInt,
kTypeInt64,
kTypeDouble,
kTypeString,
kTypeSpanBool,
kTypeSpanInt,
kTypeSpanUInt,
kTypeSpanInt64,
kTypeSpanDouble,
kTypeSpanString,
kTypeUInt64,
kTypeSpanUInt64,
kTypeSpanByte
};
/**
* Creates an owned copy (OwnedAttributeValue) of a non-owning AttributeValue.
*/
struct AttributeConverter
{
OwnedAttributeValue operator()(bool v) { return OwnedAttributeValue(v); }
OwnedAttributeValue operator()(int32_t v) { return OwnedAttributeValue(v); }
OwnedAttributeValue operator()(uint32_t v) { return OwnedAttributeValue(v); }
OwnedAttributeValue operator()(int64_t v) { return OwnedAttributeValue(v); }
OwnedAttributeValue operator()(uint64_t v) { return OwnedAttributeValue(v); }
OwnedAttributeValue operator()(double v) { return OwnedAttributeValue(v); }
OwnedAttributeValue operator()(nostd::string_view v)
{
return OwnedAttributeValue(std::string(v));
}
OwnedAttributeValue operator()(std::string v) { return OwnedAttributeValue(v); }
OwnedAttributeValue operator()(const char *v) { return OwnedAttributeValue(std::string(v)); }
OwnedAttributeValue operator()(nostd::span<const uint8_t> v) { return convertSpan<uint8_t>(v); }
OwnedAttributeValue operator()(nostd::span<const bool> v) { return convertSpan<bool>(v); }
OwnedAttributeValue operator()(nostd::span<const int32_t> v) { return convertSpan<int32_t>(v); }
OwnedAttributeValue operator()(nostd::span<const uint32_t> v) { return convertSpan<uint32_t>(v); }
OwnedAttributeValue operator()(nostd::span<const int64_t> v) { return convertSpan<int64_t>(v); }
OwnedAttributeValue operator()(nostd::span<const uint64_t> v) { return convertSpan<uint64_t>(v); }
OwnedAttributeValue operator()(nostd::span<const double> v) { return convertSpan<double>(v); }
OwnedAttributeValue operator()(nostd::span<const nostd::string_view> v)
{
return convertSpan<std::string>(v);
}
template <typename T, typename U = T>
OwnedAttributeValue convertSpan(nostd::span<const U> vals)
{
const std::vector<T> copy(vals.begin(), vals.end());
return OwnedAttributeValue(std::move(copy));
}
};
/**
* Class for storing attributes.
*/
class AttributeMap : public std::unordered_map<std::string, OwnedAttributeValue>
{
public:
// Construct empty attribute map
AttributeMap() : std::unordered_map<std::string, OwnedAttributeValue>() {}
// Construct attribute map and populate with attributes
AttributeMap(const opentelemetry::common::KeyValueIterable &attributes) : AttributeMap()
{
attributes.ForEachKeyValue(
[&](nostd::string_view key, opentelemetry::common::AttributeValue value) noexcept {
SetAttribute(key, value);
return true;
});
}
// Construct attribute map and populate with optional attributes
AttributeMap(const opentelemetry::common::KeyValueIterable *attributes) : AttributeMap()
{
if (attributes != nullptr)
{
attributes->ForEachKeyValue(
[&](nostd::string_view key, opentelemetry::common::AttributeValue value) noexcept {
SetAttribute(key, value);
return true;
});
}
}
// Construct map from initializer list by applying `SetAttribute` transform for every attribute
AttributeMap(
std::initializer_list<std::pair<nostd::string_view, opentelemetry::common::AttributeValue>>
attributes)
: AttributeMap()
{
for (auto &kv : attributes)
{
SetAttribute(kv.first, kv.second);
}
}
// Returns a reference to this map
const std::unordered_map<std::string, OwnedAttributeValue> &GetAttributes() const noexcept
{
return (*this);
}
// Convert non-owning key-value to owning std::string(key) and OwnedAttributeValue(value)
void SetAttribute(nostd::string_view key,
const opentelemetry::common::AttributeValue &value) noexcept
{
(*this)[std::string(key)] = nostd::visit(converter_, value);
}
private:
AttributeConverter converter_;
};
/**
* Class for storing attributes.
*/
class OrderedAttributeMap : public std::map<std::string, OwnedAttributeValue>
{
public:
// Contruct empty attribute map
OrderedAttributeMap() : std::map<std::string, OwnedAttributeValue>() {}
// Contruct attribute map and populate with attributes
OrderedAttributeMap(const opentelemetry::common::KeyValueIterable &attributes)
: OrderedAttributeMap()
{
attributes.ForEachKeyValue(
[&](nostd::string_view key, opentelemetry::common::AttributeValue value) noexcept {
SetAttribute(key, value);
return true;
});
}
// Construct map from initializer list by applying `SetAttribute` transform for every attribute
OrderedAttributeMap(
std::initializer_list<std::pair<nostd::string_view, opentelemetry::common::AttributeValue>>
attributes)
: OrderedAttributeMap()
{
for (auto &kv : attributes)
{
SetAttribute(kv.first, kv.second);
}
}
// Returns a reference to this map
const std::map<std::string, OwnedAttributeValue> &GetAttributes() const noexcept
{
return (*this);
}
// Convert non-owning key-value to owning std::string(key) and OwnedAttributeValue(value)
void SetAttribute(nostd::string_view key,
const opentelemetry::common::AttributeValue &value) noexcept
{
(*this)[std::string(key)] = nostd::visit(converter_, value);
}
private:
AttributeConverter converter_;
};
} // namespace common
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,107 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <stddef.h>
#include <functional>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "opentelemetry/common/attribute_value.h"
#include "opentelemetry/common/key_value_iterable.h"
#include "opentelemetry/nostd/function_ref.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/nostd/variant.h"
#include "opentelemetry/sdk/common/attribute_utils.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace common
{
template <class T>
inline void GetHash(size_t &seed, const T &arg)
{
std::hash<T> hasher;
// reference -
// https://www.boost.org/doc/libs/1_37_0/doc/html/hash/reference.html#boost.hash_combine
seed ^= hasher(arg) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
template <class T>
inline void GetHash(size_t &seed, const std::vector<T> &arg)
{
for (auto v : arg)
{
GetHash<T>(seed, v);
}
}
// Specialization for const char*
// this creates an intermediate string.
template <>
inline void GetHash<const char *>(size_t &seed, const char *const &arg)
{
std::hash<std::string> hasher;
seed ^= hasher(std::string(arg)) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
struct GetHashForAttributeValueVisitor
{
GetHashForAttributeValueVisitor(size_t &seed) : seed_(seed) {}
template <class T>
void operator()(T &v)
{
GetHash(seed_, v);
}
size_t &seed_;
};
// Calculate hash of keys and values of attribute map
inline size_t GetHashForAttributeMap(const OrderedAttributeMap &attribute_map)
{
size_t seed = 0UL;
for (auto &kv : attribute_map)
{
GetHash(seed, kv.first);
nostd::visit(GetHashForAttributeValueVisitor(seed), kv.second);
}
return seed;
}
// Calculate hash of keys and values of KeyValueIterable, filtered using callback.
inline size_t GetHashForAttributeMap(
const opentelemetry::common::KeyValueIterable &attributes,
nostd::function_ref<bool(nostd::string_view)> is_key_present_callback)
{
AttributeConverter converter;
size_t seed = 0UL;
attributes.ForEachKeyValue(
[&](nostd::string_view key, opentelemetry::common::AttributeValue value) noexcept {
if (!is_key_present_callback(key))
{
return true;
}
GetHash(seed, key);
auto attr_val = nostd::visit(converter, value);
nostd::visit(GetHashForAttributeValueVisitor(seed), attr_val);
return true;
});
return seed;
}
template <class T>
inline size_t GetHash(T value)
{
std::hash<T> hasher;
return hasher(value);
}
} // namespace common
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,35 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <string>
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace common
{
// Base64Escape()
//
// Encodes a `src` string into a base64-encoded 'dest' string with padding
// characters. This function conforms with RFC 4648 section 4 (base64) and RFC
// 2045.
OPENTELEMETRY_EXPORT void Base64Escape(opentelemetry::nostd::string_view src, std::string *dest);
OPENTELEMETRY_EXPORT std::string Base64Escape(opentelemetry::nostd::string_view src);
// Base64Unescape()
//
// Converts a `src` string encoded in Base64 (RFC 4648 section 4) to its binary
// equivalent, writing it to a `dest` buffer, returning `true` on success. If
// `src` contains invalid characters, `dest` is cleared and returns `false`.
// If padding is included (note that `Base64Escape()` does produce it), it must
// be correct. In the padding, '=' are treated identically.
OPENTELEMETRY_EXPORT bool Base64Unescape(opentelemetry::nostd::string_view src, std::string *dest);
} // namespace common
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,197 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <atomic>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/sdk/common/atomic_unique_ptr.h"
#include "opentelemetry/sdk/common/circular_buffer_range.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace common
{
/*
* A lock-free circular buffer that supports multiple concurrent producers
* and a single consumer.
*/
template <class T>
class CircularBuffer
{
public:
explicit CircularBuffer(size_t max_size)
: data_{new AtomicUniquePtr<T>[max_size + 1]}, capacity_{max_size + 1}
{}
/**
* @return a range of the elements in the circular buffer
*
* Note: This method must only be called from the consumer thread.
*/
CircularBufferRange<const AtomicUniquePtr<T>> Peek() const noexcept
{
return const_cast<CircularBuffer *>(this)->PeekImpl();
}
/**
* Consume elements from the circular buffer's tail.
* @param n the number of elements to consume
* @param callback the callback to invoke with an AtomicUniquePtr to each
* consumed element.
*
* Note: The callback must set the passed AtomicUniquePtr to null.
*
* Note: This method must only be called from the consumer thread.
*/
template <class Callback>
void Consume(size_t n, Callback callback) noexcept
{
assert(n <= static_cast<size_t>(head_ - tail_));
auto range = PeekImpl().Take(n);
static_assert(noexcept(callback(range)), "callback not allowed to throw");
tail_ += n;
callback(range);
}
/**
* Consume elements from the circular buffer's tail.
* @param n the number of elements to consume
*
* Note: This method must only be called from the consumer thread.
*/
void Consume(size_t n) noexcept
{
Consume(n, [](CircularBufferRange<AtomicUniquePtr<T>> &range) noexcept {
range.ForEach([](AtomicUniquePtr<T> &ptr) noexcept {
ptr.Reset();
return true;
});
});
}
/**
* Adds an element into the circular buffer.
* @param ptr a pointer to the element to add
* @return true if the element was successfully added; false, otherwise.
*/
bool Add(std::unique_ptr<T> &ptr) noexcept
{
while (true)
{
uint64_t tail = tail_;
uint64_t head = head_;
// The circular buffer is full, so return false.
if (head - tail >= capacity_ - 1)
{
return false;
}
uint64_t head_index = head % capacity_;
if (data_[head_index].SwapIfNull(ptr))
{
auto new_head = head + 1;
auto expected_head = head;
if (head_.compare_exchange_weak(expected_head, new_head, std::memory_order_release,
std::memory_order_relaxed))
{
// free the swapped out value
ptr.reset();
return true;
}
// If we reached this point (unlikely), it means that between the last
// iteration elements were added and then consumed from the circular
// buffer, so we undo the swap and attempt to add again.
data_[head_index].Swap(ptr);
}
}
}
bool Add(std::unique_ptr<T> &&ptr) noexcept
{
// rvalue to lvalue reference
bool result = Add(std::ref(ptr));
ptr.reset();
return result;
}
/**
* Clear the circular buffer.
*
* Note: This method must only be called from the consumer thread.
*/
void Clear() noexcept { Consume(size()); }
/**
* @return the maximum number of bytes that can be stored in the buffer.
*/
size_t max_size() const noexcept { return capacity_ - 1; }
/**
* @return true if the buffer is empty.
*/
bool empty() const noexcept { return head_ == tail_; }
/**
* @return the number of bytes stored in the circular buffer.
*
* Note: this method will only return a correct snapshot of the size if called
* from the consumer thread.
*/
size_t size() const noexcept
{
uint64_t tail = tail_;
uint64_t head = head_;
assert(tail <= head);
return head - tail;
}
/**
* @return the number of elements consumed from the circular buffer.
*/
uint64_t consumption_count() const noexcept { return tail_; }
/**
* @return the number of elements added to the circular buffer.
*/
uint64_t production_count() const noexcept { return head_; }
private:
std::unique_ptr<AtomicUniquePtr<T>[]> data_;
size_t capacity_;
std::atomic<uint64_t> head_{0};
std::atomic<uint64_t> tail_{0};
CircularBufferRange<AtomicUniquePtr<T>> PeekImpl() noexcept
{
uint64_t tail_index = tail_ % capacity_;
uint64_t head_index = head_ % capacity_;
if (head_index == tail_index)
{
return {};
}
auto data = data_.get();
if (tail_index < head_index)
{
return CircularBufferRange<AtomicUniquePtr<T>>{nostd::span<AtomicUniquePtr<T>>{
data + tail_index, static_cast<std::size_t>(head_index - tail_index)}};
}
return {nostd::span<AtomicUniquePtr<T>>{data + tail_index,
static_cast<std::size_t>(capacity_ - tail_index)},
nostd::span<AtomicUniquePtr<T>>{data, static_cast<std::size_t>(head_index)}};
}
};
} // namespace common
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,92 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <stddef.h>
#include <cassert>
#include <type_traits>
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace common
{
/**
* A non-owning view into a range of elements in a circular buffer.
*/
template <class T>
class CircularBufferRange
{
public:
CircularBufferRange() noexcept = default;
explicit CircularBufferRange(nostd::span<T> first) noexcept : first_{first} {}
CircularBufferRange(nostd::span<T> first, nostd::span<T> second) noexcept
: first_{first}, second_{second}
{}
operator CircularBufferRange<const T>() const noexcept { return {first_, second_}; }
/**
* Iterate over the elements in the range.
* @param callback the callback to call for each element
* @return true if we iterated over all elements
*/
template <class Callback>
bool ForEach(Callback callback) const
noexcept(noexcept(std::declval<Callback>()(std::declval<T &>())))
{
for (auto &value : first_)
{
if (!callback(value))
{
return false;
}
}
for (auto &value : second_)
{
if (!callback(value))
{
return false;
}
}
return true;
}
/**
* @return the number of elements in the range
*/
size_t size() const noexcept { return first_.size() + second_.size(); }
/**
* @return true if the range is empty
*/
bool empty() const noexcept { return first_.empty(); }
/**
* Return a subrange taken from the start of this range.
* @param n the number of element to take in the subrange
* @return a subrange of the first n elements in this range
*/
CircularBufferRange Take(size_t n) const noexcept
{
assert(n <= size());
if (first_.size() >= n)
{
return CircularBufferRange{nostd::span<T>{first_.data(), n}};
}
return {first_, nostd::span<T>{second_.data(), n - first_.size()}};
}
private:
nostd::span<T> first_;
nostd::span<T> second_;
};
} // namespace common
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,36 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <array>
#include <string>
#include <utility>
#include "opentelemetry/common/key_value_iterable_view.h"
#include "opentelemetry/common/macros.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
/**
* Maintain a static empty array of pairs that represents empty (default) attributes.
* This helps to avoid constructing a new empty container every time a call is made
* with default attributes.
*/
static const opentelemetry::common::KeyValueIterableView<
std::array<std::pair<std::string, int32_t>, 0>> &
GetEmptyAttributes() noexcept
{
static const std::array<std::pair<std::string, int32_t>, 0> array{};
static const opentelemetry::common::KeyValueIterableView<
std::array<std::pair<std::string, int32_t>, 0>>
kEmptyAttributes(array);
return kEmptyAttributes;
}
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,56 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <chrono>
#include <string>
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace common
{
/**
Read a boolean environment variable.
@param env_var_name Environment variable name
@param [out] value Variable value, if it exists
@return true if the variable exists
*/
bool GetBoolEnvironmentVariable(const char *env_var_name, bool &value);
/**
Read a duration environment variable.
@param env_var_name Environment variable name
@param [out] value Variable value, if it exists
@return true if the variable exists
*/
bool GetDurationEnvironmentVariable(const char *env_var_name,
std::chrono::system_clock::duration &value);
/**
Read a string environment variable.
@param env_var_name Environment variable name
@param [out] value Variable value, if it exists
@return true if the variable exists
*/
bool GetStringEnvironmentVariable(const char *env_var_name, std::string &value);
#if defined(_MSC_VER)
inline int setenv(const char *name, const char *value, int)
{
return _putenv_s(name, value);
}
inline int unsetenv(const char *name)
{
return setenv(name, "", 1);
}
#endif
} // namespace common
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,34 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace common
{
/**
* ExportResult is returned as result of exporting a batch of Records.
*/
enum class ExportResult
{
// Batch was exported successfully.
kSuccess = 0,
// Batch exporting failed, caller must not retry exporting the same batch
// and the batch must be dropped.
kFailure = 1,
// The collection does not have enough space to receive the export batch.
kFailureFull = 2,
// The export() function was passed an invalid argument.
kFailureInvalidArgument = 3
};
} // namespace common
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,225 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <sstream> // IWYU pragma: keep
#include <string>
#include <utility>
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/sdk/common/attribute_utils.h"
#include "opentelemetry/version.h"
#define OTEL_INTERNAL_LOG_LEVEL_NONE 0
#define OTEL_INTERNAL_LOG_LEVEL_ERROR 1
#define OTEL_INTERNAL_LOG_LEVEL_WARN 2
#define OTEL_INTERNAL_LOG_LEVEL_INFO 3
#define OTEL_INTERNAL_LOG_LEVEL_DEBUG 4
#ifndef OTEL_INTERNAL_LOG_LEVEL
// DEBUG by default, we can change log level on runtime
# define OTEL_INTERNAL_LOG_LEVEL OTEL_INTERNAL_LOG_LEVEL_DEBUG
#endif
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace common
{
namespace internal_log
{
enum class LogLevel
{
None = OTEL_INTERNAL_LOG_LEVEL_NONE,
Error = OTEL_INTERNAL_LOG_LEVEL_ERROR,
Warning = OTEL_INTERNAL_LOG_LEVEL_WARN,
Info = OTEL_INTERNAL_LOG_LEVEL_INFO,
Debug = OTEL_INTERNAL_LOG_LEVEL_DEBUG
};
inline std::string LevelToString(LogLevel level)
{
switch (level)
{
case LogLevel::None:
return "None";
case LogLevel::Error:
return "Error";
case LogLevel::Warning:
return "Warning";
case LogLevel::Info:
return "Info";
case LogLevel::Debug:
return "Debug";
}
return {};
}
class LogHandler
{
public:
virtual ~LogHandler();
virtual void Handle(LogLevel level,
const char *file,
int line,
const char *msg,
const opentelemetry::sdk::common::AttributeMap &attributes) noexcept = 0;
};
class DefaultLogHandler : public LogHandler
{
public:
void Handle(LogLevel level,
const char *file,
int line,
const char *msg,
const opentelemetry::sdk::common::AttributeMap &attributes) noexcept override;
};
class NoopLogHandler : public LogHandler
{
public:
void Handle(LogLevel level,
const char *file,
int line,
const char *msg,
const opentelemetry::sdk::common::AttributeMap &error_attributes) noexcept override;
};
/**
* Stores the singleton global LogHandler.
*/
class GlobalLogHandler
{
public:
/**
* Returns the singleton LogHandler.
*
* By default, a default LogHandler is returned.
*/
static inline const nostd::shared_ptr<LogHandler> &GetLogHandler() noexcept
{
return GetHandlerAndLevel().first;
}
/**
* Changes the singleton LogHandler.
* This should be called once at the start of application before creating any Provider
* instance.
*/
static inline void SetLogHandler(nostd::shared_ptr<LogHandler> eh) noexcept
{
GetHandlerAndLevel().first = eh;
}
/**
* Returns the singleton log level.
*
* By default, a default log level is returned.
*/
static inline LogLevel GetLogLevel() noexcept { return GetHandlerAndLevel().second; }
/**
* Changes the singleton Log level.
* This should be called once at the start of application before creating any Provider
* instance.
*/
static inline void SetLogLevel(LogLevel level) noexcept { GetHandlerAndLevel().second = level; }
private:
static std::pair<nostd::shared_ptr<LogHandler>, LogLevel> &GetHandlerAndLevel() noexcept;
};
} // namespace internal_log
} // namespace common
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE
/**
* GlobalLogHandler and TracerProvider/MeterProvider/LoggerProvider are lazy singletons.
* To ensure that GlobalLogHandler is the first one to be initialized (and so last to be
* destroyed), it is first used inside the constructors of TraceProvider, MeterProvider
* and LoggerProvider for debug logging. */
#define OTEL_INTERNAL_LOG_DISPATCH(level, message, attributes) \
do \
{ \
using opentelemetry::sdk::common::internal_log::GlobalLogHandler; \
using opentelemetry::sdk::common::internal_log::LogHandler; \
if (level > GlobalLogHandler::GetLogLevel()) \
{ \
break; \
} \
const opentelemetry::nostd::shared_ptr<LogHandler> &log_handler = \
GlobalLogHandler::GetLogHandler(); \
if (!log_handler) \
{ \
break; \
} \
std::stringstream tmp_stream; \
tmp_stream << message; \
log_handler->Handle(level, __FILE__, __LINE__, tmp_stream.str().c_str(), attributes); \
} while (false);
#define OTEL_INTERNAL_LOG_GET_3RD_ARG(arg1, arg2, arg3, ...) arg3
#if OTEL_INTERNAL_LOG_LEVEL >= OTEL_INTERNAL_LOG_LEVEL_ERROR
# define OTEL_INTERNAL_LOG_ERROR_1_ARGS(message) \
OTEL_INTERNAL_LOG_DISPATCH(opentelemetry::sdk::common::internal_log::LogLevel::Error, message, \
{})
# define OTEL_INTERNAL_LOG_ERROR_2_ARGS(message, attributes) \
OTEL_INTERNAL_LOG_DISPATCH(opentelemetry::sdk::common::internal_log::LogLevel::Error, message, \
attributes)
# define OTEL_INTERNAL_LOG_ERROR_MACRO(...) \
OTEL_INTERNAL_LOG_GET_3RD_ARG(__VA_ARGS__, OTEL_INTERNAL_LOG_ERROR_2_ARGS, \
OTEL_INTERNAL_LOG_ERROR_1_ARGS)
# define OTEL_INTERNAL_LOG_ERROR(...) OTEL_INTERNAL_LOG_ERROR_MACRO(__VA_ARGS__)(__VA_ARGS__)
#else
# define OTEL_INTERNAL_LOG_ERROR(...)
#endif
#if OTEL_INTERNAL_LOG_LEVEL >= OTEL_INTERNAL_LOG_LEVEL_WARN
# define OTEL_INTERNAL_LOG_WARN_1_ARGS(message) \
OTEL_INTERNAL_LOG_DISPATCH(opentelemetry::sdk::common::internal_log::LogLevel::Warning, \
message, {})
# define OTEL_INTERNAL_LOG_WARN_2_ARGS(message, attributes) \
OTEL_INTERNAL_LOG_DISPATCH(opentelemetry::sdk::common::internal_log::LogLevel::Warning, \
message, attributes)
# define OTEL_INTERNAL_LOG_WARN_MACRO(...) \
OTEL_INTERNAL_LOG_GET_3RD_ARG(__VA_ARGS__, OTEL_INTERNAL_LOG_WARN_2_ARGS, \
OTEL_INTERNAL_LOG_WARN_1_ARGS)
# define OTEL_INTERNAL_LOG_WARN(...) OTEL_INTERNAL_LOG_WARN_MACRO(__VA_ARGS__)(__VA_ARGS__)
#else
# define OTEL_INTERNAL_LOG_WARN(...)
#endif
#if OTEL_INTERNAL_LOG_LEVEL >= OTEL_INTERNAL_LOG_LEVEL_DEBUG
# define OTEL_INTERNAL_LOG_DEBUG_1_ARGS(message) \
OTEL_INTERNAL_LOG_DISPATCH(opentelemetry::sdk::common::internal_log::LogLevel::Debug, message, \
{})
# define OTEL_INTERNAL_LOG_DEBUG_2_ARGS(message, attributes) \
OTEL_INTERNAL_LOG_DISPATCH(opentelemetry::sdk::common::internal_log::LogLevel::Debug, message, \
attributes)
# define OTEL_INTERNAL_LOG_DEBUG_MACRO(...) \
OTEL_INTERNAL_LOG_GET_3RD_ARG(__VA_ARGS__, OTEL_INTERNAL_LOG_DEBUG_2_ARGS, \
OTEL_INTERNAL_LOG_DEBUG_1_ARGS)
# define OTEL_INTERNAL_LOG_DEBUG(...) OTEL_INTERNAL_LOG_DEBUG_MACRO(__VA_ARGS__)(__VA_ARGS__)
#else
# define OTEL_INTERNAL_LOG_DEBUG(...)
#endif
#if OTEL_INTERNAL_LOG_LEVEL >= OTEL_INTERNAL_LOG_LEVEL_INFO
# define OTEL_INTERNAL_LOG_INFO_1_ARGS(message) \
OTEL_INTERNAL_LOG_DISPATCH(opentelemetry::sdk::common::internal_log::LogLevel::Info, message, \
{})
# define OTEL_INTERNAL_LOG_INFO_2_ARGS(message, attributes) \
OTEL_INTERNAL_LOG_DISPATCH(opentelemetry::sdk::common::internal_log::LogLevel::Info, message, \
attributes)
# define OTEL_INTERNAL_LOG_INFO_MACRO(...) \
OTEL_INTERNAL_LOG_GET_3RD_ARG(__VA_ARGS__, OTEL_INTERNAL_LOG_INFO_2_ARGS, \
OTEL_INTERNAL_LOG_INFO_1_ARGS)
# define OTEL_INTERNAL_LOG_INFO(...) OTEL_INTERNAL_LOG_INFO_MACRO(__VA_ARGS__)(__VA_ARGS__)
#else
# define OTEL_INTERNAL_LOG_INFO(...)
#endif

View File

@@ -1,164 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <string>
#include <type_traits>
#include "opentelemetry/common/key_value_iterable_view.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/nostd/type_traits.h"
#include "opentelemetry/nostd/unique_ptr.h"
#include "opentelemetry/nostd/variant.h"
#include "opentelemetry/sdk/common/attribute_utils.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace instrumentationscope
{
using InstrumentationScopeAttributes = opentelemetry::sdk::common::AttributeMap;
class InstrumentationScope
{
public:
InstrumentationScope(const InstrumentationScope &) = default;
/**
* Returns a newly created InstrumentationScope with the specified library name and version.
* @param name name of the instrumentation scope.
* @param version version of the instrumentation scope.
* @param schema_url schema url of the telemetry emitted by the library.
* @param attributes attributes of the instrumentation scope.
* @returns the newly created InstrumentationScope.
*/
static nostd::unique_ptr<InstrumentationScope> Create(
nostd::string_view name,
nostd::string_view version = "",
nostd::string_view schema_url = "",
InstrumentationScopeAttributes &&attributes = {})
{
return nostd::unique_ptr<InstrumentationScope>(
new InstrumentationScope{name, version, schema_url, std::move(attributes)});
}
/**
* Returns a newly created InstrumentationScope with the specified library name and version.
* @param name name of the instrumentation scope.
* @param version version of the instrumentation scope.
* @param schema_url schema url of the telemetry emitted by the library.
* @param attributes attributes of the instrumentation scope.
* @returns the newly created InstrumentationScope.
*/
static nostd::unique_ptr<InstrumentationScope> Create(
nostd::string_view name,
nostd::string_view version,
nostd::string_view schema_url,
const InstrumentationScopeAttributes &attributes)
{
return nostd::unique_ptr<InstrumentationScope>(new InstrumentationScope{
name, version, schema_url, InstrumentationScopeAttributes(attributes)});
}
/**
* Returns a newly created InstrumentationScope with the specified library name and version.
* @param name name of the instrumentation scope.
* @param version version of the instrumentation scope.
* @param schema_url schema url of the telemetry emitted by the library.
* @param arg arguments used to create attributes of the instrumentation scope.
* @returns the newly created InstrumentationScope.
*/
template <
class ArgumentType,
nostd::enable_if_t<opentelemetry::common::detail::is_key_value_iterable<ArgumentType>::value>
* = nullptr>
static nostd::unique_ptr<InstrumentationScope> Create(nostd::string_view name,
nostd::string_view version,
nostd::string_view schema_url,
const ArgumentType &arg)
{
nostd::unique_ptr<InstrumentationScope> result = nostd::unique_ptr<InstrumentationScope>(
new InstrumentationScope{name, version, schema_url});
// Do not construct a KeyValueIterable, so it has better performance.
result->attributes_.reserve(opentelemetry::nostd::size(arg));
for (auto &argv : arg)
{
result->SetAttribute(argv.first, argv.second);
}
return result;
}
std::size_t HashCode() const noexcept { return hash_code_; }
/**
* Compare 2 instrumentation libraries.
* @param other the instrumentation scope to compare to.
* @returns true if the 2 instrumentation libraries are equal, false otherwise.
*/
bool operator==(const InstrumentationScope &other) const noexcept
{
return equal(other.name_, other.version_, other.schema_url_);
}
/**
* Check whether the instrumentation scope has given name and version.
* This could be used to check version equality and avoid heap allocation.
* @param name name of the instrumentation scope to compare.
* @param version version of the instrumentation scope to compare.
* @param schema_url schema url of the telemetry emitted by the scope.
* @returns true if name and version in this instrumentation scope are equal with the given name
* and version.
*/
bool equal(const nostd::string_view name,
const nostd::string_view version,
const nostd::string_view schema_url = "") const noexcept
{
return this->name_ == name && this->version_ == version && this->schema_url_ == schema_url;
}
const std::string &GetName() const noexcept { return name_; }
const std::string &GetVersion() const noexcept { return version_; }
const std::string &GetSchemaURL() const noexcept { return schema_url_; }
const InstrumentationScopeAttributes &GetAttributes() const noexcept { return attributes_; }
void SetAttribute(nostd::string_view key,
const opentelemetry::common::AttributeValue &value) noexcept
{
attributes_[std::string(key)] =
nostd::visit(opentelemetry::sdk::common::AttributeConverter(), value);
}
private:
InstrumentationScope(nostd::string_view name,
nostd::string_view version,
nostd::string_view schema_url = "",
InstrumentationScopeAttributes &&attributes = {})
: name_(name), version_(version), schema_url_(schema_url), attributes_(std::move(attributes))
{
std::string hash_data;
hash_data.reserve(name_.size() + version_.size() + schema_url_.size());
hash_data += name_;
hash_data += version_;
hash_data += schema_url_;
hash_code_ = std::hash<std::string>{}(hash_data);
}
private:
std::string name_;
std::string version_;
std::string schema_url_;
std::size_t hash_code_;
InstrumentationScopeAttributes attributes_;
};
} // namespace instrumentationscope
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,83 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <string>
#include "opentelemetry/sdk/common/attribute_utils.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace resource
{
using ResourceAttributes = opentelemetry::sdk::common::AttributeMap;
class Resource
{
public:
Resource(const Resource &) = default;
const ResourceAttributes &GetAttributes() const noexcept;
const std::string &GetSchemaURL() const noexcept;
/**
* Returns a new, merged {@link Resource} by merging the current Resource
* with the other Resource. In case of a collision, the other Resource takes
* precedence.
*
* The specification notes that if schema urls collide, the resulting
* schema url is implementation-defined. In the C++ implementation, the
* schema url of @param other is picked.
*
* @param other the Resource that will be merged with this.
* @returns the newly merged Resource.
*/
Resource Merge(const Resource &other) const noexcept;
/**
* Returns a newly created Resource with the specified attributes.
* It adds (merge) SDK attributes and OTEL attributes before returning.
* @param attributes for this resource
* @returns the newly created Resource.
*/
static Resource Create(const ResourceAttributes &attributes,
const std::string &schema_url = std::string{});
/**
* Returns an Empty resource.
*/
static Resource &GetEmpty();
/**
* Returns a Resource that indentifies the SDK in use.
*/
static Resource &GetDefault();
protected:
/**
* The constructor is protected and only for use internally by the class and
* inside ResourceDetector class.
* Users should use the Create factory method to obtain a Resource
* instance.
*/
Resource(const ResourceAttributes &attributes = ResourceAttributes(),
const std::string &schema_url = std::string{}) noexcept;
private:
ResourceAttributes attributes_;
std::string schema_url_;
friend class OTELResourceDetector;
};
} // namespace resource
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,38 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/sdk/resource/resource.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace resource
{
/**
* Interface for a Resource Detector
*/
class ResourceDetector
{
public:
ResourceDetector() = default;
virtual ~ResourceDetector() = default;
virtual Resource Detect() = 0;
};
/**
* OTelResourceDetector to detect the presence of and create a Resource
* from the OTEL_RESOURCE_ATTRIBUTES environment variable.
*/
class OTELResourceDetector : public ResourceDetector
{
public:
Resource Detect() noexcept override;
};
} // namespace resource
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,166 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <stddef.h>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <memory>
#include <mutex>
#include <thread>
#include "opentelemetry/sdk/common/circular_buffer.h"
#include "opentelemetry/sdk/trace/batch_span_processor_options.h"
#include "opentelemetry/sdk/trace/exporter.h"
#include "opentelemetry/sdk/trace/processor.h"
#include "opentelemetry/sdk/trace/recordable.h"
#include "opentelemetry/trace/span_context.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/**
* This is an implementation of the SpanProcessor which creates batches of finished spans and passes
* the export-friendly span data representations to the configured SpanExporter.
*/
class BatchSpanProcessor : public SpanProcessor
{
public:
/**
* Creates a batch span processor by configuring the specified exporter and other parameters
* as per the official, language-agnostic opentelemetry specs.
*
* @param exporter - The backend exporter to pass the ended spans to.
* @param options - The batch SpanProcessor options.
*/
BatchSpanProcessor(std::unique_ptr<SpanExporter> &&exporter,
const BatchSpanProcessorOptions &options);
/**
* Requests a Recordable(Span) from the configured exporter.
*
* @return A recordable generated by the backend exporter
*/
std::unique_ptr<Recordable> MakeRecordable() noexcept override;
/**
* Called when a span is started.
*
* NOTE: This method is a no-op.
*
* @param span - The span that just started
* @param parent_context - The parent context of the span that just started
*/
void OnStart(Recordable &span,
const opentelemetry::trace::SpanContext &parent_context) noexcept override;
/**
* Called when a span ends.
*
* @param span - A recordable for a span that just ended
*/
void OnEnd(std::unique_ptr<Recordable> &&span) noexcept override;
/**
* Export all ended spans that have not been exported yet.
*
* NOTE: Timeout functionality not supported yet.
*/
bool ForceFlush(
std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept override;
/**
* Shuts down the processor and does any cleanup required. Completely drains the buffer/queue of
* all its ended spans and passes them to the exporter. Any subsequent calls to OnStart, OnEnd,
* ForceFlush or Shutdown will return immediately without doing anything.
*
* NOTE: Timeout functionality not supported yet.
*/
bool Shutdown(
std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept override;
/**
* Class destructor which invokes the Shutdown() method. The Shutdown() method is supposed to be
* invoked when the Tracer is shutdown (as per other languages), but the C++ Tracer only takes
* shared ownership of the processor, and thus doesn't call Shutdown (as the processor might be
* shared with other Tracers).
*/
~BatchSpanProcessor() override;
protected:
/**
* The background routine performed by the worker thread.
*/
void DoBackgroundWork();
/**
* Exports all ended spans to the configured exporter.
*
*/
virtual void Export();
/**
* Called when Shutdown() is invoked. Completely drains the queue of all its ended spans and
* passes them to the exporter.
*/
void DrainQueue();
struct SynchronizationData
{
/* Synchronization primitives */
std::condition_variable cv, force_flush_cv;
std::mutex cv_m, force_flush_cv_m, shutdown_m;
/* Important boolean flags to handle the workflow of the processor */
std::atomic<bool> is_force_wakeup_background_worker{false};
std::atomic<bool> is_shutdown{false};
std::atomic<uint64_t> force_flush_pending_sequence{0};
std::atomic<uint64_t> force_flush_notified_sequence{0};
std::atomic<std::chrono::microseconds::rep> force_flush_timeout_us{0};
// Do not use SynchronizationData() = default; here, some versions of GCC&Clang have BUGs
// and may not initialize the member correctly. See also
// https://stackoverflow.com/questions/53408962/try-to-understand-compiler-error-message-default-member-initializer-required-be
inline SynchronizationData() {}
};
/**
* @brief Notify completion of shutdown and force flush. This may be called from the any thread at
* any time
*
* @param notify_force_flush Sequence to indicate whether to notify force flush completion.
* @param synchronization_data Synchronization data to be notified.
*/
static void NotifyCompletion(uint64_t notify_force_flush,
const std::unique_ptr<SpanExporter> &exporter,
const std::shared_ptr<SynchronizationData> &synchronization_data);
void GetWaitAdjustedTime(std::chrono::microseconds &timeout,
std::chrono::time_point<std::chrono::system_clock> &start_time);
/* The configured backend exporter */
std::unique_ptr<SpanExporter> exporter_;
/* Configurable parameters as per the official specs */
const size_t max_queue_size_;
const std::chrono::milliseconds schedule_delay_millis_;
const size_t max_export_batch_size_;
/* The buffer/queue to which the ended spans are added */
opentelemetry::sdk::common::CircularBuffer<Recordable> buffer_;
std::shared_ptr<SynchronizationData> synchronization_data_;
/* The background worker thread */
std::thread worker_thread_;
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,34 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <memory>
#include "opentelemetry/sdk/trace/batch_span_processor_options.h"
#include "opentelemetry/sdk/trace/exporter.h"
#include "opentelemetry/sdk/trace/processor.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/**
* Factory class for BatchSpanProcessor.
*/
class OPENTELEMETRY_EXPORT BatchSpanProcessorFactory
{
public:
/**
* Create a BatchSpanProcessor.
*/
static std::unique_ptr<SpanProcessor> Create(std::unique_ptr<SpanExporter> &&exporter,
const BatchSpanProcessorOptions &options);
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,40 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <chrono>
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/**
* Struct to hold batch SpanProcessor options.
*/
struct BatchSpanProcessorOptions
{
/**
* The maximum buffer/queue size. After the size is reached, spans are
* dropped.
*/
size_t max_queue_size = 2048;
/* The time interval between two consecutive exports. */
std::chrono::milliseconds schedule_delay_millis = std::chrono::milliseconds(5000);
/**
* The maximum batch size of every export. It must be smaller or
* equal to max_queue_size.
*/
size_t max_export_batch_size = 512;
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,68 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <chrono>
#include <memory>
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/sdk/common/exporter_utils.h"
#include "opentelemetry/sdk/trace/recordable.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/**
* SpanExporter defines the interface that protocol-specific span exporters must
* implement.
*/
class OPENTELEMETRY_EXPORT SpanExporter
{
public:
SpanExporter();
virtual ~SpanExporter();
/**
* Create a span recordable. This object will be used to record span data and
* will subsequently be passed to SpanExporter::Export. Vendors can implement
* custom recordables or use the default SpanData recordable provided by the
* SDK.
* @return a newly initialized Recordable object
*
* Note: This method must be callable from multiple threads.
*/
virtual std::unique_ptr<Recordable> MakeRecordable() noexcept = 0;
/**
* Exports a batch of span recordables. This method must not be called
* concurrently for the same exporter instance.
* @param spans a span of unique pointers to span recordables
*/
virtual sdk::common::ExportResult Export(
const nostd::span<std::unique_ptr<Recordable>> &spans) noexcept = 0;
/**
* Export all spans that have been exported.
* @param timeout an optional timeout, the default timeout of 0 means that no
* timeout is applied.
* @return return true when all data are exported, and false when timeout
*/
virtual bool ForceFlush(
std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept;
/**
* Shut down the exporter.
* @param timeout an optional timeout.
* @return return the status of the operation.
*/
virtual bool Shutdown(
std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept = 0;
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,41 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/trace/span_id.h"
#include "opentelemetry/trace/trace_id.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/** IdGenerator provides an interface for generating Trace Id and Span Id */
class IdGenerator
{
public:
IdGenerator(bool is_random) : is_random_(is_random) {}
virtual ~IdGenerator() = default;
/** Returns a SpanId represented by opaque 128-bit trace identifier */
virtual opentelemetry::trace::SpanId GenerateSpanId() noexcept = 0;
/** Returns a TraceId represented by opaque 64-bit trace identifier */
virtual opentelemetry::trace::TraceId GenerateTraceId() noexcept = 0;
bool IsRandom() const { return is_random_; }
private:
/** True if GenerateTraceId() is random,
* per https://www.w3.org/TR/trace-context-2/#random-trace-id-flag
*/
bool is_random_;
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,168 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <map>
#include "opentelemetry/common/timestamp.h"
#include "opentelemetry/sdk/trace/processor.h"
#include "opentelemetry/sdk/trace/recordable.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
namespace
{
std::size_t MakeKey(const SpanProcessor &processor)
{
return reinterpret_cast<std::size_t>(&processor);
}
} // namespace
class MultiRecordable : public Recordable
{
public:
void AddRecordable(const SpanProcessor &processor,
std::unique_ptr<Recordable> recordable) noexcept
{
recordables_[MakeKey(processor)] = std::move(recordable);
}
const std::unique_ptr<Recordable> &GetRecordable(const SpanProcessor &processor) const noexcept
{
// TODO - return nullptr ref on failed lookup?
auto i = recordables_.find(MakeKey(processor));
if (i != recordables_.end())
{
return i->second;
}
static std::unique_ptr<Recordable> empty(nullptr);
return empty;
}
std::unique_ptr<Recordable> ReleaseRecordable(const SpanProcessor &processor) noexcept
{
auto i = recordables_.find(MakeKey(processor));
if (i != recordables_.end())
{
std::unique_ptr<Recordable> result(i->second.release());
recordables_.erase(MakeKey(processor));
return result;
}
return std::unique_ptr<Recordable>(nullptr);
}
void SetIdentity(const opentelemetry::trace::SpanContext &span_context,
opentelemetry::trace::SpanId parent_span_id) noexcept override
{
for (auto &recordable : recordables_)
{
recordable.second->SetIdentity(span_context, parent_span_id);
}
}
void SetAttribute(nostd::string_view key,
const opentelemetry::common::AttributeValue &value) noexcept override
{
for (auto &recordable : recordables_)
{
recordable.second->SetAttribute(key, value);
}
}
void AddEvent(nostd::string_view name,
opentelemetry::common::SystemTimestamp timestamp,
const opentelemetry::common::KeyValueIterable &attributes) noexcept override
{
for (auto &recordable : recordables_)
{
recordable.second->AddEvent(name, timestamp, attributes);
}
}
void AddLink(const opentelemetry::trace::SpanContext &span_context,
const opentelemetry::common::KeyValueIterable &attributes) noexcept override
{
for (auto &recordable : recordables_)
{
recordable.second->AddLink(span_context, attributes);
}
}
void SetStatus(opentelemetry::trace::StatusCode code,
nostd::string_view description) noexcept override
{
for (auto &recordable : recordables_)
{
recordable.second->SetStatus(code, description);
}
}
void SetName(nostd::string_view name) noexcept override
{
for (auto &recordable : recordables_)
{
recordable.second->SetName(name);
}
}
void SetTraceFlags(opentelemetry::trace::TraceFlags flags) noexcept override
{
for (auto &recordable : recordables_)
{
recordable.second->SetTraceFlags(flags);
}
}
void SetSpanKind(opentelemetry::trace::SpanKind span_kind) noexcept override
{
for (auto &recordable : recordables_)
{
recordable.second->SetSpanKind(span_kind);
}
}
void SetResource(const opentelemetry::sdk::resource::Resource &resource) noexcept override
{
for (auto &recordable : recordables_)
{
recordable.second->SetResource(resource);
}
}
void SetStartTime(opentelemetry::common::SystemTimestamp start_time) noexcept override
{
for (auto &recordable : recordables_)
{
recordable.second->SetStartTime(start_time);
}
}
void SetDuration(std::chrono::nanoseconds duration) noexcept override
{
for (auto &recordable : recordables_)
{
recordable.second->SetDuration(duration);
}
}
void SetInstrumentationScope(const InstrumentationScope &instrumentation_scope) noexcept override
{
for (auto &recordable : recordables_)
{
recordable.second->SetInstrumentationScope(instrumentation_scope);
}
}
private:
std::map<std::size_t, std::unique_ptr<Recordable>> recordables_;
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,188 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <chrono>
#include <memory>
#include <mutex>
#include <vector>
#include "opentelemetry/sdk/trace/multi_recordable.h"
#include "opentelemetry/sdk/trace/processor.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/** Instantiation options. */
struct MultiSpanProcessorOptions
{};
/**
* Span processor allow hooks for span start and end method invocations.
*
* Built-in span processors are responsible for batching and conversion of
* spans to exportable representation and passing batches to exporters.
*/
class MultiSpanProcessor : public SpanProcessor
{
public:
MultiSpanProcessor(std::vector<std::unique_ptr<SpanProcessor>> &&processors)
: head_(nullptr), tail_(nullptr), count_(0)
{
for (auto &processor : processors)
{
AddProcessor(std::move(processor));
}
}
void AddProcessor(std::unique_ptr<SpanProcessor> &&processor)
{
// Add preocessor to end of the list.
if (processor)
{
ProcessorNode *pNode = new ProcessorNode(std::move(processor), tail_);
if (count_ > 0)
{
tail_->next_ = pNode;
tail_ = pNode;
}
else
{
head_ = tail_ = pNode;
}
count_++;
}
}
std::unique_ptr<Recordable> MakeRecordable() noexcept override
{
auto recordable = std::unique_ptr<Recordable>(new MultiRecordable);
auto multi_recordable = static_cast<MultiRecordable *>(recordable.get());
ProcessorNode *node = head_;
while (node != nullptr)
{
auto processor = node->value_.get();
multi_recordable->AddRecordable(*processor, processor->MakeRecordable());
node = node->next_;
}
return recordable;
}
virtual void OnStart(Recordable &span,
const opentelemetry::trace::SpanContext &parent_context) noexcept override
{
auto multi_recordable = static_cast<MultiRecordable *>(&span);
ProcessorNode *node = head_;
while (node != nullptr)
{
auto processor = node->value_.get();
auto &recordable = multi_recordable->GetRecordable(*processor);
if (recordable != nullptr)
{
processor->OnStart(*recordable, parent_context);
}
node = node->next_;
}
}
virtual void OnEnd(std::unique_ptr<Recordable> &&span) noexcept override
{
auto multi_recordable = static_cast<MultiRecordable *>(span.release());
ProcessorNode *node = head_;
while (node != nullptr)
{
auto processor = node->value_.get();
auto recordable = multi_recordable->ReleaseRecordable(*processor);
if (recordable != nullptr)
{
processor->OnEnd(std::move(recordable));
}
node = node->next_;
}
delete multi_recordable;
}
bool ForceFlush(
std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept override
{
bool result = true;
ProcessorNode *node = head_;
while (node != nullptr)
{
auto processor = node->value_.get();
result |= processor->ForceFlush(timeout);
node = node->next_;
}
return result;
}
bool Shutdown(
std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept override
{
bool result = true;
ProcessorNode *node = head_;
while (node != nullptr)
{
auto processor = node->value_.get();
result |= processor->Shutdown(timeout);
node = node->next_;
}
return result;
}
~MultiSpanProcessor() override
{
Shutdown();
Cleanup();
}
private:
struct ProcessorNode
{
std::unique_ptr<SpanProcessor> value_;
ProcessorNode *next_, *prev_;
ProcessorNode(std::unique_ptr<SpanProcessor> &&value,
ProcessorNode *prev = nullptr,
ProcessorNode *next = nullptr)
: value_(std::move(value)), next_(next), prev_(prev)
{}
};
void Cleanup()
{
if (count_)
{
ProcessorNode *node = tail_;
while (node != nullptr)
{
if (node->next_ != nullptr)
{
delete node->next_;
node->next_ = nullptr;
}
if (node->prev_ != nullptr)
{
node = node->prev_;
}
else
{
delete node;
node = nullptr;
}
}
head_ = tail_ = nullptr;
count_ = 0;
}
}
ProcessorNode *head_, *tail_;
size_t count_;
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,78 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <chrono>
#include <memory>
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
class SpanContext;
} // namespace trace
namespace sdk
{
namespace trace
{
class Recordable;
/**
* Span processor allow hooks for span start and end method invocations.
*
* Built-in span processors are responsible for batching and conversion of
* spans to exportable representation and passing batches to exporters.
*/
class OPENTELEMETRY_EXPORT SpanProcessor
{
public:
virtual ~SpanProcessor() = default;
/**
* Create a span recordable. This requests a new span recordable from the
* associated exporter.
* @return a newly initialized recordable
*
* Note: This method must be callable from multiple threads.
*/
virtual std::unique_ptr<Recordable> MakeRecordable() noexcept = 0;
/**
* OnStart is called when a span is started.
* @param span a recordable for a span that was just started
* @param parent_context The parent context of the span that just started
*/
virtual void OnStart(Recordable &span,
const opentelemetry::trace::SpanContext &parent_context) noexcept = 0;
/**
* OnEnd is called when a span is ended.
* @param span a recordable for a span that was ended
*/
virtual void OnEnd(std::unique_ptr<Recordable> &&span) noexcept = 0;
/**
* Export all ended spans that have not yet been exported.
* @param timeout an optional timeout, the default timeout of 0 means that no
* timeout is applied.
*/
virtual bool ForceFlush(
std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept = 0;
/**
* Shut down the processor and do any cleanup required. Ended spans are
* exported before shutdown. After the call to Shutdown, subsequent calls to
* OnStart, OnEnd, ForceFlush or Shutdown will return immediately without
* doing anything.
* @param timeout an optional timeout, the default timeout of 0 means that no
* timeout is applied.
*/
virtual bool Shutdown(
std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept = 0;
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,29 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/sdk/trace/id_generator.h"
#include "opentelemetry/trace/span_id.h"
#include "opentelemetry/trace/trace_id.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
class RandomIdGenerator : public IdGenerator
{
public:
RandomIdGenerator() : IdGenerator(true) {}
opentelemetry::trace::SpanId GenerateSpanId() noexcept override;
opentelemetry::trace::TraceId GenerateTraceId() noexcept override;
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,31 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <memory>
#include "opentelemetry/sdk/trace/id_generator.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/**
* Factory class for RandomIdGenerator.
*/
class RandomIdGeneratorFactory
{
public:
/**
* Create a RandomIdGenerator.
*/
static std::unique_ptr<IdGenerator> Create();
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,191 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <chrono>
#include "opentelemetry/common/attribute_value.h"
#include "opentelemetry/common/timestamp.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/sdk/common/empty_attributes.h"
#include "opentelemetry/sdk/instrumentationscope/instrumentation_scope.h"
#include "opentelemetry/trace/span_context.h"
#include "opentelemetry/trace/span_id.h"
#include "opentelemetry/trace/span_metadata.h"
#include "opentelemetry/version.h"
// TODO: Create generic short pattern for opentelemetry::common and opentelemetry::trace
OPENTELEMETRY_BEGIN_NAMESPACE
namespace common
{
class KeyValueIterable;
} // namespace common
namespace sdk
{
namespace resource
{
class Resource;
} // namespace resource
namespace trace
{
using namespace opentelemetry::sdk::instrumentationscope;
class SpanData;
/**
* Maintains a representation of a span in a format that can be processed by a recorder.
*
* This class is thread-compatible.
*/
class Recordable
{
public:
virtual ~Recordable() = default;
/**
* Set the span context and parent span id
* @param span_context the span context to set
* @param parent_span_id the parent span id to set
*/
virtual void SetIdentity(const opentelemetry::trace::SpanContext &span_context,
opentelemetry::trace::SpanId parent_span_id) noexcept = 0;
/**
* Set an attribute of a span.
* @param name the name of the attribute
* @param value the attribute value
*/
virtual void SetAttribute(nostd::string_view key,
const opentelemetry::common::AttributeValue &value) noexcept = 0;
/**
* Add an event to a span.
* @param name the name of the event
* @param timestamp the timestamp of the event
* @param attributes the attributes associated with the event
*/
virtual void AddEvent(nostd::string_view name,
opentelemetry::common::SystemTimestamp timestamp,
const opentelemetry::common::KeyValueIterable &attributes) noexcept = 0;
/**
* Add an event to a span with default timestamp and attributes.
* @param name the name of the event
*/
void AddEvent(nostd::string_view name)
{
AddEvent(name, opentelemetry::common::SystemTimestamp(std::chrono::system_clock::now()),
opentelemetry::sdk::GetEmptyAttributes());
}
/**
* Add an event to a span with default (empty) attributes.
* @param name the name of the event
* @param timestamp the timestamp of the event
*/
void AddEvent(nostd::string_view name, opentelemetry::common::SystemTimestamp timestamp)
{
AddEvent(name, timestamp, opentelemetry::sdk::GetEmptyAttributes());
}
/**
* Add an event to a span.
* @param name the name of the event
* @param attributes the attributes associated with the event
*/
void AddEvent(nostd::string_view name,
const opentelemetry::common::KeyValueIterable &attributes) noexcept
{
AddEvent(name, opentelemetry::common::SystemTimestamp(std::chrono::system_clock::now()),
attributes);
}
/**
* Add a link to a span.
* @param span_context the span context of the linked span
* @param attributes the attributes associated with the link
*/
virtual void AddLink(const opentelemetry::trace::SpanContext &span_context,
const opentelemetry::common::KeyValueIterable &attributes) noexcept = 0;
/**
* Add a link to a span with default (empty) attributes.
* @param span_context the span context of the linked span
*/
void AddLink(opentelemetry::trace::SpanContext span_context)
{
AddLink(span_context, opentelemetry::sdk::GetEmptyAttributes());
}
/**
* Set the status of the span.
* @param code the status code
* @param description a description of the status
*/
virtual void SetStatus(opentelemetry::trace::StatusCode code,
nostd::string_view description) noexcept = 0;
/**
* Set the name of the span.
* @param name the name to set
*/
virtual void SetName(nostd::string_view name) noexcept = 0;
/**
* Set the trace flags of the span.
* @param flags the flags to set
*/
virtual void SetTraceFlags(opentelemetry::trace::TraceFlags /* flags */) noexcept {}
/**
* Set the spankind of the span.
* @param span_kind the spankind to set
*/
virtual void SetSpanKind(opentelemetry::trace::SpanKind span_kind) noexcept = 0;
/**
* Set Resource of the span
* @param Resource the resource to set
*/
virtual void SetResource(const opentelemetry::sdk::resource::Resource &resource) noexcept = 0;
/**
* Set the start time of the span.
* @param start_time the start time to set
*/
virtual void SetStartTime(opentelemetry::common::SystemTimestamp start_time) noexcept = 0;
/**
* Set the duration of the span.
* @param duration the duration to set
*/
virtual void SetDuration(std::chrono::nanoseconds duration) noexcept = 0;
/**
* Get the SpanData object for this Recordable.
*
* @return SpanData*
*/
virtual explicit operator SpanData *() const { return nullptr; }
/**
* Set the instrumentation scope of the span.
* @param instrumentation_scope the instrumentation scope to set
*/
virtual void SetInstrumentationScope(
const InstrumentationScope &instrumentation_scope) noexcept = 0;
OPENTELEMETRY_DEPRECATED_MESSAGE("Please use SetInstrumentationScope instead")
void SetInstrumentationLibrary(const InstrumentationScope &instrumentation_scope) noexcept
{
SetInstrumentationScope(instrumentation_scope);
}
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,108 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <map>
#include <memory>
#include <string>
#include "opentelemetry/common/attribute_value.h"
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/trace/span_metadata.h"
#include "opentelemetry/trace/trace_id.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace common
{
class KeyValueIterable;
} // namespace common
namespace trace
{
class SpanContext;
class SpanContextKeyValueIterable;
class TraceState;
} // namespace trace
namespace sdk
{
namespace trace
{
/**
* A sampling Decision for a Span to be created.
*/
enum class Decision
{
// IsRecording() == false, span will not be recorded and all events and attributes will be
// dropped.
DROP,
// IsRecording() == true, but Sampled flag MUST NOT be set.
RECORD_ONLY,
// IsRecording() == true AND Sampled flag` MUST be set.
RECORD_AND_SAMPLE
};
/**
* The output of ShouldSample.
* It contains a sampling Decision and a set of Span Attributes.
*/
struct SamplingResult
{
Decision decision;
// A set of span Attributes that will also be added to the Span. Can be nullptr.
std::unique_ptr<const std::map<std::string, opentelemetry::common::AttributeValue>> attributes;
// The tracestate used by the span.
nostd::shared_ptr<opentelemetry::trace::TraceState> trace_state;
inline bool IsRecording()
{
return decision == Decision::RECORD_ONLY || decision == Decision::RECORD_AND_SAMPLE;
}
inline bool IsSampled() { return decision == Decision::RECORD_AND_SAMPLE; }
};
/**
* The Sampler interface allows users to create custom samplers which will return a
* SamplingResult based on information that is typically available just before the Span was created.
*/
class Sampler
{
public:
virtual ~Sampler() = default;
/**
* Called during Span creation to make a sampling decision.
*
* @param parent_context a const reference to the SpanContext of a parent Span.
* An invalid SpanContext if this is a root span.
* @param trace_id the TraceId for the new Span. This will be identical to that in
* the parentContext, unless this is a root span.
* @param name the name of the new Span.
* @param spanKind the opentelemetry::trace::SpanKind of the Span.
* @param attributes list of AttributeValue with their keys.
* @param links Collection of links that will be associated with the Span to be created.
* @return sampling result whether span should be sampled or not.
* @since 0.1.0
*/
virtual SamplingResult ShouldSample(
const opentelemetry::trace::SpanContext &parent_context,
opentelemetry::trace::TraceId trace_id,
nostd::string_view name,
opentelemetry::trace::SpanKind span_kind,
const opentelemetry::common::KeyValueIterable &attributes,
const opentelemetry::trace::SpanContextKeyValueIterable &links) noexcept = 0;
/**
* Returns the sampler name or short description with the configuration.
* This may be displayed on debug pages or in the logs.
*
* @return the description of this Sampler.
*/
virtual nostd::string_view GetDescription() const noexcept = 0;
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,62 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/sdk/trace/sampler.h"
#include "opentelemetry/trace/span_context.h"
#include "opentelemetry/trace/span_metadata.h"
#include "opentelemetry/trace/trace_id.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace common
{
class KeyValueIterable;
} // namespace common
namespace trace
{
class SpanContextKeyValueIterable;
} // namespace trace
namespace sdk
{
namespace trace
{
/**
* The always on sampler is a default sampler which always return Decision::RECORD_AND_SAMPLE
*/
class AlwaysOnSampler : public Sampler
{
public:
/**
* @return Always return Decision RECORD_AND_SAMPLE
*/
inline SamplingResult ShouldSample(
const opentelemetry::trace::SpanContext &parent_context,
opentelemetry::trace::TraceId /*trace_id*/,
nostd::string_view /*name*/,
opentelemetry::trace::SpanKind /*span_kind*/,
const opentelemetry::common::KeyValueIterable & /*attributes*/,
const opentelemetry::trace::SpanContextKeyValueIterable & /*links*/) noexcept override
{
if (!parent_context.IsValid())
{
return {Decision::RECORD_AND_SAMPLE, nullptr, opentelemetry::trace::TraceState::GetDefault()};
}
else
{
return {Decision::RECORD_AND_SAMPLE, nullptr, parent_context.trace_state()};
}
}
/**
* @return Description MUST be AlwaysOnSampler
*/
inline nostd::string_view GetDescription() const noexcept override { return "AlwaysOnSampler"; }
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,31 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <memory>
#include "opentelemetry/sdk/trace/sampler.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/**
* Factory class for AlwaysOnSampler.
*/
class AlwaysOnSamplerFactory
{
public:
/**
* Create an AlwaysOnSampler.
*/
static std::unique_ptr<Sampler> Create();
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,102 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <atomic>
#include <chrono>
#include <memory>
#include <mutex>
#include <utility>
#include "opentelemetry/common/spin_lock_mutex.h"
#include "opentelemetry/nostd/span.h"
#include "opentelemetry/sdk/common/exporter_utils.h"
#include "opentelemetry/sdk/trace/exporter.h"
#include "opentelemetry/sdk/trace/processor.h"
#include "opentelemetry/sdk/trace/recordable.h"
#include "opentelemetry/trace/span_context.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/**
* The simple span processor passes finished recordables to the configured
* SpanExporter, as soon as they are finished.
*
* OnEnd and ForceFlush are no-ops.
*
* All calls to the configured SpanExporter are synchronized using a
* spin-lock on an atomic_flag.
*/
class SimpleSpanProcessor : public SpanProcessor
{
public:
/**
* Initialize a simple span processor.
* @param exporter the exporter used by the span processor
*/
explicit SimpleSpanProcessor(std::unique_ptr<SpanExporter> &&exporter) noexcept
: exporter_(std::move(exporter))
{}
std::unique_ptr<Recordable> MakeRecordable() noexcept override
{
return exporter_->MakeRecordable();
}
void OnStart(Recordable & /* span */,
const opentelemetry::trace::SpanContext & /* parent_context */) noexcept override
{}
void OnEnd(std::unique_ptr<Recordable> &&span) noexcept override
{
nostd::span<std::unique_ptr<Recordable>> batch(&span, 1);
const std::lock_guard<opentelemetry::common::SpinLockMutex> locked(lock_);
if (exporter_->Export(batch) == sdk::common::ExportResult::kFailure)
{
/* Once it is defined how the SDK does logging, an error should be
* logged in this case. */
}
}
bool ForceFlush(
std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept override
{
if (exporter_ != nullptr)
{
return exporter_->ForceFlush(timeout);
}
return true;
}
bool Shutdown(
std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept override
{
// We only call shutdown ONCE.
if (exporter_ != nullptr && !shutdown_latch_.test_and_set(std::memory_order_acquire))
{
return exporter_->Shutdown(timeout);
}
return true;
}
~SimpleSpanProcessor() override { Shutdown(); }
private:
std::unique_ptr<SpanExporter> exporter_;
opentelemetry::common::SpinLockMutex lock_;
#if defined(__cpp_lib_atomic_value_initialization) && \
__cpp_lib_atomic_value_initialization >= 201911L
std::atomic_flag shutdown_latch_{};
#else
std::atomic_flag shutdown_latch_ = ATOMIC_FLAG_INIT;
#endif
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,32 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <memory>
#include "opentelemetry/sdk/trace/exporter.h"
#include "opentelemetry/sdk/trace/processor.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/**
* Factory class for SimpleSpanProcessor.
*/
class OPENTELEMETRY_EXPORT SimpleSpanProcessorFactory
{
public:
/**
* Create a SimpleSpanProcessor.
*/
static std::unique_ptr<SpanProcessor> Create(std::unique_ptr<SpanExporter> &&exporter);
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,328 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <chrono>
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "opentelemetry/common/attribute_value.h"
#include "opentelemetry/common/key_value_iterable.h"
#include "opentelemetry/common/key_value_iterable_view.h"
#include "opentelemetry/common/timestamp.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/sdk/common/attribute_utils.h"
#include "opentelemetry/sdk/instrumentationscope/instrumentation_scope.h"
#include "opentelemetry/sdk/resource/resource.h"
#include "opentelemetry/sdk/trace/recordable.h"
#include "opentelemetry/trace/span_context.h"
#include "opentelemetry/trace/span_id.h"
#include "opentelemetry/trace/span_metadata.h"
#include "opentelemetry/trace/trace_flags.h"
#include "opentelemetry/trace/trace_id.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/**
* Class for storing events in SpanData.
*/
class SpanDataEvent
{
public:
SpanDataEvent(std::string name,
opentelemetry::common::SystemTimestamp timestamp,
const opentelemetry::common::KeyValueIterable &attributes)
: name_(name), timestamp_(timestamp), attribute_map_(attributes)
{}
/**
* Get the name for this event
* @return the name for this event
*/
std::string GetName() const noexcept { return name_; }
/**
* Get the timestamp for this event
* @return the timestamp for this event
*/
opentelemetry::common::SystemTimestamp GetTimestamp() const noexcept { return timestamp_; }
/**
* Get the attributes for this event
* @return the attributes for this event
*/
const std::unordered_map<std::string, opentelemetry::sdk::common::OwnedAttributeValue> &
GetAttributes() const noexcept
{
return attribute_map_.GetAttributes();
}
private:
std::string name_;
opentelemetry::common::SystemTimestamp timestamp_;
opentelemetry::sdk::common::AttributeMap attribute_map_;
};
/**
* Class for storing links in SpanData.
*/
class SpanDataLink
{
public:
SpanDataLink(opentelemetry::trace::SpanContext span_context,
const opentelemetry::common::KeyValueIterable &attributes)
: span_context_(span_context), attribute_map_(attributes)
{}
/**
* Get the attributes for this link
* @return the attributes for this link
*/
const std::unordered_map<std::string, opentelemetry::sdk::common::OwnedAttributeValue> &
GetAttributes() const noexcept
{
return attribute_map_.GetAttributes();
}
/**
* Get the span context for this link
* @return the span context for this link
*/
const opentelemetry::trace::SpanContext &GetSpanContext() const noexcept { return span_context_; }
private:
opentelemetry::trace::SpanContext span_context_;
opentelemetry::sdk::common::AttributeMap attribute_map_;
};
/**
* SpanData is a representation of all data collected by a span.
*/
class SpanData final : public Recordable
{
public:
SpanData() : resource_{nullptr}, instrumentation_scope_{nullptr} {}
/**
* Get the trace id for this span
* @return the trace id for this span
*/
opentelemetry::trace::TraceId GetTraceId() const noexcept { return span_context_.trace_id(); }
/**
* Get the span id for this span
* @return the span id for this span
*/
opentelemetry::trace::SpanId GetSpanId() const noexcept { return span_context_.span_id(); }
/**
* Get the span context for this span
* @return the span context for this span
*/
const opentelemetry::trace::SpanContext &GetSpanContext() const noexcept { return span_context_; }
/**
* Get the parent span id for this span
* @return the span id for this span's parent
*/
opentelemetry::trace::SpanId GetParentSpanId() const noexcept { return parent_span_id_; }
/**
* Get the name for this span
* @return the name for this span
*/
opentelemetry::nostd::string_view GetName() const noexcept { return name_; }
/**
* Get the trace flags for this span
* @return the trace flags for this span
*/
opentelemetry::trace::TraceFlags GetFlags() const noexcept { return flags_; }
/**
* Get the kind of this span
* @return the kind of this span
*/
opentelemetry::trace::SpanKind GetSpanKind() const noexcept { return span_kind_; }
/**
* Get the status for this span
* @return the status for this span
*/
opentelemetry::trace::StatusCode GetStatus() const noexcept { return status_code_; }
/**
* Get the status description for this span
* @return the description of the the status of this span
*/
opentelemetry::nostd::string_view GetDescription() const noexcept { return status_desc_; }
/**
* Get the attributes associated with the resource
* @returns the attributes associated with the resource configured for TracerProvider
*/
const opentelemetry::sdk::resource::Resource &GetResource() const noexcept
{
if (resource_ == nullptr)
{
// this shouldn't happen as TraceProvider provides default resources
static opentelemetry::sdk::resource::Resource resource =
opentelemetry::sdk::resource::Resource::GetEmpty();
return resource;
}
return *resource_;
}
/**
* Get the attributes associated with the resource
* @returns the attributes associated with the resource configured for TracerProvider
*/
const opentelemetry::sdk::trace::InstrumentationScope &GetInstrumentationScope() const noexcept
{
if (instrumentation_scope_ == nullptr)
{
// this shouldn't happen as Tracer ensures there is valid default instrumentation scope.
static std::unique_ptr<opentelemetry::sdk::instrumentationscope::InstrumentationScope>
instrumentation_scope =
opentelemetry::sdk::instrumentationscope::InstrumentationScope::Create(
"unknown_service");
return *instrumentation_scope;
}
return *instrumentation_scope_;
}
OPENTELEMETRY_DEPRECATED_MESSAGE("Please use GetInstrumentationScope instead")
const opentelemetry::sdk::trace::InstrumentationScope &GetInstrumentationLibrary() const noexcept
{
return GetInstrumentationScope();
}
/**
* Get the start time for this span
* @return the start time for this span
*/
opentelemetry::common::SystemTimestamp GetStartTime() const noexcept { return start_time_; }
/**
* Get the duration for this span
* @return the duration for this span
*/
std::chrono::nanoseconds GetDuration() const noexcept { return duration_; }
/**
* Get the attributes for this span
* @return the attributes for this span
*/
const std::unordered_map<std::string, opentelemetry::sdk::common::OwnedAttributeValue> &
GetAttributes() const noexcept
{
return attribute_map_.GetAttributes();
}
/**
* Get the events associated with this span
* @return the events associated with this span
*/
const std::vector<SpanDataEvent> &GetEvents() const noexcept { return events_; }
/**
* Get the links associated with this span
* @return the links associated with this span
*/
const std::vector<SpanDataLink> &GetLinks() const noexcept { return links_; }
void SetIdentity(const opentelemetry::trace::SpanContext &span_context,
opentelemetry::trace::SpanId parent_span_id) noexcept override
{
span_context_ = span_context;
parent_span_id_ = parent_span_id;
}
void SetAttribute(nostd::string_view key,
const opentelemetry::common::AttributeValue &value) noexcept override
{
attribute_map_.SetAttribute(key, value);
}
void AddEvent(nostd::string_view name,
opentelemetry::common::SystemTimestamp timestamp =
opentelemetry::common::SystemTimestamp(std::chrono::system_clock::now()),
const opentelemetry::common::KeyValueIterable &attributes =
opentelemetry::common::KeyValueIterableView<std::map<std::string, int32_t>>(
{})) noexcept override
{
SpanDataEvent event(std::string(name), timestamp, attributes);
events_.push_back(event);
}
void AddLink(const opentelemetry::trace::SpanContext &span_context,
const opentelemetry::common::KeyValueIterable &attributes) noexcept override
{
SpanDataLink link(span_context, attributes);
links_.push_back(link);
}
void SetStatus(opentelemetry::trace::StatusCode code,
nostd::string_view description) noexcept override
{
status_code_ = code;
status_desc_ = std::string(description);
}
void SetName(nostd::string_view name) noexcept override
{
name_ = std::string(name.data(), name.length());
}
void SetTraceFlags(opentelemetry::trace::TraceFlags flags) noexcept override { flags_ = flags; }
void SetSpanKind(opentelemetry::trace::SpanKind span_kind) noexcept override
{
span_kind_ = span_kind;
}
void SetResource(const opentelemetry::sdk::resource::Resource &resource) noexcept override
{
resource_ = &resource;
}
void SetStartTime(opentelemetry::common::SystemTimestamp start_time) noexcept override
{
start_time_ = start_time;
}
void SetDuration(std::chrono::nanoseconds duration) noexcept override { duration_ = duration; }
void SetInstrumentationScope(const InstrumentationScope &instrumentation_scope) noexcept override
{
instrumentation_scope_ = &instrumentation_scope;
}
private:
opentelemetry::trace::SpanContext span_context_{false, false};
opentelemetry::trace::SpanId parent_span_id_;
opentelemetry::common::SystemTimestamp start_time_;
std::chrono::nanoseconds duration_{0};
std::string name_;
opentelemetry::trace::StatusCode status_code_{opentelemetry::trace::StatusCode::kUnset};
std::string status_desc_;
opentelemetry::sdk::common::AttributeMap attribute_map_;
std::vector<SpanDataEvent> events_;
std::vector<SpanDataLink> links_;
opentelemetry::trace::TraceFlags flags_;
opentelemetry::trace::SpanKind span_kind_{opentelemetry::trace::SpanKind::kInternal};
const opentelemetry::sdk::resource::Resource *resource_;
const InstrumentationScope *instrumentation_scope_;
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,111 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <stdint.h>
#include "opentelemetry/common/key_value_iterable.h"
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/sdk/instrumentationscope/instrumentation_scope.h"
#include "opentelemetry/sdk/resource/resource.h"
#include "opentelemetry/sdk/trace/id_generator.h"
#include "opentelemetry/sdk/trace/processor.h"
#include "opentelemetry/sdk/trace/sampler.h"
#include "opentelemetry/sdk/trace/tracer_context.h"
#include "opentelemetry/trace/span.h"
#include "opentelemetry/trace/span_context_kv_iterable.h"
#include "opentelemetry/trace/span_startoptions.h"
#include "opentelemetry/trace/tracer.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
using namespace opentelemetry::sdk::instrumentationscope;
class Tracer final : public opentelemetry::trace::Tracer,
public std::enable_shared_from_this<Tracer>
{
public:
/** Construct a new Tracer with the given context pipeline. */
explicit Tracer(std::shared_ptr<TracerContext> context,
std::unique_ptr<InstrumentationScope> instrumentation_scope =
InstrumentationScope::Create("")) noexcept;
nostd::shared_ptr<opentelemetry::trace::Span> StartSpan(
nostd::string_view name,
const opentelemetry::common::KeyValueIterable &attributes,
const opentelemetry::trace::SpanContextKeyValueIterable &links,
const opentelemetry::trace::StartSpanOptions &options = {}) noexcept override;
#if OPENTELEMETRY_ABI_VERSION_NO >= 2
/**
* Force any buffered spans to flush.
* @param timeout to complete the flush
*/
template <class Rep, class Period>
void ForceFlush(std::chrono::duration<Rep, Period> timeout) noexcept
{
this->ForceFlushWithMicroseconds(static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::microseconds>(timeout).count()));
}
void ForceFlushWithMicroseconds(uint64_t timeout) noexcept;
/**
* ForceFlush any buffered spans and stop reporting spans.
* @param timeout to complete the flush
*/
template <class Rep, class Period>
void Close(std::chrono::duration<Rep, Period> timeout) noexcept
{
this->CloseWithMicroseconds(static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::microseconds>(timeout).count()));
}
void CloseWithMicroseconds(uint64_t timeout) noexcept;
#else
/* Exposed in the API in ABI version 1, but does not belong to the API */
void ForceFlushWithMicroseconds(uint64_t timeout) noexcept override;
void CloseWithMicroseconds(uint64_t timeout) noexcept override;
#endif
/** Returns the configured span processor. */
SpanProcessor &GetProcessor() noexcept { return context_->GetProcessor(); }
/** Returns the configured Id generator */
IdGenerator &GetIdGenerator() const noexcept { return context_->GetIdGenerator(); }
/** Returns the associated instrumentation scope */
const InstrumentationScope &GetInstrumentationScope() const noexcept
{
return *instrumentation_scope_;
}
OPENTELEMETRY_DEPRECATED_MESSAGE("Please use GetInstrumentationScope instead")
const InstrumentationScope &GetInstrumentationLibrary() const noexcept
{
return GetInstrumentationScope();
}
/** Returns the currently configured resource **/
const opentelemetry::sdk::resource::Resource &GetResource() { return context_->GetResource(); }
// Note: Test only
Sampler &GetSampler() { return context_->GetSampler(); }
private:
// order of declaration is important here - instrumentation scope should destroy after
// tracer-context.
std::shared_ptr<InstrumentationScope> instrumentation_scope_;
std::shared_ptr<TracerContext> context_;
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,107 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <chrono>
#include <memory>
#include <vector>
#include "opentelemetry/sdk/resource/resource.h"
#include "opentelemetry/sdk/trace/id_generator.h"
#include "opentelemetry/sdk/trace/processor.h"
#include "opentelemetry/sdk/trace/random_id_generator.h"
#include "opentelemetry/sdk/trace/sampler.h"
#include "opentelemetry/sdk/trace/samplers/always_on.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/**
* A class which stores the TracerProvider context.
*
* This class meets the following design criteria:
* - A shared reference between TracerProvider and Tracers instantiated.
* - A thread-safe class that allows updating/altering processor/exporter pipelines
* and sampling config.
* - The owner/destroyer of Processors/Exporters. These will remain active until
* this class is destroyed. I.e. Sampling, Exporting, flushing, Custom Iterator etc. are all ok
* if this object is alive, and they will work together. If this object is destroyed, then no shared
* references to Processor, Exporter, Recordable, Custom Iterator etc. should exist, and all
* associated pipelines will have been flushed.
*/
class TracerContext
{
public:
explicit TracerContext(
std::vector<std::unique_ptr<SpanProcessor>> &&processor,
const opentelemetry::sdk::resource::Resource &resource =
opentelemetry::sdk::resource::Resource::Create({}),
std::unique_ptr<Sampler> sampler = std::unique_ptr<AlwaysOnSampler>(new AlwaysOnSampler),
std::unique_ptr<IdGenerator> id_generator =
std::unique_ptr<IdGenerator>(new RandomIdGenerator())) noexcept;
virtual ~TracerContext() = default;
/**
* Attaches a span processor to list of configured processors to this tracer context.
* Processor once attached can't be removed.
* @param processor The new span processor for this tracer. This must not be
* a nullptr. Ownership is given to the `TracerContext`.
*
* Note: This method is not thread safe.
*/
void AddProcessor(std::unique_ptr<SpanProcessor> processor) noexcept;
/**
* Obtain the sampler associated with this tracer.
* @return The sampler for this tracer.
*/
Sampler &GetSampler() const noexcept;
/**
* Obtain the configured (composite) processor.
*
* Note: When more than one processor is active, this will
* return an "aggregate" processor
*/
SpanProcessor &GetProcessor() const noexcept;
/**
* Obtain the resource associated with this tracer context.
* @return The resource for this tracer context.
*/
const opentelemetry::sdk::resource::Resource &GetResource() const noexcept;
/**
* Obtain the Id Generator associated with this tracer context.
* @return The ID Generator for this tracer context.
*/
opentelemetry::sdk::trace::IdGenerator &GetIdGenerator() const noexcept;
/**
* Force all active SpanProcessors to flush any buffered spans
* within the given timeout.
*/
bool ForceFlush(std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept;
/**
* Shutdown the span processor associated with this tracer provider.
*/
bool Shutdown(std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept;
private:
// order of declaration is important here - resource object should be destroyed after processor.
opentelemetry::sdk::resource::Resource resource_;
std::unique_ptr<Sampler> sampler_;
std::unique_ptr<IdGenerator> id_generator_;
std::unique_ptr<SpanProcessor> processor_;
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,61 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <memory>
#include <vector>
#include "opentelemetry/sdk/resource/resource.h"
#include "opentelemetry/sdk/trace/id_generator.h"
#include "opentelemetry/sdk/trace/processor.h"
#include "opentelemetry/sdk/trace/sampler.h"
#include "opentelemetry/sdk/trace/tracer_context.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/**
* Factory class for TracerContext.
*/
class OPENTELEMETRY_EXPORT TracerContextFactory
{
public:
/**
* Create a TracerContext.
*/
static std::unique_ptr<TracerContext> Create(
std::vector<std::unique_ptr<SpanProcessor>> &&processors);
/**
* Create a TracerContext.
*/
static std::unique_ptr<TracerContext> Create(
std::vector<std::unique_ptr<SpanProcessor>> &&processors,
const opentelemetry::sdk::resource::Resource &resource);
/**
* Create a TracerContext.
*/
static std::unique_ptr<TracerContext> Create(
std::vector<std::unique_ptr<SpanProcessor>> &&processors,
const opentelemetry::sdk::resource::Resource &resource,
std::unique_ptr<Sampler> sampler);
/**
* Create a TracerContext.
*/
static std::unique_ptr<TracerContext> Create(
std::vector<std::unique_ptr<SpanProcessor>> &&processors,
const opentelemetry::sdk::resource::Resource &resource,
std::unique_ptr<Sampler> sampler,
std::unique_ptr<IdGenerator> id_generator);
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,119 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <chrono>
#include <mutex>
#include <vector>
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/sdk/resource/resource.h"
#include "opentelemetry/sdk/trace/id_generator.h"
#include "opentelemetry/sdk/trace/processor.h"
#include "opentelemetry/sdk/trace/random_id_generator.h"
#include "opentelemetry/sdk/trace/sampler.h"
#include "opentelemetry/sdk/trace/samplers/always_on.h"
#include "opentelemetry/sdk/trace/tracer.h"
#include "opentelemetry/sdk/trace/tracer_context.h"
#include "opentelemetry/trace/tracer.h"
#include "opentelemetry/trace/tracer_provider.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
class OPENTELEMETRY_EXPORT TracerProvider final : public opentelemetry::trace::TracerProvider
{
public:
/**
* Initialize a new tracer provider with a specified sampler
* @param processor The span processor for this tracer provider. This must
* not be a nullptr.
* @param resource The resources for this tracer provider.
* @param sampler The sampler for this tracer provider. This must
* not be a nullptr.
* @param id_generator The custom id generator for this tracer provider. This must
* not be a nullptr
*/
explicit TracerProvider(
std::unique_ptr<SpanProcessor> processor,
const opentelemetry::sdk::resource::Resource &resource =
opentelemetry::sdk::resource::Resource::Create({}),
std::unique_ptr<Sampler> sampler = std::unique_ptr<AlwaysOnSampler>(new AlwaysOnSampler),
std::unique_ptr<IdGenerator> id_generator =
std::unique_ptr<IdGenerator>(new RandomIdGenerator())) noexcept;
explicit TracerProvider(
std::vector<std::unique_ptr<SpanProcessor>> &&processors,
const opentelemetry::sdk::resource::Resource &resource =
opentelemetry::sdk::resource::Resource::Create({}),
std::unique_ptr<Sampler> sampler = std::unique_ptr<AlwaysOnSampler>(new AlwaysOnSampler),
std::unique_ptr<IdGenerator> id_generator =
std::unique_ptr<IdGenerator>(new RandomIdGenerator())) noexcept;
/**
* Initialize a new tracer provider with a specified context
* @param context The owned tracer configuration/pipeline for this provider.
*/
explicit TracerProvider(std::unique_ptr<TracerContext> context) noexcept;
~TracerProvider() override;
/*
Make sure GetTracer() helpers from the API are seen in overload resolution.
*/
using opentelemetry::trace::TracerProvider::GetTracer;
#if OPENTELEMETRY_ABI_VERSION_NO >= 2
opentelemetry::nostd::shared_ptr<opentelemetry::trace::Tracer> GetTracer(
nostd::string_view name,
nostd::string_view version,
nostd::string_view schema_url,
const opentelemetry::common::KeyValueIterable *attributes) noexcept override;
#else
opentelemetry::nostd::shared_ptr<opentelemetry::trace::Tracer> GetTracer(
nostd::string_view name,
nostd::string_view version = "",
nostd::string_view schema_url = "") noexcept override;
#endif
/**
* Attaches a span processor to list of configured processors for this tracer provider.
* @param processor The new span processor for this tracer provider. This
* must not be a nullptr.
*
* Note: This process may not receive any in-flight spans, but will get newly created spans.
* Note: This method is not thread safe, and should ideally be called from main thread.
*/
void AddProcessor(std::unique_ptr<SpanProcessor> processor) noexcept;
/**
* Obtain the resource associated with this tracer provider.
* @return The resource for this tracer provider.
*/
const opentelemetry::sdk::resource::Resource &GetResource() const noexcept;
/**
* Shutdown the span processor associated with this tracer provider.
*/
bool Shutdown() noexcept;
/**
* Force flush the span processor associated with this tracer provider.
*/
bool ForceFlush(std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept;
private:
// order of declaration is important here - tracers should destroy only after context.
std::vector<std::shared_ptr<Tracer>> tracers_;
std::shared_ptr<TracerContext> context_;
std::mutex lock_;
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

View File

@@ -1,79 +0,0 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <memory>
#include <vector>
#include "opentelemetry/sdk/resource/resource.h"
#include "opentelemetry/sdk/trace/id_generator.h"
#include "opentelemetry/sdk/trace/processor.h"
#include "opentelemetry/sdk/trace/sampler.h"
#include "opentelemetry/sdk/trace/tracer_context.h"
#include "opentelemetry/sdk/trace/tracer_provider.h"
#include "opentelemetry/trace/tracer_provider.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{
/**
* Factory class for TracerProvider.
* See @ref TracerProvider.
*/
class OPENTELEMETRY_EXPORT TracerProviderFactory
{
public:
/* Serie of builders with a single processor. */
static std::unique_ptr<opentelemetry::sdk::trace::TracerProvider> Create(
std::unique_ptr<SpanProcessor> processor);
static std::unique_ptr<opentelemetry::sdk::trace::TracerProvider> Create(
std::unique_ptr<SpanProcessor> processor,
const opentelemetry::sdk::resource::Resource &resource);
static std::unique_ptr<opentelemetry::sdk::trace::TracerProvider> Create(
std::unique_ptr<SpanProcessor> processor,
const opentelemetry::sdk::resource::Resource &resource,
std::unique_ptr<Sampler> sampler);
static std::unique_ptr<opentelemetry::sdk::trace::TracerProvider> Create(
std::unique_ptr<SpanProcessor> processor,
const opentelemetry::sdk::resource::Resource &resource,
std::unique_ptr<Sampler> sampler,
std::unique_ptr<IdGenerator> id_generator);
/* Serie of builders with a vector of processor. */
static std::unique_ptr<opentelemetry::sdk::trace::TracerProvider> Create(
std::vector<std::unique_ptr<SpanProcessor>> &&processors);
static std::unique_ptr<opentelemetry::sdk::trace::TracerProvider> Create(
std::vector<std::unique_ptr<SpanProcessor>> &&processors,
const opentelemetry::sdk::resource::Resource &resource);
static std::unique_ptr<opentelemetry::sdk::trace::TracerProvider> Create(
std::vector<std::unique_ptr<SpanProcessor>> &&processors,
const opentelemetry::sdk::resource::Resource &resource,
std::unique_ptr<Sampler> sampler);
static std::unique_ptr<opentelemetry::sdk::trace::TracerProvider> Create(
std::vector<std::unique_ptr<SpanProcessor>> &&processors,
const opentelemetry::sdk::resource::Resource &resource,
std::unique_ptr<Sampler> sampler,
std::unique_ptr<IdGenerator> id_generator);
/* Create with a tracer context. */
static std::unique_ptr<opentelemetry::sdk::trace::TracerProvider> Create(
std::unique_ptr<TracerContext> context);
};
} // namespace trace
} // namespace sdk
OPENTELEMETRY_END_NAMESPACE

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