-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInstanaTransport.php
217 lines (173 loc) · 6.5 KB
/
InstanaTransport.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
<?php
declare(strict_types=1);
namespace Instana;
use OpenTelemetry\SDK\Common\Export\TransportInterface;
use OpenTelemetry\SDK\Common\Future\CancellationInterface;
use OpenTelemetry\SDK\Common\Future\CompletedFuture;
use OpenTelemetry\SDK\Common\Future\ErrorFuture;
use OpenTelemetry\SDK\Common\Future\FutureInterface;
use OpenTelemetry\API\Behavior\LogsMessagesTrait;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\ResponseInterface;
use BadMethodCallException;
use Exception;
use RuntimeException;
class InstanaTransport implements TransportInterface
{
use LogsMessagesTrait;
const CONTENT_TYPE = 'application/json';
const ATTEMPTS = 3;
private Client $client;
private ?string $agent_uuid = null;
private ?int $pid = null;
private array $secrets = [];
private array $tracing = [];
private bool $closed = true;
private array $headers = [];
public function __construct(
private readonly string $endpoint,
private readonly float $timeout = 0.0
) {
$this->headers += ['Content-Type' => self::CONTENT_TYPE];
if ($timeout > 0.0) {
$this->headers += ['timeout' => $timeout];
}
$this->client = new Client(['base_uri' => $endpoint]);
for ($attempt = 0; $attempt < self::ATTEMPTS && !$this->announce(); $attempt++) {
self::logDebug("Discovery request failed, attempt " . $attempt);
sleep(5);
}
if (is_null($this->agent_uuid) || is_null($this->pid)) {
throw new Exception('Failed announcement in transport');
}
}
public function contentType(): string
{
return self::CONTENT_TYPE;
}
public function send(string $payload, ?CancellationInterface $cancellation = null): FutureInterface
{
if ($this->closed) {
return new ErrorFuture(new BadMethodCallException('Transport closed'));
}
$response = $this->sendPayload($payload);
$code = $response->getStatusCode();
if ($code != 204 && $code != 307) {
self::logDebug("Sending failed with code " . $code);
return new ErrorFuture(new RuntimeException('Payload failed to send with code ' . $code));
}
return new CompletedFuture('Payload successfully sent');
}
private function sendPayload(string $payload): ResponseInterface
{
return $this->client->sendRequest(
new Request(
method: 'POST',
uri: new Uri('/com.instana.plugin.php/traces.' . $this->pid),
headers: $this->headers,
body: $payload
)
);
}
public function shutdown(?CancellationInterface $cancellation = null): bool
{
if ($this->closed) {
return false;
}
return $this->closed = true;
}
public function forceFlush(?CancellationInterface $cancellation = null): bool
{
return !$this->closed;
}
private function announce(): bool
{
self::logDebug("Announcing to " . $this->endpoint);
// Phase 1) Host lookup.
$response = $this->client->sendRequest(
new Request(method: 'GET', uri: new Uri('/'), headers: $this->headers)
);
$code = $response->getStatusCode();
$msg = $response->getBody()->getContents();
if ($code != 200 && !array_key_exists('version', json_decode($msg, true))) {
self::LogError("Failed to lookup host. Received code " . $code . " with message: " . $msg);
$this->closed = true;
return false;
}
self::logDebug("Phase 1 announcement response code " . $code);
// Phase 2) Announcement.
$response = $this->client->sendRequest(
new Request(
method: 'PUT',
uri: new Uri('/com.instana.plugin.php.discovery'),
headers: $this->headers,
body: $this->getAnnouncementPayload()
)
);
$code = $response->getStatusCode();
$msg = $response->getBody()->getContents();
self::logDebug("Phase 2 announcement response code " . $code);
if ($code < 200 || $code >= 300) {
self::LogError("Failed announcement. Received code " . $code . " with message: " . $msg);
$this->closed = true;
return false;
}
$content = json_decode($msg, true);
if (!array_key_exists('pid', $content)) {
self::LogError("Failed to receive a pid from agent");
$this->closed = true;
return false;
}
$this->pid = $content['pid'];
$this->agent_uuid = $content['agentUuid'];
// Optional values that we may receive from the agent.
if (array_key_exists('secrets', $content)) $this->secrets = $content['secrets'];
if (array_key_exists('tracing', $content)) $this->tracing = $content['tracing'];
// Phase 3) Wait for the agent ready signal.
for ($retry = 0; $retry < 5; $retry++) {
if ($retry) self::logDebug("Agent not yet ready, attempt " . $retry);
$response = $this->client->sendRequest(
new Request(
method: 'HEAD',
uri: new Uri('/com.instana.plugin.php.' . $this->pid),
headers: $this->headers
)
);
$code = $response->getStatusCode();
self::logDebug("Phase 3 announcement endpoint status " . $code);
if ($code >= 200 && $code < 300) {
$this->closed = false;
return true;
}
sleep(1);
}
$this->closed = true;
return false;
}
private function getAnnouncementPayload(): string
{
$cmdline_args = file_get_contents("/proc/self/cmdline");
$cmdline_args = explode("\0", $cmdline_args);
$cmdline_args = array_slice($cmdline_args, 1, count($cmdline_args) - 2);
return json_encode(array(
"pid" => getmypid(),
"pidFromParentNS" => false,
"pidNamespace" => readlink("/proc/self/ns/pid"),
"name" => readlink("/proc/self/exe"),
"args" => $cmdline_args,
"cpuSetFileContent" => "/",
"fd" => null,
"inode" => null
));
}
public function getPid(): ?string
{
return is_null($this->pid) ? null : strval($this->pid);
}
public function getUuid(): ?string
{
return $this->agent_uuid;
}
}