|
| 1 | +# Copyright © 2011-2025 Splunk, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"): you may |
| 4 | +# not use this file except in compliance with the License. You may obtain |
| 5 | +# 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, WITHOUT |
| 11 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 | +# License for the specific language governing permissions and limitations |
| 13 | +# under the License. |
| 14 | + |
| 15 | +from typing import Any, Optional, Tuple |
| 16 | +from splunklib.data import Record |
| 17 | +from splunklib.internal.telemetry.metric import Metric |
| 18 | +import json |
| 19 | + |
| 20 | +# TODO: decide: either struggle with the type hints or get rid of them and stick to the convention |
| 21 | + |
| 22 | +CONTENT_TYPE = [('Content-Type', 'application/json')] |
| 23 | +DEFAULT_TELEMETRY_USER = "nobody" # User `nobody` always exists |
| 24 | +DEFAULT_TELEMETRY_APP = "splunk_instrumentation" # This app is shipped with Splunk and has `telemetry-metric` endpoint |
| 25 | +TELEMETRY_ENDPOINT = "telemetry-metric" |
| 26 | + |
| 27 | + |
| 28 | +class TelemetrySender: |
| 29 | + # FIXME: adding Service typehint produces circular dependency |
| 30 | + # service: Service |
| 31 | + |
| 32 | + def __init__(self, service): |
| 33 | + self.service = service |
| 34 | + |
| 35 | + def send(self, metric: Metric, user: Optional[str] = None, app: Optional[str] = None) -> Tuple[Record, Any]: |
| 36 | + """Sends the metric to the `telemetry-metric` endpoint. |
| 37 | +
|
| 38 | + :param user: Optional user that sends the telemetry. |
| 39 | + :param app: Optional app that is used to send the telemetry. |
| 40 | +
|
| 41 | + If those values are omitted, the default values are used. |
| 42 | + This makes sure that, even if missing some info, the event will be sent. |
| 43 | + """ |
| 44 | + |
| 45 | + metric_body = self._metric_to_json(metric) |
| 46 | + |
| 47 | + user = user or DEFAULT_TELEMETRY_USER |
| 48 | + app = app or DEFAULT_TELEMETRY_APP |
| 49 | + |
| 50 | + response = self.service.post( |
| 51 | + "telemetry-metric", |
| 52 | + user, |
| 53 | + app, |
| 54 | + headers=[('Content-Type', 'application/json')], |
| 55 | + body=metric_body, |
| 56 | + ) |
| 57 | + |
| 58 | + body = json.loads(response.body.read().decode('utf-8')) |
| 59 | + |
| 60 | + return response, body |
| 61 | + |
| 62 | + def _metric_to_json(self, metric: Metric) -> str: |
| 63 | + m = { |
| 64 | + "type": metric.type.value, |
| 65 | + "component": metric.component, |
| 66 | + "data": metric.data, |
| 67 | + "optInRequired": metric.opt_in_required |
| 68 | + } |
| 69 | + |
| 70 | + return json.dumps(m) |
0 commit comments