|
12 | 12 | # See the License for the specific language governing permissions and |
13 | 13 | # limitations under the License. |
14 | 14 |
|
| 15 | +import os |
| 16 | + |
15 | 17 | from opencensus.trace.exporters import base |
16 | 18 |
|
17 | 19 | from google.cloud.trace.client import Client |
18 | 20 |
|
| 21 | +# Environment variable set in App Engine when vm:true is set. |
| 22 | +_APPENGINE_FLEXIBLE_ENV_VM = 'GAE_APPENGINE_HOSTNAME' |
| 23 | + |
| 24 | +# Environment variable set in App Engine when env:flex is set. |
| 25 | +_APPENGINE_FLEXIBLE_ENV_FLEX = 'GAE_INSTANCE' |
| 26 | + |
| 27 | +# GAE common labels |
| 28 | +# See: https://cloud.google.com/appengine/docs/flexible/python/runtime# |
| 29 | +# environment_variables |
| 30 | +GAE_LABELS = { |
| 31 | + 'GAE_FLEX_VERSION': 'g.co/gae/app/version', |
| 32 | + 'GAE_FLEX_SERVICE': 'g.co/gae/app/service', |
| 33 | + 'GAE_FLEX_PROJECT': 'g.co/gae/app/project', |
| 34 | + 'GAE_FLEX_INSTANCE': 'g.co/gae/app/instance', |
| 35 | + 'GAE_FLEX_MEMORY_MB': 'g.co/gae/app/memory_mb', |
| 36 | + 'GAE_FLEX_PORT': 'g.co/gae/app/port', |
| 37 | +} |
| 38 | + |
| 39 | +# GCE common labels |
| 40 | +GCE_LABELS = { |
| 41 | + 'GCE_INSTANCE_ID': 'g.co/gce/instanceid', |
| 42 | + 'GCE_HOSTNAME': 'g.co/gce/hostname', |
| 43 | +} |
| 44 | + |
| 45 | + |
| 46 | +def set_labels(trace): |
| 47 | + """Automatically set labels for Google Cloud environment.""" |
| 48 | + if is_gae_environment(): |
| 49 | + set_gae_labels(trace) |
| 50 | + |
| 51 | + |
| 52 | +def set_gae_labels(trace): |
| 53 | + """Set the GAE environment common labels.""" |
| 54 | + spans = trace.get('spans') |
| 55 | + |
| 56 | + for env_var, label_key in GAE_LABELS.items(): |
| 57 | + label_value = os.environ.get(env_var) |
| 58 | + |
| 59 | + if label_value is not None: |
| 60 | + for span in spans: |
| 61 | + labels = span.get('labels') |
| 62 | + labels[label_key] = label_value |
| 63 | + span['labels'] = labels |
| 64 | + |
| 65 | + |
| 66 | +def is_gae_environment(): |
| 67 | + """Return True if the GAE related env vars is detected.""" |
| 68 | + if (_APPENGINE_FLEXIBLE_ENV_VM in os.environ or |
| 69 | + _APPENGINE_FLEXIBLE_ENV_FLEX in os.environ): |
| 70 | + return True |
| 71 | + |
19 | 72 |
|
20 | 73 | class StackdriverExporter(base.Exporter): |
21 | 74 | """A exporter that send traces and trace spans to Google Cloud Stackdriver |
@@ -45,6 +98,7 @@ def translate_to_stackdriver(self, trace): |
45 | 98 | :rtype: dict |
46 | 99 | :returns: Traces in Google Cloud StackDriver Trace format. |
47 | 100 | """ |
| 101 | + set_labels(trace) |
48 | 102 | trace['projectId'] = self.project_id |
49 | 103 | traces = {'traces': [trace]} |
50 | 104 | return traces |
0 commit comments