chi-lease.py 4.28 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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
#!/usr/bin/env python

import argparse
import datetime
import json
import logging
import os

import os_client_config
from blazarclient import client as blazar_client
import keystoneauth1


def get_client(cloud=None):
    """Retrieve a client to blazar based on clouds.yaml config."""
    config = os_client_config.OpenStackConfig()
    cloud_config = config.get_one(cloud)
    session = cloud_config.get_session()

    # blazar acces
    return blazar_client.Client(1, session=session, service_type='reservation')


def do_create(argv):
    """Create a lease using <name>, with <size> nodes, starting now."""
    client = get_client(argv.cloud)
    name = argv.name
    node_count = int(argv.size)

    # start the lease now
    start_time = datetime.datetime.utcnow()
    end_time = start_time + datetime.timedelta(hours=argv.length)

    # resource properties
    props = ['=', '$node_type', 'compute_haswell']
    resources = {'min': node_count,
                 'max': node_count,
                 'resource_type': 'physical:host',
                 'hypervisor_properties': "",
                 'resource_properties': props,
                 }
    resources = {k: v if isinstance(v, str) else json.dumps(v)
                 for k, v in resources.items()}

    # put everything into blazar arguments
    args = {'name': name,
            'start': start_time.isoformat(' ', 'minutes'),
            'end': end_time.isoformat(' ', 'minutes'),
            'events': [],
            'reservations': [resources],
            }
    try:
        resp = client.lease.create(**args)
        print(json.dumps(resp, indent=4))
    except keystoneauth1.exceptions.http.InternalServerError as e:
        print(e.message)


def do_delete(argv):
    """Delete all leases with <name> as name."""
    client = get_client(argv.cloud)
    # leases are listed by lease-id, so we cannot use lease.delete()
    lease_list = client.lease.list()
    leases = [l for l in lease_list if l['name'] == argv.name]
    for lease in leases:
        client.lease.delete(lease['id'])
    if not leases:
        print("No lease named {}".format(argv.name))


def do_show(argv):
    """Show all leases with <name> as name."""
    client = get_client(argv.cloud)
    # leases are listed by lease-id, so we cannot use lease.get()
    lease_list = client.lease.list()
    # make sure to print every lease with that name.
    leases = [l for l in lease_list if l['name'] == argv.name]
    for lease in leases:
        print(json.dumps(lease, indent=4))
    if not leases:
        print("No lease named {}".format(argv.name))


def do_list(argv):
    """List all leases."""
    client = get_client(argv.cloud)
    lease_list = client.lease.list()
    if lease_list:
        print(json.dumps(lease_list, indent=4))
    else:
        print("No leases.")


def main():
    parser = argparse.ArgumentParser(description='Chameleon Lease Helper')
    parser.add_argument('--cloud', default=os.environ.get('OS_CLOUD'),
                        help='Cloud name')
    parser.add_argument('--debug', help="Print debugging output",
                        action='store_true')
    subparsers = parser.add_subparsers(title='Commands', dest='command')
    subparsers.required = True

    # create a lease
    parser_create = subparsers.add_parser("create", help="Create a lease")
    parser_create.add_argument("name", help="Lease name")
    parser_create.add_argument("size", help="Number of hosts to lease",
                               type=int)
    parser_create.add_argument("length", help="How long to lease for (hours)",
                               type=int)
    parser_create.set_defaults(func=do_create)

    parser_delete = subparsers.add_parser("delete", help="Delete a lease")
    parser_delete.add_argument("name", help="Lease name")
    parser_delete.set_defaults(func=do_delete)

    parser_show = subparsers.add_parser("show", help="Show a lease")
    parser_show.add_argument("name", help="Lease name")
    parser_show.set_defaults(func=do_show)

    parser_list = subparsers.add_parser("list", help="List all leases")
    parser_list.set_defaults(func=do_list)

    args = parser.parse_args()
    if args.debug:
        logger = logging.getLogger('keystoneauth')
        logger.addHandler(logging.StreamHandler())
        logger.setLevel(logging.DEBUG)
    args.func(args)


if __name__ == '__main__':
    main()