Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added configuration option: GLOBAL_LABELS #1007

Merged
merged 17 commits into from
Jun 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/configuration.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,36 @@ See {apm-app-ref}/filters.html#environment-selector[environment selector] in the
NOTE: This feature is fully supported in the APM app in Kibana versions >= 7.2.
You must use the query bar to filter for a specific environment in versions prior to 7.2.

[float]
[[config-global-labels]]
==== `global_labels`

[options="header"]
|============
| Hostname variable name | Option name in `php.ini`
| `ELASTIC_APM_GLOBAL_LABELS` | `elastic_apm.global_labels`
|============

[options="header"]
|============
| Default | Type
| empty map | string to string map
|============

Labels from this configuration are added to all the entities produced by the agent.

The format is `key=value[,key=value[,...]]`.
For example `dept=engineering,rack=number8`.

NOTE: When setting this configuration option in `.ini` file
it is required to enclose the value in quotes (because the value contains equal sign).
For example `elastic_apm.global_labels = "dept=engineering,rack=number8"`

Any labels set by the application via the agent's public API
will override global labels with the same keys.

NOTE: This option requires APM Server 7.2 or later. It will have no effect on older versions.

[float]
[[config-hostname]]
==== `hostname`
Expand Down
1 change: 1 addition & 0 deletions src/ElasticApm/Impl/Config/AllOptionsMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ public static function get(): array
OptionNames::DISABLE_SEND => new BoolOptionMetadata(/* default */ false),
OptionNames::ENABLED => new BoolOptionMetadata(/* default */ true),
OptionNames::ENVIRONMENT => new NullableStringOptionMetadata(),
OptionNames::GLOBAL_LABELS => new NullableLabelsOptionMetadata(),
OptionNames::HOSTNAME => new NullableStringOptionMetadata(),
OptionNames::LOG_LEVEL => new NullableLogLevelOptionMetadata(),
OptionNames::LOG_LEVEL_STDERR => new NullableLogLevelOptionMetadata(),
Expand Down
72 changes: 72 additions & 0 deletions src/ElasticApm/Impl/Config/KeyValuePairsOptionParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you 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.
*/

declare(strict_types=1);

namespace Elastic\Apm\Impl\Config;

use Elastic\Apm\Impl\Log\LoggableToString;
use Elastic\Apm\Impl\Util\TextUtil;

/**
* Code in this file is part of implementation internals and thus it is not covered by the backward compatibility.
*
* @internal
*
* @extends OptionParser<array<string>>
*/
final class KeyValuePairsOptionParser extends OptionParser
{
/**
* @param string $rawValue
*
* @return array<string>
*/
public function parse(string $rawValue): array
{
// Value format:
// key=value[,key=value[,...]]

// Treat empty string as zero key-value pairs
if (TextUtil::isEmptyString($rawValue)) {
return [];
}

$pairs = explode(',', $rawValue);
$result = [];
foreach ($pairs as $keyValuePair) {
$keyValueSeparatorPos = strpos($keyValuePair, '=');
if ($keyValueSeparatorPos === false) {
throw new ParseException('One of key-value pairs is missing key-value separator' . ' ;' . LoggableToString::convert(['keyValuePair' => $keyValuePair, 'rawValue' => $rawValue]));
}
$key = trim(substr($keyValuePair, /* offset */ 0, /* length */ $keyValueSeparatorPos));
$value = ($keyValueSeparatorPos === (strlen($keyValuePair) - 1)) ? '' : trim(substr($keyValuePair, /* offset */ $keyValueSeparatorPos + 1));
if (array_key_exists($key, $result)) {
throw new ParseException(
'Key is present more than once'
. ' ;' . LoggableToString::convert(['key' => $key, '1st value' => $result[$key], '2nd value' => $value, '2nd keyValuePair' => $keyValuePair, 'rawValue' => $rawValue])
);
}
$result[$key] = $value;
}
return $result;
}
}
82 changes: 82 additions & 0 deletions src/ElasticApm/Impl/Config/LabelsOptionParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you 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.
*/

declare(strict_types=1);

namespace Elastic\Apm\Impl\Config;

use Elastic\Apm\Impl\Tracer;

/**
* Code in this file is part of implementation internals and thus it is not covered by the backward compatibility.
*
* @internal
*
* @extends OptionParser<array<string|bool|int|float|null>>
*/
final class LabelsOptionParser extends OptionParser
{
/**
* @param string $valueAsString
*
* @return string|bool|int|float|null
*/
private static function parseValue(string $valueAsString)
{
if ($valueAsString === 'true') {
return true;
}
if ($valueAsString === 'false') {
return false;
}

if (filter_var($valueAsString, FILTER_VALIDATE_INT) !== false) {
return intval($valueAsString);
}

if (filter_var($valueAsString, FILTER_VALIDATE_FLOAT) !== false) {
return floatval($valueAsString);
}

if ($valueAsString === 'null') {
return null;
}

return Tracer::limitKeywordString($valueAsString);
}

/**
* @param string $rawValue
*
* @return array<string|bool|int|float|null>
*/
public function parse(string $rawValue): array
{
// Value format:
// key=value[,key=value[,...]]

$result = [];
foreach ((new KeyValuePairsOptionParser())->parse($rawValue) as $key => $valueAsString) {
$result[is_string($key) ? Tracer::limitKeywordString($key) : $key] = self::parseValue($valueAsString);
}
return $result;
}
}
41 changes: 41 additions & 0 deletions src/ElasticApm/Impl/Config/NullableLabelsOptionMetadata.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you 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.
*/

declare(strict_types=1);

namespace Elastic\Apm\Impl\Config;

/**
* Code in this file is part of implementation internals and thus it is not covered by the backward compatibility.
*
* @internal
*
* @extends NullableOptionMetadata<array<string|bool|int|float|null>>
*
* @noinspection PhpUnused
*/
final class NullableLabelsOptionMetadata extends NullableOptionMetadata
{
public function __construct()
{
parent::__construct(new LabelsOptionParser());
}
}
1 change: 1 addition & 0 deletions src/ElasticApm/Impl/Config/OptionNames.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ final class OptionNames
public const DISABLE_SEND = 'disable_send';
public const ENABLED = 'enabled';
public const ENVIRONMENT = 'environment';
public const GLOBAL_LABELS = 'global_labels';
public const HOSTNAME = 'hostname';
public const INTERNAL_CHECKS_LEVEL = 'internal_checks_level';
public const LOG_LEVEL = 'log_level';
Expand Down
11 changes: 11 additions & 0 deletions src/ElasticApm/Impl/Config/Snapshot.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ final class Snapshot implements LoggableInterface
/** @var ?string */
private $environment;

/** @var ?array<string|bool|int|float|null> */
private $globalLabels;

/** @var ?string */
private $hostname;

Expand Down Expand Up @@ -309,6 +312,14 @@ public function environment(): ?string
return $this->environment;
}

/**
* @return ?array<string|bool|int|float|null>
*/
public function globalLabels(): ?array
{
return $this->globalLabels;
}

public function hostname(): ?string
{
return $this->hostname;
Expand Down
4 changes: 2 additions & 2 deletions src/ElasticApm/Impl/ExecutionSegmentContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ public function jsonSerialize()
// APM Server Intake API expects 'tags' key for labels
// https://github.com/elastic/apm-server/blob/7.0/docs/spec/context.json#L46
// https://github.com/elastic/apm-server/blob/7.0/docs/spec/spans/span.json#L88
if ($this->labels !== null) {
SerializationUtil::addNameValueIfNotEmpty('tags', (object)$this->labels, /* ref */ $result);
if ($this->labels !== null && !ArrayUtil::isEmpty($this->labels)) {
SerializationUtil::addNameValue('tags', (object)$this->labels, /* ref */ $result);
}

return SerializationUtil::postProcessResult($result);
Expand Down
2 changes: 1 addition & 1 deletion src/ElasticApm/Impl/Log/LoggableToJsonEncodable.php
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ private static function convertSmallMixedKeysMapArray(array $mapArrayValue, int
{
$result = [];
foreach ($mapArrayValue as $key => $value) {
$result[] = [self::convert($key, $depth), self::convert($value, $depth)];
$result[] = ['key' => self::convert($key, $depth), 'value' => self::convert($value, $depth)];
}
return $result;
}
Expand Down
11 changes: 11 additions & 0 deletions src/ElasticApm/Impl/Metadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use Elastic\Apm\Impl\BackendComm\SerializationUtil;
use Elastic\Apm\Impl\Log\LoggableInterface;
use Elastic\Apm\Impl\Log\LoggableTrait;
use Elastic\Apm\Impl\Util\ArrayUtil;

/**
* Code in this file is part of implementation internals and thus it is not covered by the backward compatibility.
Expand All @@ -36,6 +37,13 @@ final class Metadata implements SerializableDataInterface, LoggableInterface
{
use LoggableTrait;

/**
* @var ?array<string|bool|int|float|null>
*
* @link https://github.com/elastic/apm-server/blob/v7.2.0/docs/spec/metadata.json#L32C10-L32C16
*/
public $labels = null;

/**
* @var ProcessData
*
Expand Down Expand Up @@ -65,6 +73,9 @@ public function jsonSerialize()
{
$result = [];

if ($this->labels !== null && !ArrayUtil::isEmpty($this->labels)) {
SerializationUtil::addNameValue('labels', (object)$this->labels, /* ref */ $result);
}
SerializationUtil::addNameValue('process', $this->process, /* ref */ $result);
SerializationUtil::addNameValue('service', $this->service, /* ref */ $result);
SerializationUtil::addNameValue('system', $this->system, /* ref */ $result);
Expand Down
1 change: 1 addition & 0 deletions src/ElasticApm/Impl/MetadataDiscoverer.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ public function discover(): Metadata
{
$result = new Metadata();

$result->labels = $this->config->globalLabels();
$result->process = $this->discoverProcessData();
$result->service = $this->discoverServiceData();
$result->system = $this->discoverSystemData();
Expand Down
4 changes: 2 additions & 2 deletions src/ElasticApm/Impl/TransactionContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ public function jsonSerialize()
{
$result = SerializationUtil::preProcessResult(parent::jsonSerialize());

if ($this->custom !== null) {
SerializationUtil::addNameValueIfNotEmpty('custom', (object)$this->custom, /* ref */ $result);
if ($this->custom !== null && !ArrayUtil::isEmpty($this->custom)) {
SerializationUtil::addNameValue('custom', (object)$this->custom, /* ref */ $result);
}
SerializationUtil::addNameValueIfNotNull('request', $this->request, /* ref */ $result);
SerializationUtil::addNameValueIfNotNull('user', $this->user, /* ref */ $result);
Expand Down
19 changes: 0 additions & 19 deletions src/ElasticApm/Impl/Util/JsonUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,23 +54,4 @@ public static function encode($data, bool $prettyPrint = false): string
}
return $encodedData;
}

/**
* @param string $encodedData
* @param bool $asAssocArray
*
* @return mixed
*/
public static function decode(string $encodedData, bool $asAssocArray)
{
$decodedData = json_decode($encodedData, /* assoc: */ $asAssocArray);
if ($decodedData === null && ($encodedData !== 'null')) {
throw new JsonException(
'json_decode() failed.'
. ' json_last_error_msg(): ' . json_last_error_msg() . '.'
. ' encodedData: `' . $encodedData . '\''
);
}
return $decodedData;
}
}
7 changes: 7 additions & 0 deletions src/ext/ConfigManager.c
Original file line number Diff line number Diff line change
Expand Up @@ -778,6 +778,7 @@ ELASTIC_APM_DEFINE_FIELD_ACCESS_FUNCS( stringValue, disableInstrumentations )
ELASTIC_APM_DEFINE_FIELD_ACCESS_FUNCS( boolValue, disableSend )
ELASTIC_APM_DEFINE_FIELD_ACCESS_FUNCS( boolValue, enabled )
ELASTIC_APM_DEFINE_FIELD_ACCESS_FUNCS( stringValue, environment )
ELASTIC_APM_DEFINE_FIELD_ACCESS_FUNCS( stringValue, globalLabels )
ELASTIC_APM_DEFINE_FIELD_ACCESS_FUNCS( stringValue, hostname )
ELASTIC_APM_DEFINE_ENUM_FIELD_ACCESS_FUNCS( InternalChecksLevel, internalChecksLevel )
ELASTIC_APM_DEFINE_FIELD_ACCESS_FUNCS( stringValue, logFile )
Expand Down Expand Up @@ -1012,6 +1013,12 @@ static void initOptionsMetadata( OptionMetadata* optsMeta )
ELASTIC_APM_CFG_OPT_NAME_ENVIRONMENT,
/* defaultValue: */ NULL );

ELASTIC_APM_INIT_METADATA(
buildStringOptionMetadata,
globalLabels,
ELASTIC_APM_CFG_OPT_NAME_GLOBAL_LABELS,
/* defaultValue: */ NULL );

ELASTIC_APM_INIT_METADATA(
buildStringOptionMetadata,
hostname,
Expand Down
Loading