#
Check Persistence
Checks can persist information between runs. This can for example be useful for monitoring relative increases of a metric instead of absolute thresholds.
Persistence in checks is based on the file-system. Write all files that you want to persist
to the $CHECKSON_DIR/persistent
folder. When the next run is executed, the $CHECKSON_DIR/persistent
will restored with the contents that the current run wrote to it.
CHECKSON_DIR
is an environment variable that is set by the Checkson cloud executor when it runs your
Docker image. You will have to create the persistent
subfolder before you create files in there.
Let's look at an example:
import sys
import os
checkson_dir = os.environ.get('CHECKSON_DIR', '/tmp')
persistent_dir = f"{checkson_dir}/persistent"
result_file = f"{persistent_dir}/result"
def write_result(result):
if not os.path.exists(persistent_dir):
print(f"Creating {persistent_dir}")
os.makedirs(persistent_dir)
print(f"Persisting result '{result}' to {result_file}")
with open(result_file, "w") as f:
f.write(str(result))
def read_last_result():
if not os.path.exists(result_file):
print(f"No result file found: {result_file}")
return False
with open(result_file) as f:
last_result = f.read().strip()
print(f"Persisted last result: {last_result}")
return "True" == last_result
def main():
last_result = read_last_result()
result = not last_result
write_result(result)
print(f"Last result: {last_result}, new result: {result}")
if result:
print("Check successful")
sys.exit(0)
else:
print("Check unsuccessful")
sys.exit(1)
if __name__ == "__main__":
main()
This check will alternate between successful and unsuccessful runs. It does that by
writing the result into the file $CHECKSON_DIR/persistent/result
. Before writing
the file, it creates the folder $CHECKSON_DIR/persistent
.
If the environment $CHECKSON_DIR
is not set, the example uses /tmp
as a fallback.
This is useful for testing the script locally, so you do not have to set the environment
variable.
The size of the files in $CHECKSON_DIR/persistent
should not exceed 50 KiB.
The complete example can be found on GitHub.