43 #define NCBI_USE_ERRCODE_X Corelib_Diag
90 size_t sep_pos =
NPOS;
92 for (; pos < hit.size(); pos++) {
104 if (sep_pos == 0)
return false;
105 if (sep_pos ==
NPOS)
return true;
109 size_t last_digit = sep_pos;
110 for (pos = sep_pos + 1; pos < hit.size(); pos++) {
114 if (pos == sep_pos + 1)
return false;
116 if (last_digit + 1 != pos)
return false;
123 if (
isdigit(c) ) last_digit = pos;
126 return pos > sep_pos + 1;
139 switch (action->
Get()) {
148 <<
", sanitized value will be used: " <<
m_HitId);
168 m_HitIDLoggedFlag(0),
175 m_AutoIncOnPost(
false),
179 m_Version(sm_VersionCounter.Add(1)),
194 return s_RequestCount.
Add(1);
208 if (!ignore_app_state &&
251 oss <<
ctx.GetStringUID(
ctx.UpdateUID()) <<
'_' << setw(4) << setfill(
'0')
326 size_t len =
ip.size();
330 }
else if (
ip[0] !=
'[') {
332 }
else if (
len < 3 ||
ip[
len - 1] !=
']') {
391 static bool s_DefaultAutoIncRequestIDOnPostFlag =
false;
392 return s_DefaultAutoIncRequestIDOnPostFlag;
415 const string& hit = hit_id.
GetHitId();
418 ERR_POST_X(28,
Warning <<
"Changing hit ID after one has been logged. New hit id is: " << hit);
439 LOG_ISSUED_SUBHIT_LIMIT);
451 unsigned int sub_hit_id;
462 hit_id +=
"." + subhit;
464 if (increment && sub_hit_id <= TIssuedSubHitLimitParam::GetDefault()) {
486 "Bad session ID format: " + session);
503 if (session_id.size() < 24)
return false;
504 if (session_id[16] !=
'_')
return false;
510 CTempString rqid(session_id, 17, session_id.size() - 20);
518 if ( session_id.empty() ) {
522 ITERATE (
string, c, session_id) {
548 LOG_ON_BAD_SESSION_ID);
562 LOG_SESSION_ID_FORMAT);
568 return TOnBadSessionId::GetDefault();
574 TOnBadSessionId::SetDefault(action);
580 return TSessionIdFormat::GetDefault();
586 TSessionIdFormat::SetDefault(fmt);
620 if (hit_ids.empty() || hit_ids.find_first_of(
", ") ==
NPOS) {
627 return ids.empty() ?
kEmptyStr : ids.back();
634 if (session_ids.empty() || session_ids.find_first_of(
", ") ==
NPOS) {
641 if (*it !=
"UNK_SESSION") {
715 if ( sub_phid.empty() ) {
738 ctx.UnsetSessionID();
797 NCBI_CONTEXT_FIELDS);
811 string fields_var = TNcbiContextFields::GetDefault();
812 if ( !fields_var.empty() ) {
815 ITERATE(list<string>, field, fields) {
849 props[*it] =
env.Get(*it);
860 (*sm_EnvContextProperties)[norm_prop] = it->second;
921 switch (GetErrCode()) {
923 case eBadHit:
return "eBadHit";
945 ctx.PrintRequestStart();
964 ctx.PrintRequestStop();
CNcbiOstrstreamToString class helps convert CNcbiOstrstream to a string Sample usage:
T & Get(void)
Create the variable if not created yet, return the reference.
Helper class to hold hit id and sub-hit counter which can be shared between multiple request contexts...
URL-decoder for string pairs parser.
URL-encoder for string pairs parser.
CTempString implements a light-weight string on top of a storage buffer whose lifetime management is ...
container_type::const_iterator const_iterator
container_type::iterator iterator
const_iterator end() const
iterator_bool insert(const value_type &val)
const_iterator find(const key_type &key) const
static const struct name_t names[]
const CNcbiEnvironment & GetEnvironment(void) const
Get the application's cached environment.
static CNcbiApplicationGuard InstanceGuard(void)
Singleton method.
#define ITERATE(Type, Var, Cont)
ITERATE macro to sequence through container elements.
#define REVERSE_ITERATE(Type, Var, Cont)
ITERATE macro to reverse sequence through container elements.
TValue Add(int delta) THROWS_NONE
Atomically add value (=delta), and return new counter value.
static string SelectLastHitID(const string &hit_ids)
Select the last hit id from the list of ids separated with commas and optional spaces.
TSubHitId GetNextSubHitId(void)
Get next sub-hit id value.
CDiagContext_Extra & Print(const string &name, const string &value)
The method does not print the argument, but adds it to the string.
void UnsetRequestStatus(void)
ESessionIDFormat
Session ID format.
string x_GetHitID(CDiagContext::EDefaultHitIDFlags flag) const
void SetBytesWr(Int8 bytes)
CEncodedString m_SessionID
static void SetRequestTracer(const shared_ptr< IRequestTracer > &tracer)
Set request tracer to be called on context events (start/stop etc.).
EDiagAppState GetGlobalAppState(void) const
Always returns global application state.
CDiagContext & GetDiagContext(void)
Get diag context instance.
void x_SetHitID(const CSharedHitId &hit_id)
static const CMask & sx_GetContextFieldsMask(void)
void SetAppState(EDiagAppState state)
static void SetRequestContext(CRequestContext *ctx)
Shortcut to CDiagContextThreadData::GetThreadData().SetRequestContext()
TSubHitId GetCurrentSubHitId(void) const
Get current sub-hit id value.
CRef< CRequestContext > m_SavedContext
static void SetBadSessionIDAction(EOnBadSessionID action)
void x_SetProp(EProperty prop)
static string sx_NormalizeContextPropertyName(const string &name)
string GetSessionID(void) const
Session ID.
string Serialize(EFormat format) const
Serialize current values using the specified format.
CDiagContext_Extra Extra(void) const
Create a temporary CDiagContext_Extra object.
bool IsSetRequestStatus(void) const
const string & GetProperty(const string &name) const
Get property value or empty string.
bool x_IsSetProp(EProperty prop) const
const string & GetNextSubHitID(CTempString prefix=CTempString())
Get current hit id appended with auto-incremented sub-hit id.
static unique_ptr< TPassThroughProperties > sm_EnvContextProperties
void SetClientIP(const string &client)
static TCount GetNextRequestID(void)
Return the next available application-wide request ID.
const string & SetHitID(void)
Generate unique hit id, assign it to this request, return the hit id value.
CRequestContextGuard_Base(CRequestContext *context, TFlags flags=0)
Initialize guard.
static string SelectLastSessionID(const string &session_ids)
Select the last session id from the list of ids separated with commas and optional spaces,...
void SetProperty(const string &name, const string &value)
Add/change property.
bool m_OriginatesFromThrow
void x_DeserializeUrlEncoded(CTempString data)
bool IsSetSessionID(void) const
void SetStatus(int status)
Set request context status.
TCount GetRequestID(void) const
Get request ID (or zero if not set).
string GetClientIP(void) const
Client IP/hostname.
static bool & sx_GetDefaultAutoIncRequestIDOnPost(void)
CRef< CRequestContext > Clone(void) const
Copy current request context to a new one.
void UnsetProperty(const string &name)
Remove property from the map.
string x_SerializeUrlEncoded(void) const
void x_SetPassThroughProp(CTempString name, CTempString value, bool update) const
static shared_ptr< IRequestTracer > sm_Tracer
static ESessionIDFormat GetAllowedSessionIDFormat(void)
Get/set allowed session id format.
void SetRequestStatus(int status)
bool IsSetHitID(EHitIDSource src=eHitID_Any) const
Check if there's an explicit hit id or the default one.
void x_UpdateStdContextProp(CTempString name) const
static bool IsValidSessionID(const string &session_id)
Check if session id fits the allowed format.
void UnsetRequestID(void)
Reset request ID.
const string & GetDtab(void) const
static bool GetDefaultAutoIncRequestIDOnPost(void)
Get default auto-increment flag.
static CAtomicCounter sm_VersionCounter
bool x_IsSetPassThroughProp(CTempString name, bool update) const
void Deserialize(CTempString data, EFormat format)
Deserialize values using the specified format.
#define ERR_POST_X(err_subcode, message)
Error posting with default error code and given error subcode.
bool IsSetProperty(const string &name) const
Check if the property has a value (even if it's an empty string).
static EOnBadSessionID GetBadSessionIDAction(void)
Get/set session id error action.
const CStopWatch & GetRequestTimer(void) const
Request execution timer.
EFormat
Supported serialization/deserialization formats.
CRef< CRequestContext > m_Context
static unique_ptr< CMaskFileName > sm_ContextFields
bool IsSetDtab(void) const
Dtab.
void UnsetSessionID(void)
void x_SetHitId(const string &hit_id)
Set new hit id, checks its validity.
const string & x_GetPassThroughProp(CTempString name, bool update) const
void x_ResetPassThroughProp(CTempString name, bool update) const
void x_LoadEnvContextProperties(void)
const string & SetSessionID(void)
Create and set new session ID.
void SetBytesRd(Int8 bytes)
virtual ~CRequestContext(void)
static void SetAllowedSessionIDFormat(ESessionIDFormat fmt)
CSharedHitId x_GetDefaultHitID(EDefaultHitIDFlags flag) const
EDiagAppState
Application execution states shown in the std prefix.
bool IsSetClientIP(void) const
SDiagMessage::TCount TCount
EOnBadSessionID
Session ID error actions.
void AddPassThroughProperty(const string &name, const string &value)
Add pass-through value if it matches a pattern from NCBI_CONTEXT_FIELDS.
void UnsetHitID(void)
Reset explicit hit id.
string GetHitID(void) const
Get explicit hit id or the default one (from HTTP_NCBI_PHID etc).
void Reset(void)
Reset all properties to the initial state.
TPassThroughProperties m_PassThroughProperties
static void SetDefaultAutoIncRequestIDOnPost(bool enable)
Set default auto-increment flag used for each default request context.
void SetShared(void) const
Mark this hit id as a shared one and start using shared counter.
CRequestContext(TContextFlags flags=fDefault)
shared_ptr< IRequestTracer > m_Tracer
const string & GetHitId(void) const
Get hit id value.
void x_UpdateStdPassThroughProp(CTempString name) const
void Release(void)
Release the guarded context, restore the saved context if any, do not perform any other actions (logg...
const string & GetCurrentSubHitID(CTempString prefix=CTempString())
Get the last generated sub-hit id.
void x_UpdateSubHitID(bool increment, CTempString prefix)
void x_LogHitID(bool ignore_app_state=false) const
~CRequestContextGuard_Base(void)
Destroy guard.
CRef< CRequestContext > m_RequestContext
EDiagAppState GetAppState(void) const
Application state.
virtual const char * GetErrCodeString(void) const override
Translate from the error code value to its string representation.
bool x_CanModify(void) const
void SetDefaultErrorStatus(int status)
Set default error status, which will be used if an uncaught exception is detected.
@ fResetOnStart
Reset values when printing request-start.
@ eSID_Other
Any other format.
@ eSID_Ncbi
Strict NCBI format: (UID:16)_(RqID:4+)SID.
@ eSID_Standard
Alpanum, underscore, -.:@, (default)
@ eBadSession
Invalid session id.
@ fPrintRequestStart
Print request-start automatically in the constructor.
@ eFormat_UrlEncoded
name=value pairs URL-encoded and separated with '&'
@ eDiagAppState_RequestEnd
RE.
@ eDiagAppState_RequestBegin
RB.
@ eDiagAppState_NotSet
Reserved value, never used in messages.
@ eDiagAppState_Request
R.
@ eOnBadSID_Allow
Don't validate session id.
@ eOnBadSID_IgnoreAndReport
Ignore and show warning.
@ eOnBadSID_AllowAndReport
Accept but show warning (default).
@ eOnBadSID_Throw
Throw on bad session id.
@ eOnBadSID_Ignore
Ignore bad session id.
#define NCBI_THROW(exception_class, err_code, message)
Generic macro to throw an exception, given the exception class, error code and message string.
void Warning(CExceptionArgs_Base &args)
virtual const char * GetErrCodeString(void) const
Get error code interpreted as text.
TObjectType * GetNonNullPointer(void)
Get pointer value and throw a null pointer exception if pointer is null.
void Reset(void)
Reset reference object.
@ eParam_NoThread
Do not use per-thread values.
#define END_NCBI_SCOPE
End previously defined NCBI scope.
#define BEGIN_NCBI_SCOPE
Define ncbi namespace.
static string PrintableString(const CTempString str, TPrintableMode mode=fNewLine_Quote|fNonAscii_Passthru)
Get a printable version of the specified string.
void Parse(const CTempString str, NStr::EMergeDelims merge_argsep=NStr::eMergeDelims)
Parse the string.
static CTempString TruncateSpaces_Unsafe(const CTempString str, ETrunc where=eTrunc_Both)
Truncate whitespace in a string.
string Merge(void) const
Merge name-value pairs into a single string using the currently set separators and the provided encod...
static list< string > & Split(const CTempString str, const CTempString delim, list< string > &arr, TSplitFlags flags=0, vector< SIZE_TYPE > *token_pos=NULL)
Split a string using specified delimiters.
static bool EndsWith(const CTempString str, const CTempString end, ECase use_case=eCase)
Check if a string ends with a specified suffix value.
const char * g_GetNcbiString(ENcbiStrings what)
const string & GetOriginalString(void) const
Get the original unencoded string.
bool empty(void) const
Return true if the represented string is empty (i.e., the length is zero)
static string & Replace(const string &src, const string &search, const string &replace, string &dst, SIZE_TYPE start_pos=0, SIZE_TYPE max_replace=0, SIZE_TYPE *num_replace=0)
Replace occurrences of a substring within a string.
static Uint8 StringToUInt8(const CTempString str, TStringToNumFlags flags=0, int base=10)
Convert string to Uint8.
static unsigned int StringToUInt(const CTempString str, TStringToNumFlags flags=0, int base=10)
Convert string to unsigned int.
static string Sanitize(CTempString str, TSS_Flags flags=fSS_print)
Sanitize a string, allowing only specified classes of characters.
static bool IsIPAddress(const CTempStringEx str)
Check if the string contains a valid IP address.
static bool EqualNocase(const CTempString s1, SIZE_TYPE pos, SIZE_TYPE n, const char *s2)
Case-insensitive equality of a substring with another string.
void SetString(const CTempString s, NStr::EUrlEncode flag=NStr::eUrlEnc_SkipMarkChars)
Set new original string.
static enable_if< is_arithmetic< TNumeric >::value||is_convertible< TNumeric, Int8 >::value, string >::type NumericToString(TNumeric value, TNumToStringFlags flags=0, int base=10)
Convert numeric value to string.
@ fSS_NoMerge
Do not merge adjacent spaces (rejected chars)
@ fSS_alnum
Check on isalnum()
@ fConvErr_NoThrow
Do not throw an exception on error.
@ fSplit_MergeDelimiters
Merge adjacent delimiters.
@ eUrlEnc_Cookie
Same as SkipMarkChars with encoded ','.
@ eNocase
Case insensitive compare.
double Restart(void)
Return time elapsed since first Start() or last Restart() call (in seconds).
void Reset(void)
Stop (if running) and reset the timer.
Definition of all error codes used in corelib (xncbi.lib).
const GenericPointer< typename T::ValueType > T2 value
Classes to match a string against a set of masks.
String constants used in NCBI C/C++ toolkit.
static int match(PCRE2_SPTR start_eptr, PCRE2_SPTR start_ecode, uint16_t top_bracket, PCRE2_SIZE frame_size, pcre2_match_data *match_data, match_block *mb)
NCBI_PARAM_DECL(unsigned int, Log, Issued_SubHit_Limit)
static const char * kAllowedIdMarkchars
static const char * kPassThrough_Sid
NCBI_PARAM_ENUM_DEF_EX(EOnBadHitID, Log, On_Bad_Hit_Id, eOnBadPHID_AllowAndReport, eParam_NoThread, LOG_ON_BAD_HIT_ID)
static const char * kPassThrough_ClientIp
static const char * kBadIP
NCBI_PARAM_ENUM_ARRAY(EOnBadHitID, Log, On_Bad_Hit_Id)
NCBI_PARAM_ENUM_DECL(EOnBadHitID, Log, On_Bad_Hit_Id)
static bool IsValidHitID(const string &hit)
typedef NCBI_PARAM_TYPE(Log, On_Bad_Hit_Id) TOnBadHitId
DEFINE_STATIC_MUTEX(s_ContextFieldsMutex)
@ eOnBadPHID_AllowAndReport
@ eOnBadPHID_IgnoreAndReport
static const char * kPassThrough_Phid
NCBI_PARAM_DEF_EX(unsigned int, Log, Issued_SubHit_Limit, 200, eParam_NoThread, LOG_ISSUED_SUBHIT_LIMIT)
static const char * kPassThrough_Dtab
Defines CRequestContext class for NCBI C++ diagnostic API.
static CNamedPipeClient * client
static CS_CONTEXT * context