├── .github └── workflows │ ├── security-audit.yml │ └── tests.yml ├── .gitignore ├── CONTRIBUTING.md ├── COPYRIGHT.md ├── Cargo.toml ├── LICENSE ├── README.md ├── SECURITY.md ├── docs └── img │ └── gcloud-example.png ├── examples ├── enable-exporter.rs └── tracing-exporter.rs ├── renovate.json └── src ├── errors.rs ├── google_trace_exporter_client.rs ├── lib.rs └── span_exporter.rs /.github/workflows/security-audit.yml: -------------------------------------------------------------------------------- 1 | name: security audit 2 | on: 3 | push: 4 | paths: 5 | - '**/Cargo.toml' 6 | - '**/Cargo.lock' 7 | schedule: 8 | - cron: '5 4 * * 6' 9 | jobs: 10 | security_audit: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: actions-rs/toolchain@v1 15 | with: 16 | profile: minimal 17 | toolchain: stable 18 | components: rustfmt, clippy 19 | - run: cargo install cargo-audit && cargo audit || true && cargo audit --ignore RUSTSEC-2020-0159 --ignore RUSTSEC-2020-0071 20 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: tests & formatting 2 | on: 3 | push: 4 | pull_request: 5 | types: [opened] 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v4 11 | - uses: actions-rs/toolchain@v1 12 | with: 13 | profile: minimal 14 | toolchain: stable 15 | components: rustfmt, clippy 16 | - run: cargo fmt -- --check && cargo clippy -- -Dwarnings && cargo test 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | Cargo.lock 3 | **/*.rs.bk 4 | .idea/ 5 | *.tmp 6 | *.orig 7 | *.swp 8 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Welcome! Please read this document to understand what you can do: 4 | * [Analyze Issues](#analyze-issues) 5 | * [Report an Issue](#report-an-issue) 6 | * [Contribute Code](#contribute-code) 7 | 8 | ## Analyze Issues 9 | 10 | Analyzing issue reports can be a lot of effort. Any help is welcome! 11 | Go to the GitHub issue tracker and find an open issue which needs additional work or a bugfix (e.g. issues labeled with "help wanted" or "bug"). 12 | Additional work could include any further information, or a gist, or it might be a hint that helps understanding the issue. 13 | 14 | ## Report an Issue 15 | 16 | If you find a bug - you are welcome to report it. 17 | You can go to the GitHub issue tracker to report the issue. 18 | 19 | ### Quick Checklist for Bug Reports 20 | 21 | Issue report checklist: 22 | * Real, current bug for the latest/supported version 23 | * No duplicate 24 | * Reproducible 25 | * Minimal example 26 | 27 | ### Issue handling process 28 | 29 | When an issue is reported, a committer will look at it and either confirm it as a real issue, close it if it is not an issue, or ask for more details. 30 | An issue that is about a real bug is closed as soon as the fix is committed. 31 | 32 | 33 | ### Reporting Security Issues 34 | 35 | If you find or suspect a security issue, please act responsibly and do not report it in the public issue tracker, but directly to us, so we can fix it before it can be exploited. 36 | For details please check our [Security policy](SECURITY.md). 37 | 38 | ## Contribute Code 39 | 40 | You are welcome to contribute code in order to fix bugs or to implement new features. 41 | 42 | There are three important things to know: 43 | 44 | 1. You must be aware of the Apache License (which describes contributions) and **agree to the Contributors License Agreement**. This is common practice in all major Open Source projects. 45 | For company contributors special rules apply. See the respective section below for details. 46 | 2. **Not all proposed contributions can be accepted**. Some features may e.g. just fit a third-party add-on better. The code must fit the overall direction and really improve it. The more effort you invest, the better you should clarify in advance whether the contribution fits: the best way would be to just open an issue to discuss the feature you plan to implement (make it clear you intend to contribute). 47 | 48 | ### Contributor License Agreement 49 | 50 | When you contribute (code, documentation, or anything else), you have to be aware that your contribution is covered by the same [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). 51 | 52 | This applies to all contributors, including those contributing on behalf of a company. 53 | 54 | ### Contribution Content Guidelines 55 | 56 | These are some of the rules we try to follow: 57 | 58 | - Apply a clean coding style adapted to the surrounding code, even though we are aware the existing code is not fully clean 59 | - Use variable naming conventions like in the other files you are seeing 60 | - No println() - use logging service if needed 61 | - Comment your code where it gets non-trivial 62 | - Keep an eye on performance and memory consumption, properly destroy objects when not used anymore 63 | - Avoid incompatible changes if possible, especially do not modify the name or behavior of public API methods or properties 64 | 65 | ### How to contribute - the Process 66 | 67 | 1. Make sure the change would be welcome (e.g. a bugfix or a useful feature); best do so by proposing it in a GitHub issue 68 | 2. Create a branch forking the cla-assistant repository and do your change 69 | 3. Commit and push your changes on that branch 70 | 4. In the commit message 71 | - Describe the problem you fix with this change. 72 | - Describe the effect that this change has from a user's point of view. App crashes and lockups are pretty convincing for example, but not all bugs are that obvious and should be mentioned in the text. 73 | - Describe the technical details of what you changed. It is important to describe the change in a most understandable way so the reviewer is able to verify that the code is behaving as you intend it to. 74 | 5. Create a Pull Request 75 | 6. Once the change has been approved we will inform you in a comment 76 | 7. We will close the pull request, feel free to delete the now obsolete branch 77 | -------------------------------------------------------------------------------- /COPYRIGHT.md: -------------------------------------------------------------------------------- 1 | Copyright 2022 Abdulla Abdurakhmanov (me@abdolence.dev) 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "opentelemetry-gcloud-trace" 3 | version = "0.20.0" 4 | authors = ["Abdulla Abdurakhmanov "] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | description = "OpenTelemetry support for Google Cloud Trace" 8 | homepage = "https://github.com/abdolence/opentelemetry-gcloud-trace-rs" 9 | repository = "https://github.com/abdolence/opentelemetry-gcloud-trace-rs" 10 | documentation = "https://docs.rs/opentelemetry-gcloud-trace" 11 | keywords = ["opentelemetry", "metrics", "span", "google", "stackdriver"] 12 | categories = ["api-bindings"] 13 | readme = "README.md" 14 | include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE", "SECURITY.md"] 15 | 16 | [badges] 17 | maintenance = { status = "actively-developed" } 18 | 19 | [lib] 20 | name = "opentelemetry_gcloud_trace" 21 | path = "src/lib.rs" 22 | 23 | [dependencies] 24 | tracing = "0.1" 25 | opentelemetry = { version = "0.30" } 26 | opentelemetry_sdk = { version = "0.30", features = ["rt-tokio", "experimental_trace_batch_span_processor_with_async_runtime"] } 27 | opentelemetry-semantic-conventions = { version = "0.30" } 28 | gcloud-sdk = { version = "0.27", features = ["google-devtools-cloudtrace-v2"], default-features = false } 29 | rvstruct = "0.3" 30 | rsb_derive = "0.5" 31 | tokio = { version = "1" } 32 | tokio-stream = "0.1" 33 | futures = "0.3" 34 | async-trait = "0.1" 35 | 36 | [features] 37 | default = ["tls-roots"] 38 | tls-roots = ["gcloud-sdk/tls-roots"] 39 | tls-webpki-roots = ["gcloud-sdk/tls-webpki-roots"] 40 | 41 | [dev-dependencies] 42 | tokio = { version = "1", features = ["full"] } 43 | opentelemetry = { version = "0.30" } 44 | tracing = "0.1" 45 | tracing-subscriber = { version = "0.3", features = ["env-filter","registry"] } 46 | tracing-opentelemetry = { version = "0.31" } 47 | cargo-husky = { version = "1.5", default-features = false, features = ["run-for-all", "prepush-hook", "run-cargo-fmt"] } 48 | rustls = "0.23" 49 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Cargo](https://img.shields.io/crates/v/opentelemetry-gcloud-trace.svg)](https://crates.io/crates/opentelemetry-gcloud-trace) 2 | ![tests and formatting](https://github.com/abdolence/opentelemetry-gcloud-trace-rs/workflows/tests%20&%20formatting/badge.svg) 3 | ![security audit](https://github.com/abdolence/opentelemetry-gcloud-trace-rs/workflows/security%20audit/badge.svg) 4 | 5 | # OpenTelemetry support for Google Cloud Trace 6 | 7 | ## Quick start 8 | 9 | Cargo.toml: 10 | ```toml 11 | [dependencies] 12 | opentelemetry-gcloud-trace = "0.20" 13 | ``` 14 | 15 | ### Crypto provider error 16 | 17 | Depends on your other dependencies you may see the error like: 18 | 19 | ``` 20 | no process-level CryptoProvider available -- call CryptoProvider::install_default() before this point 21 | ``` 22 | 23 | This is because the TLS providers are not installed by default and you can choose different. 24 | The easiest way to fix is just to include one of the provider, for example: 25 | 26 | ```toml 27 | [dependencies] 28 | rustls = "0.23" 29 | ``` 30 | 31 | If you have multiple you may need to call `CryptoProvider::install_default()` before using the Firestore client. 32 | 33 | ```rust 34 | rustls::crypto::ring::default_provider().install_default().expect("Failed to install rustls crypto provider"); 35 | ``` 36 | 37 | ## Compatibility matrix 38 | 39 | | opentelemetry-gcloud-trace version | opentelemetry version | tracing-opentelemetry | gcloud-sdk | 40 | |------------------------------------|-----------------------|-----------------------|------------| 41 | | 0.20 | 0.30 | 0.31 | 0.27 | 42 | | 0.19 | 0.29 | 0.30 | 0.27 | 43 | | 0.18 | 0.28 | 0.29 | 0.26 | 44 | | 0.17 | 0.27 | 0.28 | 0.26 | 45 | | 0.16 | 0.27 | 0.28 | 0.25 | 46 | | 0.15 | 0.25 | 0.26 | 0.25 | 47 | | 0.12 | 0.24 | 0.25 | 0.25 | 48 | 49 | Example: 50 | 51 | ```rust 52 | 53 | let gcp_trace_exporter = GcpCloudTraceExporterBuilder::for_default_project_id().await?; // or GcpCloudTraceExporterBuilder::new(config_env_var("PROJECT_ID")?) 54 | 55 | let tracer_provider = gcp_trace_exporter.create_provider().await?; 56 | let tracer: opentelemetry_sdk::trace::Tracer = gcp_trace_exporter.install(&tracer_provider).await?; 57 | 58 | opentelemetry::global::set_tracer_provider(tracer_provider.clone()); 59 | 60 | tracer.in_span("doing_work_parent", |cx| { 61 | // ... 62 | }); 63 | 64 | tracer_provider.shutdown()?; 65 | 66 | 67 | ``` 68 | 69 | All examples are available at [examples](examples) directory. 70 | 71 | To run an example use with environment variables: 72 | ``` 73 | # PROJECT_ID= cargo run --example enable-exporter 74 | ``` 75 | 76 | ![Google Cloud Console Example](docs/img/gcloud-example.png) 77 | 78 | 79 | ```toml 80 | [dependencies] 81 | opentelemetry = { version = "*", features = [] } 82 | opentelemetry_sdk = { version = "*", features = ["rt-tokio"] } 83 | opentelemetry-gcloud-trace = "*" 84 | ``` 85 | 86 | ### Crypto provider error 87 | 88 | Depends on your other dependencies you may see the error like: 89 | 90 | ``` 91 | no process-level CryptoProvider available -- call CryptoProvider::install_default() before this point 92 | ``` 93 | 94 | This is because the TLS providers are not installed by default and you can choose different. 95 | The easiest way to fix is just to include one of the provider, for example: 96 | 97 | ```toml 98 | [dependencies] 99 | rustls = "0.23" 100 | ``` 101 | 102 | If you have multiple you may need to call `CryptoProvider::install_default()` before using the Firestore client. 103 | 104 | ```rust 105 | rustls::crypto::ring::default_provider().install_default().expect("Failed to install rustls crypto provider"); 106 | ``` 107 | 108 | ## Configuration 109 | 110 | You can specify trace configuration using `with_tracer_provider_builder`: 111 | 112 | ```rust 113 | let exporter = GcpCloudTraceExporterBuilder::new(google_project_id); 114 | let provider = exporter.create_provider_from_builder ( TracerProvider::builder() 115 | .with_sampler(Sampler::AlwaysOn) 116 | .with_id_generator(RandomIdGenerator::default()) 117 | )); 118 | ``` 119 | 120 | ## Limitations 121 | - This exporter doesn't support any other runtimes except Tokio. 122 | 123 | ## Integration with logs 124 | This crate intentionally doesn't export logs using API to avoid duplicate logs on GKE/GCE environments. 125 | You can use this crate in combination with `tracing-stackdriver` crate to produce 126 | JSON formatted logs and logs and traces will be correlated by `trace_id` and `span_id` 127 | fields automatically. 128 | 129 | This is an example of this kind of configuration: 130 | ```rust 131 | 132 | fn init_console_log( 133 | tracer: opentelemetry_sdk::trace::Tracer, 134 | ) -> Result<(), Box> { 135 | let telemetry = tracing_opentelemetry::layer().with_tracer(tracer); 136 | 137 | let subscriber = tracing_subscriber::registry::Registry::default() 138 | .with(tracing_subscriber::fmt::layer()) 139 | .with(tracing_subscriber::EnvFilter::from_str( 140 | "gcloud_sdk=debug", 141 | )?) 142 | .with(telemetry); 143 | 144 | tracing::subscriber::set_global_default(subscriber)?; 145 | 146 | Ok(()) 147 | } 148 | 149 | fn init_stackdriver_log( 150 | gcp_project_id: &str, 151 | tracer: opentelemetry_sdk::trace::Tracer, 152 | ) -> Result<(), BoxedError> { 153 | let telemetry_layer = tracing_opentelemetry::layer().with_tracer(tracer); 154 | 155 | let stackdriver_layer = tracing_stackdriver::layer().with_cloud_trace( 156 | tracing_stackdriver::CloudTraceConfiguration { 157 | project_id: gcp_project_id.to_string(), 158 | }, 159 | ); 160 | 161 | let subscriber = tracing_subscriber::Registry::default() 162 | .with(telemetry_layer) 163 | .with(stackdriver_layer) 164 | .with(tracing_subscriber::EnvFilter::from_str( 165 | "gcloud_sdk=debug", 166 | )?); 167 | tracing::subscriber::set_global_default(subscriber) 168 | .expect("Could not set up global logger"); 169 | 170 | Ok(()) 171 | } 172 | 173 | async fn init_tracing(app_mode: &GlobalAppMode, 174 | tracer: GcpCloudTraceExporter, 175 | gcp_project_id: &str) -> Result<(), BoxedError> { 176 | match app_mode { 177 | GlobalAppMode::Production => init_stackdriver_log(gcp_project_id, tracer), 178 | GlobalAppMode::Development => init_console_log(tracer), 179 | } 180 | } 181 | 182 | #[tokio::main] 183 | async fn main() -> Result<(), BoxedError> { 184 | let gcp_project_id = "my-gcp-project-id"; 185 | let exporter = GcpCloudTraceExporterBuilder::new(gcp_project_id.into()); 186 | let tracer_provider = gcp_trace_exporter.create_provider().await?; 187 | let tracer: opentelemetry_sdk::trace::Tracer = gcp_trace_exporter.install(&tracer_provider).await?; 188 | let app_mode = GlobalAppMode::Development; 189 | 190 | opentelemetry::global::set_tracer_provider(tracer_provider.clone()); 191 | 192 | init_tracing(&app_mode, tracer, gcp_project_id).await?; 193 | 194 | // ... 195 | 196 | tracer_provider.shutdown()?; 197 | } 198 | 199 | 200 | ``` 201 | 202 | ## TLS related features 203 | Cargo provides support for different TLS features for dependencies: 204 | - `tls-roots`: default feature to support native TLS roots 205 | - `tls-webpki-roots`: feature to switch to webpki crate roots 206 | 207 | ## Licence 208 | Apache Software License (ASL) 209 | 210 | ## Author 211 | Abdulla Abdurakhmanov 212 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Reporting a Vulnerability 4 | 5 | Please follow general guidelines defined here: 6 | https://cheatsheetseries.owasp.org/cheatsheets/Vulnerability_Disclosure_Cheat_Sheet.html 7 | 8 | ## Contacts 9 | E-mail: me@abdolence.dev 10 | -------------------------------------------------------------------------------- /docs/img/gcloud-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abdolence/opentelemetry-gcloud-trace-rs/cd78ad4c00e91a4ee18b92cbc6d5d9e0c30b4b4d/docs/img/gcloud-example.png -------------------------------------------------------------------------------- /examples/enable-exporter.rs: -------------------------------------------------------------------------------- 1 | use opentelemetry::trace::*; 2 | 3 | use opentelemetry_gcloud_trace::*; 4 | 5 | pub fn config_env_var(name: &str) -> Result { 6 | std::env::var(name).map_err(|e| format!("{}: {}", name, e)) 7 | } 8 | 9 | #[tokio::main] 10 | async fn main() -> Result<(), Box> { 11 | let gcp_trace_exporter = GcpCloudTraceExporterBuilder::for_default_project_id() 12 | .await? 13 | .with_resource( 14 | opentelemetry_sdk::Resource::builder() 15 | .with_attributes(vec![opentelemetry::KeyValue::new( 16 | "service.name", 17 | "simple-app", 18 | )]) 19 | .build(), 20 | ); // or GcpCloudTraceExporterBuilder::new(config_env_var("PROJECT_ID")?) 21 | let tracer_provider = gcp_trace_exporter.create_provider().await?; 22 | let tracer: opentelemetry_sdk::trace::Tracer = 23 | gcp_trace_exporter.install(&tracer_provider).await?; 24 | 25 | opentelemetry::global::set_tracer_provider(tracer_provider.clone()); 26 | 27 | tracer.in_span("my_parent_work", |cx| { 28 | let span = cx.span(); 29 | span.set_attribute(opentelemetry::KeyValue::new( 30 | "http.client_ip", 31 | "42.42.42.42", 32 | )); 33 | span.set_attribute(opentelemetry::KeyValue::new( 34 | "my_test_arr", 35 | opentelemetry::Value::Array(vec![42i64, 42i64].into()), 36 | )); 37 | span.add_event( 38 | "test-event", 39 | vec![opentelemetry::KeyValue::new( 40 | "test_event_attr", 41 | "test-event-value", 42 | )], 43 | ); 44 | tracer.in_span("my_child_work", |cx| { 45 | println!( 46 | "Do printing, nothing more here. Please check your Google Cloud Trace dashboard." 47 | ); 48 | 49 | cx.span().add_event( 50 | "test-child-event", 51 | vec![opentelemetry::KeyValue::new( 52 | "test_event_attr", 53 | "test-event-value", 54 | )], 55 | ); 56 | }) 57 | }); 58 | 59 | tracer_provider.shutdown()?; 60 | 61 | Ok(()) 62 | } 63 | -------------------------------------------------------------------------------- /examples/tracing-exporter.rs: -------------------------------------------------------------------------------- 1 | use tracing::*; 2 | use tracing_subscriber::layer::SubscriberExt; 3 | use tracing_subscriber::Registry; 4 | 5 | use opentelemetry_gcloud_trace::*; 6 | 7 | pub fn config_env_var(name: &str) -> Result { 8 | std::env::var(name).map_err(|e| format!("{}: {}", name, e)) 9 | } 10 | 11 | #[tokio::main] 12 | async fn main() -> Result<(), Box> { 13 | let gcp_trace_exporter = GcpCloudTraceExporterBuilder::for_default_project_id() 14 | .await? 15 | .with_resource( 16 | opentelemetry_sdk::Resource::builder() 17 | .with_attributes(vec![opentelemetry::KeyValue::new( 18 | "service.name", 19 | "simple-app", 20 | )]) 21 | .build(), 22 | ); // or GcpCloudTraceExporterBuilder::new(config_env_var("PROJECT_ID")?) 23 | let tracer_provider = gcp_trace_exporter.create_provider().await?; 24 | let tracer: opentelemetry_sdk::trace::Tracer = 25 | gcp_trace_exporter.install(&tracer_provider).await?; 26 | 27 | opentelemetry::global::set_tracer_provider(tracer_provider.clone()); 28 | 29 | // Create a tracing layer with the configured tracer 30 | let telemetry = tracing_opentelemetry::layer().with_tracer(tracer); 31 | 32 | // Use the tracing subscriber `Registry`, or any other subscriber 33 | // that impls `LookupSpan` 34 | let subscriber = Registry::default().with(telemetry); 35 | 36 | // Trace executed code 37 | tracing::subscriber::with_default(subscriber, || { 38 | // Spans will be sent to the configured OpenTelemetry exporter 39 | let root = span!(tracing::Level::TRACE, "my_app", work_units = 2); 40 | let _enter = root.enter(); 41 | 42 | let child_span = span!( 43 | tracing::Level::TRACE, 44 | "my_child", 45 | work_units = 2, 46 | "http.client_ip" = "42.42.42.42" 47 | ); 48 | child_span.in_scope(|| { 49 | info!( 50 | "Do printing, nothing more here. Please check your Google Cloud Trace dashboard." 51 | ); 52 | }); 53 | 54 | error!("This event will be logged in the root span."); 55 | }); 56 | 57 | tracer_provider.shutdown()?; 58 | 59 | Ok(()) 60 | } 61 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:recommended" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /src/errors.rs: -------------------------------------------------------------------------------- 1 | use gcloud_sdk::error::Error; 2 | use opentelemetry_sdk::ExportError; 3 | use rsb_derive::*; 4 | 5 | pub type BoxedError = Box; 6 | 7 | #[derive(Debug)] 8 | pub enum GcloudTraceError { 9 | SystemError(GcloudTraceSystemError), 10 | NetworkError(GcloudTraceNetworkError), 11 | } 12 | 13 | impl std::fmt::Display for GcloudTraceError { 14 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 15 | match *self { 16 | GcloudTraceError::SystemError(ref err) => err.fmt(f), 17 | GcloudTraceError::NetworkError(ref err) => err.fmt(f), 18 | } 19 | } 20 | } 21 | 22 | impl std::error::Error for GcloudTraceError { 23 | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { 24 | match *self { 25 | GcloudTraceError::SystemError(ref err) => Some(err), 26 | GcloudTraceError::NetworkError(ref err) => Some(err), 27 | } 28 | } 29 | } 30 | 31 | #[derive(Debug, Builder)] 32 | pub struct GcloudTraceSystemError { 33 | pub message: String, 34 | pub root_cause: Option, 35 | } 36 | 37 | impl std::fmt::Display for GcloudTraceSystemError { 38 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 39 | write!(f, "System error: {:?}", self.message) 40 | } 41 | } 42 | 43 | impl std::error::Error for GcloudTraceSystemError {} 44 | 45 | #[derive(Debug, Eq, PartialEq, Clone, Builder)] 46 | pub struct GcloudTraceNetworkError { 47 | pub message: String, 48 | } 49 | 50 | impl std::fmt::Display for GcloudTraceNetworkError { 51 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 52 | write!(f, "Network error: {}", self.message) 53 | } 54 | } 55 | 56 | impl std::error::Error for GcloudTraceNetworkError {} 57 | 58 | impl From for GcloudTraceError { 59 | fn from(gcloud_error: Error) -> Self { 60 | GcloudTraceError::SystemError( 61 | GcloudTraceSystemError::new(format!("Google SDK error: {gcloud_error}")) 62 | .with_root_cause(Box::new(gcloud_error)), 63 | ) 64 | } 65 | } 66 | 67 | impl From for GcloudTraceError { 68 | fn from(status: gcloud_sdk::tonic::Status) -> Self { 69 | GcloudTraceError::NetworkError(GcloudTraceNetworkError::new(format!("{status}"))) 70 | } 71 | } 72 | 73 | impl ExportError for GcloudTraceError { 74 | fn exporter_name(&self) -> &'static str { 75 | "GoogleCloudTraceExporter" 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/google_trace_exporter_client.rs: -------------------------------------------------------------------------------- 1 | use crate::TraceExportResult; 2 | use gcloud_sdk::google::devtools::cloudtrace::v2::{ 3 | attribute_value as gcp_attribute_value, span as gspan, AttributeValue as GcpAttributeValue, 4 | BatchWriteSpansRequest, Span as GcpSpan, TruncatableString, 5 | }; 6 | use gcloud_sdk::google::rpc::{Code as GcpStatusCode, Status as GcpStatus}; 7 | use gcloud_sdk::*; 8 | use opentelemetry::KeyValue; 9 | use opentelemetry_sdk::{trace::SpanData, Resource}; 10 | use std::ops::Deref; 11 | 12 | #[derive(Clone)] 13 | pub struct GcpCloudTraceExporterClient { 14 | client: GoogleApi< 15 | google::devtools::cloudtrace::v2::trace_service_client::TraceServiceClient< 16 | GoogleAuthMiddleware, 17 | >, 18 | >, 19 | google_project_id: String, 20 | resource_attributes: Vec, 21 | } 22 | 23 | impl GcpCloudTraceExporterClient { 24 | pub async fn new(google_project_id: &str, resource: Resource) -> TraceExportResult { 25 | let client: GoogleApi< 26 | google::devtools::cloudtrace::v2::trace_service_client::TraceServiceClient< 27 | GoogleAuthMiddleware, 28 | >, 29 | > = GoogleApi::from_function( 30 | google::devtools::cloudtrace::v2::trace_service_client::TraceServiceClient::new, 31 | "https://cloudtrace.googleapis.com", 32 | None, 33 | ) 34 | .await?; 35 | 36 | Ok(Self { 37 | client, 38 | google_project_id: google_project_id.to_string(), 39 | resource_attributes: resource 40 | .iter() 41 | .map(|(k, v)| KeyValue::new(k.clone(), v.clone())) 42 | .collect(), 43 | }) 44 | } 45 | 46 | pub async fn export_batch(&self, batch: Vec) -> TraceExportResult<()> { 47 | let batch_request = BatchWriteSpansRequest { 48 | name: format!("projects/{}", self.google_project_id), 49 | spans: batch 50 | .into_iter() 51 | .map(|span| GcpSpan { 52 | name: format!( 53 | "projects/{}/traces/{}/spans/{}", 54 | self.google_project_id, 55 | span.span_context.trace_id(), 56 | span.span_context.span_id() 57 | ), 58 | span_id: span.span_context.span_id().to_string(), 59 | parent_span_id: if span.parent_span_id != opentelemetry::trace::SpanId::INVALID 60 | { 61 | span.parent_span_id.to_string() 62 | } else { 63 | "".to_string() 64 | }, 65 | display_name: Some(Self::truncatable_string(span.name.deref(), 128)), 66 | start_time: Some(prost_types::Timestamp::from(span.start_time)), 67 | end_time: Some(prost_types::Timestamp::from(span.end_time)), 68 | attributes: Some(self.convert_span_attrs(&span.attributes)), 69 | time_events: Some(Self::convert_time_events(&span.events)), 70 | links: Some(Self::convert_links(&span.links)), 71 | status: Self::convert_status(&span), 72 | span_kind: Self::convert_span_kind(&span.span_kind).into(), 73 | ..GcpSpan::default() 74 | }) 75 | .collect(), 76 | ..BatchWriteSpansRequest::default() 77 | }; 78 | 79 | self.client 80 | .get() 81 | .batch_write_spans(tonic::Request::new(batch_request)) 82 | .await?; 83 | 84 | Ok(()) 85 | } 86 | 87 | fn truncatable_string(str: &str, max_len: usize) -> TruncatableString { 88 | if str.len() > max_len { 89 | let mut truncated_str = str.to_string(); 90 | truncated_str.truncate(max_len); 91 | 92 | TruncatableString { 93 | value: truncated_str, 94 | truncated_byte_count: (str.len() - max_len) as i32, 95 | } 96 | } else { 97 | TruncatableString { 98 | value: str.to_string(), 99 | truncated_byte_count: 0, 100 | } 101 | } 102 | } 103 | 104 | fn convert_span_attrs(&self, attrs: &[KeyValue]) -> gspan::Attributes { 105 | const MAX_ATTRS: usize = 32; 106 | gspan::Attributes { 107 | attribute_map: attrs 108 | .iter() 109 | .chain(&self.resource_attributes) 110 | .take(MAX_ATTRS) 111 | .map(|attribute| { 112 | ( 113 | attribute.key.to_string(), 114 | Self::convert_span_attr_value(&attribute.value), 115 | ) 116 | }) 117 | .collect(), 118 | dropped_attributes_count: if attrs.len() > MAX_ATTRS { 119 | (attrs.len() - MAX_ATTRS) as i32 120 | } else { 121 | 0 122 | }, 123 | } 124 | } 125 | 126 | fn convert_span_attr_value(attr_value: &opentelemetry::Value) -> GcpAttributeValue { 127 | const MAX_STR_LEN: usize = 256; 128 | GcpAttributeValue { 129 | value: Some(match attr_value { 130 | opentelemetry::Value::I64(value) => gcp_attribute_value::Value::IntValue(*value), 131 | opentelemetry::Value::F64(value) => gcp_attribute_value::Value::StringValue( 132 | Self::truncatable_string(format!("{value:.2}").as_str(), MAX_STR_LEN), 133 | ), 134 | opentelemetry::Value::String(value) => gcp_attribute_value::Value::StringValue( 135 | Self::truncatable_string(value.as_str(), MAX_STR_LEN), 136 | ), 137 | opentelemetry::Value::Bool(value) => gcp_attribute_value::Value::BoolValue(*value), 138 | opentelemetry::Value::Array(arr) => { 139 | // Basic array support converting to string with delimiters 140 | gcp_attribute_value::Value::StringValue(Self::truncatable_string( 141 | &arr.to_string(), 142 | MAX_STR_LEN, 143 | )) 144 | } 145 | _ => gcp_attribute_value::Value::StringValue(Self::truncatable_string( 146 | "unknown_value", 147 | MAX_STR_LEN, 148 | )), 149 | }), 150 | } 151 | } 152 | 153 | fn convert_time_events(events: &opentelemetry_sdk::trace::SpanEvents) -> gspan::TimeEvents { 154 | const MAX_EVENTS: usize = 128; 155 | 156 | gspan::TimeEvents { 157 | time_event: events 158 | .iter() 159 | .take(MAX_EVENTS) 160 | .map(Self::convert_time_event) 161 | .collect(), 162 | dropped_message_events_count: if events.len() > MAX_EVENTS { 163 | (events.dropped_count as usize + events.len() - MAX_EVENTS) as i32 164 | } else { 165 | events.dropped_count as i32 166 | }, 167 | ..gspan::TimeEvents::default() 168 | } 169 | } 170 | 171 | fn convert_time_event(event: &opentelemetry::trace::Event) -> gspan::TimeEvent { 172 | gspan::TimeEvent { 173 | time: Some(prost_types::Timestamp::from(event.timestamp)), 174 | value: Some(Self::convert_time_event_value(event)), 175 | ..gspan::TimeEvent::default() 176 | } 177 | } 178 | 179 | fn convert_time_event_value( 180 | event_value: &opentelemetry::trace::Event, 181 | ) -> gspan::time_event::Value { 182 | const MAX_ATTRS: usize = 32; 183 | gspan::time_event::Value::Annotation(gspan::time_event::Annotation { 184 | description: Some(Self::truncatable_string(event_value.name.deref(), 256)), 185 | attributes: Some(gspan::Attributes { 186 | attribute_map: event_value 187 | .attributes 188 | .iter() 189 | .take(MAX_ATTRS) 190 | .map(|kv| (kv.key.to_string(), Self::convert_span_attr_value(&kv.value))) 191 | .collect(), 192 | dropped_attributes_count: if event_value.attributes.len() > MAX_ATTRS { 193 | (event_value.dropped_attributes_count as usize + event_value.attributes.len() 194 | - MAX_ATTRS) as i32 195 | } else { 196 | event_value.dropped_attributes_count as i32 197 | }, 198 | }), 199 | }) 200 | } 201 | 202 | fn convert_links(links: &opentelemetry_sdk::trace::SpanLinks) -> gspan::Links { 203 | const MAX_LINKS: usize = 128; 204 | 205 | gspan::Links { 206 | link: links 207 | .iter() 208 | .take(MAX_LINKS) 209 | .map(Self::convert_link) 210 | .collect(), 211 | dropped_links_count: if links.len() > MAX_LINKS { 212 | (links.dropped_count as usize + links.len() - MAX_LINKS) as i32 213 | } else { 214 | links.dropped_count as i32 215 | }, 216 | ..gspan::Links::default() 217 | } 218 | } 219 | 220 | fn convert_link(link: &opentelemetry::trace::Link) -> gspan::Link { 221 | gspan::Link { 222 | trace_id: link.span_context.trace_id().to_string(), 223 | span_id: link.span_context.span_id().to_string(), 224 | ..gspan::Link::default() 225 | } 226 | } 227 | 228 | fn convert_status(span: &SpanData) -> Option { 229 | match span.status { 230 | opentelemetry::trace::Status::Unset => None, 231 | opentelemetry::trace::Status::Ok => Some(GcpStatus { 232 | code: GcpStatusCode::Ok.into(), 233 | ..GcpStatus::default() 234 | }), 235 | opentelemetry::trace::Status::Error { ref description } => Some(GcpStatus { 236 | code: GcpStatusCode::Unavailable.into(), 237 | message: description.to_string(), 238 | ..GcpStatus::default() 239 | }), 240 | } 241 | } 242 | 243 | fn convert_span_kind(span_kind: &opentelemetry::trace::SpanKind) -> gspan::SpanKind { 244 | match span_kind { 245 | opentelemetry::trace::SpanKind::Client => gspan::SpanKind::Client, 246 | opentelemetry::trace::SpanKind::Server => gspan::SpanKind::Server, 247 | opentelemetry::trace::SpanKind::Producer => gspan::SpanKind::Producer, 248 | opentelemetry::trace::SpanKind::Consumer => gspan::SpanKind::Consumer, 249 | opentelemetry::trace::SpanKind::Internal => gspan::SpanKind::Internal, 250 | } 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! # OpenTelemetry Google Cloud Trace Exporter 2 | //! 3 | //! OpenTelemetry exporter implementation for Google Cloud Trace 4 | //! 5 | //! ## Performance 6 | //! 7 | //! For optimal performance, a batch exporter is recommended as the simple exporter will export 8 | //! each span synchronously on drop. You can enable the [`rt-tokio`], [`rt-tokio-current-thread`] 9 | //! features and specify a runtime on the pipeline to have a batch exporter 10 | //! configured for you automatically. 11 | //! 12 | //! ```toml 13 | //! [dependencies] 14 | //! opentelemetry = { version = "*", features = ["rt-tokio"] } 15 | //! opentelemetry-gcloud-trace = "*" 16 | //! ``` 17 | //! 18 | //! ```ignore 19 | //! let gcp_trace_exporter = GcpCloudTraceExporterBuilder::new(config_env_var("PROJECT_ID")?) 20 | //! 21 | //! let tracer_provider = gcp_trace_exporter.create_provider().await?; 22 | //! let tracer: opentelemetry_sdk::trace::Tracer = gcp_trace_exporter.install(&tracer_provider).await?; 23 | //! 24 | //! opentelemetry::global::set_tracer_provider(tracer_provider.clone()); 25 | //! 26 | //! tracer.in_span("doing_work_parent", |cx| { 27 | //! // ... 28 | //! }); 29 | //! 30 | //! tracer_provider.shutdown()?; 31 | //! ``` 32 | //! ## Configuration 33 | //! 34 | //! You can specify trace configuration using `create_provider_from_builder`: 35 | //! 36 | //! ```ignore 37 | //! gcp_trace_exporter.create_provider_from_builder ( 38 | //! TracerProvider::builder() 39 | //! .with_sampler(Sampler::AlwaysOn) 40 | //! .with_id_generator(RandomIdGenerator::default()) 41 | //! ) 42 | //! ``` 43 | //! 44 | //! you can specify resource using `with_resource`: 45 | //! ```ignore 46 | //! let resources = Resource::new(vec![KeyValue::new("service.name", "my-service")]); 47 | //! GcpCloudTraceExporterBuilder::new(google_project_id).with_resource(resource).await?; 48 | //! ``` 49 | //! 50 | //! Have a look at full examples in the `examples` directory. 51 | //! 52 | 53 | #![allow(unused_parens, clippy::new_without_default, clippy::needless_update)] 54 | 55 | pub mod errors; 56 | pub type TraceExportResult = Result; 57 | 58 | mod google_trace_exporter_client; 59 | mod span_exporter; 60 | 61 | use crate::errors::GcloudTraceError; 62 | use opentelemetry::trace::TracerProvider; 63 | use opentelemetry::InstrumentationScope; 64 | use opentelemetry_sdk::error::OTelSdkError; 65 | use opentelemetry_sdk::trace::span_processor_with_async_runtime::BatchSpanProcessor; 66 | use opentelemetry_sdk::trace::{SdkTracerProvider, TracerProviderBuilder}; 67 | use opentelemetry_sdk::{runtime, Resource}; 68 | use rsb_derive::*; 69 | pub use span_exporter::GcpCloudTraceExporter; 70 | 71 | pub type SdkTracer = opentelemetry_sdk::trace::Tracer; 72 | 73 | #[derive(Debug, Builder)] 74 | pub struct GcpCloudTraceExporterBuilder { 75 | pub google_project_id: String, 76 | pub resource: Option, 77 | } 78 | 79 | impl GcpCloudTraceExporterBuilder { 80 | pub async fn for_default_project_id() -> TraceExportResult { 81 | let detected_project_id = gcloud_sdk::GoogleEnvironment::detect_google_project_id().await.ok_or_else(|| 82 | crate::errors::GcloudTraceError::SystemError( 83 | crate::errors::GcloudTraceSystemError::new( 84 | "No Google Project ID detected. Please specify it explicitly using env variable: PROJECT_ID or define it as default project for your service accounts".to_string() 85 | ) 86 | ) 87 | )?; 88 | Ok(Self::new(detected_project_id)) 89 | } 90 | 91 | pub async fn create_provider(&self) -> Result { 92 | self.create_provider_from_builder(SdkTracerProvider::builder()) 93 | .await 94 | } 95 | 96 | pub async fn create_provider_from_builder( 97 | &self, 98 | builder: TracerProviderBuilder, 99 | ) -> Result { 100 | let exporter = GcpCloudTraceExporter::new( 101 | &self.google_project_id, 102 | self.resource 103 | .clone() 104 | .unwrap_or_else(|| Resource::builder_empty().build()), 105 | ) 106 | .await?; 107 | 108 | let tracer_provider = builder 109 | .with_span_processor(BatchSpanProcessor::builder(exporter, runtime::Tokio).build()) 110 | .build(); 111 | 112 | Ok(tracer_provider) 113 | } 114 | 115 | pub async fn install( 116 | self, 117 | provider: &SdkTracerProvider, 118 | ) -> Result { 119 | let scope = InstrumentationScope::builder("opentelemetry-gcloud") 120 | .with_version(env!("CARGO_PKG_VERSION")) 121 | .with_schema_url("https://opentelemetry.io/schemas/1.23.0") 122 | .build(); 123 | 124 | let tracer = provider.tracer_with_scope(scope); 125 | Ok(tracer) 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/span_exporter.rs: -------------------------------------------------------------------------------- 1 | use crate::google_trace_exporter_client::GcpCloudTraceExporterClient; 2 | use crate::TraceExportResult; 3 | use futures::future::TryFutureExt; 4 | use futures::FutureExt; 5 | use opentelemetry_sdk::error::{OTelSdkError, OTelSdkResult}; 6 | use opentelemetry_sdk::{ 7 | trace::{SpanData, SpanExporter}, 8 | Resource, 9 | }; 10 | use std::fmt::Formatter; 11 | use std::sync::Arc; 12 | 13 | pub struct GcpCloudTraceExporter { 14 | gcp_export_client: Arc, 15 | } 16 | 17 | impl GcpCloudTraceExporter { 18 | pub async fn new(google_project_id: &str, resource: Resource) -> TraceExportResult { 19 | Ok(Self { 20 | gcp_export_client: Arc::new( 21 | GcpCloudTraceExporterClient::new(google_project_id, resource).await?, 22 | ), 23 | }) 24 | } 25 | } 26 | 27 | impl std::fmt::Debug for GcpCloudTraceExporter { 28 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 29 | write!(f, "GcpCloudTraceExporter") 30 | } 31 | } 32 | 33 | impl SpanExporter for GcpCloudTraceExporter { 34 | fn export( 35 | &self, 36 | batch: Vec, 37 | ) -> impl std::future::Future + Send { 38 | let client = self.gcp_export_client.clone(); 39 | async move { 40 | client 41 | .export_batch(batch) 42 | .map_err(|e| OTelSdkError::InternalFailure(e.to_string())) 43 | .await 44 | } 45 | .boxed() 46 | } 47 | } 48 | --------------------------------------------------------------------------------