aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMatt Hart <matthew.hart@linaro.org>2015-11-10 20:16:08 +0000
committerMatt Hart <matthew.hart@linaro.org>2015-11-10 20:16:08 +0000
commit48e2e3e84f3334921ec573264858d56a11f02de7 (patch)
tree9bdb1402ce6b633c0aed3e9c7a2ba6c505e945c6
parent07f56a0c99e44b5f3b08b6dfcf46d92fc80d61e7 (diff)
Migrated to github: https://github.com/mattface/pdudaemonHEADmaster
-rw-r--r--MANIFEST.in6
-rw-r--r--README3
-rwxr-xr-xetc/lavapdu-listen.init128
-rw-r--r--etc/lavapdu-listen.service11
-rwxr-xr-xetc/lavapdu-runner.init134
-rw-r--r--etc/lavapdu-runner.service11
-rw-r--r--etc/lavapdu/lavapdu.conf33
-rw-r--r--etc/lavapdulogrotate19
-rwxr-xr-xlavapdu-listen94
-rwxr-xr-xlavapdu-runner67
-rw-r--r--lavapdu/__init__.py19
-rw-r--r--lavapdu/dbhandler.py94
-rw-r--r--lavapdu/drivers/__init__.py19
-rw-r--r--lavapdu/drivers/apc7952.py103
-rw-r--r--lavapdu/drivers/apc8959.py53
-rw-r--r--lavapdu/drivers/apc9210.py61
-rw-r--r--lavapdu/drivers/apc9218.py68
-rw-r--r--lavapdu/drivers/apcbase.py73
-rw-r--r--lavapdu/drivers/driver.py84
-rw-r--r--lavapdu/drivers/strategies.py29
-rw-r--r--lavapdu/pdurunner.py84
-rw-r--r--lavapdu/runnermaster.py61
-rw-r--r--lavapdu/shared.py41
-rw-r--r--lavapdu/socketserver.py113
-rwxr-xr-xpduclient76
-rw-r--r--setup.py55
26 files changed, 3 insertions, 1536 deletions
diff --git a/MANIFEST.in b/MANIFEST.in
deleted file mode 100644
index a782c1c..0000000
--- a/MANIFEST.in
+++ /dev/null
@@ -1,6 +0,0 @@
-include etc/lavapdu/lavapdu.conf
-include etc/lavapdu-runner.init
-include etc/lavapdu-listen.init
-include etc/lavapdu-runner.service
-include etc/lavapdu-listen.service
-include etc/lavapdulogrotate
diff --git a/README b/README
new file mode 100644
index 0000000..368ba86
--- /dev/null
+++ b/README
@@ -0,0 +1,3 @@
+This project has been renamed pdudaemon and migrated to Github.
+Always accepting pull-requests at:
+See https://github.com/mattface/pdudaemon
diff --git a/etc/lavapdu-listen.init b/etc/lavapdu-listen.init
deleted file mode 100755
index ed7a26c..0000000
--- a/etc/lavapdu-listen.init
+++ /dev/null
@@ -1,128 +0,0 @@
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides: lavapdu-listen
-# Required-Start: $remote_fs $network postgresql
-# Required-Stop: $remote_fs $network
-# Default-Start: 2 3 4 5
-# Default-Stop: 0 1 6
-# Short-Description: LAVA PDU Listener
-# Description: TCP Listening daemon to accept PDU requests
-### END INIT INFO
-
-# Author: Matthew Hart <matthew.hart@linaro.org>
-
-LOGFILE="--logfile /var/log/lavapdu-listener.log"
-LOGLEVEL="--loglevel=INFO"
-
-# PATH should only include /usr/* if it runs after the mountnfs.sh script
-PATH=/sbin:/usr/sbin:/bin:/usr/bin
-DESC="lavapdu-listen" # short description
-NAME=lavapdu-listen # short server's name (truncated for 15 chars)
-DAEMON=/usr/sbin/lavapdu-listen # server's location
-DAEMON_ARGS="$LOGLEVEL" # Arguments to run the daemon with
-PIDFILE=/var/run/$DESC.pid
-SCRIPTNAME=/etc/init.d/$NAME
-
-# Exit if the package is not installed
-[ -x $DAEMON ] || exit 0
-
-# Read configuration variable file if it is present
-[ -r /etc/default/$NAME ] && . /etc/default/$NAME
-
-# Load the VERBOSE setting and other rcS variables
-#. /lib/init/vars.sh
-
-# Define LSB log_* functions.
-# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
-. /lib/lsb/init-functions
-
-#
-# Function that starts the daemon/service
-#
-do_start()
-{
- # Return
- # 0 if daemon has been started
- # 1 if daemon was already running
- # 2 if daemon could not be started
- start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
- || return 1
- start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
- $DAEMON_ARGS \
- || return 2
- # Add code here, if necessary, that waits for the process to be ready
- # to handle requests from services started subsequently which depend
- # on this one. As a last resort, sleep for some time.
-}
-
-#
-# Function that stops the daemon/service
-#
-do_stop()
-{
- # Return
- # 0 if daemon has been stopped
- # 1 if daemon was already stopped
- # 2 if daemon could not be stopped
- # other if a failure occurred
- start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
- RETVAL="$?"
- [ "$RETVAL" = 2 ] && return 2
- # Wait for children to finish too if this is a daemon that forks
- # and if the daemon is only ever run from this initscript.
- # If the above conditions are not satisfied then add some other code
- # that waits for the process to drop all resources that could be
- # needed by services started subsequently. A last resort is to
- # sleep for some time.
- # Many daemons don't delete their pidfiles when they exit.
- rm -f $PIDFILE
- return "$RETVAL"
-}
-
-case "$1" in
- start)
- [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC " "$NAME"
- do_start
- case "$?" in
- 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
- 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
- esac
- ;;
- stop)
- [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
- do_stop
- case "$?" in
- 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
- 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
- esac
- ;;
- status)
- status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
- ;;
- restart|force-reload)
- #
- # If the "reload" option is implemented then remove the
- # 'force-reload' alias
- #
- log_daemon_msg "Restarting $DESC" "$NAME"
- do_stop
- case "$?" in
- 0|1)
- do_start
- case "$?" in
- 0) log_end_msg 0 ;;
- 1) log_end_msg 1 ;; # Old process is still running
- *) log_end_msg 1 ;; # Failed to start
- esac
- ;;
- *)
- # Failed to stop
- log_end_msg 1
- ;;
- esac
- ;;
- *)
- echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
- exit 3
- ;;
-esac
diff --git a/etc/lavapdu-listen.service b/etc/lavapdu-listen.service
deleted file mode 100644
index 5ad4e7b..0000000
--- a/etc/lavapdu-listen.service
+++ /dev/null
@@ -1,11 +0,0 @@
-[Unit]
-Description=TCP Listening daemon to accept PDU requests
-After=postgresql.service
-
-[Service]
-ExecStart=/usr/sbin/lavapdu-listen
-Type=forking
-PIDFile=/var/run/lavapdu-listen.pid
-
-[Install]
-WantedBy=network.target
diff --git a/etc/lavapdu-runner.init b/etc/lavapdu-runner.init
deleted file mode 100755
index befa0c7..0000000
--- a/etc/lavapdu-runner.init
+++ /dev/null
@@ -1,134 +0,0 @@
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides: lavapdu-runner
-# Required-Start: $remote_fs $network postgresql
-# Required-Stop: $remote_fs $network
-# Default-Start: 2 3 4 5
-# Default-Stop: 0 1 6
-# Short-Description: LAVA PDU Runner
-# Description: Runner daemon to process PDU requests
-### END INIT INFO
-
-# Author: Matthew Hart <matthew.hart@linaro.org>
-
-LOGFILE="--logfile /var/log/lavapdu-runner.log"
-LOGLEVEL="--loglevel=INFO"
-
-# PATH should only include /usr/* if it runs after the mountnfs.sh script
-PATH=/sbin:/usr/sbin:/bin:/usr/bin
-DESC="lavapdu-runner" # short description
-NAME=lavapdu-runner # short server's name (truncated for 15 chars)
-DAEMON=/usr/sbin/lavapdu-runner # server's location
-DAEMON_ARGS="$LOGLEVEL" # Arguments to run the daemon with
-PIDFILE=/var/run/$DESC.pid
-SCRIPTNAME=/etc/init.d/$NAME
-
-# Exit if the package is not installed
-[ -x $DAEMON ] || exit 0
-
-# Read configuration variable file if it is present
-[ -r /etc/default/$NAME ] && . /etc/default/$NAME
-
-# Load the VERBOSE setting and other rcS variables
-#. /lib/init/vars.sh
-
-# Define LSB log_* functions.
-# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
-. /lib/lsb/init-functions
-
-#
-# Function that starts the daemon/service
-#
-do_start()
-{
- # Return
- # 0 if daemon has been started
- # 1 if daemon was already running
- # 2 if daemon could not be started
- start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
- || return 1
- start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
- $DAEMON_ARGS \
- || return 2
- # Add code here, if necessary, that waits for the process to be ready
- # to handle requests from services started subsequently which depend
- # on this one. As a last resort, sleep for some time.
-}
-
-#
-# Function that stops the daemon/service
-#
-do_stop()
-{
- # Return
- # 0 if daemon has been stopped
- # 1 if daemon was already stopped
- # 2 if daemon could not be stopped
- # other if a failure occurred
- start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE
- RETVAL="$?"
- [ "$RETVAL" = 2 ] && return 2
- # Wait for children to finish too if this is a daemon that forks
- # and if the daemon is only ever run from this initscript.
- # If the above conditions are not satisfied then add some other code
- # that waits for the process to drop all resources that could be
- # needed by services started subsequently. A last resort is to
- # sleep for some time.
- # Many daemons don't delete their pidfiles when they exit.
- if [ $RETVAL -lt 2 ]
- then
- rm -f $PIDFILE
- fi
- return "$RETVAL"
-}
-
-case "$1" in
- start)
- [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC " "$NAME"
- do_start
- sleep 1
- echo -n " "
- cat $PIDFILE
- case "$?" in
- 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
- 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
- esac
- ;;
- stop)
- [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
- do_stop
- case "$?" in
- 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
- 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
- esac
- ;;
- status)
- status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
- ;;
- restart|force-reload)
- #
- # If the "reload" option is implemented then remove the
- # 'force-reload' alias
- #
- log_daemon_msg "Restarting $DESC" "$NAME"
- do_stop
- case "$?" in
- 0|1)
- do_start
- case "$?" in
- 0) log_end_msg 0 ;;
- 1) log_end_msg 1 ;; # Old process is still running
- *) log_end_msg 1 ;; # Failed to start
- esac
- ;;
- *)
- # Failed to stop
- log_end_msg 1
- ;;
- esac
- ;;
- *)
- echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
- exit 3
- ;;
-esac
diff --git a/etc/lavapdu-runner.service b/etc/lavapdu-runner.service
deleted file mode 100644
index 9fdc7ad..0000000
--- a/etc/lavapdu-runner.service
+++ /dev/null
@@ -1,11 +0,0 @@
-[Unit]
-Description=Runner daemon to process PDU requests
-After=postgresql.service
-
-[Service]
-ExecStart=/usr/sbin/lavapdu-runner
-Type=forking
-PIDFile=/var/run/lavapdu-runner.pid
-
-[Install]
-WantedBy=network.target
diff --git a/etc/lavapdu/lavapdu.conf b/etc/lavapdu/lavapdu.conf
deleted file mode 100644
index fd9c428..0000000
--- a/etc/lavapdu/lavapdu.conf
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "daemon": {
- "hostname": "0.0.0.0",
- "port": 16421,
- "dbhost": "127.0.0.1",
- "dbuser": "pdudaemon",
- "dbpass": "pdudaemon",
- "dbname": "lavapdu",
- "retries": 5,
- "logging_level": "INFO"
- },
- "pdus": {
- "192.168.10.2": {
- "driver": "apc9210"
- },
- "192.168.10.3": {
- "driver": "apc7952",
- "telnetport": 5023
- },
- "192.168.10.4": {
- "driver": "apc7952"
- },
- "192.168.10.5": {
- "driver": "apc8959"
- },
- "192.168.10.6": {
- "driver": "apc7952"
- },
- "192.168.25.52": {
- "driver": "apc7952"
- }
- }
-}
diff --git a/etc/lavapdulogrotate b/etc/lavapdulogrotate
deleted file mode 100644
index f113324..0000000
--- a/etc/lavapdulogrotate
+++ /dev/null
@@ -1,19 +0,0 @@
-/var/log/lavapdu-listener.log {
- weekly
- rotate 12
- compress
- delaycompress
- missingok
- notifempty
- create 644 root root
-}
-
-/var/log/lavapdu-runner.log {
- weekly
- rotate 12
- compress
- delaycompress
- missingok
- notifempty
- create 644 root root
-} \ No newline at end of file
diff --git a/lavapdu-listen b/lavapdu-listen
deleted file mode 100755
index ec820ba..0000000
--- a/lavapdu-listen
+++ /dev/null
@@ -1,94 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
-
-import logging
-import os
-import sys
-import optparse
-from lavapdu.shared import get_daemon_logger
-from lavapdu.shared import read_settings
-
-import daemon
-try:
- import daemon.pidlockfile as pidlockfile
-except ImportError:
- from lockfile import pidlockfile
-
-from lavapdu.socketserver import ListenerServer
-
-
-if __name__ == '__main__':
- pidfile = "/var/run/lavapdu-listen.pid"
- logfile = "/var/log/lavapdu-listener.log"
- conffile = "/etc/lavapdu/lavapdu.conf"
- settings = read_settings(conffile)
- usage = "Usage: %prog [--logfile] --[loglevel]"
- description = "LAVA PDU request listener server," \
- "host and port are handled in %s" % conffile
- parser = optparse.OptionParser(usage=usage, description=description)
- parser.add_option("--logfile", dest="logfile", action="store",
- type="string", help="log file [%s]" % logfile)
- parser.add_option("--loglevel", dest="loglevel", action="store",
- type="string", help="logging level [INFO]")
- parser.add_option("--purge", dest="purge", action="store_true")
- (options, args) = parser.parse_args()
- if options.logfile:
- if os.path.exists(os.path.dirname(options.logfile)):
- logfile = options.logfile
- else:
- print "No such directory for specified logfile '%s'" % logfile
- open(logfile, 'w').close()
- level = logging.DEBUG
- daemon_settings = settings["daemon"]
- if daemon_settings["logging_level"] == "DEBUG":
- level = logging.DEBUG
- if daemon_settings["logging_level"] == "WARNING":
- level = logging.WARNING
- if daemon_settings["logging_level"] == "ERROR":
- level = logging.ERROR
- if daemon_settings["logging_level"] == "INFO":
- level = logging.INFO
- client_logger, watched_file_handler = get_daemon_logger(
- logfile,
- loglevel=level,
- log_format='%(asctime)s:%(levelname)s:%(name)s:%(message)s')
- if isinstance(client_logger, Exception):
- print("Fatal error creating client_logger: " + str(client_logger))
- sys.exit(os.EX_OSERR)
- # noinspection PyArgumentList
- lockfile = pidlockfile.PIDLockFile(pidfile)
- if lockfile.is_locked():
- logging.error("PIDFile %s already locked" % pidfile)
- sys.exit(os.EX_OSERR)
- context = daemon.DaemonContext(
- detach_process=True,
- working_directory=os.getcwd(),
- pidfile=lockfile,
- files_preserve=[watched_file_handler.stream],
- stderr=watched_file_handler.stream,
- stdout=watched_file_handler.stream)
- if options.purge:
- settings["purge"] = True
- with context:
- logging.info("Running LAVA PDU Listener %s %s %d."
- % (logfile,
- daemon_settings['hostname'],
- daemon_settings['port']))
- ListenerServer(settings).start()
diff --git a/lavapdu-runner b/lavapdu-runner
deleted file mode 100755
index f32b217..0000000
--- a/lavapdu-runner
+++ /dev/null
@@ -1,67 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
-
-import logging
-import os
-import sys
-import optparse
-from lavapdu.shared import get_daemon_logger
-from lavapdu.shared import read_settings
-import lavapdu.runnermaster as runnermaster
-
-import daemon
-try:
- import daemon.pidlockfile as pidlockfile
-except ImportError:
- from lockfile import pidlockfile
-
-from lavapdu.pdurunner import PDURunner
-
-
-if __name__ == '__main__':
- pidfile = "/var/run/lavapdu-runner.pid"
- logfile = "/var/log/lavapdu-runner.log"
- conffile = "/etc/lavapdu/lavapdu.conf"
- settings = read_settings(conffile)
- level = logging.DEBUG
- daemon_settings = settings["daemon"]
- if daemon_settings["logging_level"] == "DEBUG":
- level = logging.DEBUG
- if daemon_settings["logging_level"] == "WARNING":
- level = logging.WARNING
- if daemon_settings["logging_level"] == "ERROR":
- level = logging.ERROR
- if daemon_settings["logging_level"] == "INFO":
- level = logging.INFO
- client_logger, watched_file_handler = get_daemon_logger(
- logfile,
- loglevel=level,
- log_format='%(asctime)s:%(levelname)s:%(name)s:%(message)s')
- if isinstance(client_logger, Exception):
- print("Fatal error creating client_logger: " + str(client_logger))
- sys.exit(os.EX_OSERR)
- context = daemon.DaemonContext(
- detach_process=True,
- working_directory=os.getcwd(),
- files_preserve=[watched_file_handler.stream],
- stderr=watched_file_handler.stream,
- stdout=watched_file_handler.stream)
- with context:
- runnermaster.start_em_up(settings, pidfile)
diff --git a/lavapdu/__init__.py b/lavapdu/__init__.py
deleted file mode 100644
index fe1f8f3..0000000
--- a/lavapdu/__init__.py
+++ /dev/null
@@ -1,19 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
diff --git a/lavapdu/dbhandler.py b/lavapdu/dbhandler.py
deleted file mode 100644
index cc9e783..0000000
--- a/lavapdu/dbhandler.py
+++ /dev/null
@@ -1,94 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
-
-import logging
-import psycopg2
-import time
-log = logging.getLogger(__name__)
-
-
-class DBHandler(object):
- def __init__(self, config):
- log.debug("Creating new DBHandler: %s %s", config["dbhost"],
- config["dbname"])
- self.conn = psycopg2.connect(database=config["dbname"],
- user=config["dbuser"],
- password=config["dbpass"],
- host=config["dbhost"])
- self.cursor = self.conn.cursor()
-
- def do_sql(self, sql):
- log.debug("executing sql: %s", sql)
- self.cursor.execute(sql)
- self.conn.commit()
-
- def do_sql_with_fetch(self, sql):
- log.debug("executing sql: %s", sql)
- self.cursor.execute(sql)
- row = self.cursor.fetchone()
- self.conn.commit()
- return row
-
- def create_db(self):
- log.info("Creating db table if it doesn't exist")
- sql = "create table if not exists pdu_queue (id serial, hostname " \
- "text, port int, request text, exectime int)"
- self.do_sql(sql)
- sql = "select column_name from information_schema.columns where " \
- "table_name='pdu_queue' and column_name='exectime'"
- res = self.do_sql_with_fetch(sql)
- if not res:
- log.info("Old db schema discovered, upgrading")
- sql = "alter table pdu_queue add column exectime int default 1"
- self.do_sql(sql)
-
- def insert_request(self, hostname, port, request, exectime):
- sql = "insert into pdu_queue (hostname,port,request,exectime) " \
- "values ('%s',%i,'%s',%i)" % (hostname, port, request, exectime)
- self.do_sql(sql)
-
- def delete_row(self, row_id):
- log.debug("deleting row %i", row_id)
- self.do_sql("delete from pdu_queue where id=%i" % row_id)
-
- def get_res(self, sql):
- return self.cursor.execute(sql)
-
- def purge(self):
- log.debug("Purging all jobs from database")
- self.do_sql("delete from pdu_queue")
- self.close()
-
- def get_next_job(self, single_pdu=False):
- now = int(time.time())
- extra_sql = ""
- if single_pdu:
- log.debug("Looking for jobs for PDU: %s", single_pdu)
- extra_sql = "and hostname='%s'" % single_pdu
- row = self.do_sql_with_fetch("select id, hostname, port, request "
- "from pdu_queue where ((exectime < %i "
- "or exectime is null) %s) order by id asc"
- " limit 1" % (now, extra_sql))
- return row
-
- def close(self):
- log.debug("Closing DBHandler")
- self.cursor.close()
- self.conn.close()
diff --git a/lavapdu/drivers/__init__.py b/lavapdu/drivers/__init__.py
deleted file mode 100644
index fe1f8f3..0000000
--- a/lavapdu/drivers/__init__.py
+++ /dev/null
@@ -1,19 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
diff --git a/lavapdu/drivers/apc7952.py b/lavapdu/drivers/apc7952.py
deleted file mode 100644
index 7140948..0000000
--- a/lavapdu/drivers/apc7952.py
+++ /dev/null
@@ -1,103 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
-
-import logging
-from lavapdu.drivers.apcbase import APCBase
-log = logging.getLogger(__name__)
-
-
-class APC7952(APCBase):
-
- @classmethod
- def accepts(cls, drivername):
- if drivername == "apc7952":
- return True
- return False
-
- def _pdu_logout(self):
- self._back_to_main()
- log.debug("Logging out")
- self.connection.send("4\r")
-
- def _back_to_main(self):
- log.debug("Returning to main menu")
- self.connection.send("\r")
- self.connection.expect('>')
- for _ in range(1, 20):
- self.connection.send("\x1B")
- self.connection.send("\r")
- res = self.connection.expect(["4- Logout", "> "])
- if res == 0:
- log.debug("Back at main menu")
- break
-
- def _enter_outlet(self, outlet, enter_needed=True):
- outlet = "%s" % outlet
- log.debug("Attempting to enter outlet %s", outlet)
- if enter_needed:
- self.connection.expect("Press <ENTER> to continue...")
- log.debug("Sending enter")
- self.connection.send("\r")
- self.connection.expect("> ")
- log.debug("Sending outlet number")
- self.connection.send(outlet)
- self.connection.send("\r")
- log.debug("Finished entering outlet")
-
- def _port_interaction(self, command, port_number):
- log.debug("Attempting command: %s port: %i",
- command, port_number)
- # make sure in main menu here
- self._back_to_main()
- self.connection.send("\r")
- self.connection.expect("1- Device Manager")
- self.connection.expect("> ")
- log.debug("Entering Device Manager")
- self.connection.send("1\r")
- self.connection.expect("------- Device Manager")
- self.connection.send("2\r")
- self.connection.expect("1- Outlet Control/Configuration")
- self.connection.expect("> ")
- self.connection.send("1\r")
- self._enter_outlet(port_number, False)
- self.connection.expect("> ")
- self.connection.send("1\r")
- res = self.connection.expect(["> ", "Press <ENTER> to continue..."])
- if res == 1:
- log.debug("Stupid paging thingmy detected, pressing enter")
- self.connection.send("\r")
- self.connection.send("\r")
- if command == "on":
- self.connection.send("1\r")
- self.connection.expect("Immediate On")
- self._do_it()
- elif command == "off":
- self.connection.send("2\r")
- self.connection.expect("Immediate Off")
- self._do_it()
- else:
- log.debug("Unknown command!")
-
- def _do_it(self):
- self.connection.expect("Enter 'YES' to continue or "
- "<ENTER> to cancel :")
- self.connection.send("YES\r")
- self.connection.expect("Press <ENTER> to continue...")
- self.connection.send("\r")
diff --git a/lavapdu/drivers/apc8959.py b/lavapdu/drivers/apc8959.py
deleted file mode 100644
index c699962..0000000
--- a/lavapdu/drivers/apc8959.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
-
-import logging
-from lavapdu.drivers.apcbase import APCBase
-log = logging.getLogger(__name__)
-
-
-class APC8959(APCBase):
- pdu_commands = {"off": "olOff", "on": "olOn"}
-
- @classmethod
- def accepts(cls, drivername):
- if drivername == "apc8959":
- return True
- return False
-
- def _pdu_logout(self):
- log.debug("logging out")
- self.connection.send("\r")
- self.connection.send("exit")
- self.connection.send("\r")
- log.debug("done")
-
- def _pdu_get_to_prompt(self):
- self.connection.send("\r")
- self.connection.expect('apc>')
-
- def _port_interaction(self, command, port_number):
- log.debug("Attempting %s on port %i", command, port_number)
- self._pdu_get_to_prompt()
- self.connection.sendline(self.pdu_commands[command] +
- (" %i" % port_number))
- self.connection.expect("E000: Success")
- self._pdu_get_to_prompt()
- log.debug("done")
diff --git a/lavapdu/drivers/apc9210.py b/lavapdu/drivers/apc9210.py
deleted file mode 100644
index 7069820..0000000
--- a/lavapdu/drivers/apc9210.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
-
-import logging
-from lavapdu.drivers.apc7952 import APC7952
-log = logging.getLogger(__name__)
-
-
-class APC9210(APC7952):
-
- @classmethod
- def accepts(cls, drivername):
- if drivername == "apc9210":
- return True
- return False
-
- def _port_interaction(self, command, port_number):
- log.debug("Attempting command: %s port: %i", command, port_number)
- # make sure in main menu here
- self._back_to_main()
- self.connection.send("\r")
- self.connection.expect("1- Outlet Manager")
- self.connection.expect("> ")
- log.debug("Entering Outlet Manager")
- self.connection.send("1\r")
- self.connection.expect("------- Outlet Manager")
- log.debug("Got to Device Manager")
- self._enter_outlet(port_number, False)
- self.connection.expect(["1- Control of Outlet",
- "1- Outlet Control/Configuration"])
- self.connection.expect("> ")
- self.connection.send("1\r")
- self.connection.expect("Turn Outlet On")
- self.connection.expect("> ")
- if command == "on":
- self.connection.send("1\r")
- self.connection.expect("Turn Outlet On")
- self._do_it()
- elif command == "off":
- self.connection.send("2\r")
- self.connection.expect("Turn Outlet Off")
- self._do_it()
- else:
- log.debug("Unknown command!")
diff --git a/lavapdu/drivers/apc9218.py b/lavapdu/drivers/apc9218.py
deleted file mode 100644
index 4189b29..0000000
--- a/lavapdu/drivers/apc9218.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
-
-import logging
-from lavapdu.drivers.apc7952 import APC7952
-log = logging.getLogger(__name__)
-
-
-class APC9218(APC7952):
-
- @classmethod
- def accepts(cls, drivername):
- models = ["ap9606", "apc9606", "ap9218", "apc9218"]
- if drivername.lower() in models:
- return True
- return False
-
- def _port_interaction(self, command, port_number):
- # make sure in main menu here
- self._back_to_main()
- self.connection.send("\r")
- self.connection.expect("1- Device Manager")
- self.connection.expect("> ")
- log.debug("Entering Device Manager")
- self.connection.send("1\r")
- self.connection.expect("------- Device Manager")
- log.debug("Got to Device Manager")
- self._enter_outlet(port_number, False)
- self.connection.expect(["1- Control Outlet",
- "1- Outlet Control/Configuration"])
- self.connection.expect("> ")
- self.connection.send("1\r")
- res = self.connection.expect(["> ", "Press <ENTER> to continue..."])
- if res == 1:
- log.debug("Stupid paging thingmy detected, pressing enter")
- self.connection.send("\r")
- self.connection.send("\r")
- self.connection.expect(["Control Outlet %s" % port_number,
- "Control Outlet"])
- self.connection.expect("3- Immediate Reboot")
- self.connection.expect("> ")
- if command == "on":
- self.connection.send("1\r")
- self.connection.expect("Immediate On")
- self._do_it()
- elif command == "off":
- self.connection.send("2\r")
- self.connection.expect("Immediate Off")
- self._do_it()
- else:
- log.debug("Unknown command!")
diff --git a/lavapdu/drivers/apcbase.py b/lavapdu/drivers/apcbase.py
deleted file mode 100644
index 5f16705..0000000
--- a/lavapdu/drivers/apcbase.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
-
-import logging
-import pexpect
-from lavapdu.drivers.driver import PDUDriver
-log = logging.getLogger(__name__)
-
-
-class APCBase(PDUDriver):
- connection = None
-
- def __init__(self, hostname, settings):
- self.hostname = hostname
- log.debug(settings)
- self.settings = settings
- telnetport = 23
- if "telnetport" in settings:
- telnetport = settings["telnetport"]
- self.exec_string = "/usr/bin/telnet %s %d" % (hostname, telnetport)
- self.get_connection()
- super(APCBase, self).__init__()
-
- @classmethod
- def accepts(cls, drivername):
- log.debug(drivername)
- return False
-
- def port_interaction(self, command, port_number):
- log.debug("Running port_interaction from APCBase")
- self._port_interaction(command, # pylint: disable=no-member
- port_number)
-
- def get_connection(self):
- log.debug("Connecting to APC PDU with: %s", self.exec_string)
- # only uncomment this line for FULL debug when developing
- # self.connection = pexpect.spawn(self.exec_string, logfile=sys.stdout)
- self.connection = pexpect.spawn(self.exec_string)
- self._pdu_login("apc", "apc")
-
- def _cleanup(self):
- self._pdu_logout() # pylint: disable=no-member
-
- def _bombout(self):
- log.debug("Bombing out of driver: %s", self.connection)
- self.connection.close(force=True)
- del self
-
- def _pdu_login(self, username, password):
- log.debug("attempting login with username %s, password %s",
- username, password)
- self.connection.send("\r")
- self.connection.expect("User Name :")
- self.connection.send("%s\r" % username)
- self.connection.expect("Password :")
- self.connection.send("%s\r" % password)
diff --git a/lavapdu/drivers/driver.py b/lavapdu/drivers/driver.py
deleted file mode 100644
index f0bdbe7..0000000
--- a/lavapdu/drivers/driver.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
-
-import logging
-log = logging.getLogger(__name__)
-
-
-class PDUDriver(object):
- connection = None
- hostname = ""
-
- def __init__(self):
- super(PDUDriver, self).__init__()
-
- @classmethod
- def select(cls, drivername):
- log.debug("adding PDUDriver subclasses: %s",
- cls.__subclasses__()) # pylint: disable=no-member
- candidates = cls.__subclasses__() # pylint: disable=no-member
- for subc in cls.__subclasses__(): # pylint: disable=no-member
- log.debug("adding %s subclasses: %s", subc,
- subc.__subclasses__())
- candidates = candidates + (subc.__subclasses__())
- for subsubc in subc.__subclasses__():
- log.debug("adding %s subclasses: %s", subsubc,
- subsubc.__subclasses__())
- candidates = candidates + (subsubc.__subclasses__())
- log.debug(candidates)
- willing = [c for c in candidates if c.accepts(drivername)]
- if len(willing) == 0:
- raise NotImplementedError(
- "No driver accepted the request "
- "'%s' with the specified job parameters. %s" %
- (drivername, cls)
- )
- log.debug("%s accepted the request", willing[0])
- return willing[0]
-
- def handle(self, request, port_number, delay=0):
- log.debug("Driving PDU hostname: %s "
- "PORT: %s REQUEST: %s (delay %s)",
- self.hostname, port_number, request, delay)
- if request == "on":
- self.port_on(port_number)
- elif request == "off":
- self.port_off(port_number)
- else:
- log.debug("Unknown request to handle - oops")
- raise NotImplementedError(
- "Driver doesn't know how to %s " % request
- )
- self._cleanup()
-
- def port_on(self, port_number):
- self.port_interaction("on", port_number)
-
- def port_off(self, port_number):
- self.port_interaction("off", port_number)
-
- def port_interaction(self, command, port_number):
- pass
-
- def _bombout(self):
- pass
-
- def _cleanup(self):
- pass
diff --git a/lavapdu/drivers/strategies.py b/lavapdu/drivers/strategies.py
deleted file mode 100644
index df3db3e..0000000
--- a/lavapdu/drivers/strategies.py
+++ /dev/null
@@ -1,29 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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 lavapdu.drivers.apc7952 import APC7952 # pylint: disable=W0611
-from lavapdu.drivers.apc9218 import APC9218 # pylint: disable=W0611
-from lavapdu.drivers.apc8959 import APC8959 # pylint: disable=W0611
-from lavapdu.drivers.apc9210 import APC9210 # pylint: disable=W0611
-
-assert APC7952
-assert APC9218
-assert APC8959
-assert APC9210
diff --git a/lavapdu/pdurunner.py b/lavapdu/pdurunner.py
deleted file mode 100644
index 95c6767..0000000
--- a/lavapdu/pdurunner.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
-
-import logging
-import time
-import traceback
-from lavapdu.dbhandler import DBHandler
-from lavapdu.drivers.driver import PDUDriver
-import lavapdu.drivers.strategies # pylint: disable=W0611
-from lavapdu.shared import drivername_from_hostname
-from lavapdu.shared import pdus_from_config
-assert lavapdu.drivers.strategies
-log = logging.getLogger(__name__)
-
-
-class PDURunner(object):
-
- def __init__(self, config, single_pdu=False):
- self.settings = config["daemon"]
- self.pdus = config["pdus"]
- if single_pdu:
- if single_pdu not in pdus_from_config(config):
- raise NotImplementedError
- self.single_pdu = single_pdu
- self.dbh = DBHandler(self.settings)
-
- def get_one(self):
- job = self.dbh.get_next_job(self.single_pdu)
- if job:
- job_id, hostname, port, request = job
- log.debug(job)
- log.info("Processing queue item: (%s %s) on hostname: %s",
- request, port, hostname)
- self.do_job(hostname, port, request)
- self.dbh.delete_row(job_id)
-
- def driver_from_hostname(self, hostname):
- drivername = drivername_from_hostname(hostname, self.pdus)
- driver = PDUDriver.select(drivername)(hostname, self.pdus[hostname])
- return driver
-
- def do_job(self, hostname, port, request, delay=0):
- retries = self.settings["retries"]
- driver = False
- while retries > 0:
- try:
- driver = self.driver_from_hostname(hostname)
- return driver.handle(request, port, delay)
- except Exception as e: # pylint: disable=broad-except
- log.warn(traceback.format_exc())
- log.warn("Failed to execute job: %s %s %s "
- "(attempts left %i) error was %s",
- hostname, port, request, retries, e.message)
- if driver:
- driver._bombout() # pylint: disable=W0212,E1101
- time.sleep(5)
- retries -= 1
- return False
-
- def run_me(self):
- if self.single_pdu:
- log.info("Starting a PDURunner for PDU: %s", self.single_pdu)
- else:
- log.info("Starting a PDURunner for all PDUS")
- while 1:
- self.get_one()
- time.sleep(2)
diff --git a/lavapdu/runnermaster.py b/lavapdu/runnermaster.py
deleted file mode 100644
index fe979da..0000000
--- a/lavapdu/runnermaster.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
-
-import lavapdu.pdurunner as pdurunner
-from multiprocessing import Process
-from setproctitle import setproctitle # pylint: disable=no-name-in-module
-from lavapdu.shared import pdus_from_config
-import signal
-import sys
-import os
-import logging
-processes = []
-log = logging.getLogger(__name__)
-
-
-def start_runner(config, pdu):
- setproctitle("pdurunner for %s" % pdu)
- p = pdurunner.PDURunner(config, pdu)
- p.run_me()
-
-
-def start_em_up(config, pidfile):
- pid = os.getpid()
- if os.path.isfile(pidfile):
- log.error("Pidfile already exists")
- sys.exit(1)
- f = open(pidfile, 'w')
- f.write(str(pid))
- f.close()
- pdus = pdus_from_config(config)
- for pdu in pdus:
- p = Process(target=start_runner, args=(config, pdu))
- p.start()
- processes.append(p)
- signal.signal(signal.SIGTERM, signal_term_handler)
-
-
-def signal_term_handler(a, b):
- del a, b
- print 'Sending sigterm to all children'
- for proc in processes:
- log.debug("Terminate %s", proc.pid)
- proc.terminate()
- sys.exit(0)
diff --git a/lavapdu/shared.py b/lavapdu/shared.py
deleted file mode 100644
index 46af539..0000000
--- a/lavapdu/shared.py
+++ /dev/null
@@ -1,41 +0,0 @@
-import logging
-import json
-from logging.handlers import WatchedFileHandler
-
-
-def get_daemon_logger(filepath, log_format=None, loglevel=logging.INFO):
- logger = logging.getLogger()
- logger.setLevel(loglevel)
- try:
- watchedhandler = WatchedFileHandler(filepath)
- except Exception as e: # pylint: disable=broad-except
- return e
-
- watchedhandler.setFormatter(logging.Formatter(log_format
- or '%(asctime)s %(msg)s'))
- logger.addHandler(watchedhandler)
- return logger, watchedhandler
-
-
-def read_settings(filename):
- with open(filename) as stream:
- jobdata = stream.read()
- json_data = json.loads(jobdata)
- return json_data
-
-
-def drivername_from_hostname(hostname, pdus):
- if hostname in pdus:
- drivername = (pdus[hostname]["driver"])
- else:
- raise NotImplementedError("No configuration available for %s, "
- "is there a section in the lavapdu.conf?" %
- hostname)
- return drivername
-
-
-def pdus_from_config(data):
- output = []
- for pdu in data["pdus"]:
- output.append(pdu)
- return output
diff --git a/lavapdu/socketserver.py b/lavapdu/socketserver.py
deleted file mode 100644
index b5c5668..0000000
--- a/lavapdu/socketserver.py
+++ /dev/null
@@ -1,113 +0,0 @@
-#! /usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
-
-import SocketServer
-import logging
-import socket
-import time
-import sys
-import os
-from lavapdu.dbhandler import DBHandler
-from lavapdu.shared import drivername_from_hostname
-log = logging.getLogger(__name__)
-
-
-class ListenerServer(object):
-
- def __init__(self, config):
- self.config = config
- settings = config["daemon"]
- listen_host = settings["hostname"]
- listen_port = settings["port"]
- log.debug("ListenerServer __init__")
- if "purge" in config:
- self.server.dbh.purge()
- sys.exit(os.EX_OK)
- log.info("listening on %s:%s", listen_host, listen_port)
-
- self.server = TCPServer((listen_host, listen_port), TCPRequestHandler)
- self.server.settings = settings
- self.server.config = config
- self.server.dbh = DBHandler(settings)
-
-
- def start(self):
- log.info("Starting the ListenerServer")
- self.server.serve_forever()
-
-
-class TCPRequestHandler(SocketServer.BaseRequestHandler):
- # "One instance per connection. Override handle(self) to customize
- # action."
- def insert_request(self, data):
- array = data.split(" ")
- delay = 10
- custom_delay = False
- now = int(time.time())
- if (len(array) < 3) or (len(array) > 4):
- log.info("Wrong data size")
- raise Exception("Unexpected data")
- if len(array) == 4:
- delay = int(array[3])
- custom_delay = True
- hostname = array[0]
- port = int(array[1])
- request = array[2]
- # this will throw if the pdu is not found
- drivername_from_hostname(hostname, self.server.config["pdus"])
- dbh = self.server.dbh
- if not (request in ["reboot", "on", "off"]):
- log.info("Unknown request: %s", request)
- raise Exception("Unknown request: %s", request)
- if request == "reboot":
- log.debug("reboot requested, submitting off/on")
- dbh.insert_request(hostname, port, "off", now)
- dbh.insert_request(hostname, port, "on", now + delay)
- else:
- if custom_delay:
- log.debug("using delay as requested")
- dbh.insert_request(hostname, port, request, now + delay)
- else:
- dbh.insert_request(hostname, port, request, now)
-
- def handle(self):
- request_ip = self.client_address[0]
- try:
- data = self.request.recv(4096).strip()
- socket.setdefaulttimeout(2)
- try:
- request_host = socket.gethostbyaddr(request_ip)[0]
- except socket.herror:
- request_host = request_ip
- log.info("Received a request from %s: '%s'",
- request_host,
- data)
- self.insert_request(data)
- self.request.sendall("ack\n")
- except Exception as global_error: # pylint: disable=broad-except
- log.debug(global_error.__class__)
- log.debug(global_error.message)
- self.request.sendall(global_error.message)
- self.request.close()
-
-
-class TCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
- allow_reuse_address = True
- daemon_threads = True
diff --git a/pduclient b/pduclient
deleted file mode 100755
index 4e278b5..0000000
--- a/pduclient
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-
-# Copyright 2013 Linaro Limited
-# Author Matt Hart <matthew.hart@linaro.org>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 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 General Public License for more details.
-#
-# You should have received a copy of the GNU 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.
-
-import socket
-import optparse
-
-if __name__ == '__main__':
- usage = "Usage: %prog --daemon deamonhostname --hostname pduhostname " \
- "--port pduportnum --command pducommand"
- description = "LAVA PDU daemon client"
- commands = ["reboot", "on", "off"]
- parser = optparse.OptionParser(usage=usage, description=description)
- parser.add_option("--daemon", dest="pdudaemonhostname", action="store",
- type="string",
- help="LAVAPDU Daemon hostname (ex: localhost)")
- parser.add_option("--hostname", dest="pduhostname", action="store",
- type="string", help="PDU Hostname (ex: pdu05)")
- parser.add_option("--port", dest="pduportnum", action="store",
- type="string", help="PDU Portnumber (ex: 04)")
- parser.add_option("--command", dest="pducommand", action="store",
- type="string", help="PDU command (ex: reboot|on|off)")
- parser.add_option("--delay", dest="pdudelay", action="store", type="int",
- help="Delay before command runs, or between off/on "
- "when rebooting (ex: 5)")
- (options, args) = parser.parse_args()
- if not options.pdudaemonhostname \
- or not options.pduhostname \
- or not options.pduportnum \
- or not options.pducommand:
- print("Missing option, try -h for help")
- exit(1)
- if not (options.pducommand in commands):
- print("Unknown pdu command: %s" % options.pducommand)
- exit(1)
- if options.pdudelay:
- string = ("%s %s %s %s" % (options.pduhostname, options.pduportnum,
- options.pducommand, options.pdudelay))
- else:
- string = ("%s %s %s" % (options.pduhostname, options.pduportnum,
- options.pducommand))
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- # sock.setblocking(0) # optional non-blocking
- reply = ""
- # noinspection PyBroadException
- try:
- sock.connect((options.pdudaemonhostname, 16421))
- sock.send(string)
- reply = sock.recv(16384).strip() # limit reply to 16K
- sock.close()
- except Exception:
- print ("Error sending command, wrong daemon hostname?")
- exit(1)
- if reply == "ack":
- print("Command sent successfully.")
- exit(0)
- else:
- print("Error sending command! %s replied: %s" %
- (options.pdudaemonhostname, reply))
- exit(127)
diff --git a/setup.py b/setup.py
deleted file mode 100644
index 8e47cf5..0000000
--- a/setup.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#! /usr/bin/env python
-#
-# Copyright (C) 2013 Linaro Limited
-#
-# Author: Matthew Hart <matthew.hart@linaro.org>
-#
-# This file is part of PDUDAEMON.
-#
-# PDUDAEMON is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# PDUDAEMON 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 General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, see <http://www.gnu.org/licenses>.
-
-from setuptools import setup, find_packages
-
-setup(
- name='lavapdu',
- version="0.0.5",
- author="Matthew Hart",
- author_email="matthew.hart@linaro.org",
- license="GPL2+",
- description="LAVA PDU Deamon for APC PDU's",
- packages=find_packages(),
- install_requires=[
- "daemon",
- "lockfile",
- "pexpect",
- "psycopg2",
- "setproctitle"
- ],
- data_files=[
- ("/etc/init.d/", ["etc/lavapdu-runner.init"]),
- ("/etc/init.d/", ["etc/lavapdu-listen.init"]),
- ("/usr/share/lavapdu/", [
- "etc/lavapdu-listen.service",
- "etc/lavapdu-runner.service"
- ]),
- ("/etc/lavapdu/", ["etc/lavapdu/lavapdu.conf"]),
- ("/etc/logrotate.d/", ["etc/lavapdulogrotate"]),
- ],
- scripts=[
- 'lavapdu-runner',
- 'lavapdu-listen',
- 'pduclient'
- ],
- zip_safe=False,
- include_package_data=True)