diff --git a/doc/Pacemaker_Explained/en-US/Ch-Alerts.txt b/doc/Pacemaker_Explained/en-US/Ch-Alerts.txt
index 2e89293f41..7bb8628296 100644
--- a/doc/Pacemaker_Explained/en-US/Ch-Alerts.txt
+++ b/doc/Pacemaker_Explained/en-US/Ch-Alerts.txt
@@ -1,324 +1,327 @@
= Alerts =
////
We prefer [[ch-alerts]], but older versions of asciidoc don't deal well
with that construct for chapter headings
////
anchor:ch-alerts[Chapter 7, Alerts]
indexterm:[Resource,Alerts]
'Alerts' may be configured to take some external action when a cluster event
occurs (node failure, resource starting or stopping, etc.).
== Alert Agents ==
As with resource agents, the cluster calls an external program (an
'alert agent') to handle alerts. The cluster passes information about the event
to the agent via environment variables. Agents can do anything
desired with this information (send an e-mail, log to a file,
update a monitoring system, etc.).
.Simple alert configuration
=====
[source,XML]
-----
-----
=====
In the example above, the cluster will call +my-script.sh+ for each event.
Multiple alert agents may be configured; the cluster will call all of them for
each event.
+Alert agents will be called only on cluster nodes. They will be called for
+events involving Pacemaker Remote nodes, but they will never be called _on_
+those nodes.
== Alert Recipients ==
Each alert may be configured with one or more recipients.
The cluster will call the agent separately for each recipient.
.Alert configuration with recipient
=====
[source,XML]
-----
-----
=====
In the above example, the cluster will call +my-script.sh+ for each event,
passing the recipient +some-address+ as an environment variable.
The recipient may be anything the alert agent can recognize --
an IP address, an e-mail address, a file name, whatever the particular
agent supports.
== Alert Meta-Attributes ==
As with resource agents, meta-attributes can be configured for alert agents
to affect how Pacemaker calls them.
.Meta-Attributes of an Alert
[width="95%",cols="m,1,2
-----
=====
In the above example, the +my-script.sh+ will get called twice for each event,
with each call using a 15-second timeout. One call will be passed the recipient
+someuser@example.com+ and a timestamp in the format +%D %H:%M+, while the
other call will be passed the recipient +otheruser@example.com+ and a timestamp
in the format +%c+.
== Alert Instance Attributes ==
As with resource agents, agent-specific configuration values may be configured
as instance attributes. These will be passed to the agent as additional
environment variables. The number, names and allowed values of these
instance attributes are completely up to the particular agent.
.Alert configuration with instance attributes
=====
[source,XML]
-----
-----
=====
== Using the Sample Alert Agents ==
Pacemaker provides several sample alert agents, installed in
+/usr/share/pacemaker/alerts+ by default.
While these sample scripts may be copied and used as-is, they are provided
mainly as templates to be edited to suit your purposes.
See their source code for the full set of instance attributes they support.
.Sending cluster events as SNMP traps
=====
[source,XML]
-----
-----
=====
.Sending cluster events as e-mails
=====
[source,XML]
-----
-----
=====
== Writing an Alert Agent ==
.Environment variables passed to alert agents
[width="95%",cols="m,2>.
=== Linux Standard Base ===
indexterm:[Resource,LSB]
indexterm:[LSB,Resources]
indexterm:[Linux Standard Base,Resources]
LSB resource agents are those found in +/etc/init.d+.
Generally, they are provided by the OS distribution and, in order to be used
with the cluster, they must conform to the LSB Spec.
footnote:[
See
http://refspecs.linux-foundation.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
for the LSB Spec as it relates to init scripts.
]
[WARNING]
====
Many distributions claim LSB compliance but ship with broken init
scripts. For details on how to check whether your init script is
LSB-compatible, see <>. Common problematic violations of
the LSB standard include:
* Not implementing the status operation at all
* Not observing the correct exit status codes for `start/stop/status` actions
* Starting a started resource returns an error
* Stopping a stopped resource returns an error
====
[IMPORTANT]
====
Remember to make sure the computer is _not_ configured to start any
services at boot time -- that should be controlled by the cluster.
====
=== Systemd ===
indexterm:[Resource,Systemd]
indexterm:[Systemd,Resources]
Some newer distributions have replaced the old
http://en.wikipedia.org/wiki/Init#SysV-style["SysV"] style of
initialization daemons and scripts with an alternative called
http://www.freedesktop.org/wiki/Software/systemd[Systemd].
Pacemaker is able to manage these services _if they are present_.
Instead of init scripts, systemd has 'unit files'. Generally, the
services (unit files) are provided by the OS distribution, but there
are online guides for converting from init scripts.
footnote:[For example,
http://0pointer.de/blog/projects/systemd-for-admins-3.html]
[IMPORTANT]
====
Remember to make sure the computer is _not_ configured to start any
services at boot time -- that should be controlled by the cluster.
====
=== Upstart ===
indexterm:[Resource,Upstart]
indexterm:[Upstart,Resources]
Some newer distributions have replaced the old
http://en.wikipedia.org/wiki/Init#SysV-style["SysV"] style of
initialization daemons (and scripts) with an alternative called
http://upstart.ubuntu.com/[Upstart].
Pacemaker is able to manage these services _if they are present_.
Instead of init scripts, upstart has 'jobs'. Generally, the
services (jobs) are provided by the OS distribution.
[IMPORTANT]
====
Remember to make sure the computer is _not_ configured to start any
services at boot time -- that should be controlled by the cluster.
====
=== System Services ===
indexterm:[Resource,System Services]
indexterm:[System Service,Resources]
Since there are various types of system services (+systemd+,
+upstart+, and +lsb+), Pacemaker supports a special +service+ alias which
intelligently figures out which one applies to a given cluster node.
This is particularly useful when the cluster contains a mix of
+systemd+, +upstart+, and +lsb+.
In order, Pacemaker will try to find the named service as:
. an LSB init script
. a Systemd unit file
. an Upstart job
=== STONITH ===
indexterm:[Resource,STONITH]
indexterm:[STONITH,Resources]
The STONITH class is used exclusively for fencing-related resources. This is
discussed later in <>.
=== Nagios Plugins ===
indexterm:[Resource,Nagios Plugins]
indexterm:[Nagios Plugins,Resources]
Nagios Plugins
footnote:[The project has two independent forks, hosted at
https://www.nagios-plugins.org/ and https://www.monitoring-plugins.org/. Output
from both projects' plugins is similar, so plugins from either project can be
used with pacemaker.]
allow us to monitor services on remote hosts.
Pacemaker is able to do remote monitoring with the plugins _if they are
present_.
A common use case is to configure them as resources belonging to a resource
container (usually a virtual machine), and the container will be restarted
if any of them has failed. Another use is to configure them as ordinary
resources to be used for monitoring hosts or services via the network.
The supported parameters are same as the long options of the plugin.
[[primitive-resource]]
== Resource Properties ==
These values tell the cluster which resource agent to use for the resource,
where to find that resource agent and what standards it conforms to.
.Properties of a Primitive Resource
[width="95%",cols="1m,6<",options="header",align="center"]
|=========================================================
|Field
|Description
|id
|Your name for the resource
indexterm:[id,Resource]
indexterm:[Resource,Property,id]
|class
|The standard the resource agent conforms to. Allowed values:
+lsb+, +nagios+, +ocf+, +service+, +stonith+, +systemd+, +upstart+
indexterm:[class,Resource]
indexterm:[Resource,Property,class]
|type
|The name of the Resource Agent you wish to use. E.g. +IPaddr+ or +Filesystem+
indexterm:[type,Resource]
indexterm:[Resource,Property,type]
|provider
|The OCF spec allows multiple vendors to supply the same
resource agent. To use the OCF resource agents supplied by
the Heartbeat project, you would specify +heartbeat+ here.
indexterm:[provider,Resource]
indexterm:[Resource,Property,provider]
|=========================================================
The XML definition of a resource can be queried with the `crm_resource` tool.
For example:
----
# crm_resource --resource Email --query-xml
----
might produce:
.A system resource definition
=====
[source,XML]
=====
[NOTE]
=====
One of the main drawbacks to system services (LSB, systemd or
Upstart) resources is that they do not allow any parameters!
=====
////
See https://tools.ietf.org/html/rfc5737 for choice of example IP address
////
.An OCF resource definition
=====
[source,XML]
-------
-------
=====
[[s-resource-options]]
== Resource Options ==
Resources have two types of options: 'meta-attributes' and 'instance attributes'.
Meta-attributes apply to any type of resource, while instance attributes
are specific to each resource agent.
=== Resource Meta-Attributes ===
Meta-attributes are used by the cluster to decide how a resource should
behave and can be easily set using the `--meta` option of the
`crm_resource` command.
.Meta-attributes of a Primitive Resource
[width="95%",cols="2m,2,5> resources, they will not be promoted to
- master)
-* +master:+ Allow the resource to be started and, if appropriate, promoted
+* +Stopped:+ Force the resource to be stopped
+* +Started:+ Allow the resource to be started (and in the case of
+ <> resources, promoted to master if
+ appropriate)
+* +Slave:+ Allow the resource to be started, but only in Slave mode if
+ the resource is <>
+* +Master:+ Equivalent to +Started+
indexterm:[target-role,Resource Option]
indexterm:[Resource,Option,target-role]
|is-managed
|TRUE
|Is the cluster allowed to start and stop the resource? Allowed
values: +true+, +false+
indexterm:[is-managed,Resource Option]
indexterm:[Resource,Option,is-managed]
|resource-stickiness
|value of +resource-stickiness+ in the +rsc_defaults+ section
|How much does the resource prefer to stay where it is?
indexterm:[resource-stickiness,Resource Option]
indexterm:[Resource,Option,resource-stickiness]
|requires
|fencing (unless +stonith-enabled+ is +false+ or +class+ is
+stonith+, in which case it defaults to quorum)
|Conditions under which the resource can be started ('Since 1.1.8')
Allowed values:
* +nothing:+ can always be started
* +quorum:+ The cluster can only start this resource if a majority of
the configured nodes are active
* +fencing:+ The cluster can only start this resource if a majority
of the configured nodes are active _and_ any failed or unknown nodes
have been powered off
* +unfencing:+ The cluster can only start this resource if a majority
of the configured nodes are active _and_ any failed or unknown nodes
have been powered off _and_ only on nodes that have been 'unfenced'
indexterm:[requires,Resource Option]
indexterm:[Resource,Option,requires]
|migration-threshold
|INFINITY
|How many failures may occur for this resource on a node, before this
node is marked ineligible to host this resource. A value of 0 indicates that
this feature is disabled (the node will never be marked ineligible); by
constrast, the cluster treats INFINITY (the default) as a very large but
finite number. This option has an effect only if the failed operation has
on-fail=restart (the default), and additionally for failed start operations,
if the cluster property start-failure-is-fatal is false.
indexterm:[migration-threshold,Resource Option]
indexterm:[Resource,Option,migration-threshold]
|failure-timeout
|0
|How many seconds to wait before acting as if the failure had not
occurred, and potentially allowing the resource back to the node on
which it failed. A value of 0 indicates that this feature is disabled.
As with any time-based actions, this is not guaranteed to be checked more
frequently than the value of +cluster-recheck-interval+ (see
<>).
indexterm:[failure-timeout,Resource Option]
indexterm:[Resource,Option,failure-timeout]
|multiple-active
|stop_start
|What should the cluster do if it ever finds the resource active on
more than one node? Allowed values:
* +block:+ mark the resource as unmanaged
* +stop_only:+ stop all active instances and leave them that way
* +stop_start:+ stop all active instances and start the resource in
one location only
indexterm:[multiple-active,Resource Option]
indexterm:[Resource,Option,multiple-active]
|remote-node
|
|The name of the remote-node this resource defines. This both enables the
resource as a remote-node and defines the unique name used to identify the
remote-node. If no other parameters are set, this value will also be assumed as
the hostname to connect to at the port specified by +remote-port+. +WARNING:+
This value cannot overlap with any resource or node IDs. If not specified,
this feature is disabled.
|remote-port
|3121
|Port to use for the guest connection to pacemaker_remote
|remote-addr
|value of +remote-node+
|The IP address or hostname to connect to if remote-node's name is not the
hostname of the guest.
|+remote-connect-timeout+
|60s
|How long before a pending guest connection will time out.
|=========================================================
[NOTE]
====
Support for remote nodes was added in pacemaker 1.1.10. If you are using an
earlier version, options related to remote nodes will not be available.
====
As an example of setting resource options, if you performed the following
commands on an LSB Email resource:
-------
# crm_resource --meta --resource Email --set-parameter priority --parameter-value 100
# crm_resource -m -r Email -p multiple-active -v block
-------
the resulting resource definition might be:
.An LSB resource with cluster options
=====
[source,XML]
-------
-------
=====
[[s-resource-defaults]]
=== Setting Global Defaults for Resource Meta-Attributes ===
To set a default value for a resource option, add it to the
+rsc_defaults+ section with `crm_attribute`. For example,
----
# crm_attribute --type rsc_defaults --name is-managed --update false
----
would prevent the cluster from starting or stopping any of the
resources in the configuration (unless of course the individual
resources were specifically enabled by having their +is-managed+ set to
+true+).
=== Resource Instance Attributes ===
The resource agents of some resource classes (lsb, systemd and upstart 'not' among them)
can be given parameters which determine how they behave and which instance
of a service they control.
If your resource agent supports parameters, you can add them with the
`crm_resource` command. For example,
----
# crm_resource --resource Public-IP --set-parameter ip --parameter-value 192.0.2.2
----
would create an entry in the resource like this:
.An example OCF resource with instance attributes
=====
[source,XML]
-------
-------
=====
For an OCF resource, the result would be an environment variable
called +OCF_RESKEY_ip+ with a value of +192.0.2.2+.
The list of instance attributes supported by an OCF resource agent can be
found by calling the resource agent with the `meta-data` command.
The output contains an XML description of all the supported
attributes, their purpose and default values.
.Displaying the metadata for the Dummy resource agent template
=====
----
# export OCF_ROOT=/usr/lib/ocf
# $OCF_ROOT/resource.d/pacemaker/Dummy meta-data
----
[source,XML]
-------
1.0
This is a Dummy Resource Agent. It does absolutely nothing except
keep track of whether its running or not.
Its purpose in life is for testing and to serve as a template for RA writers.
NB: Please pay attention to the timeouts specified in the actions
section below. They should be meaningful for the kind of resource
the agent manages. They should be the minimum advised timeouts,
but they shouldn't/cannot cover _all_ possible resource
instances. So, try to be neither overly generous nor too stingy,
but moderate. The minimum timeouts should never be below 10 seconds.
Example stateless resource agent
Location to store the resource state in.
State file
Fake attribute that can be changed to cause a reload
Fake attribute that can be changed to cause a reload
Number of seconds to sleep during operations. This can be used to test how
the cluster reacts to operation timeouts.
Operation sleep duration in seconds.
-------
=====
== Resource Operations ==
indexterm:[Resource,Action]
'Operations' are actions the cluster can perform on a resource by calling the
resource agent. Resource agents must support certain common operations such as
start, stop and monitor, and may implement any others.
Some operations are generated by the cluster itself, for example, stopping and
starting resources as needed.
You can configure operations in the cluster configuration. As an example, by
default the cluster will 'not' ensure your resources stay healthy once they are
started. footnote:[Currently, anyway. Automatic monitoring operations may be
added in a future version of Pacemaker.] To instruct the cluster to do this,
you need to add a +monitor+ operation to the resource's definition.
.An OCF resource with a recurring health check
=====
[source,XML]
-------
-------
=====
.Properties of an Operation
[width="95%",cols="2m,3,6>.
indexterm:[interval,Action Property]
indexterm:[Action,Property,interval]
|timeout
|
|How long to wait before declaring the action has failed
indexterm:[timeout,Action Property]
indexterm:[Action,Property,timeout]
|on-fail
|restart '(except for stop operations, which default to' fence 'when
STONITH is enabled and' block 'otherwise)'
|The action to take if this action ever fails. Allowed values:
* +ignore:+ Pretend the resource did not fail.
* +block:+ Don't perform any further operations on the resource.
* +stop:+ Stop the resource and do not start it elsewhere.
* +restart:+ Stop the resource and start it again (possibly on a different node).
* +fence:+ STONITH the node on which the resource failed.
* +standby:+ Move _all_ resources away from the node on which the resource failed.
indexterm:[on-fail,Action Property]
indexterm:[Action,Property,on-fail]
|enabled
|TRUE
|If +false+, ignore this operation definition. This is typically used to pause
a particular recurring monitor operation; for instance, it can complement
the respective resource being unmanaged (+is-managed=false+), as this alone
will <>.
Disabling the operation does not suppress all actions of the given type.
Allowed values: +true+, +false+.
indexterm:[enabled,Action Property]
indexterm:[Action,Property,enabled]
|record-pending
|
|If +true+, the intention to perform the operation is recorded so that
GUIs and CLI tools can indicate that an operation is in progress.
This is best set as an 'operation default' (see next section).
Allowed values: +true+, +false+.
indexterm:[enabled,Action Property]
indexterm:[Action,Property,enabled]
|role
|
|Run the operation only on node(s) that the cluster thinks should be in
the specified role. This only makes sense for recurring monitor operations.
Allowed (case-sensitive) values: +Stopped+, +Started+, and in the
case of <> resources, +Slave+ and +Master+.
indexterm:[role,Action Property]
indexterm:[Action,Property,role]
|=========================================================
[[s-resource-monitoring]]
=== Monitoring Resources for Failure ===
When Pacemaker first starts a resource, it runs one-time monitor operations
(referred to as 'probes') to ensure the resource is running where it's
supposed to be, and not running where it's not supposed to be. (This behavior
can be affected by the +resource-discovery+ location constraint property.)
Other than those initial probes, Pacemaker will not (by default) check that
the resource continues to stay healthy. As in the example above, you must
configure monitor operations explicitly to perform these checks.
By default, a monitor operation will ensure that the resource is running
where it is supposed to. The +target-role+ property can be used for further
checking.
For example, if a resource has one monitor operation with
+interval=10 role=Started+ and a second monitor operation with
+interval=11 role=Stopped+, the cluster will run the first monitor on any nodes
it thinks 'should' be running the resource, and the second monitor on any nodes
that it thinks 'should not' be running the resource (for the truly paranoid,
who want to know when an administrator manually starts a service by mistake).
[[s-monitoring-unmanaged]]
=== Monitoring Resources When Administration is Disabled ===
Recurring monitor operations behave differently under various administrative
settings:
* When a resource is unmanaged (by setting +is-managed=false+): No monitors
will be stopped.
+
If the unmanaged resource is stopped on a node where the cluster thinks it
should be running, the cluster will detect and report that it is not, but it
will not consider the monitor failed, and will not try to start the resource
until it is managed again.
+
Starting the unmanaged resource on a different node is strongly discouraged
and will at least cause the cluster to consider the resource failed, and
may require the resource's +target-role+ to be set to +Stopped+ then +Started+
to be recovered.
* When a node is put into standby: All resources will be moved away from the
node, and all monitor operations will be stopped on the node, except those
with +role=Stopped+. Monitor operations with +role=Stopped+ will be started
on the node if appropriate.
* When the cluster is put into maintenance mode: All resources will be marked
as unmanaged. All monitor operations will be stopped, except those with
+role=Stopped+. As with single unmanaged resources, starting a resource
on a node other than where the cluster expects it to be will cause problems.
[[s-operation-defaults]]
=== Setting Global Defaults for Operations ===
You can change the global default values for operation properties
in a given cluster. These are defined in an +op_defaults+ section
of the CIB's +configuration+ section, and can be set with `crm_attribute`.
For example,
----
# crm_attribute --type op_defaults --name timeout --update 20s
----
would default each operation's +timeout+ to 20 seconds. If an
operation's definition also includes a value for +timeout+, then that
value would be used for that operation instead.
=== When Implicit Operations Take a Long Time ===
The cluster will always perform a number of implicit operations: +start+,
+stop+ and a non-recurring +monitor+ operation used at startup to check
whether the resource is already active. If one of these is taking too long,
then you can create an entry for them and specify a longer timeout.
.An OCF resource with custom timeouts for its implicit actions
=====
[source,XML]
-------
-------
=====
=== Multiple Monitor Operations ===
Provided no two operations (for a single resource) have the same name
and interval, you can have as many monitor operations as you like. In
this way, you can do a superficial health check every minute and
progressively more intense ones at higher intervals.
To tell the resource agent what kind of check to perform, you need to
provide each monitor with a different value for a common parameter.
The OCF standard creates a special parameter called +OCF_CHECK_LEVEL+
for this purpose and dictates that it is "made available to the
resource agent without the normal +OCF_RESKEY+ prefix".
Whatever name you choose, you can specify it by adding an
+instance_attributes+ block to the +op+ tag. It is up to each
resource agent to look for the parameter and decide how to use it.
.An OCF resource with two recurring health checks, performing different levels of checks specified via +OCF_CHECK_LEVEL+.
=====
[source,XML]
-------
-------
=====
=== Disabling a Monitor Operation ===
The easiest way to stop a recurring monitor is to just delete it.
However, there can be times when you only want to disable it
temporarily. In such cases, simply add +enabled="false"+ to the
operation's definition.
.Example of an OCF resource with a disabled health check
=====
[source,XML]
-------
-------
=====
This can be achieved from the command line by executing:
----
# cibadmin --modify --xml-text ''
----
Once you've done whatever you needed to do, you can then re-enable it with
----
# cibadmin --modify --xml-text ''
----
diff --git a/extra/alerts/alert_file.sh.sample b/extra/alerts/alert_file.sh.sample
index a6a4913c78..3735dd31de 100644
--- a/extra/alerts/alert_file.sh.sample
+++ b/extra/alerts/alert_file.sh.sample
@@ -1,102 +1,102 @@
#!/bin/bash
#
# Copyright (C) 2015 Andrew Beekhof
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
##############################################################################
# Sample configuration (cib fragment in xml notation)
# ================================
#
#
#
#
#
#
#
#
#
#
#
#
#
if [ -z $CRM_alert_version ]; then
echo "Pacemaker version 1.1.15 or later is required" >> "${CRM_alert_recipient}"
exit 0
fi
debug_exec_order_default="false"
# Pacemaker passes instance attributes to alert agents as environment variables.
# It is completely up to the agent what instance attributes to support.
# Here, we define an instance attribute "debug_exec_order".
: ${debug_exec_order=${debug_exec_order_default}}
-if [ "${debug_exec_order}" = "true" ]
+if [ "${debug_exec_order}" = "true" ]; then
tstamp=`printf "%04d. " "$CRM_alert_node_sequence"`
if [ ! -z $CRM_alert_timestamp ]; then
tstamp="${tstamp} $CRM_alert_timestamp (`date "+%H:%M:%S.%06N"`): "
fi
else
if [ ! -z $CRM_alert_timestamp ]; then
tstamp="$CRM_alert_timestamp: "
fi
fi
case $CRM_alert_kind in
node)
echo "${tstamp}Node '${CRM_alert_node}' is now '${CRM_alert_desc}'" >> "${CRM_alert_recipient}"
;;
fencing)
# Other keys:
#
# CRM_alert_node
# CRM_alert_task
# CRM_alert_rc
#
echo "${tstamp}Fencing ${CRM_alert_desc}" >> "${CRM_alert_recipient}"
;;
resource)
# Other keys:
#
# CRM_alert_target_rc
# CRM_alert_status
# CRM_alert_rc
#
if [ ${CRM_alert_interval} = "0" ]; then
CRM_alert_interval=""
else
CRM_alert_interval=" (${CRM_alert_interval})"
fi
if [ ${CRM_alert_target_rc} = "0" ]; then
CRM_alert_target_rc=""
else
CRM_alert_target_rc=" (target: ${CRM_alert_target_rc})"
fi
case ${CRM_alert_desc} in
Cancelled) ;;
*)
echo "${tstamp}Resource operation '${CRM_alert_task}${CRM_alert_interval}' for '${CRM_alert_rsc}' on '${CRM_alert_node}': ${CRM_alert_desc}${CRM_alert_target_rc}" >> "${CRM_alert_recipient}"
;;
esac
;;
*)
echo "${tstamp}Unhandled $CRM_alert_kind alert" >> "${CRM_alert_recipient}"
env | grep CRM_alert >> "${CRM_alert_recipient}"
;;
esac
diff --git a/lib/common/iso8601.c b/lib/common/iso8601.c
index d0be0cfc73..47f863ed31 100644
--- a/lib/common/iso8601.c
+++ b/lib/common/iso8601.c
@@ -1,1279 +1,1283 @@
/*
* Copyright (C) 2005 Andrew Beekhof
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* Primary reference:
* http://en.wikipedia.org/wiki/ISO_8601 (as at 2005-08-01)
*
* Secondary references:
* http://hydracen.com/dx/iso8601.htm
* http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt
* http://www.personal.ecu.edu/mccartyr/isowdcal.html
* http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
*
*/
#include
#include
#include
#include
#include
/*
* Andrew's code was originally written for OSes whose "struct tm" contains:
* long tm_gmtoff; :: Seconds east of UTC
* const char *tm_zone; :: Timezone abbreviation
* Some OSes lack these, instead having:
* time_t (or long) timezone;
:: "difference between UTC and local standard time"
* char *tzname[2] = { "...", "..." };
* I (David Lee) confess to not understanding the details. So my attempted
* generalisations for where their use is necessary may be flawed.
*
* 1. Does "difference between ..." subtract the same or opposite way?
* 2. Should it use "altzone" instead of "timezone"?
* 3. Should it use tzname[0] or tzname[1]? Interaction with timezone/altzone?
*/
#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
# define GMTOFF(tm) ((tm)->tm_gmtoff)
#else
/* Note: extern variable; macro argument not actually used. */
# define GMTOFF(tm) (-timezone+daylight)
#endif
struct crm_time_s {
int years;
int months; /* Only for durations */
int days;
int seconds;
int offset; /* Seconds */
bool duration;
};
char *crm_time_as_string(crm_time_t * date_time, int flags);
crm_time_t *parse_date(const char *date_str);
gboolean check_for_ordinal(const char *str);
static crm_time_t *
crm_get_utc_time(crm_time_t * dt)
{
crm_time_t *utc = calloc(1, sizeof(crm_time_t));
utc->years = dt->years;
utc->days = dt->days;
utc->seconds = dt->seconds;
utc->offset = 0;
if (dt->offset) {
crm_time_add_seconds(utc, -dt->offset);
} else {
/* Durations (which are the only things that can include months, never have a timezone */
utc->months = dt->months;
}
crm_time_log(LOG_TRACE, "utc-source", dt,
crm_time_log_date | crm_time_log_timeofday | crm_time_log_with_timezone);
crm_time_log(LOG_TRACE, "utc-target", utc,
crm_time_log_date | crm_time_log_timeofday | crm_time_log_with_timezone);
return utc;
}
crm_time_t *
crm_time_new(const char *date_time)
{
time_t tm_now;
crm_time_t *dt = NULL;
tzset();
if (date_time == NULL) {
tm_now = time(NULL);
dt = calloc(1, sizeof(crm_time_t));
crm_time_set_timet(dt, &tm_now);
} else {
dt = parse_date(date_time);
}
return dt;
}
void
crm_time_free(crm_time_t * dt)
{
if (dt == NULL) {
return;
}
free(dt);
}
static int
year_days(int year)
{
int d = 365;
if (crm_time_leapyear(year)) {
d++;
}
return d;
}
/* http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt
*
* 5. Find the Jan1Weekday for Y (Monday=1, Sunday=7)
* YY = (Y-1) % 100
* C = (Y-1) - YY
* G = YY + YY/4
* Jan1Weekday = 1 + (((((C / 100) % 4) x 5) + G) % 7)
*/
int
crm_time_january1_weekday(int year)
{
int YY = (year - 1) % 100;
int C = (year - 1) - YY;
int G = YY + YY / 4;
int jan1 = 1 + (((((C / 100) % 4) * 5) + G) % 7);
crm_trace("YY=%d, C=%d, G=%d", YY, C, G);
crm_trace("January 1 %.4d: %d", year, jan1);
return jan1;
}
int
crm_time_weeks_in_year(int year)
{
int weeks = 52;
int jan1 = crm_time_january1_weekday(year);
/* if jan1 == thursday */
if (jan1 == 4) {
weeks++;
} else {
jan1 = crm_time_january1_weekday(year + 1);
/* if dec31 == thursday aka. jan1 of next year is a friday */
if (jan1 == 5) {
weeks++;
}
}
return weeks;
}
int month_days[14] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 29 };
int
crm_time_days_in_month(int month, int year)
{
if (month == 2 && crm_time_leapyear(year)) {
month = 13;
}
return month_days[month];
}
bool
crm_time_leapyear(int year)
{
gboolean is_leap = FALSE;
if (year % 4 == 0) {
is_leap = TRUE;
}
if (year % 100 == 0 && year % 400 != 0) {
is_leap = FALSE;
}
return is_leap;
}
static uint32_t
get_ordinal_days(uint32_t y, uint32_t m, uint32_t d)
{
int lpc;
for (lpc = 1; lpc < m; lpc++) {
d += crm_time_days_in_month(lpc, y);
}
return d;
}
void
crm_time_log_alias(int log_level, const char *file, const char *function, int line,
const char *prefix, crm_time_t * date_time, int flags)
{
char *date_s = crm_time_as_string(date_time, flags);
if (log_level < LOG_CRIT) {
printf("%s%s%s\n",
prefix ? prefix : "", prefix ? ": " : "", date_s ? date_s : "__invalid_date__");
} else {
do_crm_log_alias(log_level, file, function, line, "%s%s%s",
prefix ? prefix : "", prefix ? ": " : "",
date_s ? date_s : "__invalid_date__");
}
free(date_s);
}
static int
crm_time_get_sec(int sec, uint * h, uint * m, uint * s)
{
uint hours, minutes, seconds;
if (sec < 0) {
seconds = 0 - sec;
} else {
seconds = sec;
}
hours = seconds / (60 * 60);
seconds -= 60 * 60 * hours;
minutes = seconds / (60);
seconds -= 60 * minutes;
crm_trace("%d == %.2d:%.2d:%.2d", sec, hours, minutes, seconds);
*h = hours;
*m = minutes;
*s = seconds;
return TRUE;
}
int
crm_time_get_timeofday(crm_time_t * dt, uint * h, uint * m, uint * s)
{
return crm_time_get_sec(dt->seconds, h, m, s);
}
int
crm_time_get_timezone(crm_time_t * dt, uint * h, uint * m)
{
uint s;
return crm_time_get_sec(dt->seconds, h, m, &s);
}
long long
crm_time_get_seconds(crm_time_t * dt)
{
int lpc;
crm_time_t *utc = NULL;
long long in_seconds = 0;
utc = crm_get_utc_time(dt);
for (lpc = 1; lpc < utc->years; lpc++) {
int dmax = year_days(lpc);
in_seconds += 60 * 60 * 24 * dmax;
}
/* utc->months is an offset that can only be set for a duration
* By definiton, the value is variable depending on the date to
* which it is applied
*
* Force 30-day months so that something vaguely sane happens
* for anyone that tries to use a month in this way
*/
if (utc->months > 0) {
in_seconds += 60 * 60 * 24 * 30 * utc->months;
}
if (utc->days > 0) {
in_seconds += 60 * 60 * 24 * (utc->days - 1);
}
in_seconds += utc->seconds;
crm_time_free(utc);
return in_seconds;
}
#define EPOCH_SECONDS 62135596800ULL /* Calculated using crm_time_get_seconds() */
long long
crm_time_get_seconds_since_epoch(crm_time_t * dt)
{
return crm_time_get_seconds(dt) - EPOCH_SECONDS;
}
int
crm_time_get_gregorian(crm_time_t * dt, uint * y, uint * m, uint * d)
{
int months = 0;
int days = dt->days;
if(dt->years != 0) {
for (months = 1; months <= 12 && days > 0; months++) {
int mdays = crm_time_days_in_month(months, dt->years);
if (mdays >= days) {
break;
} else {
days -= mdays;
}
}
} else if (dt->months) {
/* This is a duration including months, don't convert the days field */
months = dt->months;
} else {
/* This is a duration not including months, still don't convert the days field */
}
*y = dt->years;
*m = months;
*d = days;
crm_trace("%.4d-%.3d -> %.4d-%.2d-%.2d", dt->years, dt->days, dt->years, months, days);
return TRUE;
}
int
crm_time_get_ordinal(crm_time_t * dt, uint * y, uint * d)
{
*y = dt->years;
*d = dt->days;
return TRUE;
}
int
crm_time_get_isoweek(crm_time_t * dt, uint * y, uint * w, uint * d)
{
/*
* Monday 29 December 2008 is written "2009-W01-1"
* Sunday 3 January 2010 is written "2009-W53-7"
*/
int year_num = 0;
int jan1 = crm_time_january1_weekday(dt->years);
int h = -1;
CRM_CHECK(dt->days > 0, return FALSE);
/* 6. Find the Weekday for Y M D */
h = dt->days + jan1 - 1;
*d = 1 + ((h - 1) % 7);
/* 7. Find if Y M D falls in YearNumber Y-1, WeekNumber 52 or 53 */
if (dt->days <= (8 - jan1) && jan1 > 4) {
crm_trace("year--, jan1=%d", jan1);
year_num = dt->years - 1;
*w = crm_time_weeks_in_year(year_num);
} else {
year_num = dt->years;
}
/* 8. Find if Y M D falls in YearNumber Y+1, WeekNumber 1 */
if (year_num == dt->years) {
int dmax = year_days(year_num);
int correction = 4 - *d;
if ((dmax - dt->days) < correction) {
crm_trace("year++, jan1=%d, i=%d vs. %d", jan1, dmax - dt->days, correction);
year_num = dt->years + 1;
*w = 1;
}
}
/* 9. Find if Y M D falls in YearNumber Y, WeekNumber 1 through 53 */
if (year_num == dt->years) {
int j = dt->days + (7 - *d) + (jan1 - 1);
*w = j / 7;
if (jan1 > 4) {
*w -= 1;
}
}
*y = year_num;
crm_trace("Converted %.4d-%.3d to %.4d-W%.2d-%d", dt->years, dt->days, *y, *w, *d);
return TRUE;
}
char *
crm_time_as_string(crm_time_t * date_time, int flags)
{
char *date_s = NULL;
char *time_s = NULL;
char *offset_s = NULL;
char *result_s = NULL;
crm_time_t *dt = NULL;
crm_time_t *utc = NULL;
if (date_time == NULL) {
return strdup("");
} else if (date_time->offset && (flags & crm_time_log_with_timezone) == 0) {
crm_trace("UTC conversion");
utc = crm_get_utc_time(date_time);
dt = utc;
} else {
dt = date_time;
}
CRM_CHECK(dt != NULL, return NULL);
if (flags & crm_time_log_duration) {
uint h = 0, m = 0, s = 0;
int offset = 0, max = 128;
date_s = calloc(1, max+1);
crm_time_get_sec(dt->seconds, &h, &m, &s);
if (date_s == NULL) {
goto done;
}
if(dt->years) {
offset += snprintf(date_s+offset, max-offset, "%4d year%s ", dt->years, dt->years>1?"s":"");
}
if(dt->months) {
offset += snprintf(date_s+offset, max-offset, "%2d month%s ", dt->months, dt->months>1?"s":"");
}
if(dt->days) {
offset += snprintf(date_s+offset, max-offset, "%2d day%s ", dt->days, dt->days>1?"s":"");
}
if(dt->seconds) {
offset += snprintf(date_s+offset, max-offset, "%d seconds ( ", dt->seconds);
if(h) {
offset += snprintf(date_s+offset, max-offset, "%d hour%s ", h, h>1?"s":"");
}
if(m) {
offset += snprintf(date_s+offset, max-offset, "%d minute%s ", m, m>1?"s":"");
}
if(s) {
offset += snprintf(date_s+offset, max-offset, "%d second%s ", s, s>1?"s":"");
}
offset += snprintf(date_s+offset, max-offset, ")");
}
goto done;
}
if (flags & crm_time_log_date) {
date_s = calloc(1, 32);
if (date_s == NULL) {
goto done;
} else if (flags & crm_time_seconds) {
unsigned long long s = crm_time_get_seconds(date_time);
snprintf(date_s, 31, "%lld", s); /* Durations may not be +ve */
goto done;
} else if (flags & crm_time_epoch) {
unsigned long long s = crm_time_get_seconds_since_epoch(date_time);
snprintf(date_s, 31, "%lld", s); /* Durations may not be +ve */
goto done;
} else if (flags & crm_time_weeks) {
/* YYYY-Www-D */
uint y, w, d;
if (crm_time_get_isoweek(dt, &y, &w, &d)) {
snprintf(date_s, 31, "%d-W%.2d-%d", y, w, d);
}
} else if (flags & crm_time_ordinal) {
/* YYYY-DDD */
uint y, d;
if (crm_time_get_ordinal(dt, &y, &d)) {
snprintf(date_s, 31, "%d-%.3d", y, d);
}
} else {
/* YYYY-MM-DD */
uint y, m, d;
if (crm_time_get_gregorian(dt, &y, &m, &d)) {
snprintf(date_s, 31, "%.4d-%.2d-%.2d", y, m, d);
}
}
}
if (flags & crm_time_log_timeofday) {
uint h, m, s;
time_s = calloc(1, 32);
if (time_s == NULL) {
goto cleanup;
}
if (crm_time_get_timeofday(dt, &h, &m, &s)) {
snprintf(time_s, 31, "%.2d:%.2d:%.2d", h, m, s);
}
if (dt->offset != 0) {
crm_time_get_sec(dt->offset, &h, &m, &s);
}
offset_s = calloc(1, 32);
if ((flags & crm_time_log_with_timezone) == 0 || dt->offset == 0) {
crm_trace("flags %6x %6x", flags, crm_time_log_with_timezone);
snprintf(offset_s, 31, "Z");
} else {
snprintf(offset_s, 31, " %c%.2d:%.2d", dt->offset < 0 ? '-' : '+', h, m);
}
}
done:
result_s = calloc(1, 100);
snprintf(result_s, 100, "%s%s%s%s",
date_s ? date_s : "", (date_s != NULL && time_s != NULL) ? " " : "",
time_s ? time_s : "", offset_s ? offset_s : "");
cleanup:
free(date_s);
free(time_s);
free(offset_s);
crm_time_free(utc);
return result_s;
}
static int
crm_time_parse_sec(const char *time_str)
{
int rc;
uint hour = 0;
uint minute = 0;
uint second = 0;
rc = sscanf(time_str, "%d:%d:%d", &hour, &minute, &second);
if (rc == 1) {
rc = sscanf(time_str, "%2d%2d%2d", &hour, &minute, &second);
}
if (rc > 0 && rc < 4) {
crm_trace("Got valid time: %.2d:%.2d:%.2d", hour, minute, second);
if (hour >= 24) {
crm_err("Invalid hour: %d", hour);
} else if (minute >= 60) {
crm_err("Invalid minute: %d", minute);
} else if (second >= 60) {
crm_err("Invalid second: %d", second);
} else {
second += (minute * 60);
second += (hour * 60 * 60);
}
} else {
crm_err("Bad time: %s (%d)", time_str, rc);
}
return second;
}
static int
crm_time_parse_offset(const char *offset_str)
{
int offset = 0;
tzset();
if (offset_str == NULL) {
#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
time_t now = time(NULL);
struct tm *now_tm = localtime(&now);
#endif
int h_offset = GMTOFF(now_tm) / (3600);
int m_offset = (GMTOFF(now_tm) - (3600 * h_offset)) / (60);
if (h_offset < 0 && m_offset < 0) {
m_offset = 0 - m_offset;
}
offset += (60 * 60 * h_offset);
offset += (60 * m_offset);
} else if (offset_str[0] == 'Z') {
} else if (offset_str[0] == '+' || offset_str[0] == '-' || isdigit((int)offset_str[0])) {
gboolean negate = FALSE;
if (offset_str[0] == '-') {
negate = TRUE;
offset_str++;
}
offset = crm_time_parse_sec(offset_str);
if (negate) {
offset = 0 - offset;
}
}
return offset;
}
static crm_time_t *
crm_time_parse(const char *time_str, crm_time_t * a_time)
{
uint h, m, s;
char *offset_s = NULL;
crm_time_t *dt = a_time;
tzset();
if (a_time == NULL) {
dt = calloc(1, sizeof(crm_time_t));
}
if (time_str) {
dt->seconds = crm_time_parse_sec(time_str);
offset_s = strstr(time_str, "Z");
if (offset_s == NULL) {
offset_s = strstr(time_str, " ");
}
}
if (offset_s) {
while (isspace(offset_s[0])) {
offset_s++;
}
}
dt->offset = crm_time_parse_offset(offset_s);
crm_time_get_sec(dt->offset, &h, &m, &s);
crm_trace("Got tz: %c%2.d:%.2d", dt->offset < 0 ? '-' : '+', h, m);
return dt;
}
crm_time_t *
parse_date(const char *date_str)
{
char *time_s;
crm_time_t *dt = NULL;
int year = 0;
int month = 0;
int week = 0;
int day = 0;
int rc = 0;
CRM_CHECK(date_str != NULL, return NULL);
CRM_CHECK(strlen(date_str) > 0, return NULL);
if (date_str[0] == 'T' || date_str[2] == ':') {
/* Just a time supplied - Infer current date */
dt = crm_time_new(NULL);
dt = crm_time_parse(date_str, dt);
goto done;
} else {
dt = calloc(1, sizeof(crm_time_t));
}
if (safe_str_eq("epoch", date_str)) {
dt->days = 1;
dt->years = 1970;
crm_time_log(LOG_TRACE, "Unpacked", dt, crm_time_log_date | crm_time_log_timeofday);
return dt;
}
/* YYYY-MM-DD */
rc = sscanf(date_str, "%d-%d-%d", &year, &month, &day);
if (rc == 1) {
/* YYYYMMDD */
rc = sscanf(date_str, "%4d%2d%2d", &year, &month, &day);
}
if (rc == 3) {
if (month > 12) {
crm_err("Invalid month: %d", month);
} else if (day > 31) {
crm_err("Invalid day: %d", day);
} else {
dt->years = year;
dt->days = get_ordinal_days(year, month, day);
crm_trace("Got gergorian date: %.4d-%.3d", year, dt->days);
}
goto done;
}
/* YYYY-DDD */
rc = sscanf(date_str, "%d-%d", &year, &day);
if (rc == 2) {
crm_trace("Got ordinal date");
if (day > year_days(year)) {
crm_err("Invalid day: %d (max=%d)", day, year_days(year));
} else {
dt->days = day;
dt->years = year;
}
goto done;
}
/* YYYY-Www-D */
rc = sscanf(date_str, "%d-W%d-%d", &year, &week, &day);
if (rc == 3) {
crm_trace("Got week date");
if (week > crm_time_weeks_in_year(year)) {
crm_err("Invalid week: %d (max=%d)", week, crm_time_weeks_in_year(year));
} else if (day < 1 || day > 7) {
crm_err("Invalid day: %d", day);
} else {
/*
* http://en.wikipedia.org/wiki/ISO_week_date
*
* Monday 29 December 2008 is written "2009-W01-1"
* Sunday 3 January 2010 is written "2009-W53-7"
*
* Saturday 27 September 2008 is written "2008-W37-6"
*
* http://en.wikipedia.org/wiki/ISO_week_date
* If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in week 01.
* If 1 January is on a Friday, Saturday or Sunday, it is in week 52 or 53 of the previous year.
*/
int jan1 = crm_time_january1_weekday(year);
crm_trace("Jan 1 = %d", jan1);
dt->years = year;
crm_time_add_days(dt, (week - 1) * 7);
if (jan1 <= 4) {
crm_time_add_days(dt, 1 - jan1);
} else {
crm_time_add_days(dt, 8 - jan1);
}
crm_time_add_days(dt, day);
}
goto done;
}
crm_err("Couldn't parse %s", date_str);
done:
time_s = strstr(date_str, " ");
if (time_s == NULL) {
time_s = strstr(date_str, "T");
}
if (dt && time_s) {
time_s++;
crm_time_parse(time_s, dt);
}
crm_time_log(LOG_TRACE, "Unpacked", dt, crm_time_log_date | crm_time_log_timeofday);
CRM_CHECK(crm_time_check(dt), return NULL);
return dt;
}
static int
parse_int(const char *str, int field_width, int uppper_bound, int *result)
{
int lpc = 0;
int offset = 0;
int intermediate = 0;
gboolean fraction = FALSE;
gboolean negate = FALSE;
CRM_CHECK(str != NULL, return FALSE);
CRM_CHECK(result != NULL, return FALSE);
*result = 0;
if (strlen(str) <= 0) {
return FALSE;
}
if (str[offset] == 'T') {
offset++;
}
if (str[offset] == '.' || str[offset] == ',') {
fraction = TRUE;
field_width = -1;
offset++;
} else if (str[offset] == '-') {
negate = TRUE;
offset++;
} else if (str[offset] == '+' || str[offset] == ':') {
offset++;
}
for (; (fraction || lpc < field_width) && isdigit((int)str[offset]); lpc++) {
if (fraction) {
intermediate = (str[offset] - '0') / (10 ^ lpc);
} else {
*result *= 10;
intermediate = str[offset] - '0';
}
*result += intermediate;
offset++;
}
if (fraction) {
*result = (int)(*result * uppper_bound);
} else if (uppper_bound > 0 && *result > uppper_bound) {
*result = uppper_bound;
}
if (negate) {
*result = 0 - *result;
}
if (lpc > 0) {
crm_trace("Found int: %d. Stopped at str[%d]='%c'", *result, lpc, str[lpc]);
return offset;
}
return 0;
}
crm_time_t *
crm_time_parse_duration(const char *interval_str)
{
gboolean is_time = FALSE;
crm_time_t *diff = NULL;
CRM_CHECK(interval_str != NULL, goto bail);
CRM_CHECK(strlen(interval_str) > 0, goto bail);
CRM_CHECK(interval_str[0] == 'P', goto bail);
interval_str++;
diff = calloc(1, sizeof(crm_time_t));
while (isspace((int)interval_str[0]) == FALSE) {
int an_int = 0, rc;
char ch = 0;
if (interval_str[0] == 'T') {
is_time = TRUE;
interval_str++;
}
rc = parse_int(interval_str, 10, 0, &an_int);
if (rc == 0) {
break;
}
interval_str += rc;
ch = interval_str[0];
interval_str++;
crm_trace("Testing %c=%d, rc=%d", ch, an_int, rc);
switch (ch) {
case 0:
return diff;
break;
case 'Y':
diff->years = an_int;
break;
case 'M':
if (is_time) {
/* Minutes */
diff->seconds += an_int * 60;
} else {
diff->months = an_int;
}
break;
case 'W':
diff->days += an_int * 7;
break;
case 'D':
diff->days += an_int;
break;
case 'H':
diff->seconds += an_int * 60 * 60;
break;
case 'S':
diff->seconds += an_int;
break;
default:
goto bail;
break;
}
}
return diff;
bail:
free(diff);
return NULL;
}
crm_time_period_t *
crm_time_parse_period(const char *period_str)
{
gboolean invalid = FALSE;
const char *original = period_str;
crm_time_period_t *period = NULL;
CRM_CHECK(period_str != NULL, return NULL);
CRM_CHECK(strlen(period_str) > 0, return NULL);
tzset();
period = calloc(1, sizeof(crm_time_period_t));
if (period_str[0] == 'P') {
period->diff = crm_time_parse_duration(period_str);
} else {
period->start = parse_date(period_str);
}
period_str = strstr(original, "/");
if (period_str) {
CRM_CHECK(period_str[0] == '/', invalid = TRUE;
goto bail);
period_str++;
if (period_str[0] == 'P') {
period->diff = crm_time_parse_duration(period_str);
} else {
period->end = parse_date(period_str);
}
} else if (period->diff != NULL) {
/* just aduration starting from now */
period->start = crm_time_new(NULL);
} else {
invalid = TRUE;
CRM_CHECK(period_str != NULL, goto bail);
}
/* sanity checks */
if (period->start == NULL && period->end == NULL) {
crm_err("Invalid time period: %s", original);
invalid = TRUE;
} else if (period->start == NULL && period->diff == NULL) {
crm_err("Invalid time period: %s", original);
invalid = TRUE;
} else if (period->end == NULL && period->diff == NULL) {
crm_err("Invalid time period: %s", original);
invalid = TRUE;
}
bail:
if (invalid) {
free(period->start);
free(period->end);
free(period->diff);
free(period);
return NULL;
}
if (period->end == NULL && period->diff == NULL) {
}
if (period->start == NULL) {
period->start = crm_time_subtract(period->end, period->diff);
} else if (period->end == NULL) {
period->end = crm_time_add(period->start, period->diff);
}
crm_time_check(period->start);
crm_time_check(period->end);
return period;
}
void
crm_time_set(crm_time_t * target, crm_time_t * source)
{
crm_trace("target=%p, source=%p", target, source);
CRM_CHECK(target != NULL && source != NULL, return);
target->years = source->years;
target->days = source->days;
target->months = source->months; /* Only for durations */
target->seconds = source->seconds;
target->offset = source->offset;
crm_time_log(LOG_TRACE, "source", source,
crm_time_log_date | crm_time_log_timeofday | crm_time_log_with_timezone);
crm_time_log(LOG_TRACE, "target", target,
crm_time_log_date | crm_time_log_timeofday | crm_time_log_with_timezone);
}
static void
ha_set_tm_time(crm_time_t * target, struct tm *source)
{
int h_offset = 0;
int m_offset = 0;
+ /* Ensure target is fully initialized */
+ target->years = 0;
+ target->months = 0;
+ target->days = 0;
+ target->seconds = 0;
+ target->offset = 0;
target->duration = FALSE;
if (source->tm_year > 0) {
/* years since 1900 */
target->years = 1900 + source->tm_year;
}
if (source->tm_yday >= 0) {
/* days since January 1 [0-365] */
target->days = 1 + source->tm_yday;
}
- target->seconds = 0;
if (source->tm_hour >= 0) {
target->seconds += 60 * 60 * source->tm_hour;
}
if (source->tm_min >= 0) {
target->seconds += 60 * source->tm_min;
}
if (source->tm_sec >= 0) {
target->seconds += source->tm_sec;
}
/* tm_gmtoff == offset from UTC in seconds */
h_offset = GMTOFF(source) / (3600);
m_offset = (GMTOFF(source) - (3600 * h_offset)) / (60);
crm_trace("Offset (s): %ld, offset (hh:mm): %.2d:%.2d", GMTOFF(source), h_offset, m_offset);
- target->offset = 0;
target->offset += 60 * 60 * h_offset;
target->offset += 60 * m_offset;
}
void
crm_time_set_timet(crm_time_t * target, time_t * source)
{
ha_set_tm_time(target, localtime(source));
}
crm_time_t *
crm_time_add(crm_time_t * dt, crm_time_t * value)
{
crm_time_t *utc = NULL;
crm_time_t *answer = NULL;
CRM_CHECK(dt != NULL && value != NULL, return NULL);
answer = calloc(1, sizeof(crm_time_t));
crm_time_set(answer, dt);
utc = crm_get_utc_time(value);
answer->years += utc->years;
crm_time_add_months(answer, utc->months);
crm_time_add_days(answer, utc->days);
crm_time_add_seconds(answer, utc->seconds);
crm_time_free(utc);
return answer;
}
crm_time_t *
crm_time_calculate_duration(crm_time_t * dt, crm_time_t * value)
{
crm_time_t *utc = NULL;
crm_time_t *answer = NULL;
CRM_CHECK(dt != NULL && value != NULL, return NULL);
utc = crm_get_utc_time(value);
answer = crm_get_utc_time(dt);
answer->duration = TRUE;
answer->years -= utc->years;
if(utc->months != 0) {
crm_time_add_months(answer, -utc->months);
}
crm_time_add_days(answer, -utc->days);
crm_time_add_seconds(answer, -utc->seconds);
crm_time_free(utc);
return answer;
}
crm_time_t *
crm_time_subtract(crm_time_t * dt, crm_time_t * value)
{
crm_time_t *utc = NULL;
crm_time_t *answer = NULL;
CRM_CHECK(dt != NULL && value != NULL, return NULL);
answer = calloc(1, sizeof(crm_time_t));
crm_time_set(answer, dt);
utc = crm_get_utc_time(value);
answer->years -= utc->years;
if(utc->months != 0) {
crm_time_add_months(answer, -utc->months);
}
crm_time_add_days(answer, -utc->days);
crm_time_add_seconds(answer, -utc->seconds);
return answer;
}
bool
crm_time_check(crm_time_t * dt)
{
int ydays = 0;
CRM_CHECK(dt != NULL, return FALSE);
ydays = year_days(dt->years);
crm_trace("max ydays: %d", ydays);
CRM_CHECK(dt->days > 0, return FALSE);
CRM_CHECK(dt->days <= ydays, return FALSE);
CRM_CHECK(dt->seconds >= 0, return FALSE);
CRM_CHECK(dt->seconds < 24 * 60 * 60, return FALSE);
return TRUE;
}
#define do_cmp_field(l, r, field) \
if(rc == 0) { \
if(l->field > r->field) { \
crm_trace("%s: %d > %d", \
#field, l->field, r->field); \
rc = 1; \
} else if(l->field < r->field) { \
crm_trace("%s: %d < %d", \
#field, l->field, r->field); \
rc = -1; \
} \
}
int
crm_time_compare(crm_time_t * a, crm_time_t * b)
{
int rc = 0;
crm_time_t *t1 = NULL;
crm_time_t *t2 = NULL;
if (a == NULL && b == NULL) {
return 0;
} else if (a == NULL) {
return -1;
} else if (b == NULL) {
return 1;
}
t1 = crm_get_utc_time(a);
t2 = crm_get_utc_time(b);
do_cmp_field(t1, t2, years);
do_cmp_field(t1, t2, days);
do_cmp_field(t1, t2, seconds);
crm_time_free(t1);
crm_time_free(t2);
return rc;
}
void
crm_time_add_seconds(crm_time_t * a_time, int extra)
{
int days = 0;
int seconds = 24 * 60 * 60;
crm_trace("Adding %d seconds to %d (max=%d)", extra, a_time->seconds, seconds);
a_time->seconds += extra;
while (a_time->seconds >= seconds) {
a_time->seconds -= seconds;
days++;
}
while (a_time->seconds < 0) {
a_time->seconds += seconds;
days--;
}
crm_time_add_days(a_time, days);
}
void
crm_time_add_days(crm_time_t * a_time, int extra)
{
int lower_bound = 1;
int ydays = crm_time_leapyear(a_time->years) ? 366 : 365;
crm_trace("Adding %d days to %.4d-%.3d", extra, a_time->years, a_time->days);
a_time->days += extra;
while (a_time->days > ydays) {
a_time->years++;
a_time->days -= ydays;
ydays = crm_time_leapyear(a_time->years) ? 366 : 365;
}
if(a_time->duration) {
lower_bound = 0;
}
while (a_time->days < lower_bound) {
a_time->years--;
a_time->days += crm_time_leapyear(a_time->years) ? 366 : 365;
}
}
void
crm_time_add_months(crm_time_t * a_time, int extra)
{
int lpc;
uint32_t y, m, d, dmax;
crm_time_get_gregorian(a_time, &y, &m, &d);
crm_trace("Adding %d months to %.4d-%.2d-%.2d", extra, y, m, d);
if (extra > 0) {
for (lpc = extra; lpc > 0; lpc--) {
m++;
if (m == 13) {
m = 1;
y++;
}
}
} else {
for (lpc = -extra; lpc > 0; lpc--) {
m--;
if (m == 0) {
m = 12;
y--;
}
}
}
dmax = crm_time_days_in_month(m, y);
if (dmax < d) {
/* Preserve day-of-month unless the month doesn't have enough days */
d = dmax;
}
crm_trace("Calculated %.4d-%.2d-%.2d", y, m, d);
a_time->years = y;
a_time->days = get_ordinal_days(y, m, d);
crm_time_get_gregorian(a_time, &y, &m, &d);
crm_trace("Got %.4d-%.2d-%.2d", y, m, d);
}
void
crm_time_add_minutes(crm_time_t * a_time, int extra)
{
crm_time_add_seconds(a_time, extra * 60);
}
void
crm_time_add_hours(crm_time_t * a_time, int extra)
{
crm_time_add_seconds(a_time, extra * 60 * 60);
}
void
crm_time_add_weeks(crm_time_t * a_time, int extra)
{
crm_time_add_days(a_time, extra * 7);
}
void
crm_time_add_years(crm_time_t * a_time, int extra)
{
a_time->years += extra;
}