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
216 #if defined(NCBI_THREADS)
229 #if defined(NCBI_COMPILER_WORKSHOP)
274 ERR_POST_X(1,
Info <<
"DryRun: default implementation does nothing");
289 "Command-line argument description is not found");
306 #if defined(NCBI_OS_DARWIN)
309 const char*
const** argvPtr,
310 const string& exepath)
318 static const char* s_ArgMacPsn =
"-psn_";
321 NStr::strncmp((*argvPtr)[1], s_ArgMacPsn, strlen(s_ArgMacPsn)) == 0) {
337 ERR_POST_X(2,
Info <<
"Mac arguments file not found: " << args_fname);
345 v.push_back((*argvPtr)[0]);
347 v.push_back(exepath);
361 Critical <<
"Overly high argument count " << v.size()
365 *argcPtr =
static_cast<int>(v.size());
367 char** argv =
new char*[v.size()];
369 ITERATE(vector<string>, vp, v) {
370 argv[c++] =
strdup(vp->c_str());
384 return TParamCatchExceptions::GetDefault();
428 #if (defined(NCBI_COMPILER_ICC) && NCBI_COMPILER_VERSION < 900)
444 arg_desc->SetUsageContext
446 "This program has no mandatory arguments");
452 #define NCBI_LOG_PARAM(type,Name,NAME) \
453 NCBI_PARAM_DECL (type, Log, LogApp ## Name); \
454 NCBI_PARAM_DEF_EX(type, Log, LogApp ## Name, false, eParam_NoThread, DIAG_LOG_APP_ ## NAME); \
455 typedef NCBI_PARAM_TYPE(Log, LogApp ## Name) TLogApp ## Name;
489 if ( TLogAppRunContext::GetDefault() ) {
515 const Uint8 limit = 1000;
519 value = value_in_bytes / 1024;
522 if (
value / 1024 > limit) {
528 #define RES_SIZE_USAGE(name, value_in_bytes) \
532 s_RoundResUsageSize(value_in_bytes, suffix, value); \
533 extra.Print(name + suffix, value); \
536 #define RES_TIME_USAGE(name, value) \
538 extra.Print(name, (Uint8)value)
550 extra.
Print(
"LogAppEnvironment",
"true");
551 list<string> env_keys;
553 env.Enumerate(env_keys);
554 ITERATE(list<string>, it, env_keys) {
555 const string&
val =
env.Get(*it);
564 extra.
Print(
"LogAppRegistry",
"true");
565 list<string> reg_sections;
568 ITERATE(list<string>, it, reg_sections) {
569 string section, name;
570 list<string> section_entries;
572 ITERATE(list<string>, it_entry, section_entries) {
573 const string&
val = reg.
Get(*it, *it_entry);
574 string path =
"[" + *it +
"]" + *it_entry;
583 extra.
Print(
"LogAppArguments",
"true");
591 extra.
Print(
"LogAppPath",
"true");
598 extra.
Print(
"LogAppResUsage",
"true");
611 double real, user, sys;
651 "Application's initialization failed", e);
652 *got_exception =
true;
655 catch (
const exception& e) {
656 ERR_POST_X(6,
"Application's initialization failed: " << e.
what());
657 *got_exception =
true;
682 if (*exit_code == 1) {
696 "CException thrown", e);
700 "Application's execution failed", e);
701 *got_exception =
true;
704 catch (
const exception& e) {
706 *got_exception =
true;
727 *got_exception =
true;
729 catch (
const exception& e) {
731 *got_exception =
true;
739 #if defined(NCBI_OS_MSWIN) && defined(_UNICODE)
741 void s_Create_ArgsOrEnvW(
742 vector<string>& storage,
744 const TXChar*
const* begin)
746 const TXChar*
const* arg = begin;
751 const char** args =
new const char*[count+1];
759 for (
i=0;
i<count; ++
i) {
763 for (
i=0;
i < storage.size(); ++
i) {
764 args[
i] = storage[
i].c_str();
771 const TXChar*
const* argv,
772 const TXChar*
const* envp,
777 vector< string> argv_storage;
780 s_Create_ArgsOrEnvW(argv_storage, argv_pointers, argv);
783 vector< string> envp_storage;
786 s_Create_ArgsOrEnvW(envp_storage, envp_pointers, envp);
800 const char*
const* argv,
801 const char*
const* envp,
814 for (
int i = 1;
i < argc;
i++) {
841 "Application diagnostic stream's setup failed");
842 }
catch (
const exception& e) {
844 "Application diagnostic stream's setup failed: " +
853 string appname = name;
854 if (appname.empty()) {
855 if (!exepath.empty()) {
857 }
else if (argc > 0 && argv[0] !=
NULL && *argv[0] !=
'\0') {
869 if ( exepath.empty() ) {
871 <<
"Warning: Could not determine this application's "
872 "file name and location. Using \""
873 << appname <<
"\" instead.\n"
874 "Please fix FindProgramExecutablePath() on this platform.");
878 #if defined(NCBI_OS_DARWIN)
882 s_MacArgMunging(*
this, &argc, &argv, exepath);
895 const char* conf_arg =
nullptr;
897 const char** v =
new const char*[argc];
899 int real_arg_index = 1;
901 for (
int i = 1;
i < argc;
i++) {
909 v[real_arg_index++] = argv[
i];
919 v[real_arg_index++] = argv[
i - 1];
920 v[real_arg_index++] = argv[
i];
926 v[real_arg_index++] = argv[
i - 1];
927 v[real_arg_index++] = argv[
i];
932 v[real_arg_index++] = argv[
i];
972 v[real_arg_index++] = argv[
i];
975 if (real_arg_index == argc ) {
978 argc = real_arg_index;
982 if (
CFile(conf_arg).Exists()) {
986 ERR_POST_X(23,
Critical <<
"Registry file \"" << conf_arg <<
"\" not found, aborting.");
1003 if ( !post_level.empty() ) {
1018 bool got_exception =
false;
1024 x_TryMain(diag, conf, &exit_code, &got_exception);
1031 #if defined(NCBI_COMPILER_MSVC) && defined(_DEBUG)
1039 "Application has thrown an exception of unknown type");
1045 #ifdef NCBI_OS_MSWIN
1046 if ( !IsDebuggerPresent() ) {
1050 x_TryMain(diag, conf, &exit_code, &got_exception);
1065 if (!errh || errh->
GetStream() != &cerr) {
1066 cerr <<
"Error in command-line arguments. "
1067 "See error logs for more details." << endl;
1071 cerr <<
"Error in command-line arguments." << endl;
1072 cerr << e.
what() << endl;
1074 cerr <<
string(72,
'=') << endl << endl;
1078 got_exception =
true;
1088 _TRACE(
"Overriding exit code from " << exit_code
1138 ERR_POST_X(19,
"SetVersion() should be used from constructor of " \
1139 "CNcbiApplication derived class, see description");
1148 ERR_POST_X(19,
"SetVersion() should be used from constructor of " \
1149 "CNcbiApplication derived class, see description");
1157 ERR_POST_X(19,
"SetFullVersion() should be used from constructor of "\
1158 "CNcbiApplication derived class, see description");
1221 }
else if (conf->empty()) {
1239 "Registry file of application \"" <<
basename
1240 <<
"\" is not found");
1243 "Registry file \"" + *conf +
"\" cannot be opened");
1280 const char*
const* )
1310 IOS_BASE::sync_with_stdio(
false);
1318 #if defined(NCBI_COMPILER_GCC) && defined(NCBI_OS_SOLARIS)
1321 const size_t kCinBufSize = 5120;
1326 #ifdef NCBI_OS_MSWIN
1341 desc->AddStdArguments(
mask);
1348 if (app_name.empty())
return;
1362 switch (name_type) {
1395 const char*
const* argv,
1403 static bool s_Init =
false;
1408 *real_path = *s_RealPath;
1419 if (argc > 0 && argv[0] !=
NULL && argv[0][0] !=
'\0') {
1421 }
else if (instance) {
1425 #if defined(NCBI_OS_MSWIN) || defined(NCBI_OS_UNIX)
1427 # ifdef NCBI_OS_MSWIN
1435 BOOL (STDMETHODCALLTYPE
FAR * dllEnumProcessModules)
1442 dllEnumProcessModules = dll_psapi.
GetEntryPoint_Func(
"EnumProcessModules", &dllEnumProcessModules);
1443 if ( !dllEnumProcessModules ) {
1448 HANDLE process = GetCurrentProcess();
1453 if ( dllEnumProcessModules(process, &module,
sizeof(HMODULE), &needed) ) {
1454 if ( needed && module ) {
1456 DWORD ncount = GetModuleFileName(module,
buf, MAX_PATH);
1462 *real_path = *s_RealPath;
1475 # ifdef NCBI_OS_LINUX
1477 if (ret_val.empty() && !real_path) {
1478 real_path = &ret_val;
1485 real_path->assign(
buf, ncount);
1486 if (real_path == &ret_val || ret_val.empty()) {
1489 *s_RealPath = *real_path;
1497 if (ret_val.empty()) {
1506 #if !defined(NCBI_OS_MSWIN) && !defined(NCBI_OS_LINUX)
1516 string app_path = ret_val;
1519 # ifdef NCBI_OS_MSWIN
1522 string dir, title, ext;
1524 if ( ext.empty() ) {
1528 if (
CFile(app_path).Exists() ) {
1531 if ( !
CFile(app_path).Exists() ) {
1543 list<string> split_path;
1544 # ifdef NCBI_OS_MSWIN
1552 ITERATE(list<string>, it, split_path) {
1554 if (
CFile(app_path).Exists() ) {
1562 (app_path.empty() && argv !=
NULL && argv[0] !=
NULL) ? argv[0] : app_path);
1566 # error "Unsupported platform, sorry -- please contact NCBI"
1574 *real_path = *s_RealPath;
1614 if ( !post_level.empty() ) {
1623 if ( !msg_file.empty() ) {
1625 if ( !
info || !
info->Read(msg_file) ) {
1631 <<
"\" is not found");
1645 if ( !reg->
Get(
"NCBI",
"HeapSizeLimit").empty() ) {
1647 <<
"Config param [NCBI.HeapSizeLimit] is deprecated,"
1648 <<
"please use [NCBI.MemorySizeLimit] instead.");
1649 int mem_size_limit = reg->
GetInt(
"NCBI",
"HeapSizeLimit", 0);
1650 if (mem_size_limit < 0) {
1652 "Configuration file error: [NCBI.HeapSizeLimit] < 0");
1657 if ( !reg->
Get(
"NCBI",
"MemorySizeLimit").empty() ) {
1658 size_t mem_size_limit = 0;
1660 size_t pos = s.find(
"%");
1664 if (percents > 100) {
1666 "Configuration file error: [NCBI.HeapSizeLimit] > 100%");
1680 "Configuration file error: [NCBI.MemorySizeLimit] is too big");
1682 mem_size_limit = (size_t)bytes;
1689 if ( !reg->
Get(
"NCBI",
"CpuTimeLimit").empty() ) {
1690 int cpu_time_limit = reg->
GetInt(
"NCBI",
"CpuTimeLimit", 0);
1691 if (cpu_time_limit < 0) {
1693 "Configuration file error: [NCBI.CpuTimeLimit] < 0");
1702 string trace_filter = reg->
Get(
"DIAG",
"TRACE_FILTER");
1703 if ( !trace_filter.empty() )
1706 "Failed to load and set diag. filter for traces");
1710 string post_filter = reg->
Get(
"DIAG",
"POST_FILTER");
1711 if ( !post_filter.empty() )
1714 "Failed to load and set diag. filter for regular errors");
1722 if ( cmd_line.empty() ) {
1723 cmd_line = (*m_Arguments)[0];
1741 if ( !
ctx.IsSetExitCode() ) {
1742 ctx.SetExitCode(exit_code);
1759 case eSecond:
return "eSecond";
static void fatal(const char *msg,...)
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.
void Print(const CCompactSAMApplication::AlignInfo &ai)
constexpr auto begin(const ct_const_array< T, N > &in) noexcept
string Path(const string &dir, const string &file)
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
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.
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.
void SetIdler(INcbiIdler *idler, EOwnership ownership)
Set new idler and ownership.
string m_RealExePath
Symlink-free executable path.
virtual ~CNcbiApplicationAPI(void)
Destructor.
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.
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
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.
#define DIAG_POST_LEVEL
Diagnostic post severity level.
void FlushMessages(CDiagHandler &handler)
Flush the collected messages to the current diag handler.
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.
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
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, TLimitsPrintParameter parameter)
[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_)
static const char * suffix[]
Defines CRequestContext class for NCBI C++ diagnostic API.
static const char * str(char *buf, int n)
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.