2021-01-02 23:10:01 +00:00
|
|
|
|
2021-01-03 20:44:56 +00:00
|
|
|
import sys
|
2021-01-04 21:02:56 +00:00
|
|
|
import json
|
2021-01-03 01:07:43 +00:00
|
|
|
import aiohttp
|
2021-01-02 23:10:01 +00:00
|
|
|
from flask import Blueprint
|
|
|
|
from flask import current_app
|
|
|
|
from flask import request
|
2021-01-03 20:44:56 +00:00
|
|
|
from flask.json import jsonify
|
2021-01-02 23:10:01 +00:00
|
|
|
from werkzeug.exceptions import abort
|
|
|
|
|
2021-01-04 19:32:52 +00:00
|
|
|
from capsulflask.shared import my_exec_info_message, authorized_as_hub
|
2021-01-02 23:10:01 +00:00
|
|
|
|
2021-01-03 01:07:43 +00:00
|
|
|
bp = Blueprint("spoke", __name__, url_prefix="/spoke")
|
2021-01-02 23:10:01 +00:00
|
|
|
|
2021-01-04 19:32:52 +00:00
|
|
|
@bp.route("/heartbeat", methods=("POST",))
|
2021-01-03 01:07:43 +00:00
|
|
|
def heartbeat():
|
2021-01-04 19:32:52 +00:00
|
|
|
if authorized_as_hub(request.headers):
|
2021-01-04 01:17:30 +00:00
|
|
|
url = f"{current_app.config['HUB_URL']}/hub/heartbeat/{current_app.config['SPOKE_HOST_ID']}"
|
|
|
|
authorization_header = f"Bearer {current_app.config['SPOKE_HOST_TOKEN']}"
|
2021-02-16 05:51:59 +00:00
|
|
|
result = current_app.config['HTTP_CLIENT'].do_http_sync(url, body=None, authorization_header=authorization_header)
|
2021-01-04 01:17:30 +00:00
|
|
|
if result.status_code == -1:
|
2021-02-16 05:51:59 +00:00
|
|
|
current_app.logger.info(f"/spoke/heartbeat returned 503: hub at {url} timed out or cannot be reached")
|
2021-01-04 01:17:30 +00:00
|
|
|
return abort(503, "Service Unavailable: hub timed out or cannot be reached")
|
|
|
|
if result.status_code == 401:
|
2021-02-16 05:51:59 +00:00
|
|
|
current_app.logger.info(f"/spoke/heartbeat returned 502: hub at {url} rejected our token")
|
2021-01-04 01:17:30 +00:00
|
|
|
return abort(502, "hub rejected our token")
|
|
|
|
if result.status_code != 200:
|
2021-02-16 05:51:59 +00:00
|
|
|
current_app.logger.info(f"/spoke/heartbeat returned 502: hub at {url} returned {result.status_code}")
|
2021-01-04 01:17:30 +00:00
|
|
|
return abort(502, "Bad Gateway: hub did not return 200")
|
|
|
|
|
|
|
|
return "OK"
|
2021-01-02 23:10:01 +00:00
|
|
|
else:
|
2021-02-16 05:51:59 +00:00
|
|
|
current_app.logger.info(f"/spoke/heartbeat returned 401: invalid hub token")
|
2021-01-03 01:07:43 +00:00
|
|
|
return abort(401, "invalid hub token")
|
2021-01-02 23:10:01 +00:00
|
|
|
|
2021-01-04 21:02:56 +00:00
|
|
|
@bp.route("/operation/<int:operation_id>", methods=("POST",))
|
|
|
|
def operation_with_id(operation_id: int):
|
|
|
|
return operation_impl(operation_id)
|
|
|
|
|
2021-01-04 19:32:52 +00:00
|
|
|
@bp.route("/operation", methods=("POST",))
|
2021-01-04 21:02:56 +00:00
|
|
|
def operation_without_id():
|
|
|
|
return operation_impl(None)
|
|
|
|
|
2021-02-16 00:35:44 +00:00
|
|
|
def operation_impl(operation_id: int):
|
2021-01-04 19:32:52 +00:00
|
|
|
if authorized_as_hub(request.headers):
|
2021-01-04 21:02:56 +00:00
|
|
|
request_body_json = request.json
|
|
|
|
request_body = json.loads(request_body_json)
|
2021-01-04 23:20:03 +00:00
|
|
|
#current_app.logger.info(f"request.json: {request_body}")
|
2021-01-03 20:44:56 +00:00
|
|
|
handlers = {
|
|
|
|
"capacity_avaliable": handle_capacity_avaliable,
|
|
|
|
"get": handle_get,
|
|
|
|
"list_ids": handle_list_ids,
|
|
|
|
"create": handle_create,
|
|
|
|
"destroy": handle_destroy,
|
2021-02-17 03:13:51 +00:00
|
|
|
"vm_state_command": handle_vm_state_command,
|
2021-01-03 20:44:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
error_message = ""
|
|
|
|
types_csv = ", ".join(handlers.keys())
|
|
|
|
if isinstance(request_body, dict) and 'type' in request_body:
|
|
|
|
if request_body['type'] in handlers:
|
2021-01-03 21:19:29 +00:00
|
|
|
try:
|
2021-01-04 21:02:56 +00:00
|
|
|
return handlers[request_body['type']](operation_id, request_body)
|
2021-01-03 21:19:29 +00:00
|
|
|
except:
|
|
|
|
error_message = my_exec_info_message(sys.exc_info())
|
|
|
|
current_app.logger.error(f"unhandled exception in {request_body['type']} handler: {error_message}")
|
|
|
|
return jsonify(dict(error_message=error_message))
|
2021-01-03 20:44:56 +00:00
|
|
|
else:
|
|
|
|
error_message = f"'type' must be one of {types_csv}"
|
|
|
|
else:
|
|
|
|
error_message = "'type' json property is required"
|
|
|
|
|
|
|
|
if error_message != "":
|
2021-01-04 23:20:03 +00:00
|
|
|
current_app.logger.error(f"/hosts/operation returned 400: {error_message}")
|
2021-01-03 20:44:56 +00:00
|
|
|
return abort(400, f"bad request; {error_message}")
|
|
|
|
else:
|
2021-01-04 23:20:03 +00:00
|
|
|
current_app.logger.warning(f"/hosts/operation returned 401: invalid hub token")
|
2021-01-03 20:44:56 +00:00
|
|
|
return abort(401, "invalid hub token")
|
|
|
|
|
2021-01-04 21:02:56 +00:00
|
|
|
def handle_capacity_avaliable(operation_id, request_body):
|
2021-01-03 20:44:56 +00:00
|
|
|
if 'additional_ram_bytes' not in request_body:
|
2021-01-04 23:20:03 +00:00
|
|
|
current_app.logger.error(f"/hosts/operation returned 400: additional_ram_bytes is required for capacity_avaliable")
|
2021-01-03 20:44:56 +00:00
|
|
|
return abort(400, f"bad request; additional_ram_bytes is required for capacity_avaliable")
|
|
|
|
|
|
|
|
has_capacity = current_app.config['SPOKE_MODEL'].capacity_avaliable(request_body['additional_ram_bytes'])
|
|
|
|
return jsonify(dict(assignment_status="assigned", capacity_avaliable=has_capacity))
|
|
|
|
|
2021-01-04 21:02:56 +00:00
|
|
|
def handle_get(operation_id, request_body):
|
2021-01-03 20:44:56 +00:00
|
|
|
if 'id' not in request_body:
|
2021-01-04 23:20:03 +00:00
|
|
|
current_app.logger.error(f"/hosts/operation returned 400: id is required for get")
|
2021-01-03 20:44:56 +00:00
|
|
|
return abort(400, f"bad request; id is required for get")
|
|
|
|
|
2021-02-16 00:16:15 +00:00
|
|
|
vm = current_app.config['SPOKE_MODEL'].get(request_body['id'], request_body['get_ssh_host_keys'])
|
2021-02-17 03:13:51 +00:00
|
|
|
if vm is None:
|
|
|
|
return jsonify(dict(assignment_status="assigned"))
|
2021-01-03 20:44:56 +00:00
|
|
|
|
2021-02-18 02:50:17 +00:00
|
|
|
return jsonify(dict(assignment_status="assigned", id=vm.id, host=vm.host, state=vm.state, ipv4=vm.ipv4, ipv6=vm.ipv6, ssh_host_keys=vm.ssh_host_keys))
|
2021-01-03 20:44:56 +00:00
|
|
|
|
2021-01-04 21:02:56 +00:00
|
|
|
def handle_list_ids(operation_id, request_body):
|
2021-01-03 20:44:56 +00:00
|
|
|
return jsonify(dict(assignment_status="assigned", ids=current_app.config['SPOKE_MODEL'].list_ids()))
|
|
|
|
|
2021-01-04 21:02:56 +00:00
|
|
|
def handle_create(operation_id, request_body):
|
|
|
|
if not operation_id:
|
2021-01-04 23:20:03 +00:00
|
|
|
current_app.logger.error(f"/hosts/operation returned 400: operation_id is required for create ")
|
2021-01-04 21:02:56 +00:00
|
|
|
return abort(400, f"bad request; operation_id is required. try POST /spoke/operation/<id>")
|
|
|
|
|
2021-02-16 01:44:26 +00:00
|
|
|
parameters = ["email", "id", "template_image_file_name", "vcpus", "memory_mb", "ssh_authorized_keys"]
|
2021-01-03 20:44:56 +00:00
|
|
|
error_message = ""
|
|
|
|
for parameter in parameters:
|
|
|
|
if parameter not in request_body:
|
|
|
|
error_message = f"{error_message}\n{parameter} is required for create"
|
|
|
|
|
|
|
|
if error_message != "":
|
2021-01-04 23:20:03 +00:00
|
|
|
current_app.logger.error(f"/hosts/operation returned 400: {error_message}")
|
2021-01-03 20:44:56 +00:00
|
|
|
return abort(400, f"bad request; {error_message}")
|
|
|
|
|
2021-01-04 01:17:30 +00:00
|
|
|
# only one host should create the vm, so we first race to assign this create operation to ourselves.
|
|
|
|
# only one host will win this race
|
|
|
|
authorization_header = f"Bearer {current_app.config['SPOKE_HOST_TOKEN']}"
|
2021-01-04 21:02:56 +00:00
|
|
|
url = f"{current_app.config['HUB_URL']}/hub/claim-operation/{operation_id}/{current_app.config['SPOKE_HOST_ID']}"
|
2021-02-16 05:51:59 +00:00
|
|
|
result = current_app.config['HTTP_CLIENT'].do_http_sync(url, body=None, authorization_header=authorization_header)
|
2021-01-04 01:17:30 +00:00
|
|
|
|
|
|
|
assignment_status = ""
|
|
|
|
if result.status_code == 200:
|
|
|
|
assignment_status = "assigned"
|
|
|
|
elif result.status_code == 409:
|
|
|
|
assignment_status = "assigned_to_other_host"
|
|
|
|
else:
|
2021-01-04 23:20:03 +00:00
|
|
|
current_app.logger.error(f"{url} returned {result.status_code}: {result.body}")
|
2021-01-04 01:17:30 +00:00
|
|
|
return abort(503, f"hub did not cleanly handle our request to claim the create operation")
|
|
|
|
|
2021-01-03 20:44:56 +00:00
|
|
|
if assignment_status == "assigned":
|
|
|
|
try:
|
|
|
|
current_app.config['SPOKE_MODEL'].create(
|
|
|
|
email=request_body['email'],
|
|
|
|
id=request_body['id'],
|
|
|
|
template_image_file_name=request_body['template_image_file_name'],
|
|
|
|
vcpus=request_body['vcpus'],
|
|
|
|
memory_mb=request_body['memory_mb'],
|
2021-02-16 01:44:26 +00:00
|
|
|
ssh_authorized_keys=request_body['ssh_authorized_keys'],
|
2021-01-03 20:44:56 +00:00
|
|
|
)
|
|
|
|
except:
|
|
|
|
error_message = my_exec_info_message(sys.exc_info())
|
2021-02-21 20:26:00 +00:00
|
|
|
params = f"email='{request_body['email'] if 'email' in request_body else 'KeyError'}', "
|
|
|
|
params= f"{params} id='{request_body['id'] if 'id' in request_body else 'KeyError'}', "
|
|
|
|
params= f"{params} template_image_file_name='{request_body['template_image_file_name'] if 'template_image_file_name' in request_body else 'KeyError'}', "
|
|
|
|
params= f"{params} vcpus='{request_body['vcpus'] if 'vcpus' in request_body else 'KeyError'}', "
|
|
|
|
params= f"{params} memory_mb='{request_body['memory_mb'] if 'memory_mb' in request_body else 'KeyError'}', "
|
|
|
|
params= f"{params} ssh_authorized_keys='{request_body['ssh_authorized_keys'] if 'ssh_authorized_keys' in request_body else 'KeyError'}', "
|
2021-01-04 01:17:30 +00:00
|
|
|
current_app.logger.error(f"spoke_model.create({params}) failed: {error_message}")
|
2021-01-03 20:44:56 +00:00
|
|
|
return jsonify(dict(assignment_status=assignment_status, error_message=error_message))
|
|
|
|
|
|
|
|
return jsonify(dict(assignment_status=assignment_status))
|
|
|
|
|
2021-01-04 21:02:56 +00:00
|
|
|
def handle_destroy(operation_id, request_body):
|
2021-01-03 20:44:56 +00:00
|
|
|
if 'id' not in request_body:
|
2021-01-04 23:20:03 +00:00
|
|
|
current_app.logger.error(f"/hosts/operation returned 400: id is required for destroy")
|
2021-01-03 20:44:56 +00:00
|
|
|
return abort(400, f"bad request; id is required for destroy")
|
|
|
|
|
|
|
|
if 'email' not in request_body:
|
2021-01-04 23:20:03 +00:00
|
|
|
current_app.logger.error(f"/hosts/operation returned 400: email is required for destroy")
|
2021-01-03 20:44:56 +00:00
|
|
|
return abort(400, f"bad request; email is required for destroy")
|
|
|
|
|
|
|
|
try:
|
|
|
|
current_app.config['SPOKE_MODEL'].destroy(id=request_body['id'], email=request_body['email'])
|
|
|
|
except:
|
|
|
|
error_message = my_exec_info_message(sys.exc_info())
|
2021-02-21 20:26:00 +00:00
|
|
|
params = f"email='{request_body['email'] if 'email' in request_body else 'KeyError'}', "
|
|
|
|
params= f"{params} id='{request_body['id'] if 'id' in request_body else 'KeyError'}', "
|
|
|
|
current_app.logger.error(f"current_app.config['SPOKE_MODEL'].destroy({params}) failed: {error_message}")
|
2021-01-03 20:44:56 +00:00
|
|
|
return jsonify(dict(assignment_status="assigned", status="error", error_message=error_message))
|
|
|
|
|
2021-02-17 03:13:51 +00:00
|
|
|
return jsonify(dict(assignment_status="assigned", status="success"))
|
|
|
|
|
|
|
|
|
|
|
|
def handle_vm_state_command(operation_id, request_body):
|
|
|
|
|
|
|
|
required_properties = ['id', 'email', 'command']
|
|
|
|
for required_property in required_properties:
|
|
|
|
if required_property not in request_body:
|
|
|
|
current_app.logger.error(f"/hosts/operation returned 400: {required_property} is required for vm_state_command")
|
|
|
|
return abort(400, f"bad request; {required_property} is required for vm_state_command")
|
|
|
|
|
|
|
|
if request_body['command'] not in ["stop", "force-stop", "start", "restart"]:
|
|
|
|
current_app.logger.error(f"/hosts/operation returned 400: command ({request_body['command']}) must be one of stop, force-stop, start, or restart")
|
|
|
|
return abort(400, f"bad request; command ({request_body['command']}) must be one of stop, force-stop, start, or restart")
|
|
|
|
|
|
|
|
try:
|
|
|
|
current_app.config['SPOKE_MODEL'].vm_state_command(id=request_body['id'], email=request_body['email'], command=request_body['command'])
|
|
|
|
except:
|
|
|
|
error_message = my_exec_info_message(sys.exc_info())
|
2021-02-21 20:26:00 +00:00
|
|
|
params = f"email='{request_body['email'] if 'email' in request_body else 'KeyError'}', "
|
|
|
|
params= f"{params} id='{request_body['id'] if 'id' in request_body else 'KeyError'}', "
|
|
|
|
params= f"{params} command='{request_body['command'] if 'command' in request_body else 'KeyError'}', "
|
|
|
|
current_app.logger.error(f"current_app.config['SPOKE_MODEL'].vm_state_command({params}) failed: {error_message}")
|
2021-02-17 03:13:51 +00:00
|
|
|
return jsonify(dict(assignment_status="assigned", status="error", error_message=error_message))
|
|
|
|
|
2021-01-03 20:44:56 +00:00
|
|
|
return jsonify(dict(assignment_status="assigned", status="success"))
|