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

fix: Background Sender reset on Swoole Fork #2645

Merged
merged 17 commits into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from 13 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
6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -918,6 +918,7 @@ TEST_WEB_82 := \
test_web_laravel_9x \
test_web_laravel_10x \
test_web_laravel_11x \
test_web_laravel_octane \
test_web_lumen_81 \
test_web_lumen_90 \
test_web_lumen_100 \
Expand Down Expand Up @@ -972,6 +973,7 @@ TEST_WEB_83 := \
test_web_laravel_9x \
test_web_laravel_10x \
test_web_laravel_11x \
test_web_laravel_octane \
test_web_lumen_81 \
test_web_lumen_90 \
test_web_lumen_100 \
Expand Down Expand Up @@ -1306,6 +1308,10 @@ test_web_laravel_10x: global_test_run_dependencies
test_web_laravel_11x: global_test_run_dependencies
$(call run_composer_with_retry,tests/Frameworks/Laravel/Version_11_x,)
$(call run_tests_debug,--testsuite=laravel-11x-test)
test_web_laravel_octane: global_test_run_dependencies
$(MAKE) test_scenario_swoole5
$(call run_composer_with_retry,tests/Frameworks/Laravel/Octane,)
$(call run_tests_debug,--testsuite=laravel-octane-test)
test_web_lumen_52: global_test_run_dependencies
$(call run_composer_with_retry,tests/Frameworks/Lumen/Version_5_2,)
$(call run_tests_debug,tests/Integrations/Lumen/V5_2)
Expand Down
3 changes: 1 addition & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ x-aliases:
- seccomp:unconfined
# Privileged is required to run some pcntl tests locally as well as native profiler.
privileged: true

- &windows_php_service
volumes:
- .:C:\Users\ContainerAdministrator\app
Expand Down Expand Up @@ -223,7 +223,6 @@ services:
- SNAPSHOTS_DIR=/snapshots
- SNAPSHOT_CI=0
- SNAPSHOT_REMOVED_ATTRS=start,duration,metrics.php.compilation.total_time_ms,metrics.process_id
- SNAPSHOT_IGNORED_ATTRS=meta._dd.parent_id,meta.tracestate
- ENABLED_CHECKS=trace_stall,trace_peer_service,trace_dd_service


Expand Down
4 changes: 4 additions & 0 deletions ext/coms.c
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,10 @@ static void _dd_deinit_read_userdata(void *userdata) {
static ddtrace_coms_stack_t *_dd_coms_attempt_acquire_stack(void) {
ddtrace_coms_stack_t *stack = NULL;

if (!ddtrace_coms_globals.stacks) {
return NULL;
}

for (size_t i = 0; i < ddtrace_coms_globals.max_backlog_size; i++) {
ddtrace_coms_stack_t *stack_tmp = ddtrace_coms_globals.stacks[i];
if (stack_tmp && atomic_load(&stack_tmp->refcount) == 0 && atomic_load(&stack_tmp->bytes_written) > 0) {
Expand Down
49 changes: 49 additions & 0 deletions ext/ddtrace.c
Original file line number Diff line number Diff line change
Expand Up @@ -2136,6 +2136,55 @@ static void dd_ensure_root_span(void) {
}
}

/* {{{ proto void dd_handle_fork(): void */
PHP_FUNCTION(dd_handle_fork) {
UNUSED(execute_data);
UNUSED(return_value);
// CHILD PROCESS
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume it's still todo to deduplicate with the code in handlers_pcntl.c?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you exactly mean by "deduplicate"? Do you mean some refactoring duplicated code (using this function in the pcntl code)?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, refactoring the common code out into a single function.

#ifndef _WIN32
if (!get_global_DD_TRACE_SIDECAR_TRACE_SENDER()) {
ddtrace_coms_curl_shutdown();
ddtrace_coms_clean_background_sender_after_fork();
}
#endif
if (DDTRACE_G(remote_config_reader)) {
ddog_agent_remote_config_reader_drop(DDTRACE_G(remote_config_reader));
DDTRACE_G(remote_config_reader) = NULL;
}
ddtrace_seed_prng();
ddtrace_generate_runtime_id();
ddtrace_reset_sidecar_globals();
ddtrace_compile_time_reset();
dd_prepare_for_new_trace();
if (!get_DD_TRACE_FORKED_PROCESS()) {
ddtrace_disable_tracing_in_current_request();
}
if (get_DD_TRACE_ENABLED()) {
if (get_DD_DISTRIBUTED_TRACING()) {
DDTRACE_G(distributed_parent_trace_id) = ddtrace_peek_span_id();
DDTRACE_G(distributed_trace_id) = ddtrace_peek_trace_id();
} else {
DDTRACE_G(distributed_parent_trace_id) = 0;
DDTRACE_G(distributed_trace_id) = (ddtrace_trace_id){ 0 };
}
ddtrace_free_span_stacks(true);
ddtrace_init_span_stacks();
if (get_DD_TRACE_GENERATE_ROOT_SPAN()) {
ddtrace_push_root_span();
}
}

#ifndef _WIN32
if (!get_global_DD_TRACE_SIDECAR_TRACE_SENDER()) {
ddtrace_coms_init_and_start_writer();

if (ddtrace_coms_agent_config_handle) {
ddog_agent_remote_config_reader_for_anon_shm(ddtrace_coms_agent_config_handle, &DDTRACE_G(remote_config_reader));
}
}
#endif
}

/* {{{ proto string DDTrace\active_span() */
PHP_FUNCTION(DDTrace_active_span) {
if (zend_parse_parameters_none() == FAILURE) {
Expand Down
5 changes: 5 additions & 0 deletions ext/ddtrace.stub.php
Original file line number Diff line number Diff line change
Expand Up @@ -977,4 +977,9 @@ function dd_untrace(string $functionName, string $className = null): bool {}
* @param int $timeout Timeout in milliseconds to wait for the flush to complete
*/
function dd_trace_synchronous_flush(int $timeout): void {}

/**
* @internal
*/
function dd_handle_fork(): void {}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we please add no new functions to top-level namespace, but add to DDTrace or DDTrace\Internal as appropriate?

}
6 changes: 5 additions & 1 deletion ext/ddtrace_arginfo.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: 1271064f2b0fcdc3d20e2f3d6c780607b300c5f9 */
* Stub hash: e3aae0a14c816df228a915cf422a2f79fe458eb1 */

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_DDTrace_trace_method, 0, 3, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, className, IS_STRING, 0)
Expand Down Expand Up @@ -251,6 +251,8 @@ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_dd_trace_synchronous_flush, 0, 1
ZEND_ARG_TYPE_INFO(0, timeout, IS_LONG, 0)
ZEND_END_ARG_INFO()

#define arginfo_dd_handle_fork arginfo_DDTrace_flush

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_DDTrace_SpanLink_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()

Expand Down Expand Up @@ -336,6 +338,7 @@ ZEND_FUNCTION(DDTrace_trace_function);
ZEND_FUNCTION(DDTrace_trace_method);
ZEND_FUNCTION(dd_untrace);
ZEND_FUNCTION(dd_trace_synchronous_flush);
ZEND_FUNCTION(dd_handle_fork);
ZEND_METHOD(DDTrace_SpanLink, jsonSerialize);
ZEND_METHOD(DDTrace_SpanLink, fromHeaders);
ZEND_METHOD(DDTrace_SpanData, getDuration);
Expand Down Expand Up @@ -411,6 +414,7 @@ static const zend_function_entry ext_functions[] = {
ZEND_FALIAS(dd_trace_method, DDTrace_trace_method, arginfo_dd_trace_method)
ZEND_FE(dd_untrace, arginfo_dd_untrace)
ZEND_FE(dd_trace_synchronous_flush, arginfo_dd_trace_synchronous_flush)
ZEND_FE(dd_handle_fork, arginfo_dd_handle_fork)
ZEND_FE_END
};

Expand Down
2 changes: 1 addition & 1 deletion ext/integrations/integrations.c
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ void ddtrace_integrations_minit(void) {
DD_SET_UP_DEFERRED_LOADING_BY_METHOD(DDTRACE_INTEGRATION_SLIM, "Slim\\App", "__construct",
"DDTrace\\Integrations\\Slim\\SlimIntegration");

DD_SET_UP_DEFERRED_LOADING_BY_METHOD(DDTRACE_INTEGRATION_SWOOLE, "Swoole\\Http\\Server", "on",
DD_SET_UP_DEFERRED_LOADING_BY_METHOD(DDTRACE_INTEGRATION_SWOOLE, "Swoole\\Http\\Server", "__construct",
"DDTrace\\Integrations\\Swoole\\SwooleIntegration");

DD_SET_UP_DEFERRED_LOADING_BY_METHOD(DDTRACE_INTEGRATION_LARAVELQUEUE, "Illuminate\\Queue\\Worker", "__construct",
Expand Down
48 changes: 46 additions & 2 deletions src/DDTrace/Integrations/Swoole/SwooleIntegration.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Swoole\Http\Server;
use function DDTrace\consume_distributed_tracing_headers;
use function DDTrace\extract_ip_from_headers;
use function DDTrace\hook_method;

class SwooleIntegration extends Integration
{
Expand Down Expand Up @@ -105,6 +106,27 @@ function (HookData $hook) use ($integration, $server, $scheme) {
);
}

public function instrumentWorkerStart(callable $callback, SwooleIntegration $integration, Server $server)
{
\DDTrace\install_hook(
$callback,
function (HookData $hook) use ($integration, $server) {
dd_handle_fork();
}
);
}

public function instrumentWorkerStop(callable $callback, SwooleIntegration $integration, Server $server)
{
\DDTrace\install_hook(
$callback,
null,
function (HookData $hook) use ($integration, $server) {
dd_handle_fork();
}
);
}

public function init(): int
{
if (version_compare(swoole_version(), '5.0.2', '<')) {
Expand All @@ -116,6 +138,16 @@ public function init(): int
ini_set("datadog.trace.auto_flush_enabled", 1);
ini_set("datadog.trace.generate_root_span", 0);

\DDTrace\hook_method(
'Swoole\Http\Server',
'__construct',
function ($server) use ($integration) {
foreach (['workerstart', 'workerstop', 'workerexit', 'workererror'] as $serverEvent) {
$server->on($serverEvent, function () { });
}
}
);

\DDTrace\hook_method(
'Swoole\Http\Server',
'on',
Expand All @@ -127,9 +159,21 @@ function ($server, $scope, $args, $retval) use ($integration) {

list($eventName, $callback) = $args;

if ($eventName === 'request') {
$integration->instrumentRequestStart($callback, $integration, $server);
$eventName = strtolower($eventName);
switch ($eventName) {
case 'request':
$integration->instrumentRequestStart($callback, $integration, $server);
break;
case 'workerstart':
$integration->instrumentWorkerStart($callback, $integration, $server);
break;
case 'workerstop':
case 'workerexit':
case 'workererror':
$integration->instrumentWorkerStop($callback, $integration, $server);
break;
}

}
);

Expand Down
25 changes: 16 additions & 9 deletions tests/Common/TracerTestTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,10 +275,11 @@ public function resetRequestDumper()
*
* @param $fn
* @param null $tracer
* @param callable|null $until
* @return array[]
* @throws \Exception
* @throws Exception
*/
public function tracesFromWebRequest($fn, $tracer = null)
public function tracesFromWebRequest($fn, $tracer = null, callable $until = null)
{
self::putEnv('DD_TRACE_SHUTDOWN_TIMEOUT=666666'); // Arbitrarily high value to avoid flakiness
self::putEnv('DD_TRACE_AGENT_RETRIES=3');
Expand All @@ -297,7 +298,7 @@ public function tracesFromWebRequest($fn, $tracer = null)
self::putEnv('DD_TRACE_SHUTDOWN_TIMEOUT');
self::putEnv('DD_TRACE_AGENT_RETRIES');

return $this->parseTracesFromDumpedData();
return $this->parseTracesFromDumpedData($until);
}

private function parseRawDumpedTraces($rawTraces)
Expand Down Expand Up @@ -331,9 +332,9 @@ private function parseRawDumpedTraces($rawTraces)
* @return array
* @throws \Exception
*/
private function parseTracesFromDumpedData()
private function parseTracesFromDumpedData(callable $until = null)
{
$loaded = $this->retrieveDumpedTraceData();
$loaded = $this->retrieveDumpedTraceData($until);
if (!$loaded) {
return [];
}
Expand Down Expand Up @@ -431,11 +432,17 @@ public function retrieveDumpedData(callable $until = null, $throw = false)
return $allResponses;
}

public function retrieveDumpedTraceData()
public function retrieveDumpedTraceData(callable $until = null)
{
return array_values(array_filter($this->retrieveDumpedData(), function ($request) {
return strpos($request["uri"] ?? "", "/telemetry/") !== 0;
}));
if ($until) {
return array_values(array_filter($this->retrieveDumpedData($until), function ($request) use ($until) {
return $until($request);
}));
} else {
return array_values(array_filter($this->retrieveDumpedData(), function ($request) {
return strpos($request["uri"] ?? "", "/telemetry/") !== 0;
}));
}
}

/**
Expand Down
12 changes: 10 additions & 2 deletions tests/Common/WebFrameworkTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ protected static function isSwoole()
return false;
}

protected static function isOctane()
{
return false;
}

protected static function isFrankenphp()
{
return false;
Expand Down Expand Up @@ -164,8 +169,11 @@ protected static function setUpWebServer(array $additionalEnvs = [], array $addi
if ($version = static::getRoadrunnerVersion()) {
self::$appServer->setRoadrunner($version);
}
if ($version = static::isSwoole()) {
self::$appServer->setSwoole($version);
if (static::isOctane()) {
self::$appServer->setOctane();
}
if (static::isSwoole()) {
self::$appServer->setSwoole();
}
if (static::isFrankenphp()) {
if (!ZEND_THREAD_SAFE) {
Expand Down
18 changes: 18 additions & 0 deletions tests/Frameworks/Laravel/Octane/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false

[*.{yml,yaml}]
indent_size = 2

[docker-compose.yml]
indent_size = 4
Loading
Loading