PMREGISTERDERIVED(3)
๐ PMREGISTERDERIVED(3) ๐
okay so bestie, welcome to pmRegisterDerived(3) from the Library Functions Manual โ it's giving "I want new metrics and I want them now" energy and honestly? iconic. let's get into it ๐
โจ NAME โจ
pmRegisterDerived, pmRegisterDerivedMetric โ register a global derived metric name and definition ๐
๐ธ C SYNOPSIS ๐ธ
#include <pcp/pmapi.h>
char *pmRegisterDerived(char *name, char *expr);
int pmRegisterDerivedMetric(char *name, char *expr, char **errmsg);
cc ... -lpcp
๐ฆ DESCRIPTION ๐ฆ
so. derived metrics are literally the glow-up of the Performance Metrics Name Space (PMNS) ๐ โ they let you bolt brand-new metrics onto the PMNS, defined on the PCP client-side, using expressions built out of the performance metrics that already exist. no cap.
like, the classic use case is aggregating a whole bunch of similar metrics into one higher-level summary metric ๐, or supporting the ``delta value-a over delta value-b'' class of metrics โ which, btw, are just not possible with the base data semantics of PCP. the girlies that need the second one? average I/O size, defined as:
delta(disk.dev.total_bytes) / delta(disk.dev.total)
where both of the disk.dev metrics are counters, and what you actually want is to sample both metrics, compute the difference between the current and previous values, and then calculate the ratio of those differences. math queen behavior โจ
the args ๐ซถ
the arguments to pmRegisterDerived are:
nameโ the name of the new derived metric ๐exprโ an expression defining how the values ofnameshould be computed ๐งฎ
pmRegisterDerivedMetric is the exact functional equivalent to pmRegisterDerived โ the only difference is it gives you a simplified model of error handling, where a formatted message comes back via the errmsg parameter. same brain, cuter delivery ๐
when stuff gets checked ๐
- Syntactic checking happens at the time
pmRegisterDerivedis called. like, right then. immediately. - Semantic checking is deferred ๐ญ โ it waits until each new PMAPI context is created with
pmNewContext(3), or re-established withpmReconnectContext(3). that's the moment when the PMNS and metadata are finally available, so semantic checking can happen and the metadata of the derived metrics can be determined.
if you callpmRegisterDerivedafter one or more PMAPI contexts has already been opened, then the newly registered metrics will be available in those contexts โ but the more normal use is to make all your calls topmRegisterDerived(possibly viapmLoadDerivedConfig(3)) orpmRegisterDerivedMetricbefore callingpmNewContext(3). bestie. do it in that order. trust.
all of the defined global derived metrics are available in all PMAPI contexts. periodt. ๐
per-context girlies ๐
it's also possible to define per-context derived metrics once a PMAPI context has been established. these ones are private to the context they were defined in, and you make them with the allied routines pmAddDerived(3) and pmAddDerivedMetric(3). it's giving "this stays between us" ๐
to undefine a derived metric by name, go refer to pmUnregisterDerived(3) โ which removes all instances of the derived metric in all contexts, irrespective of how the derived metric was defined. it does not care how you got here, it is removing everything ๐
naming rules ๐
name should follow the syntactic rules for the names of performance metrics, namely:
- one or more components separated with a dot (
.) - each component must begin with an alphabetic, followed by zero or more characters drawn from the alphabetics, numerics and underscore (
_)
for more details, refer to PCPIntro(1) and PMNS(5) ๐
name must be unique across all derived metrics, and should not match the name of any regular metric in the PMNS. it is acceptable for name to share some part of its prefix with an existing subtree of the PMNS ๐ธ โ e.g. the average I/O size metric above could be named disk.dev.avgsz, which would place it amongst the other disk.dev metrics in the PMNS. alternatively, derived metrics could populate their own subtree of the PMNS, e.g. that same average I/O size metric could be named my.summary.disk.avgsz. main character energy, your own little neighborhood ๐ก
the expression rules (the important part, bestie) ๐
the expression expr follows these syntactic rules:
- Terminal elements are either names of existing metrics or numeric constants. recursive definitions are not allowed, so only the names of regular metrics (not other derived metrics) may be used. numeric constants are either integers constrained to the precision of 32-bit unsigned integers, or double precision floating point numbers. ๐ข
- the usual binary arithmetic operators are supported, namely addition (
+), subtraction (-), multiplication (*) and division (/) with the normal precedence rules where multiplication and division have higher precedence than addition and subtraction, soa+b*cis evaluated asa+(b*c). โจ - unary negation may be used, e.g.
-3*some.metric. โ - C-style relational operators are supported, namely
<,<=,==,>=,>and!=. relational expressions return a value as a 32-bit unsigned number, being0for false and1for true. the expected operator precedence rules apply, so arithmetic operators have higher precedence than relational operators, anda-b>c+dis evaluated as(a-b)>(c+d). all the relational operators have equal precedence, so the (slightly odd) expression involving consecutive relational operatorsa>b!=cis evaluated as(a>b)!=c. ๐ค - C-style boolean operators are supported, namely and (
&&) and or (||). boolean expressions return a value as a 32-bit unsigned number, being0for false and1for true. the expected operator precedence rules apply, so relational operators have higher precedence than boolean operators, anda>b*c&&d<=e+fis evaluated as(a>(b*c))&&(d<=(e+f)). both the boolean operators have equal precedence, so the expression involving consecutive boolean operatorsa>=b||b>c&&d!=e||f>gis evaluated as(((a>=b)||(b>c))&&(d!=e))||(f>g). ๐ฅ - additionally, the
!operator may be used to negate a boolean or relational expression, returning a value as a 32-bit unsigned number, being0for false and1for true. the expected operator precedence rules apply, so boolean (and relational) operators have higher precedence than boolean negation, and!a>b||c<dis evaluated as!((a>b)||(c<d)), while!a<b+cis evaluated as!(a<(b+c)). ๐ - C-style ternary conditional expressions are supported. in general terms the expression
check ? foo : baris evaluated asfoo(thetrue'' operand) if `check` (theguard'') is true, else the expression evaluates tobar(thefalse'' operand). some **special semantic rules** apply to theguard'' expression and the other two operand expressions:
(a) each expression may involve a singular value or a set of values (when the expression involves one or more metrics with an instance domain). ๐ธ
(b) all expressions with a set of values must be defined over the same instance domain.
(c) both operand expressions must have the same metadata, so the same metric type, semantics and units (dimension and scale). ๐
(d) the ``guard'' expression must have an arithmetic or relational or boolean value, so that it can be evaluated as 0 for false, else true.
(e) if the guard'' expression has a singular value and one or more of the other operand expressions involves an instance domain, the guard'' applies to all instances.
(f) if the guard'' expression has a set of values and one or more of the other operand expressions involves an instance domain, the guard'' is evaluated once for each instance (there must be exactly one instance domain as per rule (b) above).
(g) if one of the operand expressions has a singular value and the other has a set of values, and the singular value is selected based on the evaluation of the ``guard'', then the result is a set of values (all the same) with instance enumeration being taken from the other operand expression. for example in the expression: check ? foo : bar, if foo is an expression with a singular value and bar is a set-valued expression, then if check is true, then the result is a set of values (all having the same value, foo) over the instance domain of bar.
(h) as a special case, either (but not both) of the expressions foo or bar may be the special constructor novalue(). if novalue() needs to be evaluated, it will return no values. the most common use of novalue() is in conjunction with defined() as in the following example:
mumble = defined(abc.def) ? count(abc.def) : novalue()
the metadata for novalue() is taken from the peer operand of the : operator, making conditions (b) and (c) above trivially true; if the peer operand cannot be evaluated, then the default metadata for novalue() is a singular discrete integer with no units, and conditions (b) and (c) are waived. ๐ซถ
an extension of novalue() is novalue(<metadata>) where the <metadata> can be specified using one or more parameters of the form tag=value or tag="value" as described for the mkconst() constructor below, for example:
novalue(type=float, semantics=instant, units="Kbytes/sec")
(i) as an additional further case, if check is of the form defined(somemetric) then references to undefined metrics are allowed in whichever of foo or bar is not required once the existence of somemetric has been established. this allows uses of the form:
fumble = defined(new.metric) ? new.metric : old.metric
which is valid when new.metric is defined and when new.metric is not defined, although this does mean rules (b) and (c) are relaxed in this case, which further means novalue() may have no peer operand to provide metadata. ๐ญ
a generalization of this construct is supported for any check that can be evaluated statically, so a boolean expression involving defined() predicates, for example:
bar = !defined(a) || !defined(b) ? novalue() : a + b
- selection of a single instance can be specified by the construct
[instance_name]which may be appended to a metric name or a parenthesized expression. for example: ๐ฏ
fw.bytes = network.interface.in.bytes[eth1] + \
network.interface.out.bytes[eth1]
or (equivalently):
fw.bytes = (network.interface.in.bytes + \
network.interface.out.bytes)[eth1]
all characters between the ['' and ]'' are considered to be part of the (external) instance name, so be careful to avoid any spurious white space. ๐ค a backslash may be used as an escape prefix in the (unlikely) event that the external instance name contains a ``]''. ๐ฆ
- Numeric constants can also be built with the
mkconst()constructor, which is lowkey iconic because it takes a bunch of arguments: the first one is a numeric constant (integer or floating point, dealer's choice ๐ ), and then you get one or more parameters shaped liketag=valueortag="value", where the allowed tags and values are, bestie, exactly this:typeโ one of the numeric metric types from<pcp/pmapi.h>, with thePM_TYPE_prefix stripped off, so:32,U32,64,U64,FLOATorDOUBLE. โจsemanticsโ one of the semantic types from<pcp/pmapi.h>, with thePM_SEM_prefix stripped off, so:COUNTER,INSTANTorDISCRETE. ๐ฆunitsโ a spec of dimension and scale (together they make up the units, periodt) written in the syntax thatpmParseUnitsStr(3)accepts. ๐ธindomโ an instance domain number, given asNULLforPM_INDOM_NULL(which is the default) or asdomain.serialwheredomainsits in the range[0,510]andserialsits in the range[0,4194303]. ๐metaโ a metric name, and that metric is the one supplying the base metadata that other parameters are allowed to modify. ๐
The value can optionally be wrapped in double quotes, and it can show up in any mix of UPPER and/or lower case. The tag, though, must be lower case exactly like the table above โ no cap, it's giving lowercase or nothing. ๐
This whole thing is most useful when the expression semantics require matching type and/or semantics and/or units for the operands, like:
idle = mem.util.free > mkconst(10485760, units=Kbyte)
avg_io_size = delta(disk.dev.total) == 0 ? \
mkconst(1.0, semantics=instant, units="kbyte / count") : \
delta(disk.dev.total_bytes) / delta(disk.dev.total)
- Rescaling โ expressions can be rescaled with the
rescalefunction, which takes two arguments. The first is an arithmetic expression to be rescaled, and the second is the desired units after rescaling, given as a string value in the syntax accepted bypmParseUnitsStr(3). For example:
rescale(network.interface.total.bytes, "Mbytes/hour")
The expression and the desired units must both have the same dimension, e.g Space=1, Time=-1 and Count=0 in the example above. No dimension-mismatch shenanigans, okay? ๐ซถ
- The unary functions below operate on a single performance metric and return one or more values. For all of them โ except
count()anddefined()โ the type of the operand metric must be arithmetic (integer of various sizes and signedness, float or double). ๐avg(x)โ a singular instance that is the average value across all instances for the metricx. ๐count(x)โ a singular instance that is the count of the number of instances for the metricx. Special case alert ๐จ: if fetching the metricxreturns an error, thencount(x)will be0.defined(x)โ a boolean value that is true (1) if the metricxis defined in the PMNS, else false (0). The function is evaluated when a new PMAPI context is created withpmNewContext(3)or re-established withpmReconnectContext(3). So any subsequent changes to the PMNS after the PMAPI context has been established will not change the value of this function in the expression evaluation. It's frozen in time, bestie. ๐งmax(x)โ a singular instance that is the maximum value across all instances for the metricx. ๐ฅmin(x)โ a singular instance that is the minimum value across all instances for the metricx. ๐ธsum(x)โ a singular instance that is the sum of the values across all instances for the metricx. โ
- One more unary function here, and it returns the instantaneous value of an expression โ not the rate-converted value that is the default for expressions with the semantics of
PM_SEM_COUNTER. ๐คinstant(expr)โ returns the current value of the expression, even if it has the semantics of a counter, i.e.PM_SEM_COUNTER. The semantics of the derived metric are based on the semantics of the expressionexpr; ifexprhas semanticsPM_SEM_COUNTER, the semantics ofinstant(expr)isPM_SEM_INSTANT, otherwise the semantics of the derived metric is the same as the semantics ofexpr. โจ
- And the consecutive-sample girlies โ the following unary functions return values computed from the value of an expression on consecutive samples, or
pmFetch(3)calls. The expression (exprbelow) may involve one or more metrics but must have an arithmetic value (integer of various sizes and signedness, float or double) for all instances. No exceptions, fr fr. ๐
okay so if expr is a set-valued expression (iykyk, it hands you a whole little squad of instances instead of one single value), then only the instances that show up in both samples make it into the result. no newcomers, no strays. ๐
โจ the two glow-up functions: delta and rate โจ
delta(expr)โ bestie, this one gives you the difference in values for the expression between one call topmFetch(3)and the next. there's one value in the result for every instance that appears in both the current and the previous sample. ๐ซถ
and here's the type tea: if the expression is unsigned, the type of the result gets converted so as much precision as possible can be retained. so if the expression has type PM_TYPE_U32 then the result is of type PM_TYPE_64, else if the expression has type PM_TYPE_U64 then the result is of type PM_TYPE_DOUBLE. otherwise the type of the result is the same as the type of the expression. no cap. โจ
rate(expr)โ this one returns the difference in values for the expression between one call topmFetch(3)and the next, divided by the elapsed time between the calls topmFetch(3). it's giving speed. ๐ฅ
the semantics of the derived metric are based on the semantics of the expression with the dimension in the time domain decreased by one, plus scaling if required in the time utilization case where the operand is in units of time and the derived metric is unitless.
there's one value in the result for each instance that appears in both the current and the previous sample โ except in the case where the expression has the semantics of a counter, i.e. PM_SEM_COUNTER, and the current value of an instance is smaller than the previous value of the same instance. in that case, no value is returned for this instance (this corresponds to a counter wrap'' or a counter reset''). ๐ญ these rules mimic the rate conversion applied to counter metrics by tools such as pmval(1), pmie(1) and pmchart(1).
- the
matchinstfunction may be used to select a subset of the instances from an instance domain for a metric or expression. it takes two arguments:- (a) an instance filter that consists of an optional negation operator
!'' followed by a regular expression delimited by/'' characters. the regular expression follows the POSIX Extended Regular Expression syntax as described inregex(3). a single backslash may be used to escape the regular expression delimiter/'', but double backslashes are required to escape any regular expression special characters, e.g. for the (extremely unlikely) case of wanting to match instance names likesome*text/other[text]'' a regular expression of the form/some\\*text\/other\\[text]/would be required. and if present, the negation operator reverses the sense of the filtering, so all instances not matching the regular expression will be selected. ๐ - (b) a metric or expression that must be defined over an instance domain.
- (a) an instance filter that consists of an optional negation operator
for example, the following expression will have values for the metric network.interface.in.bytes for all network interfaces except the loopback and virtual bridge devices:
matchinst(!/^(lo)|(vbir)/, network.interface.in.bytes)
- the
scalarfunction may be used to convert a metric or expression defined over an instance domain into a scalar value that can be used in other expressions. for example:
net.in.bytes = scalar(network.interface.in.bytes[eth0]) + \
scalar(network.interface.in.bytes[eth1])
the instance domain is removed from the metadata for the result, and the instance identifier is removed from the value during fetching.
โ ๏ธ okay so listen: if the metric or expression involves more than one instance, then the result is formed by picking the first instance โ this is arbitrary, which implies thescalarfunction should only be used for metrics or expressions that are expected to contain zero or one instances, e.g. the construct ``[instance_name]'' or thematchinstfunction with a pattern that matches at most one instance. don't come crying to me when you get a random instance, bestie. ๐
- parenthesis may be used for explicit grouping. ๐
- a line ending with
\'' is treated asto be continued'' and the following line is appended after stripping the ``'' and the embedded newline. the way that little backslash keeps the vibe going... iconic. โจ - control lines begin with
#controlfollowed by settings for one or more derived metric controls or options as described inpmSetDerivedControl(3). ๐ - other lines beginning with ``#'' are treated as comments and ignored. (not me ignoring things that start with a # ๐ฅ)
- white space is ignored. it's just there for the aesthetic, and honestly? same. ๐ธ
๐ง SEMANTIC CHECKS AND RULES ๐ง
okay bestie so here's the thing โ before any derived metric can actually exist, there's a whole lil conversion pipeline that has to figure out its metadata, plus a vibe check to make sure the expression even makes sense. It's giving "math teacher who cares about your feelings." ๐
โจ the semantics tea โ
In an arithmetic expression or a relational expression, if the semantics of both operands is not a counter (i.e. PM_SEM_INSTANT or PM_SEM_DISCRETE), then the result gets semantics PM_SEM_INSTANT โ unless both operands are PM_SEM_DISCRETE, in which case the result is also PM_SEM_DISCRETE. slay, the discrete stays discrete. ๐
For an arithmetic expression, the dimension of each operand must be the same. For a relational expression, the dimension of each operand must also be the same โ except numeric constants (with no dimension) are allowed to sneak in, e.g. in the expression network.interface.in.drops > 0. ๐ซถ
๐ซ no chaotic combinations pls
To prevent arbitrary and non-sensical combinations, some restrictions apply to expressions that combine metrics with counter semantics to produce a result with counter semantics. For an arithmetic expression:
- if both operands have the semantics of a counter, then only addition or subtraction is allowed
- or if the left operand is a counter and the right operand is not, then only multiplication or division are allowed
- or if the left operand is not a counter and the right operand is a counter, then only multiplication is allowed
Metrics with extra units, like temperature or voltage, are subject to some additional constraints, specifically:
- no automatic scale conversion (although the
rescalefunction works as expected) - extra units cannot be used for both operands in multiplication (
*) - extra units are only allowed for both operands of division (
/) if the units and scale are identical
Because relational expressions use the current value only and produce a result that is not a counter, either or both operands of a relational expression may be counters. iconic behaviour honestly. ๐
๐ mapping the pmUnits of the metadata
The rules go like this:
- If both operands have a dimension of Count and the scales are not the same, use the larger scale and convert the values of the operand with the smaller scale.
- If both operands have a dimension of Time and the scales are not the same, use the larger scale and convert the values of the operand with the smaller scale.
- If both operands have a dimension of Space and the scales are not the same, use the larger scale and convert the values of the operand with the smaller scale.
- For addition and subtraction all dimensions for each of the operands and result are identical.
- For multiplication, the dimensions of the result are the sum of the dimensions of the operands.
- For division, the dimensions of the result are the difference of the dimensions of the operands.
Scale conversion involves division if the dimension is positive, else multiplication if the dimension is negative. And heads up โ if scale conversion is applied to either of the operands, the result is promoted to type PM_TYPE_DOUBLE. glow up achieved โจ
๐งฎ putting it all together (example time)
Consider the derived metric defined as follows:
x = network.interface.speed - delta(network.interface.in.bytes) /
delta(sample.milliseconds)
The type, dimension and scale settings would propagate up the expression tree as follows.
โโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโฌโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโ
โ Expression โ Type โ Dimension & โ Scale Factor(s) โ
โ โ โ Scale โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโผโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโค
โ sample.milliseconds โ DOUBLE โ millisec โ โ
โ delta(...) โ DOUBLE โ millisec โ โ
โ network...bytes โ U64 โ byte โ โ
โ delta(...) โ U64 โ byte โ โ
โ delta(...) / delta(...) โ DOUBLE โ byte/millisec โ /1048576 and โ
โ โ โ โ *1000 โ
โ network...speed โ FLOAT โ Mbyte/sec โ โ
โ x โ DOUBLE โ Mbyte/sec โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโดโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโ
๐ซง instance domains & the semantic check timing drama
Expressions involving single instance selection or the matchinst function must be associated with underlying metrics that have an instance domain. These constructors make no sense for singular metrics, fr fr. ๐
Because semantic checking cannot be done at the time pmRegisterDerived is called, errors found during semantic checking (when any subsequent calls to pmNewContext(3) or pmReconnectContext(3) succeed) are reported using pmprintf(3). These include:
Error: derived metric <name1>: operand: <name2>: <reason>There was a problem callingpmLookupName(3)to identify the operand metric<name2>used in the definition of the derived metric<name1>.Error: derived metric <name1>: operand (<name2> [<pmid2>]): <reason>There was a problem callingpmLookupDesc(3)to identify the operand metric<name2>with PMID<pmid2>used in the definition of the derived metric<name1>.Semantic error: derived metric <name>: <operand> : <operand> Different <metadata> for ternary operandsFor a ternary expression, the "true" operand and the "false" operand must have exactly the same metadata, so type, semantics, instance domain, and units (dimension and scale).Semantic error: derived metric <name>: <operand> <op> <operand>: Dimensions are not the sameOperands must have the same units (dimension and scale) for each of addition, subtraction, the relational operators and the boolean "and" or "or" operators.Semantic error: derived metric <name>: <operand> <op> <operand>: Illegal operator for counter and non-counterOnly multiplication or division are allowed if the left operand has the semantics of a counter and the right operand is not a counter.Semantic error: derived metric <name>: <operand> <op> <operand>: Illegal operator for countersIf both operands have the semantics of counter, only addition or subtraction make sense, so multiplication and division are not allowed.Semantic error: derived metric <name>: <operand> <op> <operand>: Illegal operator for non-counter and counterOnly multiplication is allowed if the right operand has the semantics of a counter and the left operand is not a counter.Semantic error: derived metric <metric> <expr> RESCALE <units>: Incompatible dimensionsThe parameters<expr>and<units>to therescalefunction must have the same dimension along the axes of Time, Space and Count.Semantic error: derived metric <name>: Incorrect time dimension for operandRate conversion using therate()function is only possible for operand metrics with a Time dimension of 0 or 1 (seepmLookupDesc(3)). If the operand metric's Time dimension is 0, then the derived metrics has a value "per second" (Time dimension of -1). If the operand metric's Time dimension is 1, then the derived metrics has a value of time utilization (Time dimension of 0).Semantic error: derived metric <name>: <function>(<operand>): Non-arithmetic operand for functionThe unary functions are only defined if the operand has arithmetic type. Similarly the first argument to therescalefunction must be of arithmetic type.Semantic error: derived metric <name>: <expr> ? ...: Non-arithmetic operand for ternary guardThe first expression for a ternary operator must have an arithmetic type.Semantic error: derived metric <name>: ... - ...: Non-arithmetic operand for unary negationUnary negation only makes sense if the following expression has an arithmetic type.Semantic error: derived metric <name>: <operand> <op> <operand>: Non-arithmetic type for <left-or-right> operandThe binary arithmetic operators are only allowed with operands with an arithmetic type (integer of various sizes and signedness, float or double).Semantic error: derived metric <name>: <operand> <op> <operand>: Non-counter and not dimensionless for <left-or-right> operandFor multiplication or division or any of the relational operators, if one of the operands has the semantics of a counter and the other has the semantics of a non-counter (instantaneous or discrete) then the non-counter operand must have no units (dimension and scale).Semantic error: derived metric <name>: <expr> ? <expr> : <expr>: Non-scalar ternary guard with scalar expressionsIf the "true" and "false" operands of a ternary expression have a scalar value, then the "guard" expression must also have a scalar value.Semantic error: derived metric <name>: <expr> <op> <expr>: Operands should have the same instance domainFor all of the binary operators (arithmetic and relational), if both operands have non-scalar values, then they must be defined over the same instance domain.Semantic error: derived metric <name>: operand <dname>: Illegal nested derived metricA derived metric (<dname>) cannot be nested (i.e. used) in the definition of another derived metric (<name>).Semantic error: derived metric <name>: <expr> <op> <expr>: Illegal operator for non-countersMetrics with counter semantics may be added or subtracted, but<op>(division or multiplication) is not allowed.Semantic error: derived metric <name>: operand <bname>: Unknown metric for ternary expressionWhen a new context was established, the metric<bname>was not in the PMNS of the new context and<bname>is a required operand in the definition of the derived metric<name>.
fr fr bestie, that error list is LONG but every single one is a real thing that can happen, so keep it in your back pocket ๐
โจ EXPRESSION EVALUATION โจ
okay bestie, so when we're talking about the binary arithmetic operators, there's this whole type-promotion situation going on and honestly it's giving โจhierarchyโจ ๐
Here's the tea: if either operand has to be scaled (like, think convert bytes to Kbytes energy), then the result gets promoted to PM_TYPE_DOUBLE. no negotiations. ๐
Otherwise? The type of the result is decided by the types of the operands, and you go through this list from top to bottom until you find a match โ first one wins, periodt ๐
- either is
PM_TYPE_DOUBLEโ operator: any โ result type:PM_TYPE_DOUBLE - any โ operator: division โ result type:
PM_TYPE_DOUBLE - either is
PM_TYPE_FLOATโ operator: any โ result type:PM_TYPE_FLOAT - either is
PM_TYPE_U64โ operator: any โ result type:PM_TYPE_U64 - either is
PM_TYPE_64โ operator: any โ result type:PM_TYPE_64 - either is
PM_TYPE_U32โ operator: any โ result type:PM_TYPE_U32 - otherwise (both are
PM_TYPE_32) โ operator: any โ result type:PM_TYPE_32
๐ซถ pro tip from me to you: the order is NOT optional, bestie. it literally says evaluated from top to bottom until a match is found. so like, don't go jumping around the list, okay? ๐ญ
๐ PMIDs AND MASKING ๐
ok so bestie, before we get into the messy part, let's talk IDs ๐
Inside PCP, every single metric gets its very own Performance Metric Identifier (that's a PMID, iykyk) and internally that PMID is built from 3 fields:
- the domain number โ that's the Performance Metrics Domain Agent, aka the PMDA
- the cluster number
- the item number
Derived metrics use the reserved domain number 511 plus some special PMIDs, and the whole vibe is that a PMID is written out as domain.cluster.item. Here's the tea ๐:
globalโ starting PMID is511.0.1. Metrics get assigned ascending PMIDs as they're registered viapmRegisterDerivedorpmRegisterDerivedMetric, orpmLoadDerivedConfig(3).per-contextโ starting PMID is511.2047.1023. Metrics get assigned descending PMIDs as they're registered viapmAddDerived(3)orpmAddDerivedMetric(3).remappedโ starting PMID is511.c.i. When a derived metric gets recorded into a PCP archive bypmlogger(1)or one of the related archive creation tools, the PMID of the derived metric gets remapped in the archive so thatcis the cluster of the derived metric plus 2048, andiis the item of the derived metric. For example, a derived metric with PMID511.0.13will have the remapped PMID511.2048.13in an archive. Seepmlogger(1)for the whole discussion about adding derived metrics to a PCP archive. ๐
Now for base metrics from a host or archive context, there's a requirement that every metric name is unique. But derived metrics need that restriction to be relaxed, so the same metric name could be associated with a base metric, and/or a per-context derived metric, and/or a global metric. Which means... one or more of the metrics with the same name may be masked by other metrics of the same name ๐
Here's exactly which metric gets used when one of these multiply-defined names gets presented to the PMAPI:
base metric: no,remapped: no,per-context: no,global: noโ none; the metric is undefinedbase metric: no,remapped: no,per-context: no,global: yesโ global derivedbase metric: no,remapped: no,per-context: yes,global: noโ per-context derivedbase metric: no,remapped: no,per-context: yes,global: yesโ per-context derivedbase metric: no,remapped: yes,per-context: no,global: noโ remappedbase metric: no,remapped: yes,per-context: no,global: yesโ remappedbase metric: no,remapped: yes,per-context: yes,global: noโ remappedbase metric: no,remapped: yes,per-context: yes,global: yesโ remappedbase metric: yes,remapped: no,per-context: no,global: noโ base metricbase metric: yes,remapped: no,per-context: no,global: yesโ base metricbase metric: yes,remapped: no,per-context: yes,global: noโ base metricbase metric: yes,remapped: no,per-context: yes,global: yesโ base metricbase metric: yes,remapped: yes,per-context: -,global: -โ cannot happen; for any name there can be at most one of a base metric or a remapped metric
When masking happens, it happens silently. Like, no drama, no notification, it just... does it ๐
Most PCP applications support -Dderive on the command line, and this pmdbg(1) debug option will report derived metric operations (including masking) on stderr. So if you're like "where did my metric GO" โ that's your girl ๐ซถ
๐ CAVEATS ๐
Okay bestie, listen up because this one matters:
Derived metrics are not available when usingpmFetchArchive(3), because this routine does not use a target list of PMIDs that could be remapped โ which is exactly what is done forpmFetch(3). ๐ญ
๐ DIAGNOSTICS ๐
ok bestie, vibe check on how this thing tells you whether it ate or flopped:
- Success?
pmRegisterDerivedhands you backNULL. That's the good ending ๐ - Found a syntactic error at registration time? Then the value
pmRegisterDerivedreturns is a pointer intoexprshowing exactly where the error is lurking. To figure out what the error actually was, your app should callpmDerivedErrStr(3)and pull the matching parser error message. iykyk โจ pmRegisterDerivedMetric? On success it returns0, anderrmsgis undefined โ don't go reading it, it's not your moment ๐- If the given
exprdoes not conform to the required syntax,pmRegisterDerivedMetricreturns-1and drops a dynamically allocated error message string intoerrmsg. That string is terminated with a newline and includes both the input name andexpr, along with an indicator of the position where the error got caught. e.g.
Error: pmRegisterDerivedMetric("my.disk.rates", ...) syntax error
4rat(disk.dev.read)
^
- Sometimes that position indicator line is followed by an extra diagnostic line describing the nature of the error, when that info is available ๐ฆ
- > โ ๏ธ real talk: if there's an error, you โ the
pmRegisterDerivedMetriccaller โ are the one responsible for callingfree(3)to release the space allocated forerrmsg. Nobody else is coming to do it for you. periodt ๐
The debugging option derive (see pmdbg(1)) can be used to give you extra diagnostic info about the parsing, binding and evaluation of derived metric expressions. Stack more debugging options on top of derive for even more info, as laid out below. Alternatively, an application can use pmSetDerivedControl(3) to achieve the same result โจ
appl0โPCP_DERIVED_DEBUG_SYNTAXโ coverspmRegisterDerived,pmAddDerived(3), the lexical scanner, the syntactic checks, andpmUnregisterDerived(3).appl1โPCP_DERIVED_DEBUG_SEMANTICSโ covers the actions when a new PMAPI context is created, the semantic checks, detailed error reports for binding failures, and the updates that catch global derived metrics registered after the PMAPI context was created.appl2โPCP_DERIVED_DEBUG_EVALโ covers PMNS operations,pmFetch(3)andpmLookupDesc(3).
And for even more detail, add the desperate debugging option to any of the above, e.g. -Dderive,appl1,desperate shows the binding of every expression node for every derived metric when a new PMAPI context is created ๐
โจ OPTIONS โจ
On top of the diagnostic control options, pmSetDerivedControl(3) can also set this one option, which controls the parsing and evaluation of derived metric expressions:
PCP_DERIVED_OPTION_NOVALUEโ if a metric operand inside a derived metric expression isn't available in the current PMAPI context, the default behaviour (that's when this option has the value0) is to mark the expression as invalid and the associated derived metric name is not visible in the PMNS โ so neither metadata nor values can be fetched. Setting this option to1switches things up: the unavailable operand gets replaced by thenovalue()constructor, with the default metadata of a singular discrete integer metric with no units. The derived metric stays in the PMNS, but attempts to retrieve values viapmFetch(3)will likely returnPM_ERR_VALUE(Missing metric value(s)).
Refer to pmSetDerivedControl(3) for the alternative ways controls and options can be set โ via the PCP_DERIVED_CONTROL environment variable and/or #control lines in a the definition of a derived metric ๐ธ
๐ซถ SEE ALSO ๐ซถ
PCPIntro(1)pmdbg(1)pmlogger(1)PMAPI(3)free(3)pmAddDerived(3)pmAddDerivedMetric(3)pmDerivedErrStr(3)pmFetch(3)pmFetchArchive(3)pmLoadDerivedConfig(3)pmLookupDesc(3)pmLookupName(3)pmNewContext(3)pmParseUnitsStr(3)pmReconnectContext(3)pmSetDerivedControl(3)pmUnregisterDerived(3)pmprintf(3)regex(3)PMNS(5)
and that's a wrap on the whole page bestie, you made it all the way through ๐ this one's straight from Performance Co-Pilot, filed under PMREGISTERDERIVED(3) โ go forth and register those derived metrics, ur literally the main character of the PMNS now ๐๐๐
๐ฆ where this page comes from
- arch rolling: pcp 7.2.2-2 ยท GPL-2.0-or-later AND LGPL-2.1-or-later AND CC-BY-3.0
- fedora 43: pcp-doc 7.2.1-1.fc43
- fedora 43: pcp-doc 7.2.2-1.fc43
- fedora 43: pcp-doc 7.2.2-2.fc43 ยท GPL-2.0-or-later AND CC-BY-3.0
- fedora 44: pcp-doc 7.2.1-1.fc44
- fedora 44: pcp-doc 7.2.2-1.fc44
- fedora 44: pcp-doc 7.2.2-2.fc44 ยท GPL-2.0-or-later AND CC-BY-3.0
- ubuntu stonking: libpcp4-dev 7.2.1-2build1
- Copyright (c) 2009 Ken McDonell. All Rights Reserved
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms