Develop Advisor checks¶
When the built-in checks don’t cover a rule that matters for your databases, for example an internal naming convention or a setting that your team requires, write your own check.
You create custom checks in the PMM UI, and PMM runs them on your services together with the built-in checks.
A check queries your database, PMM metrics or Query Analytics, and turns the results into findings with a Starlark script, which uses Python syntax.
Prerequisites¶
Before you create a check:
- Check that you have the Admin role. Only Admins can create, edit, clone, test and delete checks, because a check’s queries run on your databases with the privileges of the PMM monitoring user. Editors can only view, run, enable and disable checks. Before you give other users access, review the permissions of every role.
- Check that the Advisors option is turned on under Configuration > Settings > Advisors.
- Check that PMM monitors at least one service of the technology that your check targets, so that you can test the check on it.
Built-in and custom checks¶
Before you write a check from scratch, look for a built-in check that already does most of what you need. In Advisors > Catalog, the Source column shows Built-in for the checks that ship with PMM and Custom for the checks that you create.
You can run, test and turn off checks of both kinds, and open, copy or clone their scripts. Only custom checks can be edited or deleted, so to adapt a built-in check, clone it and edit the copy. The scripts of the built-in checks are good examples to start from.
Create a check¶
Create a check from scratch, or clone a built-in check that is close to what you need and adapt the copy.
To create a check:
-
Go to Advisors > Catalog and open the check form:
- click the Add advisor check icon to start from scratch
- double-click a check’s row and click Clone in the details pane to start from that check. The clone’s name starts as
custom_followed by the name of the source check.
-
In Name, complete the ID after
custom_, for examplecustom_mysql_test_database. You can’t change it later. - Enter a Summary, a short title of the check, and a Description of what the check verifies.
- In Category, select an existing category, such as Security or Performance, or type a new one.
- In Technology, select the type of database that the check targets: MySQL, PostgreSQL or MongoDB. The check runs only on services of that type, and the query types you can choose depend on it.
- Under Queries, add the queries that collect the data that your check needs.
- In Script, write the script that turns the query results into findings.
-
To try the check before you save it, select a service in Test on service and click Test:
- Test results shows the findings, or the error if a query or the script failed.
- Script output shows what the script printed with
print().
The test doesn’t save the check and doesn’t record any insight.
-
Click Save check. The check appears in the catalog as enabled, with Custom in the Source column.
Collect the data that the check needs¶
Decide which data your check needs, and add one query for each set of data. A query can read your database, through the PMM Client that monitors it, or the metrics and Query Analytics data that PMM Server stores.
To add a query to a check:
- Under Queries, click Add query.
-
In Type, select the type that reads the data your check needs. The list offers only the types that fit the check’s database:
MYSQL_SHOWorMYSQL_SELECTto run aSHOW …orSELECT …statement on a MySQL servicePOSTGRESQL_SELECTto run aSELECT …statement on a PostgreSQL service, orPOSTGRESQL_SHOWto read all its settings withSHOW ALL- a
MONGODB_*type to run an admin command on theadmindatabase of a MongoDB service:MONGODB_GETPARAMETERfor the server parameters, with the getParameter commandMONGODB_BUILDINFOfor the version and build details, with the buildInfo commandMONGODB_GETCMDLINEOPTSfor the startup options, with the getCmdLineOpts commandMONGODB_REPLSETGETSTATUSfor the replica set status, with the replSetGetStatus commandMONGODB_GETDIAGNOSTICDATAfor the full-time diagnostic data
METRICS_INSTANTto read the current value of a metric that PMM collects, orMETRICS_RANGEto read its values over a time range, with a MetricsQL queryCLICKHOUSE_SELECTto run aSELECT …statement on the Query Analytics data
-
In Query, enter the query text. Leave it empty for
POSTGRESQL_SHOWand theMONGODB_*types, which take none. To query only the service that the check runs on, use these placeholders:{{.ServiceName}}and{{.NodeName}}inMETRICS_INSTANTandMETRICS_RANGEqueries, for the names of the service and its node{{.ServiceName}}and{{.ServiceID}}inCLICKHOUSE_SELECTqueries, for the name and ID of the service
-
If the query type accepts parameters, click Add parameter under the query, select or type the parameter name in Parameter, and enter its Value. Durations take a number with a unit, such as
30s,5mor8h. You can set each parameter only once per query:- lookback for
METRICS_INSTANTandMETRICS_RANGE, optional: how far back in the metrics history the query looks. Without it, the query reads the latest data. - range for
METRICS_RANGE, required: the time window of the query, as in the Prometheus range query API - step for
METRICS_RANGE, required: the resolution of the query, as in the Prometheus range query API - all_dbs for
POSTGRESQL_SELECT, optional: set it totrueto run the query on every database of the PostgreSQL instance. Without it, the query runs on the database that was specified when the service was added to PMM.
- lookback for
The script receives the results in the order of the queries. To remove a query or a parameter, click its Remove query or Remove parameter icon.
Write the check script¶
Write the script that decides, from the query results, whether a service has an issue. Keep it fast: the script has 5 seconds to finish, and the whole check, including its queries, has 5 minutes.
The script runs in a sandbox on PMM Server, so it can’t read or write files or access the network.
In the script, define a check_context(docs, context) function:
docsis a read-only list with one item for each query, in the order of the queries. Each item holds the result of that query: the returned rows for SQL databases and the returned documents for MongoDB.contextis a dictionary with helper functions.
Indent the script with spaces, not tabs.
Return findings¶
To tell PMM what the check found, return a list of findings, one for each issue. Each finding becomes a Failed insight.
An empty list means that the check passed, and the service gets an OK insight. Learn what each insight status means.
Each finding is a dictionary with these keys:
summary(required): a short description of the issueseverity(required):critical,error,warningorinfo, in lowercasedescription(optional): details of the issueread_more_url(optional): a valid URL that links to the steps that fix the issuelabels(optional): a dictionary of string keys and values that describe the finding
PMM rejects any other severity, including the emergency, alert, notice and debug levels that earlier versions accepted, and the check gets the Error status.
If the check can’t evaluate the data, return a string or call fail() instead. The check then gets the Error status with your message.
Report one finding per service¶
To keep Advisors > Insights easy to read, return one finding per service, or one per database for checks that examine per-database objects, rather than one finding per affected object.
The list tells findings apart by their summary and labels, so per-object findings with the same summary fill the list with rows that look identical.
To report several objects in one finding:
- put the count in the summary, for example
3 relation(s) with unused indexes in database app - list the objects in the description
- set labels such as
databaseandcount
If the check finds issues at different severity levels, return one finding per severity level.
Use the helper functions¶
Use the helper functions to debug your script and to handle versions and IP addresses without writing that logic yourself.
To debug the script, call print: when you test the check, Script output shows what it wrote. To stop the check with an error, call fail.
The context dictionary provides these functions:
parse_version(version)parses a version string and returns a dictionary with themajor,minor,patch,rest,numandnumrestkeys.format_version_num(num)formats a version number, such as80036, as a version string, such as8.0.36.current_date()returns today’s date in UTC as aYYYY-MM-DDstring.days_until(date)returns the number of whole days from today (UTC) until aYYYY-MM-DDdate. The number is negative for a date in the past.ip_is_private(address)returnsTrueif the IP address is private, or if the network in CIDR notation, such as10.0.0.0/8, lies fully inside a private address block. It returnsFalseif it isn’t, andNoneif the argument isn’t a valid address or network.
Get a function from context before you call it, for example parse_version = context.get("parse_version", fail).
Try an example check¶
To see how queries and a script work together, create a check that reports the MySQL version, the uptime and the recent load average of each MySQL service.
In the check form, set Technology to MySQL, then:
- Add a
MYSQL_SHOWquery with the textVARIABLES. - Add a
METRICS_INSTANTquery with the textmysql_global_status_uptime{service_name=~"{{.ServiceName}}"}. - Add a
METRICS_RANGEquery with the textavg by (node_name) (avg_over_time(node_load1{node_name=~"{{.NodeName}}"}[5m])), and set itsrangeparameter to15mand itsstepparameter to5m. -
In Script, paste this script. It reads the results of the three queries from
docs[0],docs[1]anddocs[2], in the order that you added them. Each series of aMETRICS_RANGEresult holds its data points invalues, as[timestamp, value]pairs:def check_context(docs, context): results = [] for row in docs[0]: name, value = row["Variable_name"], row["Value"] if name == "version": results.append({ "summary": "MySQL has version {}".format(value), "description": "Current version is {}".format(value), "read_more_url": "", "severity": "info", "labels": {}, }) uptimeNow = int(int(docs[1][0]["value"][1])/60) results.append({ "summary": "MySQL uptime {} min".format(uptimeNow), "description": "Current uptime is {} min".format(uptimeNow), "read_more_url": "", "severity": "info", "labels": {}, }) dataPoints = [] for row in docs[2][0]["values"]: dataPoints.append(row[1]) results.append({ "summary": "Node load average for the last 15 minutes {}".format(dataPoints), "description": "Data points {}".format(dataPoints), "read_more_url": "", "severity": "info", "labels": {}, }) return results -
Select a MySQL service in Test on service and click Test. Test results shows 3 findings: the version, the uptime and the load average.
Run the check and review its results¶
Your check runs on every schedule set to All checks, together with the built-in checks. To see its results before the next scheduled run:
- Go to Advisors > Catalog, find your check and click the Run icon in its row.
- In the confirmation message, click View results. Advisors > Insights shows the results of that run for each service.
- To follow your check across all runs, click the icon in one of its insights and select Filter by name.
To make sure that the run reached all your services, check the coverage numbers of the run in Advisors > Run history.
Change or delete a check¶
Change a custom check when your rules change, and delete it when you no longer need it.
Built-in checks can’t be changed or deleted: to adapt one, clone it, and turn off the original with its Status switch.
In Advisors > Catalog:
- click the Edit icon in a check’s row, or Edit in its details pane, to change any field except Name. Test your changes before you click Save check.
- click the Delete icon in a check’s row and confirm to delete the check. You can’t undo the deletion.
Troubleshooting¶
Fix the most common problems with custom checks: no services to test on, tests that fail, and checks that you need to debug in the logs.
Test on service lists no services¶
If Test on service lists no services, PMM doesn’t monitor any service of the check’s database type through a PMM Client. Add a service of that type to PMM, or change the check’s Technology. PMM Server’s internal PostgreSQL database is never listed.
The test fails¶
If a test fails, find the cause:
- Read the error message. It shows the failed query or the script error, followed by the script’s output.
- Check that each parameter fits its query type and has a valid value, and that every
METRICS_RANGEquery hasrangeandstep. These problems also stop you from saving the check. - Check that the Advisors option is turned on under Configuration > Settings > Advisors.
- Check that the PMM Client of the service is connected. If it’s too old for the check, upgrade PMM Client on that node, or test on another service.
Find the check logs¶
To find out why a check fails, read the pmm-managed logs on PMM Server. Every log line of the checks includes component=checks:
-
To follow the logs of a PMM Server that runs in Docker, run:
docker exec -it pmm-server supervisorctl tail -f pmm-managed -
To list only the check logs, filter the log file:
docker exec pmm-server grep "component=checks" /srv/logs/pmm-managed.log -
If the logs don’t show enough detail, set
PMM_DEBUG=1on the PMM Server container to turn on verbose logging. Turn it off again when you’re done, because verbose logs grow quickly and hide important messages.
Submit feedback¶
Tell us how we can improve developing and debugging checks: post your comments or questions on the Percona Forums.