Skip to content

Commit

Permalink
Merge pull request #37 from NETWAYS/feature/getenv
Browse files Browse the repository at this point in the history
Add option to set flags via env variables and read password from file
  • Loading branch information
martialblog authored Sep 16, 2024
2 parents 1cafa1f + 4b9fe86 commit bd40556
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 2 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,18 @@ options:
-U USER, --user USER user name for the database connections
-p PASSWORD, --password PASSWORD
password for the database connections
password for the database connections (CHECK_BAREOS_DATABASE_PASSWORD)
--password-file PASSWORD_FILE
path to a password file. Can be the bareos-dir.conf
-H HOST, --Host HOST database host
-P PORT, --port PORT database port
-d DATABASE, --database DATABASE
database name
-v, --version show program's version number and exit
```

Various flags can be set with environment variables, refer to the help to see which flags.

## Job

Check the status of Bareos Jobs.
Expand Down
46 changes: 45 additions & 1 deletion check_bareos.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import argparse
import sys
import re
import os
import psycopg2
import psycopg2.extras

Expand Down Expand Up @@ -57,6 +58,30 @@
}


def read_password_from_file(fp):
"""
Tries to read a password from the given file
This allows to extract the password from the Bareos configuration
or from any other file that contains 'Password = secretpassword'
"""
l = []
password = None
# Extract the password from the given file
with open(fp, encoding='utf-8') as pwfile:
for line in pwfile:
line = line.strip()
if 'Password' in line:
l = line.split()
# Validate that we got a password
try:
password = l[2]
except IndexError:
pass
if not password:
raise ValueError('No password found in', fp)

return password

def check_threshold(value, warning, critical):
# checks a value against warning and critical thresholds
if critical is not None:
Expand Down Expand Up @@ -562,10 +587,25 @@ def printNagiosOutput(checkResult):


def commandline(args):
"""
Parse commandline arguments.
"""
def environ_or_required(key):
return ({'default': os.environ.get(key)} if os.environ.get(key) else {})

parser = argparse.ArgumentParser(description='Check Plugin for Bareos Backup Status')
group = parser.add_argument_group()
group.add_argument('-U', '--user', dest='user', action='store', required=True, help='user name for the database connections')
group.add_argument('-p', '--password', dest='password', action='store', help='password for the database connections', default="")

password_group = group.add_mutually_exclusive_group()

password_group.add_argument('-p', '--password', dest='password', action='store',
**environ_or_required('CHECK_BAREOS_DATABASE_PASSWORD'),
help='password for the database connections (CHECK_BAREOS_DATABASE_PASSWORD)')
password_group.add_argument('--password-file', dest='password_file', action='store',
default='/etc/bareos/bareos-dir.conf',
help='path to a password file. Can be the bareos-dir.conf')

group.add_argument('-H', '--Host', dest='host', action='store', help='database host', default="127.0.0.1")
group.add_argument('-P', '--port', dest='port', action='store', help='database port', default=5432, type=int)
group.add_argument('-d', '--database', dest='database', default='bareos', help='database name')
Expand Down Expand Up @@ -708,6 +748,10 @@ def checkStatus(args):
if __name__ == '__main__': # pragma: no cover
try:
ARGS = commandline(sys.argv[1:])

if ARGS.password_file and not ARGS.password:
ARGS.password = read_password_from_file(ARGS.password_file)

ARGS.func(ARGS)
except SystemExit:
# Re-throw the exception
Expand Down
4 changes: 4 additions & 0 deletions contrib/bareos-dir.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Director {
Name = bareos-dir
Password = secretpassword
}
19 changes: 19 additions & 0 deletions test_check_bareos.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

import unittest
import unittest.mock as mock
import os
import sys

sys.path.append('..')


from check_bareos import commandline
from check_bareos import read_password_from_file
from check_bareos import createBackupKindString
from check_bareos import createFactor
from check_bareos import printNagiosOutput
Expand Down Expand Up @@ -38,6 +40,16 @@ def test_commandline(self):
self.assertEqual(actual.host, 'localhost')
self.assertEqual(actual.user, 'bareos')


def test_commandline_fromenv(self):
os.environ['CHECK_BAREOS_DATABASE_PASSWORD'] = 'secret'

actual = commandline(['-H', 'localhost', '-U', 'bareos'])
self.assertEqual(actual.user, 'bareos')
self.assertEqual(actual.password, 'secret')

os.unsetenv('CHECK_BAREOS_DATABASE_PASSWORD')

class ThresholdTesting(unittest.TestCase):

def test_thresholds(self):
Expand Down Expand Up @@ -91,6 +103,13 @@ def test_printNagiosOutput(self, mock_print):
actual = printNagiosOutput({'returnCode': 1, 'returnMessage': "bar", 'performanceData': 'foo'})
self.assertEqual(sysexit.exception.code, 1)

def test_read_password_from_file(self):
actual = read_password_from_file('contrib/bareos-dir.conf')
expected = 'secretpassword'
self.assertEqual(actual, expected)

with self.assertRaises(FileNotFoundError) as sysexit:
read_password_from_file('contrib/nosuch')

class SQLTesting(unittest.TestCase):

Expand Down

0 comments on commit bd40556

Please sign in to comment.