示例#1
0
def create_patch(original, target, output):
    with open(original) as original_file, open(target) as target_file:
        original_json = json.load(original_file)
        target_json = json.load(target_file)
        result = json_merge_patch.create_patch(original_json, target_json)

    patch = json.dumps(result, indent=4)

    if output:
        with open(output, 'w+') as output_file:
            output_file.write(patch)
    else:
        print(patch)
示例#2
0
    def take_action(self, parsed_args):
        vnf_client = self.app.eclsdk.conn.virtual_network_appliance

        target = vnf_client.\
            get_virtual_network_appliance(
            parsed_args.virtual_network_appliance)

        rows = ['ID', 'Name', 'Description', 'Tags']
        row_headers = rows

        # serialize request parmeter as JSON
        requested_param = {}
        if hasattr(parsed_args, 'name') and parsed_args.name is not None:
            requested_param['name'] = parsed_args.name
        if hasattr(parsed_args,
                   'description') and parsed_args.description is not None:
            requested_param['description'] = parsed_args.description
        if hasattr(parsed_args, 'tags') and parsed_args.tags is not None:
            tags = parsed_args.tags or '{}'
            try:
                requested_param['tags'] = json.loads(tags)
            except Exception:
                msg = _("You must specify JSON object format")
                raise exceptions.CommandError(msg)

        # serialize current parmeter as JSON
        current_param = {
            'name': target.name,
            'description': target.description,
            'tags': target.tags,
        }
        origin_param = copy.deepcopy(current_param)
        merged_param = jmp.merge(current_param, requested_param)
        patch = jmp.create_patch(origin_param, merged_param)

        if target.tags != requested_param['tags']:
            patch[tags] = requested_param['tags']

        if not patch:
            msg = _('No change will be expected')
            raise exceptions.CommandError(msg)

        data = vnf_client.update_virtual_network_appliance(
            parsed_args.virtual_network_appliance, **patch)

        _set_interface_names_for_display(data)

        return row_headers, utils.get_item_properties(data, rows)
示例#3
0
 def does_this_create_or_change_record(self):
     self._build_type_and_record(create_if_dont_exist=False)
     # If record not currently exist, it's creating something
     if not isinstance(self.record, Record):
         return True
     # If does exist, need to check content for changes
     edit = Edit()
     edit.record = self.record
     edit.mode = self.mode
     edit.data_key = self.key
     edit.data = self.data
     new_cached_data = apply_edit_get_new_cached_data(edit)
     patch = json_merge_patch.create_patch(self.record.cached_data,
                                           new_cached_data)
     has_patch = bool(patch)
     return has_patch
示例#4
0
    def take_action(self, parsed_args):
        vnf_client = self.app.eclsdk.conn.virtual_network_appliance

        target = vnf_client.\
            get_virtual_network_appliance(
            parsed_args.virtual_network_appliance)

        rows = ROWS_FOR_SHOW
        row_headers = rows

        aaps = []
        adds = parsed_args.adds or []
        delete_aaps = []
        deletes = parsed_args.deletes or []

        if len(adds) == 0 and len(deletes) == 0:
            msg = _("No options are specified.")
            raise exceptions.CommandError(msg)

        VALID_KEYS = [
            'interface-slot-no', 'ip-address', 'mac-address', 'type', 'vrid'
        ]
        for aap_str in adds:
            aap_info = {}
            aap_info.update(utils.parse_vna_interface(aap_str, VALID_KEYS))
            aaps.append(aap_info)

        for aap_str in deletes:
            slot_no = re.sub(r'^interface-slot-no=(\d+)$', '\\1', aap_str)
            if not re.match(r'^\d+$', slot_no):
                msg = 'No interface number is specified.'
                raise exceptions.CommandError(msg)

            delete_aaps.append(slot_no)

        # duplicate interfaces check
        tmp_aaps = []
        for aap in aaps:
            tmp_aaps.append(aap.get('interface-slot-no'))

        for slot_no in delete_aaps:
            tmp_aaps.append(slot_no)

        if len(tmp_aaps) != len(set(tmp_aaps)):
            msg = _("Interfaces are duplicates")
            raise exceptions.CommandError(msg)

        requested_aap_object = {}
        for aap in aaps:
            slot_no = aap.get('interface-slot-no', None)
            if not slot_no:
                msg = 'No interface number is specified.'
                raise exceptions.CommandError(msg)

            # create key <-> value if not exist.
            if_key = 'interface_' + str(slot_no)
            requested_aap_object.setdefault(if_key,
                                            {'allowed_address_pairs': []})

            ip_address = aap.get('ip-address')
            mac_address = aap.get('mac-address')
            aap_type = aap.get('type')
            vrid = aap.get('vrid')

            each_aap_info = {'mac_address': '', 'type': '', 'vrid': None}

            if ip_address:
                each_aap_info.update({'ip_address': ip_address})

            if mac_address:
                each_aap_info.update({'mac_address': mac_address})

            if aap_type:
                each_aap_info.update({'type': aap_type})

            if vrid:
                try:
                    each_aap_info.update({'vrid': int(vrid)})
                except ValueError:
                    msg = 'vrid should be a positive number 1〜255'
                    raise exceptions.CommandError(msg)

            requested_aap_object[if_key]['allowed_address_pairs'].\
                append(each_aap_info)

            if mac_address and (aap_type == "vrrp" or vrid):
                msg = 'mac_address and vrrp type cannot be set ' \
                      'at the same time.'
                raise exceptions.CommandError(msg)

        for slot_no in delete_aaps:
            if_key = 'interface_' + slot_no
            requested_aap_object[if_key] = {'allowed_address_pairs': []}

        current_interface_object = copy.deepcopy(target.interfaces)
        merged_interface_object = jmp.merge(current_interface_object,
                                            requested_aap_object)
        patch = jmp.create_patch(target.interfaces, merged_interface_object)

        patch = {'interfaces': patch}
        if not patch:
            msg = _('No change will be expected')
            raise exceptions.CommandError(msg)

        data = vnf_client.update_virtual_network_appliance(
            parsed_args.virtual_network_appliance, **patch)

        _set_interfaces_for_display(data)

        return row_headers, utils.get_item_properties(data, rows)
示例#5
0
    def take_action(self, parsed_args):
        vnf_client = self.app.eclsdk.conn.virtual_network_appliance

        target = vnf_client.\
            get_virtual_network_appliance(
            parsed_args.virtual_network_appliance)

        rows = ROWS_FOR_SHOW
        row_headers = rows

        interfaces = []
        VALID_KEYS = [
            'slot-no', 'name', 'description', 'tags', 'net-id', 'fixed-ips'
        ]
        for if_str in parsed_args.interface:
            # if_info = {"net-id": "", "fixed-ips": "",
            #            "slot-no": ""}
            if_info = {}
            if_info.update(utils.parse_vna_interface(if_str, VALID_KEYS))

            interfaces.append(if_info)

        # conflict interfaces
        tmp_interfaces = []
        for interface in interfaces:
            tmp_interfaces.append(interface.get('slot-no'))

        if len(tmp_interfaces) != len(set(tmp_interfaces)):
            msg = _("Interfaces are duplicates")
            raise exceptions.CommandError(msg)

        requested_interface_object = {}
        tag_flag = False
        for interface in interfaces:
            slot_no = interface.get('slot-no')
            if_key = 'interface_' + str(slot_no)

            network_id = interface.get('net-id')
            fixed_ips_tmp = interface.get('fixed-ips')

            each_if_info = {}

            if 'name' in interface:
                name = interface.get('name', '')
                each_if_info.update({'name': name})

            if 'description' in interface:
                description = interface.get('description', '')
                each_if_info.update({'description': description})

            if 'tags' in interface:
                tag_flag = True
                tags = interface.get('tags')
                tags = tags if tags else '{}'
                try:
                    obj = json.loads(tags)
                except Exception:
                    msg = _("You must specify JSON object format")
                    raise exceptions.CommandError(msg)

                each_if_info.update({'tags': obj})

            if 'net-id' in interface:
                each_if_info.update({'network_id': network_id})

            if 'fixed-ips' in interface:
                fixed_ips = []
                if fixed_ips_tmp:
                    fixed_ips = [{
                        'ip_address': ip
                    } for ip in fixed_ips_tmp.split(':')]
                each_if_info.update({'fixed_ips': fixed_ips})

            interface_tmp = {if_key: each_if_info}
            requested_interface_object.update(interface_tmp)

        current_interface_object = copy.deepcopy(target.interfaces)
        merged_interface_object = jmp.merge(current_interface_object,
                                            requested_interface_object)
        patch = jmp.create_patch(target.interfaces, merged_interface_object)

        if patch == {} and tag_flag == False:
            msg = _('No change will be expected')
            raise exceptions.CommandError(msg)

        # ridding keys of unnecessary keys
        def __ridding_none_value(current, json_keys):
            for json_key in json_keys:
                if type(current) == 'dict':
                    next_current = tmp_current = current[json_key]
                    if tmp_current is None:
                        del current[json_key]
                    else:
                        next_keys = tmp_current.keys()
                        if len(next_keys) > 0:
                            current[json_key] = __ridding_none_value(
                                next_current, next_keys)
            return current

        if len(patch.keys()) > 0:
            patch = __ridding_none_value(patch, patch.keys())

        # replacing patched tags with requested tags
        for if_key in requested_interface_object.keys():
            interface = requested_interface_object[if_key]
            if 'tags' in interface:
                patch[if_key]['tags'] = interface.get('tags')

        patch = {'interfaces': patch}
        data = vnf_client.update_virtual_network_appliance(
            parsed_args.virtual_network_appliance, **patch)

        _set_interfaces_for_display(data)

        return (row_headers, utils.get_item_properties(data, rows))
    def take_action(self, parsed_args):
        vnf_client = self.app.eclsdk.conn.virtual_network_appliance

        target = vnf_client.\
            get_virtual_network_appliance(
            parsed_args.virtual_network_appliance)

        rows = ROWS_FOR_SHOW
        row_headers = rows

        aaps = []
        VALID_KEYS = [
            'interface-slot-no', 'ip-address', 'mac-address', 'type', 'vrid'
        ]
        for aap_str in parsed_args.allowed_address_pair:
            aap_info = {}
            aap_info.update(utils.parse_vna_interface(aap_str))

            for k in aap_info.keys():
                if k not in VALID_KEYS:
                    msg = 'Invalid key %s is specified.' % k
                    raise exceptions.CommandError(msg)

            aaps.append(aap_info)

        requested_aap_object = {}
        for aap in aaps:
            slot_no = aap.get('interface-slot-no', None)
            if not slot_no:
                msg = 'No interface number is specified.'
                raise exceptions.CommandError(msg)

            # create key <-> value if not exist.
            if_key = 'interface_' + str(slot_no)
            requested_aap_object.setdefault(if_key,
                                            {'allowed_address_pairs': []})

            ip_address = aap.get('ip-address')
            mac_address = aap.get('mac-address')
            aap_type = aap.get('type')
            vrid = aap.get('vrid')

            each_aap_info = {'mac_address': '', 'type': '', 'vrid': None}

            if ip_address:
                each_aap_info.update({'ip_address': ip_address})

            if mac_address:
                each_aap_info.update({'mac_address': mac_address})

            if aap_type:
                each_aap_info.update({'type': aap_type})

            if vrid:
                try:
                    each_aap_info.update({'vrid': int(vrid)})
                except ValueError:
                    msg = 'vrid should be a positive number 1〜255'
                    raise exceptions.CommandError(msg)

            requested_aap_object[if_key]['allowed_address_pairs'].\
                append(each_aap_info)

            if mac_address and (aap_type == "vrrp" or vrid):
                msg = 'mac_address and vrrp type cannot be set ' \
                      'at the same time.'
                raise exceptions.CommandError(msg)

        current_interface_object = copy.deepcopy(target.interfaces)
        merged_interface_object = jmp.merge(current_interface_object,
                                            requested_aap_object)
        patch = jmp.create_patch(target.interfaces, merged_interface_object)

        patch = {'interfaces': patch}
        if not patch:
            msg = _('No change will be expected')
            raise exceptions.CommandError(msg)

        data = vnf_client.update_virtual_network_appliance(
            parsed_args.virtual_network_appliance, **patch)

        _set_interfaces_for_display(data)

        return row_headers, utils.get_item_properties(data, rows)
    def take_action(self, parsed_args):
        vnf_client = self.app.eclsdk.conn.virtual_network_appliance

        target = vnf_client.\
            get_virtual_network_appliance(
            parsed_args.virtual_network_appliance)

        rows = ROWS_FOR_SHOW
        row_headers = rows

        interfaces = []
        VALID_KEYS = ['slot-no', 'net-id', 'fixed-ips']
        for if_str in parsed_args.interface:
            # if_info = {"net-id": "", "fixed-ips": "",
            #            "slot-no": ""}
            if_info = {}
            if_info.update(utils.parse_vna_interface(if_str))
            for k in if_info.keys():
                if k not in VALID_KEYS:
                    msg = 'Invalid key %s is specified.' % k
                    raise exceptions.CommandError(msg)

            interfaces.append(if_info)

        requested_interface_object = {}
        for interface in interfaces:
            slot_no = interface.get('slot-no')
            if_key = 'interface_' + str(slot_no)

            network_id = interface.get('net-id')
            fixed_ips_tmp = interface.get('fixed-ips')

            each_if_info = {}

            if network_id:
                each_if_info.update({'network_id': network_id})

            if fixed_ips_tmp:
                fixed_ips = [{
                    'ip_address': ip
                } for ip in fixed_ips_tmp.split(':')]
                each_if_info.update({'fixed_ips': fixed_ips})

            interface_tmp = {if_key: each_if_info}
            requested_interface_object.update(interface_tmp)

        current_interface_object = copy.deepcopy(target.interfaces)
        merged_interface_object = jmp.merge(current_interface_object,
                                            requested_interface_object)
        patch = jmp.create_patch(target.interfaces, merged_interface_object)

        patch = {'interfaces': patch}
        if not patch:
            msg = _('No change will be expected')
            raise exceptions.CommandError(msg)

        data = vnf_client.update_virtual_network_appliance(
            parsed_args.virtual_network_appliance, **patch)

        _set_interfaces_for_display(data)

        return (row_headers, utils.get_item_properties(data, rows))
    def take_action(self, parsed_args):
        vnf_client = self.app.eclsdk.conn.virtual_network_appliance

        target = vnf_client.\
            get_virtual_network_appliance(
            parsed_args.virtual_network_appliance)

        rows = [
            'ID',
            'Name',
            'Description',
            'Interface Names',
        ]
        row_headers = rows

        interfaces = []
        VALID_KEYS = ['slot-no', 'name']

        if parsed_args.interface:
            for if_str in parsed_args.interface:
                if_names = {}
                if_names.update(utils.parse_vna_interface(if_str))
                for k in if_names.keys():
                    if k not in VALID_KEYS:
                        msg = 'Invalid key %s is specified.' % k
                        raise exceptions.CommandError(msg)
                interfaces.append(if_names)

        # serialize request parmeter as JSON
        requested_param = {}
        if hasattr(parsed_args, 'name'):
            requested_param['name'] = parsed_args.name
        if hasattr(parsed_args, 'description'):
            requested_param['description'] = parsed_args.description
        for interface in interfaces:
            if 'interfaces' not in requested_param:
                requested_param['interfaces'] = {}
            slot_no = interface.get('slot-no')
            if_key = 'interface_%s' % slot_no
            name = interface.get('name')
            each_if_info = {}
            if name:
                each_if_info.update({'name': name})
            requested_param['interfaces'].update({if_key: each_if_info})

        # serialize current parmeter as JSON
        current_param = {
            'name': target.name,
            'description': target.description,
        }
        current_param['interfaces'] = copy.deepcopy(target.interfaces)
        origin_param = copy.deepcopy(current_param)
        merged_param = jmp.merge(current_param, requested_param)
        patch = jmp.create_patch(origin_param, merged_param)

        if not patch:
            msg = _('No change will be expected')
            raise exceptions.CommandError(msg)

        data = vnf_client.update_virtual_network_appliance(
            parsed_args.virtual_network_appliance, **patch)

        _set_interface_names_for_display(data)

        return row_headers, utils.get_item_properties(data, rows)