PEP 8 clean thanks to auto pep8

This commit is contained in:
Julien Duponchelle committed 2015-01-20 13:24:00 +01:00
1 parent 7f185663d1
commit f5ed9fbcf1
124 files changed
+340 -210

No files matched your search

-1
View File
@@ -175,7 +175,6 @@ class BaseCloudCtrl(object):
except Exception as e:
log.error("list_instances returned an error: {}".format(e))
def create_key_pair(self, name):
""" Create and return a new Key Pair. """
+22
View File
@@ -1,45 +1,67 @@
""" Exception classes for CloudCtrl classes. """
class ApiError(Exception):
""" Raised when the server returns 500 Compute Error. """
pass
class BadRequest(Exception):
""" Raised when the server returns 400 Bad Request. """
pass
class ComputeFault(Exception):
""" Raised when the server returns 400|500 Compute Fault. """
pass
class Forbidden(Exception):
""" Raised when the server returns 403 Forbidden. """
pass
class ItemNotFound(Exception):
""" Raised when the server returns 404 Not Found. """
pass
class KeyPairExists(Exception):
""" Raised when the server returns 409 Conflict Key pair exists. """
pass
class MethodNotAllowed(Exception):
""" Raised when the server returns 405 Method Not Allowed. """
pass
class OverLimit(Exception):
""" Raised when the server returns 413 Over Limit. """
pass
class ServerCapacityUnavailable(Exception):
""" Raised when the server returns 503 Server Capacity Uavailable. """
pass
class ServiceUnavailable(Exception):
""" Raised when the server returns 503 Service Unavailable. """
pass
class Unauthorized(Exception):
""" Raised when the server returns 401 Unauthorized. """
pass
+33 -33
View File
@@ -41,7 +41,7 @@ from os.path import expanduser
SCRIPT_NAME = os.path.basename(__file__)
#Is the full path when used as an import
# Is the full path when used as an import
SCRIPT_PATH = os.path.dirname(__file__)
if not SCRIPT_PATH:
@@ -98,6 +98,8 @@ Options:
""" % (SCRIPT_NAME)
# Parse cmd line options
def parse_cmd_line(argv):
"""
Parse command line arguments
@@ -107,22 +109,22 @@ def parse_cmd_line(argv):
short_args = "dvhk"
long_args = ("debug",
"verbose",
"help",
"cloud_user_name=",
"cloud_api_key=",
"instance_id=",
"region=",
"dead_time=",
"init-wait=",
"check-interval=",
"file=",
"background",
)
"verbose",
"help",
"cloud_user_name=",
"cloud_api_key=",
"instance_id=",
"region=",
"dead_time=",
"init-wait=",
"check-interval=",
"file=",
"background",
)
try:
opts, extra_opts = getopt.getopt(argv[1:], short_args, long_args)
except getopt.GetoptError as e:
print("Unrecognized command line option or missing required argument: %s" %(e))
print("Unrecognized command line option or missing required argument: %s" % (e))
print(usage)
sys.exit(2)
@@ -133,7 +135,7 @@ def parse_cmd_line(argv):
cmd_line_option_list["cloud_api_key"] = None
cmd_line_option_list["instance_id"] = None
cmd_line_option_list["region"] = None
cmd_line_option_list["dead_time"] = 60 * 60 #minutes
cmd_line_option_list["dead_time"] = 60 * 60 # minutes
cmd_line_option_list["check-interval"] = None
cmd_line_option_list["init-wait"] = 5 * 60
cmd_line_option_list["file"] = None
@@ -146,8 +148,7 @@ def parse_cmd_line(argv):
elif sys.platform == "osx":
cmd_line_option_list['syslog'] = "/var/run/syslog"
else:
cmd_line_option_list['syslog'] = ('localhost',514)
cmd_line_option_list['syslog'] = ('localhost', 514)
get_gns3secrets(cmd_line_option_list)
cmd_line_option_list["dead_time"] = int(cmd_line_option_list["dead_time"])
@@ -181,7 +182,7 @@ def parse_cmd_line(argv):
elif (opt in ("--background")):
cmd_line_option_list["daemon"] = True
if cmd_line_option_list["shutdown"] == False:
if cmd_line_option_list["shutdown"] is False:
if cmd_line_option_list["check-interval"] is None:
cmd_line_option_list["check-interval"] = cmd_line_option_list["dead_time"] + 120
@@ -211,9 +212,9 @@ def parse_cmd_line(argv):
print(usage)
sys.exit(2)
return cmd_line_option_list
def get_gns3secrets(cmd_line_option_list):
"""
Load cloud credentials from .gns3secrets
@@ -248,10 +249,10 @@ def set_logging(cmd_options):
log_level = logging.INFO
log_level_console = logging.WARNING
if cmd_options['verbose'] == True:
if cmd_options['verbose']:
log_level_console = logging.INFO
if cmd_options['debug'] == True:
if cmd_options['debug']:
log_level_console = logging.DEBUG
log_level = logging.DEBUG
@@ -275,6 +276,7 @@ def set_logging(cmd_options):
return log
def send_shutdown(pid_file):
"""
Sends the daemon process a kill signal
@@ -291,8 +293,9 @@ def send_shutdown(pid_file):
def _get_file_age(filename):
return datetime.datetime.fromtimestamp(
os.path.getmtime(filename)
)
os.path.getmtime(filename)
)
def monitor_loop(options):
"""
@@ -307,7 +310,7 @@ def monitor_loop(options):
terminate_attempts = 0
while options['shutdown'] == False:
while options['shutdown'] is False:
log.debug("In monitor_loop for : %s" % (
datetime.datetime.now() - options['starttime'])
)
@@ -320,15 +323,15 @@ def monitor_loop(options):
if delta.seconds > options["dead_time"]:
log.warning("Dead time exceeded, terminating instance ...")
#Terminate involves many layers of HTTP / API calls, lots of
#different errors types could occur here.
# Terminate involves many layers of HTTP / API calls, lots of
# different errors types could occur here.
try:
rksp = Rackspace(options)
rksp.terminate()
except Exception as e:
log.critical("Exception during terminate: %s" % (e))
terminate_attempts+=1
terminate_attempts += 1
log.warning("Termination sent, attempt: %s" % (terminate_attempts))
time.sleep(600)
else:
@@ -372,14 +375,13 @@ def main():
for key, value in iter(sorted(options.items())):
log.debug("%s : %s" % (key, value))
log.debug("Checking file ....")
if os.path.isfile(options["file"]) == False:
if os.path.isfile(options["file"]) is False:
log.critical("File does not exist!!!")
sys.exit(1)
test_acess = _get_file_age(options["file"])
if type(test_acess) is not datetime.datetime:
if not isinstance(test_acess, datetime.datetime):
log.critical("Can't get file modification time!!!")
sys.exit(1)
@@ -390,13 +392,11 @@ def main():
class MyDaemon(daemon.daemon):
def run(self):
monitor_loop(self.options)
if __name__ == "__main__":
result = main()
sys.exit(result)
+1 -1
View File
@@ -21,4 +21,4 @@
# three numbers are the components of the version number. The fourth
# is zero for an official release, positive for a development branch,
# or negative for a release candidate or beta (after the base version
# number has been incremented)
# number has been incremented)
+14 -8
View File
@@ -1,8 +1,14 @@
"""Generic linux daemon base class for python 3.x."""
import sys, os, time, atexit, signal
import sys
import os
import time
import atexit
import signal
class daemon:
"""A generic daemon class.
Usage: subclass the daemon class and override the run() method."""
@@ -54,7 +60,7 @@ class daemon:
atexit.register(self.delpid)
pid = str(os.getpid())
with open(self.pidfile,'w+') as f:
with open(self.pidfile, 'w+') as f:
f.write(pid + '\n')
def delpid(self):
@@ -74,7 +80,7 @@ class daemon:
# Check for a pidfile to see if the daemon already runs
try:
with open(self.pidfile,'r') as pf:
with open(self.pidfile, 'r') as pf:
pid = int(pf.read().strip())
except IOError:
@@ -101,20 +107,20 @@ class daemon:
# Get the pid from the pidfile
try:
with open(self.pidfile,'r') as pf:
with open(self.pidfile, 'r') as pf:
pid = int(pf.read().strip())
except IOError:
pid = None
if not pid:
message = "pidfile {0} does not exist. " + \
"Daemon not running?\n"
"Daemon not running?\n"
sys.stderr.write(message.format(self.pidfile))
return # not an error in a restart
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
while True:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
except OSError as err:
@@ -123,7 +129,7 @@ class daemon:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print (str(err.args))
print(str(err.args))
sys.exit(1)
def restart(self):
+5 -2
View File
@@ -23,7 +23,8 @@
# or negative for a release candidate or beta (after the base version
# number has been incremented)
import os, sys
import os
import sys
import json
import logging
import socket
@@ -34,7 +35,9 @@ from gns3dms.cloud.rackspace_ctrl import RackspaceCtrl
LOG_NAME = "gns3dms.rksp"
log = logging.getLogger("%s" % (LOG_NAME))
class Rackspace(object):
def __init__(self, options):
self.username = options["cloud_user_name"]
self.apikey = options["cloud_api_key"]
@@ -54,7 +57,7 @@ class Rackspace(object):
for region in self.rksp.list_regions():
log.debug("Rackspace regions: %s" % (region))
log.debug("Checking region: %s" % (self.region))
self.rksp.set_region(self.region)
for server in self.rksp.list_instances():