entrypoint.py 8.66 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
import json
import logging
import os
import sys
from argparse import ArgumentParser, Namespace, FileType, RawDescriptionHelpFormatter
Daniele Venzano's avatar
Daniele Venzano committed
26
from typing import Tuple
27 28

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


36 37 38 39 40 41 42 43 44 45
def info_cmd(args_):
    """Queries the info endpoint."""
    info_api = ZoeInfoAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
    info = info_api.info()
    print("Zoe version: ", info['version'])
    print("Zoe API version: ", info['api_version'])
    print("ZApp format version: ", info['application_format_version'])
    print("Deployment name: ", info['deployment_name'])


46
def app_validate_cmd(args):
47
    """Validate an application description."""
48
    app_descr = json.load(args.jsonfile)
49
    try:
50 51 52
        app_validate(app_descr)
    except InvalidApplicationDescription as e:
        print(e)
53
    else:
54
        print("Static validation OK")
55 56 57


def app_get_cmd(args):
58
    """Extract an application description from an execution."""
59
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
60
    execution = exec_api.get(args.id)
61
    if execution is None:
62
        print("no such execution")
63
    else:
64
        json.dump(execution['description'], sys.stdout, sort_keys=True, indent=4)
65 66


67 68
def exec_list_cmd(args_):
    """List executions"""
69 70
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
    data = exec_api.list()
71
    for e in data.values():
72
        print('Execution {} (User: {}, ID: {}): {}'.format(e['name'], e['user_id'], e['id'], e['status']))
73 74 75


def exec_start_cmd(args):
76
    """Submit an execution."""
77
    app_descr = json.load(args.jsonfile)
78
    app_validate(app_descr)
79
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
80
    ret = exec_api.start(args.name, app_descr)
81 82 83 84
    print("Application scheduled successfully with ID {}, use the exec-get command to check its status".format(ret))


def exec_get_cmd(args):
85
    """Gather information about an execution."""
86
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
Daniele Venzano's avatar
Daniele Venzano committed
87
    cont_api = ZoeServiceAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
88
    execution = exec_api.get(args.id)
89 90 91 92 93
    if execution is None:
        print('Execution not found')
    else:
        print('Execution {} (ID: {})'.format(execution['name'], execution['id']))
        print('Status: {}'.format(execution['status']))
94
        if execution['status'] == 'error':
95
            print('Last error: {}'.format(execution['error_message']))
96 97 98 99 100 101 102 103 104 105 106 107 108
        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']
109
        print('Application name: {}'.format(app['name']))
110
        for c_id in execution['services']:
111
            service = cont_api.get(c_id)
112 113 114 115 116 117 118
            print('Service {} (ID: {})'.format(service['name'], service['id']))
            print(' - zoe status: {}'.format(service['status']))
            print(' - docker status: {}'.format(service['docker_status']))
            if service['docker_status'] == 'started':
                ip = service['ip_address']
                for port in service['description']['ports']:
                    print(' - {}: {}://{}:{}{}'.format(port['name'], port['protocol'], ip, port['port_number'], port['path']))
119 120 121


def exec_kill_cmd(args):
122
    """Kill an execution."""
123 124 125 126
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
    exec_api.terminate(args.id)


127
def exec_rm_cmd(args):
128
    """Delete an execution and kill it if necessary."""
129 130 131 132
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
    exec_api.delete(args.id)


133 134 135
def logs_cmd(args):
    """Retrieves and streams the logs of a service."""
    service_api = ZoeServiceAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
136 137 138 139 140 141 142 143
    try:
        for line in service_api.get_logs(args.service_id):
            if args.timestamps:
                print(line[0], line[1])
            else:
                print(line[1])
    except KeyboardInterrupt:
        print('CTRL-C detected, exiting...')
144

145 146 147 148 149 150
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'''


Daniele Venzano's avatar
Daniele Venzano committed
151
def process_arguments() -> Tuple[ArgumentParser, Namespace]:
152
    """Parse command line arguments."""
153 154 155 156 157
    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()

158 159 160
    argparser_info = subparser.add_parser('info', help="Queries the API for supported versions")
    argparser_info.set_defaults(func=info_cmd)

161 162 163
    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)
164

Francesco Pace's avatar
Francesco Pace committed
165
    argparser_exec_start = subparser.add_parser('start', help="Start an application")
166
    argparser_exec_start.add_argument('name', help="Name of the execution")
167
    argparser_exec_start.add_argument('jsonfile', type=FileType("r"), help='Application description')
168 169
    argparser_exec_start.set_defaults(func=exec_start_cmd)

170 171 172
    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)

173 174 175 176
    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)

177
    argparser_app_get = subparser.add_parser('exec-app-get', help="Retrieve an already defined application description")
178
    argparser_app_get.add_argument('id', help='The ID of the application')
179
    argparser_app_get.set_defaults(func=app_get_cmd)
180 181 182 183 184

    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)

185 186 187 188
    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)

189 190
    argparser_logs = subparser.add_parser('logs', help="Streams the service logs")
    argparser_logs.add_argument('service_id', type=int, help="Service id")
191
    argparser_logs.add_argument('-t', '--timestamps', action='store_true', help="Prefix timestamps for each line")
192 193
    argparser_logs.set_defaults(func=logs_cmd)

194 195 196 197
    return parser, parser.parse_args()


def zoe():
198
    """Main entrypoint."""
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    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)