Пример #1
0
def network_delete(network):
    """Delete network.

    If the network does not exist, a NotFoundError will be raised.
    """
    db = model.Session()
    network = _must_find(db, model.Network, network)

    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output(['haas','network_delete', 
                                   network.label+'_'+network.creator.label], 
                                   stderr=STDOUT, 
                                   shell=False) 
        error_checker(bHaaS_out)
    else:
        if network.nics:
            raise BlockedError("Network still connected to nodes")
        if network.hnics:
            raise BlockedError("Network still connected to headnodes")
        if network.scheduled_nics:
            raise BlockedError("Network scheduled to become connected to nodes.")
        if network.allocated:
            driver_name = cfg.get('general', 'driver')
            driver = importlib.import_module('haas.drivers.' + driver_name)
            driver.free_network_id(db, network.network_id)

    db.delete(network)
    
    if cfg.getboolean('recursive', 'rHaaS'):
        b_project = cfg.get('recursive', 'project')
        network_name = network.label + b_project 
        cli.network_delete(network_name)

    db.commit()
Пример #2
0
def headnode_create(headnode, project, base_img):
    """Create headnode.

    If a node with the same name already exists, a DuplicateError will be
    raised.

    If the project already has a headnode, a DuplicateError will be raised.

    If the project does not exist, a NotFoundError will be raised.

    """
    if not cfg.getboolean('recursive', 'rHaaS'):
        valid_imgs = cfg.get('headnode', 'base_imgs')
        valid_imgs = [img.strip() for img in valid_imgs.split(',')]

        if base_img not in valid_imgs:
            raise BadArgumentError('Provided image is not a valid image.')

    # first check the local database to make sure the headnode doesn't already exist
    # and the project is valid

    db = model.Session()
    _assert_absent(db, model.Headnode, headnode)

    project = _must_find(db, model.Project, project)

    #check for recursive HaaS instance, pass down to base HaaS and check for success/failure
    if cfg.getboolean('recursive', 'rHaaS'):
        b_project = cfg.get('recursive', 'project')
        bHaaS_out = check_output([
            'haas', 'headnode_create', headnode + '_' + project.label,
            b_project, base_img
        ],
                                 stderr=STDOUT,
                                 shell=False)

        error_checker(bHaaS_out)

    #else if not recursive, do anything that should only happen @ bHaaS
    else:
        valid_imgs = cfg.get('headnode', 'base_imgs')
        valid_imgs = [img.strip() for img in valid_imgs.split(',')]

        if base_img not in valid_imgs:
            raise BadArgumentError('Provided image is not a valid image.')

    headnode = model.Headnode(project, headnode, base_img)
    db.add(headnode)
    db.commit()
Пример #3
0
def headnode_create_hnic(headnode, hnic):
    """Create hnic attached to given headnode.

    If the node does not exist, a NotFoundError will be raised.

    If there is already an hnic with that name, a DuplicateError will
    be raised.
    """
    db = model.Session()
    headnode = _must_find(db, model.Headnode, headnode)
    _assert_absent_n(db, headnode, model.Hnic, hnic)

    if not headnode.dirty:
        raise IllegalStateError

    hnic = model.Hnic(headnode, hnic)
    db.add(hnic)

    if cfg.getboolean('recursive', 'rHaaS'):
        project = headnode.project.label
        bHaaS_out = check_output([
            'haas', 'headnode_create_hnic', headnode.label + '_' + project,
            hnic.label + '_' + project
        ],
                                 stderr=STDOUT,
                                 shell=False)
        error_checker(bHaaS_out)

    db.commit()
Пример #4
0
def node_detach_network(node, nic):
    """Detach a physical nic from any network it's on.

    Raises ProjectMismatchError if the node is not in a project.
    """
    db = model.Session()
    node = _must_find(db, model.Node, node)
    nic = _must_find_n(db, node, model.Nic, nic)

    if not node.project:
        raise ProjectMismatchError("Node not in project")

    if nic.current_action:
        raise BlockedError(
            "A networking operation is already active on the nic.")

    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output(
            ['haas', 'node_detach_network', node.label, nic.label],
            stderr=STDOUT,
            shell=False)
        error_checker(bHaaS_out)

    db.add(model.NetworkingAction(nic, None))
    db.commit()
Пример #5
0
def headnode_delete_hnic(headnode, hnic):
    """Delete hnic on a given headnode.

    If the hnic does not exist, a NotFoundError will be raised.
    """
    db = model.Session()
    headnode = _must_find(db, model.Headnode, headnode)
    hnic = _must_find_n(db, headnode, model.Hnic, hnic)

    if not headnode.dirty:
        raise IllegalStateError
    if not hnic:
        raise NotFoundError("Hnic: " + hnic.label)

    if cfg.getboolean('recursive', 'rHaaS'):
        project = headnode.project.label
        bHaaS_out = check_output([
            'haas', 'headnode_delete_hnic', headnode.label + '_' + project,
            hnic.label + '_' + project
        ],
                                 stderr=STDOUT,
                                 shell=False)
        error_checker(bHaaS_out)

    db.delete(hnic)
    db.commit()
Пример #6
0
def headnode_detach_network(headnode, hnic):
    """Detach a headnode's nic from any network it's on.

    Raises IllegalStateError if the headnode has already been started.
    """
    db = model.Session()

    headnode = _must_find(db, model.Headnode, headnode)
    hnic = _must_find_n(db, headnode, model.Hnic, hnic)

    if not headnode.dirty:
        raise IllegalStateError

    if cfg.getboolean('recursive','rHaaS'):
        project = headnode.project.label
        bHaaS_out = check_output(['haas','headnode_detach_network', 
                                   headnode.label+'_'+project, 
                                   hnic.label+'_'+project],
                                   stderr=STDOUT, 
                                   shell=False) 
        error_checker(bHaaS_out)
  
    hnic.network = None

    db.commit()
Пример #7
0
def headnode_detach_network(headnode, hnic):
    """Detach a headnode's nic from any network it's on.

    Raises IllegalStateError if the headnode has already been started.
    """
    db = model.Session()

    headnode = _must_find(db, model.Headnode, headnode)
    hnic = _must_find_n(db, headnode, model.Hnic, hnic)

    if not headnode.dirty:
        raise IllegalStateError

    if cfg.getboolean('recursive', 'rHaaS'):
        project = headnode.project.label
        bHaaS_out = check_output([
            'haas', 'headnode_detach_network', headnode.label + '_' + project,
            hnic.label + '_' + project
        ],
                                 stderr=STDOUT,
                                 shell=False)
        error_checker(bHaaS_out)

    hnic.network = None

    db.commit()
Пример #8
0
def headnode_delete_hnic(headnode, hnic):
    """Delete hnic on a given headnode.

    If the hnic does not exist, a NotFoundError will be raised.
    """
    db = model.Session()
    headnode = _must_find(db, model.Headnode, headnode)
    hnic = _must_find_n(db, headnode, model.Hnic, hnic)

    if not headnode.dirty:
        raise IllegalStateError
    if not hnic:
        raise NotFoundError("Hnic: " + hnic.label)
    
    if cfg.getboolean('recursive','rHaaS'):
        project = headnode.project.label
        bHaaS_out = check_output(['haas','headnode_delete_hnic', 
                                   headnode.label+'_'+project, 
                                   hnic.label+'_'+project],
                                   stderr=STDOUT, 
                                   shell=False) 
        error_checker(bHaaS_out)
    
    db.delete(hnic)
    db.commit()
Пример #9
0
Файл: cli.py Проект: lokI8/haas
def serve(port):
    try:
        port = schema.And(schema.Use(int), lambda n: MIN_PORT_NUMBER <= n <= MAX_PORT_NUMBER).validate(port)
    except schema.SchemaError:
	sys.exit('Error: Invaid port. Must be in the range 1-65535.')
    except Exception as e:
	sys.exit('Unxpected Error!!! \n %s' % e)

    """Start the HaaS API server"""
    if cfg.has_option('devel', 'debug'):
        debug = cfg.getboolean('devel', 'debug')
    else:
        debug = False
    # We need to import api here so that the functions within it get registered
    # (via `rest_call`), though we don't use it directly:
    from haas import model, api, rest
    model.init_db()
    # Stop all orphan console logging processes on startup
    db = model.Session()
    nodes = db.query(model.Node).all()
    for node in nodes:
        node.stop_console()
        node.delete_console()
    # Start server
    rest.serve(port, debug=debug)
Пример #10
0
def node_connect_network(node, nic, network):
    """Connect a physical NIC to a network.

    Raises ProjectMismatchError if the node is not in a project, or if the
    project does not have access rights to the given network.
    """
    db = model.Session()

    node = _must_find(db, model.Node, node)
    nic = _must_find_n(db, node, model.Nic, nic)
    network = _must_find(db, model.Network, network)

    if not node.project:
        raise ProjectMismatchError("Node not in project")

    project = node.project

    if (network.access is not None) and (network.access is not project):
        raise ProjectMismatchError("Project does not have access to given network.")

    if nic.current_action:
        raise BlockedError("A networking operation is already active on the nic.")
    
    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output(['haas','node_connect_network', node.label, nic.label, network.label],stderr=STDOUT, shell=False) 
        error_checker(bHaaS_out)

    db.add(model.NetworkingAction(nic, network))
    db.commit()
Пример #11
0
def headnode_create_hnic(headnode, hnic):
    """Create hnic attached to given headnode.

    If the node does not exist, a NotFoundError will be raised.

    If there is already an hnic with that name, a DuplicateError will
    be raised.
    """
    db = model.Session()
    headnode = _must_find(db, model.Headnode, headnode)
    _assert_absent_n(db, headnode, model.Hnic, hnic)

    if not headnode.dirty:
        raise IllegalStateError

    hnic = model.Hnic(headnode, hnic)
    db.add(hnic)

    if cfg.getboolean('recursive','rHaaS'):
        project = headnode.project.label
        bHaaS_out = check_output(['haas','headnode_create_hnic', 
                                   headnode.label+'_'+project, 
                                   hnic.label+'_'+project],
                                   stderr=STDOUT, 
                                   shell=False) 
        error_checker(bHaaS_out)

    db.commit()
Пример #12
0
def headnode_start(headnode):
    """Start the headnode.

    This actually boots up the headnode virtual machine. The VM is created
    within libvirt if needed. Once the VM has been started once, it is
    "frozen," and all other headnode-related api calls will fail (by raising
    an IllegalStateException), with the exception of headnode_stop.
    """
    db = model.Session()
    headnode = _must_find(db, model.Headnode, headnode)

    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output([
            'haas', 'headnode_start',
            headnode.label + '_' + headnode.project.label
        ],
                                 stderr=STDOUT,
                                 shell=False)
        error_checker(bHaaS_out)
        #TODO: is there some way to record headnode.dirty on the rHaaS database also? headnode.dirty = False breaks things

    else:
        if headnode.dirty:
            headnode.create()
        headnode.start()

    db.commit()
Пример #13
0
    def _should_save(self, switch_type):
        """checks the config file to see if switch should save or not"""

        switch_ext = 'haas.ext.switches.' + switch_type
        if cfg.has_option(switch_ext, 'save'):
            if not cfg.getboolean(switch_ext, 'save'):
                return False
        return True
Пример #14
0
def headnode_create(headnode, project, base_img):
    """Create headnode.

    If a node with the same name already exists, a DuplicateError will be
    raised.

    If the project already has a headnode, a DuplicateError will be raised.

    If the project does not exist, a NotFoundError will be raised.

    """
    if not cfg.getboolean('recursive', 'rHaaS'):
        valid_imgs = cfg.get('headnode', 'base_imgs')
        valid_imgs = [img.strip() for img in valid_imgs.split(',')]

        if base_img not in valid_imgs:
            raise BadArgumentError('Provided image is not a valid image.')
    
    # first check the local database to make sure the headnode doesn't already exist
    # and the project is valid


    db = model.Session()
    _assert_absent(db, model.Headnode, headnode)

    project = _must_find(db, model.Project, project)
    
    #check for recursive HaaS instance, pass down to base HaaS and check for success/failure
    if cfg.getboolean('recursive', 'rHaaS'):
        b_project = cfg.get('recursive', 'project')
        bHaaS_out = check_output(['haas','headnode_create', headnode+'_'+project.label, b_project, base_img],stderr=STDOUT, shell=False) 
        
        error_checker(bHaaS_out)
       
    #else if not recursive, do anything that should only happen @ bHaaS
    else:          
        valid_imgs = cfg.get('headnode', 'base_imgs')
        valid_imgs = [img.strip() for img in valid_imgs.split(',')]

        if base_img not in valid_imgs:
            raise BadArgumentError('Provided image is not a valid image.')

    headnode = model.Headnode(project, headnode, base_img)
    db.add(headnode)
    db.commit()
Пример #15
0
def start_console(nodename):
    """Start logging output from the console."""
    db = model.Session()
    node = _must_find(db, model.Node, nodename)
    if cfg.getboolean('recursive','rHaaS'):
        bHaaS_out = check_output(['haas','start_console', node.label], stderr=STDOUT, shell=False) 
        error_checker(bHaaS_out)
    else:
        node.start_console()
Пример #16
0
def init_auth():
    ok = auth.get_auth_backend().authenticate()
    if cfg.has_option('auth', 'require_authentication'):
        require_auth = cfg.getboolean('auth', 'require_authentication')
    else:
        require_auth = True
    if not ok and require_auth:
        raise AuthorizationError("Authentication failed. Authentication "
                                 "is required to use this service.")
Пример #17
0
def init_auth():
    ok = auth.get_auth_backend().authenticate()
    if cfg.has_option('auth', 'require_authentication'):
        require_auth = cfg.getboolean('auth', 'require_authentication')
    else:
        require_auth = True
    if not ok and require_auth:
        raise AuthorizationError("Authentication failed. Authentication "
                                 "is required to use this service.")
Пример #18
0
 def __enter__(self):
     local.db = Session()
     ok = auth.get_auth_backend().authenticate()
     if cfg.has_option('auth', 'require_authentication'):
         require_auth = cfg.getboolean('auth', 'require_authentication')
     else:
         require_auth = True
     if not ok and require_auth:
         local.db.close()
         raise AuthorizationError("Authentication failed. Authentication "
                                  "is required to use this service.")
Пример #19
0
def node_power_cycle(node):

    db = model.Session()
    node = _must_find(db, model.Node, node) 
    
    if cfg.getboolean('recursive','rHaaS'):
        bHaaS_out = check_output(['haas','node_power_cycle', node.label], stderr=STDOUT, shell=False) 
        error_checker(bHaaS_out)
    else:
        if not node.power_cycle():
            raise ServerError('Could not power cycle node %s' % node.label)
Пример #20
0
def start_console(nodename):
    """Start logging output from the console."""
    db = model.Session()
    node = _must_find(db, model.Node, nodename)
    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output(['haas', 'start_console', node.label],
                                 stderr=STDOUT,
                                 shell=False)
        error_checker(bHaaS_out)
    else:
        node.start_console()
Пример #21
0
def node_power_cycle(node):

    db = model.Session()
    node = _must_find(db, model.Node, node)

    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output(['haas', 'node_power_cycle', node.label],
                                 stderr=STDOUT,
                                 shell=False)
        error_checker(bHaaS_out)
    else:
        if not node.power_cycle():
            raise ServerError('Could not power cycle node %s' % node.label)
Пример #22
0
def network_delete(network):
    """Delete network.

    If the network does not exist, a NotFoundError will be raised.
    """
    db = model.Session()
    network = _must_find(db, model.Network, network)

    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output([
            'haas', 'network_delete',
            network.label + '_' + network.creator.label
        ],
                                 stderr=STDOUT,
                                 shell=False)
        error_checker(bHaaS_out)
    else:
        if network.nics:
            raise BlockedError("Network still connected to nodes")
        if network.hnics:
            raise BlockedError("Network still connected to headnodes")
        if network.scheduled_nics:
            raise BlockedError(
                "Network scheduled to become connected to nodes.")
        if network.allocated:
            driver_name = cfg.get('general', 'driver')
            driver = importlib.import_module('haas.drivers.' + driver_name)
            driver.free_network_id(db, network.network_id)

    db.delete(network)

    if cfg.getboolean('recursive', 'rHaaS'):
        b_project = cfg.get('recursive', 'project')
        network_name = network.label + b_project
        cli.network_delete(network_name)

    db.commit()
Пример #23
0
def headnode_stop(headnode):
    """Stop the headnode.

    This powers off the headnode. This is a hard poweroff; the VM is not given
    the opportunity to shut down cleanly. This does *not* unfreeze the VM;
    headnode_start will be the only valid API call after the VM is powered off.
    """
    db = model.Session()
    headnode = _must_find(db, model.Headnode, headnode)

    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output(['haas','headnode_stop', headnode.label+'_'+headnode.project.label],stderr=STDOUT, shell=False) 
        error_checker(bHaaS_out)
    else:
        headnode_stop()
Пример #24
0
def show_headnode(nodename):
    """Show details of a headnode.

    Returns a JSON object representing a headnode.
    The obect will have at least the following fields:
        * "name", the name/label of the headnode (string).
        * "project", the project to which the headnode belongs.
        * "hnics", a JSON array of hnic labels that are attached to this
            headnode.
        * "vncport", the vnc port that the headnode VM is listening on; this
            value can be None if the VM is powered off or has not been
            created yet.

    Example:  '{"name": "headnode1",
                "project": "project1",
                "hnics": ["hnic1", "hnic2"],
                "vncport": 5900
               }'
    """
    db = model.Session()
    headnode = _must_find(db, model.Headnode, nodename)

    # NOTE: this needs a recursive call because the vncport is only known to base HaaS
    # If there is some way to pass that back up on creation and store it in rHaaS,
    # this call would not need to be recursive.
    #
    if cfg.getboolean('recursive', 'rHaaS'):
        b_project = headnode.project.label
        bHaaS_out = check_output(
            ['haas', 'show_headnode', headnode.label + '_' + b_project],
            stderr=STDOUT,
            shell=False)
        print "bhaas_out:"
        print bHaaS_out
        error_checker(bHaaS_out)
        pos = find(bHaaS_out, '{')
        if (pos < 0):
            raise NotFoundError('No JSON found in the base HaaS output')
        else:
            parsed = json.loads(bHaaS_out[pos:])

    headnode.dirty = True
    return json.dumps({
        'name': headnode.label,
        'project': headnode.project.label,
        'hnics': [n.label for n in headnode.hnics],
        'vncport': parsed['vncport'],
    })
Пример #25
0
def show_console(nodename):
    """Show the contents of the console log."""
    db = model.Session()
    node = _must_find(db, model.Node, nodename)
    #for now we are assumming the node is named the same in rHaaS & bHaaS
   
    if cfg.getboolean('recursive','rHaaS'):
        bHaaS_out = check_output(['haas','show_console', node.label], stderr=STDOUT, shell=False) 
        error_checker(bHaaS_out)
    
    else:
        log = node.get_console()
        if log is None:
            raise NotFoundError('The console log for %s '
                            'does not exist.' % nodename)
        return log
Пример #26
0
def node_delete(node):
    """Delete node.

    If the node does not exist, a NotFoundError will be raised.
    """
    db = model.Session()
    node = _must_find(db, model.Node, node)
    node.stop_console()
    node.delete_console()
    db.delete(node)

    if cfg.getboolean('recursive', 'rHaaS'):
        b_project = cfg.get('recursive','project')
        bHaaS_out = check_output(['haas','project_detach_node', b_project, node.label],stderr=STDOUT, shell=False) 
        error_checker(bHaaS_out)

    db.commit()
Пример #27
0
def show_headnode(nodename):
    """Show details of a headnode.

    Returns a JSON object representing a headnode.
    The obect will have at least the following fields:
        * "name", the name/label of the headnode (string).
        * "project", the project to which the headnode belongs.
        * "hnics", a JSON array of hnic labels that are attached to this
            headnode.
        * "vncport", the vnc port that the headnode VM is listening on; this
            value can be None if the VM is powered off or has not been
            created yet.

    Example:  '{"name": "headnode1",
                "project": "project1",
                "hnics": ["hnic1", "hnic2"],
                "vncport": 5900
               }'
    """
    db = model.Session()
    headnode = _must_find(db, model.Headnode, nodename)

    # NOTE: this needs a recursive call because the vncport is only known to base HaaS
    # If there is some way to pass that back up on creation and store it in rHaaS, 
    # this call would not need to be recursive.
    # 
    if cfg.getboolean('recursive','rHaaS'):
        b_project = headnode.project.label
        bHaaS_out = check_output(['haas','show_headnode', headnode.label+'_'+b_project], stderr=STDOUT, shell=False) 
        print "bhaas_out:"
        print bHaaS_out
        error_checker(bHaaS_out)
        pos = find(bHaaS_out, '{') 
        if (pos < 0):
            raise NotFoundError('No JSON found in the base HaaS output') 
        else:   
            parsed = json.loads(bHaaS_out[pos:])
    
    headnode.dirty = True;
    return json.dumps({
            'name': headnode.label,
            'project': headnode.project.label,
            'hnics': [n.label for n in headnode.hnics],
            'vncport': parsed['vncport'],
        })
Пример #28
0
def serve():
    """Start the HaaS API server"""
    if cfg.has_option('devel', 'debug'):
        debug = cfg.getboolean('devel', 'debug')
    else:
        debug = False
    # We need to import api here so that the functions within it get registered
    # (via `rest_call`), though we don't use it directly:
    from haas import model, api, rest
    model.init_db()
    # Stop all orphan console logging processes on startup
    db = model.Session()
    nodes = db.query(model.Node).all()
    for node in nodes:
        node.stop_console()
        node.delete_console()
    # Start server
    rest.serve(debug=debug)
Пример #29
0
def show_console(nodename):
    """Show the contents of the console log."""
    db = model.Session()
    node = _must_find(db, model.Node, nodename)
    #for now we are assumming the node is named the same in rHaaS & bHaaS

    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output(['haas', 'show_console', node.label],
                                 stderr=STDOUT,
                                 shell=False)
        error_checker(bHaaS_out)

    else:
        log = node.get_console()
        if log is None:
            raise NotFoundError('The console log for %s '
                                'does not exist.' % nodename)
        return log
Пример #30
0
def serve():
    """Start the HaaS API server"""
    if cfg.has_option('devel', 'debug'):
        debug = cfg.getboolean('devel', 'debug')
    else:
        debug = False
    # We need to import api here so that the functions within it get registered
    # (via `rest_call`), though we don't use it directly:
    from haas import model, api, rest
    model.init_db()
    # Stop all orphan console logging processes on startup
    db = model.Session()
    nodes = db.query(model.Node).all()
    for node in nodes:
        node.stop_console()
        node.delete_console()
    # Start server
    rest.serve(debug=debug)
Пример #31
0
def serve(port):
    try:
        port = schema.And(schema.Use(int), lambda n: MIN_PORT_NUMBER <= n <= MAX_PORT_NUMBER).validate(port)
    except schema.SchemaError:
	sys.exit('Error: Invaid port. Must be in the range 1-65535.')
    except Exception as e:
	sys.exit('Unxpected Error!!! \n %s' % e)

    """Start the HaaS API server"""
    if cfg.has_option('devel', 'debug'):
        debug = cfg.getboolean('devel', 'debug')
    else:
        debug = False
    # We need to import api here so that the functions within it get registered
    # (via `rest_call`), though we don't use it directly:
    from haas import model, api, rest
    server.init(stop_consoles=True)
    rest.serve(port, debug=debug)
Пример #32
0
def headnode_connect_network(headnode, hnic, network):
    """Connect a headnode's hnic to a network.

    Raises IllegalStateError if the headnode has already been started.

    Raises ProjectMismatchError if the project does not have access rights to
    the given network.

    Raises BadArgumentError if the network is a non-allocated network. This
    is currently unsupported due to an implementation limitation, but will be
    supported in a future release. See issue #333.
    """
    db = model.Session()

    headnode = _must_find(db, model.Headnode, headnode)
    hnic = _must_find_n(db, headnode, model.Hnic, hnic)
    network = _must_find(db, model.Network, network)

    if not network.allocated:
        raise BadArgumentError("Headnodes may only be connected to networks "
                               "allocated by the project.")

    if not headnode.dirty:
        raise IllegalStateError

    project = headnode.project

    if (network.access is not None) and (network.access is not project):
        raise ProjectMismatchError(
            "Project does not have access to given network.")

    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output([
            'haas', 'headnode_connect_network', headnode.label + '_' +
            project.label, hnic.label + '_' + project.label,
            network.label + '_' + project.label
        ],
                                 stderr=STDOUT,
                                 shell=False)
        error_checker(bHaaS_out)

    hnic.network = network

    db.commit()
Пример #33
0
def serve(port):
    try:
        port = schema.And(
            schema.Use(int),
            lambda n: MIN_PORT_NUMBER <= n <= MAX_PORT_NUMBER).validate(port)
    except schema.SchemaError:
        sys.exit('Error: Invaid port. Must be in the range 1-65535.')
    except Exception as e:
        sys.exit('Unxpected Error!!! \n %s' % e)
    """Start the HaaS API server"""
    if cfg.has_option('devel', 'debug'):
        debug = cfg.getboolean('devel', 'debug')
    else:
        debug = False
    # We need to import api here so that the functions within it get registered
    # (via `rest_call`), though we don't use it directly:
    from haas import model, api, rest
    server.init(stop_consoles=True)
    rest.serve(port, debug=debug)
Пример #34
0
def headnode_delete(headnode):
    """Delete headnode.

    If the node does not exist, a NotFoundError will be raised.
    """
    db = model.Session()
    headnode = _must_find(db, model.Headnode, headnode)
    
    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output(['haas','headnode_delete', headnode.label+'_'+headnode.project.label],stderr=STDOUT, shell=False) 
        error_checker(bHaaS_out)
    
    if not headnode.dirty:
        headnode.delete()
    for hnic in headnode.hnics:
        db.delete(hnic)
    
    db.delete(headnode)
    db.commit()
Пример #35
0
def headnode_connect_network(headnode, hnic, network):
    """Connect a headnode's hnic to a network.

    Raises IllegalStateError if the headnode has already been started.

    Raises ProjectMismatchError if the project does not have access rights to
    the given network.

    Raises BadArgumentError if the network is a non-allocated network. This
    is currently unsupported due to an implementation limitation, but will be
    supported in a future release. See issue #333.
    """
    db = model.Session()

    headnode = _must_find(db, model.Headnode, headnode)
    hnic = _must_find_n(db, headnode, model.Hnic, hnic)
    network = _must_find(db, model.Network, network)

    if not network.allocated:
        raise BadArgumentError("Headnodes may only be connected to networks "
                               "allocated by the project.")

    if not headnode.dirty:
        raise IllegalStateError

    project = headnode.project

    if (network.access is not None) and (network.access is not project):
        raise ProjectMismatchError("Project does not have access to given network.")

    if cfg.getboolean('recursive','rHaaS'):
        bHaaS_out = check_output(['haas','headnode_connect_network', 
                                   headnode.label+'_'+project.label, 
                                   hnic.label+'_'+project.label,
                                   network.label+'_'+project.label],
                                   stderr=STDOUT, 
                                   shell=False) 
        error_checker(bHaaS_out)

    hnic.network = network
       
    db.commit()
Пример #36
0
def node_delete(node):
    """Delete node.

    If the node does not exist, a NotFoundError will be raised.
    """
    db = model.Session()
    node = _must_find(db, model.Node, node)
    node.stop_console()
    node.delete_console()
    db.delete(node)

    if cfg.getboolean('recursive', 'rHaaS'):
        b_project = cfg.get('recursive', 'project')
        bHaaS_out = check_output(
            ['haas', 'project_detach_node', b_project, node.label],
            stderr=STDOUT,
            shell=False)
        error_checker(bHaaS_out)

    db.commit()
Пример #37
0
def headnode_stop(headnode):
    """Stop the headnode.

    This powers off the headnode. This is a hard poweroff; the VM is not given
    the opportunity to shut down cleanly. This does *not* unfreeze the VM;
    headnode_start will be the only valid API call after the VM is powered off.
    """
    db = model.Session()
    headnode = _must_find(db, model.Headnode, headnode)

    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output([
            'haas', 'headnode_stop',
            headnode.label + '_' + headnode.project.label
        ],
                                 stderr=STDOUT,
                                 shell=False)
        error_checker(bHaaS_out)
    else:
        headnode_stop()
Пример #38
0
def node_detach_network(node, nic):
    """Detach a physical nic from any network it's on.

    Raises ProjectMismatchError if the node is not in a project.
    """
    db = model.Session()
    node = _must_find(db, model.Node, node)
    nic = _must_find_n(db, node, model.Nic, nic)

    if not node.project:
        raise ProjectMismatchError("Node not in project")

    if nic.current_action:
        raise BlockedError("A networking operation is already active on the nic.")

    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output(['haas','node_detach_network', node.label, nic.label],stderr=STDOUT, shell=False) 
        error_checker(bHaaS_out)

    db.add(model.NetworkingAction(nic, None))
    db.commit()
Пример #39
0
def headnode_start(headnode):
    """Start the headnode.

    This actually boots up the headnode virtual machine. The VM is created
    within libvirt if needed. Once the VM has been started once, it is
    "frozen," and all other headnode-related api calls will fail (by raising
    an IllegalStateException), with the exception of headnode_stop.
    """
    db = model.Session()
    headnode = _must_find(db, model.Headnode, headnode)
    
    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output(['haas','headnode_start', headnode.label+'_'+headnode.project.label],stderr=STDOUT, shell=False) 
        error_checker(bHaaS_out)
        #TODO: is there some way to record headnode.dirty on the rHaaS database also? headnode.dirty = False breaks things
    
    else:
        if headnode.dirty:
            headnode.create()
        headnode.start()

    db.commit()
Пример #40
0
def node_connect_network(node, nic, network):
    """Connect a physical NIC to a network.

    Raises ProjectMismatchError if the node is not in a project, or if the
    project does not have access rights to the given network.
    """
    db = model.Session()

    node = _must_find(db, model.Node, node)
    nic = _must_find_n(db, node, model.Nic, nic)
    network = _must_find(db, model.Network, network)

    if not node.project:
        raise ProjectMismatchError("Node not in project")

    project = node.project

    if (network.access is not None) and (network.access is not project):
        raise ProjectMismatchError(
            "Project does not have access to given network.")

    if nic.current_action:
        raise BlockedError(
            "A networking operation is already active on the nic.")

    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output([
            'haas', 'node_connect_network', node.label, nic.label,
            network.label
        ],
                                 stderr=STDOUT,
                                 shell=False)
        error_checker(bHaaS_out)

    db.add(model.NetworkingAction(nic, network))
    db.commit()
Пример #41
0
def headnode_delete(headnode):
    """Delete headnode.

    If the node does not exist, a NotFoundError will be raised.
    """
    db = model.Session()
    headnode = _must_find(db, model.Headnode, headnode)

    if cfg.getboolean('recursive', 'rHaaS'):
        bHaaS_out = check_output([
            'haas', 'headnode_delete',
            headnode.label + '_' + headnode.project.label
        ],
                                 stderr=STDOUT,
                                 shell=False)
        error_checker(bHaaS_out)

    if not headnode.dirty:
        headnode.delete()
    for hnic in headnode.hnics:
        db.delete(hnic)

    db.delete(headnode)
    db.commit()
Пример #42
0
def network_create(network, creator, access, net_id):
    """Create a network.

    If the network with that name already exists, a DuplicateError will be
    raised.

    If the combination of creator, access, and net_id is illegal, a
    BadArgumentError will be raised.

    If network ID allocation was requested, and the network cannot be
    allocated (due to resource exhaustion), an AllocationError will be raised.

    Pass 'admin' as creator for an administrator-owned network.  Pass '' as
    access for a publicly accessible network.  Pass '' as net_id if you wish
    to use the HaaS's network-id allocation pool.

    Details of the various combinations of network attributes are in
    docs/networks.md
    """
    db = model.Session()
    _assert_absent(db, model.Network, network)


    # Check legality of arguments, and find correct 'access' and 'creator'
    if creator != "admin":
        # Project-owned network
        if access != creator:
            raise BadArgumentError("Project-created networks must be accessed only by that project.")
        if net_id != "":
            raise BadArgumentError("Project-created networks must use network ID allocation")
        creator = _must_find(db, model.Project, creator)
        access = _must_find(db, model.Project, access)
    else:
        # Administrator-owned network
        creator = None
        if access == "":
            access = None
        else:
            access = _must_find(db, model.Project, access)

    if cfg.getboolean('recursive','rHaaS'):

        #TODO - work out whether there is such a thing as an admin-created network in rHaaS
        # if so, how do we handle this case at bHaaS
        
        project = creator.label
        b_project = cfg.get('recursive','project')
        allocated = True; #rHaaS always has allocated netIDs
        net_id = "dummy";

        #if creator.label == "admin":  
        #   b_project = cfg.get('recursive','project')
        #else:
        #   project = creator.label
        #   print project

        bHaaS_out = check_output(['haas','network_create', 
                                   network+'_'+project, 
                                   b_project,  #how to handle case of admin in rHaaS?
                                   b_project,  #access and creator must be the same?
                                   ""], 
                                   stderr=STDOUT, 
                                   shell=False) 
        error_checker(bHaaS_out) #can you get the assigned netID here? for now just dummy it out?
        network = model.Network(creator, access, allocated, net_id, network)
    else:
        # Allocate net_id, if requested
        if net_id == "":
            driver_name = cfg.get('general', 'driver')
            driver = importlib.import_module('haas.drivers.' + driver_name)
            net_id = driver.get_new_network_id(db)
            if net_id is None:
                raise AllocationError('No more networks')
            allocated = True
        else:
            allocated = False
        network = model.Network(creator, access, allocated, net_id, network)
  
    db.add(network)
    
    if cfg.getboolean('recursive', 'rHaaS'):
        b_project = cfg.get('recursive', 'project')
        network_name = network.label + b_project
        net_id = ''
        cli.network_create(network_name, b_project, b_project, net_id)

    db.commit()
Пример #43
0
def network_create(network, creator, access, net_id):
    """Create a network.

    If the network with that name already exists, a DuplicateError will be
    raised.

    If the combination of creator, access, and net_id is illegal, a
    BadArgumentError will be raised.

    If network ID allocation was requested, and the network cannot be
    allocated (due to resource exhaustion), an AllocationError will be raised.

    Pass 'admin' as creator for an administrator-owned network.  Pass '' as
    access for a publicly accessible network.  Pass '' as net_id if you wish
    to use the HaaS's network-id allocation pool.

    Details of the various combinations of network attributes are in
    docs/networks.md
    """
    db = model.Session()
    _assert_absent(db, model.Network, network)

    # Check legality of arguments, and find correct 'access' and 'creator'
    if creator != "admin":
        # Project-owned network
        if access != creator:
            raise BadArgumentError(
                "Project-created networks must be accessed only by that project."
            )
        if net_id != "":
            raise BadArgumentError(
                "Project-created networks must use network ID allocation")
        creator = _must_find(db, model.Project, creator)
        access = _must_find(db, model.Project, access)
    else:
        # Administrator-owned network
        creator = None
        if access == "":
            access = None
        else:
            access = _must_find(db, model.Project, access)

    if cfg.getboolean('recursive', 'rHaaS'):

        #TODO - work out whether there is such a thing as an admin-created network in rHaaS
        # if so, how do we handle this case at bHaaS

        project = creator.label
        b_project = cfg.get('recursive', 'project')
        allocated = True
        #rHaaS always has allocated netIDs
        net_id = "dummy"

        #if creator.label == "admin":
        #   b_project = cfg.get('recursive','project')
        #else:
        #   project = creator.label
        #   print project

        bHaaS_out = check_output(
            [
                'haas',
                'network_create',
                network + '_' + project,
                b_project,  #how to handle case of admin in rHaaS?
                b_project,  #access and creator must be the same?
                ""
            ],
            stderr=STDOUT,
            shell=False)
        error_checker(
            bHaaS_out
        )  #can you get the assigned netID here? for now just dummy it out?
        network = model.Network(creator, access, allocated, net_id, network)
    else:
        # Allocate net_id, if requested
        if net_id == "":
            driver_name = cfg.get('general', 'driver')
            driver = importlib.import_module('haas.drivers.' + driver_name)
            net_id = driver.get_new_network_id(db)
            if net_id is None:
                raise AllocationError('No more networks')
            allocated = True
        else:
            allocated = False
        network = model.Network(creator, access, allocated, net_id, network)

    db.add(network)

    if cfg.getboolean('recursive', 'rHaaS'):
        b_project = cfg.get('recursive', 'project')
        network_name = network.label + b_project
        net_id = ''
        cli.network_create(network_name, b_project, b_project, net_id)

    db.commit()