Exemple #1
0
def save_scenario():
    """
    save scenario setting.
    :return: the error list for the edited scenario setting.
    """
    scenario_config_data = request.json if request.method == "POST" else request.args
    print("save_scenario")
    print(scenario_config_data)

    xml_configs = \
        get_xml_configs(scenario_config_data['old_scenario_name'].startswith('user_defined_'))
    board_type = xml_configs[1]
    scenario_config = xml_configs[3]

    if board_type is None or xml_configs[0] is None:
        return {'status': 'fail',
                'error_list': {'error': 'Please select the board info before this operation.'}}

    scenario_path = os.path.join(current_app.config.get('CONFIG_PATH'), board_type)
    old_scenario_name = scenario_config_data['old_scenario_name']
    if scenario_config_data['old_scenario_name'].startswith('user_defined_'):
        old_scenario_name = scenario_config_data['old_scenario_name'][13:]
    scenario_config.set_curr(old_scenario_name)
    for key in scenario_config_data:
        if key not in ['old_scenario_name', 'new_scenario_name', 'board_info_file',
                       'board_info_upload']:
            if isinstance(scenario_config_data[key], list):
                scenario_config.set_curr_list(scenario_config_data[key], *tuple(key.split(',')))
            else:
                scenario_config.set_curr_value(scenario_config_data[key], *tuple(key.split(',')))

    tmp_scenario_file = os.path.join(scenario_path, 'user_defined',
                                     'tmp_'+scenario_config_data['new_scenario_name']+'.xml')
    # if os.path.isfile(tmp_scenario_file):
    #     os.remove(tmp_scenario_file)
    scenario_config.save('tmp_'+scenario_config_data['new_scenario_name'])

    # call validate function
    error_list = {}
    new_scenario_name = scenario_config_data['new_scenario_name']
    rename = False
    try:
        (error_list, vm_info) = validate_scenario_setting(
            os.path.join(os.path.dirname(os.path.abspath(__file__)), 'res', xml_configs[0]+'.xml'),
            tmp_scenario_file)
        print('vm_info: ', vm_info)
    except Exception as error:
        return {'status': 'fail', 'file_name': new_scenario_name,
                'rename': rename, 'error_list': {'error': str(error)}}

    print('error_list: ', error_list)

    if not error_list:
        old_scenario_path = os.path.join(scenario_path, old_scenario_name + '.xml')
        if scenario_config_data['old_scenario_name'].startswith('user_defined_'):
            old_scenario_path = os.path.join(scenario_path, 'user_defined',
                                             old_scenario_name + '.xml')

        # check name conflict
        new_scenario_path = os.path.join(scenario_path, 'user_defined',
                                         scenario_config_data['new_scenario_name']+'.xml')
        if old_scenario_path != new_scenario_path and os.path.isfile(new_scenario_path):
            new_scenario_name = new_scenario_name + '_' + datetime.now().strftime('%Y%m%d%H%M%S')
            rename = True

        if os.path.isfile(old_scenario_path) \
                and scenario_config_data['old_scenario_name'].startswith('user_defined_'):
            os.remove(old_scenario_path)
        scenario_config.save(new_scenario_name)

    if os.path.isfile(tmp_scenario_file):
        os.remove(tmp_scenario_file)

    return {'status': 'success', 'file_name': new_scenario_name,
            'rename': rename, 'error_list': error_list}
Exemple #2
0
def save_scenario():
    """
    save scenario setting.
    :return: the error list for the edited scenario setting.
    """
    scenario_config_data = request.json if request.method == "POST" else request.args
    xml_configs = get_xml_configs()
    board_type = xml_configs[1]
    scenario_config = xml_configs[3]

    if board_type is None or xml_configs[0] is None:
        return {
            'status': 'fail',
            'error_list': {
                'error': 'Please select the board info before this operation.'
            }
        }

    scenario_path = os.path.join(current_app.config.get('CONFIG_PATH'),
                                 board_type)
    old_scenario_name = scenario_config_data['old_scenario_name']
    scenario_config.set_curr(old_scenario_name)
    for key in scenario_config_data:
        if key not in [
                'old_scenario_name', 'new_scenario_name', 'generator',
                'add_vm_type'
        ]:
            if isinstance(scenario_config_data[key], list):
                scenario_config.set_curr_list(scenario_config_data[key],
                                              *tuple(key.split(',')))
            else:
                scenario_config.set_curr_value(scenario_config_data[key],
                                               *tuple(key.split(',')))

    generator = scenario_config_data['generator']
    if generator is not None:
        if generator == 'remove_vm_kata':
            scenario_config.delete_curr_key('vm:desc=specific for Kata')
            assign_vm_id(scenario_config)
        elif generator == 'add_vm_kata':
            vm_list = []
            for vm in scenario_config.get_curr_root().getchildren():
                if vm.tag == 'vm':
                    vm_list.append(vm.attrib['id'])
            if len(vm_list) >= MAX_VM_NUM:
                return {
                    'status': 'fail',
                    'error_list': {
                        'error':
                        'Can not add a new VM. Max VM number is {}.'.format(
                            MAX_VM_NUM)
                    }
                }

            # clone vm kata from generic config
            generic_scenario_config = get_generic_scenario_config(
                scenario_config)
            generic_scenario_config_root = generic_scenario_config.get_curr_root(
            )
            elem_kata = None
            for vm in generic_scenario_config_root.getchildren():
                if 'desc' in vm.attrib and vm.attrib[
                        'desc'] == 'specific for Kata':
                    elem_kata = vm
                    break
            if elem_kata is not None:
                scenario_config.clone_curr_elem(elem_kata)
            assign_vm_id(scenario_config)
        elif generator.startswith('add_vm:'):
            vm_list = []
            for vm in scenario_config.get_curr_root().getchildren():
                if vm.tag == 'vm':
                    vm_list.append(vm.attrib['id'])
            if len(vm_list) >= MAX_VM_NUM:
                return {
                    'status': 'fail',
                    'error_list': {
                        'error':
                        'Can not add a new VM. Max VM number is {}.'.format(
                            MAX_VM_NUM)
                    }
                }
            curr_vm_id = generator.split(':')[1]
            add_vm_type = scenario_config_data['add_vm_type']
            generic_scenario_config = get_generic_scenario_config(
                scenario_config, add_vm_type)
            generic_scenario_config_root = generic_scenario_config.get_curr_root(
            )
            vm_to_add = []
            if str(curr_vm_id) == '-1':
                curr_vm_index = 1
            else:
                curr_vm_index = len(vm_list) + 1
                for i in range(len(vm_list)):
                    if curr_vm_id == vm_list[i]:
                        curr_vm_index = i + 2
                        break
            for vm in generic_scenario_config_root.getchildren():
                if vm.tag == 'vm':
                    for i in range(0, MAX_VM_NUM):
                        if str(i) not in vm_list:
                            break
                    vm.attrib['id'] = str(i)
                    vm_to_add.append(vm)
            for vm in vm_to_add:
                scenario_config.insert_curr_elem(curr_vm_index, vm)
                curr_vm_index += 1
            assign_vm_id(scenario_config)
        elif generator.startswith('remove_vm:'):
            remove_vm_id = generator.split(':')[1]
            scenario_config.delete_curr_key('vm:id=' + remove_vm_id.strip())
            assign_vm_id(scenario_config)

    scenario_config.set_curr_attr('board', board_type)
    scenario_config.set_curr_attr('scenario',
                                  scenario_config_data['new_scenario_name'])

    tmp_scenario_file = os.path.join(
        scenario_path, 'user_defined',
        'tmp_' + scenario_config_data['new_scenario_name'] + '.xml')
    # if os.path.isfile(tmp_scenario_file):
    #     os.remove(tmp_scenario_file)
    scenario_config.save('tmp_' + scenario_config_data['new_scenario_name'])

    # call validate function
    error_list = {}
    new_scenario_name = scenario_config_data['new_scenario_name']
    rename = False
    try:
        if generator is None or not (generator.startswith('add_vm:')
                                     or generator.startswith('remove_vm:')):
            (error_list, vm_info) = validate_scenario_setting(
                os.path.join(os.path.dirname(os.path.abspath(__file__)), 'res',
                             xml_configs[0] + '.xml'), tmp_scenario_file)
    except Exception as error:
        if os.path.isfile(tmp_scenario_file):
            os.remove(tmp_scenario_file)
        return {
            'status': 'fail',
            'file_name': new_scenario_name,
            'rename': rename,
            'error_list': {
                'error': str(error)
            }
        }

    if not error_list:
        scenario_config.save(new_scenario_name)
        if old_scenario_name != new_scenario_name:
            os.remove(
                os.path.join(scenario_path, 'user_defined',
                             old_scenario_name + '.xml'))

    if os.path.isfile(tmp_scenario_file):
        os.remove(tmp_scenario_file)

    return {
        'status': 'success',
        'file_name': new_scenario_name,
        'rename': rename,
        'error_list': error_list
    }