utilities modules: PEP8 compliancy (#27741)

This commit is contained in:
Dag Wieers 2017-08-10 10:36:28 +02:00 committed by John R Barker
parent f30589c91d
commit eee09565b1
4 changed files with 75 additions and 65 deletions

View file

@ -110,20 +110,26 @@ CHUNK_SIZE=10240
# FIXME: this all should be moved to module_common, as it's # FIXME: this all should be moved to module_common, as it's
# pretty much a copy from the callbacks/util code # pretty much a copy from the callbacks/util code
DEBUG_LEVEL = 0 DEBUG_LEVEL = 0
def log(msg, cap=0): def log(msg, cap=0):
global DEBUG_LEVEL global DEBUG_LEVEL
if DEBUG_LEVEL >= cap: if DEBUG_LEVEL >= cap:
syslog.syslog(syslog.LOG_NOTICE | syslog.LOG_DAEMON, msg) syslog.syslog(syslog.LOG_NOTICE | syslog.LOG_DAEMON, msg)
def v(msg): def v(msg):
log(msg, cap=1) log(msg, cap=1)
def vv(msg): def vv(msg):
log(msg, cap=2) log(msg, cap=2)
def vvv(msg): def vvv(msg):
log(msg, cap=3) log(msg, cap=3)
def vvvv(msg): def vvvv(msg):
log(msg, cap=4) log(msg, cap=4)
@ -137,6 +143,7 @@ except ImportError:
SOCKET_FILE = os.path.join(get_module_path(), '.ansible-accelerate', ".local.socket") SOCKET_FILE = os.path.join(get_module_path(), '.ansible-accelerate', ".local.socket")
def get_pid_location(module): def get_pid_location(module):
""" """
Try to find a pid directory in the common locations, falling Try to find a pid directory in the common locations, falling
@ -191,6 +198,7 @@ def daemonize_self(module, password, port, minutes, pid_file):
os.dup2(dev_null.fileno(), sys.stderr.fileno()) os.dup2(dev_null.fileno(), sys.stderr.fileno())
log("daemonizing successful") log("daemonizing successful")
class LocalSocketThread(Thread): class LocalSocketThread(Thread):
server = None server = None
terminated = False terminated = False
@ -271,6 +279,7 @@ class LocalSocketThread(Thread):
self.s.shutdown(socket.SHUT_RDWR) self.s.shutdown(socket.SHUT_RDWR)
self.s.close() self.s.close()
class ThreadWithReturnValue(Thread): class ThreadWithReturnValue(Thread):
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, Verbose=None): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, Verbose=None):
Thread.__init__(self, group, target, name, args, kwargs, Verbose) Thread.__init__(self, group, target, name, args, kwargs, Verbose)
@ -285,10 +294,12 @@ class ThreadWithReturnValue(Thread):
Thread.join(self, timeout=timeout) Thread.join(self, timeout=timeout)
return self._return return self._return
class ThreadedTCPServer(socketserver.ThreadingTCPServer): class ThreadedTCPServer(socketserver.ThreadingTCPServer):
key_list = [] key_list = []
last_event = datetime.datetime.now() last_event = datetime.datetime.now()
last_event_lock = Lock() last_event_lock = Lock()
def __init__(self, server_address, RequestHandlerClass, module, password, timeout, use_ipv6=False): def __init__(self, server_address, RequestHandlerClass, module, password, timeout, use_ipv6=False):
self.module = module self.module = module
self.key_list.append(AesKey.Read(password)) self.key_list.append(AesKey.Read(password))
@ -309,6 +320,7 @@ class ThreadedTCPServer(socketserver.ThreadingTCPServer):
self.running = False self.running = False
socketserver.ThreadingTCPServer.shutdown(self) socketserver.ThreadingTCPServer.shutdown(self)
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler): class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
# the key to use for this connection # the key to use for this connection
active_key = None active_key = None
@ -575,6 +587,7 @@ class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
self.server.module.atomic_move(out_path, final_path) self.server.module.atomic_move(out_path, final_path)
return dict() return dict()
def daemonize(module, password, port, timeout, minutes, use_ipv6, pid_file): def daemonize(module, password, port, timeout, minutes, use_ipv6, pid_file):
try: try:
daemonize_self(module, password, port, minutes, pid_file) daemonize_self(module, password, port, minutes, pid_file)
@ -640,17 +653,18 @@ def daemonize(module, password, port, timeout, minutes, use_ipv6, pid_file):
log("exception caught, exiting accelerated mode: %s\n%s" % (e, tb)) log("exception caught, exiting accelerated mode: %s\n%s" % (e, tb))
sys.exit(0) sys.exit(0)
def main(): def main():
global DEBUG_LEVEL global DEBUG_LEVEL
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(
port=dict(required=False, default=5099), port=dict(type='int', default=5099),
ipv6=dict(required=False, default=False, type='bool'), ipv6=dict(type='bool', default=False),
multi_key=dict(required=False, default=False, type='bool'), multi_key=dict(type='bool', default=False),
timeout=dict(required=False, default=300), timeout=dict(type='int', default=300),
password=dict(required=True, no_log=True), password=dict(type='str', required=True, no_log=True),
minutes=dict(required=False, default=30), minutes=dict(type='int', default=30),
debug=dict(required=False, default=0, type='int') debug=dict(type='int', default=0)
), ),
supports_check_mode=True supports_check_mode=True
) )
@ -682,9 +696,7 @@ def main():
# whether other signals can be sent # whether other signals can be sent
os.kill(daemon_pid, 0) os.kill(daemon_pid, 0)
except OSError as e: except OSError as e:
message = 'the accelerate daemon appears to be running' message = 'the accelerate daemon appears to be running as a different user that this user cannot access pid=%s' % daemon_pid
message += 'as a different user that this user cannot access'
message += 'pid=%s' % daemon_pid
if e.errno == errno.EPERM: if e.errno == errno.EPERM:
# no permissions means the pid is probably # no permissions means the pid is probably
@ -726,5 +738,6 @@ def main():
# try to start up the daemon # try to start up the daemon
daemonize(module, password, port, timeout, minutes, ipv6, pid_file) daemonize(module, password, port, timeout, minutes, ipv6, pid_file)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -84,7 +84,7 @@ def main():
module.fail_json(ansible_job_id=jid, results_file=log_path, module.fail_json(ansible_job_id=jid, results_file=log_path,
msg="Could not parse job output: %s" % data, started=1, finished=1) msg="Could not parse job output: %s" % data, started=1, finished=1)
if not 'started' in data: if 'started' not in data:
data['finished'] = 1 data['finished'] = 1
data['ansible_job_id'] = jid data['ansible_job_id'] = jid
elif 'finished' not in data: elif 'finished' not in data:

View file

@ -27,9 +27,11 @@ PY3 = sys.version_info[0] == 3
syslog.openlog('ansible-%s' % os.path.basename(__file__)) syslog.openlog('ansible-%s' % os.path.basename(__file__))
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % " ".join(sys.argv[1:])) syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % " ".join(sys.argv[1:]))
def notice(msg): def notice(msg):
syslog.syslog(syslog.LOG_NOTICE, msg) syslog.syslog(syslog.LOG_NOTICE, msg)
def daemonize_self(): def daemonize_self():
# daemonizing code: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 # daemonizing code: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012
try: try:
@ -60,6 +62,7 @@ def daemonize_self():
os.dup2(dev_null.fileno(), sys.stdout.fileno()) os.dup2(dev_null.fileno(), sys.stdout.fileno())
os.dup2(dev_null.fileno(), sys.stderr.fileno()) os.dup2(dev_null.fileno(), sys.stderr.fileno())
# NB: this function copied from module_utils/json_utils.py. Ensure any changes are propagated there. # NB: this function copied from module_utils/json_utils.py. Ensure any changes are propagated there.
# FUTURE: AnsibleModule-ify this module so it's Ansiballz-compatible and can use the module_utils copy of this function. # FUTURE: AnsibleModule-ify this module so it's Ansiballz-compatible and can use the module_utils copy of this function.
def _filter_non_json_lines(data): def _filter_non_json_lines(data):
@ -186,9 +189,6 @@ def _run_module(wrapped_cmd, jid, job_path):
os.rename(tmp_job_path, job_path) os.rename(tmp_job_path, job_path)
####################
## main ##
####################
if __name__ == '__main__': if __name__ == '__main__':
if len(sys.argv) < 5: if len(sys.argv) < 5:
@ -295,9 +295,9 @@ if __name__ == '__main__':
except Exception: except Exception:
e = sys.exc_info()[1] e = sys.exc_info()[1]
notice("error: %s"%(e)) notice("error: %s" % e)
print(json.dumps({ print(json.dumps({
"failed": True, "failed": True,
"msg" : "FATAL ERROR: %s" % str(e) "msg": "FATAL ERROR: %s" % e
})) }))
sys.exit(1) sys.exit(1)

View file

@ -483,7 +483,4 @@ lib/ansible/modules/system/systemd.py
lib/ansible/modules/system/timezone.py lib/ansible/modules/system/timezone.py
lib/ansible/modules/system/ufw.py lib/ansible/modules/system/ufw.py
lib/ansible/modules/system/user.py lib/ansible/modules/system/user.py
lib/ansible/modules/utilities/helper/_accelerate.py
lib/ansible/modules/utilities/logic/async_status.py
lib/ansible/modules/utilities/logic/async_wrapper.py
lib/ansible/playbook/base.py lib/ansible/playbook/base.py