from load.projects.cloud.cloud_helper.metadata_compute import get_instance_attributes
from load.projects.cloud.env_config import load_config
from load.projects.cloud.loadtesting.config import ENV_CONFIG, \
    HELPER_DEFAULT_CONFIG_PATH, HELPER_CONFIG_PATH_ATTR, SERVER_DEFAULT_CONFIG_PATH, SERVER_CONFIG_PATH_ATTR
from load.projects.cloud.loadtesting.server.admin import adminized
from load.projects.cloud.loadtesting.server.admin.healthcheck import healthcheck
from load.projects.cloud.loadtesting.server.api.server import API


def serve():
    attrs = get_instance_attributes()
    for config_path in [
            attrs.get(HELPER_CONFIG_PATH_ATTR, HELPER_DEFAULT_CONFIG_PATH),
            attrs.get(SERVER_CONFIG_PATH_ATTR, SERVER_DEFAULT_CONFIG_PATH)]:
        load_config(config_path)
    secure_port = str(int(ENV_CONFIG.SERVER_PORT) + 1)

    with API(insecure_port=ENV_CONFIG.SERVER_PORT, secure_port=secure_port) as api:
        with adminized(server_to_follow=api.server, logging_controller=api.logging_controller):
            with healthcheck(api.server, ENV_CONFIG.HEALTHCHECK_PORT):
                api.server.wait_for_termination()


def main():
    serve()
