def setInterfaceIpAddress(if_name, ip_addr, pfix_len): # Populate the attributes for the CPS Object # From the arguments if_index = cps_operations.getIfIndexFromName(if_name) ip_attributes = { "base-ip/ipv4/ifindex": if_index, "ip": ip_addr, "prefix-length": pfix_len } # Create CPS Object cps_utils.add_attr_type('base-ip/ipv4/address/ip', "ipv4") cps_obj = cps_utils.CPSObject('base-ip/ipv4/address', data=ip_attributes) # Create the CPS Transaction for object create cps_update = ('create', cps_obj.get()) transaction = cps_utils.CPSTransaction([cps_update]) # Verify return value ret = transaction.commit() if not ret: raise RuntimeError("Error changing interface ip address") Utils.cliLogger( "CPSOPErations: Changed interface ip address: " + ip_addr, 0)
def print_obj(obj): cps_utils.print_obj(obj) cps_obj = cps_utils.CPSObject(obj=obj) ifindex = cps_obj.get_attr_data("ifindex") ifname = nas_os_utils.if_indextoname(ifindex) print "base-sflow/entry/ifname = " + ifname print "\n\n"
def read(self, path): '''Read - to be mapped on a JSON RPC read for a this entity argument is a json rpc path. ''' (yin_form, data) = yin_path(path) needs_adjust = True cps_obj = None try: cps_obj = cps_utils.CPSObject(yin_form, data=data) except ValueError: return None k = [cps_obj.get()] res_list = [] cps.get(k, res_list) result = [] for element in res_list: if needs_adjust: yin_form = prep_path(yin_form, element) needs_adjust = False result.append(convert_result(yin_form, element)) cps_type = cps.type(yin_form) try: if cps_type["attribute_type"] == "list": if data != {}: if len(result) == 0: return None else: return result[0] else: return result return result[0] except IndexError: return None
def deleteIpv4RouteEntry(route_prefix, prefix_len): # deleteIpv4RouteEntry("10.1.1.0", 24) ip_version = "ipv4" obj = cps_utils.CPSObject('base-route/obj/entry') obj.add_attr("vrf-id", 0) obj.add_attr("af", socket.AF_INET) ip = net.IPNetwork(route_prefix) obj.add_attr_type("route-prefix", ip_version) obj.add_attr("route-prefix", str(ip.network)) obj.add_attr("prefix-len", int(prefix_len)) cps_update = ('delete', obj.get()) transaction = cps_utils.CPSTransaction([cps_update]) ret = transaction.commit() if not ret: raise RuntimeError("Error deleting Route") Utils.timeLogger("CPSOperations| CPS delete route:") Utils.cliLogger( "CPSOPErations: Deleted route: " + route_prefix + "/" + str(prefix_len), 0)
def _prep_cps_op(self, orig_path, path, data): '''Shared code for transactional CPS ops''' (oyin_form, opath_data) = yin_path(orig_path) data = _prep_data(oyin_form, data) (yin_form, path_data) = yin_path(path) data.update(path_data) return cps_utils.CPSObject(yin_form, data=data)
def mirror_delete(mirr_id): cfg_mo = cps_utils.CPSObject('base-mirror/entry') cfg_mo.add_attr('id', mirr_id) r = cps_utils.CPSTransaction([('delete', cfg_mo.get())]).commit() if r == False: print ("Error deleting mirror" + str(mirr_id)) else: print ("Successfully deleted mirror" + str(mirr_id))
def get_if_name(index=0): global ifs if not ifs: ifs = nas_os_if_utils.nas_os_if_list() while not ifs: ifs = nas_os_if_utils.nas_os_if_list() time.sleep(1) if not ifs: raise RuntimeError("No interfaces found") if index < len(ifs): if_wr_obj = cps_utils.CPSObject(obj=ifs[index]) else: if_wr_obj = cps_utils.CPSObject(obj=ifs[0]) return if_wr_obj.get_attr_data('if/interfaces/interface/name')
def mirror_create(dst_intf): cfg_mo = cps_utils.CPSObject('base-mirror/entry') cfg_mo.add_attr('type', 1) # Local SPAN cfg_mo.add_attr('dst-intf', dst_intf) print cfg_mo.get() r = cps_utils.CPSTransaction([('create', cfg_mo.get())]).commit() if r == False: raise RuntimeError( "Mirror creation failed on interface " + str(dst_intf)) ret_obj = r[0]['change'] mirr_wr_obj = cps_utils.CPSObject('base-mirror/entry', obj=ret_obj) mirr_id = mirr_wr_obj.get_attr_data('id') print "Successfully installed Mirror Id = ", mirr_id print "Opaque data = " + mirr_wr_obj.get_attr_data('opaque-data') return mirr_id, ret_obj['data']['base-mirror/entry/opaque-data']
def del_filter(name): '''Delete a filter based on its unique ID returned by set_filters''' cps_obj = cps_utils.CPSObject(module='base-acl/entry', data={ 'table-id': TBL_ID, 'name': name }) cps_upd = ('delete', cps_obj.get()) cps_trans = cps_utils.CPSTransaction([cps_upd]) return cps_trans.commit()
def get_ports(bridge): '''A simple function to return the openswitch perception of the port list in a vlan''' cps_obj = cps_utils.CPSObject(IFOBJ, data={IFNAME: bridge.encode('ascii')}) cps_result = [] if not cps.get([cps_obj.get()], cps_result): return None result = [] for value in cps_result[0]['data'][PORTS]: result.append(cps_utils.cps_attr_types_map.from_data(PORTS, value)) return result
def get_first_phy_port(): ret_data_list = nas_os_if_utils.nas_os_if_list() if not ret_data_list: return None name_list = [] for ret_data in ret_data_list: cps_obj = cps_utils.CPSObject(obj=ret_data) port_name = cps_obj.get_attr_data('if/interfaces/interface/name') name_list.append(port_name) name_list.sort() return name_list[0]
def get_cpu_port(): ifs = nas_os_if_utils.nas_os_cpu_if() cpu_ifs = [] cpu_ifnames = [] for intf in ifs: obj = cps_utils.CPSObject(obj=intf) try: iftype = obj.get_attr_data('if/interfaces/interface/type') except ValueError: continue if iftype != base_cpu_intf_type: continue cpu_ifnames.append(obj.get_attr_data('if/interfaces/interface/name')) cpu_ifs.append(obj.get_attr_data('dell-base-if-cmn/if/interfaces/interface/if-index')) return cpu_ifs, cpu_ifnames
def build_route_obj(route_ip, version): ver, prefix_len, ip_addr = nas_route.extract_ip_netmask(route_ip) if version != 'ipv' + str(ver): print 'Improper IP Address' usage() obj = cps_utils.CPSObject(nas_route.get_route_key()[int(0)]) obj.add_attr("vrf-id", 0) if version == 'ipv4': obj.add_attr("af", socket.AF_INET) elif version == 'ipv6': obj.add_attr("af", socket.AF_INET6) obj.add_attr_type("route-prefix", version) obj.add_attr("route-prefix", str(ip_addr)) obj.add_attr("prefix-len", int(prefix_len)) return obj
def addIpv4RouteEntry(route_prefix, prefix_len, if_name, weight, next_hop): version = 'ipv4' obj = cps_utils.CPSObject('base-route/obj/entry') obj.add_attr("vrf-id", 0) # Ipv4 version obj.add_attr("af", socket.AF_INET) ip = net.IPNetwork(route_prefix) obj.add_attr_type("route-prefix", version) obj.add_attr("route-prefix", str(ip.network)) obj.add_attr("prefix-len", int(prefix_len)) # Next hops lst = ["nh-list", "0", "nh-addr"] obj.add_embed_attr(lst, str(next_hop)) #ifindex = cps_operations.getIfIndexFromName(if_name) #lst = ["nh-list", "0", "ifindex"] #obj.add_embed_attr(lst, int(ifindex)) lst = ["nh-list", "0", "weight"] obj.add_embed_attr(lst, int(weight)) obj.add_attr("nh-count", 1) # Create transaction cps_update = ('create', obj.get()) transaction = cps_utils.CPSTransaction([cps_update]) # Verify return value ret = transaction.commit() if not ret: #raise RuntimeError("Error creating Route") print("[CPSOperations]Error Creating Route") return Utils.timeLogger("CPSOperations| CPS add route:") Utils.cliLogger( "New route: " + str(route_prefix) + "/" + str(prefix_len) + " interface: " + str(if_name) + " metric " + str(weight), 0)
def run(path, method, notify): '''Run the event loop''' handle = cps.event_connect() (yin_form, data) = cps_parse.yin_path(path) if yin_form is None: return cps_obj = cps_utils.CPSObject(yin_form, data=data, qual="observed") cps.event_register_object(handle, cps_obj.get()) import traceback while True: result = cps.event_wait(handle) try: event_path = cps_parse.prep_path(yin_form, result) if result['data'].get( "cps/object-group/return-code") is not None: del result['data']["cps/object-group/return-code"] parsed = cps_parse.convert_result(event_path, result) notify(method, parsed) except KeyError: pass except AttributeError: pass
def build_route_obj(route_prefix, prefix_len, version): ver = extract_version(route_prefix) if version != 'ipv' + str(ver): print 'Improper IP Address' print str(ver) print version usage() obj = cps_utils.CPSObject(nas_route.get_route_key()[int(0)]) obj.add_attr("vrf-id", 0) if version == 'ipv4': obj.add_attr("af", socket.AF_INET) elif version == 'ipv6': obj.add_attr("af", socket.AF_INET6) obj.add_attr_type("route-prefix", version) obj.add_attr("route-prefix", str(route_prefix)) obj.add_attr("prefix-len", int(prefix_len)) # print "Configuring Route prefix:" + str(route_prefix),"pref_len:",prefix_len,"Version:"+ str(ver) return obj
#Python code block to delete a route import cps_utils import socket import netaddr as net version = 'ipv4' route_ip = '70.5.5.0' obj = cps_utils.CPSObject('base-route/obj/entry') obj.add_attr("vrf-id", 0) if version == 'ipv4': obj.add_attr("af", socket.AF_INET) elif version == 'ipv6': obj.add_attr("af", socket.AF_INET6) ip = net.IPNetwork(route_ip) obj.add_attr_type("route-prefix", version) obj.add_attr("route-prefix", str(ip.network)) obj.add_attr("prefix-len", int(ip.prefixlen)) print obj.get() cps_update = ('delete', obj.get()) transaction = cps_utils.CPSTransaction([cps_update]) ret = transaction.commit() if not ret:
import cps_utils cps_utils.add_attr_type("base-mac/table/mac-address", "mac") d = {"mac-address": "00:0a:0b:cc:0d:0e", "ifindex": 18, "vlan": "100"} obj = cps_utils.CPSObject('base-mac/table', data=d) tr_obj = ('delete', obj.get()) transaction = cps_utils.CPSTransaction([tr_obj]) ret = transaction.commit() if not ret: raise RuntimeError("Error deleting entry from MAC Table")
type_map = { 'base-acl/entry/DST_IP_VALUE/addr': 'ipv4', 'base-acl/entry/SRC_MAC_VALUE/addr': 'mac', 'base-acl/entry/SRC_MAC_VALUE/mask': 'mac', 'base-acl/entry/DSCP_VALUE/data': 'uint8_t', 'base-acl/entry/DSCP_VALUE/mask': 'uint8_t', 'base-acl/entry/NEW_TC_VALUE': 'uint8_t' } for key,val in type_map.items(): cps_utils.cps_attr_types_map.add_type(key, val) # ACL Table # Container to hold ACL entries obj = cps_utils.CPSObject(module='base-acl/table', data={'stage': e_stg['INGRESS'], 'priority': 99}) obj.add_list ('allowed-match-fields', [e_ftype['SRC_MAC'], e_ftype['DST_IP'], e_ftype['DSCP'], e_ftype['IN_PORT']]) # CPS Transaction upd = ('create', obj.get()) r = cps_utils.CPSTransaction([upd]).commit() if not r: raise RuntimeError ("Error creating ACL Table") ret = cps_utils.CPSObject (module='base-acl/table', obj=r[0]['change']) tbl_id = ret.get_attr_data ('id') print "Successfully created ACL Table " + str(tbl_id)
def mirror_show(): filt = cps_utils.CPSObject('base-mirror/entry') ret = [] r = cps.get([filt.get()], ret) for obj in ret: cps_utils.print_obj(obj)
'base-qos/meter/peak-rate': 'uint64_t', 'base-qos/meter/id': 'uint64_t', } for key, val in type_map.items(): cps_utils.cps_attr_types_map.add_type(key, val) # Sample interface ifindex = 16 print '\nconfigure qos port-ingress for port %s\n' % ifindex print 'Start to create storm control policer profiles' meter_obj = cps_utils.CPSObject(module='base-qos/meter', data={ 'type': e_meter_type['PACKET'], 'peak-rate': 300, 'mode': e_meter_mode['STORM_CONTROL'] }) upd = ('create', meter_obj.get()) r = cps_utils.CPSTransaction([upd]).commit() if not r: raise RuntimeError("Error creating " + 'base-qos/meter') ret = cps_utils.CPSObject(module='base-qos/meter', obj=r[0]['change']) meter_id = ret.get_attr_data('id') print 'Setup port ingress profile with policers' port_ing_obj = cps_utils.CPSObject(module='base-qos/port-ingress', data={ 'port-id': ifindex, 'broadcast_storm_control': meter_id })
#Python code block to request MAC address table entry import cps_utils import cps #Register the attribute type cps_utils.add_attr_type("base-mac/query/mac-address", "mac") #Define the MAC address request type d = {"mac-address": "00:0a:0b:cc:0d:0e","request-type":"2"} #Associate the get operation with the CPS object obj = cps_utils.CPSObject('base-mac/query', data= d) #Create an object filter list filter_list = [] filter_list.append(obj.get()) l = [] #Check for failure if cps.get(filter_list,l): if l: for ret_obj in l: cps_utils.print_obj(ret_obj) else: print "No objects found" else: print "No objects found" raise RuntimeError ("Error Getting MAC Table Entries")
# Python code block to set IP address import cps_utils # Populate the attributes for the CPS object ifindex = 16 ip_addr = "10.0.0.1" pfix_len = 16 ip_attributes = { "base-ip/ipv4/ifindex": ifindex, "ip": ip_addr, "prefix-length": pfix_len } # Create CPS object cps_utils.add_attr_type('base-ip/ipv4/address/ip', "ipv4") cps_obj = cps_utils.CPSObject('base-ip/ipv4/address', data=ip_attributes) # Create the CPS transaction for object create cps_update = ('create', cps_obj.get()) transaction = cps_utils.CPSTransaction([cps_update]) # Check for failure ret = transaction.commit() if not ret: raise RuntimeError("Error ")
def delete(self, path): '''delete - delete a data element. ''' (yin_form, path_data) = yin_path(path) cps_obj = cps_utils.CPSObject(yin_form, data=path_data) self._cps_tx.append({'change': cps_obj.get(), 'operation': 'delete'})
# Python code block to remove multiple MAC table entries import cps_utils # Define VLANs vlan_list =[1,2,3,4,5] # Create CPS object obj = cps_utils.CPSObject('base-mac/flush') # Add VLAN list to CPS object count = 0 el = ["input/filter","0","vlan"] for vlan in vlan_list: obj.add_embed_attr(el, vlan) count = count + 1 el[1] = str(count) # Association operation to object tr_obj = ('rpc', obj.get()) transaction = cps_utils.CPSTransaction([tr_obj]) # Verify the return value ret = transaction.commit() if not ret: raise RuntimeError("Error Flushing entries from MAC Table")
import cps import cps_utils handle = cps.event_connect() obj = cps_utils.CPSObject('base-port/interface',qual='observed', data= {"ifindex":23}) cps.event_send(handle, obj.get())
# Inform CPS utility about the type of each attribute type_map = { 'base-acl/entry/SRC_MAC_VALUE/addr': 'mac', 'base-acl/entry/SRC_MAC_VALUE/mask': 'mac', } for key,val in type_map.items(): cps_utils.cps_attr_types_map.add_type(key, val) # Create ACL Table # # Create CPS Object and fill leaf attributes cps_obj = cps_utils.CPSObject(module='base-acl/table') cps_obj.add_attr ('stage', e_stg['INGRESS']) cps_obj.add_attr ('priority', 99) # Populate the leaf-list attribute cps_obj.add_list ('allowed-match-fields', [e_ftype['SRC_MAC'], e_ftype['DST_IP'], e_ftype['DSCP'], e_ftype['IN_PORT']]) # Associate the CPS Object with a CPS operation cps_update = ('create', cps_obj.get()) # Add the CPS object to a new CPS Transaction cps_trans = cps_utils.CPSTransaction([cps_update]) # Commit the CPS transaction r = cps_trans.commit() if not r: raise RuntimeError ("Error creating ACL Table") ret = cps_utils.CPSObject (module='base-acl/table', obj=r[0]['change']) tbl_id = ret.get_attr_data ('id') print "Successfully created ACL Table " + str(tbl_id)
import cps_utils #Create the CPS Object and fill the table-id and entry-id key values cps_obj = cps_utils.CPSObject(module='base-acl/entry', data={ 'table-id': 2, 'id': 1 }) #Associate the CPS Object with a CPS operation cps_update = ('delete', cps_obj.get()) #Add the CPS object to a new CPS Transaction cps_trans = cps_utils.CPSTransaction([cps_update]) #Commit the CPS transaction r = cps_trans.commit() if not r: raise RuntimeError("Error deleting ACL Entry")
} e_atype = {'PACKET_ACTION': 3, 'SET_TC': 10} e_ptype = {'DROP': 1} # Tell CPS utility about the type of each attribute type_map = { 'base-acl/entry/SRC_MAC_VALUE/addr': 'mac', 'base-acl/entry/SRC_MAC_VALUE/mask': 'mac', } for key, val in type_map.items(): cps_utils.cps_attr_types_map.add_type(key, val) # Create ACL Table # # Create CPS Object and fill leaf attributes cps_obj = cps_utils.CPSObject(module='base-acl/table') cps_obj.add_attr('stage', e_stg['INGRESS']) cps_obj.add_attr('priority', 99) # Populate the leaf-list attribute cps_obj.add_list('allowed-match-fields', [ e_ftype['SRC_MAC'], e_ftype['DST_IP'], e_ftype['DSCP'], e_ftype['IN_PORT'] ]) # Associate the CPS Object with a CPS operation cps_update = ('create', cps_obj.get()) # Add the CPS object to a new CPS Transaction cps_trans = cps_utils.CPSTransaction([cps_update]) # Commit the CPS transaction r = cps_trans.commit() if not r: raise RuntimeError("Error creating ACL Table")
def nas_mirror_op(op, data_dict, commit=True): obj = cps_utils.CPSObject(module="base-mirror/entry", data=data_dict) if commit: nas_ut.get_cb_method(op)(obj) else: return obj