NCBI C++ ToolKit
ncbiapp_api.hpp
Go to the documentation of this file.

Go to the SVN repository for this file.

1 #ifndef CORELIB___NCBIAPP_API__HPP
2 #define CORELIB___NCBIAPP_API__HPP
3 
4 /* $Id: ncbiapp_api.hpp 102237 2024-04-10 15:29:32Z ivanov $
5  * ===========================================================================
6  *
7  * PUBLIC DOMAIN NOTICE
8  * National Center for Biotechnology Information
9  *
10  * This software/database is a "United States Government Work" under the
11  * terms of the United States Copyright Act. It was written as part of
12  * the author's official duties as a United States Government employee and
13  * thus cannot be copyrighted. This software/database is freely available
14  * to the public for use. The National Library of Medicine and the U.S.
15  * Government have not placed any restriction on its use or reproduction.
16  *
17  * Although all reasonable efforts have been taken to ensure the accuracy
18  * and reliability of the software and data, the NLM and the U.S.
19  * Government do not and cannot warrant the performance or results that
20  * may be obtained by using this software or data. The NLM and the U.S.
21  * Government disclaim all warranties, express or implied, including
22  * warranties of performance, merchantability or fitness for any particular
23  * purpose.
24  *
25  * Please cite the author in any work or product based on this material.
26  *
27  * ===========================================================================
28  *
29  * Authors: Denis Vakatov, Vsevolod Sandomirskiy
30  *
31  *
32  */
33 
34 /// @file ncbiapp.hpp
35 /// Defines the CNcbiApplication and CAppException classes for creating
36 /// NCBI applications.
37 ///
38 /// The CNcbiApplicationAPI class defines the application framework and the high
39 /// high level behavior of an application, and the CAppException class is used
40 /// for the exceptions generated by CNcbiApplicationAPI.
41 
42 
43 #include <corelib/ncbiargs.hpp>
44 #include <corelib/ncbienv.hpp>
45 #include <corelib/metareg.hpp>
46 #include <corelib/version_api.hpp>
48 
49 /// Avoid preprocessor name clash with the NCBI C Toolkit.
50 #if !defined(NCBI_OS_UNIX) || defined(HAVE_NCBI_C)
51 # if defined(GetArgs)
52 # undef GetArgs
53 # endif
54 # define GetArgs GetArgs
55 #endif
56 
57 
58 /** @addtogroup AppFramework
59  *
60  * @{
61  */
62 
63 
65 
66 
67 /////////////////////////////////////////////////////////////////////////////
68 ///
69 /// CAppException --
70 ///
71 /// Define exceptions generated by CNcbiApplicationAPI.
72 ///
73 /// CAppException inherits its basic functionality from CCoreException
74 /// and defines additional error codes for applications.
75 
77 {
78 public:
79  /// Error types that an application can generate.
80  ///
81  /// These error conditions are checked for and caught inside AppMain().
82  enum EErrCode {
83  eUnsetArgs, ///< Command-line argument description not found
84  eSetupDiag, ///< Application diagnostic stream setup failed
85  eLoadConfig, ///< Registry data failed to load from config file
86  eSecond, ///< Second instance of CNcbiApplicationAPI is prohibited
87  eNoRegistry ///< Registry file cannot be opened
88  };
89 
90  /// Translate from the error code value to its string representation.
91  virtual const char* GetErrCodeString(void) const override;
92 
93  // Standard exception boilerplate code.
95 };
96 
97 
98 ///////////////////////////////////////////////////////
99 // CNcbiApplicationGuard
100 //
101 
102 
103 class CNcbiApplicationAPI;
104 
106 {
107 public:
108  ~CNcbiApplicationGuard(void);
109 
110  CNcbiApplicationAPI* Get(void) { return m_App; }
111  const CNcbiApplicationAPI* Get(void) const { return m_App; }
112  CNcbiApplicationAPI* operator->(void) { return Get(); }
113  CNcbiApplicationAPI& operator*(void) { return *Get(); }
114  operator bool(void) const { return m_App != nullptr; }
115  bool operator !(void) const { return m_App == nullptr; }
116 
117 private:
118  friend class CNcbiApplicationAPI;
120 
122  shared_ptr<CReadLockGuard> m_AppLock;
123 };
124 
125 
126 ///////////////////////////////////////////////////////
127 // CNcbiApplicationAPI
128 //
129 
130 
131 /////////////////////////////////////////////////////////////////////////////
132 ///
133 /// CNcbiApplicationAPI --
134 ///
135 /// Basic (abstract) NCBI application class.
136 ///
137 /// Defines the high level behavior of an NCBI application.
138 /// A new application is written by deriving a class from the CNcbiApplicationAPI
139 /// and writing an implementation of the Run() and maybe some other (like
140 /// Init(), Exit(), etc.) methods.
141 
143 {
144 public:
145  /// Singleton method.
146  ///
147  /// Track the instance of CNcbiApplicationAPI, and throw an exception
148  /// if an attempt is made to create another instance of the application.
149  /// @return
150  /// Current application instance.
151  /// @sa
152  /// GetInstanceMutex()
153  static CNcbiApplicationAPI* Instance(void);
154 
155  /// Singleton method.
156  ///
157  /// Get instance of the application and prevent its destruction until the lock is destroyed.
158  /// @return
159  /// Current application instance guard.
160  /// @sa
161  /// CNcbiApplicationGuard
162  static CNcbiApplicationGuard InstanceGuard(void);
163 
164  /// Mutex for application singleton object.
165  ///
166  /// Lock this mutex when calling Instance()
167  /// @return
168  /// Reference to application instance mutex.
169  /// @sa
170  /// Instance()
171  /// @deprecated Use InstanceGuard() instead.
173  static SSystemMutex& GetInstanceMutex(void);
174 
175  /// Constructor.
176  ///
177  /// Register the application instance, and reset important
178  /// application-specific settings to empty values that will
179  /// be set later.
180  explicit
181  CNcbiApplicationAPI(const SBuildInfo& build_info);
182 
183  /// Destructor.
184  ///
185  /// Clean up the application settings, flush the diagnostic stream.
186  virtual ~CNcbiApplicationAPI(void);
187 
188  /// Main function (entry point) for the NCBI application.
189  ///
190  /// You can specify where to write the diagnostics to (EAppDiagStream),
191  /// and where to get the configuration file (LoadConfig()) to load
192  /// to the application registry (accessible via GetConfig()).
193  ///
194  /// Throw exception if:
195  /// - not-only instance
196  /// - cannot load explicitly specified config.file
197  /// - SetupDiag() throws an exception
198  ///
199  /// If application name is not specified a default of "ncbi" is used.
200  /// Certain flags such as -logfile, -conffile and -version are special so
201  /// AppMain() processes them separately.
202  /// @param argc
203  /// Argument count [argc in a regular main(argc, argv)].
204  /// @param argv
205  /// Argument vector [argv in a regular main(argc, argv)].
206  /// @param envp
207  /// Environment pointer [envp in a regular main(argc, argv, envp)];
208  /// a null pointer (the default) corresponds to the standard system
209  /// array (environ on most Unix platforms).
210  /// @param diag
211  /// Specify diagnostic stream.
212  /// @param conf
213  /// Specify registry to load, as per LoadConfig(). The default is an
214  /// empty string, requesting automatic detection; it is also possible
215  /// to pass a specific name (optionally qualified) or a NULL pointer
216  /// (disabling application-specific registry lookup altogether).
217  /// @param name
218  /// Specify application name, used in diagnostics and automatic
219  /// registry searching.
220  /// @return
221  /// Exit code from Run(). Can also return non-zero value if application
222  /// threw an exception.
223  /// @sa
224  /// LoadConfig(), Init(), Run(), Exit()
225  int AppMain
226  (int argc,
227  const char* const* argv,
228  const char* const* envp = 0,
230  const char* conf = NcbiEmptyCStr,
231  const string& name = NcbiEmptyString
232  );
233 
234 #if defined(NCBI_OS_MSWIN) && defined(_UNICODE)
235  int AppMain
236  (int argc,
237  const TXChar* const* argv,
238  const TXChar* const* envp = 0,
240  const TXChar* conf = NcbiEmptyXCStr,
241  const TXString& name = NcbiEmptyXString
242  );
243 #endif
244 
245  /// Initialize the application.
246  ///
247  /// The default behavior of this is "do nothing". If you have special
248  /// initialization logic that needs to be peformed, then you must override
249  /// this method with your own logic.
250  virtual void Init(void);
251 
252  /// Run the application.
253  ///
254  /// It is defined as a pure virtual method -- so you must(!) supply the
255  /// Run() method to implement the application-specific logic.
256  /// @return
257  /// Exit code.
258  virtual int Run(void) = 0;
259 
260  /// Test run the application.
261  ///
262  /// It is only supposed to test if the Run() is possible,
263  /// or makes sense: that is, test all preconditions etc.
264  /// @return
265  /// Exit code.
266  virtual int DryRun(void);
267 
268  /// Cleanup on application exit.
269  ///
270  /// Perform cleanup before exiting. The default behavior of this is
271  /// "do nothing". If you have special cleanup logic that needs to be
272  /// performed, then you must override this method with your own logic.
273  virtual void Exit(void);
274 
275  /// Get the application's cached unprocessed command-line arguments.
276  const CNcbiArguments& GetArguments(void) const;
277 
278  /// Get parsed command line arguments.
279  ///
280  /// Get command line arguments parsed according to the arg descriptions
281  /// set by SetupArgDescriptions(). Throw exception if no descriptions
282  /// have been set.
283  /// @return
284  /// The CArgs object containing parsed cmd.-line arguments.
285  /// @sa
286  /// SetupArgDescriptions().
287  virtual const CArgs& GetArgs(void) const;
288 
289  /// Get the application's cached environment.
290  const CNcbiEnvironment& GetEnvironment(void) const;
291 
292  /// Get a non-const copy of the application's cached environment.
293  CNcbiEnvironment& SetEnvironment(void);
294 
295  /// Set a specified environment variable by name
296  void SetEnvironment(const string& name, const string& value);
297 
298  /// Check if the config file has been loaded
299  bool HasLoadedConfig(void) const;
300 
301  /// Check if the application has finished loading config file (successfully or not).
302  bool FinishedLoadingConfig(void) const;
303 
304  /// Get the application's cached configuration parameters (read-only).
305  ///
306  /// Application also can use protected GetRWConfig() to get read-write
307  // access to the configuration parameters.
308  /// @sa
309  /// GetRWConfig
310  const CNcbiRegistry& GetConfig(void) const;
311 
312  /// @deprecated Please use the const version of GetConfig() or protected GetRWConfig()
313  //NCBI_DEPRECATED
314  CNcbiRegistry& GetConfig(void);
315 
316  /// Get the full path to the configuration file (if any) we ended
317  /// up using.
318  const string& GetConfigPath(void) const;
319 
320  /// Reload the configuration file. By default, does nothing if
321  /// the file has the same size and date as before.
322  ///
323  /// Note that this may lose other data stored in the registry!
324  ///
325  /// @param flags
326  /// Controls how aggressively to reload.
327  /// @param reg_flags
328  /// Flags to use when parsing the registry; ignored if the registry
329  /// was already cached (as it should normally have been).
330  /// @return
331  /// TRUE if a reload actually occurred.
332  bool ReloadConfig(CMetaRegistry::TFlags flags
335 
336  /// Flush the in-memory diagnostic stream (for "eDS_ToMemory" case only).
337  ///
338  /// In case of "eDS_ToMemory", the diagnostics is stored in
339  /// the internal application memory buffer ("m_DiagStream").
340  /// Call this function to dump all the diagnostics to stream "os" and
341  /// purge the buffer.
342  /// @param os
343  /// Output stream to dump diagnostics to. If it is NULL, then
344  /// nothing will be written to it (but the buffer will still be purged).
345  /// @param close_diag
346  /// If "close_diag" is TRUE, then also destroy "m_DiagStream".
347  /// @return
348  /// Total number of bytes actually written to "os".
349  SIZE_TYPE FlushDiag(CNcbiOstream* os, bool close_diag = false);
350 
351  /// Get the application's "display" name.
352  ///
353  /// Get name of this application, suitable for displaying
354  /// or for using as the base name for other files.
355  /// Will be the 'name' argument of AppMain if given.
356  /// Otherwise will be taken from the actual name of the application file
357  /// or argv[0].
358  const string& GetProgramDisplayName(void) const;
359 
360  /// Get the application's executable path.
361  ///
362  /// The path to executable file of this application.
363  /// Return empty string if not possible to determine this path.
364  const string& GetProgramExecutablePath(EFollowLinks follow_links = eIgnoreLinks) const;
365 
367  eBaseName, ///< per GetProgramDisplayName
368  eFullName, ///< per GetProgramExecutablePath(eIgnoreLinks)
369  eRealName ///< per GetProgramExecutablePath(eFollowLinks)
370  };
371  static string GetAppName(EAppNameType name_type = eBaseName,
372  int argc = 0, const char* const* argv = NULL);
373 
374  /// Get the program version information.
375  ///
376  /// @sa SetVersion, SetFullVersion
377  CVersionInfo GetVersion(void) const;
378 
379  /// Get the program version information.
380  const CVersionAPI& GetFullVersion(void) const;
381 
382  /// Check if it is a test run.
383  bool IsDryRun(void) const;
384 
385  /// Setup application specific diagnostic stream.
386  ///
387  /// Called from SetupDiag when it is passed the eDS_AppSpecific parameter.
388  /// Currently, this calls SetupDiag(eDS_ToStderr) to setup diagonistic
389  /// stream to the std error channel.
390  /// @return
391  /// TRUE if successful, FALSE otherwise.
392  /// @deprecated
393  NCBI_DEPRECATED virtual bool SetupDiag_AppSpecific(void);
394 
395  /// Add callback to be executed from CNcbiApplicationAPI destructor.
396  /// @note It is executed earlier, at CNcbiApplication destructor; and, it
397  /// may be executed even earlier from destructors of other
398  /// CNcbiApplicationAPI-derived classes.
399  /// @sa CNcbiActionGuard, ExecuteOnExitActions()
400  template<class TFunc> void AddOnExitAction(TFunc func)
401  {
402  m_OnExitActions.AddAction(func);
403  }
404 
405 protected:
406  friend class CNcbiApplicationGuard;
407  static CRWLock& GetInstanceLock(void);
408 
409  /// Result of PreparseArgs()
411  ePreparse_Continue, ///< Continue application execution
412  ePreparse_Exit ///< Exit the application with zero exit code
413  };
414 
415  /// Check the command line arguments before parsing them.
416  /// @sa EPreparseArgs
417  virtual EPreparseArgs PreparseArgs(int argc,
418  const char* const* argv);
419 
420  /// Disable argument descriptions.
421  ///
422  /// Call with a bit flag set if you do not want std AND user
423  /// cmd.line args to be parsed.
424  /// Note that by default the parsing of cmd.line args are enabled.
426  fDisableStdArgs = 0x01 ///< (-logfile, -conffile, -version etc)
427  };
428  typedef int TDisableArgDesc; ///< Binary OR of "EDisableArgDesc"
429  void DisableArgDescriptions(TDisableArgDesc disable = fDisableStdArgs);
430 
431  /// Which standard flag's descriptions should not be displayed in
432  /// the usage message.
433  ///
434  /// Do not display descriptions of the standard flags such as the
435  /// -h, -logfile, -conffile, -version
436  /// flags in the usage message. Note that you still can pass them in
437  /// the command line.
439  fHideLogfile = CArgDescriptions::fHideLogfile, ///< Hide log file description
440  fHideConffile = CArgDescriptions::fHideConffile, ///< Hide configuration file description
441  fHideVersion = CArgDescriptions::fHideVersion, ///< Hide version description
442  fHideFullVersion = CArgDescriptions::fHideFullVersion, ///< Hide full version description
443  fHideDryRun = CArgDescriptions::fHideDryRun, ///< Hide dryrun description
444  fHideHelp = CArgDescriptions::fHideHelp, ///< Hide help description
445  fHideFullHelp = CArgDescriptions::fHideFullHelp, ///< Hide full help description
446  fHideXmlHelp = CArgDescriptions::fHideXmlHelp, ///< Hide XML help description
447  fHideAll = CArgDescriptions::fHideAll ///< Hide all standard argument descriptions
448  };
449  typedef int THideStdArgs; ///< Binary OR of "EHideStdArgs"
450 
451  /// Set the hide mask for the Hide Std Flags.
452  void HideStdArgs(THideStdArgs hide_mask);
453 
454  /// Flags to adjust standard I/O streams' behaviour.
455  enum EStdioSetup {
456  fNoSyncWithStdio = 0x01,
457  ///< Turn off synchronizing of "C++" cin/cout/cerr streams with
458  ///< their "C" counterparts, possibly making the former not thread-safe.
459 
460  fDefault_CinBufferSize = 0x02,
461  ///< Use compiler-specific default of Cin buffer size.
462  fBinaryCin = 0x04, ///< treat standard input as binary
463  fBinaryCout = 0x08, ///< treat standard output as binary
464 
465  fDefault_SyncWithStdio = 0x00, ///< @deprecated @sa fNoSyncWithStdio
466  };
467  typedef int TStdioSetupFlags; ///< Binary OR of "EStdioSetup"
468 
469  /// Adjust the behavior of standard I/O streams.
470  ///
471  /// Unless this function is called, the behaviour of "C++" Cin/Cout/Cerr
472  /// streams will be the same regardless of the compiler used.
473  ///
474  /// IMPLEMENTATION NOTE: Do not call this function more than once
475  /// and from places other than App's constructor.
476  void SetStdioFlags(TStdioSetupFlags stdio_flags);
477 
478  /// Set the version number for the program.
479  ///
480  /// If not set, a default of 0.0.teamcity_build_number is used.
481  /// @note
482  /// This function should be used from constructor of CNcbiApplicationAPI
483  /// derived class, otherwise command-like arguments "-version" and
484  /// "-version-full" will not work as expected.
485  /// @sa GetVersion, NCBI_APP_SET_VERSION, NCBI_APP_SET_VERSION_AUTO
486  void SetVersion(const CVersionInfo& version);
487  void SetVersion(const CVersionInfo& version, const SBuildInfo& build_info);
488  NCBI_DEPRECATED void SetVersionByBuild(int major);
489 
490  /// Set version data for the program.
491  ///
492  /// @note
493  /// This function should be used from constructor of CNcbiApplicationAPI
494  /// derived class, otherwise command-like arguments "-version" and
495  /// "-version-full" will not work as expected.
496  /// @sa GetVersion
497  void SetFullVersion( CRef<CVersionAPI> version);
498 
499  /// Setup the command line argument descriptions.
500  ///
501  /// Call from the Init() method. The passed "arg_desc" will be owned
502  /// by this class, and it will be deleted by ~CNcbiApplicationAPI(),
503  /// or if SetupArgDescriptions() is called again.
504  virtual void SetupArgDescriptions(CArgDescriptions* arg_desc);
505 
506  /// Get argument descriptions (set by SetupArgDescriptions)
507  const CArgDescriptions* GetArgDescriptions(void) const;
508 
509  /// Setup the application diagnostic stream.
510  /// @return
511  /// TRUE if successful, FALSE otherwise.
512  /// @deprecated
513  NCBI_DEPRECATED bool SetupDiag(EAppDiagStream diag);
514 
515  /// Load settings from the configuration file to the registry.
516  ///
517  /// This method is called from inside AppMain() to load (add) registry
518  /// settings from the configuration file specified as the "conf" arg
519  /// passed to AppMain(). The "conf" argument has the following special
520  /// meanings:
521  /// - NULL -- don't try to load an application-specific registry
522  /// from any file at all.
523  /// - non-empty -- if "conf" contains a path, then try to load from the
524  /// conf.file of name "conf" (only!). Else - see NOTE.
525  /// TIP: if the path is not fully qualified then:
526  /// if it starts from "../" or "./" -- look starting
527  /// from the current working dir.
528  /// - empty -- compose conf.file name from the application name
529  /// plus ".ini". If it does not match an existing
530  /// file, then try to strip file extensions, e.g. for
531  /// "my_app.cgi.exe" -- try subsequently:
532  /// "my_app.cgi.exe.ini", "my_app.cgi.ini", "my_app.ini".
533  ///
534  /// Regardless, this method normally loads global settings
535  /// from .ncbirc or ncbi.ini when reg_flags contains fWithNcbirc
536  /// (as it typically does), even if conf is NULL.
537  ///
538  /// NOTE:
539  /// If "conf" arg is empty or non-empty, but without path, then
540  /// the Toolkit will try to look for it in several potentially
541  /// relevant directories, as described in <corelib/metareg.hpp>.
542  ///
543  /// Throw an exception if "conf" is non-empty, and cannot open file.
544  /// Throw an exception if file exists, but contains invalid entries.
545  /// @param reg
546  /// The loaded registry is returned via the reg parameter.
547  /// @param conf
548  /// The configuration file to loaded the registry entries from.
549  /// @param reg_flags
550  /// Flags for loading the registry
551  /// @return
552  /// TRUE only if the file was non-NULL, found and successfully read.
553  /// @sa
554  /// CMetaRegistry::GetDefaultSearchPath
555  virtual bool LoadConfig(CNcbiRegistry& reg, const string* conf,
556  CNcbiRegistry::TFlags reg_flags);
557 
558  /// Load settings from the configuration file to the registry.
559  ///
560  /// CNcbiApplicationAPI::LoadConfig(reg, conf) just calls
561  /// LoadConfig(reg, conf, IRegistry::fWithNcbirc).
562  virtual bool LoadConfig(CNcbiRegistry& reg, const string* conf);
563 
564  /// Get the application's cached configuration parameters,
565  /// accessible for read-write for an application's internal use only.
566  /// @sa
567  /// GetConfig
568  CNcbiRegistry& GetRWConfig(void);
569 
570  /// Set program's display name.
571  ///
572  /// Set up application name suitable for display or as a basename for
573  /// other files. It can also be set by the user when calling AppMain().
574  void SetProgramDisplayName(const string& app_name);
575 
576  /// Find the application's executable file.
577  ///
578  /// Find the path and name of the executable file that this application
579  /// is running from. Will be accessible by GetArguments().GetProgramName().
580  /// @param argc
581  /// Standard argument count "argc".
582  /// @param argv
583  /// Standard argument vector "argv".
584  /// @param real_path
585  /// If non-NULL, will get the fully resolved path to the executable.
586  /// @return
587  /// Name of application's executable file (may involve symlinks).
588  /// @sa
589  /// GetArguments().GetProgramName(), GetProgramExecutablePath
590  static string FindProgramExecutablePath(int argc, const char* const* argv,
591  string* real_path = 0);
592 
593  /// Method to be called before application start.
594  /// Can be used to set DiagContext properties to be printed
595  /// in the application start message (e.g. host|host_ip_addr,
596  /// client_ip and session_id for CGI applications).
597  virtual void AppStart(void);
598 
599  /// Method to be called before application exit.
600  /// Can be used to set DiagContext properties to be printed
601  /// in the application stop message (exit_status, exit_signal,
602  /// exit_code).
603  virtual void AppStop(int exit_code);
604 
605  /// When to return a user-set exit code
606  enum EExitMode {
607  eNoExits, ///< never (stick to existing logic)
608  eExceptionalExits, ///< when an (uncaught) exception occurs
609  eAllExits ///< always (ignoring Run's return value)
610  };
611  /// Force the program to return a specific exit code later, either
612  /// when it exits due to an exception or unconditionally. In the
613  /// latter case, Run's return value will be ignored.
614  void SetExitCode(int exit_code, EExitMode when = eExceptionalExits);
615 
616  enum EAppFlags {
617  fSkipSafeStaticDestroy = 1 << 0
618  };
619  typedef int TAppFlags;
620  void SetAppFlags(TAppFlags flags) { m_AppFlags = flags; }
621 
622  /// Should only be called from the destructors of classes derived from
623  /// CNcbiApplicationAPI - if it is necessary to access their data members
624  /// and virtual methods; or to dynamic_cast<> from the base app class.
625  /// @sa AddOnExitAction()
626  void ExecuteOnExitActions();
627 
628  /// Set Phone Home Policy.
629  ///
630  /// - To activate a new policy this method can be used in the application's Init(),
631  /// after setting up a command line arguments, or as soon as possible in the Run().
632  /// - To deactivate current policy and cleanup, it can be used at the end of Run(),
633  /// or in the application's Exit() with the NULL argument.
634  /// @param policy
635  /// Pointer to new Phone Home policy.
636  /// NULL - delete current policy without a setting new one. If you have active policy,
637  /// it automatically calls Finish() for the previously set policy, if any.
638  /// @param ownership
639  /// Phone Home policy ownership.
640  /// @sa GetPhoneHomePolicy(), IPhoneHomePolicy
641  void SetPhoneHomePolicy(IPhoneHomePolicy* policy, ENcbiOwnership ownership = eNoOwnership);
642 
643  /// Return pointer to current Phone Home Policy or NULL.
644  /// @sa SetPhoneHomePolicy(), IPhoneHomePolicy
645  IPhoneHomePolicy* GetPhoneHomePolicy() const { return m_PhoneHomePolicy; };
646 
647 private:
648  /// Read standard NCBI application configuration settings.
649  ///
650  /// [NCBI]: HeapSizeLimit, CpuTimeLimit
651  /// [DEBUG]: ABORT_ON_THROW, DIAG_POST_LEVEL, MessageFile
652  /// @param reg
653  /// Registry to read from. If NULL, use the current registry setting.
654  void x_HonorStandardSettings(IRegistry* reg = 0);
655 
656  /// Read switches that are stored in m_LogOptions from registry and
657  /// environment
658  void x_ReadLogOptions();
659 
660  /// Log environment, registry, command arguments, path
661  void x_LogOptions(int event);
662 
663  /// Setup C++ standard I/O streams' behaviour.
664  ///
665  /// Called from AppMain() to do compiler-specific optimization
666  /// for C++ I/O streams. For example, since SUN WorkShop STL stream
667  /// library has significant performance loss when sync_with_stdio is
668  /// TRUE (default), so we turn it off. Another, for GCC version greater
669  /// than 3.00 we forcibly set cin stream buffer size to 4096 bytes -- which
670  /// boosts the performance dramatically.
671  void x_SetupStdio(void);
672 
673  void x_AddDefaultArgs(void);
674 
675  // Wrappers for parts of AppMain() called with or without try/catch
676  // depending on settings.
677  void x_TryInit(EAppDiagStream diag, const char* conf);
678  void x_TryMain(EAppDiagStream diag,
679  const char* conf,
680  int* exit_code,
681  bool* got_exception);
682 
683  static CNcbiApplicationAPI* m_Instance; ///< Current app. instance
684  CRef<CVersionAPI> m_Version; ///< Program version
685  unique_ptr<CNcbiEnvironment> m_Environ; ///< Cached application env.
686  CRef<CNcbiRegistry> m_Config; ///< Guaranteed to be non-NULL
687  unique_ptr<CNcbiOstream> m_DiagStream; ///< Opt., aux., see eDS_ToMemory
688  unique_ptr<CNcbiArguments> m_Arguments; ///< Command-line arguments
689  unique_ptr<CArgDescriptions> m_ArgDesc; ///< Cmd.-line arg descriptions
690  unique_ptr<CArgs> m_Args; ///< Parsed cmd.-line args
691  TDisableArgDesc m_DisableArgDesc; ///< Arg desc. disabled
692  THideStdArgs m_HideArgs; ///< Std cmd.-line flags to hide
693  TStdioSetupFlags m_StdioFlags; ///< Std C++ I/O adjustments
694  char* m_CinBuffer; ///< Cin buffer if changed
695  string m_ProgramDisplayName; ///< Display name of app
696  string m_ExePath; ///< Program executable path
697  string m_RealExePath; ///< Symlink-free executable path
698  mutable string m_LogFileName; ///< Log file name
699  string m_ConfigPath; ///< Path to .ini file used
700  int m_ExitCode; ///< Exit code to force
701  EExitMode m_ExitCodeCond; ///< When to force it (if ever)
702  bool m_DryRun; ///< Dry run
703  string m_DefaultConfig; ///< conf parameter to AppMain
704  bool m_ConfigLoaded; ///< Finished loading config
705  const char* m_LogFile; ///< Logfile if set in the command line
706  int m_LogOptions; ///< logging of env, reg, args, path
707  CNcbiActionGuard m_OnExitActions; ///< Actions executed on app destruction
708  IPhoneHomePolicy* m_PhoneHomePolicy; ///< Pointer to active Phone Home Policy, if any
709  ENcbiOwnership m_PhoneHomePolicy_Ownership; ///< Phone Home Policy ownersheep
710  TAppFlags m_AppFlags = 0;
711 };
712 
713 /// Interface for application idler.
715 public:
716  virtual ~INcbiIdler(void) {}
717 
718  // Perform any actions. Called by RunIdle().
719  virtual void Idle(void) = 0;
720 };
721 
722 
723 /// Default idler.
725 {
726 public:
727  CDefaultIdler(void) {}
728  virtual ~CDefaultIdler(void) {}
729 
730  virtual void Idle(void);
731 };
732 
733 
734 /// Return currently installed idler or NULL. Update idler ownership
735 /// according to the flag.
737 
738 /// Set new idler and ownership.
740  EOwnership ownership = eTakeOwnership);
741 
742 /// Execute currently installed idler if any.
743 NCBI_XNCBI_EXPORT void RunIdler(void);
744 
745 
746 /* @} */
747 
748 
749 
750 /////////////////////////////////////////////////////////////////////////////
751 // IMPLEMENTATION of INLINE functions
752 /////////////////////////////////////////////////////////////////////////////
753 
754 
756 {
757  return *m_Arguments;
758 }
759 
761 {
762  return *m_Environ;
763 }
764 
766 {
767  return *m_Environ;
768 }
769 
771 {
772  return *m_Config;
773 }
774 
775 /// @deprecated
777 {
778  return *m_Config;
779 }
780 
782 {
783  return *m_Config;
784 }
785 
786 inline const string& CNcbiApplicationAPI::GetConfigPath(void) const
787 {
788  return m_ConfigPath;
789 }
790 
792 {
793  return !m_ConfigPath.empty();
794 }
795 
797 {
798  return m_ConfigLoaded;
799 }
800 
802 {
803  return CMetaRegistry::Reload(GetConfigPath(), GetRWConfig(), flags, reg_flags);
804 }
805 
806 inline const string& CNcbiApplicationAPI::GetProgramDisplayName(void) const
807 {
808  return m_ProgramDisplayName;
809 }
810 
811 inline const string&
813 {
814  return follow_links == eFollowLinks ? m_RealExePath : m_ExePath;
815 }
816 
817 
819 {
820  return m_ArgDesc.get();
821 }
822 
823 
824 inline bool CNcbiApplicationAPI::IsDryRun(void) const
825 {
826  return m_DryRun;
827 }
828 
829 
830 #ifndef CORELIB___NCBIAPP__HPP
831 # define CNcbiApplication CNcbiApplicationAPI
832 #endif
833 
835 
836 #endif /* CORELIB___NCBIAPP_API__HPP */
CAppException –.
Definition: ncbiapp_api.hpp:77
CArgDescriptions –.
Definition: ncbiargs.hpp:541
CArgs –.
Definition: ncbiargs.hpp:379
CCoreException –.
Definition: ncbiexpt.hpp:1476
Default idler.
static bool Reload(const string &path, IRWRegistry &reg, TFlags flags=0, TRegFlags reg_flags=0)
Reload the configuration file "path".
Definition: metareg.hpp:228
@ fReloadIfChanged
Reload if time or size has changed.
Definition: metareg.hpp:53
int TFlags
Binary OR of "EFlags".
Definition: metareg.hpp:57
CNcbiActionGuard class Executes registered callbacks on request or on destruction.
Definition: ncbimisc.hpp:1387
CNcbiApplicationAPI –.
CNcbiArguments –.
Definition: ncbienv.hpp:236
CNcbiEnvironment –.
Definition: ncbienv.hpp:110
CNcbiRegistry –.
Definition: ncbireg.hpp:913
CRWLock –.
Definition: ncbimtx.hpp:953
CVersionInfo –.
Interface for application idler.
Interface class for Phone Home Policy.
IRegistry –.
Definition: ncbireg.hpp:73
static uch flags
#define bool
Definition: bool.h:34
static void Init(void)
Definition: cursor6.c:76
void AddOnExitAction(TFunc func)
Add callback to be executed from CNcbiApplicationAPI destructor.
EHideStdArgs
Which standard flag's descriptions should not be displayed in the usage message.
bool HasLoadedConfig(void) const
Check if the config file has been loaded.
unique_ptr< CNcbiArguments > m_Arguments
Command-line arguments.
bool ReloadConfig(CMetaRegistry::TFlags flags=CMetaRegistry::fReloadIfChanged, IRegistry::TFlags reg_flags=IRegistry::fWithNcbirc)
Reload the configuration file.
CNcbiApplicationAPI * m_App
unique_ptr< CNcbiOstream > m_DiagStream
Opt., aux., see eDS_ToMemory.
int TStdioSetupFlags
Binary OR of "EStdioSetup".
NCBI_EXCEPTION_DEFAULT(CAppException, CCoreException)
string m_ConfigPath
Path to .ini file used.
CNcbiActionGuard m_OnExitActions
Actions executed on app destruction.
TDisableArgDesc m_DisableArgDesc
Arg desc. disabled.
TStdioSetupFlags m_StdioFlags
Std C++ I/O adjustments.
string m_LogFileName
Log file name.
friend class CNcbiApplicationGuard
string m_ProgramDisplayName
Display name of app.
CNcbiApplicationAPI * operator->(void)
virtual int Run(void)=0
Run the application.
int m_LogOptions
logging of env, reg, args, path
void SetAppFlags(TAppFlags flags)
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.
EExitMode
When to return a user-set exit code.
const CNcbiRegistry & GetConfig(void) const
Get the application's cached configuration parameters (read-only).
EStdioSetup
Flags to adjust standard I/O streams' behaviour.
int m_ExitCode
Exit code to force.
char * m_CinBuffer
Cin buffer if changed.
EPreparseArgs
Result of PreparseArgs()
INcbiIdler * GetIdler(EOwnership ownership=eNoOwnership)
Return currently installed idler or NULL.
Definition: ncbiapp.cpp:1852
const char * m_LogFile
Logfile if set in the command line.
bool m_DryRun
Dry run.
EErrCode
Error types that an application can generate.
Definition: ncbiapp_api.hpp:82
const CArgDescriptions * GetArgDescriptions(void) const
Get argument descriptions (set by SetupArgDescriptions)
shared_ptr< CReadLockGuard > m_AppLock
unique_ptr< CNcbiEnvironment > m_Environ
Cached application env.
const string & GetConfigPath(void) const
Get the full path to the configuration file (if any) we ended up using.
unique_ptr< CArgs > m_Args
Parsed cmd.-line args.
IPhoneHomePolicy * GetPhoneHomePolicy() const
Return pointer to current Phone Home Policy or NULL.
int THideStdArgs
Binary OR of "EHideStdArgs".
bool FinishedLoadingConfig(void) const
Check if the application has finished loading config file (successfully or not).
EFollowLinks
Whether to follow symbolic links (also known as shortcuts or aliases)
Definition: ncbimisc.hpp:143
const string & GetProgramDisplayName(void) const
Get the application's "display" name.
bool IsDryRun(void) const
Check if it is a test run.
EExitMode m_ExitCodeCond
When to force it (if ever)
CNcbiRegistry & GetRWConfig(void)
Get the application's cached configuration parameters, accessible for read-write for an application's...
const CNcbiApplicationAPI * Get(void) const
unique_ptr< CArgDescriptions > m_ArgDesc
Cmd.-line arg descriptions.
virtual void Idle(void)=0
EDisableArgDesc
Disable argument descriptions.
int TDisableArgDesc
Binary OR of "EDisableArgDesc".
CNcbiApplicationAPI * Get(void)
CRef< CNcbiRegistry > m_Config
Guaranteed to be non-NULL.
static CNcbiApplicationAPI * m_Instance
Current app. instance.
CNcbiApplicationAPI & operator*(void)
ENcbiOwnership m_PhoneHomePolicy_Ownership
Phone Home Policy ownersheep.
void SetIdler(INcbiIdler *idler, EOwnership ownership=eTakeOwnership)
Set new idler and ownership.
Definition: ncbiapp.cpp:1858
virtual ~CDefaultIdler(void)
virtual ~INcbiIdler(void)
string m_RealExePath
Symlink-free executable path.
const CNcbiArguments & GetArguments(void) const
Get the application's cached unprocessed command-line arguments.
void RunIdler(void)
Execute currently installed idler if any.
Definition: ncbiapp.cpp:1864
bool m_ConfigLoaded
Finished loading config.
THideStdArgs m_HideArgs
Std cmd.-line flags to hide.
string m_DefaultConfig
conf parameter to AppMain
CRef< CVersionAPI > m_Version
Program version.
@ eNoExits
never (stick to existing logic)
@ eExceptionalExits
when an (uncaught) exception occurs
@ ePreparse_Continue
Continue application execution.
@ eUnsetArgs
Command-line argument description not found.
Definition: ncbiapp_api.hpp:83
@ eSecond
Second instance of CNcbiApplicationAPI is prohibited.
Definition: ncbiapp_api.hpp:86
@ eLoadConfig
Registry data failed to load from config file.
Definition: ncbiapp_api.hpp:85
@ eSetupDiag
Application diagnostic stream setup failed.
Definition: ncbiapp_api.hpp:84
@ eIgnoreLinks
Do not follow symbolic links.
Definition: ncbimisc.hpp:144
@ eFollowLinks
Follow symbolic links.
Definition: ncbimisc.hpp:145
@ eFullName
per GetProgramExecutablePath(eIgnoreLinks)
@ eBaseName
per GetProgramDisplayName
@ eTakeOwnership
An object can take ownership of another.
Definition: ncbi_types.h:136
@ eNoOwnership
No ownership is assumed.
Definition: ncbi_types.h:135
@ fHideAll
Hide all standard argument descriptions.
Definition: ncbiargs.hpp:1072
@ fHideFullVersion
Hide full version description.
Definition: ncbiargs.hpp:1067
@ fHideConffile
Hide configuration file description.
Definition: ncbiargs.hpp:1065
@ fHideHelp
Hide help description.
Definition: ncbiargs.hpp:1069
@ fHideXmlHelp
Hide XML help description.
Definition: ncbiargs.hpp:1071
@ fHideLogfile
Hide log file description.
Definition: ncbiargs.hpp:1064
@ fHideVersion
Hide version description.
Definition: ncbiargs.hpp:1066
@ fHideFullHelp
Hide full help description.
Definition: ncbiargs.hpp:1070
@ fHideDryRun
Hide dryrun description.
Definition: ncbiargs.hpp:1068
#define NULL
Definition: ncbistd.hpp:225
EAppDiagStream
Where to write the application's diagnostics to.
Definition: ncbidiag.hpp:1780
@ eDS_Default
Try standard log file (app.name + ".log") in /log/, use stderr on failure.
Definition: ncbidiag.hpp:1790
virtual const char * GetErrCodeString(void) const override
Translate from the error code value to its string representation.
Definition: ncbiexpt.cpp:757
#define NCBI_DEPRECATED
int TFlags
Binary OR of "EFlags".
Definition: ncbireg.hpp:107
@ fWithNcbirc
Include .ncbirc (used only by CNcbiReg.)
Definition: ncbireg.hpp:93
#define END_NCBI_SCOPE
End previously defined NCBI scope.
Definition: ncbistl.hpp:103
#define BEGIN_NCBI_SCOPE
Define ncbi namespace.
Definition: ncbistl.hpp:100
IO_PREFIX::ostream CNcbiOstream
Portable alias for ostream.
Definition: ncbistre.hpp:149
NCBI_NS_STD::string::size_type SIZE_TYPE
Definition: ncbistr.hpp:132
#define NcbiEmptyCStr
Definition: ncbistr.hpp:59
#define NcbiEmptyXCStr
Definition: ncbistr.hpp:184
#define NcbiEmptyXString
Definition: ncbistr.hpp:185
char TXChar
Definition: ncbistr.hpp:172
string TXString
Definition: ncbistr.hpp:173
#define NcbiEmptyString
Definition: ncbistr.hpp:122
enum ENcbiOwnership EOwnership
Ownership relations between objects.
ENcbiOwnership
Ownership relations between objects.
Definition: ncbi_types.h:134
#define NCBI_XNCBI_EXPORT
Definition: ncbi_export.h:1283
CMetaRegistry: Singleton class for loading CRegistry data from files; keeps track of what it loaded f...
const TYPE & Get(const CNamedParameterList *param)
const string version
version string
Definition: variables.hpp:66
const GenericPointer< typename T::ValueType > T2 value
Definition: pointer.h:1227
#define GetArgs
Avoid preprocessor name clash with the NCBI C Toolkit.
Definition: ncbiapp_api.hpp:54
Defines command line argument related classes.
Defines unified interface to application:
Define IPhoneHomePolicy, interface class for Phone Home Policy.
This class allows to add build info (date and tag) to application version.
Definition: version_api.hpp:62
Modified on Fri Sep 20 14:57:45 2024 by modify_doxy.py rev. 669887