Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/bareos/bareos.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFrank Ueberschar <frank.ueberschar@bareos.com>2021-03-11 14:43:19 +0300
committerFrank Ueberschar <frank.ueberschar@bareos.com>2021-03-11 14:43:19 +0300
commita858176f44188e33bdc41e714fac7f11c7dfecb4 (patch)
tree5e593491f41e6b1758910606eeb63729c5c75125 /contrib
parentdcba064a29e02883b2a7f16dc04ac7922f3c89df (diff)
parentddb51476a56cda95dd56fea2f54a3ffca98ac4b8 (diff)
Add 'contrib/' from commit 'ddb51476a56cda95dd56fea2f54a3ffca98ac4b8'
git-subtree-dir: contrib git-subtree-mainline: dcba064a29e02883b2a7f16dc04ac7922f3c89df git-subtree-split: ddb51476a56cda95dd56fea2f54a3ffca98ac4b8
Diffstat (limited to 'contrib')
-rw-r--r--contrib/.gitignore1
-rw-r--r--contrib/README.md12
-rw-r--r--contrib/dir-plugins/README.md1
-rw-r--r--contrib/dir-plugins/graphite/BareosDirPluginGraphiteSender.py120
-rw-r--r--contrib/dir-plugins/graphite/README.md31
-rw-r--r--contrib/dir-plugins/graphite/bareos-dir-graphite-sender.py49
-rw-r--r--contrib/dir-plugins/nagios_icinga/BareosDirPluginNscaSender.py130
-rw-r--r--contrib/dir-plugins/nagios_icinga/README.md26
-rw-r--r--contrib/dir-plugins/nagios_icinga/bareos-dir-nsca-sender.py53
-rw-r--r--contrib/dir-plugins/nagios_icinga/check_bareos_jobs.ncfg91
-rw-r--r--contrib/fd-plugins/README.md29
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/BareosFdTaskClass.py334
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/LICENSE.md660
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/README.md52
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/__init__.py0
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/mysql/BareosFdMySQLClass.py88
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/mysql/README.md71
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/mysql/__init__.py0
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/mysql/bareos-fd-mysql.py28
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/oracle/BareosFdOracleClass.py58
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/oracle/README.md74
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/oracle/__init__.py0
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/oracle/bareos-fd-oracle.py28
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/pgsql/BareosFdPgSQLClass.py92
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/pgsql/README.md71
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/pgsql/__init__.py0
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/pgsql/bareos-fd-pgsql.py28
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/xenserver/BareosFdXenServerClass.py75
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/xenserver/README.md66
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/xenserver/__init__.py0
-rw-r--r--contrib/fd-plugins/bareos-tasks-plugins/xenserver/bareos-fd-xenserver.py28
-rw-r--r--contrib/fd-plugins/bareos_elasticsearch/BareosFdPluginElasticsearch.py83
-rw-r--r--contrib/fd-plugins/bareos_elasticsearch/README.md80
-rw-r--r--contrib/fd-plugins/bareos_elasticsearch/bareos-fd-elasticsearch.py26
-rwxr-xr-xcontrib/fd-plugins/mysql-python/BareosFdMySQLclass.py285
-rw-r--r--contrib/fd-plugins/mysql-python/README.md90
-rw-r--r--contrib/fd-plugins/mysql-python/bareos-fd-mysql.py26
-rw-r--r--contrib/fd-plugins/options-plugin-sample/BareosFdPluginFileInteract.py28
-rw-r--r--contrib/fd-plugins/options-plugin-sample/README.md33
-rw-r--r--contrib/fd-plugins/options-plugin-sample/bareos-fd-file-interact.py26
-rw-r--r--contrib/fd-plugins/plugins_intro.pdfbin0 -> 511420 bytes
-rwxr-xr-xcontrib/misc/bareos-migrate-config/bareos-migrate-config.sh46
-rw-r--r--contrib/misc/bareos_pam_integration/README.rst173
-rwxr-xr-xcontrib/misc/bareos_pam_integration/pam_exec_add_bareos_user.py145
-rw-r--r--contrib/misc/bsmc/LICENSE662
-rw-r--r--contrib/misc/bsmc/README.md55
-rwxr-xr-xcontrib/misc/bsmc/bin/bsmc442
-rw-r--r--contrib/misc/bsmc/debian/compat1
-rw-r--r--contrib/misc/bsmc/debian/control14
-rw-r--r--contrib/misc/bsmc/debian/install3
-rwxr-xr-xcontrib/misc/bsmc/debian/rules7
-rw-r--r--contrib/misc/bsmc/debian/source/format1
-rw-r--r--contrib/misc/bsmc/etc/bareos/bareos-dir.d/archivejob.conf53
-rw-r--r--contrib/misc/bsmc/etc/bareos/bsmc.conf13
-rw-r--r--contrib/misc/bsmc/packaging/bareos-bsmc.changes5
-rw-r--r--contrib/misc/bsmc/packaging/bareos-bsmc.dsc10
-rw-r--r--contrib/misc/bsmc/packaging/bareos-bsmc.spec46
-rw-r--r--contrib/misc/bsmc/packaging/debian.debtransform1
-rw-r--r--contrib/misc/performance/graphite/README.md69
-rwxr-xr-xcontrib/misc/performance/graphite/bareos-graphite-poller.py439
-rw-r--r--contrib/misc/performance/graphite/graphite-poller.conf9
-rw-r--r--contrib/misc/recover_single_job_from_dbdump/README.md34
-rwxr-xr-xcontrib/misc/recover_single_job_from_dbdump/split_bareos_pg_dump.py18
-rw-r--r--contrib/misc/triggerjob/README.md37
-rwxr-xr-xcontrib/misc/triggerjob/triggerjob.py93
-rw-r--r--contrib/sd-plugins/README.md1
66 files changed, 5350 insertions, 0 deletions
diff --git a/contrib/.gitignore b/contrib/.gitignore
new file mode 100644
index 000000000..485dee64b
--- /dev/null
+++ b/contrib/.gitignore
@@ -0,0 +1 @@
+.idea
diff --git a/contrib/README.md b/contrib/README.md
new file mode 100644
index 000000000..c2163eb1a
--- /dev/null
+++ b/contrib/README.md
@@ -0,0 +1,12 @@
+bareos-contrib
+==============
+
+External contributions of unsupported code and scripts
+
+Contributions and LICENSE
+
+If you want to contribute: please fork this repository, add your stuff and send format patches or pull requests.
+
+All stuff in this repository is open source and licensed AGPL v3.
+
+Anyone contributing to this repository fully accepts AGPLv3 and confirms that he/she has the right to publish his/her software under the AGPLv3 license.
diff --git a/contrib/dir-plugins/README.md b/contrib/dir-plugins/README.md
new file mode 100644
index 000000000..8a8465cec
--- /dev/null
+++ b/contrib/dir-plugins/README.md
@@ -0,0 +1 @@
+This directory is intended for Python Director plugins. Please use a subdirectory for each plugin.
diff --git a/contrib/dir-plugins/graphite/BareosDirPluginGraphiteSender.py b/contrib/dir-plugins/graphite/BareosDirPluginGraphiteSender.py
new file mode 100644
index 000000000..efeefa10d
--- /dev/null
+++ b/contrib/dir-plugins/graphite/BareosDirPluginGraphiteSender.py
@@ -0,0 +1,120 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# BAREOS - Backup Archiving REcovery Open Sourced
+#
+# Copyright (C) 2014-2014 Bareos GmbH & Co. KG
+#
+# This program is Free Software; you can redistribute it and/or
+# modify it under the terms of version three of the GNU Affero General Public
+# License as published by the Free Software Foundation, which is
+# listed in the file LICENSE.
+#
+# This program 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
+# Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# Author: Kozlov Alexander
+#
+# GraphiteSender for Bareos python plugins
+# Functions taken and adapted from bareos-dir.py
+
+from bareosdir import *
+from bareos_dir_consts import *
+import BareosDirPluginBaseclass
+from socket import socket, AF_INET, SOCK_STREAM
+import time
+
+
+class BareosDirPluginGraphiteSender(BareosDirPluginBaseclass.BareosDirPluginBaseclass):
+ ''' Bareos DIR python plugin Nagios / Icinga sender class '''
+
+ def parse_plugin_definition(self, context, plugindef):
+ '''
+ Check, if mandatory monitoringHost is set and set default for other unset parameters
+ '''
+ super(BareosDirPluginGraphiteSender, self).parse_plugin_definition(
+ context, plugindef)
+ # monitoring Host is mandatory
+ if 'collectorHost' not in self.options:
+ self.collectorHost = "graphite"
+ else:
+ self.collectorHost = self.options['collectorHost']
+ if 'collectorPort' not in self.options:
+ self.collectorPort = 2003
+ else:
+ self.collectorPort = int(self.options['collectorPort'])
+ if 'metricPrefix' not in self.options:
+ self.metricPrefix = 'apps'
+ else:
+ self.metricPrefix = self.options['metricPrefix']
+ # we return OK in anyway, we do not want to produce Bareos errors just because of failing
+ # Nagios notifications
+ return bRCs['bRC_OK']
+
+ def handle_plugin_event(self, context, event):
+ '''
+ This method is calle for every registered event
+ '''
+
+ # We first call the method from our superclass to get job attributes read
+ super(BareosDirPluginGraphiteSender, self).handle_plugin_event(context, event)
+
+ if event == bDirEventType['bDirEventJobEnd']:
+ # This event is called at the end of a job, here evaluate the results
+ self.evaluateJobStatus(context)
+ self.transmitResult(context)
+
+ return bRCs['bRC_OK']
+
+ def evaluateJobStatus(self, context):
+ '''
+ Depending on the jobStatus we compute monitoring status and monitoring message
+ You may overload this method to adjust messages
+ '''
+ self.metrics = {}
+ job = '_'.join(self.jobName.split('.')[:-3])
+ if (self.jobStatus == 'E' or self.jobStatus == 'f'):
+ self.metrics['bareos.jobs.{}.status.error'.format(job)] = 1
+ elif (self.jobStatus == 'W'):
+ self.metrics['bareos.jobs.{}.status.warning'.format(job)] = 1
+ elif (self.jobStatus == 'T'):
+ self.metrics['bareos.jobs.{}.status.success'.format(job)] = 1
+ self.metrics['bareos.jobs.{}.jobbytes'.format(job)] = self.jobBytes
+ self.metrics['bareos.jobs.{}.jobfiles'.format(job)] = self.jobFiles
+ self.metrics['bareos.jobs.{}.runningtime'.format(job)] = self.jobRunningTime
+ self.metrics['bareos.jobs.{}.throughput'.format(job)] = self.throughput
+ else:
+ self.metrics['bareos.jobs.{}.status.other'.format(job)] = 1
+
+ DebugMessage(context, 100, "Graphite metrics: {}\n".format(self.metrics))
+
+ def transmitResult(self, context):
+ '''
+ Here we send the result to the Icinga / Nagios server using NSCA
+ Overload this method if you want ot submit your changes on a different way
+ '''
+ DebugMessage(context, 100, "Submitting metrics to {}:{}".format(self.collectorHost,
+ self.collectorPort))
+ try:
+ sock = socket(AF_INET, SOCK_STREAM)
+ sock.connect((self.collectorHost, self.collectorPort))
+ for key, value in self.metrics.items():
+ sock.send('{prefix}.{key} {value} {time}\n'.format(prefix=self.metricPrefix,
+ key=key,
+ value=value,
+ time=int(time.time())))
+ sock.close()
+ except Exception as e:
+ JobMessage(context, bJobMessageType['M_WARNING'],
+ "Plugin {} could not transmit check result to {}:{}: {}\n".format(self.__class__,
+ self.collectorHost,
+ self.collectorPort,
+ e.message))
+
+# vim: ts=4 tabstop=4 expandtab shiftwidth=4 softtabstop=4
diff --git a/contrib/dir-plugins/graphite/README.md b/contrib/dir-plugins/graphite/README.md
new file mode 100644
index 000000000..e4b83ddb0
--- /dev/null
+++ b/contrib/dir-plugins/graphite/README.md
@@ -0,0 +1,31 @@
+This plugin implements a statistics sender to Graphite.
+
+Usage
+
+In bareos-dir.conf enable director plugins and load the Python plugin:
+
+ Director {
+ Plugin Directory = /usr/lib64/bareos/plugins
+ Plugin Names = "python"
+ # ...
+ }
+
+In your JobDefs or Job Definition configure the plugin itself:
+
+ Job {
+ Name = "BackupClient1"
+ DIR Plugin Options ="python:module_path=/usr/lib64/bareos/plugins:module_name=bareos-dir-graphite-sender:collectorHost=graphite:collectorPort=2003:metricPrefix=app"
+ JobDefs = "DefaultJob"
+ }
+
+* collectorHost (default graphite): IP our resolvable address of your graphite host
+* collectorPort (default 2003): graphite server port
+* metricPrefix (default apps) : prefix, added to all metric names
+
+Metrics
+
+* <metricPrefix>.bareos.jobs.<jobName>.status.(error|warning|success)
+* <metricPrefix>.bareos.jobs.<jobName>.jobbytes
+* <metricPrefix>.bareos.jobs.<jobName>.jobfiles
+* <metricPrefix>.bareos.jobs.<jobName>.runningtime
+* <metricPrefix>.bareos.jobs.<jobName>.throughput
diff --git a/contrib/dir-plugins/graphite/bareos-dir-graphite-sender.py b/contrib/dir-plugins/graphite/bareos-dir-graphite-sender.py
new file mode 100644
index 000000000..9787f85ea
--- /dev/null
+++ b/contrib/dir-plugins/graphite/bareos-dir-graphite-sender.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# BAREOS - Backup Archiving REcovery Open Sourced
+#
+# Copyright (C) 2014-2014 Bareos GmbH & Co. KG
+#
+# This program is Free Software; you can redistribute it and/or
+# modify it under the terms of version three of the GNU Affero General Public
+# License as published by the Free Software Foundation, which is
+# listed in the file LICENSE.
+#
+# This program 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
+# Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# Author: Kozlov Alexander
+#
+
+# Provided by the Bareos Dir Python plugin interface
+import bareos_dir_consts
+
+# This module contains the wrapper functions called by the Bareos-Dir, the
+# functions call the corresponding methods from your plugin class
+import BareosDirWrapper
+from BareosDirWrapper import *
+
+# This module contains the used plugin class
+import BareosDirPluginGraphiteSender
+
+
+def load_bareos_plugin(context, plugindef):
+ '''
+ This function is called by the Bareos-Dir to load the plugin
+ We use it to instantiate the plugin class
+ '''
+ # BareosDirWrapper.bareos_dir_plugin_object is the module attribute that
+ # holds the plugin class object
+ BareosDirWrapper.bareos_dir_plugin_object = \
+ BareosDirPluginGraphiteSender.BareosDirPluginGraphiteSender(
+ context, plugindef)
+ return bareos_dir_consts.bRCs['bRC_OK']
+
+# the rest is done in the Plugin module
diff --git a/contrib/dir-plugins/nagios_icinga/BareosDirPluginNscaSender.py b/contrib/dir-plugins/nagios_icinga/BareosDirPluginNscaSender.py
new file mode 100644
index 000000000..1dfc11580
--- /dev/null
+++ b/contrib/dir-plugins/nagios_icinga/BareosDirPluginNscaSender.py
@@ -0,0 +1,130 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# BAREOS - Backup Archiving REcovery Open Sourced
+#
+# Copyright (C) 2014-2014 Bareos GmbH & Co. KG
+#
+# This program is Free Software; you can redistribute it and/or
+# modify it under the terms of version three of the GNU Affero General Public
+# License as published by the Free Software Foundation, which is
+# listed in the file LICENSE.
+#
+# This program 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
+# Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# Author: Maik Aussendorf
+#
+# NscaSender for Bareos python plugins
+# Functions taken and adapted from bareos-dir.py
+
+from bareosdir import *
+from bareos_dir_consts import *
+import BareosDirPluginBaseclass
+import pynsca
+
+class BareosDirPluginNscaSender(BareosDirPluginBaseclass.BareosDirPluginBaseclass):
+ ''' Bareos DIR python plugin Nagios / Icinga sender class '''
+
+ def parse_plugin_definition(self, context, plugindef):
+ '''
+ Check, if mandatory monitoringHost is set and set default for other unset parameters
+ '''
+ super(BareosDirPluginNscaSender, self).parse_plugin_definition(
+ context, plugindef)
+ # monitoring Host is mandatory
+ if not 'monitorHost' in self.options:
+ JobMessage(context, bJobMessageType['M_WARNING'], "Plugin %s needs parameter 'monitorHost' specified\n" %(self.__class__))
+ self.monitorHost = ""
+ else:
+ self.monitorHost = self.options['monitorHost']
+ if not 'encryption' in self.options:
+ DebugMessage(context, 100, "Paraemter encryption not set for plugin %s. Setting to 1 (XOR nsca default)" %(self.__class__))
+ self.encryption= 1; # XOR is nsca default
+ else:
+ self.encryption = int(self.options['encryption'])
+ if not 'monitorPort' in self.options:
+ self.monitorPort = 5667
+ else:
+ self.monitorPort = int(self.options['monitorPort'])
+ if not 'checkHost' in self.options:
+ self.checkHost = 'bareos'
+ else:
+ self.checkHost = self.options['checkHost']
+ if not 'checkService' in self.options:
+ self.checkService = 'backup_job'
+ else:
+ self.checkService = self.options['checkService']
+ # we return OK in anyway, we do not want to produce Bareos errors just because of failing
+ # Nagios notifications
+ return bRCs['bRC_OK']
+
+ def handle_plugin_event(self, context, event):
+ '''
+ This method is calle for every registered event
+ '''
+
+ # We first call the method from our superclass to get job attributes read
+ super(BareosDirPluginNscaSender, self).handle_plugin_event(context, event)
+
+ if event == bDirEventType['bDirEventJobEnd']:
+ # This event is called at the end of a job, here evaluate the results
+ self.evaluateJobStatus (context)
+ self.transmitResult (context)
+
+ return bRCs['bRC_OK'];
+
+
+ def evaluateJobStatus(self,context):
+ '''
+ Depending on the jobStatus we compute monitoring status and monitoring message
+ You may overload this method to adjust messages
+ '''
+ self.nagiosMessage = "";
+ coreMessage = "Bareos job %s on %s with id %d level %s, %d errors, %d jobBytes, %d files terminated with status %s" \
+ %(self.jobName, self.jobClient, self.jobId, self.jobLevel, self.jobErrors, self.jobBytes, self.jobFiles, self.jobStatus)
+ if (self.jobStatus == 'E' or self.jobStatus == 'f'):
+ self.nagiosResult = 2; # critical
+ self.nagiosMessage = "CRITICAL: %s" %coreMessage
+ elif (self.jobStatus == 'W'):
+ self.nagiosResult = 1; # warning
+ self.nagiosMessage = "WARNING: %s" %coreMessage
+ elif (self.jobStatus == 'A'):
+ self.nagiosResult = 1; # warning
+ self.nagiosMessage = "WARNING: %s CANCELED" %coreMessage
+ elif (self.jobStatus == 'T'):
+ self.nagiosResult = 0; # OK
+ self.nagiosMessage = "OK: %s" %coreMessage
+ else:
+ self.nagiosResult = 3; # unknown
+ self.nagiosMessage = "UNKNOWN: %s" %coreMessage
+
+ # Performance data according Nagios developer guide
+ self.perfstring = "|Errors=%d;;;; Bytes=%d;;;; Files=%d;;;; Throughput=%dB/s;;;; jobRuntime=%ds;;;; jobTotalTime=%ds;;;;" \
+ % (self.jobErrors, self.jobBytes, self.jobFiles, self.throughput, self.jobRunningTime, self.jobTotalTime)
+
+ DebugMessage(context, 100, "Nagios Code: %d, NagiosMessage: %s\n" %(self.nagiosResult,self.nagiosMessage));
+ DebugMessage(context, 100, "Performance data: %s\n" %self.perfstring)
+
+
+ def transmitResult(self,context):
+ '''
+ Here we send the result to the Icinga / Nagios server using NSCA
+ Overload this method if you want ot submit your changes on a different way
+ '''
+ DebugMessage(context, 100, "Submitting check result to host %s, encryption: %d, Port: %d\n" \
+ %(self.monitorHost,self.encryption, self.monitorPort))
+ try:
+ notif = pynsca.NSCANotifier(self.monitorHost,self.monitorPort, self.encryption)
+ notif.svc_result(self.checkHost, self.checkService, self.nagiosResult, self.nagiosMessage + self.perfstring)
+ except:
+ JobMessage(context, bJobMessageType['M_WARNING'], "Plugin %s could not transmit check result to host %s, port %d\n"\
+ %(self.__class__, self.monitorHost, self.monitorPort))
+
+# vim: ts=4 tabstop=4 expandtab shiftwidth=4 softtabstop=4
diff --git a/contrib/dir-plugins/nagios_icinga/README.md b/contrib/dir-plugins/nagios_icinga/README.md
new file mode 100644
index 000000000..f4a3298b3
--- /dev/null
+++ b/contrib/dir-plugins/nagios_icinga/README.md
@@ -0,0 +1,26 @@
+This plugin uses the baseclass and implements a sender to Icinga / Nagios using the NSCA protocol.
+It needs the pynsca module from https://github.com/djmitche/pynsca.
+
+Usage
+
+In bareos-dir.conf enable director plugins and load the Python plugin:
+
+ Director {
+ Plugin Directory = /usr/lib64/bareos/plugins
+ Plugin Names = "python"
+ # ...
+ }
+
+In your JobDefs or Job Definition configure the plugin itself:
+
+ Job {
+ Name = "BackupClient1"
+ DIR Plugin Options ="python:module_path=/usr/lib64/bareos/plugins:module_name=bareos-dir-nsca-sender:monitorHost=your.monitor.server:checkHost=bareos:checkService=bareos_job_client1:encryption=1"
+ JobDefs = "DefaultJob"
+ }
+
+* monitorHost: IP our resolvable address of your Icinga/Nagios host
+* checkHost: the host name for your check result
+* checkService: the service name for your result
+* encryption=1 nsca encryption method
+* monitorPort (default 5667), nsca port
diff --git a/contrib/dir-plugins/nagios_icinga/bareos-dir-nsca-sender.py b/contrib/dir-plugins/nagios_icinga/bareos-dir-nsca-sender.py
new file mode 100644
index 000000000..52907ebe7
--- /dev/null
+++ b/contrib/dir-plugins/nagios_icinga/bareos-dir-nsca-sender.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# BAREOSĀ® - Backup Archiving REcovery Open Sourced
+#
+# Copyright (C) 2014-2014 Bareos GmbH & Co. KG
+#
+# This program is Free Software; you can redistribute it and/or
+# modify it under the terms of version three of the GNU Affero General Public
+# License as published by the Free Software Foundation, which is
+# listed in the file LICENSE.
+#
+# This program 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
+# Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# Bareos-dir-local-fileset a simple example for a python Bareos Dir Plugin using
+# BareosDirPluginBaseclass. The plugin argument 'filename' is used to read
+# all files listed in that file and add it to the fileset
+#
+# Author: Maik Aussendorf
+#
+
+# Provided by the Bareos Dir Python plugin interface
+import bareos_dir_consts
+
+# This module contains the wrapper functions called by the Bareos-Dir, the
+# functions call the corresponding methods from your plugin class
+import BareosDirWrapper
+from BareosDirWrapper import *
+
+# This module contains the used plugin class
+import BareosDirPluginNscaSender
+
+
+def load_bareos_plugin(context, plugindef):
+ '''
+ This function is called by the Bareos-Dir to load the plugin
+ We use it to instantiate the plugin class
+ '''
+ # BareosDirWrapper.bareos_dir_plugin_object is the module attribute that
+ # holds the plugin class object
+ BareosDirWrapper.bareos_dir_plugin_object = \
+ BareosDirPluginNscaSender.BareosDirPluginNscaSender(
+ context, plugindef)
+ return bareos_dir_consts.bRCs['bRC_OK']
+
+# the rest is done in the Plugin module
diff --git a/contrib/dir-plugins/nagios_icinga/check_bareos_jobs.ncfg b/contrib/dir-plugins/nagios_icinga/check_bareos_jobs.ncfg
new file mode 100644
index 000000000..76cc9944c
--- /dev/null
+++ b/contrib/dir-plugins/nagios_icinga/check_bareos_jobs.ncfg
@@ -0,0 +1,91 @@
+# ---
+# NagiosGrapher Template for Bareos_job-related checks
+# ---
+
+# Usually backup jobs run on a daily basis, this means performance data are only transmitted once a day.
+# It may take up to 3 days before you actually get a graph.
+
+# EXTERNAL COMMAND: PROCESS_SERVICE_CHECK_RESULT;localhost;bareos_config;0;OK: Bareos job theseus-server-config.2014-11-24_11.09.24_09 on theseus-fd with id 15818 level I, 0 errors, 47577 jobBytes, 15 files terminated with status T|Errors=0;;;; Bytes=47577;;;; Files=15;;;; Throughput=3987B/s;;;; jobRuntime=11s;;;; jobTotalTime=13s;;;;
+
+define ngraph{
+ service_name bareos_job
+ graph_perf_regex Errors=(\d+)
+ graph_value Errors
+ graph_units
+ graph_legend Errors per Job
+ rrd_plottype AREA
+ rrd_color ff0000
+ step 86400
+ page Errors
+ heartbeat 120000
+}
+
+
+
+define ngraph{
+ service_name bareos_job
+ graph_perf_regex Files=(\d+)
+ graph_value Files
+ graph_units
+ graph_legend Files per Job
+ rrd_plottype AREA
+ rrd_color 0000ff
+ step 86400
+ page Files
+ heartbeat 120000
+}
+
+define ngraph{
+ service_name bareos_job
+ graph_perf_regex Bytes=(\d+)
+ graph_value Bytes
+ graph_units B
+ graph_legend Bytes per Job
+ rrd_plottype AREA
+ rrd_color 00ff00
+ step 86400
+ page JobBytes
+ heartbeat 120000
+}
+
+define ngraph{
+ service_name bareos_job
+ graph_perf_regex Throughput=(\d+)
+ graph_value Throughput
+ graph_units B/s
+ graph_legend Bytes/s
+ rrd_plottype AREA
+ rrd_color 00ff00
+ step 86400
+ page Throughput
+ heartbeat 120000
+}
+
+
+define ngraph{
+ service_name bareos_job
+ graph_perf_regex jobRuntime=(\d+)
+ graph_value jobRuntime
+ graph_units Seconds
+ graph_legend Effective Job Runtime
+ rrd_plottype LINE3
+ rrd_color 00ff00
+ page Time
+ step 86400
+ heartbeat 120000
+}
+
+define ngraph{
+ service_name bareos_job
+ graph_perf_regex jobTotalTime=(\d+)
+ graph_value jobTotalTime
+ graph_units Seconds
+ graph_legend Job Total Time
+ rrd_plottype AREA
+ rrd_color ff0000
+ page Time
+ step 86400
+ heartbeat 120000
+}
+
+# [EOF]
diff --git a/contrib/fd-plugins/README.md b/contrib/fd-plugins/README.md
new file mode 100644
index 000000000..930b7b68f
--- /dev/null
+++ b/contrib/fd-plugins/README.md
@@ -0,0 +1,29 @@
+This directory is intended for Python FD plugins. Please use a subdirectory for each plugin.
+
+Please add a little documentation with a working configuration snippet to your contributions.
+
+
+## Sample pyhon plugins for Bareos FD
+
+### Introduction
+
+Bacula's FD plugin interface calls C-functions at certain entry points in the FD code. Developing plugins required deep C-knowledge. In Bareos this plugin interface has been extended with python bindings (since version 13.4, you need the latest master version, it's not in the current stable release 13.2). This allows developers to write FD plugins in Python.
+
+Documentation is yet to be written, this README gives some starting points and examples but is not intended to replace full documentation. We hope to encourage people to use the Python interface to develop their own plugins to suite their needs.
+
+Any help by means of documentation, new plugins, feedback is appreciated.
+
+
+### The sample plugin shipped with Bareos
+
+
+The package `bareos-filedaemon-python-plugin` contains a sample plugin `/usr/lib64/bareos/plugins/bareos-fd.py` which implements needed functions for a bareos-fd-plugin in python. It takes the plugin option 'filename' and adds it to the fileset.
+
+A class based approach
+
+This sample plugin consists of set of functions that are called by the Bareos FD at certain points. Since I prefer to use classes; I've written a little wrapper class, that makes it hopefully easier to program python plugins using a base class.
+
+The base class and a class based example is now part of the package `bareos-filedaemon-python-plugin`
+
+Please read the Wiki page to learn more about the plugins: https://github.com/aussendorf/bareos-fd-python-plugins/wiki
+
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/BareosFdTaskClass.py b/contrib/fd-plugins/bareos-tasks-plugins/BareosFdTaskClass.py
new file mode 100644
index 000000000..97913fda7
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/BareosFdTaskClass.py
@@ -0,0 +1,334 @@
+#!/usr/bin/env python
+# -*- Mode: Python; tab-width: 4 -*-
+#
+# Bareos FileDaemon Task plugin
+# Copyright (C) 2018 Marco Lertora <marco.lertora@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program 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 Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import os
+import subprocess
+from StringIO import StringIO
+from fcntl import fcntl, F_GETFL, F_SETFL
+from pwd import getpwnam
+
+from bareosfd import JobMessage, DebugMessage, StatPacket, GetValue
+from bareos_fd_consts import bRCs, bIOPS, bJobMessageType, bFileType, bVariable
+from BareosFdPluginBaseclass import BareosFdPluginBaseclass
+
+
+bJobType = dict(
+ BACKUP=66,
+ PREVIOUS=77,
+ VERIFY=86,
+ RESTORE=82,
+ CONSOLE=99,
+ COPY=67,
+ INTERNAL=73,
+ ADMIN=68,
+ ARCHIVE=65,
+ MIGRATION=103,
+ SCAN=83,
+)
+
+
+class TaskException(Exception):
+ pass
+
+
+class Task(object):
+ task_name = 'unknown'
+ file_extension = 'dump'
+ block_size = 65536
+ unknown_size = 0
+ pool_counter = 0
+ pool_interval = 100
+
+ def get_name(self):
+ return self.task_name
+
+ def get_details(self):
+ return self.get_name()
+
+ def get_next_tasks(self):
+ return list()
+
+ def get_filename(self):
+ return '{0}.{1}'.format(self.get_name(), self.file_extension)
+
+ def get_size(self):
+ return self.unknown_size
+
+ def get_block_size(self):
+ return self.block_size
+
+ def task_pool(self):
+ self.pool_counter = (self.pool_counter % self.pool_interval) + 1
+ if self.pool_counter == self.pool_interval:
+ self.pool()
+
+ def pool(self):
+ return
+
+ def task_open(self):
+ return
+
+ def task_read(self, buf):
+ raise Exception('need to be override')
+
+ def task_close(self):
+ return
+
+ def task_wait(self):
+ return 0
+
+
+class TaskStringIO(Task):
+ file_extension = 'log'
+
+ def __init__(self, task_name, data):
+ self.task_name = task_name
+ self.data = data
+
+ def task_open(self):
+ self.data.seek(0)
+
+ def task_read(self, buf):
+ chunk = self.data.read(len(buf))
+ buf[:len(chunk)] = chunk
+ return len(chunk)
+
+
+class TaskProcess(Task):
+ process = None
+ run_as_user = None
+ run_environ = dict()
+ command = list()
+ use_stdout = True
+ use_stderr = True
+ stderr_buffer = StringIO()
+
+ def get_details(self):
+ sep = ' '
+ return '{0} {1}'.format(self.get_name(), sep.join(self.command))
+
+ def get_next_tasks(self):
+ tasks = list()
+ if self.use_stderr:
+ tasks.append(TaskStringIO(self.get_name() + '-stderr', self.stderr_buffer))
+ return tasks
+
+ def pre_run_execute(self):
+ if self.run_as_user:
+ item = getpwnam(self.run_as_user)
+ os.chdir(item.pw_dir)
+ os.setgid(item.pw_gid)
+ os.setuid(item.pw_uid)
+
+ for key, value in self.run_environ.items():
+ os.environ[key] = value
+
+ def execute_command(self, command):
+ try:
+ return subprocess.check_output(command, shell=False, bufsize=-1,
+ preexec_fn=self.pre_run_execute)
+ except (subprocess.CalledProcessError, OSError, ValueError), e:
+ raise TaskException(e)
+
+ def pool(self):
+ if self.use_stderr:
+ try:
+ self.stderr_buffer.write(self.process.stderr.read())
+ except IOError:
+ pass
+
+ def task_open(self):
+ try:
+ self.process = subprocess.Popen(self.command, shell=False, bufsize=-1,
+ stdout=subprocess.PIPE if self.use_stdout else None,
+ stderr=subprocess.PIPE if self.use_stderr else None,
+ preexec_fn=self.pre_run_execute)
+ if self.use_stderr:
+ fcntl(self.process.stderr, F_SETFL, fcntl(self.process.stderr, F_GETFL) | os.O_NONBLOCK)
+ except (subprocess.CalledProcessError, OSError, ValueError), e:
+ raise TaskException('invalid command: {0} {1}'.format(self.command, e))
+
+ def task_read(self, buf):
+ if not self.process:
+ raise TaskException('pipe closed')
+ try:
+ return self.process.stdout.readinto(buf)
+ except IOError, e:
+ raise TaskException(e)
+
+ def task_wait(self):
+ self.process.wait()
+ code = self.process.poll()
+
+ if code is None:
+ return '[X] unknown error'
+
+ if not code == 0:
+ stdout, stderr = self.process.communicate()
+ return '[{0}] {1}'.format(code, stderr.strip())
+
+
+class TaskProcessFIFO(TaskProcess):
+ fifo = None
+ fifo_path = '/var/lib/bareos/task.fifo'
+ use_stdout = False
+
+ def make_fifo(self):
+ if os.path.exists(self.fifo_path):
+ os.remove(self.fifo_path)
+
+ os.mkfifo(self.fifo_path)
+
+ if self.run_as_user:
+ item = getpwnam(self.run_as_user)
+ os.chown(self.fifo_path, item.pw_uid, item.pw_gid)
+
+ def task_open(self):
+ self.make_fifo()
+ super(TaskProcessFIFO, self).task_open()
+ self.fifo = open(self.fifo_path, 'rb')
+
+ def task_read(self, buf):
+ if not self.fifo:
+ raise TaskException('pipe closed')
+
+ try:
+ return self.fifo.readinto(buf)
+ except IOError, e:
+ raise TaskException(e)
+
+ def task_close(self):
+ super(TaskProcessFIFO, self).task_close()
+ self.fifo.close()
+
+
+class PluginConfig(dict):
+
+ def get_boolean(self, key, default=False):
+ value = self.get(key)
+ if value is None:
+ return default
+ return value == 'yes'
+
+ def get_list(self, key, default=list()):
+ value = self.get(key)
+ if value is None:
+ return default
+ return value.split(':')
+
+
+class BareosFdTaskClass(BareosFdPluginBaseclass):
+ debug_level = 100
+ plugin_name = 'unknown'
+
+ def __init__(self, context, plugin_def):
+ BareosFdPluginBaseclass.__init__(self, context, plugin_def)
+ self.config = None
+ self.folder = None
+ self.job_type = None
+ self.task = None
+ self.tasks = list()
+
+ def log_format(self, message):
+ return '{0}: {1}\n'.format(self.plugin_name, message.lower())
+
+ def job_message(self, context, level, message):
+ self.debug_message(context, message)
+ JobMessage(context, level, self.log_format(message))
+
+ def debug_message(self, context, message):
+ DebugMessage(context, self.debug_level, self.log_format(message))
+
+ def prepare_tasks(self):
+ raise Exception('need to be override')
+
+ def parse_plugin_definition(self, context, plugin_def):
+ BareosFdPluginBaseclass.parse_plugin_definition(self, context, plugin_def)
+ self.job_type = GetValue(context, bVariable['bVarType'])
+ self.config = PluginConfig(**self.options)
+ self.folder = self.config.get('folder', '@{0}'.format(self.plugin_name.upper()))
+ try:
+ self.prepare_tasks()
+ except TaskException, _:
+ return bRCs['bRC_Error']
+
+ self.debug_message(context, '{0} task created'.format(len(self.tasks)))
+ return bRCs['bRC_OK']
+
+ def start_backup_file(self, context, save_pkt):
+
+ if not len(self.tasks):
+ self.job_message(context, bJobMessageType['M_WARNING'], 'no tasks defined')
+ return bRCs['bRC_Skip']
+
+ self.task = self.tasks.pop()
+ stat_pkt = StatPacket()
+ stat_pkt.size = self.task.get_size()
+ stat_pkt.blksize = self.task.get_block_size()
+ save_pkt.statp = stat_pkt
+ save_pkt.fname = os.path.join('/', self.folder, self.task.get_filename())
+ save_pkt.type = bFileType['FT_REG']
+
+ return bRCs['bRC_OK']
+
+ def plugin_io(self, context, iop):
+ if self.job_type == bJobType['BACKUP']:
+
+ if iop.func == bIOPS['IO_OPEN']:
+ try:
+ self.job_message(context, bJobMessageType['M_INFO'], '{0} started'.format(self.task.get_name()))
+ self.task.task_pool()
+ self.task.task_open()
+ except TaskException, e:
+ self.job_message(context, bJobMessageType['M_ERROR'], '{0} {1}'.format(self.task.get_name(), e))
+ return bRCs['bRC_Error']
+ return bRCs['bRC_OK']
+
+ elif iop.func == bIOPS['IO_CLOSE']:
+ try:
+ self.job_message(context, bJobMessageType['M_INFO'], '{0} done'.format(self.task.get_name()))
+ self.task.task_pool()
+ self.task.task_close()
+ except TaskException, e:
+ self.job_message(context, bJobMessageType['M_ERROR'], '{0} {1}'.format(self.task.get_name(), e))
+ return bRCs['bRC_Error']
+ return bRCs['bRC_OK']
+
+ elif iop.func == bIOPS['IO_READ']:
+ try:
+ self.task.task_pool()
+ iop.io_errno = 0
+ iop.buf = bytearray(iop.count)
+ iop.status = self.task.task_read(iop.buf)
+ except TaskException, e:
+ self.job_message(context, bJobMessageType['M_ERROR'], '{0} {1}'.format(self.task.get_name(), e))
+ return bRCs['bRC_Error']
+ return bRCs['bRC_OK']
+
+ return BareosFdPluginBaseclass.plugin_io(self, context, iop)
+
+ def end_backup_file(self, context):
+ result = self.task.task_wait()
+
+ if result:
+ self.job_message(context, bJobMessageType['M_ERROR'], '{0} {1}'.format(self.task.get_details(), result))
+ return bRCs['bRC_Error']
+
+ self.tasks.extend(self.task.get_next_tasks())
+ return bRCs['bRC_More'] if len(self.tasks) else bRCs['bRC_OK']
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/LICENSE.md b/contrib/fd-plugins/bareos-tasks-plugins/LICENSE.md
new file mode 100644
index 000000000..cba6f6a15
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/LICENSE.md
@@ -0,0 +1,660 @@
+### GNU AFFERO GENERAL PUBLIC LICENSE
+
+Version 3, 19 November 2007
+
+Copyright (C) 2007 Free Software Foundation, Inc.
+<https://fsf.org/>
+
+Everyone is permitted to copy and distribute verbatim copies of this
+license document, but changing it is not allowed.
+
+### Preamble
+
+The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains
+free software for all its users.
+
+When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing
+under this license.
+
+The precise terms and conditions for copying, distribution and
+modification follow.
+
+### TERMS AND CONDITIONS
+
+#### 0. Definitions.
+
+"This License" refers to version 3 of the GNU Affero General Public
+License.
+
+"Copyright" also means copyright-like laws that apply to other kinds
+of works, such as semiconductor masks.
+
+"The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of
+an exact copy. The resulting work is called a "modified version" of
+the earlier work or a work "based on" the earlier work.
+
+A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user
+through a computer network, with no transfer of a copy, is not
+conveying.
+
+An interactive user interface displays "Appropriate Legal Notices" to
+the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+#### 1. Source Code.
+
+The "source code" for a work means the preferred form of the work for
+making modifications to it. "Object code" means any non-source form of
+a work.
+
+A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+The Corresponding Source need not include anything that users can
+regenerate automatically from other parts of the Corresponding Source.
+
+The Corresponding Source for a work in source code form is that same
+work.
+
+#### 2. Basic Permissions.
+
+All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+You may make, run and propagate covered works that you do not convey,
+without conditions so long as your license otherwise remains in force.
+You may convey covered works to others for the sole purpose of having
+them make modifications exclusively for you, or provide you with
+facilities for running those works, provided that you comply with the
+terms of this License in conveying all material for which you do not
+control copyright. Those thus making or running the covered works for
+you must do so exclusively on your behalf, under your direction and
+control, on terms that prohibit them from making any copies of your
+copyrighted material outside their relationship with you.
+
+Conveying under any other circumstances is permitted solely under the
+conditions stated below. Sublicensing is not allowed; section 10 makes
+it unnecessary.
+
+#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such
+circumvention is effected by exercising rights under this License with
+respect to the covered work, and you disclaim any intention to limit
+operation or modification of the work as a means of enforcing, against
+the work's users, your or third parties' legal rights to forbid
+circumvention of technological measures.
+
+#### 4. Conveying Verbatim Copies.
+
+You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+#### 5. Conveying Modified Source Versions.
+
+You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these
+conditions:
+
+- a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+- b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under
+ section 7. This requirement modifies the requirement in section 4
+ to "keep intact all notices".
+- c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+- d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+#### 6. Conveying Non-Source Forms.
+
+You may convey a covered work in object code form under the terms of
+sections 4 and 5, provided that you also convey the machine-readable
+Corresponding Source under the terms of this License, in one of these
+ways:
+
+- a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+- b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the Corresponding
+ Source from a network server at no charge.
+- c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+- d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+- e) Convey the object code using peer-to-peer transmission,
+ provided you inform other peers where the object code and
+ Corresponding Source of the work are being offered to the general
+ public at no charge under subsection 6d.
+
+A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal,
+family, or household purposes, or (2) anything designed or sold for
+incorporation into a dwelling. In determining whether a product is a
+consumer product, doubtful cases shall be resolved in favor of
+coverage. For a particular product received by a particular user,
+"normally used" refers to a typical or common use of that class of
+product, regardless of the status of the particular user or of the way
+in which the particular user actually uses, or expects or is expected
+to use, the product. A product is a consumer product regardless of
+whether the product has substantial commercial, industrial or
+non-consumer uses, unless such uses represent the only significant
+mode of use of the product.
+
+"Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to
+install and execute modified versions of a covered work in that User
+Product from a modified version of its Corresponding Source. The
+information must suffice to ensure that the continued functioning of
+the modified object code is in no case prevented or interfered with
+solely because modification has been made.
+
+If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or
+updates for a work that has been modified or installed by the
+recipient, or for the User Product in which it has been modified or
+installed. Access to a network may be denied when the modification
+itself materially and adversely affects the operation of the network
+or violates the rules and protocols for communication across the
+network.
+
+Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+#### 7. Additional Terms.
+
+"Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders
+of that material) supplement the terms of this License with terms:
+
+- a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+- b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+- c) Prohibiting misrepresentation of the origin of that material,
+ or requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+- d) Limiting the use for publicity purposes of names of licensors
+ or authors of the material; or
+- e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+- f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions
+ of it) with contractual assumptions of liability to the recipient,
+ for any liability that these contractual assumptions directly
+ impose on those licensors and authors.
+
+All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions; the
+above requirements apply either way.
+
+#### 8. Termination.
+
+You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+However, if you cease all violation of this License, then your license
+from a particular copyright holder is reinstated (a) provisionally,
+unless and until the copyright holder explicitly and finally
+terminates your license, and (b) permanently, if the copyright holder
+fails to notify you of the violation by some reasonable means prior to
+60 days after the cessation.
+
+Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+#### 9. Acceptance Not Required for Having Copies.
+
+You are not required to accept this License in order to receive or run
+a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+#### 10. Automatic Licensing of Downstream Recipients.
+
+Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+#### 11. Patents.
+
+A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+A contributor's "essential patent claims" are all patent claims owned
+or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+A patent license is "discriminatory" if it does not include within the
+scope of its coverage, prohibits the exercise of, or is conditioned on
+the non-exercise of one or more of the rights that are specifically
+granted under this License. You may not convey a covered work if you
+are a party to an arrangement with a third party that is in the
+business of distributing software, under which you make payment to the
+third party based on the extent of your activity of conveying the
+work, and under which the third party grants, to any of the parties
+who would receive the covered work from you, a discriminatory patent
+license (a) in connection with copies of the covered work conveyed by
+you (or copies made from those copies), or (b) primarily for and in
+connection with specific products or compilations that contain the
+covered work, unless you entered into that arrangement, or that patent
+license was granted, prior to 28 March 2007.
+
+Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+#### 12. No Surrender of Others' Freedom.
+
+If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under
+this License and any other pertinent obligations, then as a
+consequence you may not convey it at all. For example, if you agree to
+terms that obligate you to collect a royalty for further conveying
+from those to whom you convey the Program, the only way you could
+satisfy both those terms and this License would be to refrain entirely
+from conveying the Program.
+
+#### 13. Remote Network Interaction; Use with the GNU General Public License.
+
+Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your
+version supports such interaction) an opportunity to receive the
+Corresponding Source of your version by providing access to the
+Corresponding Source from a network server at no charge, through some
+standard or customary means of facilitating copying of software. This
+Corresponding Source shall include the Corresponding Source for any
+work covered by version 3 of the GNU General Public License that is
+incorporated pursuant to the following paragraph.
+
+Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+#### 14. Revised Versions of this License.
+
+The Free Software Foundation may publish revised and/or new versions
+of the GNU Affero General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever
+published by the Free Software Foundation.
+
+If the Program specifies that a proxy can decide which future versions
+of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+#### 15. Disclaimer of Warranty.
+
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
+WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
+PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
+DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
+CORRECTION.
+
+#### 16. Limitation of Liability.
+
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
+CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
+ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
+NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
+LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
+TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
+PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+#### 17. Interpretation of Sections 15 and 16.
+
+If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+END OF TERMS AND CONDITIONS
+
+### How to Apply These Terms to Your New Programs
+
+If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these
+terms.
+
+To do so, attach the following notices to the program. It is safest to
+attach them to the start of each source file to most effectively state
+the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as
+ published by the Free Software Foundation, either version 3 of the
+ License, or (at your option) any later version.
+
+ This program 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 Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper
+mail.
+
+If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for
+the specific requirements.
+
+You should also get your employer (if you work as a programmer) or
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. For more information on this, and how to apply and follow
+the GNU AGPL, see <https://www.gnu.org/licenses/>.
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/README.md b/contrib/fd-plugins/bareos-tasks-plugins/README.md
new file mode 100644
index 000000000..d498b9333
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/README.md
@@ -0,0 +1,52 @@
+# Bareos FileDaemon Tasks Plugins
+
+These plugins provide specific application's backup for Bareos FileDaemon.
+
+1. XenServer Host, Pool and VM backup [bareos-fd-xenserver.py](xenserver/README.md)
+2. PostgreSQL Database backup [bareos-fd-pgsql.py](psql/README.md)
+3. MySQL Database backup [bareos-fd-mysql.py](mysql/README.md)
+4. Oracle Database backup [bareos-fd-oracle.py](oracle/README.md)
+
+**Warning:** These plugins comes with no warranty. They are in early stage of development.
+Verify your backup before use it in production.
+
+## Getting Start
+
+Installation and configuration instructions are documented in each plugins.
+
+## Deployment
+
+I start to develop a generic base plugin class *BareosFdTaskClass.py* with the aim to create a fast and
+simple way to write new plugins.
+
+### Backup
+
+The plugin handles a list of tasks. A task is responsible of a backup operation such as database dump,
+system state or a vm export and could store one or more files. A couple of base tasks are available and
+should be overridden to implement the backup operation wanted.
+
+So, to write a new plugin you have to follow these steps:
+
+1. Override *BareosFdTaskClass.py* class.
+2. Define a list of tasks in the *prepare_tasks* function.
+3. Customize the task to execute the specific backup procedure and return data to plugin.
+
+Source code should be quite easy to understand and provided plugins could be easily used as template.
+
+### Restore
+
+The restore operation, at least at the moment, is not managed by this class.
+File are restored in the filesystem as regular file as it is implemented in *BareosFdPluginBaseClass,py*.
+Anyway, the plugin needs to be installed on the FileDaemon used as destination.
+
+## Contributing
+
+Contributions are welcome.
+
+## Authors
+
+* [**Marco Lertora**](https://github.com/marcolertora/) - <marco.lertora@gmail.com>
+
+## License
+
+This project is licensed under the GNU Affero General Public License v3.0 License - see the [LICENSE](LICENSE.md) file for details
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/__init__.py b/contrib/fd-plugins/bareos-tasks-plugins/__init__.py
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/__init__.py
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/mysql/BareosFdMySQLClass.py b/contrib/fd-plugins/bareos-tasks-plugins/mysql/BareosFdMySQLClass.py
new file mode 100644
index 000000000..5146a6f16
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/mysql/BareosFdMySQLClass.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python
+# -*- Mode: Python; tab-width: 4 -*-
+#
+# Bareos FileDaemon Task plugin
+# Copyright (C) 2018 Marco Lertora <marco.lertora@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program 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 Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import shlex
+
+from BareosFdTaskClass import TaskProcess, BareosFdTaskClass
+
+
+class TaskQueryDatabase(TaskProcess):
+
+ def __init__(self, mysql=None, mysql_user=None):
+ self.run_as_user = mysql_user
+ mysql_options = '--batch --skip-column-names'
+ self.command = [mysql if mysql else 'mysql'] + shlex.split(mysql_options)
+ super(TaskQueryDatabase, self).__init__()
+
+ def execute_query(self, query):
+ data = self.execute_command(self.command + ['--execute=' + query])
+ return list(map(lambda x: x.split('\t'), data.splitlines()))
+
+ def get_database_size(self, database):
+ query = 'SELECT SUM(DATA_LENGTH + INDEX_LENGTH) FROM information_schema.TABLES WHERE TABLE_SCHEMA = \"{0}\";'.format(database)
+ items = self.execute_query(query)
+ size = int(items[0][0])
+ return size
+
+ def get_databases(self):
+ query = 'SHOW DATABASES;'
+ exclude = ['performance_schema', 'information_schema', 'mysql']
+ items = self.execute_query(query)
+ items = map(lambda x: x[0], items)
+ items = filter(lambda x: x not in exclude, items)
+ return items
+
+
+class TaskDumpDatabase(TaskProcess):
+ task_name = 'dump-database'
+ file_extension = 'sql'
+
+ def __init__(self, database, mysql=None, mysql_dump=None, mysql_user=None, mysql_dump_options=''):
+ self.database = database
+ self.mysql = mysql
+ self.run_as_user = mysql_user
+ self.command = [mysql_dump if mysql_dump else 'mysqldump'] + shlex.split(mysql_dump_options) + [self.database]
+ super(TaskDumpDatabase, self).__init__()
+
+ def get_name(self):
+ return '{0}-{1}'.format(self.task_name, self.database)
+
+ def get_size(self):
+ return TaskQueryDatabase(self.mysql, self.run_as_user).get_database_size(self.database)
+
+
+class BareosFdMySQLClass(BareosFdTaskClass):
+ plugin_name = 'mysql'
+
+ def prepare_tasks(self):
+ self.tasks = list()
+
+ mysql = self.options.get('mysql', 'mysql')
+ mysql_dump = self.options.get('mysql_dump', 'mysqldump')
+ mysql_dump_options = self.options.get('mysql_dump_options', '--events --single-transaction --add-drop-database')
+ mysql_user = self.options.get('mysql_user')
+
+ databases = self.config.get_list('databases', TaskQueryDatabase(mysql, mysql_user).get_databases())
+
+ if 'exclude' in self.config:
+ exclude = self.config.get_list('exclude')
+ databases = filter(lambda x: x not in exclude, databases)
+
+ for database in databases:
+ self.tasks.append(TaskDumpDatabase(database, mysql, mysql_dump, mysql_user, mysql_dump_options))
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/mysql/README.md b/contrib/fd-plugins/bareos-tasks-plugins/mysql/README.md
new file mode 100644
index 000000000..909d384e7
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/mysql/README.md
@@ -0,0 +1,71 @@
+# Bareos FileDaemon MySQL Plugin
+This plugin makes backup of any database found in a MySQL. Each databases is stored in an individual files.
+For restore select the needed database file, found in */@MYSQL* in the catalog.
+
+## Prerequisites
+The *mysqldump* and *mysql* command must be installed and user *root* must have read-access to the databases.
+See below, if you want to use another user.
+
+You need the packages *bareos-filedaemon-python-plugin* installed on your client.
+
+## Installation
+1. Make sure you have met the prerequisites.
+2. Install the files *BareosFdTaskClass.py*, *psql/BareosFdMySQLClass.py* and *psql/bareos-fd-mysql.py* in your Bareos plugin directory (usually */usr/lib/bareos/plugins*)
+
+## Configuration
+
+Activate your plugin directory in the *fd* resource configuration on the client
+```
+FileDaemon {
+ Name = client-fd
+ ...
+ Plugin Directory = /usr/lib/bareos/plugins
+}
+```
+
+Include the Plugin in the fileset definition on the director
+```
+FileSet {
+ Name = "client-data"
+ Include {
+ Options {
+ compression = LZ4
+ signature = MD5
+ }
+ File = /etc
+ #...
+ Plugin = "python:module_path=/usr/lib/bareos/plugins:module_name=bareos-fd-mysql"
+ }
+ }
+}
+```
+
+### Options
+You can append options to the plugin call as key=value pairs, separated by ':'.
+Please read more about the Bareos Python Plugin Interface here: http://doc.bareos.org/master/html/bareos-manual-main-reference.html#Python-fdPlugin
+
+Example plugin options:
+```
+ Plugin = "python:module_path=/usr/lib/bareos/plugins:module_name=bareos-fd-mysql:databases=db001,db002"
+```
+
+#### folder
+Virtual folder used in catalog. Default: *@MYSQL*
+
+#### mysql
+Command (with or without full path) to *mysql* tool. Default: *mysql*
+
+#### mysql_dump
+Command (with or without full path) to *mysqldump* tool. Default: *mysqldump*
+
+#### mysql_dump_options
+Options to be used with the *mysqldump* tool. Default: *--no-owner --no-acl*
+
+#### mysql_user
+Username of the system user running the *mysql* and *mysqldump* tools. Default: *root*
+
+#### databases
+Comma separated list of database names to backup, if unset all databases (except 'performance_schema' and 'information_schema') are dumped. Default: unset
+
+#### exclude
+Comma separated list of database names exclude from backup. Default: unset \ No newline at end of file
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/mysql/__init__.py b/contrib/fd-plugins/bareos-tasks-plugins/mysql/__init__.py
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/mysql/__init__.py
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/mysql/bareos-fd-mysql.py b/contrib/fd-plugins/bareos-tasks-plugins/mysql/bareos-fd-mysql.py
new file mode 100644
index 000000000..a493c3b37
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/mysql/bareos-fd-mysql.py
@@ -0,0 +1,28 @@
+#!/usr/bin/env python
+# -*- Mode: Python; tab-width: 4 -*-
+#
+# Bareos FileDaemon Task plugin
+# Copyright (C) 2018 Marco Lertora <marco.lertora@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program 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 Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import BareosFdWrapper
+from bareos_fd_consts import bRCs
+from BareosFdWrapper import *
+from BareosFdMySQLClass import BareosFdMySQLClass
+
+
+def load_bareos_plugin(context, plugin_def):
+ BareosFdWrapper.bareos_fd_plugin_object = BareosFdMySQLClass(context, plugin_def)
+ return bRCs['bRC_OK']
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/oracle/BareosFdOracleClass.py b/contrib/fd-plugins/bareos-tasks-plugins/oracle/BareosFdOracleClass.py
new file mode 100644
index 000000000..9f1a9e9e3
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/oracle/BareosFdOracleClass.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+# -*- Mode: Python; tab-width: 4 -*-
+#
+# Bareos FileDaemon Task plugin
+# Copyright (C) 2018 Marco Lertora <marco.lertora@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program 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 Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import os
+import shlex
+
+from BareosFdTaskClass import BareosFdTaskClass, TaskProcessFIFO
+
+
+class TaskDumpDatabase(TaskProcessFIFO):
+ task_name = 'dump-database'
+ file_extension = 'dump'
+
+ def __init__(self, db_sid, db_user, db_password, ora_home, ora_exp, ora_user, ora_exp_options):
+ self.database = db_user + '-' + db_sid
+ self.run_as_user = ora_user
+ self.run_environ = dict(ORACLE_SID=db_sid, ORACLE_HOME=ora_home)
+ ora_exp = os.path.join(ora_home, 'bin/', ora_exp)
+ db_credential = db_user + '/' + db_password
+ self.command = [ora_exp, db_credential] + shlex.split(ora_exp_options) + ['file=' + self.fifo_path]
+ super(TaskDumpDatabase, self).__init__()
+
+ def get_name(self):
+ return '{0}-{1}'.format(self.task_name, self.database)
+
+
+class BareosFdOracleClass(BareosFdTaskClass):
+ plugin_name = 'oracle'
+
+ def prepare_tasks(self):
+ self.tasks = list()
+
+ ora_exp = self.options.get('ora_exp', 'exp')
+ ora_home = self.options.get('ora_home', '/opt/oracle/app/oracle/product/10.2.0')
+ ora_user = self.options.get('ora_user', 'oracle')
+ ora_exp_options = self.options.get('ora_exp_options', 'full=yes') # 'tables=TABLE_NAME'
+ ora_exp_options += ' statistics=none compress=N direct=yes recordlength={0}'.format(TaskDumpDatabase.block_size)
+ db_sid = self.options.get('db_sid')
+ db_user = self.options.get('db_user')
+ db_password = self.options.get('db_password')
+
+ self.tasks.append(TaskDumpDatabase(db_sid, db_user, db_password, ora_home, ora_exp, ora_user, ora_exp_options))
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/oracle/README.md b/contrib/fd-plugins/bareos-tasks-plugins/oracle/README.md
new file mode 100644
index 000000000..f4037ddd8
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/oracle/README.md
@@ -0,0 +1,74 @@
+# Bareos FileDaemon Oracle Plugin
+This plugin makes a backup of an oracle database using exp tool in a single file.
+For restore select the needed database file, found in */@ORACLE* in the catalog.
+
+## Prerequisites
+The *exp* tool must be installed and user *oracle* must have read-access to the database.
+See below, if you want to use another user.
+
+You need the packages *bareos-filedaemon-python-plugin* installed on your client.
+
+## Installation
+1. Make sure you have met the prerequisites.
+2. Install the files *BareosFdTaskClass.py*, *oracle/BareosFdOracleClass.py* and *oracle/bareos-fd-oracle.py* in your Bareos plugin directory (usually */usr/lib/bareos/plugins*)
+
+## Configuration
+
+Activate your plugin directory in the *fd* resource configuration on the client
+```
+FileDaemon {
+ Name = client-fd
+ ...
+ Plugin Directory = /usr/lib/bareos/plugins
+}
+```
+
+Include the Plugin in the *fileset* definition on the director
+```
+FileSet {
+ Name = "client-data"
+ Include {
+ Options {
+ compression = LZ4
+ signature = MD5
+ }
+ File = /etc
+ #...
+ Plugin = "python:module_path=/usr/lib/bareos/plugins:module_name=bareos-fd-oracle:db_sid=DBSID:db_user=DBUSER:db_password=DBPASSWORD"
+ }
+ }
+}
+```
+
+### Options
+You can append options to the plugin call as key=value pairs, separated by ':'.
+Please read more about the Bareos Python Plugin Interface here: http://doc.bareos.org/master/html/bareos-manual-main-reference.html#Python-fdPlugin
+
+Example plugin options:
+```
+ Plugin = "python:module_path=/usr/lib/bareos/plugins:module_name=bareos-fd-oracle:db_sid=MAIN:db_user=oracle:db_password=secret"
+```
+
+#### folder
+Virtual folder used in catalog. Default: *@ORACLE*
+
+#### ora_exp
+Command (with or without full path) to *exp* tool. Default: *exp*
+
+#### ora_home
+Full path to oracle home. Default: Required
+
+#### ora_user
+Username of the system user running the *ora_exp* tool. Default: *oracle*
+
+#### ora_exp_options
+Options to be used with the *exp* tool. Default: *full=yes statistics=none*
+
+#### db_sid
+Specifies the *sid* of the oracle instance to use. Required
+
+#### db_user
+Specifies the username of the user performing the export. Required
+
+#### db_password
+Specifies the password of the user performing the export. Required \ No newline at end of file
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/oracle/__init__.py b/contrib/fd-plugins/bareos-tasks-plugins/oracle/__init__.py
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/oracle/__init__.py
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/oracle/bareos-fd-oracle.py b/contrib/fd-plugins/bareos-tasks-plugins/oracle/bareos-fd-oracle.py
new file mode 100644
index 000000000..39d93dd3d
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/oracle/bareos-fd-oracle.py
@@ -0,0 +1,28 @@
+#!/usr/bin/env python
+# -*- Mode: Python; tab-width: 4 -*-
+#
+# Bareos FileDaemon Task plugin
+# Copyright (C) 2018 Marco Lertora <marco.lertora@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program 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 Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import BareosFdWrapper
+from bareos_fd_consts import bRCs
+from BareosFdWrapper import *
+from BareosFdOracleClass import BareosFdOracleClass
+
+
+def load_bareos_plugin(context, plugin_def):
+ BareosFdWrapper.bareos_fd_plugin_object = BareosFdOracleClass(context, plugin_def)
+ return bRCs['bRC_OK']
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/pgsql/BareosFdPgSQLClass.py b/contrib/fd-plugins/bareos-tasks-plugins/pgsql/BareosFdPgSQLClass.py
new file mode 100644
index 000000000..1cb2f983c
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/pgsql/BareosFdPgSQLClass.py
@@ -0,0 +1,92 @@
+#!/usr/bin/env python
+# -*- Mode: Python; tab-width: 4 -*-
+#
+# Bareos FileDaemon Task plugin
+# Copyright (C) 2018 Marco Lertora <marco.lertora@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program 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 Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import shlex
+
+from BareosFdTaskClass import TaskProcess, BareosFdTaskClass
+
+
+class TaskQueryDatabase(TaskProcess):
+
+ def __init__(self, psql=None, pg_user=None):
+ self.run_as_user = pg_user
+ psql_options = '--expanded --no-align'
+ self.command = [psql if psql else 'psql'] + shlex.split(psql_options)
+ super(TaskQueryDatabase, self).__init__()
+
+ def execute_query(self, query):
+ items = list()
+ data = self.execute_command(self.command + ['--command=' + query])
+ for record in data.split('\n\n'):
+ item = dict(map(lambda x: x.split('|', 1), record.splitlines()))
+ items.append(item)
+ return items
+
+ def get_database_size(self, database):
+ query = 'SELECT pg_database_size(\'{0}\');'.format(database)
+ items = self.execute_query(query)
+ size = int(items[0]['pg_database_size'])
+ return size
+
+ def get_databases(self):
+ query = 'SELECT datname FROM pg_database;'
+ exclude = ['postgres', 'template1', 'template0']
+ items = self.execute_query(query)
+ items = map(lambda x: x['datname'], items)
+ items = filter(lambda x: x not in exclude, items)
+ return items
+
+
+class TaskDumpDatabase(TaskProcess):
+ task_name = 'dump-database'
+ file_extension = 'sql'
+
+ def __init__(self, database, psql=None, pg_dump=None, pg_user=None, pg_dump_options=''):
+ self.database = database
+ self.psql = psql
+ self.run_as_user = pg_user
+ self.command = [pg_dump if pg_dump else 'pg_dump'] + shlex.split(pg_dump_options) + [self.database]
+ super(TaskDumpDatabase, self).__init__()
+
+ def get_name(self):
+ return '{0}-{1}'.format(self.task_name, self.database)
+
+ def get_size(self):
+ return TaskQueryDatabase(self.psql, self.run_as_user).get_database_size(self.database)
+
+
+class BareosFdPgSQLClass(BareosFdTaskClass):
+ plugin_name = 'pgsql'
+
+ def prepare_tasks(self):
+ self.tasks = list()
+
+ psql = self.options.get('psql', 'psql')
+ pg_dump = self.options.get('pg_dump', 'pg_dump')
+ pg_dump_options = self.options.get('pg_dump_options', '--no-owner --no-acl')
+ pg_user = self.options.get('pg_user', 'postgres')
+
+ databases = self.config.get_list('databases', TaskQueryDatabase(psql, pg_user).get_databases())
+
+ if 'exclude' in self.config:
+ exclude = self.config.get_list('exclude')
+ databases = filter(lambda x: x not in exclude, databases)
+
+ for database in databases:
+ self.tasks.append(TaskDumpDatabase(database, psql, pg_dump, pg_user, pg_dump_options))
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/pgsql/README.md b/contrib/fd-plugins/bareos-tasks-plugins/pgsql/README.md
new file mode 100644
index 000000000..376ef19fb
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/pgsql/README.md
@@ -0,0 +1,71 @@
+# Bareos FileDaemon PostgreSQL Plugin
+This plugin makes backup of any database found in a PostgreSQL. Each databases is stored in an individual files.
+For restore select the needed database file, found in */@PGSQL* in the catalog.
+
+## Prerequisites
+The *pg_dump* and *psql* command must be installed and user *postgres* must have read-access to the databases.
+See below, if you want to use another user.
+
+You need the packages *bareos-filedaemon-python-plugin* installed on your client.
+
+## Installation
+1. Make sure you have met the prerequisites.
+2. Install the files *BareosFdTaskClass.py*, *psql/BareosFdPgSQLClass.py* and *psql/bareos-fd-pgsql.py* in your Bareos plugin directory (usually */usr/lib/bareos/plugins*)
+
+## Configuration
+
+Activate your plugin directory in the *fd* resource configuration on the client
+```
+FileDaemon {
+ Name = client-fd
+ ...
+ Plugin Directory = /usr/lib/bareos/plugins
+}
+```
+
+Include the Plugin in the fileset definition on the director
+```
+FileSet {
+ Name = "client-data"
+ Include {
+ Options {
+ compression = LZ4
+ signature = MD5
+ }
+ File = /etc
+ #...
+ Plugin = "python:module_path=/usr/lib/bareos/plugins:module_name=bareos-fd-pgsql"
+ }
+ }
+}
+```
+
+### Options
+You can append options to the plugin call as key=value pairs, separated by ':'.
+Please read more about the Bareos Python Plugin Interface here: http://doc.bareos.org/master/html/bareos-manual-main-reference.html#Python-fdPlugin
+
+Example plugin options:
+```
+ Plugin = "python:module_path=/usr/lib/bareos/plugins:module_name=bareos-fd-pgsql:databases=db001,db002"
+```
+
+#### folder
+Virtual folder used in catalog. Default: *@PGSQL*
+
+#### psql
+Command (with or without full path) to *psql* tool. Default: *psql*
+
+#### pg_dump
+Command (with or without full path) to *pg_dup* tool. Default: *pg_dump*
+
+#### pg_dump_options
+Options to be used with the *pg_dump* tool. Default: *--no-owner --no-acl*
+
+#### pg_user
+Username of the system user running the *psql* and *pg_dump* tools. Default: *postgres*
+
+#### databases
+Comma separated list of database names to backup, if unset all databases (except 'postgres', 'template1' and 'template0') are dumped. Default: unset
+
+#### exclude
+Comma separated list of database names exclude from backup. Default: unset \ No newline at end of file
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/pgsql/__init__.py b/contrib/fd-plugins/bareos-tasks-plugins/pgsql/__init__.py
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/pgsql/__init__.py
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/pgsql/bareos-fd-pgsql.py b/contrib/fd-plugins/bareos-tasks-plugins/pgsql/bareos-fd-pgsql.py
new file mode 100644
index 000000000..92f80fd3a
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/pgsql/bareos-fd-pgsql.py
@@ -0,0 +1,28 @@
+#!/usr/bin/env python
+# -*- Mode: Python; tab-width: 4 -*-
+#
+# Bareos FileDaemon Task plugin
+# Copyright (C) 2018 Marco Lertora <marco.lertora@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program 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 Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import BareosFdWrapper
+from bareos_fd_consts import bRCs
+from BareosFdWrapper import *
+from BareosFdPgSQLClass import BareosFdPgSQLClass
+
+
+def load_bareos_plugin(context, plugin_def):
+ BareosFdWrapper.bareos_fd_plugin_object = BareosFdPgSQLClass(context, plugin_def)
+ return bRCs['bRC_OK']
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/xenserver/BareosFdXenServerClass.py b/contrib/fd-plugins/bareos-tasks-plugins/xenserver/BareosFdXenServerClass.py
new file mode 100644
index 000000000..fd1e64869
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/xenserver/BareosFdXenServerClass.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python
+# -*- Mode: Python; tab-width: 4 -*-
+#
+# Bareos FileDaemon Task plugin
+# Copyright (C) 2018 Marco Lertora <marco.lertora@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program 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 Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import socket
+from BareosFdTaskClass import TaskProcess, BareosFdTaskClass
+
+
+class TaskHostBackup(TaskProcess):
+ task_name = 'host-backup'
+
+ def __init__(self, hostname):
+ self.command = ['xe', 'host-backup', 'hostname=' + hostname, 'file-name=']
+
+
+class TaskPoolDumpDatabase(TaskProcess):
+ task_name = 'pool-dump-database'
+ file_extension = 'xml'
+
+ def __init__(self):
+ self.command = ['xe', 'pool-dump-database', 'file-name=']
+
+
+class TaskVmExport(TaskProcess):
+ task_name = 'vm-export'
+ file_extension = 'xva'
+
+ def __init__(self, vm_name):
+ self.vm_name = vm_name
+ self.command = ['xe', 'vm-export', 'vm=' + self.vm_name, 'filename=']
+ super(TaskVmExport, self).__init__()
+
+ def get_name(self):
+ return '{0}-{1}'.format(self.task_name, self.vm_name)
+
+
+class BareosFdXenServerClass(BareosFdTaskClass):
+ plugin_name = 'xenserver'
+ pool_conf_path = '/etc/xensource/pool.conf'
+
+ @staticmethod
+ def get_hostname():
+ return socket.gethostname()
+
+ def is_pool_master(self):
+ with open(self.pool_conf_path, 'r') as fin:
+ data = fin.read()
+ return data == 'master'
+
+ def prepare_tasks(self):
+ self.tasks = list()
+
+ if self.config.get_boolean('host_backup', True):
+ self.tasks.append(TaskHostBackup(BareosFdXenServerClass.get_hostname()))
+
+ if self.config.get_boolean('pool_dump_database', True) and self.is_pool_master():
+ self.tasks.append(TaskPoolDumpDatabase())
+
+ for vm in self.config.get_list('vms'):
+ self.tasks.append(TaskVmExport(vm))
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/xenserver/README.md b/contrib/fd-plugins/bareos-tasks-plugins/xenserver/README.md
new file mode 100644
index 000000000..fb4dbd776
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/xenserver/README.md
@@ -0,0 +1,66 @@
+# Bareos FileDaemon XenServer Plugin
+This plugin makes backup of Xen Server. It can be used to save:
+
+1. VM: using the *xe vm-export* command. The vm should not be running.
+2. HOST: using the *xe host-backup* command
+3. POOL DATABASE: using the *xe pool-dump-database* command
+
+For restore select the needed file, found in */@XENSERVER* in the catalog.
+
+## Prerequisites
+The plugins has been developed and tested with Xen Server 7.1
+
+You need the packages *bareos-filedaemon-python-plugin* installed on your client.
+
+## Installation
+1. Make sure you have met the prerequisites.
+2. Install the files *BareosFdTaskClass.py*, *xenserver/BareosFdXenServerClass.py* and *xenserver/bareos-fd-xenserver.py* in your Bareos plugin directory (usually */usr/lib/bareos/plugins*)
+
+## Configuration
+
+Activate your plugin directory in the *fd* resource configuration on the client
+```
+FileDaemon {
+ Name = client-fd
+ ...
+ Plugin Directory = /usr/lib/bareos/plugins
+}
+```
+
+nclude the Plugin in the fileset definition on the director
+```
+FileSet {
+ Name = "client-data"
+ Include {
+ Options {
+ compression = LZO
+ signature = MD5
+ }
+ File = /etc
+ #...
+ Plugin = "python:module_path=/usr/lib/bareos/plugins:module_name=bareos-fd-xenserver"
+ }
+ }
+}
+```
+
+### Options
+You can append options to the plugin call as key=value pairs, separated by ':'.
+Please read more about the Bareos Python Plugin Interface here: http://doc.bareos.org/master/html/bareos-manual-main-reference.html#Python-fdPlugin
+
+Example plugin options:
+```
+ Plugin = "python:module_path=/usr/lib/bareos/plugins:module_name=bareos-fd-xenserver:host_backup=yes"
+```
+
+#### folder
+Virtual folder used in catalog. Default: *@XENSERVER*
+
+#### vms
+Comma separated list of VM names to backup. Default: unset
+
+#### host_backup
+Set to *no* to disable host backup. Default: *yes*
+
+#### pool_dump_database
+Set to *no* to disable pool dump database. Default: *yes*
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/xenserver/__init__.py b/contrib/fd-plugins/bareos-tasks-plugins/xenserver/__init__.py
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/xenserver/__init__.py
diff --git a/contrib/fd-plugins/bareos-tasks-plugins/xenserver/bareos-fd-xenserver.py b/contrib/fd-plugins/bareos-tasks-plugins/xenserver/bareos-fd-xenserver.py
new file mode 100644
index 000000000..8a4d95934
--- /dev/null
+++ b/contrib/fd-plugins/bareos-tasks-plugins/xenserver/bareos-fd-xenserver.py
@@ -0,0 +1,28 @@
+#!/usr/bin/env python
+# -*- Mode: Python; tab-width: 4 -*-
+#
+# Bareos FileDaemon Task plugin
+# Copyright (C) 2018 Marco Lertora <marco.lertora@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program 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 Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import BareosFdWrapper
+from bareos_fd_consts import bRCs
+from BareosFdWrapper import *
+from BareosFdXenServerClass import BareosFdXenServerClass
+
+
+def load_bareos_plugin(context, plugin_def):
+ BareosFdWrapper.bareos_fd_plugin_object = BareosFdXenServerClass(context, plugin_def)
+ return bRCs['bRC_OK']
diff --git a/contrib/fd-plugins/bareos_elasticsearch/BareosFdPluginElasticsearch.py b/contrib/fd-plugins/bareos_elasticsearch/BareosFdPluginElasticsearch.py
new file mode 100644
index 000000000..7a4d818a7
--- /dev/null
+++ b/contrib/fd-plugins/bareos_elasticsearch/BareosFdPluginElasticsearch.py
@@ -0,0 +1,83 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Bareos python class PoC option plugin to index files
+# with Tika and Elasticsearch, including Bareos JobId
+#
+# Configure your Elasticsearch server and Tika-Jar
+# inline below
+#
+# This is Proof of Concept code. Use with caution
+# TODO:
+# - Make Tika and Elastic configurable by file / option
+# - Better error handling
+#
+# (c) 2019 Bareos GmbH & Co. KG
+# AGPL v.3
+# Author: Maik Aussendorf
+
+from bareosfd import *
+from bareos_fd_consts import *
+import os
+from BareosFdPluginBaseclass import *
+import BareosFdWrapper
+from elasticsearch import Elasticsearch
+from tikapp import TikaApp
+import subprocess
+import sys
+import json
+
+
+class BareosFdPluginFileElasticsearch (BareosFdPluginBaseclass):
+
+ def handle_backup_file(self,context, savepkt):
+ DebugMessage(context, 100, "handle_backup_file called with " + str(savepkt) + "\n");
+ DebugMessage(context, 100, "fname: " + savepkt.fname + " Type: " + str(savepkt.type) + "\n");
+ if ( savepkt.type == bFileType['FT_REG'] ):
+ DebugMessage(context, 100, "regulaer file, do something now...\n");
+ # configure your Elasticsearch server here:
+ es = Elasticsearch([{'host': '192.168.17.2', 'port': 9200}])
+ # configure your TikaApp jar file here:
+ try:
+ tika_client = TikaApp(file_jar="/usr/local/bin/tika-app-1.20.jar")
+ except Exception as ex:
+ JobMessage(context, bJobMessageType['M_ERROR'], 'Error indexing %s. Tika error: %s' % (savepkt.fname, str(ex)))
+ return bRCs['bRC_OK'];
+ # tika_client has several parser options
+ # Next one is for metadata only:
+ #result_payload=tika_client.extract_only_metadata(savepkt.fname)
+ # This one includes file contents as text:
+ try:
+ result_payload=tika_client.extract_all_content(savepkt.fname)
+ except Exception as ex:
+ JobMessage(context, bJobMessageType['M_ERROR'], 'Error extracting contents from %s. Tika error: %s' % (savepkt.fname, str(ex)))
+ return bRCs['bRC_OK'];
+ # result_payload is a list of json-strings. Nested structes like
+ # tar-files or emails with attachments or inline documents are
+ # returned as distinct json string.
+ # The first string [0] contains information for the main file
+ # TODO: care about nested structures, for now we only takte the first/main file
+ try:
+ data = json.loads(result_payload)[0]
+ except Exception as ex:
+ JobMessage(context, bJobMessageType['M_ERROR'],
+ 'Error reading json fields delivered by Tika examining file %s. Json error: %s' % (savepkt.fname, str(ex)))
+ return bRCs['bRC_OK'];
+ # Tika eventually adds "Unkonwn Tags (id)", with id as increasing number, which
+ # could lead to exceed the keyword limit in elasticsearch indices, we
+ # remove those tags
+ for data_keyword in data.keys():
+ if data_keyword.startswith ("Unknown tag ("):
+ del data[data_keyword]
+ # Tika adds some emptylines at the beginning of content, we strip it here
+ if 'X-TIKA:content' in data:
+ data['X-TIKA:content'] = data['X-TIKA:content'].strip()
+ data['bareos_jobId'] = self.jobId
+ data['bareos_fdname'] = self.fdname
+ data['bareos_joblevel'] = unichr(self.level)
+ data['bareos_directory'] = os.path.dirname(savepkt.fname)
+ try:
+ esRes = es.index (index="bareos-test", doc_type='_doc', body=data)
+ except Exception as ex:
+ JobMessage(context, bJobMessageType['M_ERROR'], 'Error indexing %s. Elastic error: %s' % (savepkt.fname, str(ex)))
+ return bRCs['bRC_OK'];
diff --git a/contrib/fd-plugins/bareos_elasticsearch/README.md b/contrib/fd-plugins/bareos_elasticsearch/README.md
new file mode 100644
index 000000000..2c46ad56a
--- /dev/null
+++ b/contrib/fd-plugins/bareos_elasticsearch/README.md
@@ -0,0 +1,80 @@
+# The Bareos Elasticsearch Plugin
+
+This plugin uses Apache Tika to parse documents and sends the information including Bareos jobId to
+an Elasticsearch database.
+
+This is Proof of Concept (PoC) code.
+
+## Prerequisites
+
+You need
+* a running Elasticsearch server
+* Apache Tika jarfile from http://tika.apache.org/
+* Python tika-app https://pypi.org/project/tika-app/
+* Python Elasticsearch: https://pypi.org/project/elasticsearch/
+* Bareos FD Plugin Baseclass installed: bareos-filedaemon-python-plugin from http://download.bareos.org
+
+## Compatibility
+
+Tested with Elasticsearch 6.5, tika-app-1.20.jar, Python elasticsearch 6.3.1, Python tika-app 1.5.0 on Bareos 17.2.
+
+## Installation ##
+
+1. Make sure you have met the prerequisites.
+2. Install the files *BareosFdPluginElasticsearch.py* and *bareos-fd-elasticsearch.py* in your Bareos plugin directory (usually */usr/lib64/bareos/plugins*)
+
+
+## Configuration ##
+
+You have to adjust
+* the location of your Tika-Jar
+* Elasticsearch server
+
+in *BareosFdPluginElasticsearch.py*:
+
+```
+es = Elasticsearch([{'host': '192.168.17.2', 'port': 9200}])
+#...
+tika_client = TikaApp(file_jar="/usr/local/bin/tika-app-1.20.jar")
+```
+
+The Python Tika module supports parsing of metadata only or metadata and full-text parsing.
+Full text parsing is enabled by default:
+```
+result_payload=tika_client.extract_all_content(savepkt.fname)
+# If you want meta-data only, change this to:
+result_payload=tika_client.extract_only_metadata(savepkt.fname)
+```
+
+### Activate your plugin directory in the fd resource conf on the client
+```
+FileDaemon {
+ Name = client-fd
+ ...
+ Plugin Directory = /usr/lib64/bareos/plugins
+}
+```
+
+### Include the Plugin in the fileset definition as Option on the director
+```
+FileSet {
+ Name = "client-data"
+ Include {
+ Options {
+ compression=GZIP
+ signature = MD5
+ Plugin = "python:module_path=/usr/lib64/bareos/plugins:module_name=bareos-fd-elasticsearch"
+ }
+ File = /etc
+ }
+}
+```
+
+#### Options ####
+
+Not implemented, yet.
+
+
+## Troubleshooting ##
+
+Support is available here: https://www.bareos.com
diff --git a/contrib/fd-plugins/bareos_elasticsearch/bareos-fd-elasticsearch.py b/contrib/fd-plugins/bareos_elasticsearch/bareos-fd-elasticsearch.py
new file mode 100644
index 000000000..19ce11398
--- /dev/null
+++ b/contrib/fd-plugins/bareos_elasticsearch/bareos-fd-elasticsearch.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# bareos-fd-elasticsearch.py parses any file in the backup job and sends metadata and (optionally) contents
+# to an Elasticsearch server.
+
+# Provided by the Bareos FD Python plugin interface
+from bareosfd import *
+from bareos_fd_consts import *
+
+# This module contains the wrapper functions called by the Bareos-FD, the functions call the corresponding
+# methods from your plugin class
+from BareosFdWrapper import *
+
+# This module contains the used plugin class
+from BareosFdPluginElasticsearch import *
+
+def load_bareos_plugin(context, plugindef):
+ '''
+ This function is called by the Bareos-FD to load the plugin
+ We use it to intantiate the plugin class
+ '''
+ # BareosFdWrapper.bareos_fd_plugin_object is the module attribute that holds the plugin class object
+ BareosFdWrapper.bareos_fd_plugin_object = BareosFdPluginFileElasticsearch (context, plugindef);
+ return bRCs['bRC_OK'];
+
+# the rest is done in the Plugin module
diff --git a/contrib/fd-plugins/mysql-python/BareosFdMySQLclass.py b/contrib/fd-plugins/mysql-python/BareosFdMySQLclass.py
new file mode 100755
index 000000000..3bd8618b5
--- /dev/null
+++ b/contrib/fd-plugins/mysql-python/BareosFdMySQLclass.py
@@ -0,0 +1,285 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# originally contributed by:
+#Copyright 2014 Battelle Memorial Institute
+#Written by Evan Felix
+
+# With additions from Maik Aussendorf, Bareos GmbH & Co. KG 2015
+
+# This program is Free Software; you can redistribute it and/or
+# modify it under the terms of version three of the GNU Affero General Public
+# License as published by the Free Software Foundation, which is
+# listed in the file LICENSE.
+#
+# This program 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
+# Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301, USA.
+
+
+from bareosfd import *
+import os
+from subprocess import *
+from BareosFdPluginBaseclass import *
+import BareosFdWrapper
+
+
+class BareosFdMySQLclass (BareosFdPluginBaseclass):
+ '''
+ Plugin for backing up all mysql databases found in a specific mysql server
+ '''
+ def __init__(self, plugindef):
+ BareosFdPluginBaseclass.__init__(self, plugindef)
+ self.file=None
+
+ def parse_plugin_definition(self, plugindef):
+ '''
+ '''
+ BareosFdPluginBaseclass.parse_plugin_definition(self, plugindef)
+
+ # mysql host and credentials, by default we use localhost and root and
+ # prefer to have a my.cnf with mysql credentials
+ self.mysqlconnect = ''
+
+ if 'dumpbinary' in self.options:
+ self.dumpbinary = self.options['dumpbinary']
+ else:
+ self.dumpbinary = "mysqldump"
+
+ # if dumpotions is set, we use that completely here, otherwise defaults
+ if 'dumpoptions' in self.options:
+ self.dumpoptions = self.options['dumpoptions']
+ else:
+ self.dumpoptions = " --events --single-transaction "
+ # default is to add the drop statement
+ if not 'drop_and_recreate' in self.options or not self.options['drop_and_recreate'] == 'false':
+ self.dumpoptions += " --add-drop-database --databases "
+
+ # if defaultsfile is set
+ if 'defaultsfile' in self.options:
+ self.defaultsfile = self.options['defaultsfile']
+ self.mysqlconnect += " --defaults-file=" + self.defaultsfile
+
+ if 'mysqlhost' in self.options:
+ self.mysqlhost = self.options['mysqlhost']
+ self.mysqlconnect += " -h " + self.mysqlhost
+
+ if 'mysqluser' in self.options:
+ self.mysqluser = self.options['mysqluser']
+ self.mysqlconnect += " -u " + self.mysqluser
+
+ if 'mysqlpassword' in self.options:
+ self.mysqlpassword = self.options['mysqlpassword']
+ self.mysqlconnect += " --password=" + self.mysqlpassword
+
+ # if plugin has db configured (a list of comma separated databases to backup
+ # we use it here as list of databases to backup
+ if 'db' in self.options:
+ self.databases = self.options['db'].split(',')
+ # Otherwise we backup all existing databases
+ else:
+ showDbCommand = "mysql %s -B -N -e 'show databases'" % self.mysqlconnect
+ showDb = Popen(showDbCommand, shell=True, stdout=PIPE, stderr=PIPE)
+ self.databases = showDb.stdout.read().splitlines()
+ if 'performance_schema' in self.databases:
+ self.databases.remove('performance_schema')
+ if 'information_schema' in self.databases:
+ self.databases.remove('information_schema')
+ showDb.wait()
+ returnCode = showDb.poll()
+ if returnCode == None:
+ JobMessage(
+ M_FATAL,
+ "No databases specified and show databases failed for unknown reason"
+ )
+ DebugMessage(
+ 10,
+ "Failed mysql command: '%s'"
+ % showDbCommand
+ )
+ return bRC_Error
+ if returnCode != 0:
+ (stdOut, stdError) = showDb.communicate()
+ JobMessage(
+ M_FATAL,
+ "No databases specified and show databases failed. %s"
+ % stdError
+ )
+ DebugMessage(
+ 10,
+ "Failed mysql command: '%s'"
+ % showDbCommand
+ )
+ return bRC_Error
+
+ if 'ignore_db' in self.options:
+ DebugMessage(
+ 100,
+ "databases in ignore list: %s\n"
+ % (self.options['ignore_db'].split(','))
+ )
+ for ignored_cur in self.options['ignore_db'].split(','):
+ try:
+ self.databases.remove(ignored_cur)
+ except:
+ pass
+ DebugMessage(
+ 100,
+ "databases to backup: %s\n"
+ % (self.databases)
+ )
+ return bRC_OK
+
+
+ def start_backup_file(self, savepkt):
+ '''
+ This method is called, when Bareos is ready to start backup a file
+ For each database to backup we create a mysqldump subprocess, wrting to
+ the pipe self.stream.stdout
+ '''
+ DebugMessage(
+ 100,
+ "start_backup called\n"
+ )
+ if not self.databases:
+ DebugMessage(
+ 100,
+ "No databases to backup"
+ )
+ JobMessage(
+ M_ERROR,
+ "No databases to backup.\n"
+ )
+ return bRC_Skip
+
+ db = self.databases.pop()
+
+ sizeDbCommand = "mysql %s -B -N -e 'SELECT (SUM(DATA_LENGTH + INDEX_LENGTH)) FROM information_schema.TABLES WHERE TABLE_SCHEMA = \"%s\"'" % (self.mysqlconnect, db)
+ sizeDb = Popen(sizeDbCommand, shell=True, stdout=PIPE, stderr=PIPE)
+ size_curr_db = sizeDb.stdout.read()
+ sizeDb.wait()
+ sizereturnCode = sizeDb.poll()
+
+ statp = StatPacket()
+ savepkt.statp = statp
+ savepkt.fname = "/_mysqlbackups_/" + db + ".sql"
+ savepkt.type = FT_REG
+
+ dumpcommand = ("%s %s %s %s" % (self.dumpbinary, self.mysqlconnect, db, self.dumpoptions))
+ DebugMessage(
+ 100,
+ "Dumper: '" + dumpcommand + "'\n"
+ )
+ self.stream = Popen(dumpcommand, shell=True, stdout=PIPE, stderr=PIPE)
+
+ JobMessage(
+ M_INFO,
+ "Starting backup of " + savepkt.fname + "\n"
+ )
+ return bRC_OK
+
+
+ def plugin_io(self, IOP):
+ '''
+ Called for io operations. We read from pipe into buffers or on restore
+ create a file for each database and write into it.
+ '''
+ DebugMessage(
+ 100,
+ "plugin_io called with " + str(IOP.func) + "\n"
+ )
+
+ if IOP.func == IO_OPEN:
+ try:
+ if IOP.flags & (os.O_CREAT | os.O_WRONLY):
+ self.file = open(IOP.fname, 'wb');
+ except Exception,msg:
+ IOP.status = -1;
+ DebugMessage(
+ 100,
+ "Error opening file: " + IOP.fname + "\n"
+ )
+ print msg;
+ return bRC_Error
+ return bRC_OK
+
+ elif IOP.func == IO_READ:
+ IOP.buf = bytearray(IOP.count)
+ IOP.status = self.stream.stdout.readinto(IOP.buf)
+ IOP.io_errno = 0
+ return bRC_OK
+
+ elif IOP.func == IO_WRITE:
+ try:
+ self.file.write(IOP.buf);
+ IOP.status = IOP.count
+ IOP.io_errno = 0
+ except IOError,msg:
+ IOP.io_errno = -1
+ DebugMessage(
+ 100,
+ "Error writing data: " + msg + "\n"
+ )
+ return bRC_OK
+
+ elif IOP.func == IO_CLOSE:
+ if self.file:
+ self.file.close()
+ return bRC_OK
+
+ elif IOP.func == IO_SEEK:
+ return bRC_OK
+
+ else:
+ DebugMessage(
+ 100,
+ "plugin_io called with unsupported IOP:" + str(IOP.func) + "\n"
+ )
+ return bRC_OK
+
+ def end_backup_file(self):
+ '''
+ Check, if dump was successfull.
+ '''
+ # Usually the mysqldump process should have terminated here, but on some servers
+ # it has not always.
+ self.stream.wait()
+ returnCode = self.stream.poll()
+ if returnCode == None:
+ JobMessage(
+ M_ERROR,
+ "Dump command not finished properly for unknown reason"
+ )
+ returnCode = -99
+ else:
+ DebugMessage(
+ 100,
+ "end_backup_file() entry point in Python called. Returncode: %d\n"
+ % self.stream.returncode
+ )
+ if returnCode != 0:
+ (stdOut, stdError) = self.stream.communicate()
+ if stdError == None:
+ stdError = ''
+ JobMessage(
+ M_ERROR,
+ "Dump command returned non-zero value: %d, message: %s\n"
+ % (returnCode,stdError)
+ )
+
+ if self.databases:
+ return bRC_More
+ else:
+ if returnCode == 0:
+ return bRC_OK
+ else:
+ return bRC_Error
+
+
+# vim: ts=4 tabstop=4 expandtab shiftwidth=4 softtabstop=4
diff --git a/contrib/fd-plugins/mysql-python/README.md b/contrib/fd-plugins/mysql-python/README.md
new file mode 100644
index 000000000..93864472a
--- /dev/null
+++ b/contrib/fd-plugins/mysql-python/README.md
@@ -0,0 +1,90 @@
+# MySQL Plugin
+
+This plugin makes a backup of each database found in mysql in a single file.
+For restore select the needed database file, found in `/_mysqlbackups_` in the catalog.
+
+## Prerequisites
+The `mysqldump` and `mysql` command must be installed and user root (running the fd) must have read-access to the databases. See below, if you
+want to use another user / password or want to restrict database access for the backup user.
+
+You need the packages bareos-filedaemon-python-plugin installed on your client.
+
+## Configuration
+
+### Activate your plugin directory in the fd resource conf on the client
+```
+FileDaemon {
+ Name = client-fd
+ ...
+ Plugin Directory = /usr/lib64/bareos/plugins
+}
+```
+
+### Include the Plugin in the fileset definition on the director
+```
+FileSet {
+ Name = "client-data"
+ Include {
+ Options {
+ compression=GZIP
+ signature = MD5
+ }
+ File = /etc
+ #...
+ Plugin = "python:module_path=/usr/lib64/bareos/plugins:module_name=bareos-fd-mysql"
+ }
+}
+```
+
+#### Options ####
+
+##### Databases #####
+By default all found databases (except 'performance_schema' and 'information_schema') are backuped, if the paramater 'db' is unset. You can have the plugin only certain databases saved, if you add
+the parameter db=db1,db2, with a comma separated list of datbases. Also you can exclude specific database from backup by 'ignore_db' option with a comma separated list ignored databases.
+Example plugin string:
+```
+ Plugin = "python:module_path=/usr/lib64/bareos/plugins:module_name=bareos-fd-mysql:db=test,mysql"
+```
+This will backup only the databases with name 'test' and 'mysql'.
+
+##### Database host #####
+
+By default the mysql connection is made to localhost. If want to connect to another host, use
+```
+mysqlhost=hostname
+```
+
+##### mysqldump options #####
+
+By default the opition string
+```
+--events --single-transaction --add-drop-database --databases
+```
+is used.
+
+You may overwrite the whole option string with parameter dumpoptions or just supress the latter two, which are needed to include drop and
+create database statements into the dump. With drop_and_recreate set to 'false', these options are skipped.
+
+##### defaultsfile option ####
+
+This parameter allows to specify a defaultsfile that shall be used for mysql(client) and mysqldump command line utilities.
+
+
+##### Database access / user and password #####
+
+By default the root user (the user, which runs the Bareos filedaemon) is used to connect to the database. We recommend that you set
+a password for the user and store it in your my.cnf or use the defaultsfile option to point to another client configuration file.
+You can however set a user and / or password as plugin options:
+```
+mysqluser=username:mysqlpassword=secret
+```
+
+Minimum privileges for the backup user are:
+```
+GRANT USAGE ON *.* TO 'bareos'@'localhost' IDENTIFIED BY 'bareos';
+GRANT SELECT, LOCK TABLES, SHOW VIEW, EVENT, TRIGGER ON *.* TO 'bareos'@'localhost'
+```
+##### dumpbinary #####
+
+Command (with or without full path) to create the dumps. Default: mysqldump
+
diff --git a/contrib/fd-plugins/mysql-python/bareos-fd-mysql.py b/contrib/fd-plugins/mysql-python/bareos-fd-mysql.py
new file mode 100644
index 000000000..2b588e740
--- /dev/null
+++ b/contrib/fd-plugins/mysql-python/bareos-fd-mysql.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Bareos-fd-local-fileset a simple example for a python Bareos FD Plugin using BareosFdPluginLocalFileset
+# The plugin argument 'filename' is used to read all files listed in that file and add it to the fileset
+# License: AGPLv3
+
+# Provided by the Bareos FD Python plugin interface
+from bareosfd import *
+
+# This module contains the wrapper functions called by the Bareos-FD, the functions call the corresponding
+# methods from your plugin class
+from BareosFdWrapper import *
+
+# This module contains the used plugin class
+from BareosFdMySQLclass import *
+
+def load_bareos_plugin(plugindef):
+ '''
+ This function is called by the Bareos-FD to load the plugin
+ We use it to instantiate the plugin class
+ '''
+ # BareosFdWrapper.bareos_fd_plugin_object is the module attribute that holds the plugin class object
+ BareosFdWrapper.bareos_fd_plugin_object = BareosFdMySQLclass (plugindef);
+ return bRC_OK
+
+# the rest is done in the Plugin module
diff --git a/contrib/fd-plugins/options-plugin-sample/BareosFdPluginFileInteract.py b/contrib/fd-plugins/options-plugin-sample/BareosFdPluginFileInteract.py
new file mode 100644
index 000000000..e29bbcabb
--- /dev/null
+++ b/contrib/fd-plugins/options-plugin-sample/BareosFdPluginFileInteract.py
@@ -0,0 +1,28 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Bareos python class as stub for option plugin
+# handle_backup_file gets called for each file in the backup
+#
+# (c) Bareos GmbH & Co. KG
+# AGPL v.3
+# Author: Maik Aussendorf
+
+from bareosfd import *
+from bareos_fd_consts import *
+import os
+from BareosFdPluginBaseclass import *
+import BareosFdWrapper
+
+class BareosFdPluginFileInteract (BareosFdPluginBaseclass):
+
+ def handle_backup_file(self,context, savepkt):
+ DebugMessage(context, 100, "handle_backup_file called with " + str(savepkt) + "\n");
+ DebugMessage(context, 100, "fname: " + savepkt.fname + " Type: " + str(savepkt.type) + "\n");
+ if ( savepkt.type == bFileType['FT_REG'] ):
+ DebugMessage(context, 100, "regulaer file, do something now...\n");
+ # add your stuff here
+
+ return bRCs['bRC_OK'];
+
+
diff --git a/contrib/fd-plugins/options-plugin-sample/README.md b/contrib/fd-plugins/options-plugin-sample/README.md
new file mode 100644
index 000000000..6c7a59acd
--- /dev/null
+++ b/contrib/fd-plugins/options-plugin-sample/README.md
@@ -0,0 +1,33 @@
+# FD Option Plugin stub
+Sample for an option plugin. The method handle_backup_file gets called for each file in the backup, you can use this
+as template for your option plugin to implement some extra action on files.
+
+## Prerequisites
+You need the package bareos-filedaemon-python-plugin installed on your client.
+
+## Configuration
+
+### Activate your plugin directory in the fd resource conf on the client
+```
+FileDaemon {
+ Name = client-fd
+ ...
+ Plugin Directory = /usr/lib64/bareos/plugins
+}
+```
+
+### Include the Plugin in the fileset / option definition on the director
+```
+FileSet {
+ Name = "client-data"
+ Include {
+ Options {
+ compression=GZIP
+ signature = MD5
+ Plugin = "python:module_path=/usr/lib64/bareos/plugins:module_name=bareos-fd-file-interact"
+ }
+ File = /etc
+ #...
+ }
+}
+```
diff --git a/contrib/fd-plugins/options-plugin-sample/bareos-fd-file-interact.py b/contrib/fd-plugins/options-plugin-sample/bareos-fd-file-interact.py
new file mode 100644
index 000000000..42e64113a
--- /dev/null
+++ b/contrib/fd-plugins/options-plugin-sample/bareos-fd-file-interact.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Bareos-fd-local-fileset a simple example for a python Bareos FD Plugin using BareosFdPluginLocalFileset
+# The plugin argument 'filename' is used to read all files listed in that file and add it to the fileset
+
+# Provided by the Bareos FD Python plugin interface
+from bareosfd import *
+from bareos_fd_consts import *
+
+# This module contains the wrapper functions called by the Bareos-FD, the functions call the corresponding
+# methods from your plugin class
+from BareosFdWrapper import *
+
+# This module contains the used plugin class
+from BareosFdPluginFileInteract import *
+
+def load_bareos_plugin(context, plugindef):
+ '''
+ This function is called by the Bareos-FD to load the plugin
+ We use it to intantiate the plugin class
+ '''
+ # BareosFdWrapper.bareos_fd_plugin_object is the module attribute that holds the plugin class object
+ BareosFdWrapper.bareos_fd_plugin_object = BareosFdPluginFileInteract (context, plugindef);
+ return bRCs['bRC_OK'];
+
+# the rest is done in the Plugin module
diff --git a/contrib/fd-plugins/plugins_intro.pdf b/contrib/fd-plugins/plugins_intro.pdf
new file mode 100644
index 000000000..80dd1dece
--- /dev/null
+++ b/contrib/fd-plugins/plugins_intro.pdf
Binary files differ
diff --git a/contrib/misc/bareos-migrate-config/bareos-migrate-config.sh b/contrib/misc/bareos-migrate-config/bareos-migrate-config.sh
new file mode 100755
index 000000000..56097ccaa
--- /dev/null
+++ b/contrib/misc/bareos-migrate-config/bareos-migrate-config.sh
@@ -0,0 +1,46 @@
+#!/bin/bash
+
+#
+# Split existing configuration into separate resource files, as used by the
+# http://doc.bareos.org/master/html/bareos-manual-main-reference.html#SubdirectoryConfigurationScheme
+#
+# Author: philipp.storz@bareos.com
+#
+
+BCONSOLE=${BCONSOLE:-/usr/bin/bconsole}
+
+bconsole()
+{
+ local out="$1"
+ local cmd="$2"
+ local temp=`mktemp`
+ printf "%s\n%s\n%s\n" "gui on" "@out $temp" "$cmd" | $BCONSOLE > /dev/null
+ # The send command is also written to the output. Remove it.
+ # Error messages normally also contain the command, so they are also removed.
+ grep -v -e "$cmd" "$temp" > "$out"
+}
+
+for restype in catalog client console counter director fileset job jobdefs messages pool profile schedule storage; do
+ printf "\n%s:\n" "$restype"
+ printf "==========\n"
+ mkdir $restype 2>/dev/null
+ if [ $restype = director ]; then
+ bconsole "$restype/bareos-dir.conf" "show director"
+ else
+ dotcommand=".${restype}"
+ if [ $restype = "messages" ]; then
+ dotcommand=".msgs"
+ elif [ $restype = "job" ]; then
+ dotcommand=".jobs"
+ fi
+ TEMP=`mktemp`
+ bconsole "$TEMP" "$dotcommand"
+ cat $TEMP
+ while read res; do
+ #CONFFILENAME=`sed 's/ /_/g' <<< ${res}`
+ CONFFILENAME="${res}"
+ bconsole "$restype/${CONFFILENAME}.conf" "show ${restype}=\"${res}\""
+ done < $TEMP
+ fi
+done
+
diff --git a/contrib/misc/bareos_pam_integration/README.rst b/contrib/misc/bareos_pam_integration/README.rst
new file mode 100644
index 000000000..e7a29e352
--- /dev/null
+++ b/contrib/misc/bareos_pam_integration/README.rst
@@ -0,0 +1,173 @@
+Bareos PAM Integration
+======================
+
+PAM, the *Pluggable Authentication Modules* used by Linux
+provide dynamic authentication support for applications and services in a Linux system.
+
+PAM authentication is included since Bareos >= 18.2, see https://docs.bareos.org/master/TasksAndConcepts/PAM.html#configuration
+
+However, this supports only the authentication mechanism.
+That means, the user must be known in the backend system used by PAM (:file:`/etc/passwd`, LDAP or ...)
+**and** the user has to exist in the Bareos Director.
+
+The PAM implementation of Bareos is only used for authentication of console connections.
+Console access is only provided by the Bareos Director.
+
+PAM Configuration
+-----------------
+
+By default, PAM configuration files resides in the directory :file:`/etc/pam.d/`.
+
+Authentication using PAM is requested by a service name.
+The Bareos Director uses the service name **bareos**.
+The corresponding configuration file is :file:`/etc/pam.d/bareos`.
+If this file does not exist, PAM uses the fallback file :file:`/etc/pam.d/other`.
+
+Often PAM is offered by system services, meaning the calling process has *root* priviliges.
+In contrast, the Bareos Director on Linux runs as user *bareos*,
+therefore by default it might not offer all required functionality.
+
+Known Limitations of PAM Modules
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+:pam_unix:
+ When authenticating with pam_unix, it tries to read system files,
+ including the file :file:`/etc/shadow`.
+ By default, the user *bareos* do not have the permission to read this file.
+ If this functionality is required, adapt the priviliges accordingly
+ (e.g. add the user bareos to the group owning the file).
+
+:pam_ldap:
+ When using pam_ldap make sure
+ your configuration does not require the rootbinddn and :file:`/etc/pam_ldap.secret` settings.
+ Instead use the binddn/bindpw settings (if required).
+
+Another limitation is, that some PAM modules do not ask for a login name.
+They only ask for the password.
+As result, the bconsole command (without the -p parameter)
+will only ask for a password, but not the login name.
+As the user is unknown, the authentication fails.
+
+One method to circumvent this
+is to provide the PAM credentials to the bconsole by an extra credentials file.
+This credentials file is adressed by the bconsole -p parameter.
+
+Testing PAM Authentication
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+If you have configured the PAM settings for Bareos (:file:`/etc/pam.d/bareos`),
+you can test it outside of Bareos.
+
+Make sure, the program **pamtester** (package: pamtester on Debian) is installed.
+
+In this example, we will test, if the user USER_TO_TEST can be successfully authenticated by PAM.
+
+::
+
+ # switch to user bareos, to run with the same priviliges as bareos-dir
+ su - bareos -s /bin/bash
+
+ # use pamtester to try authentication by the PAM service bareos
+ pamtester bareos USER_TO_TEST authenticate
+
+
+Pamtester will ask for a password.
+After providing this,
+it will print if the user can be authenticated successfully (output: "pamtester: successfully authenticated") or not.
+
+Testing PAM Authentication of the Bareos Director
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+After PAM has been successfully tested using pamtester,
+it can be tested using the bareos-dir.
+
+Configure the Bareos Director as described by https://docs.bareos.org/master/TasksAndConcepts/PAM.html#configuration.
+
+Create a bconsole configuration file, name it :file:`bconsole-pam.conf`.
+
+Test to connect via bconsole to the bareos-dir::
+
+ $ bconsole -c bconsole-pam.conf
+ Connecting to Director localhost:9101
+ Encryption: ECDHE-PSK-CHACHA20-POLY1305
+ Login:USER_TO_TEST
+ Passwort: ********
+ 1000 OK: bareos-dir Version: 19.1.2 (01 February 2019)
+ You are logged in as: USER_TO_TEST
+
+ Enter a period to cancel a command.
+ *
+
+After successfully testing with bconsole, the Bareos WebUI can be tested.
+
+Reuse your existing PamConsole or create an additional one::
+
+ Console {
+ Name = "pam-webui"
+ Password = "secret"
+ UsePamAuthentication = yes
+ TLS Enable = no
+ }
+
+As PHP does not yet support TLS-PSK, the setting ``TLS Enable = no`` is required.
+Therefore it is advised to run the Bareos Director and Bareos WebUI on the same host.
+
+You may want to add following section to your :file:`/etc/bareos-webui/directors.ini`::
+
+ [localhost-dir-pam]
+ enabled = "yes"
+ diraddress = "localhost"
+ dirport = 9101
+ tls_verify_peer = false
+ server_can_do_tls = false
+ server_requires_tls = false
+ client_can_do_tls = false
+ client_requires_tls = false
+ pam_console_name = "pam-webui"
+ pam_console_password = "secret"
+
+Now you should be able to login to the WebUI using PAM users.
+
+
+Auto Create Bareos Users
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+Until now, only PAM users that are already configured in the Bareos Director can login.
+
+The PAM script ``pam_exec_add_bareos_user.py`` can circumvent this.
+
+It can be integrated into the Bareos PAM configuration by ``pam_exec`` .
+
+This version of the script requires at least Bareos >= 19.2.4.
+
+Installation
+^^^^^^^^^^^^
+
+* Verify that ``pam_exec`` is installed. On Debian it is part of the PAM base package **libpam-modules**.
+* Install ``python-bareos``.
+* Copy ``pam_exec_add_bareos_user.py`` to :file:`/usr/local/bin/`.
+
+Create a Bareos console for user pam-adduser:
+
+::
+
+ Console {
+ Name = "pam-adduser"
+ Password = "secret"
+ CommandACL = ".api", ".profiles", ".users", "configure", "version"
+ TlsEnable = no
+ }
+
+
+Add a pam_exec line to the PAM configuration file :file:`/etc/pam.d/bareos`.
+This example uses pam_ldap to authenticate.
+
+::
+
+ auth requisite pam_ldap.so
+ auth [default=ignore] pam_exec.so /usr/local/bin/pam_exec_add_bareos_user.py --name pam-adduser --password secret --profile webui-admin
+
+Make sure, an unsuccessful authentication ends before pam_exec.so.
+In this example, this is done by the *requisite* keyword (when not successful, stop executing the PAM stack).
+
+Using this, a user who successfully authenticates against LDAP, will be created as Bareos user with ACLs as defined in profile *webui-admin*.
diff --git a/contrib/misc/bareos_pam_integration/pam_exec_add_bareos_user.py b/contrib/misc/bareos_pam_integration/pam_exec_add_bareos_user.py
new file mode 100755
index 000000000..aae864afd
--- /dev/null
+++ b/contrib/misc/bareos_pam_integration/pam_exec_add_bareos_user.py
@@ -0,0 +1,145 @@
+#!/usr/bin/env python
+
+"""
+This script is intended to be integrated with pam_exec into the Linux authentication process.
+It can be used to auto-create users that do already exist as PAM users as Bareos users.
+
+Requires Bareos >= 19.2.4.
+"""
+
+from __future__ import print_function
+import argparse
+import bareos.bsock
+import bareos.exceptions
+import logging
+import os
+from pprint import pformat
+import random
+import string
+import sys
+
+
+def check_requirements(director):
+ min_version = "19.2.4"
+ logger = logging.getLogger()
+ logger.debug("checking requirements: start")
+ try:
+ result = director.call(".users")
+ except (bareos.exceptions.Error) as e:
+ logger.error(
+ "The .users command is required, but not available: {}".format(str(e))
+ )
+ sys.exit(1)
+ try:
+ result = director.call("version")
+ except (bareos.exceptions.Error) as e:
+ logger.error(
+ "The version command is required, but not available: {}".format(str(e))
+ )
+ sys.exit(1)
+ version = result["version"]["version"]
+ if version < min_version:
+ logger.error(
+ "Bareos has version {}. However Bareos >= {} is required.".format(
+ version, min_version
+ )
+ )
+ sys.exit(1)
+ logger.debug("checking requirements: finish")
+
+
+def get_user_names(director):
+ result = director.call(".users")["users"]
+ users = [i["name"] for i in result]
+ return users
+
+
+def does_user_exists(director, username):
+ return username in get_user_names(director)
+
+
+def add_user(director, username, profile):
+
+ result = director.call(
+ 'configure add user="{username}" profile="{profile}"'.format(
+ username=username, profile=profile
+ )
+ )
+
+ try:
+ if result["configure"]["add"]["name"] != username:
+ logger.error("Failed to create user {}.".format(username))
+ # logger.debug(str(result))
+ return False
+ except KeyError:
+ logger.debug("result: {}".format(pformat(result)))
+ errormessage = pformat(result)
+ try:
+ errormessage = "".join(result["error"]["data"]["messages"]["error"])
+ except KeyError:
+ pass
+ print("Failed to add user {}:\n".format(username))
+ print("{}".format(errormessage))
+ return False
+
+ return True
+
+
+def getArguments():
+ argparser = argparse.ArgumentParser(
+ description="Add a PAM user to Bareos Director."
+ )
+ argparser.add_argument(
+ "-d", "--debug", action="store_true", help="enable debugging output"
+ )
+ bareos.bsock.DirectorConsole.argparser_add_default_command_line_arguments(argparser)
+ argparser.add_argument(
+ "--username", help="Name of the user to add. Default: content of ENV(PAM_USER)"
+ )
+ argparser.add_argument(
+ "--profile",
+ default="webui-admin",
+ help="Bareos Profile for the newly generated user",
+ )
+ args = argparser.parse_args()
+ return args
+
+
+if __name__ == "__main__":
+ logging.basicConfig(
+ format="%(levelname)s %(module)s.%(funcName)s: %(message)s", level=logging.INFO
+ )
+ logger = logging.getLogger()
+
+ args = getArguments()
+ if args.debug:
+ logger.setLevel(logging.DEBUG)
+
+ bareos_args = bareos.bsock.DirectorConsole.argparser_get_bareos_parameter(args)
+ logger.debug("options: %s" % (bareos_args))
+
+ try:
+ director = bareos.bsock.DirectorConsoleJson(**bareos_args)
+ except (bareos.exceptions.Error) as e:
+ print(str(e))
+ sys.exit(1)
+ logger.debug("authentication successful")
+
+ check_requirements(director)
+
+ username = os.getenv("PAM_USER", args.username)
+ profile = getattr(args, "profile", "webui-admin")
+
+ if username is None:
+ logger.error("Failed: Username not given.")
+ sys.exit(1)
+
+ if does_user_exists(director, username):
+ print("Skipped. User {} already exists.".format(username))
+ sys.exit(0)
+
+ if not add_user(director, username, profile):
+ logger.error("Failed to add user {}.".format(username))
+ sys.exit(1)
+
+ print("Added user {} (with profile {}) to Bareos.".format(username, profile))
diff --git a/contrib/misc/bsmc/LICENSE b/contrib/misc/bsmc/LICENSE
new file mode 100644
index 000000000..9591157b0
--- /dev/null
+++ b/contrib/misc/bsmc/LICENSE
@@ -0,0 +1,662 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published
+ by the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program 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 Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<http://www.gnu.org/licenses/>.
+
diff --git a/contrib/misc/bsmc/README.md b/contrib/misc/bsmc/README.md
new file mode 100644
index 000000000..d370b6c23
--- /dev/null
+++ b/contrib/misc/bsmc/README.md
@@ -0,0 +1,55 @@
+PoC code to implement a Bareos commandline tool that allows to trigger
+common tasks from a Bareos client.
+bsmc stands for "Bareos simple management cli"
+
+Implemented are show scheduler, trigger incremental backup and restore a
+single given file. Further the bsmc archive command backups all given
+filenames and directories using a predefined archive job.
+
+Sample Calls:
+```
+bsmc rest filename
+bsmc incr
+bsmc query sched
+bsmc archive /etc/vimrc /etc/bash.bashrc /etc/profile.d/
+```
+
+Query for lost files and restore:
+```
+[root@titania etc]# rm -f vimrc
+[root@titania etc]# bsmc query lost
+./vimrc
+[root@titania etc]# bsmc rest vimrc
+INFO bsmc.runJob: Job scheduled with JobId: 166
+INFO bsmc.runJob: OK: Job 166 finished with with status T
+[root@titania etc]# ls -l vimrc
+-rw-r--r--. 1 root root 2029 15. Okt 11:36 vimrc
+```
+
+You need a config file
+/etc/bareos/bsmc.conf
+
+This contains information about how to connect to the director and
+basic information about the client itself like fd name and jobs that
+are associated with this client.
+
+Sample bsmc.conf:
+```
+[director]
+server=laptop.fqhn
+name=laptop-dir
+password=geheim
+
+[client]
+# fd name
+name=laptop-fd
+jobs=BackupClient1,some,other,jobs
+# this job will be used for 'bsmc archive' calls
+archivejob=archive
+# Used as includefile by the archivejob and will be temporarily created
+# and filled by 'bsmc archive' calls
+archivefilelist=/tmp/bsmc.archive
+```
+
+Sample configuration for an archive job to be in included in your bareos-dir.conf is here:
+etc/bareos/bareos-dir.d/archivejob.conf
diff --git a/contrib/misc/bsmc/bin/bsmc b/contrib/misc/bsmc/bin/bsmc
new file mode 100755
index 000000000..a22ff24c9
--- /dev/null
+++ b/contrib/misc/bsmc/bin/bsmc
@@ -0,0 +1,442 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+# BAREOSĀ® - Backup Archiving REcovery Open Sourced
+#
+# Copyright (C) 2015-2018 Bareos GmbH & Co. KG
+#
+# This program is Free Software; you can redistribute it and/or
+# modify it under the terms of version three of the GNU Affero General Public
+# License as published by the Free Software Foundation, which is
+# listed in the file LICENSE.
+#
+# This program 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
+# Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# Author: Maik Aussendorf
+#
+# PoC code to implement a Bareos commandline tool that allows to trigger
+# common tasks from a Bareos client.
+# bsmc stands for "Bareos simple management cli"
+#
+# Implemented are show scheduler, trigger incremental backup and restore a
+# single given file.
+#
+
+
+import ConfigParser
+import argparse
+import bareos.bsock
+import logging
+import time
+import sys
+import re
+import os
+#import fcntl
+import struct
+import random
+import string
+
+
+def getArguments():
+ '''
+ CLI argument parser
+ '''
+ parser = argparse.ArgumentParser(description='CLI to Bareos director.', prog="bsmc")
+ parser.add_argument('-d', '--debug', action='store_true', help="enable debugging output")
+ parser.add_argument('-p', '--password', help="password to authenticate at Bareos Director")
+ subparsers = parser.add_subparsers(help='Run \'bsmc subcommand help\'', dest='command')
+ parser_query = subparsers.add_parser(
+ 'query', help='query command is used to query information from director')
+ parser_query.add_argument('queryobject', default='status',
+ choices=['sched', 'schedule', 'status', 'lost'], help="Object to query")
+ parser_query.add_argument('-r', '--recursive', action='store_true', default=False,
+ dest='query_recursive', help="query lost files recursively")
+ parser_incremental = subparsers.add_parser(
+ 'incr', help='run incremental job(s) defined for this client')
+ parser_restore = subparsers.add_parser(
+ 'rest', help="Restore a file or directory")
+ parser_restore.add_argument('filename', help="File or directory to restore")
+ parser_restore.add_argument("-l","--lost", help=
+ "Restore any lost file found in backup in directory given by filename argument", action='store_true', default=False)
+ parser_restore.add_argument("-d", "--destination", help="Directory prefix for restore," +
+ " default =None, will restore to original place in filesystem. Ignored with -l",
+ default=None)
+ parser_restore.add_argument("-o","--restoreoption",
+ help="Option-string added to restore command. Be careful", default='')
+ parser_archive = subparsers.add_parser(
+ 'archive', help="Archive a list of files and / or directories")
+ parser_archive.add_argument('filenames', nargs='+',
+ help="list of files and / or directories to archive")
+ args = parser.parse_args()
+ return args
+
+def getLostFiles(client, searchpath, recursive=False, printPrefix="./"):
+ '''
+ List all files in searchpath that exist in a backup but not in
+ the filesystem. Use recursive=True to iterate through subdirectories
+ Return triple:
+ 1. list of lost filenames
+ 2. list of FileIds
+ 3. Set of job ids
+ '''
+ lostFiles = []
+ lostFileIds = []
+ relevantJobIds = set()
+ jobids = getClientJobs (client)
+ jobIdList = 'jobid={}'.format(','.join(jobids))
+ # first refresh bvfs_cache regarding needed jobids
+ dirCommand = ".bvfs_update %s" %jobIdList
+ logger.debug ("command: %s" %dirCommand)
+ jsonDirector.call(dirCommand)
+ dirCommand = ".bvfs_lsfiles %s path=\"%s\"" %(jobIdList, searchpath)
+ res = jsonDirector.call(dirCommand)
+ if 'files' in res:
+ for file in res['files']:
+ if not 'name' in file:
+ continue
+ if not (os.path.lexists(searchpath + file['name'])):
+ lostFiles.append(printPrefix + file['name'])
+ lostFileIds.append(file['fileid'])
+ relevantJobIds.add(file['jobid'])
+ dirCommand = ".bvfs_lsdirs %s path=\"%s\"" %(jobIdList, searchpath)
+ res = jsonDirector.call(dirCommand)
+ if 'directories' in res:
+ for dir in res['directories']:
+ if dir['name'] == '.' or dir['name'] == '..':
+ continue
+ if recursive:
+ rLostFiles, rLostIds, rJobIds = getLostFiles(client, searchpath + dir['name'],
+ True, printPrefix + dir['name'])
+ lostFiles += rLostFiles
+ lostFileIds += rLostIds
+ relevantJobIds.update(rJobIds)
+ return (lostFiles, lostFileIds, relevantJobIds)
+
+def query(queryobject, client, query_recursive=False):
+ '''
+ Query scheduler information for client
+ '''
+ if queryobject in ["sched", "schedule"]:
+ command = "status scheduler client=" + client
+ director.send(command)
+ msg = director.recv_msg()
+ sys.stdout.write(msg)
+ elif queryobject in ['status', 'st']:
+ command = "status client=" + client
+ director.send(command)
+ msg = director.recv_msg()
+ sys.stdout.write(msg)
+ elif queryobject in ['lost']:
+ myPath = os.getcwd()
+ if not myPath == '/':
+ myPath += '/'
+ fileNames, fileIds, jobIds = getLostFiles(client, myPath, query_recursive)
+ print ('\n'.join(fileNames))
+ else:
+ logger.error("Unknown query object " + queryobject)
+
+def getClientJobs(client):
+ '''
+ Get list of jobs for a client
+ '''
+ res = jsonDirector.call('list jobs client={}'.format(client))
+ jobids = []
+ for job in res['jobs']:
+ if job['jobstatus'] in ['T', 'W'] and job['type'] == 'B':
+ jobids.append(job['jobid'])
+ return jobids
+
+def waitForJob(jobId):
+ '''
+ Wait for a given job to finish and return a tupel (jobStatus, job message).
+ Returns a tupel (char jobStatus, string jobMessage)
+
+ Arguments
+ jobID -- int job ID to wait for
+ '''
+ command = "wait jobid=%s" % jobId
+ result=jsonDirector.call(command)
+ if 'Job' not in result:
+ logger.error("No Job Status found for JobId=%d\n" % jobId)
+ return (None, None)
+ else:
+ jobStatus = result['Job']['jobstatus']
+ jobMsg = result['Job']['jobstatuslong']
+ return (jobStatus, jobMsg)
+
+
+def incremental(client_joblist=None):
+ '''
+ Trigger incremental backup for client, using client_joblist
+ Returns 0, if all jobs went fine, number of jobs with errors otherwise
+ '''
+ if client_joblist is None:
+ # TODO: use all jobs configured for client instead of error here
+ logger.error("No joblist configured. Use 'jobs' in [client] section" +
+ " of your bsmc config file")
+ return 1
+ errors = 0
+ warnings = 0
+ successful = 0
+ jobList = []
+ for job in client_joblist:
+ backup_command = "run client=%s level=Incremental job=%s yes" % (client_fd, job)
+ logger.debug("running %s\n" % backup_command)
+ (jobId, jobStatus) = runJob(backup_command)
+ if jobId is None:
+ continue
+ else:
+ jobList.append(jobId)
+
+ # now wait until all started jobs are done and report results
+ for job in jobList:
+ jobResult, jobMessage = waitForJob(job)
+
+ if jobResult in ['E', 'f']:
+ logger.error("Job %d finished with with status %s" % (job, jobResult))
+ errors += 1
+ elif jobResult in ['W', 'A']:
+ logger.warning("Job %d finished with with status %s" % (job, jobResult))
+ warnings += 1
+ elif jobResult == 'T':
+ logger.info("Job %d finished with with status %s" % (job, jobResult))
+ successful += 1
+ else:
+ logger.warning("Job %d has unrecognized status %s" % (job, jobResult))
+ warnings += 1
+
+ logger.info("Run %d jobs, with %d warnings and %d errors."
+ % (len(client_joblist), warnings, errors))
+ return errors
+
+def restoreFiles(fileList, fileIds, jobIds, optionString=''):
+ '''
+ Restore a list of files with an optional relocationString
+ Arguments:
+ fileList: list of files
+ optionString: general options for the restore command, no error checking here
+ '''
+ tableId = "b2" + ''.join(random.choice(string.digits) for _ in range(9))
+ command = ".bvfs_restore fileid=%s jobid=%s path=%s" %(','.join(map(str,fileIds)), ','.join(map(str,jobIds)), tableId)
+ logger.debug("command: %s" %command)
+ result = jsonDirector.call(command)
+ command = "restore file=?%s client=%s %s" %(tableId, client_fd, optionString)
+ logger.debug("command: %s" %command)
+ (jobId, jobResult) = runJob(command, True)
+ restoreResult = jobResult in ['T']
+ command = ".bvfs_cleanup path=%s" %tableId
+ logger.debug("command: %s" %command)
+ result = jsonDirector.call(command)
+ return restoreResult
+
+
+def restoreFile(filename, relocation=None):
+ '''
+ Restore a single file. Returns 0, if file got restored without errors, 1 otherwise
+ Arguments:
+ filename -- The filename with full path to restore
+ relocation -- Recover file to either a given directory or to a
+ filename (if relocation is not a directory). Default: original filename
+ '''
+ filename = os.path.abspath(filename)
+ filename = filename.encode('string-escape')
+ where = '/'
+ if relocation is None:
+ relocationString = ''
+ elif os.path.isdir(relocation):
+ relocationString = "strip_prefix=.*/ add_prefix=/%s/" % relocation
+ else:
+ relocationString = "strip_prefix=.* add_prefix=%s" % relocation
+
+ restore_command = ("restore file=%s client=%s %s where=%s yes"
+ % (filename, client_fd, relocationString, where))
+ logger.debug("Command: %s" % restore_command)
+ (jobId, jobResult) = runJob(restore_command, True)
+ return jobResult in ['T']
+
+
+def runJob(jobCommand, wait=False):
+ '''
+ Runs the job specified by jobCommand
+ and return (jobId, None) if wait is false,
+ otherwise wait until job has finished and return
+ tupel (jobID, jobStatus), with jobSTatus in {E,f,W,A,T}
+ '''
+ result=jsonDirector.call(jobCommand)
+ if 'run' in result:
+ jobId = int(result['run']['jobid'])
+ logger.info("Job scheduled with JobId: %s" % jobId)
+ else:
+ logger.error("Warning: No JobId returned. Message was: %s" % result)
+ return (None, None)
+
+ if not wait:
+ # TODO get and return jobStatus here (failed, running, waiting)
+ return (jobId, None)
+
+ (jobResult, jobMessage) = waitForJob(jobId)
+ logger.debug("JobResult for job %d is: :%s, jobMessage: %s" % (jobId, jobResult, jobMessage))
+
+ if jobResult in ['E', 'f']:
+ logger.error("Job %d finished with with status %s. Message: %s"
+ % (jobId, jobResult, jobMessage))
+ elif jobResult in ['W', 'A']:
+ logger.warning("Job %d finished with with status %s. Message: %s"
+ % (jobId, jobResult, jobMessage))
+ elif jobResult == 'T':
+ logger.info("OK: Job %d finished with with status %s" % (jobId, jobResult))
+ else:
+ logger.warning("Job %d has unrecognized status %s. Message: %s"
+ % (jobId, jobResult, jobMessage))
+ errors += 1
+ return (jobId, jobResult)
+
+
+def lockFile(fileName, waitIfLocked=False, waitIntervall=1):
+ '''
+ Checks, if a file is locked by another process.
+ fileName : Filename to lock (append a suffix and write pid to lockfile
+ waitIfLocked: if true, wait until existings lock has disappeared
+ waitIntervall: if waiting, then retry every n seconds set here
+ returns success (true / false)
+ '''
+ lockFilename = fileName + ".lock"
+ if os.path.isfile(lockFilename):
+ if not waitIfLocked:
+ logger.warning("File %s is locked by another process, quit." % fileName)
+ return False
+ else:
+ logger.info("File %s is locked by another process. Waiting." % fileName)
+ needLineBreak = False
+ while os.path.isfile(lockFilename):
+ time.sleep(waitIntervall)
+ sys.stdout.write('.')
+ sys.stdout.flush()
+ needLineBreak = True
+ f = open(lockFilename, "wb")
+ f.write(str(os.getpid()))
+ f.close()
+ if needLineBreak:
+ sys.stdout.write('\n')
+ sys.stdout.flush()
+ return True
+
+
+def unlockFile(fileName):
+ '''
+ Unlock a file previously locked with lockFile()
+ '''
+ lockFilename = fileName + ".lock"
+ if not os.path.isfile(lockFilename):
+ logger.warning("File %s is not locked, while trying to unlock it" % fileName)
+ try:
+ os.remove(lockFilename)
+ except IOError as e:
+ logger.error("Could not remove lockfile '%s'" % lockFilename)
+
+
+def archiveFiles(fileNames):
+ '''
+ Creates a temporary filelist with files to backup
+ and start a predefined archive job for those files
+ '''
+ if client_archivefilelist is None or client_archivejob is None:
+ logger.error("Need archivejob and archivefilelist set in " +
+ "configuration file to run archive jobs")
+ return 1
+ lockFile(client_archivefilelist, waitIfLocked=True)
+ fl = open(client_archivefilelist, "wb")
+
+ for fileName in fileNames:
+ absolute_filename = os.path.abspath(fileName)
+ fl.write(absolute_filename)
+ fl.write('\n')
+ fl.close()
+ jobCommand = "run client=%s job=%s yes" % (client_fd, client_archivejob)
+ (jobId, jobResult) = runJob(jobCommand, True)
+ try:
+ os.remove(client_archivefilelist)
+ except IOError as e:
+ logger.warning("Could not remove file for archive files '%s'" % client_archivefilelist)
+ unlockFile(client_archivefilelist)
+ return jobResult in ['T']
+
+if __name__ == '__main__':
+ logging.basicConfig(format='%(levelname)s %(module)s.%(funcName)s: %(message)s',
+ level=logging.INFO)
+ logger = logging.getLogger()
+
+ args = getArguments()
+ if args.debug:
+ logger.setLevel(logging.DEBUG)
+
+ parser = ConfigParser.SafeConfigParser({'port': '9101'})
+ # TODO make configfile an option
+ parser.readfp(open("/etc/bareos/bsmc.conf", "r"))
+
+ host = parser.get("director", "server")
+ dirname = parser.get("director", "name")
+ password = parser.get("director", "password")
+ dir_port = parser.getint("director", "port")
+ # TODO: restructure client as directory
+ client_fd = parser.get("client", "name")
+ # Relevant jobs for this client to be run when triggering "incremental" jobs.
+ if parser.has_option("client", "jobs"):
+ client_joblist = parser.get("client", "jobs").split(',')
+ logger.debug(client_joblist)
+ else:
+ client_joblist = None
+ if parser.has_option("client", "archivejob"):
+ client_archivejob = parser.get("client", "archivejob")
+ else:
+ client_archivejob = None
+
+ if parser.has_option("client", "archivefilelist"):
+ client_archivefilelist = parser.get("client", "archivefilelist")
+ else:
+ client_archivefilelist = None
+
+ try:
+ director = bareos.bsock.BSock(address=host, port=dir_port, dirname=dirname,
+ password=bareos.bsock.Password(password))
+ # Another director of class json
+ jsonDirector = bareos.bsock.DirectorConsoleJson(address=host, port=dir_port, dirname=dirname,
+ password=bareos.bsock.Password(password))
+ except RuntimeError as e:
+ print str(e)
+ sys.exit(1)
+
+ logger.debug("Command: " + args.command + "\n")
+
+ if args.command in ["query", 'q']:
+ query(args.queryobject, client_fd, args.query_recursive)
+ elif args.command in ['Incremental', 'incr']:
+ exitCode = incremental(client_joblist)
+ sys.exit(exitCode)
+ elif args.command in ['restore', 'rest']:
+ if args.lost:
+ if not os.path.isdir(args.filename):
+ logger.error("Restore lost files requires directory as filename argument")
+ sys.exit(1)
+ lostFiles, fileIds, jobIds = getLostFiles(client_fd, args.filename, True, args.filename)
+ if lostFiles:
+ jobDone = restoreFiles (lostFiles, fileIds, jobIds, args.restoreoption)
+ else:
+ logger.info ("no lost files found")
+ jobDone = True
+ else:
+ jobDone = restoreFile(args.filename, args.destination)
+ if jobDone:
+ sys.exit(0)
+ else:
+ sys.exit(1)
+ elif (args.command in ['archive', 'arch']):
+ if archiveFiles(args.filenames):
+ sys.exit(0)
diff --git a/contrib/misc/bsmc/debian/compat b/contrib/misc/bsmc/debian/compat
new file mode 100644
index 000000000..7f8f011eb
--- /dev/null
+++ b/contrib/misc/bsmc/debian/compat
@@ -0,0 +1 @@
+7
diff --git a/contrib/misc/bsmc/debian/control b/contrib/misc/bsmc/debian/control
new file mode 100644
index 000000000..24940eded
--- /dev/null
+++ b/contrib/misc/bsmc/debian/control
@@ -0,0 +1,14 @@
+Source: bareos-bsmc
+Maintainer: Maik Aussendorf <maik.aussendorf@bareos.com>
+Section: python
+Priority: optional
+Build-Depends: debhelper (>= 7.4.3)
+Standards-Version: 3.9.1
+
+Package: bareos-bsmc
+Architecture: all
+Depends: ${misc:Depends}, ${python:Depends}, python-bareos
+# required for restoring
+Recommends: bareos-filedaemon (>=15.2.1)
+Description: Backup Archiving Recovery Open Sourced - bsmc
+ bareos-bsmc is a CLI to trigger backup, restore, or archive-jobs from the command line.
diff --git a/contrib/misc/bsmc/debian/install b/contrib/misc/bsmc/debian/install
new file mode 100644
index 000000000..ae814f6cd
--- /dev/null
+++ b/contrib/misc/bsmc/debian/install
@@ -0,0 +1,3 @@
+/bin/*
+/etc/bareos/*
+/etc/bareos/bareos-dir.d/*
diff --git a/contrib/misc/bsmc/debian/rules b/contrib/misc/bsmc/debian/rules
new file mode 100755
index 000000000..ccb292c93
--- /dev/null
+++ b/contrib/misc/bsmc/debian/rules
@@ -0,0 +1,7 @@
+#!/usr/bin/make -f
+
+# This file was automatically generated by stdeb 0.6.0+git at
+# Mon, 07 Sep 2015 16:46:19 +0200
+
+%:
+ dh $@
diff --git a/contrib/misc/bsmc/debian/source/format b/contrib/misc/bsmc/debian/source/format
new file mode 100644
index 000000000..d3827e75a
--- /dev/null
+++ b/contrib/misc/bsmc/debian/source/format
@@ -0,0 +1 @@
+1.0
diff --git a/contrib/misc/bsmc/etc/bareos/bareos-dir.d/archivejob.conf b/contrib/misc/bsmc/etc/bareos/bareos-dir.d/archivejob.conf
new file mode 100644
index 000000000..8bdee207c
--- /dev/null
+++ b/contrib/misc/bsmc/etc/bareos/bareos-dir.d/archivejob.conf
@@ -0,0 +1,53 @@
+# Predifined stuff for archive jobs
+# Take care that pruning for all clients eventually using archiv jobs is off
+
+
+FileSet {
+ Name = "archive"
+ Include {
+ Options {
+ signature = MD5
+ compression = lz4
+ }
+ # Include file /tmp/bsmc.archive on _client_
+ # This file will be dynamically filled by bsmc
+ File = "\\</tmp/bsmc.archive"
+ #The plugin is PoC only, does not get ownership information but has options to allow or deny files
+ #Plugin = "python:module_path=/usr/lib64/bareos/plugins:module_name=bareos-fd-local-fileset:filename=/tmp/bsmc.archive:deny=/root/.*"
+ }
+}
+
+Schedule {
+ Name = "Never"
+}
+
+Pool {
+ Name = Archive
+ Pool Type = Backup
+ Label Format = "File-Archive-"
+ Recycle = no # Bareos can automatically recycle Volumes
+ AutoPrune = no # Prune expired volumes
+ Volume Retention = 100 years # 100 years for your archive
+ Maximum Volume Bytes = 10MB # Limit Volume size to something reasonable
+ Maximum Volumes = 100 # Limit number of Volumes in Pool
+}
+
+JobDefs {
+ Name = "ArchiveDefaults"
+ Type = Backup
+ Level = Full
+ FileSet = "archive"
+ Schedule = "Never"
+ Storage = File
+ Messages = Standard
+ Pool = Archive
+ Priority = 10
+ SpoolData = yes
+}
+
+Job {
+ Name = "archive"
+ JobDefs = "ArchiveDefaults"
+ # insert a client name here
+ Client = "puck-fd"
+}
diff --git a/contrib/misc/bsmc/etc/bareos/bsmc.conf b/contrib/misc/bsmc/etc/bareos/bsmc.conf
new file mode 100644
index 000000000..34deeb45d
--- /dev/null
+++ b/contrib/misc/bsmc/etc/bareos/bsmc.conf
@@ -0,0 +1,13 @@
+[director]
+server=bareos-server
+name=bareos-dir
+password=
+
+[client]
+name=yourclient-fd
+# comma separated list of backup jobs relevant for this client
+jobs=BackupJob1
+# dedicated job for longterm archiving files
+archivejob=archive
+# temporary file for archive job
+archivefilelist=/tmp/bsmc.archive
diff --git a/contrib/misc/bsmc/packaging/bareos-bsmc.changes b/contrib/misc/bsmc/packaging/bareos-bsmc.changes
new file mode 100644
index 000000000..17a58c07f
--- /dev/null
+++ b/contrib/misc/bsmc/packaging/bareos-bsmc.changes
@@ -0,0 +1,5 @@
+bareos-bsmc (0.1.0-1) unstable; urgency=low
+
+ * initial
+
+ -- Maik Aussendorf <maik.aussendorf@bareos.com> Fri, 04 Dec 2015 11:45:40 +0200
diff --git a/contrib/misc/bsmc/packaging/bareos-bsmc.dsc b/contrib/misc/bsmc/packaging/bareos-bsmc.dsc
new file mode 100644
index 000000000..db3732622
--- /dev/null
+++ b/contrib/misc/bsmc/packaging/bareos-bsmc.dsc
@@ -0,0 +1,10 @@
+Format: 1.0
+Source: bareos-bsmc
+Binary: bareos-bsmc
+Architecture: all
+Version: 0.1-1
+Maintainer: Maik Aussendorf <maik.aussendorf@bareos.com>
+Standards-Version: 3.9.1
+Build-Depends: debhelper (>= 7.4.3)
+DEBTRANSFORM-RELEASE: 1
+Files:
diff --git a/contrib/misc/bsmc/packaging/bareos-bsmc.spec b/contrib/misc/bsmc/packaging/bareos-bsmc.spec
new file mode 100644
index 000000000..94186baa1
--- /dev/null
+++ b/contrib/misc/bsmc/packaging/bareos-bsmc.spec
@@ -0,0 +1,46 @@
+Name: bareos-bsmc
+Version: 0.1
+Release: 1%{?dist}
+Summary: Bareos Simple Management CLI
+Group: Productivity/Archiving/Backup
+License: AGPL-3.0
+URL: https://github.com/bareos/bareos-bsmc/
+Vendor: The Bareos Team
+Source: %{name}-%{version}.tar.gz
+BuildRoot: %{_tmppath}/%{name}-root
+BuildArch: noarch
+BuildRequires: rsync
+# for directory /etc/bareos/bareos-dir.d/
+BuildRequires: bareos-common
+# required for restoring.
+# Recommends would be enough, but nor supported by all distributions.
+Requires: bareos-filedaemon >= 15.2.1
+# bsmcrmount
+Requires: python-bareos
+
+%description
+Bareos - Backup Archiving Recovery Open Sourced - bsmc
+
+bareos-bsmc is a CLI to Bareos, which lets you trigger tasks like backup or restore from command line.
+
+%prep
+%setup -q
+
+%build
+
+%install
+mkdir -p %{buildroot}/bin %{buildroot}/etc
+rsync -av bin/. %{buildroot}/bin/.
+rsync -av etc/. %{buildroot}/etc/.
+
+
+%check
+
+%files
+%defattr(-,root,root,-)
+%doc README.md
+%config(noreplace) %attr(644,root,root) /etc/bareos/bsmc.conf
+%config(noreplace) %attr(644,root,root) /etc/bareos/bareos-dir.d/*
+/bin/*
+
+%changelog
diff --git a/contrib/misc/bsmc/packaging/debian.debtransform b/contrib/misc/bsmc/packaging/debian.debtransform
new file mode 100644
index 000000000..b90c561dd
--- /dev/null
+++ b/contrib/misc/bsmc/packaging/debian.debtransform
@@ -0,0 +1 @@
+# this file is only required to activate debtransform from Open Build Service (OBS)
diff --git a/contrib/misc/performance/graphite/README.md b/contrib/misc/performance/graphite/README.md
new file mode 100644
index 000000000..af2528b0b
--- /dev/null
+++ b/contrib/misc/performance/graphite/README.md
@@ -0,0 +1,69 @@
+Bareos - Graphite - Feeder
+
+Use bareos-graphite-poller.py to read performance data from Bareos and feed it into a Graphite backend.
+
+# Configuration
+
+The default configuration file is /etc/bareos/graphite-poller.conf, which can be adjusted using -c when calling the poller.
+Here you configure Bareos director access and the Graphite backend.
+
+```
+[director]
+server=fqhn
+name=your-director-name
+password=secret
+
+[graphite]
+server=localhost
+port=2003
+```
+
+# Usage
+
+Output from help:
+
+```
+usage: bareos-graphite-poller.py [-h] [-d {error,warning,info,debug}]
+ [-c CONFIG] [-e] [-j] [-v] [-s START] [-t TO]
+
+Graphite poller for Bareos director.
+
+optional arguments:
+ -h, --help show this help message and exit
+ -d {error,warning,info,debug}, --debug {error,warning,info,debug}
+ Set debug level to {error,warning,info,debug}
+ -c CONFIG, --config CONFIG
+ Configfile
+ -e, --events Import Events (JobStart / JobEnd)
+ -j, --jobstats Import jobstats
+ -v, --devicestats Import devicestats
+ -s START, --start START
+ Import entries after this timestamp (only used for
+ stats and events)
+ -t TO, --to TO Import entries before this timestamp (only used for
+ stats and events)
+```
+
+If you use `-s last` a timestamp file will be created, unique for the options used. On the first call, no data will be imported, on all following calls
+with this options, all data since the last call will read and transferred. This is suitable to use as cronjob.
+
+Example call:
+`bareos-graphite-poller.py -c /etc/bareos/graphite-poller-jenkins.conf -s "last" -e -j -v`
+
+Which will call the poller, using the given configuration file, using timestamps and also process events, jobstats and devicestats.
+
+# Details and options
+
+By default some standard metrics will be queried, like number of running jobs, total bytes in backup and statistics per pool, job and clients.
+
+If you are using enhanced device- and job- statistics from Bareos, these can be queried by -v and -j. If you specify -e for events, all timestamps
+regarding job-start and job-end are submitted as events to Graphite.
+
+See http://doc.bareos.org for more information to enable statistic gathering in Bareos.
+
+# Metrics
+
+The metrics in Grahite will have the prefix bareos.*your director name*.[clients|devices|jobs|pools].
+
+
+
diff --git a/contrib/misc/performance/graphite/bareos-graphite-poller.py b/contrib/misc/performance/graphite/bareos-graphite-poller.py
new file mode 100755
index 000000000..da1f153dc
--- /dev/null
+++ b/contrib/misc/performance/graphite/bareos-graphite-poller.py
@@ -0,0 +1,439 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+# BAREOSĀ® - Backup Archiving REcovery Open Sourced
+#
+# Copyright(C) 2015-2015 Bareos GmbH & Co. KG
+#
+# This program is Free Software; you can redistribute it and/or
+# modify it under the terms of version three of the GNU Affero General Public
+# License as published by the Free Software Foundation, which is
+# listed in the file LICENSE.
+#
+# This program 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
+# Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# Author: Maik Aussendorf
+#
+# PoC code to implement a Bareos commandline tool that allows to trigger
+# common tasks from a Bareos client.
+# bsmc stands for "Bareos simple management cli"
+#
+# Implemented are show scheduler, trigger incremental backup and restore a
+# single given file.
+#
+
+
+import ConfigParser
+import argparse
+import bareos.bsock.bsockjson
+import logging
+import time
+import sys
+import datetime
+import requests
+import json
+import hashlib
+import os
+import os.path
+from socket import socket
+from django.contrib.messages.context_processors import messages
+
+
+def sentItemsToCarbon(messages, carbonHost, carbonPort):
+ '''
+ Send messages to carbon via socket
+ '''
+ field_separator = ' '
+ line_separator = '\n'
+ sock = socket()
+ try:
+ sock.connect((carbonHost, carbonPort))
+ except:
+ print "Could not connect to carbonHost: %s, port: %d\n" % (carbonHost, carbonPort)
+ return False
+ carbonMessage = ""
+ while messages:
+ carbonMessage += field_separator.join(map(str, messages.pop())) + line_separator
+ try:
+ sock.sendall(carbonMessage)
+ except:
+ print "Error could not transmit data to carbon host\n"
+
+
+def sendEvent(url, eventPayload):
+ '''
+ Send a single event to Carbon via http/json
+ Parameters
+ url: the carbon api url to receive events
+ eventPayLoad: event data in json format
+ '''
+ logger.debug("send eventdata %s to %s" % (json.dumps(eventPayload), url))
+ r = requests.post(url, data=json.dumps(eventPayload))
+ if r.status_code != 200:
+ logger.error("http post for event failed with code %d and reason: %s" % (r.statuscode, r.reason))
+ return 1
+ logger.debug(r.text)
+ return 0
+
+
+def sendEventsToCarbon(url, events):
+ '''
+ Send a list of events to carbon
+ '''
+ if not events:
+ logger.info("No events to send")
+ return None
+ for line in events:
+ sendEvent(url, line)
+
+
+def getJobStats(where):
+ '''
+ Get Job Statistics.
+ Returns a list of of stat items, a stat item is a list (triplet)
+ of identifier (metric name), value, timestamp.
+ '''
+ messages = []
+ statement = """select * from JobStats %s""" % where
+ logger.debug("Query db: %s" % statement)
+ response = director.call(".sql query=\"%s\"" % statement)
+ if not 'query' in response:
+ return []
+ for row in response['query']:
+ jobId = int(row['jobid'])
+ if not jobId in jobIdMapping.keys():
+ statement = """select clientid,name from Job where jobid=%s""" % jobId
+ logger.debug("Query db: %s" % statement)
+ jobDetails = director.call(".sql query=\"%s\"" % statement)
+ jobIdMapping[jobId] = jobDetails['query'][0]['clientid']
+ jobNameMapping[jobId] = jobDetails['query'][0]['name']
+ clientName = clientIdMapping[jobIdMapping[jobId]]
+ jobName = jobNameMapping[jobId]
+ timeObject = datetime.datetime.strptime(row['sampletime'], "%Y-%m-%d %H:%M:%S")
+ timestamp = int(timeObject.strftime("%s"))
+ logger.info("%s.clients.%s.jobs.%s.jobbytes %s at %d" %
+ (metricPrefix, clientName, jobName, row['jobbytes'], timestamp))
+ messages.append(["%s.clients.%s.jobs.%s.jobbytes" %
+ (metricPrefix, clientName, jobName), int(row['jobbytes']), timestamp])
+ messages.append(["%s.clients.%s.jobs.%s.jobfiles" %
+ (metricPrefix, clientName, jobName), int(row['jobfiles']), timestamp])
+ return messages
+
+
+def getDeviceStats(where):
+ '''
+ Get DeviceStats in timeframe specified by where.
+ Returns a list of of stat items, a stat item is a list (triplet)
+ of identifier (metric name), value, timestamp.
+ '''
+ messages = []
+ statement = """select * from DeviceStats %s""" % where
+ logger.debug("Query db: %s" % statement)
+ response = director.call(".sql query=\"%s\"" % statement)
+ if not 'query' in response:
+ return []
+ for row in response['query']:
+ deviceId = row['deviceid']
+ if not deviceId in deviceIdMapping.keys():
+ logger.error("Device ID: %s unknown. Ignoring" % deviceId)
+ continue
+ deviceName = deviceIdMapping[deviceId]
+ timeObject = datetime.datetime.strptime(row['sampletime'], "%Y-%m-%d %H:%M:%S")
+ timestamp = int(timeObject.strftime("%s"))
+ for dataItem in deviceStatKeys:
+ logger.info("%s.devices.%s.%s %d at %d"
+ % (metricPrefix, deviceName, dataItem, int(row[dataItem]), timestamp))
+ messages.append(["%s.devices.%s.%s" % (metricPrefix, deviceName, dataItem), int(row[dataItem]), timestamp])
+ return messages
+
+
+def getJobTotals():
+ '''
+ Get total bytes / files per job
+ '''
+ messages = []
+ now = int(time.time())
+ response = director.call("list jobtotals")
+ totalFiles = response['jobtotals']['files']
+ totalBytes = response['jobtotals']['bytes']
+ totalJobs = response['jobtotals']['jobs']
+ messages.append([metricPrefix+".totalFiles", int(totalFiles), now])
+ messages.append([metricPrefix+".totalBytes", int(totalBytes), now])
+ messages.append([metricPrefix+".totalJobs", int(totalJobs), now])
+
+ for job in response['jobs']:
+ jobFiles = job['files']
+ jobName = job['job']
+ jobBytes = job['bytes']
+ jobCount = job['jobs']
+ logger.info("job: %s, files: %s, count: %s, bytes: %s" % (jobName, jobFiles, jobCount, jobBytes))
+ messages.append(["%s.jobs.%s.totalFiles" % (metricPrefix, jobName), jobFiles, now])
+ messages.append(["%s.jobs.%s.totalBytes" % (metricPrefix, jobName), jobBytes, now])
+ messages.append(["%s.jobs.%s.jobCount" % (metricPrefix, jobName), jobCount, now])
+ return messages
+
+
+def getPoolStatistics():
+ '''
+ Get Statisctics regarding all defined pools
+ '''
+ messages = []
+ now = int(time.time())
+ response = director.call('list volumes')
+ for pool in response['volumes'].keys():
+ totalBytes = 0
+ numVolumes = 0
+ volStatus = dict()
+ for volume in response['volumes'][pool]:
+ totalBytes += int(volume['volbytes'])
+ numVolumes += 1
+ status = volume['volstatus']
+ if status not in volStatus.keys():
+ volStatus[status] = 1
+ else:
+ volStatus[status] += 1
+ logger.info("pool: %s, bytes: %d Volumes: %d" % (pool, totalBytes, numVolumes))
+ messages.append(["%s.pools.%s.totalBytes" % (metricPrefix, pool), totalBytes, now])
+ messages.append(["%s.pools.%s.totalVolumes" % (metricPrefix, pool), numVolumes, now])
+ for status in volStatus.keys():
+ messages.append(["%s.pools.%s.volumeStatus.%s" % (metricPrefix, pool, status), volStatus[status], now])
+ return messages
+
+
+def getEvents(whereJobs):
+ '''
+ Reads job-events (start, stop, scheduled start, real end) from the given timerange
+ and returns a list of events. Each event is a dictionary with the fields
+ ...
+ '''
+ events = []
+ statement = """select * from Job %s and starttime <> '0000-00-00 00:00:00'""" % whereJobs
+ logger.debug("Query db: %s" % statement)
+ response = director.call(".sql query=\"%s\"" % statement)
+ if 'query' in response.keys():
+ rows = response['query']
+ else:
+ rows = []
+ logger.info("No events found")
+ for row in rows:
+ jobId = row['jobid']
+ if not jobId in jobIdMapping.keys():
+ statement = """select clientid from Job where jobid=%s""" % jobId
+ result = director.call(".sql query=\"%s\"" % statement)
+ #print result
+ jobIdMapping[jobId] = result['query'][0]['clientid']
+ clientName = clientIdMapping[jobIdMapping[jobId]]
+ jobLevelTag = "level=%s" % row['level']
+ jobStatusTag = "status=%s" % row['jobstatus']
+ jobIdTag = "id=%s" % jobId
+ clientTag = "client=%s" % clientName
+ jobInformation = "JobBytes: %s, JobFiles: %s" % (row['jobbytes'], row['jobfiles'])
+ if row['poolid'] in poolIdMapping.keys():
+ jobPoolTag = "pool=%s" % poolIdMapping[row['poolid']]
+ else:
+ jobPoolTag = "pool=%s" % row['poolid']
+ timeObject = datetime.datetime.strptime(row['starttime'], "%Y-%m-%d %H:%M:%S")
+ jobStartTime = int(timeObject.strftime("%s"))
+ timeObject = datetime.datetime.strptime(row['schedtime'], "%Y-%m-%d %H:%M:%S")
+ jobSchedTime = int(timeObject.strftime("%s"))
+ timeObject = datetime.datetime.strptime(row['endtime'], "%Y-%m-%d %H:%M:%S")
+ jobEndTime = int(timeObject.strftime("%s"))
+ timeObject = datetime.datetime.strptime(row['realendtime'], "%Y-%m-%d %H:%M:%S")
+ jobRealEndTime = int(timeObject.strftime("%s"))
+ jobTags = clientTag + ' ' + jobIdTag + ' ' + jobLevelTag + ' ' + jobStatusTag + ' ' + jobPoolTag
+ logger.info(jobTags)
+ events.append({"what": "Job Starttime", "tags": jobTags + ' JobStart',
+ "when": jobStartTime, "data": jobInformation})
+ events.append({"what": "Job Endtime", "tags": jobTags + ' JobEnd',
+ "when": jobEndTime, "data": jobInformation})
+ events.append({"what": "Job Schedtime", "tags": jobTags + ' JobScheduled',
+ "when": jobSchedTime, "data": jobInformation})
+ events.append({"what": "Job Realendtime", "tags": jobTags + ' JobRealEnd',
+ "when": jobRealEndTime, "data": jobInformation})
+ return events
+
+
+if __name__ == '__main__':
+
+ argParser = argparse.ArgumentParser(description='Graphite poller for Bareos director.',
+ prog="bareos-graphite-poller.py")
+ argParser.add_argument('-d', '--debug', default='error', choices=['error', 'warning', 'info', 'debug'],
+ help="Set debug level to {error,warning,info,debug}")
+ argParser.add_argument('-c', '--config', help="Configfile", default="/etc/bareos/graphite-poller.conf")
+ argParser.add_argument('-e', '--events', dest='events', help="Import Events (JobStart / JobEnd)",
+ action='store_true')
+ argParser.add_argument('-j', '--jobstats', dest='jobstats', help="Import jobstats", action='store_true')
+ argParser.add_argument('-v', '--devicestats', dest='devicestats', help="Import devicestats", action='store_true')
+ argParser.add_argument('-s', '--start', help="Import entries after this timestamp (only used for stats and events)")
+ argParser.add_argument('-t', '--to', help="Import entries before this timestamp (only used for stats and events)")
+ args = argParser.parse_args()
+
+ logging.basicConfig(format='%(levelname)s %(module)s.%(funcName)s: %(message)s',
+ level=logging.ERROR)
+ logger = logging.getLogger()
+
+ if args.debug == 'info':
+ logger.setLevel(logging.INFO)
+ elif args.debug == "warning":
+ logger.setLevel(logging.WARNING)
+ elif args.debug == "debug":
+ logger.setLevel(logging.DEBUG)
+ else:
+ logger.setLevel(logging.ERROR)
+
+ parser = ConfigParser.SafeConfigParser({'port': '9101'})
+ parser.readfp(open(args.config, "r"))
+
+ host = parser.get("director", "server")
+ dirname = parser.get("director", "name")
+ password = parser.get("director", "password")
+ dir_port = parser.getint("director", "port")
+ carbonHost = parser.get("graphite", "server")
+ carbonPort = parser.getint("graphite", "port")
+ try:
+ prefix = parser.get("graphite", "prefix")
+ except ConfigParser.NoOptionError:
+ prefix = "bareos."
+ eventUrl = "http://%s/events/" % carbonHost
+ metricPrefix = prefix + dirname
+ timeStampFile = "/var/tmp/bareos-graphite-poller_"
+ timeStampFileHandler = None
+ # evaluate time-ranges (only needed for events and job/devicestats
+ where = ""
+ whereJobs = ""
+ start = ""
+ to = ""
+ startJobEnd = ""
+ toJobEnd = ""
+ now = datetime.datetime.now()
+ if args.start or args.to:
+ if args.start == 'last':
+ # we have a unique timestamp file name per option combination
+ timeStampFile += hashlib.sha224(str(args)).hexdigest()
+ if os.path.isfile(timeStampFile) and os.access(timeStampFile, os.R_OK):
+ timeStampFileHandler = open(timeStampFile, 'r+w')
+ startFromFile = timeStampFileHandler.read()
+ start = "sampletime>'%s'" % startFromFile
+ startJobEnd = "realendtime>'%s' " % startFromFile
+ to = " sampletime<'%s'" % now.strftime("%Y-%m-%d %H:%M:%S")
+ toJobEnd = "realendtime<'%s'" % now.strftime("%Y-%m-%d %H:%M:%S")
+ #where = "where %s AND %s" %(start, to)
+ #whereJobs = "where %s AND %s" %(startJobEnd, toJobEnd)
+ else:
+ logger.warning("No timestamp file found. Create one and exit")
+ timeStampFileHandler = open(timeStampFile, 'w')
+ timeStampFileHandler.write(now.strftime("%Y-%m-%d %H:%M:%S"))
+ timeStampFileHandler.close()
+ sys.exit(0)
+ elif args.start and args.start != 'last':
+ start = "sampletime>'%s' " % args.start
+ startJobEnd = "realendtime>'%s' " % args.start
+ if args.to:
+ to = " sampletime<'%s'" % args.to
+ toJobEnd = "realendtime<'%s'" % args.to
+ if (args.to or args.start == 'last') and args.start:
+ where = "where %s AND %s" % (start, to)
+ whereJobs = "where %s AND %s" % (startJobEnd, toJobEnd)
+ else:
+ where = "where " + start + to
+ whereJobs = "where " + startJobEnd + toJobEnd
+
+ # messages is a list of lists to store the performance messages
+ # Each entry consists of a triplet metric_identifier, metric_value, timestamp
+ messages = []
+ # Keys to consider when reading device statistics
+ deviceStatKeys = ['readtime', 'writetime', 'readbytes', 'writebytes', 'spoolsize',
+ 'numwaiting', 'numwriters', 'volcatbytes', 'volcatfiles', 'volcatblocks']
+
+ try:
+ logger.info("Connect to Bareos director %s, host %s, port: %d" % (dirname, host, dir_port))
+ # print password
+ director = bareos.bsock.BSockJson(address=host, port=dir_port, dirname=dirname,
+ password=bareos.bsock.Password(password))
+ except RuntimeError as e:
+ print str(e)
+ sys.exit(1)
+
+ # jobid mapping might get big, we only resolve as we need
+ jobIdMapping = {}
+ jobNameMapping = {}
+
+ # Setup client id mapping
+ clientIdMapping = {}
+ statement = """select clientid,name from Client"""
+ response = director.call(".sql query=\"%s\"" % statement)
+ if not 'query' in response.keys():
+ logger.error("No clients found in director using sql search")
+ sys.exit(1)
+ for row in response['query']:
+ clientIdMapping[row['clientid']] = row['name']
+
+ # Resolve Pool ID to pool name
+ poolIdMapping = {}
+ statement = """select poolid,name from Pool"""
+ response = director.call(".sql query=\"%s\"" % statement)
+ if not 'query' in response.keys():
+ logger.error("No pools found in director using sql search")
+ sys.exit(1)
+ for row in response['query']:
+ poolIdMapping[row['poolid']] = "%s-%s" % (row['poolid'], row['name'])
+
+ # resolve deviceid to device name (prepending id, to be unique)
+ deviceIdMapping = {}
+ statement = """select deviceid,name from Device"""
+ response = director.call(".sql query=\"%s\"" % statement)
+ if not 'query' in response.keys():
+ logger.error("No devices found in director using sql search")
+ sys.exit(1)
+ for row in response['query']:
+ deviceIdMapping[row['deviceid']] = "%s-%s" % (row['deviceid'], row['name'])
+
+ logger.debug("Processing JobTotals")
+ messages = getJobTotals()
+ sentItemsToCarbon(messages, carbonHost, carbonPort)
+ messages = []
+
+ logger.debug("Processing Pools")
+ messages = getPoolStatistics()
+ sentItemsToCarbon(messages, carbonHost, carbonPort)
+ messages = []
+
+ # get number of running jobs
+ response = director.call('llist jobs jobstatus=R count')
+ numRunningJobs = response['jobs'][0]['count']
+ logger.info("runningJobs: %s" % (numRunningJobs))
+ messages.append(["%s.jobsRunning" % metricPrefix, numRunningJobs, int(now.strftime("%s"))])
+
+ sentItemsToCarbon(messages, carbonHost, carbonPort)
+ messages = []
+
+ if args.events:
+ logger.debug("Processing events")
+ events = getEvents(whereJobs)
+ sendEventsToCarbon(eventUrl, events)
+ events = []
+
+ if args.devicestats:
+ logger.debug("Processing devicestats")
+ messages = getDeviceStats(where)
+ sentItemsToCarbon(messages, carbonHost, carbonPort)
+ messages = []
+
+ if args.jobstats:
+ logger.debug("Processing jobstats")
+ messages = getJobStats(where)
+ sentItemsToCarbon(messages, carbonHost, carbonPort)
+ messages = []
+
+ if timeStampFileHandler:
+ logger.debug("Writing timestimp")
+ timeStampFileHandler.seek(0)
+ timeStampFileHandler.write(now.strftime("%Y-%m-%d %H:%M:%S"))
+ timeStampFileHandler.close()
diff --git a/contrib/misc/performance/graphite/graphite-poller.conf b/contrib/misc/performance/graphite/graphite-poller.conf
new file mode 100644
index 000000000..efd4d6c53
--- /dev/null
+++ b/contrib/misc/performance/graphite/graphite-poller.conf
@@ -0,0 +1,9 @@
+[director]
+server=fqdn
+name=your-director-name
+password=secret
+
+[graphite]
+server=graphite
+port=2003
+prefix=bareos.
diff --git a/contrib/misc/recover_single_job_from_dbdump/README.md b/contrib/misc/recover_single_job_from_dbdump/README.md
new file mode 100644
index 000000000..7dc2d17bf
--- /dev/null
+++ b/contrib/misc/recover_single_job_from_dbdump/README.md
@@ -0,0 +1,34 @@
+How to recover a single accidentally deleted JobId
+from the database dump.
+
+- Cut the db dump into single files for easier handling with split_bareos_pg_dump.py
+
+The following tables contain the jobid:
+
+- basefiles
+- file
+- jobhisto
+- jobmedia
+- job
+- jobstats
+- log
+- ndmpjobenvironment
+- pathvisibility
+- restoreobject
+- unsavedfiles
+
+
+- Example: JobID is 192626
+- First recover the job and jobmedia entries for the job:
+ - Find the job record in the job.sql file and add it to the database
+ - head -n1 job.txt > addjob.sql
+ - grep ^192626 >> addjob.sql
+ - psql bareos < addjob.sql
+
+ - Find the jobmedia records for the jobid and add them to the database
+ - head -n1 jobmedia.sql > addjobmedia.sql
+ - grep '^[0-9]*[[:space:]]\+192626[[:space:]]' jobmedia.sql >> addjobmedia.sql
+ - psql < addjobmedia.sql
+
+- secondly recover file, filename, path, and restore objects for the job:
+
diff --git a/contrib/misc/recover_single_job_from_dbdump/split_bareos_pg_dump.py b/contrib/misc/recover_single_job_from_dbdump/split_bareos_pg_dump.py
new file mode 100755
index 000000000..9b18d7923
--- /dev/null
+++ b/contrib/misc/recover_single_job_from_dbdump/split_bareos_pg_dump.py
@@ -0,0 +1,18 @@
+#!/usr/bin/env python
+# splits an existing bareos postgres dump into single files per table
+
+import re
+
+outfile = open("header", "w")
+
+copy = re.compile("^COPY (\w+)")
+
+for line in open('bareos.sql'):
+ m = re.match(copy, line)
+ if m:
+ print line, m.group(1)
+ outfile.close()
+ outfile = open(m.group(1) + ".sql", "w")
+ outfile.write(line)
+ else:
+ outfile.write(line)
diff --git a/contrib/misc/triggerjob/README.md b/contrib/misc/triggerjob/README.md
new file mode 100644
index 000000000..d793ce11f
--- /dev/null
+++ b/contrib/misc/triggerjob/README.md
@@ -0,0 +1,37 @@
+_triggerjob_ is a Python script that allows you to perform a backup for a connected client if a definable time has passed since the last backup.
+
+It will look for all clients connected to the Director. If it finds a job named **backup-{clientname}** that did not successfully run during the specified time period, it will trigger this job. This way, clients that are not regularly connected to the director, such as notebooks, can be reliably backed up.
+
+_triggerjob_ should be executed regularly to detect newly connected clients. To do so, a **cronjob** should run the script repeatedly.
+
+Note: _triggerjob_ **requires a connection between director and client**. Therefore, activate [Client Initiated Connections](https://docs.bareos.org/TasksAndConcepts/NetworkSetup.html#client-initiated-connection) to automatically establish a connection whenever possible. Otherwise no jobs will be started
+
+Sample usage:
+
+```
+$ ./triggerjob.py -p PASSWORD --hours 24 localhost
+```
+
+```
+$ ./triggerjob.py -h
+usage: triggerjob.py [-h] [-d] [--name NAME] -p PASSWORD [--port PORT]
+ [--dirname DIRNAME] [--hours HOURS]
+ [address]
+
+Console to Bareos Director.
+
+positional arguments:
+ address Bareos Director network address
+
+optional arguments:
+ -h, --help show this help message and exit
+ -d, --debug enable debugging output
+ --name NAME use this to access a specific Bareos director named
+ console. Otherwise it connects to the default console
+ ("*UserAgent*")
+ -p PASSWORD, --password PASSWORD
+ password to authenticate to a Bareos Director console
+ --port PORT Bareos Director network port
+ --dirname DIRNAME Bareos Director name
+ --hours HOURS Minimum time since last backup in hours
+```
diff --git a/contrib/misc/triggerjob/triggerjob.py b/contrib/misc/triggerjob/triggerjob.py
new file mode 100755
index 000000000..6d29de6f1
--- /dev/null
+++ b/contrib/misc/triggerjob/triggerjob.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python
+
+from __future__ import print_function
+import argparse
+import bareos.bsock
+import logging
+import sys
+
+
+def get_job_names(director):
+ result = director.call('.jobs')['jobs']
+ jobs = [job['name'] for job in result]
+ return jobs
+
+
+def get_connected_clients(director):
+ result = director.call('status director')['client-connection']
+ clients = [client['name'] for client in result]
+ return clients
+
+
+def trigger(director, jobnames, clients, hours):
+ for client in clients:
+ jobname = 'backup-{}'.format(client)
+ if not jobname in jobnames:
+ print('{} skipped, no matching job ({}) found'.format(client, jobname))
+ else:
+ jobs = director.call(
+ ('list jobs client={} hours={}').format(client, hours))['jobs']
+ if jobs:
+ job = director.call(
+ ('list jobs client={} hours={} last').format(client, hours))['jobs'][0]
+ jobinfo = '{starttime}: jobid={jobid}, level={level}, status={jobstatus}'.format(
+ **job)
+ print('{}: skipped, recent backups available ({})'.format(
+ jobname, jobinfo))
+ else:
+ jobid = director.call('run {} yes'.format(jobname))[
+ 'run']['jobid']
+ print('{}: backup triggered, jobid={}'.format(jobname, jobid))
+
+
+def getArguments():
+ parser = argparse.ArgumentParser(description='Console to Bareos Director.')
+ parser.add_argument('-d', '--debug', action='store_true',
+ help="enable debugging output")
+ parser.add_argument('--name', default="*UserAgent*",
+ help="use this to access a specific Bareos director named console. Otherwise it connects to the default console (\"*UserAgent*\")")
+ parser.add_argument(
+ '-p', '--password', help="password to authenticate to a Bareos Director console", required=True)
+ parser.add_argument('--port', default=9101,
+ help="Bareos Director network port")
+ parser.add_argument('--dirname', help="Bareos Director name")
+ parser.add_argument('--hours', default=24,
+ help="Minimum time since last backup in hours")
+ parser.add_argument('address', nargs='?', default="localhost",
+ help="Bareos Director network address")
+ args = parser.parse_args()
+ return args
+
+
+if __name__ == '__main__':
+ logging.basicConfig(
+ format='%(levelname)s %(module)s.%(funcName)s: %(message)s', level=logging.INFO)
+ logger = logging.getLogger()
+
+ args = getArguments()
+ if args.debug:
+ logger.setLevel(logging.DEBUG)
+
+ try:
+ options = ['address', 'port', 'dirname', 'name']
+ parameter = {}
+ for i in options:
+ if hasattr(args, i) and getattr(args, i) != None:
+ logger.debug("%s: %s" % (i, getattr(args, i)))
+ parameter[i] = getattr(args, i)
+ else:
+ logger.debug('%s: ""' % (i))
+ logger.debug('options: %s' % (parameter))
+ password = bareos.bsock.Password(args.password)
+ parameter['password'] = password
+ director = bareos.bsock.DirectorConsoleJson(**parameter)
+ except RuntimeError as e:
+ print(str(e))
+ sys.exit(1)
+ logger.debug("authentication successful")
+
+ hours = str(args.hours)
+
+ jobs = get_job_names(director)
+ clients = get_connected_clients(director)
+ trigger(director, jobs, clients, hours)
diff --git a/contrib/sd-plugins/README.md b/contrib/sd-plugins/README.md
new file mode 100644
index 000000000..acb1dc313
--- /dev/null
+++ b/contrib/sd-plugins/README.md
@@ -0,0 +1 @@
+This directory is intended for Python Storage Daemon plugins. Please use a subdirectory for each plugin.