Skip to content
Merged
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
28 changes: 21 additions & 7 deletions src/spaceone/core/transaction.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import threading
import traceback
import logging
from threading import local

from spaceone.core import utils, config
from spaceone.core.error import *
from opentelemetry import trace
from opentelemetry.trace import format_trace_id
from opentelemetry.trace.span import TraceFlags
Expand All @@ -18,6 +18,8 @@
class Transaction(object):

def __init__(self, resource: str = None, verb: str = None, trace_id: str = None, meta=None):
self._id = None
self._thread_id = str(threading.current_thread().ident)
self._service = config.get_service()
self._resource = resource
self._verb = verb
Expand Down Expand Up @@ -45,6 +47,10 @@ def _set_meta(self, meta: dict = None):
def id(self) -> str:
return self._id

@property
def thread_id(self) -> str:
return self._thread_id

@property
def service(self) -> str:
return self._service
Expand Down Expand Up @@ -97,28 +103,36 @@ def notify_event(self, message):
handler.notify(self, 'IN_PROGRESS', message)


def get_transaction(trace_id: str = None, is_create: bool = True) -> [Transaction, None]:
def get_transaction(is_create: bool = True) -> [Transaction, None]:
current_span_context = trace.get_current_span().get_span_context()
thread_id = str(threading.current_thread().ident)

if current_span_context.trace_flags == TraceFlags.SAMPLED:
trace_id_from_current_span = format_trace_id(current_span_context.trace_id)
return getattr(LOCAL_STORAGE, trace_id_from_current_span, None)
elif trace_id:
return getattr(LOCAL_STORAGE, trace_id, None)
elif hasattr(LOCAL_STORAGE, thread_id):
return getattr(LOCAL_STORAGE, thread_id, None)
elif is_create:
return create_transaction()
return create_transaction(thread_id=thread_id)
else:
return None


def create_transaction(resource: str = None, verb: str = None, trace_id: str = None,
meta: dict = None) -> Transaction:
meta: dict = None, thread_id: str = None) -> Transaction:
transaction = Transaction(resource, verb, trace_id, meta)
setattr(LOCAL_STORAGE, transaction.id, transaction)

if thread_id:
setattr(LOCAL_STORAGE, thread_id, transaction)
else:
setattr(LOCAL_STORAGE, transaction.id, transaction)

return transaction


def delete_transaction() -> None:
if transaction := get_transaction(is_create=False):
if hasattr(LOCAL_STORAGE, transaction.id):
delattr(LOCAL_STORAGE, transaction.id)
elif hasattr(LOCAL_STORAGE, transaction.thread_id):
delattr(LOCAL_STORAGE, transaction.thread_id)