entrypoint.py 6.74 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright (c) 2016, Daniele Venzano
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
This module contains the entrypoint for the commandline Zoe client
"""

20
import datetime
21 22 23 24 25 26 27 28
import json
import logging
import os
import sys
from argparse import ArgumentParser, Namespace, FileType, RawDescriptionHelpFormatter
from pprint import pprint

from zoe_cmd import utils
Daniele Venzano's avatar
Daniele Venzano committed
29
from zoe_lib.services import ZoeServiceAPI
30
from zoe_lib.exceptions import ZoeAPIException, InvalidApplicationDescription
31
from zoe_lib.executions import ZoeExecutionsAPI
32
from zoe_lib.applications import app_validate
33 34


35 36
def app_validate_cmd(args):
    app_descr = json.load(args.jsonfile)
37
    try:
38 39 40
        app_validate(app_descr)
    except InvalidApplicationDescription as e:
        print(e)
41
    else:
42
        print("Static validation OK")
43 44 45


def app_get_cmd(args):
46
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
47
    execution = exec_api.get(args.id)
48
    if execution is None:
49
        print("no such execution")
50
    else:
51
        json.dump(execution['description'], sys.stdout, sort_keys=True, indent=4)
52 53 54 55 56 57


def exec_list_cmd(_):
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
    data = exec_api.list()
    for e in data:
58
        print('Execution {} (User: {}, ID: {}): {}'.format(e['name'], e['user_id'], e['id'], e['status']))
59 60 61


def exec_start_cmd(args):
62
    app_descr = json.load(args.jsonfile)
63
    app_validate(app_descr)
64
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
65
    ret = exec_api.start(args.name, app_descr)
66 67 68 69 70
    print("Application scheduled successfully with ID {}, use the exec-get command to check its status".format(ret))


def exec_get_cmd(args):
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
Daniele Venzano's avatar
Daniele Venzano committed
71
    cont_api = ZoeServiceAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
72
    execution = exec_api.get(args.id)
73 74 75 76 77
    if execution is None:
        print('Execution not found')
    else:
        print('Execution {} (ID: {})'.format(execution['name'], execution['id']))
        print('Status: {}'.format(execution['status']))
78
        if execution['status'] == 'error':
79
            print('Last error: {}'.format(execution['error']))
80 81 82 83 84 85 86 87 88 89 90 91 92
        print('Time submit: {}'.format(datetime.datetime.fromtimestamp(execution['time_submit'])))

        if execution['time_start'] is None:
            print('Time start: {}'.format('not yet'))
        else:
            print('Time start: {}'.format(datetime.datetime.fromtimestamp(execution['time_start'])))

        if execution['time_end'] is None:
            print('Time end: {}'.format('not yet'))
        else:
            print('Time end: {}'.format(datetime.datetime.fromtimestamp(execution['time_end'])))

        app = execution['description']
93
        print('Application name: {}'.format(app['name']))
94
        for c_id in execution['services']:
95
            c = cont_api.get(c_id)
96 97 98
            ip = c['ip_address']
            print('Service {} (ID: {}, {})'.format(c['name'], c['id'], c['status']))
            for p in c['description']['ports']:
99 100 101 102 103 104 105 106
                print(' - {}: {}://{}:{}{}'.format(p['name'], p['protocol'], ip, p['port_number'], p['path']))


def exec_kill_cmd(args):
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
    exec_api.terminate(args.id)


107 108 109 110 111
def exec_rm_cmd(args):
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
    exec_api.delete(args.id)


112 113 114 115 116 117 118 119 120 121 122 123
ENV_HELP_TEXT = '''To use this tool you need also to define three environment variables:
ZOE_URL: point to the URL of the Zoe Scheduler (ex.: http://localhost:5000/
ZOE_USER: the username used for authentication
ZOE_PASS: the password used for authentication'''


def process_arguments() -> Namespace:
    parser = ArgumentParser(description="Zoe command-line client", epilog=ENV_HELP_TEXT, formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument('--debug', action='store_true', help='Enable debug output')

    subparser = parser.add_subparsers()

124 125 126
    argparser_app_validate = subparser.add_parser('app-validate', help='Validate an application description')
    argparser_app_validate.add_argument('jsonfile', type=FileType("r"), help='Application description')
    argparser_app_validate.set_defaults(func=app_validate_cmd)
127

Francesco Pace's avatar
Francesco Pace committed
128
    argparser_exec_start = subparser.add_parser('start', help="Start an application")
129
    argparser_exec_start.add_argument('name', help="Name of the execution")
130
    argparser_exec_start.add_argument('jsonfile', type=FileType("r"), help='Application description')
131 132
    argparser_exec_start.set_defaults(func=exec_start_cmd)

133 134 135
    argparser_app_list = subparser.add_parser('exec-ls', help="List all executions for the calling user")
    argparser_app_list.set_defaults(func=exec_list_cmd)

136 137 138 139
    argparser_execution_get = subparser.add_parser('exec-get', help="Get execution status")
    argparser_execution_get.add_argument('id', type=int, help="Execution id")
    argparser_execution_get.set_defaults(func=exec_get_cmd)

140
    argparser_app_get = subparser.add_parser('exec-app-get', help="Retrieve an already defined application description")
141
    argparser_app_get.add_argument('id', help='The ID of the application')
142
    argparser_app_get.set_defaults(func=app_get_cmd)
143 144 145 146 147

    argparser_execution_kill = subparser.add_parser('terminate', help="Terminates an execution")
    argparser_execution_kill.add_argument('id', type=int, help="Execution id")
    argparser_execution_kill.set_defaults(func=exec_kill_cmd)

148 149 150 151
    argparser_execution_kill = subparser.add_parser('exec-rm', help="Deletes an execution")
    argparser_execution_kill.add_argument('id', type=int, help="Execution id")
    argparser_execution_kill.set_defaults(func=exec_rm_cmd)

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    return parser, parser.parse_args()


def zoe():
    parser, args = process_arguments()
    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)
    logging.getLogger("requests").setLevel(logging.WARNING)

    if not hasattr(args, "func"):
        parser.print_help()
        return

    if 'ZOE_URL' not in os.environ or 'ZOE_USER' not in os.environ or 'ZOE_PASS' not in os.environ:
        parser.print_help()
        return

    try:
        args.func(args)
    except ZoeAPIException as e:
        print(e.message)
    sys.exit(0)