35 #ifndef HAVE_LOCAL_NCBI_BUILD_VER_H
36 # define HAVE_LOCAL_NCBI_BUILD_VER_H 1
40 #undef CNcbiApplication
41 #undef CComponentVersionInfo
53 #if defined(NCBI_OS_MSWIN)
60 #if defined(NCBI_OS_UNIX)
65 #define NCBI_USE_ERRCODE_X Corelib_App
113 return s_InstanceMutex;
140 : m_ConfigLoaded(
false),
170 "Second instance of CNcbiApplication is prohibited");
184 #if NCBI_SC_VERSION_PROXY != 0
236 #if defined(NCBI_THREADS)
249 #if defined(NCBI_COMPILER_WORKSHOP)
294 ERR_POST_X(1,
Info <<
"DryRun: default implementation does nothing");
309 "Command-line argument description is not found");
326 #if defined(NCBI_OS_DARWIN)
329 const char*
const** argvPtr,
330 const string& exepath)
338 static const char* s_ArgMacPsn =
"-psn_";
341 NStr::strncmp((*argvPtr)[1], s_ArgMacPsn, strlen(s_ArgMacPsn)) == 0) {
357 ERR_POST_X(2,
Info <<
"Mac arguments file not found: " << args_fname);
365 v.push_back((*argvPtr)[0]);
367 v.push_back(exepath);
381 Critical <<
"Overly high argument count " << v.size()
385 *argcPtr =
static_cast<int>(v.size());
387 char** argv =
new char*[v.size()];
389 ITERATE(vector<string>, vp, v) {
390 argv[c++] =
strdup(vp->c_str());
404 return TParamCatchExceptions::GetDefault();
448 #if (defined(NCBI_COMPILER_ICC) && NCBI_COMPILER_VERSION < 900)
464 arg_desc->SetUsageContext
466 "This program has no mandatory arguments");
472 #define NCBI_LOG_PARAM(type,Name,NAME) \
473 NCBI_PARAM_DECL (type, Log, LogApp ## Name); \
474 NCBI_PARAM_DEF_EX(type, Log, LogApp ## Name, false, eParam_NoThread, DIAG_LOG_APP_ ## NAME); \
475 typedef NCBI_PARAM_TYPE(Log, LogApp ## Name) TLogApp ## Name;
509 if ( TLogAppRunContext::GetDefault() ) {
535 const Uint8 limit = 1000;
539 value = value_in_bytes / 1024;
542 if (
value / 1024 > limit) {
548 #define RES_SIZE_USAGE(name, value_in_bytes) \
552 s_RoundResUsageSize(value_in_bytes, suffix, value); \
553 extra.Print(name + suffix, value); \
556 #define RES_TIME_USAGE(name, value) \
558 extra.Print(name, (Uint8)value)
570 extra.
Print(
"LogAppEnvironment",
"true");
571 list<string> env_keys;
573 env.Enumerate(env_keys);
574 ITERATE(list<string>, it, env_keys) {
575 const string&
val =
env.Get(*it);
584 extra.
Print(
"LogAppRegistry",
"true");
585 list<string> reg_sections;
588 ITERATE(list<string>, it, reg_sections) {
589 string section, name;
590 list<string> section_entries;
592 ITERATE(list<string>, it_entry, section_entries) {
593 const string&
val = reg.
Get(*it, *it_entry);
594 string path =
"[" + *it +
"]" + *it_entry;
603 extra.
Print(
"LogAppArguments",
"true");
611 extra.
Print(
"LogAppPath",
"true");
618 extra.
Print(
"LogAppResUsage",
"true");
631 double real, user, sys;
671 "Application's initialization failed", e);
672 *got_exception =
true;
675 catch (
const exception& e) {
676 ERR_POST_X(6,
"Application's initialization failed: " << e.
what());
677 *got_exception =
true;
702 if (*exit_code == 1) {
714 if (cur_ctx != e_ctx) {
717 "CException thrown", e);
726 "Application's execution failed", e);
727 *got_exception =
true;
730 catch (
const exception& e) {
732 *got_exception =
true;
742 if (*exit_code != 0 || *got_exception) {
760 *got_exception =
true;
762 catch (
const exception& e) {
764 *got_exception =
true;
772 #if defined(NCBI_OS_MSWIN) && defined(_UNICODE)
774 void s_Create_ArgsOrEnvW(
775 vector<string>& storage,
777 const TXChar*
const* begin)
779 const TXChar*
const* arg = begin;
784 const char** args =
new const char*[
count+1];
796 for (
i=0;
i < storage.size(); ++
i) {
797 args[
i] = storage[
i].c_str();
804 const TXChar*
const* argv,
805 const TXChar*
const* envp,
810 vector< string> argv_storage;
813 s_Create_ArgsOrEnvW(argv_storage, argv_pointers, argv);
816 vector< string> envp_storage;
819 s_Create_ArgsOrEnvW(envp_storage, envp_pointers, envp);
833 const char*
const* argv,
834 const char*
const* envp,
847 for (
int i = 1;
i < argc;
i++) {
874 "Application diagnostic stream's setup failed");
875 }
catch (
const exception& e) {
877 "Application diagnostic stream's setup failed: " +
886 string appname = name;
887 if (appname.empty()) {
888 if (!exepath.empty()) {
890 }
else if (argc > 0 && argv && argv[0] !=
NULL && *argv[0] !=
'\0') {
902 if ( exepath.empty() ) {
904 <<
"Warning: Could not determine this application's "
905 "file name and location. Using \""
906 << appname <<
"\" instead.\n"
907 "Please fix FindProgramExecutablePath() on this platform.");
911 #if defined(NCBI_OS_DARWIN)
915 s_MacArgMunging(*
this, &argc, &argv, exepath);
928 const char* conf_arg =
nullptr;
930 const char** v =
new const char*[argc];
932 int real_arg_index = 1;
934 for (
int i = 1;
i < argc;
i++) {
942 v[real_arg_index++] = argv[
i];
952 v[real_arg_index++] = argv[
i - 1];
953 v[real_arg_index++] = argv[
i];
959 v[real_arg_index++] = argv[
i - 1];
960 v[real_arg_index++] = argv[
i];
965 v[real_arg_index++] = argv[
i];
1005 v[real_arg_index++] = argv[
i];
1008 if (real_arg_index == argc ) {
1011 argc = real_arg_index;
1015 if (
CFile(conf_arg).Exists()) {
1019 ERR_POST_X(23,
Critical <<
"Registry file \"" << conf_arg <<
"\" not found, aborting.");
1036 if ( !post_level.empty() ) {
1051 bool got_exception =
false;
1057 x_TryMain(diag, conf, &exit_code, &got_exception);
1064 #if defined(NCBI_COMPILER_MSVC) && defined(_DEBUG)
1072 "Application has thrown an exception of unknown type");
1078 #ifdef NCBI_OS_MSWIN
1079 if ( !IsDebuggerPresent() ) {
1083 x_TryMain(diag, conf, &exit_code, &got_exception);
1098 if (!errh || errh->
GetStream() != &cerr) {
1099 cerr <<
"Error in command-line arguments. "
1100 "See error logs for more details." << endl;
1104 cerr <<
"Error in command-line arguments." << endl;
1105 cerr << e.
what() << endl;
1107 cerr <<
string(72,
'=') << endl << endl;
1111 got_exception =
true;
1121 _TRACE(
"Overriding exit code from " << exit_code
1171 ERR_POST_X(19,
"SetVersion() should be used from constructor of " \
1172 "CNcbiApplication derived class, see description");
1181 ERR_POST_X(19,
"SetVersion() should be used from constructor of " \
1182 "CNcbiApplication derived class, see description");
1190 ERR_POST_X(19,
"SetFullVersion() should be used from constructor of "\
1191 "CNcbiApplication derived class, see description");
1254 }
else if (conf->empty()) {
1272 "Registry file of application \"" <<
basename
1273 <<
"\" is not found");
1276 "Registry file \"" + *conf +
"\" cannot be opened");
1313 const char*
const* )
1343 IOS_BASE::sync_with_stdio(
false);
1351 #if defined(NCBI_COMPILER_GCC) && defined(NCBI_OS_SOLARIS)
1354 const size_t kCinBufSize = 5120;
1359 #ifdef NCBI_OS_MSWIN
1374 desc->AddStdArguments(
mask);
1381 if (app_name.empty())
return;
1395 switch (name_type) {
1428 const char*
const* argv,
1436 static bool s_Init =
false;
1441 *real_path = *s_RealPath;
1452 if (argc > 0 && argv[0] !=
NULL && argv[0][0] !=
'\0') {
1454 }
else if (instance) {
1458 #if defined(NCBI_OS_MSWIN) || defined(NCBI_OS_UNIX)
1460 # ifdef NCBI_OS_MSWIN
1468 BOOL (STDMETHODCALLTYPE
FAR * dllEnumProcessModules)
1475 dllEnumProcessModules = dll_psapi.
GetEntryPoint_Func(
"EnumProcessModules", &dllEnumProcessModules);
1476 if ( !dllEnumProcessModules ) {
1481 HANDLE process = GetCurrentProcess();
1486 if ( dllEnumProcessModules(process, &module,
sizeof(HMODULE), &needed) ) {
1487 if ( needed && module ) {
1489 DWORD ncount = GetModuleFileName(module,
buf, MAX_PATH);
1495 *real_path = *s_RealPath;
1508 # ifdef NCBI_OS_LINUX
1510 if (ret_val.empty() && !real_path) {
1511 real_path = &ret_val;
1518 real_path->assign(
buf, ncount);
1519 if (real_path == &ret_val || ret_val.empty()) {
1522 *s_RealPath = *real_path;
1530 if (ret_val.empty()) {
1539 #if !defined(NCBI_OS_MSWIN) && !defined(NCBI_OS_LINUX)
1549 string app_path = ret_val;
1552 # ifdef NCBI_OS_MSWIN
1555 string dir, title, ext;
1557 if ( ext.empty() ) {
1561 if (
CFile(app_path).Exists() ) {
1564 if ( !
CFile(app_path).Exists() ) {
1576 list<string> split_path;
1577 # ifdef NCBI_OS_MSWIN
1585 ITERATE(list<string>, it, split_path) {
1587 if (
CFile(app_path).Exists() ) {
1595 (app_path.empty() && argv !=
NULL && argv[0] !=
NULL) ? argv[0] : app_path);
1599 # error "Unsupported platform, sorry -- please contact NCBI"
1607 *real_path = *s_RealPath;
1647 if ( !post_level.empty() ) {
1656 if ( !msg_file.empty() ) {
1658 if ( !
info || !
info->Read(msg_file) ) {
1664 <<
"\" is not found");
1678 if ( !reg->
Get(
"NCBI",
"HeapSizeLimit").empty() ) {
1680 <<
"Config param [NCBI.HeapSizeLimit] is deprecated,"
1681 <<
"please use [NCBI.MemorySizeLimit] instead.");
1682 int mem_size_limit = reg->
GetInt(
"NCBI",
"HeapSizeLimit", 0);
1683 if (mem_size_limit < 0) {
1685 "Configuration file error: [NCBI.HeapSizeLimit] < 0");
1690 if ( !reg->
Get(
"NCBI",
"MemorySizeLimit").empty() ) {
1691 size_t mem_size_limit = 0;
1693 size_t pos = s.find(
"%");
1697 if (percents > 100) {
1699 "Configuration file error: [NCBI.HeapSizeLimit] > 100%");
1713 "Configuration file error: [NCBI.MemorySizeLimit] is too big");
1715 mem_size_limit = (size_t)bytes;
1722 if ( !reg->
Get(
"NCBI",
"CpuTimeLimit").empty() ) {
1723 int cpu_time_limit = reg->
GetInt(
"NCBI",
"CpuTimeLimit", 0);
1724 if (cpu_time_limit < 0) {
1726 "Configuration file error: [NCBI.CpuTimeLimit] < 0");
1735 string trace_filter = reg->
Get(
"DIAG",
"TRACE_FILTER");
1736 if ( !trace_filter.empty() )
1739 "Failed to load and set diag. filter for traces");
1743 string post_filter = reg->
Get(
"DIAG",
"POST_FILTER");
1744 if ( !post_filter.empty() )
1747 "Failed to load and set diag. filter for regular errors");
1755 if ( cmd_line.empty() ) {
1756 cmd_line = (*m_Arguments)[0];
1774 if ( !
ctx.IsSetExitCode() ) {
1775 ctx.SetExitCode(exit_code);
1792 case eSecond:
return "eSecond";
AutoPtr< INcbiIdler > m_Idler
INcbiIdler * GetIdler(EOwnership own)
void SetIdler(INcbiIdler *idler, EOwnership own)
static CNcbiApplication * Instance(void)
Singleton method.
CNcbiApplication(const SBuildInfo &build_info=NCBI_SBUILDINFO_DEFAULT())
Constructor.
virtual ~CNcbiApplication(void)
Destructor.
static void Destroy(CSafeStaticLifeSpan::ELifeLevel level)
Explicitly destroy all on-demand variables up to a specified level.
static void DisableChildThreadsCheck()
Disable checking on child thread(s) running during destruction.
@ eLifeLevel_AppMain
Destroyed in CNcbiApplication::AppMain, if possible.
static void s_HonorSignalHandlingConfiguration(void)
static Uint8 GetTotalPhysicalMemorySize(void)
Return the amount of actual/total physical memory, in bytes.
CTempString implements a light-weight string on top of a storage buffer whose lifetime management is ...
Interface for application idler.
Interface class for Phone Home Policy.
void Print(const CCompactSAMApplication::AlignInfo &ai)
string Path(const string &dir, const string &file)
static void fatal(const char *msg,...)
static const char * str(char *buf, int n)
void x_LogOptions(int event)
Log environment, registry, command arguments, path.
unique_ptr< CNcbiArguments > m_Arguments
Command-line arguments.
virtual EPreparseArgs PreparseArgs(int argc, const char *const *argv)
Check the command line arguments before parsing them.
CNcbiApplicationAPI * m_App
void SetFullVersion(CRef< CVersionAPI > version)
Set version data for the program.
int TStdioSetupFlags
Binary OR of "EStdioSetup".
void reset(element_type *p=0, EOwnership ownership=eTakeOwnership)
Reset will delete the old pointer (if owned), set content to the new value, and assume the ownership ...
void ExecuteActions(void)
SIZE_TYPE FlushDiag(CNcbiOstream *os, bool close_diag=false)
Flush the in-memory diagnostic stream (for "eDS_ToMemory" case only).
string m_ConfigPath
Path to .ini file used.
CNcbiActionGuard m_OnExitActions
Actions executed on app destruction.
bool SetupDiag(EAppDiagStream diag)
Setup the application diagnostic stream.
TDisableArgDesc m_DisableArgDesc
Arg desc. disabled.
void HideStdArgs(THideStdArgs hide_mask)
Set the hide mask for the Hide Std Flags.
TStdioSetupFlags m_StdioFlags
Std C++ I/O adjustments.
static string GetAppName(EAppNameType name_type=eBaseName, int argc=0, const char *const *argv=NULL)
friend class CNcbiApplicationGuard
void x_TryMain(EAppDiagStream diag, const char *conf, int *exit_code, bool *got_exception)
void x_TryInit(EAppDiagStream diag, const char *conf)
string m_ProgramDisplayName
Display name of app.
void x_SetupStdio(void)
Setup C++ standard I/O streams' behaviour.
virtual const char * GetErrCodeString(void) const override
Translate from the error code value to its string representation.
void ExecuteOnExitActions()
Should only be called from the destructors of classes derived from CNcbiApplicationAPI - if it is nec...
virtual int Run(void)=0
Run the application.
int m_LogOptions
logging of env, reg, args, path
IPhoneHomePolicy * m_PhoneHomePolicy
Pointer to active Phone Home Policy, if any.
string m_ExePath
Program executable path.
const CNcbiEnvironment & GetEnvironment(void) const
Get the application's cached environment.
CNcbiEnvironment & SetEnvironment(void)
Get a non-const copy of the application's cached environment.
const string & GetProgramExecutablePath(EFollowLinks follow_links=eIgnoreLinks) const
Get the application's executable path.
static CNcbiApplicationGuard InstanceGuard(void)
Singleton method.
virtual void Init(void)
Initialize the application.
EExitMode
When to return a user-set exit code.
virtual void AppStop(int exit_code)
Method to be called before application exit.
const CNcbiRegistry & GetConfig(void) const
Get the application's cached configuration parameters (read-only).
~CNcbiApplicationGuard(void)
virtual const CArgs & GetArgs(void) const
Get parsed command line arguments.
int AppMain(int argc, const char *const *argv, const char *const *envp=0, EAppDiagStream diag=eDS_Default, const char *conf=NcbiEmptyCStr, const string &name=NcbiEmptyString)
Main function (entry point) for the NCBI application.
CVersionInfo GetVersion(void) const
Get the program version information.
virtual bool SetupDiag_AppSpecific(void)
Setup application specific diagnostic stream.
virtual void SetupArgDescriptions(CArgDescriptions *arg_desc)
Setup the command line argument descriptions.
int m_ExitCode
Exit code to force.
char * m_CinBuffer
Cin buffer if changed.
EPreparseArgs
Result of PreparseArgs()
static CNcbiApplicationAPI * Instance(void)
Singleton method.
virtual bool LoadConfig(CNcbiRegistry ®, const string *conf, CNcbiRegistry::TFlags reg_flags)
Load settings from the configuration file to the registry.
INcbiIdler * GetIdler(EOwnership ownership)
Return currently installed idler or NULL.
#define ITERATE(Type, Var, Cont)
ITERATE macro to sequence through container elements.
const char * m_LogFile
Logfile if set in the command line.
void SetStdioFlags(TStdioSetupFlags stdio_flags)
Adjust the behavior of standard I/O streams.
shared_ptr< CReadLockGuard > m_AppLock
unique_ptr< CNcbiEnvironment > m_Environ
Cached application env.
element_type * get(void) const
Get pointer.
void SetVersionByBuild(int major)
unique_ptr< CArgs > m_Args
Parsed cmd.-line args.
int THideStdArgs
Binary OR of "EHideStdArgs".
virtual void Exit(void)
Cleanup on application exit.
void x_AddDefaultArgs(void)
CNcbiApplicationGuard(CNcbiApplicationAPI *app)
static string FindProgramExecutablePath(int argc, const char *const *argv, string *real_path=0)
Find the application's executable file.
virtual void Apply(CNcbiApplicationAPI *app)=0
Apply policy for an application.
const string & GetProgramDisplayName(void) const
Get the application's "display" name.
EExitMode m_ExitCodeCond
When to force it (if ever)
void DisableArgDescriptions(TDisableArgDesc disable=fDisableStdArgs)
virtual void AppStart(void)
Method to be called before application start.
static CRWLock & GetInstanceLock(void)
unique_ptr< CArgDescriptions > m_ArgDesc
Cmd.-line arg descriptions.
virtual void Idle(void)=0
int TDisableArgDesc
Binary OR of "EDisableArgDesc".
CRef< CNcbiRegistry > m_Config
Guaranteed to be non-NULL.
static SSystemMutex & GetInstanceMutex(void)
Mutex for application singleton object.
static CNcbiApplicationAPI * m_Instance
Current app. instance.
virtual int DryRun(void)
Test run the application.
void SetProgramDisplayName(const string &app_name)
Set program's display name.
const CVersionAPI & GetFullVersion(void) const
Get the program version information.
ENcbiOwnership m_PhoneHomePolicy_Ownership
Phone Home Policy ownersheep.
void SetIdler(INcbiIdler *idler, EOwnership ownership)
Set new idler and ownership.
string m_RealExePath
Symlink-free executable path.
virtual ~CNcbiApplicationAPI(void)
Destructor.
virtual void Finish()
Deinitialize policy/reporting API.
element_type * get(void) const
Get pointer.
const CNcbiArguments & GetArguments(void) const
Get the application's cached unprocessed command-line arguments.
void RunIdler(void)
Execute currently installed idler if any.
void SetPhoneHomePolicy(IPhoneHomePolicy *policy, ENcbiOwnership ownership=eNoOwnership)
Set Phone Home Policy.
bool m_ConfigLoaded
Finished loading config.
THideStdArgs m_HideArgs
Std cmd.-line flags to hide.
element_type * release(void)
Release will release ownership of pointer to caller.
void SetExitCode(int exit_code, EExitMode when=eExceptionalExits)
Force the program to return a specific exit code later, either when it exits due to an exception or u...
void SetVersion(const CVersionInfo &version)
Set the version number for the program.
string m_DefaultConfig
conf parameter to AppMain
CNcbiApplicationAPI(const SBuildInfo &build_info)
Constructor.
void x_HonorStandardSettings(IRegistry *reg=0)
Read standard NCBI application configuration settings.
CRef< CVersionAPI > m_Version
Program version.
void x_ReadLogOptions()
Read switches that are stored in m_LogOptions from registry and environment.
@ fHideFullHelp
Hide full help description.
@ fHideFullVersion
Hide full version description.
@ fHideAll
Hide all standard argument descriptions.
@ fHideHelp
Hide help description.
@ fHideVersion
Hide version description.
@ eAllExits
always (ignoring Run's return value)
@ eNoExits
never (stick to existing logic)
@ eExceptionalExits
when an (uncaught) exception occurs
@ fBinaryCout
treat standard output as binary
@ fNoSyncWithStdio
Turn off synchronizing of "C++" cin/cout/cerr streams with their "C" counterparts,...
@ fDefault_CinBufferSize
Use compiler-specific default of Cin buffer size.
@ fBinaryCin
treat standard input as binary
@ ePreparse_Exit
Exit the application with zero exit code.
@ ePreparse_Continue
Continue application execution.
@ eNoRegistry
Registry file cannot be opened.
@ eUnsetArgs
Command-line argument description not found.
@ eSecond
Second instance of CNcbiApplicationAPI is prohibited.
@ eLoadConfig
Registry data failed to load from config file.
@ eSetupDiag
Application diagnostic stream setup failed.
@ eIgnoreLinks
Do not follow symbolic links.
@ eFollowLinks
Follow symbolic links.
@ eFullName
per GetProgramExecutablePath(eIgnoreLinks)
@ eRealName
per GetProgramExecutablePath(eFollowLinks)
@ eBaseName
per GetProgramDisplayName
@ eTakeOwnership
An object can take ownership of another.
@ eNoOwnership
No ownership is assumed.
CArgs * CreateArgs(TSize argc, TArray argv) const
Create parsed arguments in CArgs object.
@ eHelpShowAll
Error code for detailed help message which includes hidden arguments.
@ eHelpErr
Show short help message and return error.
@ eHelpXml
Error code for XML formatted help message.
@ eHelpFull
Error code for detailed help message.
@ fNoUsage
Do not print USAGE on argument error.
@ fDupErrToCerr
Print arg error to both log and cerr.
@ eNoValue
Expecting an argument value.
void SetDiagFilter(EDiagFilter what, const char *filter_str)
Set diagnostic filter.
CDiagContext_Extra & Print(const string &name, const string &value)
The method does not print the argument, but adds it to the string.
static bool IsSetOldPostFormat(void)
Check old/new format flag (for compatibility only)
void PrintStart(const string &message)
Print start/stop etc.
CDiagContext & GetDiagContext(void)
Get diag context instance.
static void SetRequestContext(CRequestContext *ctx)
Shortcut to CDiagContextThreadData::GetThreadData().SetRequestContext()
void SetDiagFixedPostLevel(EDiagSev post_sev)
Sets and locks the level, combining the previous two calls.
void DiagHandler_Reopen(void)
Ask diagnostic handler to reopen log files if necessary.
CDiagContext_Extra Extra(void) const
Create a temporary CDiagContext_Extra object.
bool IsSetExitCode(void) const
Check if exit code has been set.
TUID GetUID(void) const
Return (create if not created yet) unique diagnostic ID.
EAppDiagStream
Where to write the application's diagnostics to.
shared_ptr< ITracerSpan > GetTracerSpan(void) const
#define DIAG_POST_LEVEL
Diagnostic post severity level.
void FlushMessages(CDiagHandler &handler)
Flush the collected messages to the current diag handler.
static CRequestContext & GetRequestContext(void)
Shortcut to CDiagContextThreadData::GetThreadData().GetRequestContext()
void SetAppName(const string &app_name)
Set application name.
void DiscardMessages(void)
Discard the collected messages without printing them.
CDiagHandler * GetDiagHandler(bool take_ownership=false, bool *current_ownership=0)
Get the currently set diagnostic handler class.
NCBI_XNCBI_EXPORT void Abort(void)
Smart abort function.
void SetDiagErrCodeInfo(CDiagErrCodeInfo *info, bool can_delete=true)
Set handler for processing error codes.
void SetExitCode(int exit_code)
Set exit code.
#define ERR_POST_X(err_subcode, message)
Error posting with default error code and given error subcode.
virtual CNcbiOstream * GetStream(void)
static void x_FinalizeSetupDiag(void)
Internal function, should be used only by CNcbiApplication.
static void SetupDiag(EAppDiagStream ds=eDS_Default, CNcbiRegistry *config=NULL, EDiagCollectMessages collect=eDCM_NoChange, const char *cmd_logfile=NULL)
Application-wide diagnostics setup.
void InitMessages(size_t max_size=100)
Start collecting all messages (the collected messages can be flushed to a new destination later).
void SetDiagTrace(EDiagTrace how, EDiagTrace dflt=eDT_Default)
Set the diagnostic trace settings.
EDiagSev
Severity level for the posted diagnostics.
TDiagPostFlags SetDiagPostAllFlags(TDiagPostFlags flags)
Set global post flags to "flags".
#define DIAG_MESSAGE_FILE
Diagnostic message file.
#define DIAG_TRACE
Diagnostic trace setting.
static bool StrToSeverityLevel(const char *str_sev, EDiagSev &sev)
Get severity from string.
void SetDiagStream(CNcbiOstream *os, bool quick_flush=true, FDiagCleanup cleanup=0, void *cleanup_data=0, const string &stream_name="")
Set diagnostic stream.
void SetGlobalAppState(EDiagAppState state)
Set global application state.
void HonorRegistrySettings(const IRegistry *reg=0)
@ eDPF_Severity
Severity (default)
@ eDCM_NoChange
Continue collecting messages if already started.
@ eDCM_Flush
Flush the collected messages and stop collecting.
@ eDS_User
Leave as was previously set (or not set) by user.
@ eDS_ToStderr
To standard error stream.
@ eDT_Enable
Enable messages of severity "eDiag_Trace".
@ eDiagAppState_AppEnd
AE.
@ eDiagAppState_AppBegin
AB.
@ eDiagFilter_Post
for all non-TRACE, non-FATAL
@ eDiagFilter_Trace
for TRACEs only
TFunc GetEntryPoint_Func(const string &name, TFunc *func)
Get DLLs entry point (function).
void Set(const string &name, const string &value)
Set an environment variable by name.
const string & Get(const string &name, bool *found=NULL) const
Get environment value by name.
const string & GetProgramName(EFollowLinks follow_links=eIgnoreLinks) const
Get program name.
void Critical(CExceptionArgs_Base &args)
TErrCode GetErrCode(void) const
Get error code.
#define NCBI_THROW(exception_class, err_code, message)
Generic macro to throw an exception, given the exception class, error code and message string.
#define NCBI_RETHROW_SAME(prev_exception, message)
Generic macro to re-throw the same exception.
#define NCBI_CATCH_X(err_subcode, message)
Catch CExceptions as well with default error code and given error subcode placed in diagnostics.
CRequestContext & GetRequestContext(void) const
Get the request context in which the exception was thrown.
void Warning(CExceptionArgs_Base &args)
void Fatal(CExceptionArgs_Base &args)
#define ABORT_ON_THROW
ABORT_ON_THROW controls if program should be aborted.
TErrCode GetErrCode(void) const
virtual const char * GetErrCodeString(void) const
Get error code interpreted as text.
virtual const char * what(void) const noexcept
Standard report (includes full backlog).
#define NCBI_REPORT_EXCEPTION_X(err_subcode, title, ex)
Generate a report on the exception with default error code and given subcode.
#define NCBI_RETHROW(prev_exception, exception_class, err_code, message)
Generic macro to re-throw an exception.
void SetThrowTraceAbort(bool abort_on_throw_trace)
Specify whether to call "abort()" inside the DoThrowTraceAbort().
void Info(CExceptionArgs_Base &args)
static string NormalizePath(const string &path, EFollowLinks follow_links=eIgnoreLinks)
Normalize a path.
static bool IsAbsolutePath(const string &path)
Check if a "path" is absolute for the current OS.
string GetBase(void) const
Get the base entry name without extension.
static string MakePath(const string &dir=kEmptyStr, const string &base=kEmptyStr, const string &ext=kEmptyStr)
Assemble a path from basic components.
static char GetPathSeparator(void)
Get path separator symbol specific for the current platform.
static string GetCwd(void)
Get the current working directory.
string GetName(void) const
Get the base entry name with extension (if any).
static void SplitPath(const string &path, string *dir=0, string *base=0, string *ext=0)
Split a path string into its basic components.
static void SetAllocFillMode(EAllocFillMode mode)
TObjectType * GetPointer(void) THROWS_NONE
Get pointer,.
void Reset(void)
Reset reference object.
@ eParam_NoThread
Do not use per-thread values.
uint64_t Uint8
8-byte (64-bit) unsigned integer
ncbi_numeric_limits< T > get_limits(const T &)
Generic template to get STD limits by a variable.
size_t resident_peak
Peak resident set size ("high water mark")
size_t total_peak
Peak total memory usage.
size_t resident
Resident/working set size (RSS).
size_t total
Total memory usage.
size_t shared
Shared memory usage.
static bool GetMemoryUsage(SMemoryUsage &usage)
Get current process memory usage.
size_t data
Data segment size.
static bool GetTimes(double *real, double *user, double *sys, EWhat what=eProcess)
Get current process execution times.
size_t stack
Stack size of the initial thread in the process.
@ eChildren
All children of the calling process.
@ eProcess
Current process.
int TFlags
Binary OR of "EFlags".
virtual bool GetBool(const string §ion, const string &name, bool default_value, TFlags flags=0, EErrAction err_action=eThrow) const
Get boolean value of specified parameter name.
virtual void EnumerateSections(list< string > *sections, TFlags flags=fAllLayers) const
Enumerate section names.
virtual const string & Get(const string §ion, const string &name, TFlags flags=0) const
Get the parameter value.
virtual int GetInt(const string §ion, const string &name, int default_value, TFlags flags=0, EErrAction err_action=eThrow) const
Get integer value of specified parameter name.
bool Empty(TFlags flags=fAllLayers) const
Verify if Registry is empty.
bool IncludeNcbircIfAllowed(TFlags flags=fWithNcbirc)
Attempt to load a systemwide configuration file (.ncbirc on Unix, ncbi.ini on Windows) as a low-prior...
virtual void EnumerateEntries(const string §ion, list< string > *entries, TFlags flags=fAllLayers) const
Enumerate parameter names for a specified section.
IRWRegistry * Read(CNcbiIstream &is, TFlags flags=0, const string &path=kEmptyStr)
Read and parse the stream "is", and merge its content with current Registry entries.
virtual string GetString(const string §ion, const string &name, const string &default_value, TFlags flags=0) const
Get the parameter string value.
bool Write(CNcbiOstream &os, TFlags flags=0) const
Write the registry content to output stream.
void Clear(TFlags flags=fAllLayers)
Reset the registry content.
@ fWithNcbirc
Include .ncbirc (used only by CNcbiReg.)
@ eErrPost
Log the error message and return default value.
#define END_NCBI_SCOPE
End previously defined NCBI scope.
#define BEGIN_NCBI_SCOPE
Define ncbi namespace.
IO_PREFIX::ostream CNcbiOstream
Portable alias for ostream.
IO_PREFIX::ifstream CNcbiIfstream
Portable alias for ifstream.
NCBI_NS_STD::string::size_type SIZE_TYPE
static int StringToInt(const CTempString str, TStringToNumFlags flags=0, int base=10)
Convert string to int.
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 int strcmp(const char *s1, const char *s2)
String compare.
static Uint8 StringToUInt8_DataSize(const CTempString str, TStringToNumFlags flags=0)
Convert string that can contain "software" qualifiers to Uint8.
static size_t StringToSizet(const CTempString str, TStringToNumFlags flags=0, int base=10)
Convert string to size_t.
static string IntToString(int value, TNumToStringFlags flags=0, int base=10)
Convert int to string.
static bool StartsWith(const CTempString str, const CTempString start, ECase use_case=eCase)
Check if a string starts with a specified prefix value.
static unsigned int StringToUInt(const CTempString str, TStringToNumFlags flags=0, int base=10)
Convert string to unsigned int.
static int strncmp(const char *s1, const char *s2, size_t n)
String compare up to specified number of characters.
static string ShellEncode(const string &str)
Quotes a string in Bourne Again Shell (BASH) syntax, in a way that disallows non-printable characters...
@ fSplit_MergeDelimiters
Merge adjacent delimiters.
static bool WaitForAllThreads(void)
static void InitializeMainThreadId(void)
Initialize main thread's TID.
enum ENcbiOwnership EOwnership
Ownership relations between objects.
ENcbiOwnership
Ownership relations between objects.
string GetExtraValue(EExtra key, const string &default_value=kEmptyStr) const
void SetVersionInfo(int ver_major, int ver_minor, int patch_level=0, const string &ver_name=kEmptyStr)
Set version information.
const SBuildInfo & GetBuildInfo() const
Get build info (date and tag, if set)
const CVersionInfo & GetVersionInfo() const
Get version information.
static CVersionInfo GetPackageVersion(void)
#define NCBI_APP_SBUILDINFO_DEFAULT()
string Print(const string &appname, TPrintFlags flags=fPrintAll) const
Print version data, plain text.
bool IsAny() const
Check if version is all zero (major, minor, patch) Convention is that all-zero version used in reques...
string PrintXml(const string &appname, TPrintFlags flags=fPrintAll) const
Print version data, XML.
void AddComponentVersion(const string &component_name, int ver_major, int ver_minor, int patch_level, const string &ver_name, const SBuildInfo &build_info)
Add component version information.
string PrintJson(const string &appname, TPrintFlags flags=fPrintAll) const
Print version data, JSON.
@ fPackageShort
Print package info, if available.
@ fVersionInfo
Print version info.
@ eStableComponentsVersion
#define HANDLE
An abstraction for a file handle.
unsigned int
A callback function used to compare two keys in a database.
Definition of all error codes used in corelib (xncbi.lib).
constexpr bool empty(list< Ts... >) noexcept
const string version
version string
const GenericPointer< typename T::ValueType > T2 value
static string s_Path
Directory for all database files of the storage.
#define NCBI_SC_VERSION_PROXY
#define NCBI_TEAMCITY_PROJECT_NAME_PROXY
#define NCBI_TEAMCITY_BUILD_NUMBER_PROXY
#define NCBI_SUBVERSION_REVISION_PROXY
Defines MS Windows specifics for our "C++" code.
Static variables safety - create on demand, destroy on application termination.
bool SetCpuTimeLimit(unsigned int max_cpu_time, unsigned int terminate_delay_time, TLimitsPrintHandler handler=NULL, TLimitsPrintParameter parameter=NULL)
[UNIX only] Set CPU time usage limit.
@ fSuppress_Exception
Unhandled exceptions.
bool SetMemoryLimit(size_t max_size, TLimitsPrintHandler handler=NULL, TLimitsPrintParameter parameter=NULL)
[UNIX only] Set memory limit.
bool VerifyCpuCompatibility(string *message=nullptr)
Verify that the CPU, where an application run, is compatible with flags it compiled for.
void SuppressSystemMessageBox(TSuppressSystemMessageBox mode=fSuppress_Default)
Suppress popup messages on execution errors.
CSafeStatic< CIdlerWrapper > s_IdlerWrapper
#define NCBI_LOG_PARAM(type, Name, NAME)
const char * s_ArgFullVersionXml
const char * s_ArgFullVersionJson
NCBI_PARAM_DEF_EX(bool, Debug, Catch_Unhandled_Exceptions, true, eParam_NoThread, DEBUG_CATCH_UNHANDLED_EXCEPTIONS)
static CSafeStatic< CRWLock > s_InstanceRWLock(CSafeStaticLifeSpan(CSafeStaticLifeSpan::eLifeSpan_Long, 1))
@ eStartEvent
right before AppMain()
@ eOtherEvent
any case is fine
@ eStopEvent
right after AppMain()
const char * s_ArgFullVersion
typedef NCBI_PARAM_TYPE(Debug, Catch_Unhandled_Exceptions) TParamCatchExceptions
#define RES_SIZE_USAGE(name, value_in_bytes)
bool s_HandleExceptions(void)
const char * s_ArgLogFile
const char * s_ArgCfgFile
DEFINE_STATIC_MUTEX(s_InstanceMutex)
NCBI_PARAM_DECL(bool, Debug, Catch_Unhandled_Exceptions)
ELogOptions
Flags to switch what to log.
@ fLogAppRegistryStop
log app registry on app stop
@ fLogAppPath
log app executable path
@ fLogAppResUsageStop
log resource usage on app stop
@ fLogAppArguments
log app arguments
@ fLogAppEnvironment
log app environment on app start
@ fLogAppRegistry
log app registry on app start
@ fLogAppEnvironmentStop
log app environment on app stop
static bool s_IsApplicationStarted
#define RES_TIME_USAGE(name, value)
void s_RoundResUsageSize(Uint8 value_in_bytes, string &suffix, Uint8 &value)
const char * s_ArgVersion
const char * s_ArgDelimiter
Defines the CNcbiApplication and CAppException classes for creating NCBI applications.
Define class Dll and for Portable DLL handling.
Defines classes: CDirEntry, CFile, CDir, CSymLink, CMemoryFile, CFileUtil, CFileLock,...
std::istream & in(std::istream &in_, double &x_)
Defines CRequestContext class for NCBI C++ diagnostic API.
CCompressionStreamProcessor * s_Init(EInitType type, CCompressStream::EMethod method, ICompression::TFlags flags, ICompression::ELevel level)
CRef< IRWRegistry > registry
string actual_name
Either an absolute path or empty.
Process memory usage information, in bytes.
This class allows to add build info (date and tag) to application version.
Portable system-logging API.