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

Make batch processor fork aware and reinit when needed #2242

Merged
merged 27 commits into from
Nov 5, 2021
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
1b36f45
Experiment with deamon start delay
srikanthccv Oct 27, 2021
2d6b574
Fix tests
srikanthccv Oct 29, 2021
799b66a
Merge branch 'main' into delay-start
srikanthccv Oct 29, 2021
f21a65c
Fix lint
srikanthccv Oct 29, 2021
3573555
Merge branch 'delay-start' of github.com:lonewolf3739/opentelemetry-p…
srikanthccv Oct 29, 2021
ff89fc0
Add _at_fork_reinit
srikanthccv Oct 29, 2021
a003bea
Reinit worker thread
srikanthccv Oct 30, 2021
b07758f
Update _at_fork_reinit impl
srikanthccv Oct 31, 2021
89a7da5
Change order
srikanthccv Oct 31, 2021
92456de
Reorder
srikanthccv Oct 31, 2021
a3ec380
Update impl
srikanthccv Oct 31, 2021
91e8ebb
black
srikanthccv Oct 31, 2021
abdc65d
Undo prev change
srikanthccv Oct 31, 2021
9c9916a
Merge branch 're-init' into delay-start
srikanthccv Oct 31, 2021
759b0a8
Add test bsp fork
srikanthccv Nov 1, 2021
9624454
Fix lint
srikanthccv Nov 1, 2021
3909996
Conditionally run test
srikanthccv Nov 1, 2021
08f7db5
more testing
srikanthccv Nov 2, 2021
0e4d3ce
Fix lint
srikanthccv Nov 2, 2021
8341f35
Merge branch 'main' into delay-start
srikanthccv Nov 2, 2021
c473e34
Review suggestions
srikanthccv Nov 4, 2021
c36bc68
Merge branch 'main' into delay-start
srikanthccv Nov 4, 2021
1a5063c
Update log processor too
srikanthccv Nov 4, 2021
f599c16
Add CHANGELOG entry
srikanthccv Nov 4, 2021
b684e0a
Merge branch 'main' into delay-start
srikanthccv Nov 5, 2021
02c7bb9
Fix changelog
srikanthccv Nov 5, 2021
97484e8
Merge branch 'delay-start' of github.com:lonewolf3739/opentelemetry-p…
srikanthccv Nov 5, 2021
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
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import collections
import logging
import os
import sys
import threading
import typing
Expand Down Expand Up @@ -197,6 +198,11 @@ def __init__(
None
] * self.max_export_batch_size # type: typing.List[typing.Optional[Span]]
self.worker_thread.start()
# Only available in *nix since py37.
if hasattr(os, "register_at_fork"):
os.register_at_fork(
after_in_child=self._at_fork_reinit
) # pylint: disable=broad-except

def on_start(
self, span: Span, parent_context: typing.Optional[Context] = None
Expand All @@ -220,6 +226,24 @@ def on_end(self, span: ReadableSpan) -> None:
with self.condition:
self.condition.notify()

def _at_fork_reinit(self):
# could be in an inconsistent state after fork, reinitialise by calling `_at_fork_reinit`
# (creates a new lock internally https://github.com/python/cpython/blob/main/Python/thread_pthread.h#L727)
# if exists, otherwise create a new one.
if hasattr(self.condition, "_at_fork_reinit"):
srikanthccv marked this conversation as resolved.
Show resolved Hide resolved
self.condition._at_fork_reinit()
else:
self.condition = threading.Condition(threading.Lock())
aabmass marked this conversation as resolved.
Show resolved Hide resolved

self.queue.clear()
lzchen marked this conversation as resolved.
Show resolved Hide resolved

# worker_thread is local to a process, only the thread that issued fork continues
# to exist. A new worker thread must be started in child process.
self.worker_thread = threading.Thread(
lzchen marked this conversation as resolved.
Show resolved Hide resolved
name="OtelBatchSpanProcessor", target=self.worker, daemon=True
)
self.worker_thread.start()

def worker(self):
timeout = self.schedule_delay_millis / 1e3
flush_request = None # type: typing.Optional[_FlushRequest]
Expand Down
64 changes: 63 additions & 1 deletion opentelemetry-sdk/tests/trace/export/test_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import os
import sys
import threading
import time
import unittest
Expand All @@ -30,6 +31,10 @@
OTEL_BSP_SCHEDULE_DELAY,
)
from opentelemetry.sdk.trace import export
from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
InMemorySpanExporter,
)
from opentelemetry.test.concurrency_test import ConcurrencyTestBase


class MySpanExporter(export.SpanExporter):
Expand Down Expand Up @@ -157,7 +162,7 @@ def _create_start_and_end_span(name, span_processor):
span.end()


class TestBatchSpanProcessor(unittest.TestCase):
class TestBatchSpanProcessor(ConcurrencyTestBase):
@mock.patch.dict(
"os.environ",
{
Expand Down Expand Up @@ -356,6 +361,63 @@ def test_batch_span_processor_not_sampled(self):
self.assertEqual(len(spans_names_list), 0)
span_processor.shutdown()

def _check_fork_trace(self, exporter, expected):
time.sleep(0.5) # give some time for the exporter to upload spans
spans = exporter.get_finished_spans()
for span in spans:
self.assertIn(span.name, expected)

@unittest.skipUnless(
hasattr(os, "fork") and sys.version_info >= (3, 7),
"needs *nix and minor version 7 or later",
)
def test_batch_span_processor_fork(self):
tracer_provider = trace.TracerProvider()
tracer = tracer_provider.get_tracer(__name__)

exporter = InMemorySpanExporter()
span_processor = export.BatchSpanProcessor(
exporter,
max_queue_size=256,
max_export_batch_size=64,
schedule_delay_millis=10,
)
tracer_provider.add_span_processor(span_processor)
with tracer.start_as_current_span("foo"):
pass
time.sleep(0.5) # give some time for the exporter to upload spans

self.assertTrue(span_processor.force_flush())
self.assertEqual(len(exporter.get_finished_spans()), 1)
exporter.clear()
pid = os.fork()
if pid:
aabmass marked this conversation as resolved.
Show resolved Hide resolved
with tracer.start_as_current_span("parent"):
pass
self._check_fork_trace(exporter, ["parent"])
else:
exporter.clear()

def _target():
with tracer.start_as_current_span(f"span") as s:
s.set_attribute("i", "1")
with tracer.start_as_current_span("temp"):
pass

self.run_with_many_threads(_target, 100)

time.sleep(0.5)

spans = exporter.get_finished_spans()
self.assertEqual(len(spans), 200)
exporter.clear()
with tracer.start_as_current_span("child"):
with tracer.start_as_current_span("inner"):
pass
self._check_fork_trace(exporter, ["child", "inner"])

span_processor.shutdown()

def test_batch_span_processor_scheduled_delay(self):
"""Test that spans are exported each schedule_delay_millis"""
spans_names_list = []
Expand Down