Skip to content

Commit

Permalink
Merge pull request #222 from appsignal/stop-agent-helper
Browse files Browse the repository at this point in the history
Add helper to manually stop agent processes
  • Loading branch information
luismiramirez authored Aug 19, 2024
2 parents 3c712c9 + c2e3f26 commit e71b670
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
bump: patch
type: add
---

Add helper to manually stop the agent process for this AppSignal instance.

Some contexts, like serverless functions, exit before AppSignal can ensure all data is sent to our servers. To ensure the data is sent, the new `appsignal.stop()` method can be called to gracefully stop the AppSignal agent process.
16 changes: 16 additions & 0 deletions src/appsignal/client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from __future__ import annotations

import os
import signal
import time
from typing import TYPE_CHECKING

from . import internal_logger as logger
Expand Down Expand Up @@ -48,6 +51,19 @@ def start(self) -> None:
else:
logger.info("AppSignal not starting: no active config found")

def stop(self) -> None:
logger.info("Stopping AppSignal")
working_dir = self._config.option("working_directory_path") or "/tmp/appsignal"
lock_path = os.path.join(working_dir, "agent.lock")
try:
with open(lock_path) as file:
line = file.readline()
pid = int(line.split(";")[2])
os.kill(pid, signal.SIGTERM)
time.sleep(2)
except FileNotFoundError:
logger.info("Agent lock file not found")

def _start_probes(self) -> None:
if self._config.option("enable_minutely_probes"):
start_probes()
18 changes: 18 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

import os
import signal
from unittest.mock import call, mock_open, patch

from appsignal.agent import agent
from appsignal.client import Client
Expand Down Expand Up @@ -98,3 +100,19 @@ def test_client_inactive():
os.environ.get("OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST")
is None
)


@patch("time.sleep", return_value=None)
@patch("os.kill", return_value=None)
@patch("builtins.open", new_callable=mock_open, read_data="123456;running;123\n")
def test_client_stop(mock_open, mock_kill, mock_sleep):
client = Client(active=True, name="MyApp", push_api_key="0000-0000-0000-0000")
client.start()

client.stop()

mock_kill.assert_has_calls(
[
call(123, signal.SIGTERM),
]
)

0 comments on commit e71b670

Please sign in to comment.