nidas  v1.2-1520
Classes | Public Types | Public Member Functions | Static Public Member Functions | Public Attributes | Private Member Functions | Private Attributes | Static Private Attributes | List of all members
nidas::core::NidasApp Class Reference

NidasApp handles common options for NIDAS applications. More...

#include <NidasApp.h>

Classes

class  IdFormat
 An IdFormat specifies the format for the SPS ID plus other characteristics, like the width when using decimal format. More...
 

Public Types

enum  id_format_t {
  NOFORMAT_ID, AUTO_ID, DECIMAL_ID, HEX_ID,
  OCTAL_ID
}
 The four possible output formats for sensor-plus-sample IDs: More...
 

Public Member Functions

nidas_app_arglist_t loggingArgs ()
 This is a convenience method to return all of the logging-related options in a list, such that this list can be extended if new log options are enabled. More...
 
 NidasApp (const std::string &name)
 Construct a NidasApp instance and give it a name to be used for the usage info. More...
 
 ~NidasApp ()
 If this instance is the current application instance, then the application instance is reset to null when this is destroyed. More...
 
std::string getName ()
 
void setProcessName (const std::string &argv0)
 Set the name of this particular process, usually argv[0]. More...
 
std::string getProcessName ()
 Get the process name, as set by setProcessName(), or else return the app name from getName(). More...
 
void setApplicationInstance ()
 An instance of NidasApp can be set as an application-wide instance, like an application context, which other parts of the application can retrieve with getApplicationInstance(). More...
 
void allowUnrecognized (bool allow)
 Set whether unrecognized flags should throw an exception or not. More...
 
bool allowUnrecognized ()
 Return whether unrecognized flags are allowed or not. More...
 
void enableArguments (const nidas_app_arglist_t &arglist)
 Add the list of NidasAppArg pointers to the set of arguments accepted by this NidasApp instance. More...
 
void requireArguments (const nidas_app_arglist_t &arglist)
 Add arguments to this NidasApp same as enableArguments() but also set them as required. More...
 
void checkRequiredArguments ()
 Verify that all NidasAppArg arguments required by this NidasApp have been specified, otherwise throw NidasAppException. More...
 
nidas_app_arglist_t getArguments ()
 Return the list of arguments which are supported by this NidasApp, in other words, the arguments enabled by enableArguments() or requireArguments(). More...
 
void requireLongFlag (const nidas_app_arglist_t &arglist, bool require=true)
 Call acceptShortFlag(false) on the given list of NidasApp instances, meaning only the long flag will be recognized. More...
 
void startArgs (const ArgVector &args)
 Set the list of command-line argument strings to be parsed and handled by successive calls to nextArgument(). More...
 
void startArgs (int argc, const char *const argv[]) throw (NidasAppException)
 Convenience method to convert the (argc, argv) run string to a list of arguments to pass to startArgs(). More...
 
NidasAppArgparseNext () throw (NidasAppException)
 Parse the next recognized argument from the list set in startArgs(). More...
 
bool nextArg (std::string &arg)
 If the next argument to be parsed does not start with '-', then copy it into arg and remove it from the arguments. More...
 
ArgVector unparsedArgs ()
 
ArgVector parseArgs (const ArgVector &args) throw (NidasAppException)
 Parse all arguments accepted by this NidasApp in the command-line argument list args, but only handle the standard arguments. More...
 
ArgVector parseArgs (int argc, const char *const argv[]) throw (NidasAppException)
 Convenience method to convert the (argc, argv) run string to a list of arguments to pass to parseArgs(). More...
 
void parseLogConfig (const std::string &optarg) throw (NidasAppException)
 Parse a LogConfig from the given argument using the LogConfig string syntax, and add that LogConfig to the current LogScheme. More...
 
void parseLogLevel (const std::string &optarg) throw (NidasAppException)
 This is an alias for parseLogConfig(), since the LogConfig string syntax is backwards compatible with parsing just log levels. More...
 
nidas::util::UTime parseTime (const std::string &optarg)
 
void parseUsername (const std::string &username)
 
void parseInputs (const std::vector< std::string > &inputs, std::string default_input="", int default_port=0) throw (NidasAppException)
 Parse one or more input URLs from a list of non-option command-line arguments. More...
 
bool inputsProvided ()
 
void parseOutput (const std::string &optarg) throw (NidasAppException)
 Parse an output specifier in the form <strptime-filename-pattern>[<length>[smh]]. More...
 
std::string outputFileName ()
 Return just the output file pattern specified by an output option, without the file length specifier. More...
 
int outputFileLength ()
 Return the output file length in seconds. More...
 
int logLevel ()
 Return LogScheme::logLevel() for the current log scheme. More...
 
void resetLogging ()
 Reset logging to the NidasApp default. More...
 
void setProcessData (bool process)
 Set the process-data setting in this NidasApp. More...
 
bool processData ()
 Return the current process-data setting for this NidasApp. More...
 
std::string xmlHeaderFile ()
 
std::string getConfigsXML ()
 Derive the path to the XML file which lists project configs. More...
 
nidas::core::Dataset throw (nidas::util::InvalidParameterException, XMLException)
 Derive a path to an XML datasets file according to the current environment settings, searching these paths in order: More...
 
nidas::util::UTime getStartTime ()
 
nidas::util::UTime getEndTime ()
 
bool interrupted (bool allow_exception=true)
 Return the value of the global interrupted flag. More...
 
void setException (const nidas::util::Exception &ex)
 Like setInterrupted(true), but also allows an exception to be stored which can be tested and retrieved later with hasException() and getException(). More...
 
bool hasException ()
 See setException(). More...
 
nidas::util::Exception getException ()
 Return the current exception. More...
 
ProjectgetProject ()
 Return a pointer to the application-wide Project instance. More...
 
std::string usage (const std::string &indent=" ")
 Return a usage string describing the arguments accepted by this application, rendering each argument by calling NidasAppArg::usage() with the given indent string. More...
 
bool helpRequested ()
 Return true when a help option was parsed, meaning the usage info has been requested. More...
 
void setIdFormat (IdFormat idt)
 Store the format in which sample IDs should be shown. More...
 
IdFormat getIdFormat ()
 
std::ostream & formatSampleId (std::ostream &out, dsm_sample_id_t sid)
 Write the sensor-plus-sample ID part of sid to out using the ID format of this NidasApp instance, the format returned by getIdFormat(), same as calling formatSampleId(out, getIdFormat(), sid). More...
 
std::string formatId (dsm_sample_id_t sid)
 A more convenient form of formatSampleId() which just returns a string, and also includes the DSM id in the familiar format "<dsmid>,<sid>". More...
 
SampleMatchersampleMatcher ()
 Use this method to access the SampleMatcher instance for this NidasApp. More...
 
std::list< std::string > & dataFileNames ()
 Return the list of filenames parsed from the input URLs with parseInputs(). More...
 
nidas::util::SocketAddresssocketAddress ()
 If parseInputs() parsed a network socket specifier, then this method returns a pointer to the corresponding SocketAddress. More...
 
std::string getHostName ()
 Return the hostname passed to the Hostname argument, if any, otherwise return the current hostname as returned by gethostname(). More...
 
std::string getShortHostName ()
 Like getHostName(), but any '. More...
 
std::string getUserName ()
 Return the username passed to the Username argument, if enabled, otherwise return an empty string. More...
 
uid_t getUserID ()
 Return the userid of the username passed to the Username argument, otherwise 0. More...
 
uid_t getGroupID ()
 Return the groupid of the username passed to the Username argument, otherwise 0. More...
 
void setupProcess ()
 Setup a process with the user and group specified by the Username argument, and attempt to set related capabilities. More...
 
void setupDaemonLogging (bool daemon_mode)
 Setup logging according to daemon mode. More...
 
void setupDaemonLogging ()
 Call setupDaemonLogging(daemon_mode), where daemon_mode is true only if DebugDaemon is false. More...
 
void setupDaemon (bool daemon_mode)
 Call setupDaemonLogging(), then switch this process to daemon mode if daemon_mode is true. More...
 
void setupDaemon ()
 Call setupDaemon(daemon_mode), where daemon_mode is true only if DebugDaemon is false. More...
 
void lockMemory ()
 Attempt mlockall() for this process, first adding the CAP_IPC_LOCK capability if possible. More...
 
int checkPidFile ()
 Create a pid file for this process and return 0. More...
 

Static Public Member Functions

static NidasAppgetApplicationInstance ()
 Return the current application instance. More...
 
static void setInterrupted (bool interrupted)
 Set the global interrupted state for NidasApp. More...
 
static void setupSignals (void(*callback)(int signum)=0)
 Setup signal handling for HUP, INT, and TERM, equivalent to calling addSignal() for each. More...
 
static void addSignal (int signum, void(*callback)(int signum)=0, bool nolog=false)
 Add the given signal signum to the list of signals handled by the NidasApp signal handler, and optionally set an additional callback. More...
 
static std::ostream & formatSampleId (std::ostream &out, IdFormat idfmt, dsm_sample_id_t sid)
 Write the sensor-plus-sample ID part of sid to stream out using the format specified in idfmt. More...
 

Public Attributes

NidasAppArg XmlHeaderFile
 
NidasAppArg LogShow
 
NidasAppArg LogConfig
 
NidasAppArg LogFields
 
NidasAppArg LogParam
 
NidasAppArg Help
 
NidasAppArg ProcessData
 
NidasAppArg StartTime
 
NidasAppArg EndTime
 
NidasAppArg SampleRanges
 
NidasAppArg FormatHexId
 
NidasAppArg FormatSampleId
 
NidasAppArg Version
 
NidasAppInputFilesArg InputFiles
 
NidasAppArg OutputFiles
 
NidasAppArg Username
 
NidasAppArg Hostname
 
NidasAppArg DebugDaemon
 
NidasAppArg ConfigsArg
 
NidasAppArg DatasetName
 
NidasAppArg PidFile
 It is not enough to enable this arg in an app, the app must must call checkPidFile() as well. More...
 

Private Member Functions

void setupLogScheme ()
 

Private Attributes

std::string _appname
 
std::string _argv0
 
bool _processData
 
std::string _xmlFileName
 
IdFormat _idFormat
 
SampleMatcher _sampleMatcher
 
nidas::util::UTime _startTime
 
nidas::util::UTime _endTime
 
std::list< std::string > _dataFileNames
 
nidas::util::auto_ptr
< nidas::util::SocketAddress
_sockAddr
 
std::string _outputFileName
 
int _outputFileLength
 
bool _help
 
std::string _username
 
std::string _hostname
 
uid_t _userid
 
gid_t _groupid
 
bool _deleteProject
 
nidas_app_arglist_t _app_arguments
 
ArgVector _argv
 
int _argi
 
bool _hasException
 
nidas::util::Exception _exception
 
bool _allowUnrecognized
 
nidas::util::LogScheme _logscheme
 NidasApp keeps track of the LogScheme built up from arguments. More...
 

Static Private Attributes

static NidasAppapplication_instance = 0
 

Detailed Description

NidasApp handles common options for NIDAS applications.

The application specifies which of the options are valid and it can specify defaults if necessary, then command-line arguments can be parsed and their settings retrieved through this instance. This class allows for consistent option letters and syntax across NIDAS applications. Applications can extend this class with their own options, either as a subclass or by delegation to an instance.

There are several NIDAS applications with common options that can be consolidated in this class:

The goal is to keep syntax and meaning for common arguments consistent across applications.

Standard option Description Replacement Syntax
-i dsmid,sampleidSample IDs to include.
-x dsmid,sampleidSample IDs to exclude.-i ^dsmid,sampid
-l loglevelNumeric log level.-l number_or_name
-l intervalOutput file interval.output@interval
-hHelp
-pProcess samples
-XPrint Hex IDs
-vReport version.
-x xmlfileExplicit header file.
inputSocket or files.
output[@interval]Output pattern, interval
-s starttimeSkip samples before start
-e endtimeSkip samples after end
-dRun in debug mode instead of as a background daemon.
-fFilter bad samples according to default filter rules.
–filter rules Specify rules for filtering bad samples, using a key=value syntax. –filter maxdsm=1024,mindsm=1,maxlen=32768,minlen=1

Below are notes about the deprecated options and the standard options made available through NidasApp.

-x exclude samples

Where -x is accepted but deprecated, -x A,B translates to -i ^A,B.

-l interval

Since -l conflicts with log level and output file length, the separate -l for file length is being deprecated in favor of specifying the length in the output file pattern:

strptime_pattern[@_number_[units]]

Units can be (s)econds, (m)inutes, (h)ours, seconds is the default. Maybe later add units for size like kb, mb.

The -l option needs to be accepted for a while, perhaps differntiated automatically by whether it's a number greater than 10 (for apps which enable that option). But it should produce a warning. Is there ever a case where the output-file-length needs to be specified without an output file name pattern? Is there a reasonable default filename pattern if the output is simply <interval>?

–log , -l

The older –loglevel and –logconfig are obsolete. The short version -l, for the applications which accept it, is an alias for the newer –log option.

The log config string is a comma-separated list of LogConfig fields, where the field names are level, tag, file, function, file, and line. Additionally, a field can have the value 'enable' or 'disable' to set the active flag accordingly for matching log contexts. All the settings are combined into a single LogConfig and added to the current scheme.

If a field does not have an equal sign and is not 'enable' or 'disable', then it is interpreted as just a log level, compatible with what the -l option has always supported.

loglevel can be a number or the name of a log level:

7=debug,6=info,5=notice,4=warn,3=err

The default log level when a NidasApp is created is info.

–logshow

Show log points as they are encountered while the code is running. This shows what log points would log messages if enabled by the logging configuration, and it gives information about each log point that can be used to enable only that log point.

–logfields

Set the log message fields which will be shown in log messages. The <fields> argument is passed to the LogScheme::setShowFields() method of the current logging scheme.

–logparam =

Set a log parameter in the application log scheme.

-s translating sample ids

sensor_extract uses -s to map id selection to a new id, eg 10,1,10,3. Rather than add another option letter, maybe it would be better to extend the -i syntax: -i 10,1=10,3 where the = part is only allowed if specifically enabled. Then sensor_extract just needs a way to enable that extension and to get to that mapping. Or, maybe the mapping can be completely internal to the sample filter: if app passes the sample pointer to the filter, the filter can modify the sample id as specified after checking that the sample is selected.

-d,–debug debug mode

The dsm and dsm_server applications both support a debug mode which runs in the foreground instead of as a daemon, and by default sends all log messages to standard output. The long form is –debug.

-u,–user

For daemon applications, switch to the given user after setting required capabilities.

-H,–host

Run as if on the given host instead of using current system hostname.

Logging

When a NidasApp is constructed, it sets up its own default logging scheme with a fallback log level of INFO. That log scheme is set as the current scheme only if there is not already a scheme with a non-empty name. That allows an app to install its own default LogScheme before creating a NidasApp, but the app of course can also install its own scheme after creating NidasApp. When NidasApp parses logging arguments, it updates and explicitly installs its LogScheme, so the user arguments always override the app and NidasApp defaults.

Since the default INFO log level is a fallback, that will be replaced by the first log config provided as an argument. So a log argument of "warning" will set the log scheme to only show messages at or more critical than warnings.

Member Enumeration Documentation

The four possible output formats for sensor-plus-sample IDs:

noformat - Use an existing setting or the default. auto - Use decimal for samples less than 0x8000, and hex otherwise. decimal - Use decimal for all samples. hex - Use hex for all samples. octal - Use octal for all samples. Not really used.

The default is auto. Set it with –id-format {auto|decimal|hex}.

Enumerator
NOFORMAT_ID 
AUTO_ID 
DECIMAL_ID 
HEX_ID 
OCTAL_ID 

Constructor & Destructor Documentation

NidasApp::NidasApp ( const std::string &  name)

Construct a NidasApp instance and give it a name to be used for the usage info.

References ConfigsArg, getName(), PidFile, nidas::core::NidasAppArg::setDefault(), setupLogScheme(), and nidas::core::NidasAppArg::setUsageString().

NidasApp::~NidasApp ( )

If this instance is the current application instance, then the application instance is reset to null when this is destroyed.

References _deleteProject, application_instance, and nidas::core::Project::destroyInstance().

Member Function Documentation

void NidasApp::addSignal ( int  signum,
void(*)(int signum)  callback = 0,
bool  nolog = false 
)
static

Add the given signal signum to the list of signals handled by the NidasApp signal handler, and optionally set an additional callback.

If non-zero, callback is a function which will be called when the application receives an interrupt signal. The callback is called asynchronously, directly from the NidasApp signal handler function. There can only be one callback, so the one in effect is whatever was set last in setupSignals() and addSignal(). The NidasApp handler sets the flag returned by interrupted(), and then calls the callback function with the signal number as a parameter. signum is a symbol like SIGALRM, SIGHUP, SIGINT, and SIGTERM from signal.h. signum can be zero, in which case only the callback function changes.

If nolog is true, then nothing will be logged to cerr by the default signal handler when that signal is received.

References sigAction().

Referenced by DataStats::run(), and setupSignals().

void NidasApp::allowUnrecognized ( bool  allow)

Set whether unrecognized flags should throw an exception or not.

By default, NidasApp throws an exception when parsing an argument which starts with '-' but is not accepted by one of the enabled arguments. Pass true to this method to ignore those unrecognized flags and leave them in the unparsed arguments list.

References _allowUnrecognized.

Referenced by StatsProcess::parseRunstring(), parseRunstring(), ARLIngest::parseRunstring(), PacketReader::parseRunstring(), and DataDump::parseRunstring().

bool NidasApp::allowUnrecognized ( )

Return whether unrecognized flags are allowed or not.

References _allowUnrecognized.

Referenced by parseNext().

int NidasApp::checkPidFile ( )

Create a pid file for this process and return 0.

If the pid file already exists, then return 1. The path to the PID file is set by the PidFile NidasAppArg, which defaults to /tmp/run/nidas/<appname>.pid. The path can be changed on the command-line if the PidFile argument has been enabled. The directory for the pid file is created if necessary. Usually an app calls this method after the setupDaemon() and setupProcess() calls. This method checks for the pid file even if DebugDaemon is enabled. Otherwise it is possible to create multiple instances of a nidas service on a host which interfere with each other. If it is necessary to start multiple processes, then the –pid argument must be used change the pid file path.

References nidas::util::Process::checkPidFile(), nidas::util::FileSet::createDirectory(), nidas::util::FileSet::getDirPortion(), getProcessName(), nidas::core::NidasAppArg::getValue(), PidFile, PLOG, and nidas::util::Exception::what().

Referenced by nidas::core::DSMServerApp::initProcess(), and nidas::core::DSMEngine::initProcess().

void NidasApp::checkRequiredArguments ( )

Verify that all NidasAppArg arguments required by this NidasApp have been specified, otherwise throw NidasAppException.

References DLOG, and getArguments().

std::list<std::string>& nidas::core::NidasApp::dataFileNames ( )
inline

Return the list of filenames parsed from the input URLs with parseInputs().

If the input URL specified a network socket, then this list is empty. See socketAddress().

References _dataFileNames.

Referenced by StatsProcess::parseRunstring(), DataPrep::parseRunstring(), StatsProcess::run(), DataDump::run(), and DataStats::run().

void NidasApp::enableArguments ( const nidas_app_arglist_t arglist)

Add the list of NidasAppArg pointers to the set of arguments accepted by this NidasApp instance.

Since the arguments are referenced by pointer, their lifetime should match the lifetime of the NidasApp instance. For example, define additional non-standard arguments as members of the same class in which NidasApp is a member.

class MyApp {
NidasAppArg FixEverything;
}
...
app.enableArguments(FixEverything);

The arglist can be created implicitly from the NidasAppArg instances, as in this example:

NidasApp app('na');
app.enableArguments(app.LogConfig | app.ProcessData);

References _app_arguments.

Referenced by DataStats::DataStats(), main(), NidsMerge::parseRunstring(), DmdA2dCk::parseRunstring(), nidas::core::DSMServerApp::parseRunstring(), StatsProcess::parseRunstring(), PConfig::parseRunstring(), ARLIngest::parseRunstring(), PacketReader::parseRunstring(), nidas::core::DSMEngine::parseRunstring(), TeeI2C::parseRunstring(), DataPrep::parseRunstring(), DataDump::parseRunstring(), and requireArguments().

std::string NidasApp::formatId ( dsm_sample_id_t  sid)

A more convenient form of formatSampleId() which just returns a string, and also includes the DSM id in the familiar format "<dsmid>,<sid>".

References formatSampleId(), and GET_DSM_ID.

Referenced by DataStats::createCounters(), DataStats::hashId(), SampleDispatcher::SampleDispatcher(), and SampleToDatabase::SampleToDatabase().

std::ostream & NidasApp::formatSampleId ( std::ostream &  out,
IdFormat  idfmt,
dsm_sample_id_t  sid 
)
static

Write the sensor-plus-sample ID part of sid to stream out using the format specified in idfmt.

This does not print the DSM ID, only the SPS ID.

References AUTO_ID, DECIMAL_ID, nidas::core::NidasApp::IdFormat::decimalWidth(), GET_SHORT_ID, HEX_ID, nidas::core::NidasApp::IdFormat::idFormat(), and OCTAL_ID.

Referenced by formatId(), formatSampleId(), DataStats::printReport(), and DumpClient::receive().

std::ostream & NidasApp::formatSampleId ( std::ostream &  out,
dsm_sample_id_t  sid 
)

Write the sensor-plus-sample ID part of sid to out using the ID format of this NidasApp instance, the format returned by getIdFormat(), same as calling formatSampleId(out, getIdFormat(), sid).

References formatSampleId(), and getIdFormat().

NidasApp * NidasApp::getApplicationInstance ( )
static
nidas_app_arglist_t NidasApp::getArguments ( )

Return the list of arguments which are supported by this NidasApp, in other words, the arguments enabled by enableArguments() or requireArguments().

References _app_arguments.

Referenced by checkRequiredArguments().

std::string NidasApp::getConfigsXML ( )

Derive the path to the XML file which lists project configs.

This uses standard paths parameterized by environment variables, and accepts the first path whose environment variables are set in the environment:

  • "$NIDAS_CONFIGS"
  • "$PROJ_DIR/$PROJECT/$AIRCRAFT/nidas/flights.xml"
  • "$ISFS/projects/$PROJECT/ISFS/config/configs.xml"
  • "$ISFF/projects/$PROJECT/ISFF/config/configs.xml"

If none of the above paths can be derived because of missing environment variables, then throw InvalidParameterException.

References nidas::util::Process::expandEnvVars().

Referenced by nidas::core::DSMServerApp::parseRunstring(), and DataPrep::run().

nidas::util::UTime nidas::core::NidasApp::getEndTime ( )
inline
nidas::util::Exception NidasApp::getException ( )

Return the current exception.

If no exception has been set (hasException() returns false), then the return value is just a default constructed nidas::util::Exception.

References _exception.

Referenced by interrupted().

uid_t nidas::core::NidasApp::getGroupID ( )
inline

Return the groupid of the username passed to the Username argument, otherwise 0.

References _groupid.

Referenced by setupProcess().

std::string NidasApp::getHostName ( )

Return the hostname passed to the Hostname argument, if any, otherwise return the current hostname as returned by gethostname().

References _hostname, and PLOG.

Referenced by getShortHostName(), StatsProcess::getStatisticsProcessor(), and nidas::core::DSMServerApp::run().

IdFormat nidas::core::NidasApp::getIdFormat ( )
inline

References _idFormat.

Referenced by formatSampleId(), and DumpClient::printHeader().

std::string nidas::core::NidasApp::getName ( )
inline
std::string NidasApp::getProcessName ( )

Get the process name, as set by setProcessName(), or else return the app name from getName().

References _argv0, and getName().

Referenced by checkPidFile(), StatsProcess::run(), setupDaemon(), nidas::core::DSMServerApp::usage(), and DataPrep::usage().

Project * NidasApp::getProject ( )

Return a pointer to the application-wide Project instance.

The lifetime is tied to this NidasApp instance.

References _deleteProject, and nidas::core::Project::getInstance().

std::string NidasApp::getShortHostName ( )

Like getHostName(), but any '.

' qualifiers are removed and only the unqualified name is returned.

References getHostName().

Referenced by StatsProcess::parseRunstring().

nidas::util::UTime nidas::core::NidasApp::getStartTime ( )
inline
uid_t nidas::core::NidasApp::getUserID ( )
inline

Return the userid of the username passed to the Username argument, otherwise 0.

References _userid.

Referenced by setupProcess().

std::string nidas::core::NidasApp::getUserName ( )
inline

Return the username passed to the Username argument, if enabled, otherwise return an empty string.

References _username.

Referenced by setupProcess().

bool NidasApp::hasException ( )

See setException().

References _hasException.

Referenced by interrupted().

bool nidas::core::NidasApp::helpRequested ( )
inline
bool nidas::core::NidasApp::inputsProvided ( )
inline

References _dataFileNames, and _sockAddr.

bool NidasApp::interrupted ( bool  allow_exception = true)

Return the value of the global interrupted flag.

If allow_exception is true, and an exception interruption has been set with setException(), then this call will throw that exception. This allows code which checks NidasApp::interrupted() in a loop to work the usual way but also propagate exceptions from the main loop when they happen elsewhere in the application.

References getException(), and hasException().

Referenced by DataStats::readHeader(), DataStats::readSamples(), NidsMerge::run(), StatsProcess::run(), DmdA2dCk::run(), DataPrep::run(), DataDump::run(), DataStats::run(), and setInterrupted().

void NidasApp::lockMemory ( )

Attempt mlockall() for this process, first adding the CAP_IPC_LOCK capability if possible.

References _argv0, nidas::util::Process::addEffectiveCapability(), DLOG, ILOG, nidas::util::Exception::what(), and WLOG.

Referenced by nidas::core::DSMEngine::initProcess().

nidas_app_arglist_t NidasApp::loggingArgs ( )

This is a convenience method to return all of the logging-related options in a list, such that this list can be extended if new log options are enabled.

Only LogConfig has a short log option of -l, so if that option does not conflict, it should be safe to enable all of them. The current list contains these options: LogShow, LogConfig, LogFields, LogParam.

References LogConfig, LogFields, LogParam, and LogShow.

Referenced by DataStats::DataStats(), main(), DmdA2dCk::parseRunstring(), nidas::core::DSMServerApp::parseRunstring(), StatsProcess::parseRunstring(), PConfig::parseRunstring(), ARLIngest::parseRunstring(), PacketReader::parseRunstring(), nidas::core::DSMEngine::parseRunstring(), TeeI2C::parseRunstring(), DataPrep::parseRunstring(), and DataDump::parseRunstring().

int NidasApp::logLevel ( )

Return LogScheme::logLevel() for the current log scheme.

bool NidasApp::nextArg ( std::string &  arg)

If the next argument to be parsed does not start with '-', then copy it into arg and remove it from the arguments.

Callers can use this to consume multiple arguments for a single option flag. Returns true when the argument exists and has been copied into arg, otherwise returns false and arg is unchanged. The returned argument will not be seen by parseNext(), and it will not be returned by unparsedArgs().

References _argi, and _argv.

Referenced by NidsMerge::parseRunstring().

int nidas::core::NidasApp::outputFileLength ( )
inline

Return the output file length in seconds.

References _outputFileLength.

Referenced by NidsMerge::parseRunstring(), and ARLIngest::parseRunstring().

std::string nidas::core::NidasApp::outputFileName ( )
inline

Return just the output file pattern specified by an output option, without the file length specifier.

References _outputFileName.

Referenced by NidsMerge::parseRunstring(), and ARLIngest::parseRunstring().

ArgVector NidasApp::parseArgs ( const ArgVector args)
throw (NidasAppException
)

Parse all arguments accepted by this NidasApp in the command-line argument list args, but only handle the standard arguments.

Any application-specific arguments are only parsed and filled in. This is equivalent to calling startArgs() and then looping over parseNext(), except the caller can not handle individual arguments when they are parsed. For some arguments this works fine, since the last occurrence of an argument on the command-line will be the final value returned by NidasAppArg::getValue(). Returns the remaining unparsed arguments, same as would be returned by unparsedArgs().

This method deliberately does not call checkRequiredArguments(), since arguments like –help need to be handled by the caller even when required arguments are legitimately missing from the argument list. Instead, applications with required arguments should explicitly call checkRequiredArguments() after all required arguments should have been parsed.

The argument vector should not contain the process name. So this is a convenient way to call it from main():

ArgVector args = app.parseArgs(ArgVector(argv+1, argv+argc));
Parameters
argsJust the arguments, without the process name.
Returns
Any remaining arguments not accepted by this NidasApp.

Referenced by DmdA2dCk::parseRunstring(), nidas::core::DSMServerApp::parseRunstring(), StatsProcess::parseRunstring(), parseRunstring(), ARLIngest::parseRunstring(), PacketReader::parseRunstring(), nidas::core::DSMEngine::parseRunstring(), TeeI2C::parseRunstring(), DataDump::parseRunstring(), and DataStats::parseRunstring().

ArgVector NidasApp::parseArgs ( int  argc,
const char *const  argv[] 
)
throw (NidasAppException
)

Convenience method to convert the (argc, argv) run string to a list of arguments to pass to parseArgs().

Also, if the process name has not been set with setProcessName(), then set it to argv[0].

void NidasApp::parseInputs ( const std::vector< std::string > &  inputs,
std::string  default_input = "",
int  default_port = 0 
)
throw (NidasAppException
)

Parse one or more input URLs from a list of non-option command-line arguments.

The default_input and default_port can be passed here to override the defaults set in the InputFiles argument instance. If no inputs are provided, then the defaults are used. If no default is specified, then inputsProvided() will return false. An exception is not thrown just because no inputs were provided.

References nidas::util::LogContext::active(), nidas::util::Inet4Address::getByName(), LOG_DEBUG, port, and nidas::util::Exception::what().

Referenced by DmdA2dCk::parseRunstring(), StatsProcess::parseRunstring(), DataPrep::parseRunstring(), DataDump::parseRunstring(), and DataStats::parseRunstring().

void NidasApp::parseLogConfig ( const std::string &  optarg)
throw (NidasAppException
)

Parse a LogConfig from the given argument using the LogConfig string syntax, and add that LogConfig to the current LogScheme.

References err, and nidas::util::LogConfig::parse().

Referenced by parseLogLevel(), and parseNext().

void nidas::core::NidasApp::parseLogLevel ( const std::string &  optarg)
throw (NidasAppException
)
inline

This is an alias for parseLogConfig(), since the LogConfig string syntax is backwards compatible with parsing just log levels.

References parseLogConfig().

NidasAppArg * NidasApp::parseNext ( )
throw (NidasAppException
)

Parse the next recognized argument from the list set in startArgs().

If it is one of the standard arguments which are members of NidasApp, then handle the argument also. Either way, fill in the NidasAppArg with the flag and value (if any) extracted from the command-line, and return the pointer to that NidasAppArg. If no more arguments are left or none are recognized, then return null. Raise NidasAppException if there is an error parsing any of the standard arguments.

Recognized arguments are removed from the argument list. Call parseRemaining() to return the arguments which have not been parsed, such as to access positional arguments or detect unrecognized arguments. Positional arguments like input sockets and file names are not handled here, since they cannot be differentiated from app-specific arguments yet. Instead those arguments can be passed explicitly to the parseInputs() method.

References _app_arguments, _argi, _argv, _endTime, _help, _hostname, nidas::core::NidasApp::IdFormat::_idFormat, _idFormat, _logscheme, _processData, _sampleMatcher, _startTime, _xmlFileName, nidas::core::SampleMatcher::addCriteria(), nidas::util::LogScheme::addFallback(), allowUnrecognized(), AUTO_ID, DebugDaemon, DECIMAL_ID, EndTime, err, FormatHexId, FormatSampleId, nidas::core::Version::getSoftwareVersion(), nidas::core::NidasAppArg::getValue(), Help, HEX_ID, Hostname, LogConfig, LogFields, LogParam, LogShow, NOFORMAT_ID, OCTAL_ID, OutputFiles, parseLogConfig(), parseOutput(), nidas::util::LogScheme::parseParameter(), parseTime(), parseUsername(), ProcessData, SampleRanges, nidas::core::SampleMatcher::setEndTime(), setIdFormat(), nidas::util::LogScheme::setShowFields(), nidas::core::SampleMatcher::setStartTime(), nidas::util::LogScheme::showLogPoints(), StartTime, Username, and XmlHeaderFile.

Referenced by NidsMerge::parseRunstring(), PConfig::parseRunstring(), and DataPrep::parseRunstring().

void NidasApp::parseOutput ( const std::string &  optarg)
throw (NidasAppException
)

Parse an output specifier in the form <strptime-filename-pattern>[<length>[smh]].

References err.

Referenced by parseNext().

nidas::util::UTime NidasApp::parseTime ( const std::string &  optarg)
void NidasApp::parseUsername ( const std::string &  username)
bool nidas::core::NidasApp::processData ( )
inline

Return the current process-data setting for this NidasApp.

References _processData.

Referenced by DataStats::createCounters(), DataDump::run(), and DataStats::run().

void NidasApp::requireArguments ( const nidas_app_arglist_t arglist)

Add arguments to this NidasApp same as enableArguments() but also set them as required.

See NidasAppArg::setRequired(). An application can conveniently check whether required arguments have been set by calling checkRequiredArguments() when all arguments have been parsed.

References enableArguments().

void nidas::core::NidasApp::requireLongFlag ( const nidas_app_arglist_t arglist,
bool  require = true 
)
inline

Call acceptShortFlag(false) on the given list of NidasApp instances, meaning only the long flag will be recognized.

Referenced by main().

void NidasApp::resetLogging ( )

Reset logging to the NidasApp default.

This erases all log schemes, then sets up the default NidasApp log scheme same as happens in the NidasApp constructor.

References setupLogScheme().

SampleMatcher& nidas::core::NidasApp::sampleMatcher ( )
inline

Use this method to access the SampleMatcher instance for this NidasApp.

After the SampleMatcher is configured by parsing command-line options, it can be used to select sample IDs like so:

bool DumpClient::receive(const Sample* samp) throw()
{
dsm_sample_id_t sampid = samp->getId();
if (!app.sampleMatcher().match(sampid))
{
return false;
}
...
}

References _sampleMatcher.

Referenced by DataStats::createCounters(), DataDump::parseRunstring(), DataDump::run(), and SampleDispatcher::SampleDispatcher().

void NidasApp::setApplicationInstance ( )

An instance of NidasApp can be set as an application-wide instance, like an application context, which other parts of the application can retrieve with getApplicationInstance().

References application_instance.

Referenced by DataDump::DataDump(), DataStats::DataStats(), DmdA2dCk::DmdA2dCk(), main(), and PacketReader::PacketReader().

void NidasApp::setException ( const nidas::util::Exception ex)

Like setInterrupted(true), but also allows an exception to be stored which can be tested and retrieved later with hasException() and getException().

This is useful, for example, in sample receive() methods which may be called from multiple threads and not necessarily from the main thread where readSamples() is called.

Note the exception type is strictly nidas::util::Exception, so a subclass reference can be passed, but the subclass is stripped when copied by NidasApp.

References _exception, _hasException, and setInterrupted().

Referenced by SampleToDatabase::accumulate().

void NidasApp::setIdFormat ( IdFormat  idt)

Store the format in which sample IDs should be shown.

References _idFormat.

Referenced by parseNext(), and DataDump::parseRunstring().

void NidasApp::setInterrupted ( bool  interrupted)
static

Set the global interrupted state for NidasApp.

The default signal handler sets this flag, but this method allows the flag to be set from custom signal handlers or from other parts of the application.

References interrupted().

Referenced by DataStats::handleSignal(), and setException().

void nidas::core::NidasApp::setProcessData ( bool  process)
inline

Set the process-data setting in this NidasApp.

References _processData.

void NidasApp::setProcessName ( const std::string &  argv0)

Set the name of this particular process, usually argv[0].

It defaults to the application name passed to the constructor and returned by getName().

References _argv0.

void NidasApp::setupDaemon ( bool  daemon_mode)
void NidasApp::setupDaemon ( )

Call setupDaemon(daemon_mode), where daemon_mode is true only if DebugDaemon is false.

References nidas::core::NidasAppArg::asBool(), and DebugDaemon.

void NidasApp::setupDaemonLogging ( bool  daemon_mode)

Setup logging according to daemon mode.

Setup the logging scheme and create a Logger according to the daemon mode. Usually an application just calls setupDaemon(), since that method calls setupDaemonLogging() before switching to a daemon (if not disabled).

References _logscheme, getName(), LogShow, nidas::util::LogScheme::setShowFields(), and nidas::core::NidasAppArg::specified().

void NidasApp::setupDaemonLogging ( )

Call setupDaemonLogging(daemon_mode), where daemon_mode is true only if DebugDaemon is false.

References nidas::core::NidasAppArg::asBool(), and DebugDaemon.

Referenced by setupDaemon().

void NidasApp::setupLogScheme ( )
private
void NidasApp::setupProcess ( )

Setup a process with the user and group specified by the Username argument, and attempt to set related capabilities.

References _argv0, nidas::util::Process::addEffectiveCapability(), DLOG, nidas::util::Process::getEffectiveCapability(), getGroupID(), getUserID(), getUserName(), nidas::util::Exception::what(), and WLOG.

Referenced by nidas::core::DSMServerApp::initProcess(), and nidas::core::DSMEngine::initProcess().

void NidasApp::setupSignals ( void(*)(int signum)  callback = 0)
static

Setup signal handling for HUP, INT, and TERM, equivalent to calling addSignal() for each.

References addSignal().

Referenced by DataDump::DataDump(), DataStats::DataStats(), DmdA2dCk::DmdA2dCk(), NidsMerge::main(), StatsProcess::main(), and ARLIngest::main().

nidas::util::SocketAddress* nidas::core::NidasApp::socketAddress ( )
inline

If parseInputs() parsed a network socket specifier, then this method returns a pointer to the corresponding SocketAddress.

Otherwise it returns null. The NidasApp instance owns the pointer.

References _sockAddr.

Referenced by StatsProcess::parseRunstring(), DataPrep::parseRunstring(), StatsProcess::run(), DataPrep::run(), DataDump::run(), and DataStats::run().

void NidasApp::startArgs ( const ArgVector args)

Set the list of command-line argument strings to be parsed and handled by successive calls to nextArgument().

The usual calling sequence is this:

app.enableArguments(...);
app.startArgs(ArgVector(argv+1, argv+argc));
NidasAppArg* arg;
while ((arg = app.parseNext())) {
if (arg == &FixEverything)
_fixeverything = True;
else if (arg == &FixCount)
_fixcount = FixCount.asInt();
}

References _argi, and _argv.

Referenced by NidsMerge::parseRunstring(), PConfig::parseRunstring(), and DataPrep::parseRunstring().

void NidasApp::startArgs ( int  argc,
const char *const  argv[] 
)
throw (NidasAppException
)

Convenience method to convert the (argc, argv) run string to a list of arguments to pass to startArgs().

Also, if the process name has not been set with setProcessName(), then set it to argv[0].

Derive a path to an XML datasets file according to the current environment settings, searching these paths in order:

  • "$ISFS/projects/$PROJECT/ISFS/config/datasets.xml"
  • "$ISFF/projects/$PROJECT/ISFF/config/datasets.xml"

Parse the derived file and return from it the Dataset with the given name. Throws an exception if the Dataset cannt be loaded.

References nidas::util::Process::expandEnvVars(), nidas::core::Datasets::getDataset(), ILOG, nidas::core::Datasets::parseXML(), nidas::core::Dataset::putenv(), and WLOG.

ArgVector NidasApp::unparsedArgs ( )
std::string NidasApp::usage ( const std::string &  indent = "  ")

Return a usage string describing the arguments accepted by this application, rendering each argument by calling NidasAppArg::usage() with the given indent string.

References _app_arguments, and nidas::core::NidasAppArg::usage().

Referenced by usage(), DmdA2dCk::usage(), nidas::core::DSMServerApp::usage(), StatsProcess::usage(), PConfig::usage(), PacketReader::usage(), nidas::core::DSMEngine::usage(), TeeI2C::usage(), DataPrep::usage(), DataDump::usage(), and DataStats::usage().

std::string nidas::core::NidasApp::xmlHeaderFile ( )
inline

Member Data Documentation

bool nidas::core::NidasApp::_allowUnrecognized
private

Referenced by allowUnrecognized().

nidas_app_arglist_t nidas::core::NidasApp::_app_arguments
private
std::string nidas::core::NidasApp::_appname
private

Referenced by getName().

int nidas::core::NidasApp::_argi
private

Referenced by nextArg(), parseNext(), and startArgs().

ArgVector nidas::core::NidasApp::_argv
private
std::string nidas::core::NidasApp::_argv0
private
std::list<std::string> nidas::core::NidasApp::_dataFileNames
private

Referenced by dataFileNames(), and inputsProvided().

bool nidas::core::NidasApp::_deleteProject
private

Referenced by getProject(), and ~NidasApp().

nidas::util::UTime nidas::core::NidasApp::_endTime
private

Referenced by getEndTime(), and parseNext().

nidas::util::Exception nidas::core::NidasApp::_exception
private

Referenced by getException(), and setException().

gid_t nidas::core::NidasApp::_groupid
private

Referenced by getGroupID(), and parseUsername().

bool nidas::core::NidasApp::_hasException
private

Referenced by hasException(), and setException().

bool nidas::core::NidasApp::_help
private

Referenced by helpRequested(), and parseNext().

std::string nidas::core::NidasApp::_hostname
private

Referenced by getHostName(), and parseNext().

IdFormat nidas::core::NidasApp::_idFormat
private

Referenced by getIdFormat(), parseNext(), and setIdFormat().

nidas::util::LogScheme nidas::core::NidasApp::_logscheme
private

NidasApp keeps track of the LogScheme built up from arguments.

Referenced by parseNext(), setupDaemonLogging(), and setupLogScheme().

int nidas::core::NidasApp::_outputFileLength
private

Referenced by outputFileLength().

std::string nidas::core::NidasApp::_outputFileName
private

Referenced by outputFileName().

bool nidas::core::NidasApp::_processData
private
SampleMatcher nidas::core::NidasApp::_sampleMatcher
private

Referenced by parseNext(), and sampleMatcher().

nidas::util::auto_ptr<nidas::util::SocketAddress> nidas::core::NidasApp::_sockAddr
private

Referenced by inputsProvided(), and socketAddress().

nidas::util::UTime nidas::core::NidasApp::_startTime
private

Referenced by getStartTime(), and parseNext().

uid_t nidas::core::NidasApp::_userid
private

Referenced by getUserID(), and parseUsername().

std::string nidas::core::NidasApp::_username
private

Referenced by getUserName(), and parseUsername().

std::string nidas::core::NidasApp::_xmlFileName
private

Referenced by parseNext(), and xmlHeaderFile().

NidasApp * NidasApp::application_instance = 0
staticprivate
NidasAppArg nidas::core::NidasApp::ConfigsArg
NidasAppArg nidas::core::NidasApp::DatasetName
NidasAppArg nidas::core::NidasApp::DebugDaemon
NidasAppArg nidas::core::NidasApp::EndTime
NidasAppArg nidas::core::NidasApp::FormatHexId
NidasAppArg nidas::core::NidasApp::FormatSampleId
NidasAppArg nidas::core::NidasApp::Help
NidasAppArg nidas::core::NidasApp::Hostname
NidasAppInputFilesArg nidas::core::NidasApp::InputFiles
NidasAppArg nidas::core::NidasApp::LogConfig
NidasAppArg nidas::core::NidasApp::LogFields
NidasAppArg nidas::core::NidasApp::LogParam
NidasAppArg nidas::core::NidasApp::LogShow
NidasAppArg nidas::core::NidasApp::OutputFiles
NidasAppArg nidas::core::NidasApp::PidFile

It is not enough to enable this arg in an app, the app must must call checkPidFile() as well.

Referenced by checkPidFile(), NidasApp(), and nidas::core::DSMEngine::parseRunstring().

NidasAppArg nidas::core::NidasApp::ProcessData
NidasAppArg nidas::core::NidasApp::SampleRanges
NidasAppArg nidas::core::NidasApp::StartTime
NidasAppArg nidas::core::NidasApp::Username
NidasAppArg nidas::core::NidasApp::Version
NidasAppArg nidas::core::NidasApp::XmlHeaderFile

The documentation for this class was generated from the following files: