[Dockerapi] Some minor changes

This commit is contained in:
andryyy 2018-10-25 22:34:31 +02:00
parent 53333f3b4d
commit 23e3bdfe5a

View File

@ -74,7 +74,6 @@ class container_post(Resource):
if request.json['cmd'] == 'mailq':
if 'items' in request.json:
# Check if queue id is valid
r = re.compile("^[0-9a-fA-F]+$")
filtered_qids = filter(r.match, request.json['items'])
if filtered_qids:
@ -84,10 +83,7 @@ class container_post(Resource):
try:
for container in docker_client.containers.list(filters={"id": container_id}):
postsuper_r = container.exec_run(["/bin/bash", "-c", "/usr/sbin/postsuper " + sanitized_string])
if postsuper_r.exit_code == 0:
return jsonify(type='success', msg='command completed successfully')
else:
return jsonify(type='danger', msg=str(postsuper_r.output))
return exec_run_handler('generic', postsuper_r)
except Exception as e:
return jsonify(type='danger', msg=str(e))
if request.json['task'] == 'hold':
@ -96,10 +92,7 @@ class container_post(Resource):
try:
for container in docker_client.containers.list(filters={"id": container_id}):
postsuper_r = container.exec_run(["/bin/bash", "-c", "/usr/sbin/postsuper " + sanitized_string])
if postsuper_r.exit_code == 0:
return jsonify(type='success', msg='command completed successfully')
else:
return jsonify(type='danger', msg=str(postsuper_r.output))
return exec_run_handler('generic', postsuper_r)
except Exception as e:
return jsonify(type='danger', msg=str(e))
if request.json['task'] == 'unhold':
@ -108,10 +101,7 @@ class container_post(Resource):
try:
for container in docker_client.containers.list(filters={"id": container_id}):
postsuper_r = container.exec_run(["/bin/bash", "-c", "/usr/sbin/postsuper " + sanitized_string])
if postsuper_r.exit_code == 0:
return jsonify(type='success', msg='command completed successfully')
else:
return jsonify(type='danger', msg=str(postsuper_r.output))
return exec_run_handler('generic', postsuper_r)
except Exception as e:
return jsonify(type='danger', msg=str(e))
if request.json['task'] == 'deliver':
@ -128,31 +118,21 @@ class container_post(Resource):
try:
for container in docker_client.containers.list(filters={"id": container_id}):
mailq_return = container.exec_run(["/usr/sbin/postqueue", "-j"], user='postfix')
if mailq_return.exit_code == 0:
# We want plain text content from Postfix
r = Response(response=mailq_return.output, status=200, mimetype="text/plain")
r.headers["Content-Type"] = "text/plain; charset=utf-8"
return r
return exec_run_handler('utf8_text_only', mailq_return)
except Exception as e:
return jsonify(type='danger', msg=str(e))
elif request.json['task'] == 'flush':
try:
for container in docker_client.containers.list(filters={"id": container_id}):
postqueue_r = container.exec_run(["/usr/sbin/postqueue", "-f"], user='postfix')
if postqueue_r.exit_code == 0:
return jsonify(type='success', msg='command completed successfully')
else:
return jsonify(type='danger', msg=str(postqueue_r.output))
return exec_run_handler('generic', postqueue_r)
except Exception as e:
return jsonify(type='danger', msg=str(e))
elif request.json['task'] == 'super_delete':
try:
for container in docker_client.containers.list(filters={"id": container_id}):
postsuper_r = container.exec_run(["/usr/sbin/postsuper", "-d", "ALL"])
if postsuper_r.exit_code == 0:
return jsonify(type='success', msg='command completed successfully')
else:
return jsonify(type='danger', msg=str(postsuper_r.output))
return exec_run_handler('generic', postsuper_r)
except Exception as e:
return jsonify(type='danger', msg=str(e))
@ -161,9 +141,7 @@ class container_post(Resource):
if 'dir' in request.json:
try:
for container in docker_client.containers.list(filters={"id": container_id}):
# Should be changed to be able to validate a path
directory = re.sub('[^0-9a-zA-Z/]+', '', request.json['dir'])
df_return = container.exec_run(["/bin/bash", "-c", "/bin/df -H " + directory + " | /usr/bin/tail -n1 | /usr/bin/tr -s [:blank:] | /usr/bin/tr ' ' ','"], user='nobody')
df_return = container.exec_run(["/bin/bash", "-c", "/bin/df -H '" + request.json['dir'].replace("'", "'\\''") + "' | /usr/bin/tail -n1 | /usr/bin/tr -s [:blank:] | /usr/bin/tr ' ' ','"], user='nobody')
if df_return.exit_code == 0:
return df_return.output.rstrip()
else:
@ -175,34 +153,22 @@ class container_post(Resource):
if request.json['task'] == 'dovecot':
try:
for container in docker_client.containers.list(filters={"id": container_id}):
# Should be changed to be able to validate a path
reload_return = container.exec_run(["/bin/bash", "-c", "/usr/local/sbin/dovecot reload"])
if reload_return.exit_code == 0:
return jsonify(type='success', msg='command completed successfully')
else:
return jsonify(type='danger', msg='command failed: ' + reload_return.output)
return exec_run_handler('generic', reload_return)
except Exception as e:
return jsonify(type='danger', msg=str(e))
if request.json['task'] == 'postfix':
try:
for container in docker_client.containers.list(filters={"id": container_id}):
# Should be changed to be able to validate a path
reload_return = container.exec_run(["/bin/bash", "-c", "/usr/sbin/postfix reload"])
if reload_return.exit_code == 0:
return jsonify(type='success', msg='command completed successfully')
else:
return jsonify(type='danger', msg='command failed: ' + reload_return.output)
return exec_run_handler('generic', reload_return)
except Exception as e:
return jsonify(type='danger', msg=str(e))
if request.json['task'] == 'nginx':
try:
for container in docker_client.containers.list(filters={"id": container_id}):
# Should be changed to be able to validate a path
reload_return = container.exec_run(["/bin/sh", "-c", "/usr/sbin/nginx -s reload"])
if reload_return.exit_code == 0:
return jsonify(type='success', msg='command completed successfully')
else:
return jsonify(type='danger', msg='command failed: ' + reload_return.output)
return exec_run_handler('generic', reload_return)
except Exception as e:
return jsonify(type='danger', msg=str(e))
@ -212,9 +178,7 @@ class container_post(Resource):
try:
for container in docker_client.containers.list(filters={"id": container_id}):
sieve_return = container.exec_run(["/bin/bash", "-c", "/usr/local/bin/doveadm sieve list -u '" + request.json['username'].replace("'", "'\\''") + "'"])
r = Response(response=sieve_return.output, status=200, mimetype="text/plain")
r.headers["Content-Type"] = "text/plain; charset=utf-8"
return r
return exec_run_handler('utf8_text_only', sieve_return)
except Exception as e:
return jsonify(type='danger', msg=str(e))
elif request.json['task'] == 'print':
@ -222,43 +186,10 @@ class container_post(Resource):
try:
for container in docker_client.containers.list(filters={"id": container_id}):
sieve_return = container.exec_run(["/bin/bash", "-c", "/usr/local/bin/doveadm sieve get -u '" + request.json['username'].replace("'", "'\\''") + "' '" + request.json['script_name'].replace("'", "'\\''") + "'"])
r = Response(response=sieve_return.output, status=200, mimetype="text/plain")
r.headers["Content-Type"] = "text/plain; charset=utf-8"
return r
return exec_run_handler('utf8_text_only', sieve_return)
except Exception as e:
return jsonify(type='danger', msg=str(e))
# elif request.json['cmd'] == 'mail_crypt_generate' and request.json['username'] and request.json['old_password'] and request.json['new_password']:
# try:
# for container in docker_client.containers.list(filters={"id": container_id}):
# # create if missing
# crypto_generate = container.exec_run(["/bin/bash", "-c", "/usr/local/bin/doveadm mailbox cryptokey generate -u '" + request.json['username'].replace("'", "'\\''") + "' -URf"], user='vmail')
# if crypto_generate.exit_code == 0:
# # open a shell, bind stdin and return socket
# cryptokey_shell = container.exec_run(["/bin/bash"], stdin=True, socket=True, user='vmail')
# # command to be piped to shell
# cryptokey_cmd = "/usr/local/bin/doveadm mailbox cryptokey password -u '" + request.json['username'].replace("'", "'\\''") + "' -n '" + request.json['new_password'].replace("'", "'\\''") + "' -o '" + request.json['old_password'].replace("'", "'\\''") + "'\n"
# # socket is .output
# cryptokey_socket = cryptokey_shell.output;
# try :
# # send command utf-8 encoded
# cryptokey_socket.sendall(cryptokey_cmd.encode('utf-8'))
# # we won't send more data than this
# cryptokey_socket.shutdown(socket.SHUT_WR)
# except socket.error:
# # exit on socket error
# return jsonify(type='danger', msg=str('socket error'))
# # read response
# cryptokey_response = recv_socket_data(cryptokey_socket)
# crypto_error = re.search('dcrypt_key_load_private.+failed.+error', cryptokey_response)
# if crypto_error is not None:
# return jsonify(type='danger', msg=str("dcrypt_key_load_private error"))
# return jsonify(type='success', msg=str("key pair generated"))
# else:
# return jsonify(type='danger', msg=str(crypto_generate.output))
# except Exception as e:
# return jsonify(type='danger', msg=str(e))
elif request.json['cmd'] == 'maildir':
if request.json['task'] == 'cleanup':
if 'maildir' in request.json:
@ -266,10 +197,7 @@ class container_post(Resource):
for container in docker_client.containers.list(filters={"id": container_id}):
sane_name = re.sub(r'\W+', '', request.json['maildir'])
maildir_cleanup = container.exec_run(["/bin/bash", "-c", "if [[ -d '/var/vmail/" + request.json['maildir'].replace("'", "'\\''") + "' ]]; then /bin/mv '/var/vmail/" + request.json['maildir'].replace("'", "'\\''") + "' '/var/vmail/_garbage/" + str(int(time.time())) + "_" + sane_name + "'; fi"], user='vmail')
if maildir_cleanup.exit_code == 0:
return jsonify(type='success', msg=str("moved to garbage"))
else:
return jsonify(type='danger', msg=str(maildir_cleanup.output))
return exec_run_handler('generic', maildir_cleanup)
except Exception as e:
return jsonify(type='danger', msg=str(e))
@ -303,18 +231,6 @@ class container_post(Resource):
return jsonify(type='danger', msg='command did not complete')
except Exception as e:
return jsonify(type='danger', msg=str(e))
# elif request.json['cmd'] == 'mailman':
# if request.json['task'] == 'password':
# if request.json['email'] and request.json['passwd']:
# try:
# for container in docker_client.containers.list(filters={"id": container_id}):
# add_su = container.exec_run(["/bin/bash", "-c", "/opt/mm_web/add_su.py '" + request.json['passwd'].replace("'", "'\\''") + "' '" + request.json['email'].replace("'", "'\\''") + "'"], user='mailman')
# if add_su.exit_code == 0:
# return jsonify(type='success', msg='command completed successfully')
# else:
# return jsonify(type='danger', msg='command did not complete, exit code was ' + int(add_su.exit_code))
# except Exception as e:
# return jsonify(type='danger', msg=str(e))
else:
return jsonify(type='danger', msg='Unknown command')
@ -369,7 +285,21 @@ def recv_socket_data(c_socket, timeout=10):
pass
return ''.join(total_data)
def exec_run_handler(type, output):
if type == 'generic':
if output.exit_code == 0:
return jsonify(type='success', msg='command completed successfully')
else:
return jsonify(type='danger', msg='command failed: ' + output.output)
if type == 'utf8_text_only':
r = Response(response=output.output, status=200, mimetype="text/plain")
r.headers["Content-Type"] = "text/plain; charset=utf-8"
return r
def create_self_signed_cert():
success = False
while not success:
try:
pkey = crypto.PKey()
pkey.generate_key(crypto.TYPE_RSA, 2048)
cert = crypto.X509()
@ -387,6 +317,14 @@ def create_self_signed_cert():
handle.write(cert)
with os.fdopen(os.open('/key.pem', os.O_WRONLY | os.O_CREAT, 0o600), 'w') as handle:
handle.write(pkey)
success = True
except:
time.sleep(1)
try:
os.remove('/cert.pem')
os.remove('/key.pem')
except OSError:
pass
api.add_resource(containers_get, '/containers/json')
api.add_resource(container_get, '/containers/<string:container_id>/json')