factory.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. #pragma once
  4. #include <memory>
  5. #include <string>
  6. #include "opentelemetry/plugin/detail/utility.h" // IWYU pragma: export
  7. #include "opentelemetry/plugin/tracer.h"
  8. #include "opentelemetry/version.h"
  9. OPENTELEMETRY_BEGIN_NAMESPACE
  10. namespace plugin
  11. {
  12. /**
  13. * Factory creates OpenTelemetry objects from configuration strings.
  14. */
  15. class Factory final
  16. {
  17. public:
  18. class FactoryImpl
  19. {
  20. public:
  21. virtual ~FactoryImpl() {}
  22. virtual nostd::unique_ptr<TracerHandle> MakeTracerHandle(
  23. nostd::string_view tracer_config,
  24. nostd::unique_ptr<char[]> &error_message) const noexcept = 0;
  25. };
  26. Factory(std::shared_ptr<DynamicLibraryHandle> library_handle,
  27. std::unique_ptr<FactoryImpl> &&factory_impl) noexcept
  28. : library_handle_{std::move(library_handle)}, factory_impl_{std::move(factory_impl)}
  29. {}
  30. /**
  31. * Construct a tracer from a configuration string.
  32. * @param tracer_config a representation of the tracer's config as a string.
  33. * @param error_message on failure this will contain an error message.
  34. * @return a Tracer on success or nullptr on failure.
  35. */
  36. std::shared_ptr<trace::Tracer> MakeTracer(nostd::string_view tracer_config,
  37. std::string &error_message) const noexcept
  38. {
  39. nostd::unique_ptr<char[]> plugin_error_message;
  40. auto tracer_handle = factory_impl_->MakeTracerHandle(tracer_config, plugin_error_message);
  41. if (tracer_handle == nullptr)
  42. {
  43. detail::CopyErrorMessage(plugin_error_message.get(), error_message);
  44. return nullptr;
  45. }
  46. return std::shared_ptr<trace::Tracer>{new (std::nothrow)
  47. Tracer{library_handle_, std::move(tracer_handle)}};
  48. }
  49. private:
  50. // Note: The order is important here.
  51. //
  52. // It's undefined behavior to close the library while a loaded FactoryImpl is still active.
  53. std::shared_ptr<DynamicLibraryHandle> library_handle_;
  54. std::unique_ptr<FactoryImpl> factory_impl_;
  55. };
  56. } // namespace plugin
  57. OPENTELEMETRY_END_NAMESPACE