entrypoint.py 8.64 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
# 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
"""

import json
import logging
import os
import sys
from argparse import ArgumentParser, Namespace, FileType, RawDescriptionHelpFormatter
from pprint import pprint

from zoe_cmd import utils
28
from zoe_lib.users import ZoeUserAPI
Daniele Venzano's avatar
Daniele Venzano committed
29
from zoe_lib.services import ZoeServiceAPI
30
from zoe_lib.exceptions import ZoeAPIException, InvalidApplicationDescription
31 32
from zoe_lib.executions import ZoeExecutionsAPI
from zoe_lib.query import ZoeQueryAPI
33
from zoe_lib.applications import app_validate
34 35 36 37


def stats_cmd(_):
    api = ZoeQueryAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
38
    stats = api.query('stats_swarm')
39 40 41 42
    pprint(stats)


def user_new_cmd(args):
43
    api = ZoeUserAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
44 45 46 47 48 49
    name = args.name
    password = args.password
    role = args.role
    if role not in ['admin', 'user', 'guest']:
        print("Role must be one of admin, user, guest)")
        return
50
    try:
51
        api.create(name, password, role)
52 53
    except ZoeAPIException as e:
        print('Error creating user: {}'.format(e))
54 55 56


def user_get_cmd(args):
57 58
    api = ZoeUserAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
    user = api.get(args.name)
59
    if user is None:
60 61 62 63 64 65 66 67
        print('No such user')
    else:
        print('User: {}'.format(user['name']))
        print('Role: {}'.format(user['role']))
        print('Gateway URLs: {}'.format(user['gateway_urls']))


def user_delete_cmd(args):
68 69
    api = ZoeUserAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
    api.delete(args.name)
70 71 72


def user_list_cmd(_):
73 74
    api = ZoeQueryAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
    users = api.query('user')
75
    for user in users:
76
        print('<- User {} ->'.format(user['name']))
77 78 79 80
        print('Role: {}'.format(user['role']))
        print('Gateway URLs: {}'.format(user['gateway_urls']))


81 82
def app_validate_cmd(args):
    app_descr = json.load(args.jsonfile)
83
    try:
84 85 86
        app_validate(app_descr)
    except InvalidApplicationDescription as e:
        print(e)
87
    else:
88
        print("Static validation OK")
89 90 91 92


def app_get_cmd(args):
    api_query = ZoeQueryAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
93
    data = api_query.query('execution', name=args.name)
94
    if len(data) == 0:
95
        print("no such execution")
96
    else:
97 98
        execution = data[0]
        json.dump(execution['application'], sys.stdout, sort_keys=True, indent=4)
99 100 101 102 103 104


def exec_list_cmd(_):
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
    data = exec_api.list()
    for e in data:
105
        print('Execution {} (User: {}, ID: {}): {}'.format(e['name'], e['owner'], e['id'], e['status']))
106 107 108


def exec_start_cmd(args):
109
    app_descr = json.load(args.jsonfile)
110
    app_validate(app_descr)
111
    exec_api = ZoeExecutionsAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
112
    ret = exec_api.execution_start(args.name, app_descr)
113 114 115 116 117
    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
118
    cont_api = ZoeServiceAPI(utils.zoe_url(), utils.zoe_user(), utils.zoe_pass())
119 120 121 122 123 124
    execution = exec_api.execution_get(args.id)
    if execution is None:
        print('Execution not found')
    else:
        print('Execution {} (ID: {})'.format(execution['name'], execution['id']))
        print('Status: {}'.format(execution['status']))
125 126
        if execution['error'] is not None:
            print('Last error: {}'.format(execution['error']))
127 128 129
        print('Time started: {}'.format(execution['time_started']))
        print('Time scheduled: {}'.format(execution['time_scheduled']))
        print('Time finished: {}'.format(execution['time_finished']))
130
        app = execution['application']
131
        print('Application name: {}'.format(app['name']))
132
        for c_id in execution['services']:
133 134
            c = cont_api.get(c_id)
            ip = list(c['ip_address'].values())[0]  # FIXME how to decide which network is the right one?
135
            print('Service {} (ID: {})'.format(c['name'], c['id']))
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
            for p in c['ports']:
                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)


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()

    argparser_stats = subparser.add_parser('stats', help="Show the platform statistics")
    argparser_stats.set_defaults(func=stats_cmd)

    argparser_user_new = subparser.add_parser('user-new', help="Create a new user")
    argparser_user_new.add_argument('--name', help="User name")
    argparser_user_new.add_argument('--password', help="Password")
    argparser_user_new.add_argument('--role', help="Role (one of admin, user, guest)")
    argparser_user_new.set_defaults(func=user_new_cmd)

    argparser_user_get = subparser.add_parser('user-get', help="Retrieve information about a user")
    argparser_user_get.add_argument('name', help="User name")
    argparser_user_get.set_defaults(func=user_get_cmd)

    argparser_user_delete = subparser.add_parser('user-rm', help="Removes a user from the system")
    argparser_user_delete.add_argument('name', help="User name")
    argparser_user_delete.set_defaults(func=user_delete_cmd)

174
    argparser_user_list = subparser.add_parser('user-ls', help='Lists all users defined in the system')
175 176
    argparser_user_list.set_defaults(func=user_list_cmd)

177 178 179
    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)
180

Francesco Pace's avatar
Francesco Pace committed
181
    argparser_exec_start = subparser.add_parser('start', help="Start an application")
182
    argparser_exec_start.add_argument('name', help="Name of the execution")
183
    argparser_exec_start.add_argument('jsonfile', type=FileType("r"), help='Application description')
184 185
    argparser_exec_start.set_defaults(func=exec_start_cmd)

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

189 190 191 192
    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)

193 194 195
    argparser_app_get = subparser.add_parser('exec-app-get', help="Retrieve an already defined application description")
    argparser_app_get.add_argument('name', help='The name of the application')
    argparser_app_get.set_defaults(func=app_get_cmd)
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

    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)

    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)