def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            app.logger.error('No file in POST request')
            return redirect(url_for('dashboard'))
        file = request.files['file']
        if file.filename == '':
            app.logger.error('No selected file')
            return redirect(url_for('dashboard'))
        if file and allowed_file(file.filename):
            # filename = secure_filename(file.filename)
            # file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            try:
                fdu_d = FDU(json.loads(file.read()))
                session['fdu_descriptor'] = fdu_d.to_json()
                app.logger.debug('File upload succeeded')
                res = a.fdu.onboard(fdu_d)
                app.logger.debug(res.to_json())
                e_uuid = res.get_uuid()
                session['fdu_uuid'] = e_uuid
            except ValueError:
                app.logger.error("Fdu configuration json is malformed")
            return redirect(url_for('dashboard'))
        else:
            app.logger.error('Extension not allowed')
            return redirect(url_for('dashboard'))
Example #2
0
        def onboard(self, descriptor):
            '''
            Registers an FDU descriptor in the system catalog
            Needs at least one node in the system!

            parameters
            ----------
            descriptor : FDU
                FDU descriptor

            returns
            -------
            FDU
            '''
            if not isinstance(descriptor, FDU):
                raise ValueError(
                    'descriptor should be of type FDU; actual type: {}'.format(
                        type(descriptor)))
            nodes = self.connector.glob.actual.get_all_nodes(
                self.sysid, self.tenantid)
            if len(nodes) == 0:
                raise SystemError('No nodes in the system!')
            n = random.choice(nodes)

            res = self.connector.glob.actual.onboard_fdu_from_node(
                self.sysid, self.tenantid, n, descriptor.get_uuid(),
                descriptor.to_json())
            if res.get('result') is None:
                raise SystemError(
                    'Error during onboarding {} with message {}'.format(
                        res['error'], res['error_msg']))
            return FDU(res['result'])
Example #3
0
def main(ip, fdufile, netfile):
    a = FIMAPI(ip)

    nodes = a.node.list()
    if len(nodes) == 0:
        print('No nodes')
        exit(-1)

    print('Nodes:')
    for n in nodes:
        print('UUID: {}'.format(n))

    fdu_d = FDU(json.loads(read_file(fdufile)))
    net_d = json.loads(read_file(netfile))

    n_uuid = net_d.get('uuid')

    n1 = '4a560914-1c3e-4966-9fa8-7f0acc903253'  #nuc

    input("Press enter to create network")
    a.network.add_network(net_d)
    a.network.add_network_to_node(net_d, n1)

    input('press enter to onboard descriptor')
    res = a.fdu.onboard(fdu_d)
    e_uuid = res.get_uuid()
    input('Press enter to define')
    inst_info = a.fdu.define(e_uuid)
    print(inst_info.to_json())
    instid = inst_info.get_uuid()

    input('Press enter to configure')
    a.fdu.configure(instid)

    input('Press enter to start')
    a.fdu.start(instid)

    # input('Press enter to stop')
    # a.entity.stop(e_uuid, n1, i_uuid)
    # input('Press enter to clean')
    # a.entity.clean(e_uuid, n1, i_uuid)
    # input('Press enter to undefine')
    # a.entity.undefine(e_uuid, n1)

    # input('Press enter to migrate')
    input('Press get info')
    info = a.fdu.instance_info(instid)
    print(info.to_json())

    #res = a.entity.migrate(e_uuid, i_uuid, n1, n2)
    #print('Res is: {}'.format(res))
    input('Press enter to terminate')

    a.fdu.terminate(instid)
    a.fdu.offload(e_uuid)
    input("Press enter to remove network")
    a.network.remove_network_from_node(n_uuid, n1)
    a.network.remove_network(n_uuid)

    exit(0)
def main(ip, fdufile, netfile):
    a = FIMAPI(ip)
    nodes = a.node.list()
    if len(nodes) == 0:
        print('No nodes')
        exit(-1)

    print('Nodes:')
    for n in nodes:
        print('UUID: {}'.format(n))

    fdu_d = FDU(json.loads(read_file(fdufile)))

    net_d = json.loads(read_file(netfile))

    n_uuid = net_d.get('uuid')

    n1 = '1e03d6b9-908e-44e6-9fc2-3282e38c442d'  #fog01
    n2 = 'dc02633d-491b-40b3-83be-072748142fc4'  #fog02

    input("Press enter to create network")
    a.network.add_network(net_d)
    net_info = get_net_info(a, net_d['uuid'])
    print('Net info {}'.format(net_info))

    input('press enter to network creation')
    a.network.add_network_to_node(net_info['uuid'], n1)

    input('press enter to onboard descriptor')
    res = a.fdu.onboard(fdu_d)
    e_uuid = res.get_uuid()
    input('Press enter to define')
    inst_info = a.fdu.define(e_uuid)
    print(inst_info.to_json())
    instid = inst_info.get_uuid()

    input('Press enter to configure')
    a.fdu.configure(instid)

    input('Press enter to start')
    a.fdu.start(instid)

    input('Press get info')
    info = a.fdu.instance_info(instid)
    print(info.to_json())

    #res = a.entity.migrate(e_uuid, i_uuid, n1, n2)
    #print('Res is: {}'.format(res))
    input('Press enter to terminate')

    a.fdu.terminate(instid)
    a.fdu.offload(e_uuid)
    input("Press enter to remove network")
    a.network.remove_network_from_node(n_uuid, n1)
    a.network.remove_network(n_uuid)

    exit(0)
Example #5
0
def main(ip, fdufile):
    a = FIMAPI(ip)

    nodes = a.node.list()
    if len(nodes) == 0:
        print('No nodes')
        exit(-1)

    print('Nodes:')
    for n in nodes:
        print('UUID: {}'.format(n))

    fdu_d = FDU(json.loads(read_file(fdufile)))

    input('press enter to onboard descriptor')
    res = a.fdu.onboard(fdu_d)
    print(res.to_json())
    e_uuid = res.get_uuid()
    # code.interact(local=locals())

    # display choice
    print('Choose at which node you want to define the fdu:')
    for idx, n in enumerate(nodes):
        print('{}: {}'.format(idx, n))
    index = input('')

    inst_info = a.fdu.define(e_uuid, nodes[int(index)])
    print(inst_info.to_json())
    instid = inst_info.get_uuid()

    input('Press enter to configure')
    a.fdu.configure(instid)

    input('Press enter to start')
    a.fdu.start(instid)

    input('Press get info')
    info = a.fdu.instance_info(instid)
    print(info.to_json())

    input('Press enter to stop')
    a.fdu.stop(instid)

    input('Press enter to clean')
    a.fdu.clean(instid)

    input('Press enter to remove')

    a.fdu.undefine(instid)
    a.fdu.offload(e_uuid)

    exit(0)
Example #6
0
def main(ip, fdufile):
    a = FIMAPI(ip)

    nodes = a.node.list()
    if len(nodes) == 0:
        print('No nodes')
        exit(-1)

    print('Nodes:')
    for n in nodes:
        print('UUID: {}'.format(n))

    fdu_d = FDU(json.loads(read_file(fdufile)))

    input('press enter to onboard descriptor')
    res = a.fdu.onboard(fdu_d)
    print(res.to_json())
    e_uuid = res.get_uuid()
    # code.interact(local=locals())

    input('Press enter to define')
    inst_info = a.fdu.define(e_uuid)
    print(inst_info.to_json())
    instid = inst_info.get_uuid()

    input('Press enter to configure')
    a.fdu.configure(instid)

    input('Press enter to start')
    a.fdu.start(instid)

    input('Press get info')
    info = a.fdu.instance_info(instid)
    print(info.to_json())

    input('Press enter to stop')
    a.fdu.stop(instid)

    input('Press enter to clean')
    a.fdu.clean(instid)

    input('Press enter to remove')

    a.fdu.undefine(instid)
    a.fdu.offload(e_uuid)

    exit(0)
Example #7
0
def main(ip):
    a = FIMAPI(ip)

    fdus = {}
    nets = []

    print('Current Eclipse fog05 Infrastrucutre:')

    nodes = a.node.list()
    for nid in nodes:
        info = a.node.info(nid)
        print('ID: {} Hostname: {}'.format(nid, info['name']))


    input('Press enter to instantiate the demo')

    for d in net_desc:
        path_d = os.path.join(DESC_FOLDER,d)
        netd = json.loads(read(path_d))
        a.network.add_network(netd)
        nets.append(netd['uuid'])
        time.sleep(1)

    for d in descs:
        nid = descs[d]
        print('Instantiating {} to {}'.format(d, nid))
        path_d = os.path.join(DESC_FOLDER,d)
        data = json.loads(read(path_d))
        fdu_d = FDU(data)
        fduinfo = a.fdu.onboard(fdu_d)
        fdu_id = fduinfo.uuid
        print ('fdu_id : {}'.format(fdu_id))
        inst_info = a.fdu.define(fdu_id, nid)
        iid = inst_info.uuid
        time.sleep(1)
        a.fdu.configure(iid)
        time.sleep(1)
        a.fdu.start(iid)
        print ('iid : {}'.format(iid))
        print('Instantiated: {}'.format(fdu_d.name))
        fdus.update({fdu_id: iid})
        time.sleep(2)

    print('Instantiated:')
    print(json.dumps(fdus, indent=2))
    print('Bye!')
Example #8
0
        def info(self, fdu_uuid):
            '''
            Gets information about the given FDU from the catalog

            parameters
            ----------
            fdu_uuid : string
                UUID of the FDU

            returns
            -------
            FDU
            '''
            data = self.connector.glob.actual.get_catalog_fdu_info(
                self.sysid, self.tenantid, fdu_uuid)
            fdu = FDU(data)
            return fdu
Example #9
0
def container_deploy(descs, api):
    for d in descs:
        path_d = os.path.join(DESC_FOLDER, d)
        fdu_d = FDU(json.loads(read(path_d)))
        input('press enter to onboard descriptor')
        res = api.fdu.onboard(fdu_d)
        e_uuid = res.get_uuid()
        input('Press enter to define')
        inst_info = api.fdu.define(e_uuid)
        print(inst_info.to_json())
        instid = inst_info.get_uuid()
        input('Press enter to configure')
        api.fdu.configure(instid)
        input('Press enter to start')
        api.fdu.start(instid)
        input('Press get info')
        info = api.fdu.instance_info(instid)
        print(info.to_json())
    def __init__(self, data=None):
        '''

        Constructor for the FDU Descriptor
        :param data dictionary containing the FDU descriptor

        :return the FDU object

        '''

        self.ae = user_atomic_entity.user_atomic_entity()
        self.encoder = pybindJSONEncoder()
        self.id = None
        self.uuid = None
        self.name = None
        self.description = None
        self.fdus = []
        self.internal_virtual_links = []
        self.connection_points = []
        self.depends_on = []
        if data is not None:
            pybindJSONDecoder.load_ietf_json({'ae_descriptor': data},
                                             None,
                                             None,
                                             obj=self.ae,
                                             skip_unknown=True)
            self.enforce()

            self.id = self.ae.ae_descriptor.id
            self.name = data.get('name')
            self.description = data.get('description')
            self.uuid = data.get('uuid', None)
            self.fdus = [FDU(x) for x in data.get('fdus')]
            self.internal_virtual_links = data.get('internal_virtual_links')
            self.connection_points = data.get('connection_points')
            self.depends_on = data.get('depends_on')
def main(ip, ip2, fdufile, fdu2, netfile):
    a = FIMAPI(ip)

    a2 = FIMAPI(ip2)

    nodes = a.node.list()
    if len(nodes) == 0:
        print('No nodes')
        exit(-1)

    print('Nodes:')
    for n in nodes:
        print('UUID: {}'.format(n))

    fdu_d = FDU(json.loads(read_file(fdufile)))
    second_fdu_d = FDU(json.loads(read_file(fdu2)))

    net_d = json.loads(read_file(netfile))

    n_uuid = net_d.get('uuid')

    n1 = 'dc02633d-491b-40b3-83be-072748142fc4'  #fog02
    n2 = '1e03d6b9-908e-44e6-9fc2-3282e38c442d'  #fog01

    input("Press enter to create network")
    a.network.add_network(net_d)
    net_info = get_net_info(a, net_d['uuid'])
    print('Net info {}'.format(net_info))

    input('press enter to network creation')
    a.network.add_network_to_node(net_info['uuid'], n1)

    input('press enter to onboard descriptor')
    res = a.fdu.onboard(fdu_d)
    e_uuid = res.get_uuid()
    input('Press enter to define')
    inst_info = a.fdu.define(e_uuid)
    print(inst_info.to_json())
    instid = inst_info.get_uuid()

    input('Press enter to configure')
    a.fdu.configure(instid)

    input('Press enter to start')
    a.fdu.start(instid)

    # input('press enter to onboard second descriptor')
    # res = a.fdu.onboard(second_fdu_d)
    # s_e_uuid = res.get_uuid()
    # input('Press enter to define')
    # s_inst_info = a.fdu.define(s_e_uuid)
    # print(s_inst_info.to_json())
    # s_instid = s_inst_info.get_uuid()

    # input('Press enter to configure')
    # a.fdu.configure(s_instid)

    # input('Press enter to start')
    # a.fdu.start(s_instid)

    # input('Press enter to stop')
    # a.entity.stop(e_uuid, n1, i_uuid)
    # input('Press enter to clean')
    # a.entity.clean(e_uuid, n1, i_uuid)
    # input('Press enter to undefine')
    # a.entity.undefine(e_uuid, n1)

    # input('Press enter to migrate')
    input('Press get info')
    info = a.fdu.instance_info(instid)
    print(info.to_json())

    # input('Press get info')
    # info = a.fdu.instance_info(s_instid)
    # print(info.to_json())

    input('Press to move client to second domain')
    net_info = get_net_info(a, net_d['uuid'])
    input('Press to create federated vxlan to second domain')
    a2.network.add_network(net_info)

    net_info2 = get_net_info(a2, net_info['uuid'])
    print('Net info {}'.format(net_info2))
    a2.network.add_network_to_node(net_info2['uuid'], n2)

    # input('remove client from first domain')
    # a.fdu.terminate(s_instid)
    # a.fdu.offload(s_e_uuid)

    input('press enter to onboard second descriptor')
    res = a2.fdu.onboard(second_fdu_d)
    s_e_uuid = res.get_uuid()
    input('Press enter to define')
    s_inst_info = a2.fdu.define(s_e_uuid)
    print(s_inst_info.to_json())
    s_instid = s_inst_info.get_uuid()

    input('Press enter to configure')
    a2.fdu.configure(s_instid)

    input('Press enter to start')
    a2.fdu.start(s_instid)

    input('Press get info')
    info = a2.fdu.instance_info(s_instid)
    print(info.to_json())

    #res = a.entity.migrate(e_uuid, i_uuid, n1, n2)
    #print('Res is: {}'.format(res))
    input('Press enter to terminate')

    a.fdu.terminate(instid)
    a.fdu.offload(e_uuid)
    a2.fdu.terminate(s_instid)
    a2.fdu.offload(s_e_uuid)
    input("Press enter to remove network")
    a.network.remove_network_from_node(n_uuid, n1)
    a.network.remove_network(n_uuid)

    exit(0)
Example #12
0
def main(ip, fdufile, netfile, routerfile):
    a = FIMAPI(ip)

    nodes = a.node.list()
    if len(nodes) == 0:
        print('No nodes')
        exit(-1)

    print('Nodes:')
    for n in nodes:
        print('UUID: {}'.format(n))

    fdu_d = FDU(json.loads(read_file(fdufile)))
    net_d = json.loads(read_file(netfile))
    router_d = json.loads(read_file(routerfile))

    # e_uuid = fdu_d.get('uuid')
    n_uuid = net_d.get('uuid')
    r_uuid = router_d.get('uuid')

    input("Press enter to create network")
    a.network.add_network(net_d)

    n1 = '4a560914-1c3e-4966-9fa8-7f0acc903253'  #nuc

    input('press enter to onboard descriptor')
    desc = a.fdu.onboard(fdu_d)
    e_uuid = desc.get_uuid()
    input('Press enter to instantiate')
    rec = a.fdu.instantiate(e_uuid, n1)
    intsid = rec.get_uuid()
    input('Press enter to create router')
    a.network.add_router(n1, router_d)

    # input("press enter to add router port")
    # res = a.network.add_router_port(n1, r_uuid, "INTERNAL", "6cc2aa30-1dcf-4c93-a57e-433fd0bd498e", "192.168.234.1/24")
    # print(res)

    # input("press enter to remove router port")
    # res = a.network.remove_router_port(n1, r_uuid, "6cc2aa30-1dcf-4c93-a57e-433fd0bd498e")
    # print(res)

    # input('Press enter to stop')
    # a.entity.stop(e_uuid, n1, i_uuid)
    # input('Press enter to clean')
    # a.entity.clean(e_uuid, n1, i_uuid)
    # input('Press enter to undefine')
    # a.entity.undefine(e_uuid, n1)

    # input('Press enter to migrate')

    #res = a.entity.migrate(e_uuid, i_uuid, n1, n2)
    #print('Res is: {}'.format(res))
    input('Press enter to remove')

    a.fdu.terminate(intsid)
    a.fdu.offload(e_uuid)
    input('Press enter to remove router')
    a.network.remove_router(n1, r_uuid)
    input("Press enter to remove network")
    a.network.remove_network(n_uuid)

    exit(0)
Example #13
0
def consumer(ip, fdufile, netfile):
    # Access the fog05 domain web socket
    a = FIMAPI(ip)
    # Get the nodes from the domain
    nodes = a.node.list()
    if len(nodes) == 0:
        print('No nodes')
        exit(-1)
    # Print the nodes from the domain
    print('Nodes:')
    for n in nodes:
        print('UUID: {}'.format(n))

    # Load the FDU (descriptors)
    fdu_d = FDU(json.loads(read_file(fdufile)))
    # Load the network descriptor
    net_d = json.loads(read_file(netfile))
    n_uuid = net_d.get('uuid')

    # Create network based on the descriptor
    input("Press enter to create network")
    a.network.add_network(net_d)
    # Get info if the network is created
    net_info = get_net_info(a, net_d['uuid'])
    print('Net info {}'.format(net_info))

    # Add the created network to the node (n1)
    input('press enter to network creation')
    a.network.add_network_to_node(net_info['uuid'], n1)

    #  On-board the FDU
    input('press enter to onboard descriptor')
    res = a.fdu.onboard(fdu_d)
    # Get the identifier of the on-boarded FDU
    e_uuid = res.get_uuid()
    # Define an instance of the on-boarded FDU
    input('Press enter to define')
    inst_info = a.fdu.define(e_uuid)
    # Get the ID of the defined FDU instance
    print(inst_info.to_json())
    instid = inst_info.get_uuid()

    # Configure the defined FDU instance
    input('Press enter to configure')
    a.fdu.configure(instid)

    # Start the configured FDU instance
    input('Press enter to start')
    a.fdu.start(instid)
    # Get the info of the started FDU instance
    input('Press get info')
    info = a.fdu.instance_info(instid)
    print(info.to_json())

    ########## FEDERATION STARTS HERE ###########################################################
    debug_txt = input("\nUse service_id:")
    service_id = debug_txt
    print(net_d)
    # net_d = {"uuid": "6cc2aa30-1dcf-4c93-a57e-433fd0bd498e",\
    #         "name": "net1",\
    #         "net_type": "ELAN",\
    #         "is_mgmt": False
    #         }

    print("\nSERVICE_ID:", service_id)
    debug_txt = input("\nCreate Service anouncement....(ENTER)")
    start = time.time()
    bids_event = AnnounceService(net_d, service_id)
    bidderArrived = False
    while bidderArrived == False:
        new_events = bids_event.get_all_entries()
        for event in new_events:
            event_id = str(web3.toText(event['args']['_id']))
            print(service_id, web3.toText(event['args']['_id']),
                  event['args']['max_bid_index'])
            #if event_id == web3.toText(text= service_id):
            bid_index = int(event['args']['max_bid_index'])
            bidderArrived = True
            if int(bid_index) < 2:
                bid_info = GetBidInfo(int(bid_index - 1), service_id)
                print(bid_info)
                ChooseProvider(int(bid_index) - 1, service_id)
                break
    serviceDeployed = False
    while serviceDeployed == False:
        serviceDeployed = True if GetServiceState(service_id) == 2 else False
    serviceDeployedInfo = GetServiceInfo(service_id, False)
    end = time.time()
    print(serviceDeployedInfo)
    print("SERVICE FEDERATED!")
    print("Time it took:", int(end - start))
    ########## FEDERATION FINISH HERE ###########################################################

    input('Press enter to terminate')
    a.fdu.terminate(instid)
    a.fdu.offload(e_uuid)
    input("Press enter to remove network")
    a.network.remove_network_from_node(n_uuid, n1)
    a.network.remove_network(n_uuid)

    exit(0)
def main(ip, fdufile):
    t1 = time.time()
    a = FIMAPI(ip)
    t2 = time.time()
    t_conn = t2 - t1

    nodes = a.node.list()
    if len(nodes) == 0:
        print('No nodes')
        exit(-1)

    print('Nodes:')
    for n in nodes:
        print('UUID: {}'.format(n))

    fdu_d = FDU(json.loads(read_file(fdufile)))

    input('press enter to onboard descriptor')
    t1 = time.time()
    res = a.fdu.onboard(fdu_d)
    t2 = time.time()
    t_fdu = t2 - t1
    print(res.to_json())
    e_uuid = res.get_uuid()
    # code.interact(local=locals())

    # display choice
    print('Choose at which node you want to define the fdu:')
    for idx, n in enumerate(nodes):
        print('{}: {}'.format(idx, n))
    index = input('')

    t1 = time.time()
    inst_info = a.fdu.define(e_uuid, nodes[int(index)])
    t2 = time.time()
    t_define = t2 - t1
    print(inst_info.to_json())
    instid = inst_info.get_uuid()

    input('Press enter to configure')
    t1 = time.time()
    a.fdu.configure(instid)
    t2 = time.time()
    t_config = t2 - t1

    input('Press enter to start')
    # cl = pylxd.Client(endpoint='https://192.168.56.112:8443', verify=False)
    cl = pylxd.Client()
    inst = cl.instances.get("c{}".format(instid))
    t1 = time.time()
    a.fdu.start(instid)

    while inst.state().status != 'Running':
        time.sleep(0.01)
    t2 = time.time()
    t_start = t2 - t1

    input('Press get info')
    info = a.fdu.instance_info(instid)
    print(info.to_json())

    input('Press enter to stop')
    t1 = time.time()
    a.fdu.stop(instid)
    t2 = time.time()
    t_stop = t2 - t1

    input('Press enter to clean')
    t1 = time.time()
    a.fdu.clean(instid)
    t2 = time.time()
    t_clean = t2 - t1

    input('Press enter to remove')
    t1 = time.time()
    a.fdu.undefine(instid)
    t2 = time.time()
    t_undef = t2 - t1
    t1 = time.time()
    a.fdu.offload(e_uuid)
    t2 = time.time()
    t_delfdu = t2 - t1

    print(
        "connection: {} \n Fdu: {} \n Define: {} \n Config: {} \n Start: {} \n Stop: {} \n Clean: {} \n Undef: {} \n DelFdu: {}"
        .format(t_conn, t_fdu, t_define, t_config, t_start, t_stop, t_clean,
                t_undef, t_delfdu))

    exit(0)
Example #15
0
    def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None, disk_list=None,
                       availability_zone_index=None, availability_zone_list=None):
        """Adds a VM instance to VIM
        :param start: (boolean) indicates if VM must start or created in pause mode.
        :param image_id: :param flavor_id: image and flavor VIM id to use for the VM
        :param net_list: list of interfaces, each one is a dictionary with:
            'name': (optional) name for the interface.
            'net_id': VIM network id where this interface must be connect to. Mandatory for type==virtual
            'vpci': (optional) virtual vPCI address to assign at the VM. Can be ignored depending on VIM capabilities
            'model': (optional and only have sense for type==virtual) interface model: virtio, e1000, ...
            'mac_address': (optional) mac address to assign to this interface
            'ip_address': (optional) IP address to assign to this interface
            #TODO: CHECK if an optional 'vlan' parameter is needed for VIMs when type if VF and net_id is not provided,
                the VLAN tag to be used. In case net_id is provided, the internal network vlan is used for tagging VF
            'type': (mandatory) can be one of:
                'virtual', in this case always connected to a network of type 'net_type=bridge'
                 'PCI-PASSTHROUGH' or 'PF' (passthrough): depending on VIM capabilities it can be connected to a
                  data/ptp network ot it can created unconnected
                 'SR-IOV' or 'VF' (SRIOV with VLAN tag): same as PF for network connectivity.
                 'VFnotShared'(SRIOV without VLAN tag) same as PF for network connectivity. VF where no other VFs
                        are allocated on the same physical NIC
            'bw': (optional) only for PF/VF/VFnotShared. Minimal Bandwidth required for the interface in GBPS
            'port_security': (optional) If False it must avoid any traffic filtering at this interface. If missing
                            or True, it must apply the default VIM behaviour
            After execution the method will add the key:
            'vim_id': must be filled/added by this method with the VIM identifier generated by the VIM for this
                    interface. 'net_list' is modified
        :param cloud_config: (optional) dictionary with:
            'key-pairs': (optional) list of strings with the public key to be inserted to the default user
            'users': (optional) list of users to be inserted, each item is a dict with:
                'name': (mandatory) user name,
                'key-pairs': (optional) list of strings with the public key to be inserted to the user
            'user-data': (optional) can be a string with the text script to be passed directly to cloud-init,
                or a list of strings, each one contains a script to be passed, usually with a MIMEmultipart file
            'config-files': (optional). List of files to be transferred. Each item is a dict with:
                'dest': (mandatory) string with the destination absolute path
                'encoding': (optional, by default text). Can be one of:
                    'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
                'content' (mandatory): string with the content of the file
                'permissions': (optional) string with file permissions, typically octal notation '0644'
                'owner': (optional) file owner, string with the format 'owner:group'
            'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
        :param disk_list: (optional) list with additional disks to the VM. Each item is a dict with:
            'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
            'size': (mandatory) string with the size of the disk in GB
        :param availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
        :param availability_zone_list: list of availability zones given by user in the VNFD descriptor.  Ignore if
            availability_zone_index is None
        Returns a tuple with the instance identifier and created_items or raises an exception on error
            created_items can be None or a dictionary where this method can include key-values that will be passed to
            the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
            Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
            as not present.
        """
        self.logger.debug('new_vminstance with args: {}'.format(locals()))
        fdu_uuid = '{}'.format(uuid.uuid4())

        flv = self.fos_api.flavor.get(flavor_id)
        img = self.fos_api.image.get(image_id)

        if flv is None:
            raise vimconn.VimConnNotFoundException("Flavor {} not found at VIM".format(flavor_id))
        if img is None:
            raise vimconn.VimConnNotFoundException("Image {} not found at VIM".format(image_id))

        created_items = {
            'fdu_id': '',
            'node_id': '',
            'connection_points': []
        }

        fdu_desc = {
            'name': name,
            'id': fdu_uuid,
            'uuid': fdu_uuid,
            'computation_requirements': flv,
            'image': img,
            'hypervisor': self.hv,
            'migration_kind': 'LIVE',
            'interfaces': [],
            'io_ports': [],
            'connection_points': [],
            'depends_on': [],
            'storage': []
        }

        nets = []
        cps = []
        intf_id = 0
        for n in net_list:
            cp_id = '{}'.format(uuid.uuid4())
            n['vim_id'] = cp_id
            pair_id = n.get('net_id')

            cp_d = {
                'id': cp_id,
                'name': cp_id,
                'vld_ref': pair_id
            }
            intf_d = {
                'name': n.get('name', 'eth{}'.format(intf_id)),
                'is_mgmt': False,
                'if_type': 'INTERNAL',
                'virtual_interface': {
                    'intf_type': n.get('model', 'VIRTIO'),
                    'vpci': n.get('vpci', '0:0:0'),
                    'bandwidth': int(n.get('bw', 100))
                },
                'cp_id': cp_id
            }
            if n.get('mac_address', None) is not None:
                intf_d['mac_address'] = n['mac_address']

            created_items['connection_points'].append(cp_id)
            fdu_desc['connection_points'].append(cp_d)
            fdu_desc['interfaces'].append(intf_d)

            intf_id = intf_id + 1

        if cloud_config is not None:
            configuration = {'conf_type': 'CLOUD_INIT'}
            if cloud_config.get('user-data') is not None:
                configuration['script'] = cloud_config.get('user-data')
            if cloud_config.get('key-pairs') is not None:
                configuration['ssh_keys'] = cloud_config.get('key-pairs')

            if 'script' in configuration:
                fdu_desc['configuration'] = configuration

        self.logger.debug('Eclipse fog05 FDU Descriptor: {}'.format(fdu_desc))

        fdu = FDU(fdu_desc)

        try:
            self.fos_api.fdu.onboard(fdu)
            instance = self.fos_api.fdu.define(fdu_uuid)
            instance_list = self.fos_api.fdu.instance_list(fdu_uuid)
            selected_node = ''
            for n in instance_list:
                instances = instance_list[n]
                if instance.uuid in instances:
                    selected_node = n
            if selected_node == '':
                raise ValueError("Unable to find node for network creation")

            self.logger.debug('Selected node by VIM: {}'.format(selected_node))
            created_items['fdu_id'] = fdu_uuid
            created_items['node_id'] = selected_node

            for cp in fdu_desc['connection_points']:
                nets = self.fos_api.network.list()
                for net in nets:
                    if net.get('uuid') == cp['vld_ref']:
                        self.fos_api.network.add_network_to_node(net, selected_node)

            self.fos_api.fdu.configure(instance.uuid)
            self.fos_api.fdu.start(instance.uuid)

            self.logger.debug('Eclipse fog05 FDU Started {}'.format(instance.uuid))

            created_items['instance_id'] = str(instance.uuid)

            self.fdu_node_map[instance.uuid] = selected_node
            self.logger.debug('new_vminstance returns: {} {}'.format(instance.uuid, created_items))
            return str(instance.uuid), created_items
        except fimapi.FIMAResouceExistingException as free:
            raise vimconn.VimConnConflictException("VM already exists at VIM. Error {}".format(free))
        except Exception as e:
            raise vimconn.VimConnException("Error while instantiating VM {}. Error {}".format(name, e))
Example #16
0
def provider(ip, fdufile, netfile):
    a = FIMAPI(ip)
    a2 = FIMAPI('163.117.139.226')
    # Get the nodes from the domain
    nodes = a.node.list()
    if len(nodes) == 0:
        print('No nodes')
        exit(-1)
    # Print the nodes from the domain
    print('Nodes:')
    for n in nodes:
        print('UUID: {}'.format(n))

    # Load the FDU (descriptors)
    fdu_d = FDU(json.loads(read_file(fdufile)))

    debug_txt = input("\nBegin listening?")
    service_id = ''
    print("\nSERVICE_ID:", service_id)
    debug_txt = input("\nStart listening for federation events....(ENTER)")
    newService_event = ServiceAnnouncementEvent()
    newService = False
    open_services = []
    print("Waiting for federation event....")
    while newService == False:
        new_events = newService_event.get_all_entries()
        for event in new_events:
            service_id = web3.toText(event['args']['id'])
            if GetServiceState(service_id) == 0:
                open_services.append(service_id)
        if len(open_services) > 0:
            print("OPEN = ", len(open_services))
            newService = True
    service_id = open_services[-1]
    winnerChosen_event = PlaceBid(service_id)
    winnerChosen = False
    while winnerChosen == False:
        new_events = winnerChosen_event.get_all_entries()
        for event in new_events:
            event_serviceid = web3.toText(event['args']['_id'])
            if event_serviceid == service_id:
                winnerChosen = True
                break
    am_i_winner = CheckWinner(service_id)
    if am_i_winner == True:
        net_d = GetServiceInfo(service_id, True)
        ########## FEDERATED SERVICE DEPLOYEMENT HERE ###########################################################
        print(net_d)
        if net_d['uuid'] == "6cc2aa30-1dcf-4c93-a57e-433fd0bd498e":
            print("UUID match")
        else:
            print("UUID does not match")

        # Create network based on the descriptor
        # input("Press enter to create network")
        # Get info if the network is created
        print(net_d['uuid'])
        print(a2.network.list())
        net_info = get_net_info(a2, net_d['uuid'])
        print('Net info {}'.format(net_info))

        a.network.add_network(net_info)
        # Add the created network to the node (n1)
        input('press enter to network creation')
        a.network.add_network_to_node(net_info['uuid'], n2)

        #  On-board the FDU
        input('press enter to onboard descriptor')
        res = a.fdu.onboard(fdu_d)
        # Get the identifier of the on-boarded FDU
        e_uuid = res.get_uuid()
        # Define an instance of the on-boarded FDU
        input('Press enter to define')
        inst_info = a.fdu.define(e_uuid)
        # Get the ID of the defined FDU instance
        print(inst_info.to_json())
        instid = inst_info.get_uuid()

        # Configure the defined FDU instance
        input('Press enter to configure')
        a.fdu.configure(instid)

        # Start the configured FDU instance
        input('Press enter to start')
        a.fdu.start(instid)
        # Get the info of the started FDU instance
        input('Press get info')
        info = a.fdu.instance_info(instid)
        print(info.to_json())

        ######################### UNTIL HERE ####################################################################
        ServiceDeployed(service_id)
    else:
        print("I am not a Winner")

    input('Press enter to terminate')

    a.fdu.terminate(instid)
    a.fdu.offload(e_uuid)
    exit(0)
Example #17
0
def read_file(filepath):
    with open(filepath, 'r') as f:
        data = f.read()
    return data


api = FIMAPI('192.168.31.232')
uuid_fisso = '01369aac-9965-4277-96c0-280cf007e953'
uuid_portatile = '9806ff42-cecc-48c1-9f44-da51955d4732'

descs = json.loads(read_file("./system.json"))
for label in descs["devices"]:
    print(label)
    print(descs["devices"][label])
    desc = json.loads(read_file("./" + descs["devices"][label]["desc"]))
    fdu_descriptor = FDU(desc)
    fduD = api.fdu.onboard(fdu_descriptor)
    fdu_id = fduD.get_uuid()
    inst_info = api.fdu.define(fdu_id, '9806ff42-cecc-48c1-9f44-da51955d4732')
    descs["devices"][label]["nuuid"] = uuid_portatile
    descs["devices"][label]["fuuid"] = fdu_id
    descs["devices"][label]["iuuid"] = inst_info.get_uuid()
    api.fdu.configure(inst_info.get_uuid())
    # env = "nuuid=" + uuid_portatile + \
    #       "fuuid=" + fdu_id + \
    #       "iuuid=" + inst_info.get_uuid() + \
    #       "port=" + descs["devices"][label]["connector"].get("port", str(9500)) + \
    #       "ip=" + descs["devices"][label]["connector"].get("ip", str(9500)) + \
    #       "broker=" + descs["devices"][label]["connector"].get("broker", str(9500))
    api.fdu.start(inst_info.get_uuid(), "")
with open("./system.json", "w") as outp:
    def __init__(self):
        # fog05 env parameters loading
        super().__init__()
        self.nuuid = os.environ["nuuid"] if "nuuid" in os.environ else "no_nuiid"
        self.fuuid = os.environ["fuuid"] if "fuuid" in os.environ else "no_fuuid"
        self.iuuid = os.environ["iuuid"] if "iuuid" in os.environ else "manager05"
        self.label = os.environ["label"] if "label" in os.environ else "manager05"
        # if system instance description is given through Env variable
        if "system" in os.environ:
            self.config = json.loads(os.environ["system"].replace("^", ", ").replace("%", "\"").replace(":", ": "))
        else:
            self.config = json.loads(fos_utils.read_file("/var/fos/demo/deploy/system_instance.json"))
        self.mappings = json.loads(fos_utils.read_file(os.environ["config"]))
        self.lock = threading.Lock()

        self.critic = False
        if "A" in self.mappings.keys() and "B" in self.mappings.keys():
            from fog05 import FIMAPI
            from fog05_sdk.interfaces.FDU import FDU
            self.critic = True
            self.critic_nodes = {self.config["devices"]["A"]["nuuid"], self.config["devices"]["B"]["nuuid"]}
            self.fos_api = FIMAPI(self.config.get("fimapi", "192.168.31.232"))
            print("+++ this is the critic manager +++")
            if "json" in self.config["fdu_control"]:  # if descriptor is a filename, load it in fog05
                print("fog05 onboarding " + self.config["fdu_control"])
                fdu_descriptor = FDU(json.loads(fos_utils.read_file(self.config["fdu_control"])))
                fduD = self.fos_api.fdu.onboard(fdu_descriptor)
                self.config["fdu_control"] = fduD.get_uuid()

        # rebuild with factory
        # iterate on keys (i.e. labels)
        # create a set of all the managed labels
        devices = set(self.mappings.keys())
        for label in self.mappings.keys():
            for mapping in self.mappings[label]:
                devices.add(mapping["label"])
        print(str(devices))
        # for device in self.config["devices"]:
        for device in devices:
            self.devices[device] = {}
            self.devices[device]["connector"] = get_connector(self.config["devices"][device], self.payload_handler)
            # self.devices[device["label"]] = get_connector(device["connector"], self.payload_handler)

        for label in self.devices.keys():
            if "sens" in self.config["devices"][label]["desc"]:
                payload = {"action": "PUT", "state": "on"}
                # print("Manager turning on sensor " + label + " with msg " + str(payload))
                self.devices[label]["connector"].send("PUT", fos_utils.encode_state(payload))
        # for device in self.config["devices"]:
        # (self, nuuid, fuuid, iuuid, broker, payload_handler)
        # self.devices[device["label"]] = Mqtt05_comm(device["nuuid"],
        #                                             device["fuuid"],
        #                                             device["iuuid"],
        #                                             device["broker"],
        #                                             self.payload_handler)
        # # (self, ip, port, label, payload_handler)
        # self.devices[device["label"]] = Coap05_comm(device["ip"],
        #                                             device["port"],
        #                                             device["iuuid"],
        #                                             device["label"],
        #                                             self.payload_handler)
        asyncio.get_event_loop().run_forever()