def patch_devices_with_vlan_list(vlan_list_config, tag_prefix): if vlan_list_config["type"] == "single": tag_name = tag_prefix + "vlanIf" vlans = tag_utils.get_tagged_objects_from_string_names(tag_name) vlan_list = vlan_list_config["vlan_list"] vlan_port_step = vlan_list_config["vlan_port_step"] for vlan in vlans: vlan.SetCollection("IdList", vlan_list) vlan_list = [vlan_id + vlan_port_step for vlan_id in vlan_list] elif vlan_list_config["type"] == "qnq": outer_tag_name = tag_prefix + "outerVlan" outer_vlans = tag_utils.get_tagged_objects_from_string_names( outer_tag_name ) inner_tag_name = tag_prefix + "innerVlan" inner_vlans = tag_utils.get_tagged_objects_from_string_names( inner_tag_name ) outer_vlan_list = vlan_list_config["outer_vlan_list"] inner_vlan_list = vlan_list_config["inner_vlan_list"] outer_port_step = vlan_list_config["outer_port_step"] inner_port_step = vlan_list_config["inner_port_step"] for vlan in outer_vlans: vlan.SetCollection("IdList", outer_vlan_list) outer_vlan_list = [vlan_id + outer_port_step for vlan_id in outer_vlan_list] for vlan in inner_vlans: vlan.SetCollection("IdList", inner_vlan_list) inner_vlan_list = [vlan_id + inner_port_step for vlan_id in inner_vlan_list]
def run(SrcTagName, TargetTagName, RelationName, RemoveRelation): plLogger = PLLogger.GetLogger('methodology') plLogger.LogDebug("run ConfigRelationCommand") # Before walking the tree, make sure the relation is a valid one try: RelationType(RelationName) except RuntimeError as e: # Invalid name if 'does not exist' in str(e): err = "Relation name " + RelationName + \ " is not a valid relation type" plLogger.LogError(err) raise RuntimeError(err) else: raise e src_objs = tag_utils.get_tagged_objects_from_string_names([SrcTagName]) targ_objs = tag_utils.get_tagged_objects_from_string_names([TargetTagName]) for src_obj in src_objs: for targ_obj in targ_objs: if RemoveRelation is False: # TODO: Have a try block to handle expected errors, like invlaid relations, or # single-target-only relations that have mutliple targets here? src_obj.AddObject(targ_obj, RelationType(RelationName)) else: src_obj.RemoveObject(targ_obj, RelationType(RelationName)) return True
def run(TagNameList, ObjectOrder, BreakOnFail, MinVal, MaxVal, PrevIterVerdict): # plLogger = PLLogger.GetLogger('IterateOverTaggedObjects') this_cmd = get_this_cmd() key = get_this_obj_key() # If a validator fails, then set the results if BreakOnFail and PrevIterVerdict is False: this_cmd.Set('PassFailState', 'Failed') this_cmd.Set('ResetState', True) return False # Verify that the set up parameters match what's being iterated if CObjectRefStore.Exists(key): cmd_dict = CObjectRefStore.Get(key) # If they don't match, ditch what we have, start over if cmd_dict['ObjectOrder'] != ObjectOrder or \ cmd_dict['TagNameList'] != TagNameList: CObjectRefStore.Release(key) if this_cmd.Get('ResetState') or not CObjectRefStore.Exists(key): this_cmd.Set('ResetState', False) this_cmd.Set('Iteration', 0) this_cmd.Set('CurrVal', '') cmd_dict = {'ObjectOrder': ObjectOrder, 'TagNameList': TagNameList} # Assumption, if not SCALAR, it's TUPLE if ObjectOrder == 'SCALAR': obj_list = tag_utils.get_tagged_objects_from_string_names(TagNameList) hnd_list = [obj.GetObjectHandle() for obj in obj_list] else: # This expression gets too ugly the way it's set up, so will be # explicit for this nested list of lists hnd_list_list = [] for tag in TagNameList: obj_list = tag_utils.get_tagged_objects_from_string_names(tag) hnd_list = [obj.GetObjectHandle() for obj in obj_list] hnd_list_list.append(hnd_list) if len(hnd_list_list) < 2: raise ValueError('Expected multiple lists, but only got one') hnd_list = zip(*hnd_list_list) cmd_dict['HandleList'] = hnd_list CObjectRefStore.Put(key, cmd_dict) # At this point, it should exist cmd_dict = CObjectRefStore.Get(key) iter_num = this_cmd.Get('Iteration') # Done if we reach last index if iter_num >= len(cmd_dict['HandleList']): this_cmd.Set('Iteration', iter_num) this_cmd.Set('PassFailState', 'FAILED') this_cmd.Set('ResetState', True) if CObjectRefStore.Exists(key): CObjectRefStore.Release(key) return False if ObjectOrder == 'SCALAR': curr_val = str(cmd_dict['HandleList'][iter_num]) else: curr_val = ','.join([str(x) for x in cmd_dict['HandleList'][iter_num]]) this_cmd.Set('CurrVal', curr_val) iter_num = iter_num + 1 this_cmd.Set('Iteration', iter_num) return True
def test_exec(stc, stak, cleanup_all, ports): data = json.loads(test_config) topology_config = data['topology_nodes'] network_profiles = get_network_profiles(data) traffic_profiles = get_traffic_profiles(data) endpoint_infos = data['endpoint_infos'] exec_command('CreateTemplatesCommand', { 'TopologyConfig': json.dumps(topology_config), 'NetworkProfileConfig': json.dumps(network_profiles), 'TrafficProfileConfig': json.dumps(traffic_profiles), 'EndpointConfig': json.dumps(endpoint_infos) }) exec_command('AdjustMacCommand', stak['params']) assert detect_source_mac_called is True assert detect_source_mac_called_with == [ports[0].GetObjectHandle()] # subnet 1234 (west, unique, virtual, dev count == 1) # should not be randomized ethii_ifs1 = tag_utils.get_tagged_objects_from_string_names( ['net1_1234_ttEthIIIf'] ) assert len(ethii_ifs1) == 1 for eif in ethii_ifs1: assert eif.GetObject('Rfc4814EthIIIfDecorator') is None # subnet 3456 (west, unique, hw) should be randomized ethii_ifs2 = tag_utils.get_tagged_objects_from_string_names( ['net1_3456_ttEthIIIf'] ) assert len(ethii_ifs2) == 1 for eif in ethii_ifs2: assert eif.GetObject('Rfc4814EthIIIfDecorator') is not None # subnet 2345 (east, unique, virtual, dev count == 2) # should be randomized ethii_ifs3 = tag_utils.get_tagged_objects_from_string_names( ['net2_2345_ttEthIIIf'] ) assert len(ethii_ifs3) == 1 for eif in ethii_ifs3: assert eif.GetObject('Rfc4814EthIIIfDecorator') is not None # subnet 4567 (east, static, hw) should not be randomized ethii_ifs4 = tag_utils.get_tagged_objects_from_string_names( ['net2_4567_ttEthIIIf'] ) assert len(ethii_ifs4) == 1 for eif in ethii_ifs4: assert eif.GetObject('Rfc4814EthIIIfDecorator') is None
def test_tag_wizgenerated_as_created(stc): stc_sys = CStcSystem.Instance() project = stc_sys.GetObject("Project") ctor = CScriptableCreator() # Create Wizard param objects bgpParamObj = ctor.Create("BgpRouteGenParams", project) ipv4ParamObj = ctor.Create("Ipv4RouteGenParams", bgpParamObj) # Create BLL objects devObj = ctor.Create("EmulatedDevice", project) rtrObj = ctor.Create("BgpRouterConfig", devObj) routeObj = ctor.Create("BgpIpv4RouteConfig", rtrObj) # Manually set WizardGeneratedObject relation ipv4ParamObj.AddObject(routeObj, RelationType("WizardGeneratedObject")) # Run the tag function PrefixCmd.tag_wizgenerated_as_created(ipv4ParamObj, "testtag") # Check that the correct route object was tagged with the correct tag name taggObjs = tag_utils.get_tagged_objects_from_string_names("testtag") assert len(taggObjs) == 1 assert routeObj.GetObjectHandle() == taggObjs[0].GetObjectHandle() return
def get_ethii_ifs(subnet): tag_prefix = tag_name_util.get_subnet_tag_prefix(subnet) tag_name = tag_prefix + tag_name_util.get_ethIIIf_tag(subnet) ethii_ifs = tag_utils.get_tagged_objects_from_string_names( [tag_name] ) return ethii_ifs
def get_devices(subnet): tag_prefix = tag_name_util.get_subnet_tag_prefix(subnet) tag_name = tag_prefix + tag_name_util.get_dev_tag(subnet) devices = tag_utils.get_tagged_objects_from_string_names( [tag_name] ) return [device.GetObjectHandle() for device in devices]
def SetRotation(tagname, tagged_object_list, params): rots = tag_utils.get_tagged_objects_from_string_names('IterRotate') if len(rots) == 0: return 'Missing IterRotate tagged object.' for rot in rots: rot.Set('MaxVal', float(len(tagged_object_list) - 1)) rot.Set('StepVal', float(params)) rot.Set('MinVal', float(params)) return ''
def SetRulesFilename(tagname, tagged_object_list, params): cmds = tag_utils.get_tagged_objects_from_string_names('RulesFileName') if len(cmds) == 0: return 'Missing "RulesFileName" tagged command.' for cmd in cmds: if cmd.IsTypeOf(TTPKG + '.LoadAclTrafficRulesCommand'): cmd.Set('RulesFileName', params) else: return 'Only LoadAclTrafficRulesCommand is supported for RulesFileName.' return ''
def process_tagged_commands(cmd_dict): cmd_list = \ tag_utils.get_tagged_objects_from_string_names(['Y1564Command']) for cmd in cmd_list: if cmd.IsTypeOf(PKG + '.VerifyDbQueryCommand'): create_summary_queries(cmd, cmd_dict) elif cmd.IsTypeOf(PKG + '.VerifyMultipleDbQueryCommand'): create_kpi_queries(cmd, cmd_dict) elif cmd.IsTypeOf(PKG + '.ExportDbChartCommand'): create_chart_queries(cmd, cmd_dict)
def process_tagged_commands(): stc_sys = CStcSystem.Instance() cmd_list = \ tag_utils.get_tagged_objects_from_string_names(['Y1564Command']) for cmd in cmd_list: # For now, just pre-set the capture wrapper to set the capture path if cmd.IsTypeOf('CaptureDataSaveCommand'): path = os.path.normpath(stc_sys.GetApplicationSessionDataPath()) cmd.Set('FileNamePath', path) cmd.Set('FileName', 'microburst_data.pcap') cmd.Set('FileNameFormat', 'PCAP') cmd.Set('AppendSuffixToFileName', False) return
def get_streamblocks(subnet): tag_prefix = tag_name_util.get_subnet_tag_prefix(subnet) tag_name = tag_prefix + tag_name_util.get_dev_tag(subnet) devices = tag_utils.get_tagged_objects_from_string_names( [tag_name] ) streamblock_hnds = [] for device in devices: ip_if = device.GetObject("NetworkInterface", RelationType("TopLevelIf")) streamblocks = ip_if.GetObjects("StreamBlock", RelationType.ReverseDir("SrcBinding")) streamblock_hnds += [streamblock.GetObjectHandle() for streamblock in streamblocks] return streamblock_hnds
def test_twg_as_created(stc): stc_sys = CStcSystem.Instance() project = stc_sys.GetObject("Project") ctor = CScriptableCreator() paramObj = ctor.Create("BgpImportRouteTableParams", project) devObj = ctor.Create("EmulatedDevice", project) rtrObj = ctor.Create("BgpRouterConfig", devObj) routeObj = ctor.Create("BgpIpv4RouteConfig", rtrObj) paramObj.AddObject(routeObj, RelationType("WizardGenerated")) ImportCmd.tag_wizgenerated_as_created(paramObj, "testtag") taggObjs = tag_utils.get_tagged_objects_from_string_names("testtag") assert len(taggObjs) == 1 assert routeObj.GetObjectHandle() == taggObjs[0].GetObjectHandle() return
def configure_generator(tag_name, duration=100.0): ''' The generators under the tagged ports will be configured as required by the tests ''' port_list = tag_utils.get_tagged_objects_from_string_names([tag_name]) gen_list = [] for port in port_list: gen = port.GetObject('Generator') assert gen gen_cfg = gen.GetObject('GeneratorConfig') assert gen_cfg gen_cfg.Set('SchedulingMode', 'MANUAL_BASED') gen_cfg.Set('DurationMode', 'BURSTS') gen_cfg.Set('Duration', duration) gen_list.append(gen) return gen_list
def run(CommandTagName, IterationDuration, StartBw, CirBw, EirBw, OvershootBw, StepCount, ExpPktLossCount, ExpRfc4689AvgJitter, ExpMaxJitter, ExpAvgLatency, ExpMaxLatency, ExpMaxOopCount, ExpMaxLatePktCount): cmd_dict = { 'start_bw': StartBw, 'cir_bw': CirBw, 'eir_bw': EirBw, 'ovr_bw': OvershootBw, 'step_bw': StepCount, 'exp_pktloss': ExpPktLossCount, 'exp_avgjitter': ExpRfc4689AvgJitter, 'exp_maxjitter': ExpMaxJitter, 'exp_avglatency': ExpAvgLatency, 'exp_maxlatency': ExpMaxLatency, 'exp_maxoop': ExpMaxOopCount, 'exp_maxlatepkt': ExpMaxLatePktCount} # Additional work to chain/configure other properties needed CObjectRefStore.Put(OBJ_KEY, cmd_dict, True) cmd_list = \ tag_utils.get_tagged_objects_from_string_names([CommandTagName]) for cmd in cmd_list: # Assume only certain commands are tagged if cmd.IsTypeOf('WaitCommand'): cmd.Set('WaitTime', float(IterationDuration)) elif cmd.IsTypeOf(PKG + '.ObjectIteratorCommand'): bw_list = [] if StartBw < CirBw: stepBw = (CirBw - StartBw) / StepCount if stepBw == 0: bw_list.append(StartBw) else: bw = StartBw while (bw <= CirBw): if CirBw - bw < stepBw: bw = CirBw bw_list.append(bw) bw = bw + stepBw else: bw_list.append(CirBw) bw_list.append(CirBw + EirBw) bw_list.append(CirBw + EirBw + OvershootBw) cmd.SetCollection('ValueList', [str(x) for x in bw_list]) return True
def get_streamblock_handle_list(): logger.debug("get_streamblock_handle_list : ") sb_handle_list = [] if not CObjectRefStore.Exists(OBJ_KEY): logger.warn("DiffServCfgRampCommand was not called. " + "Using default threshold values.") else: tmp_dict = CObjectRefStore.Get(OBJ_KEY) logger.debug(" tmp_dict: " + str(tmp_dict)) dict_keys = tmp_dict.keys() logger.debug(" dict_keys: " + str(dict_keys)) # convert keys to handles sb_list = tag_utils.get_tagged_objects_from_string_names(dict_keys) for sb in sb_list: sb_handle_list.append(sb.GetObjectHandle()) logger.debug(" sb_handle_list: " + str(sb_handle_list)) return sb_handle_list
def Rfc2544ThroughputVerifyResults(tagname, b, params): # plLogger = PLLogger.GetLogger('methodology') # plLogger.LogDebug("Running Rfc2544ThroughputVerifyResults") res_cmd_list = tag_utils.get_tagged_objects_from_string_names(tagname) # plLogger.LogDebug("res_cmd_list: " + str(res_cmd_list)) objectIterIndex = 0 multiDbQueryIndex = 0 for idx, cmd in enumerate(res_cmd_list): if cmd.IsTypeOf(PKG + '.ObjectIteratorCommand'): objectIterIndex = idx if cmd.IsTypeOf(PKG + '.VerifyMultipleDbQueryCommand'): multiDbQueryIndex = idx # Get list of frame sizes from object iterator frameList = res_cmd_list[objectIterIndex].GetCollection('ValueList') # plLogger.LogDebug("frameList: " + str(frameList)) q_list = [] display_name_list = [] pass_list = [] fail_list = [] for frame in frameList: # For each frame size determine if there was any streams with dropped frames # If so (number of rows found > 0), that is considered a failure display_name_list.append('Frame Size ' + str(frame)) pass_list.append('Found frame rate with no dropped frames for frame size ' + str(frame)) fail_list.append('Found dropped frames for all frame rates with frame size ' + str(frame)) q = "SELECT FrameSize AS 'Frame Size (bytes)', Load AS 'Load %', " + \ "FPS AS 'Frames per Second', DroppedCount AS 'Dropped Frame Count' From " + \ "MethRfc2544Throughput WHERE FrameSize == " + str(frame) + " AND DroppedCount > 0" q_list.append(q) res_cmd_list[multiDbQueryIndex].SetCollection('DisplayNameList', display_name_list) res_cmd_list[multiDbQueryIndex].SetCollection('PassedVerdictExplanationList', pass_list) res_cmd_list[multiDbQueryIndex].SetCollection('FailedVerdictExplanationList', fail_list) res_cmd_list[multiDbQueryIndex].SetCollection('SqlQueryList', q_list) res_cmd_list[multiDbQueryIndex].Set('UseMultipleResultsDatabases', False) res_cmd_list[multiDbQueryIndex].Set('UseSummary', True) return ""
def test_run(stc): stc_sys = CStcSystem.Instance() project = stc_sys.GetObject("Project") ctor = CScriptableCreator() port = ctor.Create("Port", project) ethCopper = ctor.Create("EthernetCopper", port) port.AddObject(ethCopper, RelationType("ActivePhy")) # Create and tag router emDevice = ctor.Create("EmulatedDevice", project) emDevice.AddObject(port, RelationType("AffiliationPort")) ipv4If = ctor.Create("Ipv4If", emDevice) ethIf = ctor.Create("EthIIIf", emDevice) emDevice.AddObject(ipv4If, RelationType("TopLevelIf")) emDevice.AddObject(ipv4If, RelationType("PrimaryIf")) ipv4If.AddObject(ethIf, RelationType("StackedOnEndpoint")) ctor.Create("BgpRouterConfig", emDevice) tag_utils.add_tag_to_object(emDevice, "ttEmulatedDevice") # Create and tag wizard object bgpParamObj = ctor.Create("BgpRouteGenParams", project) tag_utils.add_tag_to_object(bgpParamObj, "ttBgpRouteGenParams") ipv4ParamObj = ctor.Create("Ipv4RouteGenParams", bgpParamObj) ipv4ParamObj.SetCollection("PrefixLengthDist", [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) ipv4ParamObj.Set("Count", 2) ipv4ParamObj.Set("PrefixLengthDistType", "CUSTOM") ctor.Create("BgpRouteGenRouteAttrParams", ipv4ParamObj) # Run the command PrefixCmd.run(["ttEmulatedDevice"], "ttBgpRouteGenParams", "ttBgpRoutes") routeObjs = tag_utils.get_tagged_objects_from_string_names("ttBgpRoutes") assert len(routeObjs) == 2 for routeObj in routeObjs: assert routeObj.IsTypeOf("BgpIpv4RouteConfig") return
def get_valid_handles(handle_list, tag_name_list): hnd_reg = CHandleRegistry.Instance() l2_obj_list = [] l3_obj_list = [] l2_handle_list = [] l3_handle_list = [] # Add object handles from the tag list to the handle list if len(tag_name_list) > 0: for obj in tag_utils.get_tagged_objects_from_string_names(tag_name_list): handle_list.append(obj.GetObjectHandle()) # The L2 learning command only allows handles of type Port and StreamBlock # The L3 learning command only allows handles of type Port, StreamBlock, Host, # Router, and EmulatedDevice for hnd in handle_list: obj = hnd_reg.Find(hnd) if obj.IsTypeOf("Port") or obj.IsTypeOf("StreamBlock") or obj.IsTypeOf("Project"): l2_obj_list.append(obj) l3_obj_list.append(obj) elif obj.IsTypeOf("EmulatedDevice") or obj.IsTypeOf("Host") or obj.IsTypeOf("Router"): l3_obj_list.append(obj) elif obj.IsTypeOf("StmTemplateMix") or obj.IsTypeOf("StmTemplateConfig"): l2_obj_list.extend(dm_utils.get_class_objects([hnd], [], ["Port", "StreamBlock", "Project"])) l3_obj_list.extend(dm_utils.get_class_objects([hnd], [], ["Port", "StreamBlock", "Project", "EmulatedDevice", "Host", "Router"])) for obj in dm_utils.sort_obj_list_by_handle(l2_obj_list): l2_handle_list.append(obj.GetObjectHandle()) for obj in dm_utils.sort_obj_list_by_handle(l3_obj_list): l3_handle_list.append(obj.GetObjectHandle()) return l2_handle_list, l3_handle_list
def run(StmTrafficMix, TagName, Load, LoadUnit): plLogger = PLLogger.GetLogger("AllocateTrafficMixLoad1Command") obj_list = CCommandEx.ProcessInputHandleVec('StmTrafficMix', [StmTrafficMix]) if TagName: obj_list = obj_list + tag_utils.get_tagged_objects_from_string_names([TagName]) if len(obj_list) == 0: plLogger.LogError("Neither StmTrafficMix nor TagName specified " + "a valid StmTrafficMix Object") return False obj_dict = {obj.GetObjectHandle(): obj for obj in obj_list} for traf_mix in obj_dict.values(): tmi = traf_mix.Get('MixInfo') if tmi == '': plLogger.LogError("MixInfo is empty") return False mix_elem = etree.fromstring(tmi) val = mix_elem.get('WeightList') weight_list = [float(x) for x in val.split()] tmpl_list = traf_mix.GetObjects('StmTemplateConfig') if len(weight_list) != len(tmpl_list): plLogger.LogError("Size of weight list does not match " + "number of templates") return False # Fractions are not supported only for these settings allow = (LoadUnit not in ['FRAMES_PER_SECOND', 'INTER_BURST_GAP']) load_list = weight.allocate_weighted_list(Load, weight_list, allow_fraction=allow) for load, tmpl in zip(load_list, tmpl_list): allocate_weighted_load(load, tmpl, LoadUnit) config_generator(tmpl, LoadUnit) # After finishing, set the appropriate fields in the mix mix_elem.set('Load', str(Load)) mix_elem.set('LoadUnit', LoadUnit) mix_elem.set('LoadDist', ' '.join([str(x) for x in load_list])) traf_mix.Set('MixInfo', etree.tostring(mix_elem)) return True
def run(RouterTagList, SrcObjectTagName, CreatedRoutesTagName): plLogger = PLLogger.GetLogger('methodology') plLogger.LogInfo(" Run RoutePrefixDistributionCommand") ctor = CScriptableCreator() this_cmd = get_this_cmd() protocolParamObjs = tag_utils.get_tagged_objects_from_string_names([SrcObjectTagName]) if len(protocolParamObjs) == 0: this_cmd.Set('Status', 'No objects with tag matching SrcObjectTagName') return False routerObjs = tag_utils.get_tagged_objects_from_string_names(RouterTagList) if len(routerObjs) == 0: this_cmd.Set('Status', 'No routers with tag in RouterTagList') return False for protocolParamObj in protocolParamObjs: for routerObj in routerObjs: if not (routerObj.IsTypeOf('EmulatedDevice') or routerObj.IsTypeOf('RouterConfig')): this_cmd.Set('Status', routerObj.Get('Name') + "is of type " + routerObj.GetType() + "should be of type EmulatedDevice or RouterConfig") return False # Get EmulatedDevice if a RouterConfig tag was passed in if routerObj.IsTypeOf('RouterConfig'): routerObj = routerObj.GetParent() # RouteGenApplyCommand will skip any Emulated Devices that don't have # and affiliation port if not routerObj.GetObject('Port', RelationType('AffiliationPort')): this_cmd.Set('Status', 'EmulatedDevice has no AffiliationPort') return False # Only EmulatedDevices allowed for SelectedRouterRelation protocolParamObj.AddObject(routerObj, RelationType('SelectedRouterRelation')) if not protocolParamObj.GetObjects('EmulatedDevice', RelationType('SelectedRouterRelation')): this_cmd.Set('Status', 'No routers specified for routes to be attached to') return False # Create the RouteGenApplyCommand cmd = ctor.CreateCommand("RouteGenApplyCommand") cmd.Set("GenParams", protocolParamObj.GetObjectHandle()) cmd.Set("DeleteRoutesOnApply", "NO") cmd.Execute() # If RouteGenApplyCommand fails, fail this command cmd_state = cmd.Get('State') cmd_status = cmd.Get('Status') if cmd_state != 'COMPLETED': this_cmd.Set('Status', "RouteGenApplyCommand did not complete: " + cmd_status) cmd.MarkDelete() return False cmd.MarkDelete() # Verify that routes were created num_routes = 0 routeParamObjs = protocolParamObj.GetObjects('RouteGenParams', RelationType('ParentChild')) for routeParamObj in routeParamObjs: num_routes += len(routeParamObj.GetObjects('Scriptable', RelationType('WizardGeneratedObject'))) if num_routes == 0: warn_msg = "Failed to generate any route objects using the RouteGenApplyCommand: " + \ cmd_status this_cmd.Set('Status', warn_msg) plLogger.LogWarn(warn_msg) routeGenParamObjs = protocolParamObj.GetObjects('RouteGenParams') for routeGenParamObj in routeGenParamObjs: if CreatedRoutesTagName: tag_wizgenerated_as_created(routeGenParamObj, CreatedRoutesTagName) return True
def test_run(stc): sequencer = CStcSystem.Instance().GetObject('Sequencer') project = CStcSystem.Instance().GetObject('Project') ctor = CScriptableCreator() hnd_reg = CHandleRegistry.Instance() cmd = ctor.Create(TPKG + '.CreateTrafficMixCommand', sequencer) plLogger = PLLogger.GetLogger('test_CreateTrafficMixCommand.test_run') plLogger.LogInfo('start') CreateTMix2Cmd.get_this_cmd = MagicMock(return_value=cmd) CreateTMix2Cmd.run(mix_info(), 'TheMix', False) # Check the created StmTemplateMix mix_hnd = cmd.Get('StmTemplateMix') mix = hnd_reg.Find(mix_hnd) assert mix assert mix.Get('MixInfo') == mix_info() # Find the tagged commands tag_json = cmd.Get('GroupCommandTagInfo') assert tag_json != '' err_str, tag_dict = json_utils.load_json(tag_json) assert err_str == "" tagged_obj_list = tag_utils.get_tagged_objects_from_string_names( [tag_dict['rowIterator']]) assert len(tagged_obj_list) == 1 obj_iter = tagged_obj_list[0] assert obj_iter.IsTypeOf(PKG + '.ObjectIteratorCommand') assert obj_iter.Get('StepVal') == 1.0 assert obj_iter.Get('MaxVal') == 0.0 assert obj_iter.Get('MinVal') == 0.0 assert obj_iter.Get('IterMode') == 'STEP' assert obj_iter.Get('ValueType') == 'RANGE' tagged_obj_list = tag_utils.get_tagged_objects_from_string_names( [tag_dict['rowConfigurator']]) assert len(tagged_obj_list) == 1 config_cmd = tagged_obj_list[0] assert config_cmd.IsTypeOf(PKG + '.IteratorConfigMixParamsCommand') assert mix_hnd == config_cmd.Get('StmTemplateMix') # Check the Tag tags = project.GetObject('Tags') assert tags user_tag_list = tags.GetObjects('Tag') assert len(user_tag_list) exp_tag = None for user_tag in user_tag_list: if user_tag.Get('Name') == 'TheMix': exp_tag = user_tag break assert exp_tag tag_target = exp_tag.GetObject('StmTemplateMix', RelationType('UserTag', 1)) assert tag_target assert tag_target.GetObjectHandle() == mix.GetObjectHandle() tagged_obj_list = tag_utils.get_tagged_objects_from_string_names( [tag_dict['templateConfigurator']]) assert len(tagged_obj_list) == 1 load_cmd = tagged_obj_list[0] assert load_cmd.IsTypeOf(PKG + '.CreateTemplateConfigCommand') load_input_mix_hnd = load_cmd.Get('StmTemplateMix') assert load_input_mix_hnd == mix.GetObjectHandle()
def y1564ResultsReport(tagname, b, params): plLogger = PLLogger.GetLogger("Methodology") plLogger.LogDebug("Running custom y1564ResultsReport script...") if not CObjectRefStore.Exists(OBJ_KEY): plLogger.LogWarn('Y1564SvcCfgRampCommand was not called. ' + 'Using default threshold values.') exp_pktloss = 0 exp_avgjitter = 0.05 exp_maxjitter = 0.2 exp_avglatency = 0.7 exp_maxlatency = 1.0 exp_maxoop = 0 exp_maxlatepkt = 0 else: cmd_dict = CObjectRefStore.Get(OBJ_KEY) exp_pktloss = cmd_dict['exp_pktloss'] exp_avgjitter = cmd_dict['exp_avgjitter'] exp_maxjitter = cmd_dict['exp_maxjitter'] exp_avglatency = cmd_dict['exp_avglatency'] exp_maxlatency = cmd_dict['exp_maxlatency'] exp_maxoop = cmd_dict['exp_maxoop'] exp_maxlatepkt = cmd_dict['exp_maxlatepkt'] obj_list = \ tag_utils.get_tagged_objects_from_string_names("ttStreamBlock") sb_hnd_list = [] for sb in obj_list: sb_hnd = str(sb.GetObjectHandle()) sb_hnd_list.append(sb_hnd) src_if = sb.GetObject('NetworkEndpoint', RelationType('SrcBinding')) src_dev = src_if.GetParent() dst_if = sb.GetObject('NetworkEndpoint', RelationType('DstBinding')) dst_dev = dst_if.GetParent() cvlan = src_dev.Get('Vlan1') svlan = src_dev.Get('Vlan2') src = src_dev.Get('Ipv4Address') if src is None: src = src_dev.Get('Ipv6Address') dst = dst_dev.Get('Ipv4Address') if dst is None: dst = dst_dev.Get('Ipv6Address') if not sb.IsTypeOf('Streamblock'): raise RuntimeError('Tag did not point to a Streamblock') res_cmd_list = \ tag_utils.get_tagged_objects_from_string_names(tagname) plLogger.LogDebug("res_cmd_list: " + str(res_cmd_list)) for cmd in res_cmd_list: if cmd.IsTypeOf(PKG + '.VerifyMultipleDbQueryCommand'): q_list = [] display_name_list = [] pass_list = [] fail_list = [] display_name_list.append('Mean Frame Transfer Delay (FTD) Results') pass_list.append("Mean FTD is within the configured threshold of " + str(exp_avglatency) + " ms.") fail_list.append("Mean FTD exceeded the configured threshold of " + str(exp_avglatency) + " ms.") q = "SELECT Name AS 'Streamblock', " + \ "Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "ROUND(AvgLatency*1e-3,3) AS 'Mean FTD (ms)', " + \ "'" + str(exp_avglatency) + "' AS 'Mean FTD Threshold (ms)' " + \ "FROM RxEotStreamResults AS RxStr JOIN StreamBlock AS Sb " + \ "ON RxStr.ParentStreamBlock == Sb.Handle " + \ "WHERE ROUND(AvgLatency*1e-3,3) > " + str(exp_avglatency) q_list.append(q) display_name_list.append("Max Frame Transfer Delay (FTD) Results") pass_list.append("Max FTD is within the configured threshold of " + str(exp_maxlatency) + " ms.") fail_list.append("Max FTD exceeded the configured threshold of " + str(exp_maxlatency) + " ms.") q = "SELECT Name AS 'Streamblock', " + \ "Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "ROUND(MaxLatency*1e-3,3) AS 'Max FTD (ms)', " + \ "'" + str(exp_maxlatency) + "' AS 'Max FTD Threshold (ms)' " + \ "FROM RxEotStreamResults AS RxStr JOIN StreamBlock AS Sb " + \ "ON RxStr.ParentStreamBlock == Sb.Handle " + \ "WHERE ROUND(MaxLatency*1e-3,3) > " + str(exp_maxlatency) q_list.append(q) display_name_list.append("RFC4689 Mean Frame Delay Variation (FDV) Results") pass_list.append("RFC4689 Mean FDV is within the configured threshold of " + str(exp_avgjitter) + " ms.") fail_list.append("RFC4689 Mean FDV exceeded the configured threshold of " + str(exp_avgjitter) + " ms.") q = "SELECT Name AS 'Streamblock', Sb.FixedFrameLength " + \ " AS 'Frame Size (bytes)', ROUND(AvgJitter*1e-3,3) " + \ "AS 'RFC4689 Mean FDV (ms)', '" + str(exp_avgjitter) + "' AS " + \ "'RFC4689 Mean FDV Threshold (ms)' FROM " + \ "RxEotStreamResults As RxStr JOIN StreamBlock " + \ "AS Sb ON RxStr.ParentStreamBlock == Sb.Handle " + \ "WHERE ROUND(AvgJitter*1e-3,3) > " + str(exp_avgjitter) q_list.append(q) display_name_list.append("Max Frame Delay Variation (FDV) Results") pass_list.append("Max FDV is within the configured threshold of " + str(exp_maxjitter) + " ms.") fail_list.append("Max FDV exceeded the configured threshold of " + str(exp_maxjitter) + " ms.") q = "SELECT Name AS 'Streamblock', Sb.FixedFrameLength " + \ "AS 'Frame Size (bytes)', ROUND(MaxJitter*1e-3,3) " + \ "AS 'Max FDV (ms)', '" + str(exp_maxjitter) + "' AS " + \ "'Max FDV Threshold (ms)' FROM RxEotStreamResults " + \ "As RxStr JOIN StreamBlock AS Sb ON " + \ "RxStr.ParentStreamBlock == Sb.Handle " + \ "WHERE ROUND(MaxJitter*1e-3,3) > " + str(exp_maxjitter) q_list.append(q) display_name_list.append("Frame Loss (FL) Results") pass_list.append("Frame Loss Count is within the configured threshold of " + str(exp_pktloss) + ".") fail_list.append("Frame Loss Count exceeded the configured threshold of " + str(exp_pktloss) + ".") q = "SELECT StreamBlockName AS 'Streamblock', " + \ "Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "TxRes.FrameCount - RxRes.FrameCount As 'FL Count', " + \ "'" + str(exp_pktloss) + "' AS 'FL Count Threshold' " + \ "From RxEotStreamResults AS RxRes JOIN TxEotStreamResults " + \ "AS TxRes JOIN Streamblock AS Sb ON RxRes.ParentStreamBlock " + \ " = TxRes.ParentStreamblock AND TxRes.ParentStreamblock = " + \ "Sb.Handle WHERE TxRes.FrameCount - RxRes.FrameCount > " + \ str(exp_pktloss) q_list.append(q) display_name_list.append("Out of Order Frame Results") pass_list.append("Out of Order Frame Count is within the configured threshold of " + str(exp_maxoop) + ".") fail_list.append("Out of Order Frame Count exceeded the configured threshold of " + str(exp_maxoop) + ".") q = "SELECT Name AS 'Streamblock', " + \ "Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "OutSeqFrameCount AS 'Out of Order Frame Count', " + \ "'" + str(exp_maxoop) + "' AS 'Out of Order Frame Count Threshold' " + \ "FROM RxEotStreamResults AS RxStr JOIN StreamBlock AS Sb " + \ "ON RxStr.ParentStreamBlock == Sb.Handle " + \ "WHERE OutSeqFrameCount > " + str(exp_maxoop) q_list.append(q) display_name_list.append("Late Frame Results") pass_list.append("Late Frame Count is within the configured threshold of " + str(exp_maxlatepkt) + ".") fail_list.append("Late Frame Count exceeded the configured threshold of " + str(exp_maxlatepkt) + ".") q = "SELECT Name AS 'Streamblock', " + \ "Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "LateFrameCount AS 'Late Frame Count', " + \ "'" + str(exp_maxlatepkt) + "' AS 'Late Frame Count Threshold' " + \ "FROM RxEotStreamResults AS RxStr JOIN StreamBlock AS Sb " + \ "ON RxStr.ParentStreamBlock == Sb.Handle " + \ "WHERE LateFrameCount > " + str(exp_maxlatepkt) q_list.append(q) cmd.SetCollection('DisplayNameList', display_name_list) cmd.SetCollection('PassedVerdictExplanationList', pass_list) cmd.SetCollection('FailedVerdictExplanationList', fail_list) cmd.SetCollection('SqlQueryList', q_list) cmd.Set('UseMultipleResultsDatabases', True) elif cmd.IsTypeOf(PKG + '.VerifyDbQueryCommand'): query = "SELECT StreamBlockName AS Service, " + \ "'" + src + "' AS Source, " + \ "'" + dst + "' AS Destination, " + \ str(svlan) + " AS 'S-Vlan', " + \ str(cvlan) + " AS 'C-Vlan', " + \ "Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "Lp.Load || CASE Lp.LoadUnit " + \ "WHEN 'PERCENT_LINE_RATE' THEN '%' " + \ "WHEN 'BITS_PER_SECOND' THEN 'bps' " + \ "WHEN 'KILOBITS_PER_SECOND' THEN 'Kbps' " + \ "WHEN 'MEGABITS_PER_SECOND' THEN 'Mbps' " + \ "WHEN 'FRAMES_PER_SECOND' THEN 'Fps' " + \ "ELSE '' END " + \ "AS 'CIR', " + \ "TxRes.FrameCount-RxRes.FrameCount AS 'FL Count', " + \ "ROUND(CAST(TxRes.FrameCount-RxRes.FrameCount AS FLOAT)/TxRes.FrameCount,3) AS 'FLR', " + \ "ROUND(MinLatency*1e-3,3) AS 'Min FTD (ms)', " +\ "ROUND(AvgLatency*1e-3,3) AS 'Mean FTD (ms)', " + \ "ROUND(MaxLatency*1e-3,3) AS 'Max FTD (ms)', " + \ "ROUND(MinJitter*1e-3,3) AS 'Min FDV (ms)', " + \ "ROUND(AvgJitter*1e-3,3) AS 'Mean FDV (ms)', " + \ "ROUND(MaxJitter*1e-3,3) AS 'Max FDV (ms)', " + \ "OutSeqFrameCount AS 'Out of Sequence Frame Count', " + \ "LateFrameCount AS 'Late Frame Count' " + \ "FROM TxEotStreamResults AS TxRes INNER JOIN " + \ "RxEotStreamResults AS RxRes ON " + \ "TxRes.ParentStreamBlock == RxRes.ParentStreamBlock " + \ "INNER JOIN StreamBlock AS Sb ON " + \ "TxRes.ParentStreamBlock IN (" + ','.join(map(str, sb_hnd_list)) + ")" + \ "INNER JOIN StreamBlockLoadProfile As Lp ON " + \ "Sb.Handle||','||Lp.Handle = " + \ "(SELECT SourceHnd||','||TargetHnd " + \ "FROM RelationTable WHERE " + \ "Type='AffiliationStreamBlockLoadProfile') " + \ "WHERE Sb.Handle IN (" + ','.join(map(str, sb_hnd_list)) + ")" cmd.Set('SqlQuery', query) cmd.Set('DisplayName', 'Y.1564 ' + params + ' Summary Results') cmd.Set('PassedVerdictExplanation', 'Y.1564 ' + params + ' Summary Results') cmd.Set('FailedVerdictExplanation', 'ERROR found in Y.1564 ' + params + ' KPI Results.') cmd.Set('UseMultipleResultsDatabases', True) cmd.Set('ApplyVerdictToSummary', False) cmd.Set('OperationType', 'GREATER_THAN_OR_EQUAL') cmd.Set('RowCount', 0L) return ""
def run(TargetObjectList, TargetObjectTagList, MixInfo, MixTagName, AutoExpandTemplateMix): # TODO: Add sample JSON plLogger = PLLogger.GetLogger("methodology") stc_sys = CStcSystem.Instance() project = stc_sys.GetObject("Project") this_cmd = get_this_cmd() ctor = CScriptableCreator() # Validate the input MixInfo against its schema res = json_utils.validate_json(MixInfo, this_cmd.Get('MixInfoJsonSchema')) if res != '': plLogger.LogError(res) this_cmd.Set("Status", res) return False # Validate the hierarchy against our current command list... msg = mix_utils.run_validate_hierarchy(this_cmd, [hierarchy()]) if msg != '': err_str = 'Invalid Sequence: ' + msg plLogger.LogError(err_str) this_cmd.Set("Status", err_str) return False # Tag the commands in our command list according to our hierarchy information... tag_dict = mix_utils.run_tag_hierarchy(this_cmd, [hierarchy()]) # Setup for property chaining / outputting the tag dictionary... this_cmd.Set('GroupCommandTagInfo', json.dumps(tag_dict)) plLogger.LogInfo('GroupCommandTagInfo: ' + this_cmd.Get('GroupCommandTagInfo')) # Create the StmTemplateMix object... plLogger.LogInfo('Creating the route mix object...') mix = ctor.Create('StmTemplateMix', project) this_cmd.Set('StmTemplateMix', mix.GetObjectHandle()) # If a MixTagName was specified, then tag the mix with it... if MixTagName: tag_utils.add_tag_to_object(mix, MixTagName) # Copy the entire MixInfo into StmTemplateMix object... mix.Set('MixInfo', MixInfo) # Load the MixInfo... err_str, mix_info = json_utils.load_json(MixInfo) if err_str != "": plLogger.LogError(err_str) this_cmd.Set("Status", err_str) return False # Directly configure all tagged commands in our hierarchy... plLogger.LogDebug('setting up commands in the group based on ' + str(tag_dict)) plLogger.LogDebug('loading json from MixInfo: ' + str(MixInfo)) num_rows = len(mix_info.get('components', [])) plLogger.LogDebug('Number of Rows: ' + str(num_rows)) # Pass table to configurator - this guy will configure other commands per iteration... conf_cmd = tag_utils.get_tagged_objects_from_string_names([tag_dict['rowConfigurator']])[0] conf_cmd.Set('StmTemplateMix', mix.GetObjectHandle()) conf_cmd.Set('TagData', this_cmd.Get('GroupCommandTagInfo')) # Pass the StmTemplateMix to the CreateTemplateConfigCommand... ctc_cmd = tag_utils.get_tagged_objects_from_string_names([tag_dict['templateConfigurator']])[0] ctc_cmd.Set('StmTemplateMix', mix.GetObjectHandle()) ctc_cmd.Set('AutoExpandTemplate', False) # Setup Row Iterator (pass in number of rows) - the While command's expression command... iter_cmd = tag_utils.get_tagged_objects_from_string_names([tag_dict['rowIterator']])[0] iter_cmd.Set('IterMode', 'STEP') iter_cmd.Set('StepVal', '1') iter_cmd.Set('ValueType', 'RANGE') iter_cmd.Set('MinVal', 0.0) iter_cmd.Set('MaxVal', (float(num_rows) - 1.0)) return True
def test_run(stc): stc_sys = CStcSystem.Instance() proj = stc_sys.GetObject('Project') sequencer = stc_sys.GetObject('Sequencer') ctor = CScriptableCreator() command1 = ctor.Create(TTPKG + '.LoadAclTrafficRulesCommand', sequencer) command2 = ctor.Create(TPKG + '.LoadTrafficTemplateCommand', sequencer) command3 = ctor.Create(PKG + '.ModifyTemplatePropertyCommand', sequencer) command4 = ctor.Create(TPKG + '.ExpandTrafficMix1Command', sequencer) Cmd1.get_this_cmd = MagicMock(return_value=command1) Cmd2.get_this_cmd = MagicMock(return_value=command2) Cmd3.get_this_cmd = MagicMock(return_value=command3) Cmd4.get_this_cmd = MagicMock(return_value=command4) traf_mix = ctor.Create('StmTrafficMix', proj) assert traf_mix is not None mix_info = {'Load': str(100.0), 'LoadUnit': 'PERCENT_LINE_RATE', 'WeightList': ''} mix_elem = etree.Element('MixInfo', mix_info) assert mix_elem is not None xml = etree.tostring(mix_elem) traf_mix.Set('MixInfo', xml) assert xml == traf_mix.Get('MixInfo') mix = traf_mix.GetObjectHandle() assert mix is not None rules = 'test_CsvTraffic.rules' try: with open(rules, "w") as f: f.write(rules_file_content1()) msg = Cmd1.validate(1, [], template1(), '', '', False, False, mix, 0.0, rules, 1, True) assert msg == '' assert Cmd1.run(1, [], template1(), '', 'bad', False, False, mix, 40.0, rules, 2, True) Cmd4.run(mix) e = etree.fromstring(traf_mix.Get('MixInfo')) assert e is not None for w in e.get('WeightList').split(' '): assert float(w) == 4.0 sb_list = tag_utils.get_tagged_objects_from_string_names(['badttStreamBlock']) assert len(sb_list) == 10 for sb in sb_list: load_prof = sb.GetObject('StreamBlockLoadProfile', RelationType('AffiliationStreamBlockLoadProfile')) assert load_prof.Get('Load') == 4.0 rm_list = tag_utils.get_tagged_objects_from_string_names(['badttDstMac']) assert len(rm_list) == 10 for rm, v in zip(rm_list, ['00:01:02:03:04:05', '00:01:02:03:FE:FF', '00:01:02:03:FF:FF', '00:00:01:00:00:01', '00:00:01:00:00:01', '00:01:02:03:04:05', '00:01:02:03:FE:FE', '00:01:02:03:FF:FE', '00:00:01:00:00:01', '00:00:01:00:00:01']): assert rm.Get('Data') == v rm_list = tag_utils.get_tagged_objects_from_string_names(['badttSrcMac']) assert len(rm_list) == 10 for rm, v in zip(rm_list, ['00:01:02:03:33:FF', '00:01:02:03:FF:00', '00:01:02:04:00:00', '00:10:94:00:00:01', '00:10:94:00:00:01', '00:01:02:03:33:FF', '00:01:02:03:FF:01', '00:01:02:04:00:01', '00:10:94:00:00:01', '00:10:94:00:00:01']): assert rm.Get('Data') == v rm_list = tag_utils.get_tagged_objects_from_string_names(['badttDstIpAddr']) assert len(rm_list) == 10 for rm, v in zip(rm_list, ['1.1.1.1', '3.1.2.0', '4.1.2.0', '193.85.1.3', '193.85.1.3', '1.1.1.1', '3.1.2.1', '4.1.2.1', '193.85.1.3', '193.85.1.3']): assert rm.Get('Data') == v rm_list = tag_utils.get_tagged_objects_from_string_names(['badttSrcIpAddr']) assert len(rm_list) == 10 for rm, v in zip(rm_list, ['4.1.1.1', '6.1.0.255', '5.1.2.0', '41.1.1.1', '12.1.1.1', '4.1.1.1', '6.1.0.254', '5.1.2.1', '41.1.1.1', '12.1.1.1']): assert rm.Get('Data') == v finally: os.remove(rules) return
def validate(TagNameList, RxLoadPercent): plLogger = PLLogger.GetLogger('methodology') plLogger.LogDebug("DiffServConfigStreamBlockLoadCommand.Validate") if len(TagNameList) < 1: return "Error: Empty TagList" if (RxLoadPercent < 0) or (RxLoadPercent > 100): return "Error: RxLoadPercent value out of range" # Find the StreamBlock objects that have been tagged sb_obj_list = tag_utils.get_tagged_objects_from_string_names( TagNameList, remove_duplicates=True, ignore_tags_obj=True, class_name="StreamBlock") if not sb_obj_list: return "Error: No tagged stream block found" ''' Check ports - All stream blocks must have endpoints - All TX ports must be the same speed - All RX ports must be the same speed ''' tx_port_speeds = [] rx_port_speeds = [] for sb_obj in sb_obj_list: # Check that ports exist tx_port = sb_obj.GetParent() if not tx_port: return "Error: Stream block missing TX port" rx_port = sb_obj.GetObject('Port', RelationType('ExpectedRx')) if not rx_port: return "Error: Stream block missing RX port" # Check that we have active phys and add their speeds to list active_tx_phy = tx_port.GetObject('EthernetPhy', RelationType('ActivePhy')) if not active_tx_phy: return "Error: No active TX phy found" tx_line_speed = active_tx_phy.Get('LineSpeed') if tx_line_speed not in ETH_RATE_TABLE: return "Error: Unknown TX port speed detected" tx_port_speeds.append(ETH_RATE_TABLE[tx_line_speed]) active_rx_phy = rx_port.GetObject('EthernetPhy', RelationType('ActivePhy')) if not active_rx_phy: return "Error: No active RX phy found" rx_line_speed = active_rx_phy.Get('LineSpeed') if rx_line_speed not in ETH_RATE_TABLE: return "Error: Unknown RX port speed detected" rx_port_speeds.append(ETH_RATE_TABLE[rx_line_speed]) # Check that all TX speeds are the same if tx_port_speeds.count(tx_port_speeds[0]) != len(tx_port_speeds): return 'Error: All TX ports must be the same speed' # Check that all RX speeds are the same if rx_port_speeds.count(rx_port_speeds[0]) != len(rx_port_speeds): return 'Error: All RX ports must be the same speed' ''' Verify that the calculation yields a valid TX load Desired TX load = (RXLoad * RXLineSpeed)/(NumTXPorts * TXLineSpeed) ''' tx_load = (RxLoadPercent * rx_port_speeds[0]) / ((len(tx_port_speeds) * tx_port_speeds[0])) if (tx_load < 0) or (tx_load > 100): return "Error: TX Load calculation yields an invalid result. " + \ "Combination of ports and speeds must be changed." return ""
def run(TagNameList, RxLoadPercent): """ Given a list of tag names, find all the StreamBlocks with tags on the list and set their loads such that the aggregate load on each RX port is RxLoadPercent percent. - TagNameList is a list of strings - RxLoadPercent is a number between 0 and 100, inclusive """ plLogger = PLLogger.GetLogger('methodology') plLogger.LogDebug("DiffServConfigStreamBlockLoadCommand.run") plLogger.LogDebug("TagNameList: " + str(TagNameList)) # Find the StreamBlock objects that have been tagged sb_obj_list = tag_utils.get_tagged_objects_from_string_names( TagNameList, remove_duplicates=True, ignore_tags_obj=True, class_name="StreamBlock") if not sb_obj_list: plLogger.LogError("Error: No tagged stream block found") return False ''' Check ports - All stream blocks must have endpoints - All TX ports must be the same speed - All RX ports must be the same speed ''' # Create lists of ports tx_ports = [] tx_port_handles = [] rx_ports = [] rx_port_handles = [] for sb_obj in sb_obj_list: # Check that ports exist tx_port = sb_obj.GetParent() if not tx_port: plLogger.LogError("Error: Stream block missing TX port") return False # use handles to get rid of any duplicate ports. tx_port_handle = tx_port.GetObjectHandle() if tx_port_handle not in tx_port_handles: # add this port to the list tx_ports.append(tx_port) tx_port_handles.append(tx_port_handle) # Repeat for RX port rx_port = sb_obj.GetObject('Port', RelationType('ExpectedRx')) if not rx_port: plLogger.LogError("Error: Stream block missing RX port") return False # use handles to get rid of any duplicate ports. rx_port_handle = rx_port.GetObjectHandle() if rx_port_handle not in rx_port_handles: # add this port to the list rx_ports.append(rx_port) rx_port_handles.append(rx_port_handle) plLogger.LogDebug("tx_ports: " + str(tx_ports)) plLogger.LogDebug("tx_ports len: " + str(len(tx_ports))) plLogger.LogDebug("tx_port_handles: " + str(tx_port_handles)) plLogger.LogDebug("tx_port_handles len: " + str(len(tx_port_handles))) plLogger.LogDebug("rx_ports: " + str(rx_ports)) plLogger.LogDebug("rx_ports len: " + str(len(rx_ports))) # Now process each port tx_port_speeds = [] rx_port_speeds = [] for tx_port in tx_ports: # Check that we have active phys and add their speeds to list active_tx_phy = tx_port.GetObject('EthernetPhy', RelationType('ActivePhy')) if not active_tx_phy: plLogger.LogError("Error: No active TX phy found") return False tx_line_speed = active_tx_phy.Get('LineSpeed') if tx_line_speed not in ETH_RATE_TABLE: plLogger.LogError("Error: Unknown TX port speed detected") return False tx_port_speeds.append(ETH_RATE_TABLE[tx_line_speed]) for rx_port in rx_ports: active_rx_phy = rx_port.GetObject('EthernetPhy', RelationType('ActivePhy')) if not active_rx_phy: plLogger.LogError("Error: No active RX phy found") return False rx_line_speed = active_rx_phy.Get('LineSpeed') if rx_line_speed not in ETH_RATE_TABLE: plLogger.LogError("Error: Unknown RX port speed detected") return False rx_port_speeds.append(ETH_RATE_TABLE[rx_line_speed]) # Check that all TX speeds are the same if tx_port_speeds.count(tx_port_speeds[0]) != len(tx_port_speeds): plLogger.LogError("Error: All TX ports must be the same speed") return False # Check that all RX speeds are the same if rx_port_speeds.count(rx_port_speeds[0]) != len(rx_port_speeds): plLogger.LogError("Error: All RX ports must be the same speed") return False ''' Verify that the calculation yields a valid TX load Desired TX load = (RXLoad * RXLineSpeed)/(NumStreamBlocks * TXLineSpeed) ''' tx_load = (RxLoadPercent * rx_port_speeds[0]) / ((len(sb_obj_list) * tx_port_speeds[0])) if (tx_load < 0) or (tx_load > 100): err_txt = "Error: TX Load calculation yields an invalid result. " + \ "Combination of ports and speeds must be changed." plLogger.LogError(err_txt) return False # Get the load profile objects and set their loads for sb_obj in sb_obj_list: plLogger.LogDebug("Found sb: " + str(sb_obj)) loadprofile = sb_obj.GetObject('StreamBlockLoadProfile', RelationType('Affiliationstreamblockloadprofile')) if not loadprofile: plLogger.LogError("Could not find Stream Block load profile.") return False loadprofile.Set("Load", str(tx_load)) return True
def y1564ResultsReport(tagname, b, params): plLogger = PLLogger.GetLogger("Methodology") plLogger.LogDebug("Running custom y1564ResultsReport script...") if not CObjectRefStore.Exists(OBJ_KEY): plLogger.LogWarn('Y1564SvcCfgRampCommand was not called. ' + 'Using default threshold values.') exp_pktloss = 0 exp_avgjitter = 0.05 exp_maxjitter = 0.2 exp_avglatency = 0.7 exp_maxlatency = 1.0 exp_maxoop = 0 exp_maxlatepkt = 0 else: cmd_dict = CObjectRefStore.Get(OBJ_KEY) exp_pktloss = cmd_dict['exp_pktloss'] exp_avgjitter = cmd_dict['exp_avgjitter'] exp_maxjitter = cmd_dict['exp_maxjitter'] exp_avglatency = cmd_dict['exp_avglatency'] exp_maxlatency = cmd_dict['exp_maxlatency'] exp_maxoop = cmd_dict['exp_maxoop'] exp_maxlatepkt = cmd_dict['exp_maxlatepkt'] res_cmd_list = tag_utils.get_tagged_objects_from_string_names(tagname) plLogger.LogDebug("res_cmd_list: " + str(res_cmd_list)) # String input used for queries q_devSelect = "DevInfo.SRC AS 'SRC', DevInfo.DST AS 'DST', " + \ "DevInfo.SVLAN AS 'S-Vlan', DevInfo.CVLAN AS 'C-Vlan'" q_devInfo = "(SELECT Vlan.ParentHnd AS ParentHnd, SRC, DST, SVLAN, CVLAN, SbHnd " + \ "FROM (SELECT VOne.ParentHnd, VOne.Name, VOne.VlanId AS CVLAN, " + \ "VTwo.ParentHnd, VTwo.Name, VTwo.VlanId AS SVLAN FROM VlanIf as VOne " + \ "JOIN VlanIf as VTwo ON VOne.ParentHnd = VTwo.ParentHnd WHERE " + \ "VOne.Handle != VTwo.Handle GROUP BY VOne.ParentHnd) AS Vlan " + \ "JOIN (SELECT DstInfo.Address AS DST, SrcInfo.Address AS SRC, " + \ "SrcInfo.SourceHnd AS SbHnd, SrcInfo.ParentHnd AS ParentHnd FROM " + \ "(SELECT * FROM IPv4If AS Ip JOIN (SELECT * FROM RelationTable " + \ "WHERE Type = 'DstBinding') As Dst ON Ip.Handle = Dst.TargetHnd) AS DstInfo " + \ "JOIN (SELECT * FROM Ipv4If AS Ip JOIN (SELECT * FROM RelationTable " + \ "WHERE Type = 'SrcBinding') As Src ON Ip.Handle = Src.TargetHnd) " + \ "AS SrcInfo ON SrcInfo.SourceHnd = DstInfo.SourceHnd) AS Ip ON " + \ "Ip.ParentHnd = Vlan.ParentHnd GROUP BY SbHnd) As DevInfo" for cmd in res_cmd_list: if cmd.IsTypeOf(PKG + '.VerifyMultipleDbQueryCommand'): q_list = [] display_name_list = [] pass_list = [] fail_list = [] display_name_list.append("Mean Frame Transfer Delay (FTD) Results") pass_list.append("Mean FTD is within the configured threshold of " + str(exp_avglatency) + " ms.") fail_list.append("Mean FTD exceeded the configured threshold of " + str(exp_avglatency) + " ms.") q = "SELECT Sb.Name AS 'Streamblock', " + str(q_devSelect) + \ ", Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "ROUND(AvgLatency*1e-3,3) AS 'Mean FTD (ms)', " + \ str(exp_avglatency) + " AS 'Mean FTD Threshold (ms)' " + \ "FROM " + str(q_devInfo) + " JOIN RxEotStreamResults As RxStr " + \ "JOIN StreamBlock AS Sb ON RxStr.ParentStreamBlock == Sb.Handle " + \ "WHERE DevInfo.SbHnd = Sb.Handle AND " + \ "ROUND(AvgLatency*1e-3,3) > " + str(exp_avglatency) q_list.append(q) display_name_list.append("Max Frame Transfer Delay (FTD) Results") pass_list.append("Max FTD is within the configured threshold of " + str(exp_maxlatency) + " ms.") fail_list.append("Max FTD exceeded the configured threshold of " + str(exp_maxlatency) + " ms.") q = "SELECT Sb.Name AS 'Streamblock', " + str(q_devSelect) + \ ", Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "ROUND(MaxLatency*1e-3,3) AS 'Max FTD (ms)', " + \ str(exp_maxlatency) + " AS 'Max FTD Threshold (ms)' " + \ "FROM " + str(q_devInfo) + " JOIN RxEotStreamResults As RxStr " + \ "JOIN StreamBlock AS Sb ON RxStr.ParentStreamBlock == Sb.Handle " + \ "WHERE DevInfo.SbHnd = Sb.Handle AND " + \ "ROUND(MaxLatency*1e-3,3) > " + str(exp_maxlatency) q_list.append(q) display_name_list.append("RFC4689 Mean Frame Delay Variation (FDV) Results") pass_list.append("RFC4689 Mean FDV is within the configured threshold of " + str(exp_avgjitter) + " ms.") fail_list.append("RFC4689 Mean FDV exceeded the configured threshold of " + str(exp_avgjitter) + " ms.") q = "SELECT Sb.Name AS 'Streamblock', " + str(q_devSelect) + \ ", Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "ROUND(AvgJitter*1e-3,3) AS 'RFC4689 Mean FDV (ms)', " + \ str(exp_avgjitter) + " AS 'RFC4689 Mean FDV Threshold (ms)' " + \ "FROM " + str(q_devInfo) + " JOIN RxEotStreamResults As RxStr " + \ "JOIN StreamBlock AS Sb ON RxStr.ParentStreamBlock == Sb.Handle " + \ "WHERE DevInfo.SbHnd = Sb.Handle AND " + \ "ROUND(AvgJitter*1e-3,3) > " + str(exp_avgjitter) q_list.append(q) display_name_list.append("Max Frame Delay Variation (FDV) Results") pass_list.append("Max FDV is within the configured threshold of " + str(exp_maxjitter) + " ms.") fail_list.append("Max FDV exceeded the configured threshold of " + str(exp_maxjitter) + " ms.") q = "SELECT Sb.Name AS 'Streamblock', " + str(q_devSelect) + \ ", Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "ROUND(MaxJitter*1e-3,3) AS 'Max FDV (ms)', " + \ str(exp_maxjitter) + " AS 'Max FDV Threshold (ms)' " + \ "FROM " + str(q_devInfo) + " JOIN RxEotStreamResults As RxStr " + \ "JOIN StreamBlock AS Sb ON RxStr.ParentStreamBlock == Sb.Handle " + \ "WHERE DevInfo.SbHnd = Sb.Handle AND " + \ "ROUND(MaxJitter*1e-3,3) > " + str(exp_maxjitter) q_list.append(q) display_name_list.append("Frame Loss (FL) Results") pass_list.append("Frame Loss Count is within the configured threshold of " + str(exp_pktloss) + ".") fail_list.append("Frame Loss Count exceeded the configured threshold of " + str(exp_pktloss) + ".") q = "SELECT Sb.Name AS 'Streamblock', " + str(q_devSelect) + \ ", Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "TxRes.FrameCount - RxRes.FrameCount As 'FL Count', " + \ str(exp_pktloss) + " AS 'FL Count Threshold' " + \ "FROM " + str(q_devInfo) + " JOIN RxEotStreamResults AS RxRes " + \ "JOIN TxEotStreamResults AS TxRes JOIN Streamblock AS Sb " + \ "ON RxRes.ParentStreamBlock = TxRes.ParentStreamblock AND " + \ "TxRes.ParentStreamblock = Sb.Handle " + \ "WHERE DevInfo.SbHnd = Sb.Handle AND " + \ "TxRes.FrameCount - RxRes.FrameCount > " + str(exp_pktloss) q_list.append(q) display_name_list.append("Out of Order Frame Results") pass_list.append("Out of Order Frame Count is within the configured threshold of " + str(exp_maxoop) + ".") fail_list.append("Out of Order Frame Count exceeded the configured threshold of " + str(exp_maxoop) + ".") q = "SELECT Sb.Name AS 'Streamblock', " + str(q_devSelect) + \ ", Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "OutSeqFrameCount AS 'Out of Order Frame Count', " + \ str(exp_maxoop) + " AS 'Out of Order Frame Count Threshold' " + \ "FROM " + str(q_devInfo) + " JOIN RxEotStreamResults As RxStr " + \ "JOIN StreamBlock AS Sb ON RxStr.ParentStreamBlock == Sb.Handle " + \ "WHERE DevInfo.SbHnd = Sb.Handle AND " + \ "OutSeqFrameCount > " + str(exp_maxoop) q_list.append(q) display_name_list.append("Late Frame Results") pass_list.append("Late Frame Count is within the configured threshold of " + str(exp_maxlatepkt) + ".") fail_list.append("Late Frame Count exceeded the configured threshold of " + str(exp_maxlatepkt) + ".") q = "SELECT Sb.Name AS 'Streamblock', " + str(q_devSelect) + \ ", Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "LateFrameCount AS 'Late Frame Count', " + \ str(exp_maxlatepkt) + " AS 'Late Frame Count Threshold' " + \ "FROM " + str(q_devInfo) + " JOIN RxEotStreamResults As RxStr " + \ "JOIN StreamBlock AS Sb ON RxStr.ParentStreamBlock == Sb.Handle " + \ "WHERE DevInfo.SbHnd = Sb.Handle AND " + \ "LateFrameCount > " + str(exp_maxlatepkt) q_list.append(q) cmd.SetCollection('DisplayNameList', display_name_list) cmd.SetCollection('PassedVerdictExplanationList', pass_list) cmd.SetCollection('FailedVerdictExplanationList', fail_list) cmd.SetCollection('SqlQueryList', q_list) cmd.Set('UseMultipleResultsDatabases', True) elif cmd.IsTypeOf(PKG + '.VerifyDbQueryCommand'): query = "SELECT Sb.Name AS 'Streamblock', " + str(q_devSelect) + \ ", Sb.FixedFrameLength AS 'Frame Size (bytes)', " + \ "Lp.Load || CASE Lp.LoadUnit " + \ "WHEN 'PERCENT_LINE_RATE' THEN '%' " + \ "WHEN 'BITS_PER_SECOND' THEN 'bps' " + \ "WHEN 'KILOBITS_PER_SECOND' THEN 'Kbps' " + \ "WHEN 'MEGABITS_PER_SECOND' THEN 'Mbps' " + \ "WHEN 'FRAMES_PER_SECOND' THEN 'Fps' " + \ "ELSE '' END AS 'CIR', " + \ "TxRes.FrameCount-RxRes.FrameCount AS 'FL Count', " + \ "ROUND(CAST(TxRes.FrameCount-RxRes.FrameCount AS " + \ "FLOAT)/TxRes.FrameCount,3) AS 'FL Ratio', " + \ "ROUND(MinLatency*1e-3,3) AS 'Min FTD (ms)', " + \ "ROUND(AvgLatency*1e-3,3) AS 'Mean FTD (ms)', " + \ "ROUND(MaxLatency*1e-3,3) AS 'Max FTD (ms)', " + \ "ROUND(MinJitter*1e-3,3) AS 'Min FDV (ms)', " + \ "ROUND(AvgJitter*1e-3,3) AS 'Mean FDV (ms)', " + \ "ROUND(MaxJitter*1e-3,3) AS 'Max FDV (ms)', " + \ "OutSeqFrameCount AS 'Out of Order Frame Count', " + \ "LateFrameCount AS 'Late Frame Count' " + \ "FROM " + str(q_devInfo) + \ " JOIN RxEotStreamResults as RxRes JOIN TxEotStreamResults as TxRes ON " + \ "TxRes.ParentStreamBlock = RxRes.ParentStreamBlock JOIN Streamblock AS Sb " + \ "ON TxRes.ParentStreamBlock = Sb.Handle JOIN RelationTable as Rt ON " + \ "Rt.type = 'AffiliationStreamBlockLoadProfile' AND Sb.Handle = Rt.SourceHnd " + \ "JOIN StreamBlockLoadProfile as Lp ON Lp.Handle = Rt.TargetHnd " + \ "WHERE DevInfo.SbHnd = Sb.Handle" cmd.Set('SqlQuery', query) cmd.Set('DisplayName', 'Y.1564 Summary Results') cmd.Set('PassedVerdictExplanation', 'Y.1564 Summary Results') cmd.Set('FailedVerdictExplanation', 'ERROR found in Y.1564 KPI Results.') cmd.Set('UseMultipleResultsDatabases', True) cmd.Set('ApplyVerdictToSummary', False) cmd.Set('OperationType', 'GREATER_THAN_OR_EQUAL') cmd.Set('RowCount', 0L) return ""
def test_run(stc): sequencer = CStcSystem.Instance().GetObject("Sequencer") project = CStcSystem.Instance().GetObject("Project") ctor = CScriptableCreator() hnd_reg = CHandleRegistry.Instance() cmd = ctor.Create(PKG + ".CreateProtocolMixCommand", sequencer) plLogger = PLLogger.GetLogger("test_CreateProtocolMixCommand.test_run") plLogger.LogInfo("start") CreateProtoMixCmd.get_this_cmd = MagicMock(return_value=cmd) ret_val = CreateProtoMixCmd.run(get_example_mix_info(), "UnitTestProtoMix", "", False) assert cmd.Get("Status") == "" assert ret_val # Check the created StmTemplateMix mix_hnd = cmd.Get("StmTemplateMix") mix = hnd_reg.Find(mix_hnd) assert mix assert mix.Get("MixInfo") == get_example_mix_info() # Find the tagged commands tag_json = cmd.Get("GroupCommandTagInfo") assert tag_json != "" err_str, tag_dict = json_utils.load_json(tag_json) assert err_str == "" tagged_obj_list = tag_utils.get_tagged_objects_from_string_names([tag_dict["rowIterator"]]) assert len(tagged_obj_list) == 1 obj_iter = tagged_obj_list[0] assert obj_iter.IsTypeOf(PKG + ".ObjectIteratorCommand") assert obj_iter.Get("StepVal") == 1 assert obj_iter.Get("MaxVal") == 0.0 assert obj_iter.Get("MinVal") == 0.0 assert obj_iter.Get("IterMode") == "STEP" assert obj_iter.Get("ValueType") == "RANGE" tagged_obj_list = tag_utils.get_tagged_objects_from_string_names([tag_dict["rowConfigurator"]]) assert len(tagged_obj_list) == 1 config_cmd = tagged_obj_list[0] assert config_cmd.IsTypeOf(PKG + ".IteratorConfigMixParamsCommand") assert mix_hnd == config_cmd.Get("StmTemplateMix") # Check the created StmProtocolMix proto_mix_hnd = cmd.Get("StmTemplateMix") proto_mix = hnd_reg.Find(proto_mix_hnd) assert proto_mix # Check the Tag tags = project.GetObject("Tags") assert tags user_tag_list = tags.GetObjects("Tag") assert len(user_tag_list) exp_tag = None for user_tag in user_tag_list: if user_tag.Get("Name") == "UnitTestProtoMix": exp_tag = user_tag break assert exp_tag tag_target = exp_tag.GetObject("StmTemplateMix", RelationType("UserTag", 1)) assert tag_target assert tag_target.GetObjectHandle() == proto_mix.GetObjectHandle() tagged_obj_list = tag_utils.get_tagged_objects_from_string_names([tag_dict["templateConfigurator"]]) assert len(tagged_obj_list) == 1 ctc_cmd = tagged_obj_list[0] assert ctc_cmd.IsTypeOf(PKG + ".CreateTemplateConfigCommand") ctc_input_mix_hnd = ctc_cmd.Get("StmTemplateMix") assert ctc_input_mix_hnd == proto_mix.GetObjectHandle()
def run(RouteMixList, RouteMixTagList, RouteCount): plLogger = PLLogger.GetLogger("methodology") obj_list = [] this_cmd = get_this_cmd() if RouteMixList: obj_list = CCommandEx.ProcessInputHandleVec("StmTemplateMix", RouteMixList) if RouteMixTagList: obj_list = obj_list + \ tag_utils.get_tagged_objects_from_string_names( RouteMixTagList) if len(obj_list) == 0: err_str = "Neither RouteMixList nor RouteMixTagList specified a " + \ "valid StmTemplateMix object." this_cmd.Set("Status", err_str) plLogger.LogError(err_str) return False if RouteCount < 1: err_str = "RouteCount must be at least 1." this_cmd.Set("Status", err_str) plLogger.LogError(err_str) return False obj_dict = {obj.GetObjectHandle(): obj for obj in obj_list} for mix in obj_dict.values(): # Get all of the StmTemplateConfig objects for this mix... templates = mix.GetObjects("StmTemplateConfig") # Get the MixInfo str_mix_info = mix.Get("MixInfo") # Validate the input MixInfo against its schema # res = json_utils.validate_json(str_mix_info, # get_this_cmd().Get("MixInfoJsonSchema")) # if res != "": # this_cmd.Set("Status", res) # plLogger.LogError(res) # return False plLogger.LogInfo("string mix_info: " + str(str_mix_info)) err_str, mix_info = json_utils.load_json(str_mix_info) if err_str != "": plLogger.LogError(err_str) this_cmd.Set("Status", err_str) return False plLogger.LogInfo("mix_info: " + str(mix_info)) component_list = mix_info["components"] plLogger.LogInfo("number of components: " + str(len(component_list))) # Check the MixInfo component_list length against the # number of templates if len(templates) != len(component_list): err_str = "There are " + str(len(templates)) + " under the " + \ "StmTemplateMix " + mix.Get("Name") + " (" + \ str(mix.GetObjectHandle()) + ") but " + \ str(len(component_list)) + \ " components in the MixInfo. " + \ "These MUST match." plLogger.LogError(err_str) this_cmd.Set("Status", err_str) return False # Record what we will use over the whole mix mix_info["routeCount"] = RouteCount # Process the weight parameter static_list = [] percent_list = [] use_percent_list = [] for component in component_list: weight = component["weight"] is_percent, act_val, err_str = weight_ops.parse_weight_string( weight) if err_str != "": plLogger.LogError(err_str) this_cmd.Set("Status", err_str) return False if is_percent: static_list.append(0) percent_list.append(act_val) else: static_list.append(act_val) percent_list.append(0) use_percent_list.append(is_percent) total_static_count = sum(static_list) total_percent = sum(percent_list) plLogger.LogDebug("total_static_count: " + str(total_static_count)) plLogger.LogDebug("total_percent: " + str(total_percent)) # Don't allow the aggregate of static counts to exceed the # configured total route count... if total_static_count > RouteCount: err_str = "Sum total of the static counts (" + \ str(int(total_static_count)) + ") exceeds the total " + \ "configured RouteCount (" + str(RouteCount) + ")." plLogger.LogError(err_str) this_cmd.Set("Status", err_str) return False # Don't allow the total percent to exceed 100% if total_percent > 100: err_str = "Sum total of the weights defined as percentages (" + \ str(total_percent) + "%) exceeds 100%." plLogger.LogError(err_str) this_cmd.Set("Status", err_str) return False # Error if there is no RouteCount left to divide amongst # the weighted components (NetworkCount == 0 probably not allowed) if total_percent > 0 and total_static_count == RouteCount: err_str = "Not enough total RouteCount to distribute routes " + \ "to all components of the mix. The required total static " + \ "route count will use up all of the RouteCount leaving " + \ "nothing to distribute on the percent-based weighted " + \ "components." plLogger.LogError(err_str) this_cmd.Set("Status", err_str) return False # Calculate how much of the RouteCount is left for the # weighted components... total_percent_count = RouteCount - total_static_count # Check that each percent-based weighted component can get # at least 1 route if total_percent_count < sum(use_percent_list): err_str = "Not enough total RouteCount to distribute routes " + \ "to all components of the mix. Once the static counts " + \ "are handled (if any), there aren't enough routes left (" + \ str(total_percent_count) + ") such that each " + \ "percent-based mix component will get at least one route." plLogger.LogError(err_str) this_cmd.Set("Status", err_str) return False # Calculate the percent weighted counts from the percents... weighted_counts = weight_ops.allocate_weighted_list( total_percent_count, percent_list, allow_fraction=False) # Apply the counts across each component # Assume apply in creation order to map components to templates i = 0 plLogger.LogInfo("weighted_counts: " + str(weighted_counts)) plLogger.LogInfo("static_list: " + str(static_list)) for component, template in zip(component_list, templates): act_value = 0.0 if use_percent_list[i]: act_value = weighted_counts[i] else: act_value = static_list[i] # Note what we chose to apply and then apply it... component["appliedValue"] = act_value # Update the NetworkBlocks err_str = update_generated_objects(template, act_value) if err_str != "": plLogger.LogError(err_str) this_cmd.Set("Status", err_str) return False i = i + 1 # Update the mix with our changes... mix.Set("MixInfo", json.dumps(mix_info)) return True