Best Python code snippet using radish
debug.py
Source:debug.py
...20 print os.strerror(errno.ETIMEDOUT)21 os._exit(1)22def get_max_width(table, index):23 return max([len(row[index]) for row in table])24def pretty_print_table(table):25 col_paddings = []26 for i in range(len(table[0])):27 col_paddings.append(get_max_width(table, i))28 for row in table:29 print row[0].encode('UTF-8').ljust(col_paddings[0] + 1),30 for i in range(1, len(row)):31 col = row[i].encode('UTF-8').rjust(col_paddings[i] + 2)32 print col,33 print "\n",34class listConEdgesAction(argparse.Action):35 def __call__(self, parser, namespace, values, option_string=None):36 params = {"debug":"list_edges", "apiVersion":int(values[0])}37 reply = remote_server.listEdgesDebugDump(**params)38 if namespace.verbose:39 print json.dumps(reply, sort_keys = True, indent = 2)40 return41 if values[0] == "3":42 edges = []43 edges.append(["Name", "Enterprise", "Logical ID", "VC Private IP"])44 for entry in reply:45 edges.append([entry["name"], entry["enterprise_id"], entry["vceid"], entry["priv_ip"]])46 pretty_print_table(edges)47 else:48 print json.dumps(reply, sort_keys = True, indent = 2)49class pathStatsDumpAction(argparse.Action):50 def __call__(self, parser, namespace, values, option_string=None):51 params = {"debug":"path_stats"}52 reply = remote_server.pathStatsDebugDump(**params)53 print json.dumps(reply, sort_keys = True, indent = 2)54class linkStatsDumpAction(argparse.Action):55 def __call__(self, parser, namespace, values, option_string=None):56 params = {"debug":"link_stats"}57 reply = remote_server.linkStatsDebugDump(**params)58 print json.dumps(reply, sort_keys = True, indent = 2)59class peerDumpAction(argparse.Action):60 def __call__(self, parser, namespace, values, option_string=None):61 params = {"debug":"peers"}62 reply = remote_server.peerDebugDump(**params)63 #print json.dumps(reply, sort_keys = True, indent = 2)64 if namespace.verbose:65 print json.dumps(reply, sort_keys = True, indent = 2)66 return67 peers = []68 peers.append(["Enterprise", "EnterpriseID", "Type", "Name", "Destination", "MTU", "Reachable"])69 for entry in reply:70 peertbl = entry["peers"]71 for peer in peertbl:72 peers.append([str(entry["enterprise_name"]), str(entry["enterprise_id"]), peer["type"], str(peer["name"]), peer["destination"], str(peer["mtu"]), str(peer["reachable"])])73 pretty_print_table(peers)74class endpointDumpAction(argparse.Action):75 def __call__(self, parser, namespace, values, option_string=None):76 params = {"debug":"endpoints"}77 reply = remote_server.endpointDebugDump(**params)78 if namespace.verbose:79 print json.dumps(reply, sort_keys = True, indent = 2)80 return81 endpoints = []82 endpoints.append(["src_ip", "dst_ip", "refcnt"])83 for entry in reply:84 endpoints.append([str(entry["src_ip"]), str(entry["dst_ip"]), str(entry["refcnt"])])85 pretty_print_table(endpoints)86class routeDumpAction(argparse.Action):87 def __call__(self, parser, namespace, values, option_string=None):88 params = {"debug":"routes"}89 if values:90 if (len(values) == 2):91 params = {"entr": values[0], "dip": values[1]}92 else:93 params = {"entr": values[0], "dip": "all"}94 else:95 params = {"entr": "all", "dip":"all"}96 reply = remote_server.routeDebugDump(**params)97 if namespace.verbose:98 print json.dumps(reply, sort_keys = True, indent = 2)99 return100 routes = []101 routes.append(["EnterpriseID", "Address", "Netmask", "Type", "Destination", "Reachable", "Metric", "Preference", "Flags", "C-Tag", "S-Tag", "Handoff", "Mode", "Age"])102 for entry in reply:103 routetbl = entry["routes"]104 for route in routetbl:105 if str(route["type"]) == "edge2edge":106 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), "N/A", "N/A", str(route["age_s"])])107 elif str(route["type"]) == "datacenter":108 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), "0", str(-1), str(-1), "N/A", "N/A", str(route["age_s"])])109 else :110 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), str(route["handoff"]), str(route["mode"]), str(route["age_s"])])111 pretty_print_table(routes)112 print "P - PG, B - BGP, D - DCE, L - LAN SR, C - Connected, O - External, W - WAN SR, S - SecureEligible, R - Remote, s - self, H - HA, m - Management, n - nonVelocloud, v - ViaVeloCloud"113class routeNoneDumpAction(argparse.Action):114 def __call__(self, parser, namespace, values, option_string=None):115 params = {"debug":"routes"}116 reply = remote_server.routeNoneDebugDump(**params)117 if namespace.verbose:118 print json.dumps(reply, sort_keys = True, indent = 2)119 return120 routes = []121 routes.append(["Address", "Netmask", "Type", "Destination", "Reachable", "Metric", "Preference", "Flags", "C-Tag", "S-Tag", "Handoff", "Mode"])122 for route in reply:123 if str(route["type"]) == "edge2edge":124 routes.append([route["address"], route["netmask"], route["type"],125 route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), "N/A", "N/A"])126 elif str(route["type"]) == "datacenter":127 routes.append([route["address"], route["netmask"], route["type"],128 route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), "0", str(-1), str(-1), "N/A", "N/A"])129 else :130 routes.append([route["address"], route["netmask"], route["type"],131 route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), str(route["handoff"]), str(route["mode"])])132 pretty_print_table(routes)133class routeE2EDumpAction(argparse.Action):134 def __call__(self, parser, namespace, values, option_string=None):135 params = {"debug":"routes"}136 if values:137 if (len(values) == 2):138 params = {"entr": values[0], "dip": values[1]}139 else:140 params = {"entr": values[0], "dip": "all"}141 else:142 params = {"entr": "all", "dip":"all"}143 reply = remote_server.routeE2EDebugDump(**params)144 if namespace.verbose:145 print json.dumps(reply, sort_keys = True, indent = 2)146 return147 routes = []148 routes.append(["EnterpriseID", "Address", "Netmask", "Type", "Destination", "Reachable", "Metric", "Preference", "Flags", "C-Tag", "S-Tag", "Handoff", "Mode", "Age"])149 for entry in reply:150 routetbl = entry["routes"]151 for route in routetbl:152 if str(route["type"]) == "edge2edge":153 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), "N/A", "N/A", str(route["age_s"])])154 elif str(route["type"]) == "datacenter":155 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), "0", str(-1), str(-1), "N/A", "N/A", str(route["age_s"])])156 else :157 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), str(route["handoff"]), str(route["mode"]), str(route["age_s"])])158 pretty_print_table(routes)159class routePGDumpAction(argparse.Action):160 def __call__(self, parser, namespace, values, option_string=None):161 params = {"debug":"routes"}162 if values:163 if (len(values) == 2):164 params = {"entr": values[0], "dip": values[1]}165 else:166 params = {"entr": values[0], "dip": "all"}167 else:168 params = {"entr": "all", "dip":"all"}169 reply = remote_server.routePGDebugDump(**params)170 if namespace.verbose:171 print json.dumps(reply, sort_keys = True, indent = 2)172 return173 routes = []174 routes.append(["EnterpriseID", "Address", "Netmask", "Type", "Destination", "Reachable", "Metric", "Preference", "Flags", "C-Tag", "S-Tag", "Handoff", "Mode", "Age"])175 for entry in reply:176 routetbl = entry["routes"]177 for route in routetbl:178 if str(route["type"]) == "edge2edge":179 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), "N/A", "N/A", str(route["age_s"])])180 elif str(route["type"]) == "datacenter":181 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), "0", str(-1), str(-1), "N/A", "N/A", str(route["age_s"])])182 else :183 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), str(route["handoff"]), str(route["mode"]), str(route["age_s"])])184 pretty_print_table(routes)185class routeE2DCDumpAction(argparse.Action):186 def __call__(self, parser, namespace, values, option_string=None):187 params = {"debug":"routes"}188 if values:189 if (len(values) == 2):190 params = {"entr": values[0], "dip": values[1]}191 else:192 params = {"entr": values[0], "dip": "all"}193 else:194 params = {"entr": "all", "dip":"all"}195 reply = remote_server.routeE2DCDebugDump(**params)196 if namespace.verbose:197 print json.dumps(reply, sort_keys = True, indent = 2)198 return199 routes = []200 routes.append(["EnterpriseID", "Address", "Netmask", "Type", "Destination", "Reachable", "Metric", "Preference", "Flags", "C-Tag", "S-Tag", "Handoff", "Mode", "Age"])201 for entry in reply:202 routetbl = entry["routes"]203 for route in routetbl:204 if str(route["type"]) == "edge2edge":205 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), "N/A", "N/A", str(route["age_s"])])206 elif str(route["type"]) == "datacenter":207 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), "0", str(-1), str(-1), "N/A", "N/A", str(route["age_s"])])208 else :209 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), str(route["handoff"]), str(route["mode"]), str(route["age_s"])])210 pretty_print_table(routes)211class routeE2EPGDumpAction(argparse.Action):212 def __call__(self, parser, namespace, values, option_string=None):213 params = {"debug":"routes"}214 if values:215 if (len(values) == 2):216 params = {"entr": values[0], "dip": values[1]}217 else:218 params = {"entr": values[0], "dip": "all"}219 else:220 params = {"entr": "all", "dip":"all"}221 reply = remote_server.routeE2EPGDebugDump(**params)222 if namespace.verbose:223 print json.dumps(reply, sort_keys = True, indent = 2)224 return225 routes = []226 routes.append(["EnterpriseID", "Address", "Netmask", "Type", "Destination", "Reachable", "Metric", "Preference", "Flags", "C-Tag", "S-Tag", "Handoff", "Mode", "Age"])227 for entry in reply:228 routetbl = entry["routes"]229 for route in routetbl:230 if str(route["type"]) == "edge2edge":231 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), "N/A", "N/A", str(route["age_s"])])232 elif str(route["type"]) == "datacenter":233 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), "0", str(-1), str(-1), "N/A", "N/A", str(route["age_s"])])234 else :235 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), str(route["handoff"]), str(route["mode"]), str(route["age_s"])])236 pretty_print_table(routes)237class routeE2EDCDumpAction(argparse.Action):238 def __call__(self, parser, namespace, values, option_string=None):239 params = {"debug":"routes"}240 if values:241 if (len(values) == 2):242 params = {"entr": values[0], "dip": values[1]}243 else:244 params = {"entr": values[0], "dip": "all"}245 else:246 params = {"entr": "all", "dip":"all"}247 reply = remote_server.routeE2EDCDebugDump(**params)248 if namespace.verbose:249 print json.dumps(reply, sort_keys = True, indent = 2)250 return251 routes = []252 routes.append(["EnterpriseID", "Address", "Netmask", "Type", "Destination", "Reachable", "Metric", "Preference", "Flags", "C-Tag", "S-Tag", "Handoff", "Mode", "Age"])253 for entry in reply:254 routetbl = entry["routes"]255 for route in routetbl:256 if str(route["type"]) == "edge2edge":257 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), "N/A", "N/A", str(route["age_s"])])258 elif str(route["type"]) == "datacenter":259 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), "0", str(-1), str(-1), "N/A", "N/A", str(route["age_s"])])260 else :261 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), str(route["handoff"]), str(route["mode"]), str(route["age_s"])])262 pretty_print_table(routes)263class routePGDCDumpAction(argparse.Action):264 def __call__(self, parser, namespace, values, option_string=None):265 params = {"debug":"routes"}266 if values:267 if (len(values) == 2):268 params = {"entr": values[0], "dip": values[1]}269 else:270 params = {"entr": values[0], "dip": "all"}271 else:272 params = {"entr": "all", "dip":"all"}273 reply = remote_server.routePGDCDebugDump(**params)274 if namespace.verbose:275 print json.dumps(reply, sort_keys = True, indent = 2)276 return277 routes = []278 routes.append(["EnterpriseID", "Address", "Netmask", "Type", "Destination", "Reachable", "Metric", "Preference", "Flags", "C-Tag", "S-Tag", "Handoff", "Mode", "Age"])279 for entry in reply:280 routetbl = entry["routes"]281 for route in routetbl:282 if str(route["type"]) == "edge2edge":283 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), "N/A", "N/A", str(route["age_s"])])284 elif str(route["type"]) == "datacenter":285 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), "0", str(-1), str(-1), "N/A", "N/A", str(route["age_s"])])286 else :287 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), str(route["handoff"]), str(route["mode"]), str(route["age_s"])])288 pretty_print_table(routes)289class routeTesterDumpAction(argparse.Action):290 def __call__(self, parser, namespace, values, option_string=None):291 params = {"debug":"routes"}292 if values:293 if (len(values) == 2):294 params = {"entr": "all", "dip": values[1]}295 else:296 params = {"entr": values[0], "dip": "all"}297 else:298 params = {"entr": "all", "dip":"all"}299 reply = remote_server.routeTesterDebugDump(**params)300 if namespace.verbose:301 print json.dumps(reply, sort_keys = True, indent = 2)302 return303 routes = []304 routes.append(["EnterpriseID", "Address", "Netmask", "Type", "Destination", "Reachable", "Metric", "Preference", "Flags", "C-Tag", "S-Tag", "Handoff", "Mode", "Age"])305 for entry in reply:306 routetbl = entry["routes"]307 for route in routetbl:308 if str(route["type"]) == "edge2edge":309 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), "N/A", "N/A", str(route["age_s"])])310 elif str(route["type"]) == "datacenter":311 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), "0", str(-1), str(-1), "N/A", "N/A", str(route["age_s"])])312 else :313 routes.append([str(entry["enterprise_id"]), route["address"], route["netmask"], route["type"], route["destination"], str(route["reachable"]), str(route["metric"]), str(route["preference"]), route["flags"], str(route["c-tag"]), str(route["s-tag"]), str(route["handoff"]), str(route["mode"]), str(route["age_s"])])314 pretty_print_table(routes)315class verboseRouteDumpAction(argparse.Action):316 def __call__(self, parser, namespace, values, option_string=None):317 params = {"debug":"routes"}318 if values:319 if (len(values) == 2):320 params = {"entr": values[0], "dip": values[1]}321 else:322 params = {"entr": values[0], "dip": "all"}323 else:324 params = {"entr": "all", "dip":"all"}325 reply = remote_server.routeDebugDump(**params) 326 print json.dumps(reply, sort_keys = True, indent = 2)327class RouteSummary(argparse.Action):328 def __call__(self, parser, namespace, values, option_string=None):329 params = {"debug":"rsummary"}330 if values:331 if (len(values) == 2):332 params = {"entr": values[0], "edge": values[1]}333 else:334 params = {"entr": values[0], "edge": "all"}335 else:336 params = {"entr": "all", "edge":"all"}337 reply = remote_server.routeSummary(**params) 338 print json.dumps(reply, sort_keys = True, indent = 2)339def format_app_string(app_id, app_string):340 output = app_string + "(" + str(app_id) + ")"341 return output342class FlowDumpAction(argparse.Action):343 def __call__(self, parser, namespace, values, option_string=None):344 if values:345 params = {"debug":"flowdump", "val":1, "dip": values }346 else:347 params = {"debug":"flowdump", "val":1, "dip": "all" }348 reply = remote_server.flowDebugDump(**params)349 if namespace.verbose:350 print json.dumps(reply, sort_keys = True, indent = 2)351 return352 output = []353 output.append(["VCE", "LFID", "RFID", "FDSN", "MAX_RECV_FDSN",354 "FDSN_READ", "LAST_LATE_FDSN", "SRC IP", "DEST IP",355 "SRC PORT", "DEST PORT", "PROTO", "PRIORITY", "ROUTE-POL", "LINK-POL", "TRAFFIC-TYPE", "FLAGS", "IDLE TIME MS", "PEER RC MS", "PEER INSTANCE ID"])356 for entry in reply:357 flowtbl = entry["flow"]358 for flow in flowtbl:359 output.append([entry["vceid"], str(flow["localFlowId"]), str(flow["remoteFlowId"]),360 str(flow["fdsn"]), str(flow["max_recv_fdsn"]),361 str(flow["fdsn_read"]), str(flow["last_late_fdsn"]),362 flow["srcIP"], flow["destIP"], str(flow["srcPort"]),363 str(flow["destPort"]), str(flow["proto"]), flow["priority"],364 flow["route"], flow["link"], flow["type"], str(hex(flow["flags1"])),365 str(flow["idleTimeMs"]), str(flow["peerReconnectTimeMs"]), str(flow["peerInstanceId"])])366 if len(output) > 0:367 pretty_print_table(output)368class StaleFlowDumpAction(argparse.Action):369 def __call__(self, parser, namespace, values, option_string=None):370 if values:371 params = {"debug": "stale_flow_dump", "val":1, "dip": values}372 else:373 params = {"debug": "stale_flow_dump", "val":1, "dip": "all"}374 output = []375 output.append(["FC_ID", "SIP", "DIP", "SPORT", "DPORT", "DEAD SINCE", "REF OBJS", "RTQ PKTS"])376 reply = remote_server.dumpStaleFlows(**params)377 if namespace.verbose:378 print json.dumps(reply, sort_keys = True, indent = 2)379 return380 stale_flows = reply['stale_flows']381 for stale_flow in stale_flows:382 output.append([str(stale_flow['flow_id']), str(stale_flow['sip']), str(stale_flow['dip']),383 str(stale_flow['sport']), str(stale_flow['dport']), str(stale_flow['dead_since']),384 str(stale_flow['ref_objs']), str(stale_flow['pkts_in_rt_queue'])])385 if len(output) > 0:386 pretty_print_table(output)387class toggleFlowAgerAction(argparse.Action):388 def __call__(self, parser, namespace, values, option_string=None):389 if values:390 if len(values) < 1:391 print json.dumps({"result":"not enough arguments"})392 393 arg_val = int(values[0])394 if arg_val != 0 and arg_val != 1:395 print json.dumps({"result":"first argument needs to be 0/1"})396 return397 params = {"enabled": arg_val}398 for i in range(1,len(values)):399 if 'timer_interval_secs' in values[i]:400 arg_val = values[i].split('=')[1]401 params.update({'timer_interval_secs': int(arg_val)})402 elif 'idle_timeout_secs' in values[i]:403 arg_val = values[i].split('=')[1]404 params.update({'idle_timeout_secs': int(arg_val)})405 406 reply = remote_server.toggleFlowAger(**params)407 print json.dumps(reply)408 else:409 print json.dumps({"result":"no input given"})410class StaleTdDumpAction(argparse.Action):411 def __call__(self, parser, namespace, values, option_string=None):412 params = {"debug": "stale_td_dump"}413 reply = remote_server.dumpStaleTds(**params)414 if namespace.verbose:415 print json.dumps(reply, sort_keys = True, indent = 2)416 return417 output = []418 output.append(["TD", "PI", "PEER IP", "PEER TYPE", "VERSION", "STATE", "OBJ STATE", "PHY INTF NAME", "REFCNT", "REF OBJS"])419 stale_tds = reply['stale_tds']420 for stale_td in stale_tds:421 output.append([str(stale_td["td"]), str(stale_td["pi"]), str(stale_td["peer_ip"]), str(stale_td["peer_type"]),422 str(stale_td["version"]), str(stale_td["state"]), str(stale_td["obj_state"]),423 str(stale_td["phy_intf_name"]), str(stale_td["ref_cnt"]), str(stale_td["ref_objs"])])424 if len(output) > 0:425 pretty_print_table(output)426class StalePiDumpAction(argparse.Action):427 def __call__(self, parser, namespace, values, option_string=None):428 params = {"debug": "stale_pi_dump"}429 reply = remote_server.dumpStalePi(**params)430 if namespace.verbose:431 print json.dumps(reply, sort_keys = True, indent = 2)432 return433 output = []434 output.append(["PI", "PEER LOGICAL ID", "PEER TYPE", "OBJ STATE", "REFCNT", "REF OBJS"])435 stale_pis = reply['stale_pi']436 for stale_pi in stale_pis:437 output.append([str(stale_pi["pi"]), str(stale_pi["peer_logical_id"]), str(stale_pi["peer_type"]),438 str(stale_pi["obj_state"]), str(stale_pi["ref_cnt"]), str(stale_pi["ref_objs"])])439 if len(output) > 0:440 pretty_print_table(output)441class PacketLeakCheck(argparse.Action):442 def __call__(self, parser, namespace, values, option_string=None):443 if len(values) < 1:444 print "Insufficinet Arguments, Valid arguments are ON/OFF/DUMP"445 return446 params = {"debug": "pkt_leak_dump", "arg": values[0]}447 reply = remote_server.pktDump(**params)448 if namespace.verbose:449 print json.dumps(reply, sort_keys = True, indent = 2)450 return451 if values[0] == "dump":452 output = []453 output.append(["PKT", "PI", "Tracker", "Last-path", "Flags"])454 pkts = reply['leak_pkt']455 for pkt in pkts:456 output.append([str(pkt['pkt']), str(pkt['pi']), str(pkt['path']), str(pkt['last-path']), str(pkt['flags'])])457 if len(output) > 0:458 pretty_print_table(output)459 else:460 print json.dumps(reply, sort_keys = True, indent = 2)461 return462class PacketTracker(argparse.Action):463 def __call__(self, parser, namespace, values, option_string=None):464 if len(values) < 6:465 print "Insufficinet Arguments"466 return467 params = {"debug": "pkt_track", "sip": values[0], "sport": values[1], "dip": values[2], "dport": values[3], "proto": values[4], "count":values[5]}468 reply = remote_server.pktTrace(**params)469 print json.dumps(reply, sort_keys = True, indent = 2)470 return471class reloadConfigs(argparse.Action):472 def __call__(self, parser, namespace, values, option_string=None):473 params = {"debug": "reload_configs"}474 reply = remote_server.reloadConfigs(**params)475class JitterDumpAction(argparse.Action):476 def __call__(self, parser, namespace, values, option_string=None):477 if values:478 params = {"debug":"flowdump", "val":2, "dip": values }479 else:480 params = {"debug":"flowdump", "val":2, "dip": "all" }481 reply = remote_server.flowDebugDump(**params)482 if namespace.verbose:483 print json.dumps(reply, sort_keys = True, indent = 2)484 return485 output = []486 output.append(["GWIP", "FDSN", "FDSN_READ", "LAST_LATE_FDSN", "DEP_INTERVAL",487 "JBUF_ENQUEUE", "JBUF_DEQUEUE", "JBUF_TDEQUEUE", "SRC IP", "DEST IP",488 "SRC PORT", "DEST PORT", "PROTO"])489 for entry in reply:490 flowtbl = entry["flow"]491 for flow in flowtbl:492 output.append([entry["vceid"], str(flow["fdsn"]), str(flow["fdsn_read"]),493 str(flow["last_late_fdsn"]), str(flow["depInterval"]), str(flow["jbufEnqueueCnt"]),494 str(flow["jbufDequeueCnt"]), str(flow["jbufRealDequeueCnt"]), flow["srcIP"], flow["destIP"],495 str(flow["srcPort"]), str(flow["destPort"]), str(flow["proto"])])496 pretty_print_table(output)497 498class FlowFlushAction(argparse.Action):499 def __call__(self, parser, namespace, values, option_string=None):500 params = {"debug":"flowflush"}501 reply = remote_server.flowDebugFlush(**params)502 print json.dumps(reply, sort_keys = True, indent = 2)503class ikeDeleteAction(argparse.Action):504 def __call__(self, parser, namespace, values, option_string=None):505 params = {"cookie":values[0]}506 reply = remote_server.ikeDebugDeleteSpd(**params)507 print json.dumps(reply, sort_keys = True, indent = 2)508class verboseIkeDumpAction(argparse.Action):509 def __call__(self, parser, namespace, values, option_string=None):510 params = {"debug":"ike"}511 reply = remote_server.ikeDebugDump(**params)512 print json.dumps(reply, sort_keys = True, indent = 2)513 514class datacenterVpnStatusAction(argparse.Action):515 def __call__(self, parser, namespace, values, option_string=None):516 params = {"debug":"ike"}517 reply = remote_server.datacenterVpnStatusDump(**params)518 print json.dumps(reply, sort_keys = True, indent = 2)519 520class ikeDumpAction(argparse.Action):521 def __call__(self, parser, namespace, values, option_string=None):522 params = {"debug":"ike"}523 reply = remote_server.ikeDebugDump(**params)524 if namespace.verbose:525 print json.dumps(reply, sort_keys = True, indent = 2)526 return527 #first print the velocloud tunnels528 vpn_edge_to_edge = []529 vpn_edge_to_edge_cnt = 0530 vpn_edge_to_edge.append(["Name", "Source", "Destination", "Instance ID", "Cookie", "TD version", "State"])531 for entry in reply["descriptors"]:532 if (entry["type"] == "Velocloud"):533 vpn_edge_to_edge_cnt += 1534 state = "DOWN"535 if (entry["up"] == 1):536 state = "UP"537 vpn_edge_to_edge.append([entry["name"], entry["source"], entry["dest"], str(entry["inst_id"]), str(entry["cookie"]), entry["td_version"], state])538 if (vpn_edge_to_edge_cnt > 0):539 print "VeloCloud Edge Tunnels"540 print "============================================================================="541 pretty_print_table(vpn_edge_to_edge)542 print ""543 #now the DC VTI tunnels544 vpn_vti = []545 vpn_vti_cnt = 0546 vpn_vti.append(["Name", "Source", "Destination", "Instance ID", "Cookie", "Type", "Local VTI IP", "Peer VTI IP", "State"])547 for entry in reply["descriptors"]:548 if ((entry["type"] != "Velocloud") and (entry["type"] != "Cisco ASA") and (entry["type"] != "Generic Policy")):549 vpn_vti_cnt += 1550 vpn_vti.append([entry["name"], entry["source"], entry["dest"], str(entry["inst_id"]), str(entry["cookie"]), entry["type"],551 entry["local_vti_ip"], entry["peer_vti_ip"], entry["state"]])552 if (vpn_vti_cnt > 0):553 print "Datacenter VTI Tunnels"554 print "=============================================================================================================="555 pretty_print_table(vpn_vti)556 print ""557 #now the DC ASA tunnels558 vpn_asa = []559 vpn_asa_cnt = 0560 vpn_asa.append(["Name", "Source", "Destination", "Instance ID", "Cookie", "Type", "State"])561 for entry in reply["descriptors"]:562 if ((entry["type"] == "Cisco ASA") or (entry["type"] == "Generic Policy")):563 vpn_asa_cnt += 1564 vpn_asa.append([entry["name"], entry["source"], entry["dest"], str(entry["inst_id"]), str(entry["cookie"]), entry["type"], entry["state"]])565 if (vpn_asa_cnt > 0):566 print "Datacenter ASA/Policy Based Tunnels"567 print "==========================================================="568 pretty_print_table(vpn_asa)569class routeInitReqAction(argparse.Action):570 def __call__(self, parser, namespace, values, option_string=None):571 params = {"edge_id":values[0]}572 reply = remote_server.routeInitReq(**params)573 print json.dumps(reply, sort_keys = True, indent = 2)574class routeTestReqAction(argparse.Action):575 def __call__(self, parser, namespace, values, option_string=None):576 params = {"edge_id":values[0], "subnets":int(values[1])}577 reply = remote_server.routeTestReq(**params)578 print json.dumps(reply, sort_keys = True, indent = 2)579class ikeDownAction(argparse.Action):580 def __call__(self, parser, namespace, values, option_string=None):581 params = {"cookie":values[0]}582 reply = remote_server.ikeDebugDown(**params)583 print json.dumps(reply, sort_keys = True, indent = 2)584class ikeDeleteP1SaAction(argparse.Action):585 def __call__(self, parser, namespace, values, option_string=None):586 params = {"peerIp":values[0], "cookie":values[1]}587 reply = remote_server.ikeDebugDeleteP1Sa(**params)588 print json.dumps(reply, sort_keys = True, indent = 2)589class vpnStateUpdateAction(argparse.Action):590 def __call__(self, parser, namespace, values, option_string=None):591 params = {"cookie":values[0]}592 reply = remote_server.vpnStateUpdate(**params)593 print json.dumps(reply, sort_keys = True, indent = 2)594class ikeSetDebugLevelAction(argparse.Action):595 def __call__(self, parser, namespace, values, option_string=None):596 params = {"level":int(values[0])}597 reply = remote_server.ikeSetDebugLevel(**params)598 print json.dumps(reply, sort_keys = True, indent = 2)599class ikeStartDebugAction(argparse.Action):600 def __call__(self, parser, namespace, values, option_string=None):601 params = {"cookie":values[0]}602 reply = remote_server.ikeStartDebug(**params)603 print json.dumps(reply, sort_keys = True, indent = 2)604class ikeSetDynamicLogAction(argparse.Action):605 def __call__(self, parser, namespace, values, option_string=None):606 params = {"level":int(values[0])}607 reply = remote_server.ikeSetDynamicLog(**params)608 print json.dumps(reply, sort_keys = True, indent = 2)609class ikeChildsaDumpAction(argparse.Action):610 def __call__(self, parser, namespace, values, option_string=None):611 params = {"debug":"ike_childsa"}612 reply = remote_server.ikeChildsaDump(**params)613 if namespace.verbose:614 print json.dumps(reply, sort_keys = True, indent = 2)615 return616 #first print the Security Policy617 ike_childsa = []618 ike_childsa.append(["Index", "Cookie", "SpdId", "IkeSaId", "Flags", "Dir",619 "Spi", "Usage", "PeerPort", 620 "Auth", "Encr", "Tunnel // Traffic"])621 for entry in reply["descriptors"]:622 ike_childsa.append([entry["index"], entry["cookie"], entry["SpdId"], entry["IkeSaId"],623 entry["saFlags"], entry["dir"],624 entry["SaSpi"], entry["usage"],625 entry["SaUdpEncPort"],626 entry["auth_algs"], entry["encr_algs"], entry["tunnel_traffic"]])627 print "Child SA"628 print "================================================================================""================================================================================""=============================="629 pretty_print_table(ike_childsa)630class ikeSaDumpAction(argparse.Action):631 def __call__(self, parser, namespace, values, option_string=None):632 params = {"debug":"ike_sa"}633 reply = remote_server.ikeSaDump(**params)634 if namespace.verbose:635 print json.dumps(reply, sort_keys = True, indent = 2)636 return637 #first print the Security Policy638 ike_sa = []639 ike_sa.append(["Index", "IkeSaId", "Cookie", "IKE", "Flags", "Dir", "NAT",640 "Ike Spi/Cookie", "PeerAddr", "State", "Usage"])641 for entry in reply["descriptors"]:642 ike_sa.append([entry["index"], entry["Ikeid"], entry["cookie"],643 entry["ike_version"], entry["flags"], entry["dir"],644 entry["nat"], entry["SaSpi"], entry["peer_addr"],645 entry["state"], entry["usage"]])646 print "IKE SA"647 print "================================================================================""======================================================================"648 pretty_print_table(ike_sa)649class ikeSpdDumpAction(argparse.Action):650 def __call__(self, parser, namespace, values, option_string=None):651 params = {"debug":"ike_spd"}652 reply = remote_server.ikeSpdDump(**params)653 if namespace.verbose:654 print json.dumps(reply, sort_keys = True, indent = 2)655 return656 #first print the Security Policy657 ike_spd = []658 ike_spd.append(["Index", "SpdId", "Cookie", "Flags", "Mode",659 "SecuProto", "Auth", "Encr", "Tunnel", "Traffic"])660 for entry in reply["descriptors"]:661 ike_spd.append([entry["pxSp_index"], entry["SpdId"], entry["cookie"],662 entry["pxSp_flags"], entry["SaMode"],663 entry["SecuProto"], entry["auth_algs"], entry["encr_algs"],664 entry["tunnel"], entry["traffic"]])665 print "Security Policy"666 print "================================================================================""======================================================================"667 pretty_print_table(ike_spd)668class dynbwDbgDump(argparse.Action):669 def __call__(self, parser, namespace, values, option_string=None):670 params = {"debug":"dynbwdbg"}671 reply = remote_server.dynbwDbgDump(**params)672 if namespace.verbose:673 print json.dumps(reply, sort_keys = True, indent = 2)674 return675 dynbwdbg = []676 dynbwdbg.append(["debug", "noabort", "disable", "window",677 "min_pkts", "bwdecr_time", "bwincr_time",678 "bwincr_maxtime", "wait_bwtest", "rate_tlrnc",679 "max_diff", "force_max", "force_cnt", 680 "drop_delay", "drop_delay_cnt", "stop_decr",681 "wired_nodynbw", "min_latency", "latency_tlrnc",682 "pp_test", "slow_int", "fast_int", "slow_pkts", "fast_pkts"])683 dynbwdbg.append([str(reply["debug"]), str(reply["noabort"]),684 str(reply["disable"]), str(reply["window"]),685 str(reply["min_pkts"]), str(reply["bwdecr_time"]),686 str(reply["bwincr_time"]), str(reply["bwincr_maxtime"]),687 str(reply["wait_bwtest"]), str(reply["rate_tlrnc"]),688 str(reply["max_diff"]), str(reply["force_max"]),689 str(reply["force_cnt"]), 690 str(reply["drops_delay"]), str(reply["drops_delay_cnt"]),691 str(reply["stop_decr"]), str(reply["wired_nodynbw"]),692 str(reply["min_latency"]), str(reply["latency_tlrnc"]),693 str(reply["pp_test"]), str(reply["slow_int"]), str(reply["fast_int"]),694 str(reply["slow_pkts"]), str(reply["fast_pkts"])])695 pretty_print_table(dynbwdbg)696class hfscDbgDump(argparse.Action):697 def __call__(self, parser, namespace, values, option_string=None):698 params = {"debug":"hfscdbg", "sched": values[0], "specific": values[1], "detail": int(values[2])}699 reply = remote_server.hfscDbgDump(**params)700 if namespace.verbose:701 print json.dumps(reply, sort_keys = True, indent = 2)702 return703 hfscdbg = []704 hfscdbg.append(["name", "parent", "children", "qlen",705 "drops", "packets", "bytes"])706 if int(values[2]) == 0:707 for entry in reply["hfsc"]:708 hfscdbg.append([str(entry["name"]), str(entry["parent"]),709 str(entry["children"]), str(entry["qlen"]),710 str(entry["drops"]), str(entry["packets"]),711 str(entry["bytes"])])712 pretty_print_table(hfscdbg)713 else:714 # Hard to format the detailed response, dump json, analyze offline715 json.dump(reply, sys.stdout)716class handoffqDbgDump(argparse.Action):717 def __call__(self, parser, namespace, values, option_string=None):718 params = {"debug":"handoffqdbg"}719 reply = remote_server.handoffqDbgDump(**params)720 if namespace.verbose:721 print json.dumps(reply, sort_keys = True, indent = 2)722 return723 handoffqdbg = []724 handoffqdbg.append(["name", "qlimit", "lockfree", "sleeping",725 "wokenup", "enq", "deq", "drops", "head", "tail", "dummy", "next", "state"])726 for entry in reply["handoffq"]: handoffqdbg.append([str(entry["name"]), str(entry["qlimit"]),727 str(entry["lockfree"]), str(entry["sleeping"]),728 str(entry["wokenup"]), str(entry["enq"]),729 str(entry["deq"]), str(entry["drops"]),730 hex(entry["head"]), hex(entry["tail"]),731 hex(entry["dummy"]), hex(entry["next"]),732 str(entry["state"])])733 pretty_print_table(handoffqdbg)734class PktsQedDbgDump(argparse.Action):735 def __call__(self, parser, namespace, values, option_string=None):736 params = {"debug":"pktsqeddbg"}737 reply = remote_server.PktsQedDbgDump(**params)738 if namespace.verbose:739 print json.dumps(reply, sort_keys = True, indent = 2)740 return741 pktsqeddbg = []742 pktsqeddbg.append(["name", "packets"])743 for entry in reply["pktsqed"]:744 pktsqeddbg.append([entry["name"], str(entry["queued"])])745 pretty_print_table(pktsqeddbg)746class linkBwCapDump(argparse.Action):747 def __call__(self, parser, namespace, values, option_string=None):748 params = {"debug":"bwcap"}749 reply = remote_server.linkBwCapDump(**params)750 if namespace.verbose:751 print json.dumps(reply, sort_keys = True, indent = 2)752 return753 linkbw = []754 linkbw.append(["VCEID", "CurCap", "OrigCap", "wstart", 755 "decr", "incr", "test", "force",756 "Nforced", "pkts", "nacks",757 "rxkbps", "txkbps", "abort", "init", "netcap",758 "delta", "minlat", "avglat"])759 for entry in reply["bwcap"]:760 linkbw.append([entry["vceid"], str(entry["bwcap"]),761 str(entry["msrcap"]),762 str(entry["wstart"]), 763 str(entry["decr"]), str(entry["incr"]),764 str(entry["test"]), str(entry["force"]),765 str(entry["Nforced"]), str(entry["pkts"]),766 str(entry["nacks"]), str(entry["rxbps"]),767 str(entry["txbps"]),768 str(entry["abort"]), str(entry["init"]),769 str(entry["netcap"]), str(entry["delta"]),770 str(entry["minlat"]), str(entry["avglat"])])771 pretty_print_table(linkbw)772class loggerSetSquelchState(argparse.Action):773 def __call__(self, parser, namespace, values, option_string=None):774 log_squelch_state = -1775 log_squelch_max = -1776 for i in range (len(values)):777 if values[i].startswith("max="):778 log_squelch_max = int(values[i].split("=")[1])779 elif values[i] == "on":780 log_squelch_state = 1781 elif values[i] == "off":782 log_squelch_state = 0783 if (log_squelch_state == -1):784 print "invalid log squelching stat: ", log_level785 return 0786 params = {"state":log_squelch_state, "max":log_squelch_max}787 reply = remote_server.loggerSetSquelchState(**params)788 print json.dumps(reply, sort_keys = True, indent = 2)789class loggerOverrideDefaultsAction(argparse.Action):790 def __call__(self, parser, namespace, values, option_string=None):791 log_level = -1792 log_modules = ""793 logX = 0794 for i in range (len(values)):795 if values[i] == "logX":796 logX = 1797 elif values[i].startswith("module="):798 log_modules = values[i].split("=")[1].split(",")799 log_modules = [x.strip().upper() for x in log_modules]800 log_modules = ",".join(log_modules)801 elif values[i].isdigit():802 log_level = int(values[i])803 # if log_level >= 0 and < max its invalid.804 if not (log_level >= 0 and log_level <= 8):805 print "invalid log level : ", log_level806 return 0807 # modules should be with in our defined modules range.808 params = {"level":log_level, "module":log_modules, "logX":logX}809 reply = remote_server.loggerOverrideDefaults(**params)810 print json.dumps(reply, sort_keys = True, indent = 2)811class blockedSubnetDumpAction(argparse.Action):812 def __call__(self, parser, namespace, values, option_string=None):813 params = {"debug":"blocked_subnets"}814 reply = remote_server.blockedSubnetDump(**params)815 print json.dumps(reply, sort_keys = True, indent = 2)816class dceDumpAction(argparse.Action):817 def __call__(self, parser, namespace, values, option_string=None):818 params = {"debug":"dce"}819 reply = remote_server.dceTableDebugDump(**params)820 print json.dumps(reply, sort_keys = True, indent = 2)821class loggerCtxOnOff(argparse.Action):822 def __call__(self, parser, namespace, values, option_string=None):823 log_name = ""824 log_enable = ""825 for i in range (len(values)):826 if values[i].startswith("name="):827 log_name = values[i].split("=")[1]828 elif values[i].startswith("enable="):829 log_enable = values[i].split("=")[1]830 if not log_name or not log_enable:831 return -1832 params = {"name":log_name, "enable":log_enable}833 reply = remote_server.loggerCtxOnOff(**params)834 print json.dumps(reply, sort_keys = True, indent = 2)835 return 0836class qosNetDebug(argparse.Action):837 def __call__(self, parser, namespace, values, option_string=None):838 params = {"debug":"qos_net", "peer_id": values[0], "action": values[1]}839 reply = remote_server.qosNetDebug(**params)840 if values[1] == "stats":841 qos_stats = []842 qos_stats.append(["Endpoint/Class", "BW Cap (Kbps)", "Weight",843 "Kbps (10s win)", "PPS (10s win)", "Queued pkts", "Queued bytes", "Dropped pkts", "Dropped bytes"])844 for entry1 in reply:845 for entry2 in entry1:846 qos_stats.append([str(entry2["Peer"]), str(entry2["bw_cap"]),847 str(format(entry2["weight"], '.2f')), str(entry2["bytes_rate"]),848 str(entry2["pkts_rate"]), str(entry2["pkts_queued"]),849 str(entry2["bytes_queued"]), str(entry2["pkts_dropped"]),850 str(entry2["bytes_dropped"])])851 pretty_print_table(qos_stats)852 elif values[1] == "clear_drops":853 print json.dumps(reply, sort_keys = True, indent = 2)854 return 0855class qosLinkDebug(argparse.Action):856 def __call__(self, parser, namespace, values, option_string=None):857 params = {"debug":"qos_link", "peer_id":values[0], "action": values[1]}858 reply = remote_server.qosLinkDebug(**params)859 if values[1] == "stats":860 link_stats = []861 link_stats.append(["Interface", "Logical-Id", "BW (Kbps)",862 "Kbps (10s win)", "PPS (10s win)", "Queued pkts", "Queued bytes", "Dropped pkts", "Dropped bytes"])863 for entry in reply:864 link_stats.append([entry["ifname"], entry["logical_id"], 865 str(entry["bw_cap"]), str(entry["bytes_rate"]),866 str(entry["pkts_rate"]), str(entry["pkts_queued"]),867 str(entry["bytes_queued"]), str(entry["pkts_dropped"]),868 str(entry["bytes_dropped"])])869 pretty_print_table(link_stats)870 elif values[1] == "clear_drops":871 print json.dumps(reply, sort_keys = True, indent = 2)872class PlHierDebug(argparse.Action):873 def __call__(self, parser, namespace, values, option_string=None):874 params = {"debug":"pl_hier_dbg", "type":values[0], "action":values[1]}875 reply = remote_server.PlHierDebug(**params)876 print json.dumps(reply, sort_keys = True, indent = 2)877 return 0878class enableLatProbe(argparse.Action):879 def __call__(self, parser, namespace, values, option_string=None):880 params = {"debug" : "enable_lat_probe", "logical_id" : values[0], "probe_dest" : values[1], "probe_intvl" :881 values[2], "dump_probe_count" : values[3]}882 reply = remote_server.enableLatProbe(**params)883 print json.dumps(reply, sort_keys = True, indent = 2)884 return 0885 #params = {"debug":"enable_lat_probe", "logical_id" : values[0]886class disableLatProbe(argparse.Action):887 def __call__(self, parser, namespace, values, option_string=None):888 params = {"debug" : "disable_lat_probe", "logical_id" : values[0]}889 reply = remote_server.disableLatProbe(**params)890 print json.dumps(reply, sort_keys = True, indent = 2)891 return 0892class natDumpDepthAction(argparse.Action):893 def __call__(self, parser, namespace, values, option_string=None):894 params = {"debug":"nat_dump_depth"}895 reply = remote_server.natDumpDepth(**params)896 output = []897 output.append(["BUCKET", "DEPTH"])898 for entry in reply:899 output.append([ str(entry["bucket"]), str(entry["depth"]) ])900 pretty_print_table(output)901class natDumpAction(argparse.Action):902 def __call__(self, parser, namespace, values, option_string=None):903 params = {"debug":"nat_dump", "dip": values[0], "dir": values[1]}904 reply = remote_server.natDump(**params)905 if namespace.verbose:906 print json.dumps(reply, sort_keys = True, indent = 2)907 return908 output = []909 output.append(["TYPE", "OSIP", "ODIP", "OSPORT", "ODPORT", "OPROTO", 910 "MSIP", "MDIP", "MSPORT", "MDPORT", "MPROTO", "2TABLES",911 "ENTERPRISE_ID", "VCEID" ])912 for entry in reply:913 orig = entry["Original"]914 mod = entry["Modified"]915 output.append([ entry["Type"], orig["sip"], orig["dip"], str(orig["sport"]),916 str(orig["dport"]), str(mod["protocol"]), mod["sip"], mod["dip"],917 str(mod["sport"]), str(mod["dport"]), str(mod["protocol"]),918 str(entry["2tables"]), str(entry["enterprise_logical_id"]), str(entry["vce_logical_id"]) ])919 pretty_print_table(output)920class remoteNatAddEntryAction(argparse.Action):921 def __call__(self, parser, namespace, values, option_string=None):922 params = {"debug":"remote_nat_add", "nat_entries":int(values[0]), "pat_entries":int(values[1])}923 reply = remote_server.remoteNatAdd(**params)924 print json.dumps(reply, sort_keys = True, indent = 2)925class remoteNatFloodEntryAction(argparse.Action):926 def __call__(self, parser, namespace, values, option_string=None):927 params = {"debug":"remote_nat_flood", "nat_entries":int(values[0]), "sleep":int(values[1]), "nthreads":int(values[2]), "stop":int(values[3])}928 reply = remote_server.remoteNatFlood(**params)929 print json.dumps(reply, sort_keys = True, indent = 2)930class flowStats(argparse.Action):931 def __call__(self, parser, namespace, values, option_string=None):932 params = {"debug":"flow_stats"}933 params = {"debug" : "flow_stats", "logical_id" : values[0]}934 reply = remote_server.flowStats(**params)935 if namespace.verbose:936 print json.dumps(reply, sort_keys = True, indent = 2)937 return938 flow_stats = []939 if (len(reply) > 1):940 flow_stats.append(["Path", "Total Flows", "TCP Flows", "UDP Flows", "ICMP Flows", "Other Flows"])941 for entry in reply:942 flow_stats.append([entry["Path"], str(entry["Total Flows"]), 943 str(entry["Active TCP Flows"] - entry["Dead TCP Flows"]), 944 str(entry["Active UDP Flows"] - entry["Dead UDP Flows"]), 945 str(entry["Active ICMP Flows"] - entry["Dead ICMP Flows"]), 946 str(entry["Active other Flows"] - entry["Dead other Flows"])])947 pretty_print_table(flow_stats)948 else:949 print json.dumps(reply, sort_keys = True, indent = 2)950class uptime(argparse.Action):951 def __call__(self, parser, namespace, values, option_string=None):952 params = {"debug":"uptime"}953 reply = remote_server.uptime(**params)954 if namespace.verbose:955 print json.dumps(reply, sort_keys = True, indent = 2)956 return957 elapsed_ms = reply["uptime"]958 m,s = divmod((elapsed_ms/1000),60)959 h,m = divmod(m,60)960 d,h = divmod(h,24)961 print "Uptime: %02d:%02d:%02d, %d days" % (h,m,s,d)962 print "Start: %s, Current: %s" % (str(reply["start"]), str(reply["current"]))963class bgpDumpAction(argparse.Action):964 def __call__(self, parser, namespace, values, option_string=None):965 bgpRunning = subprocess.check_output("vtysh " + "-d bgpd " + "-c \"show running\"", shell=True)966 if len(bgpRunning) > 0:967 print "show running-config"968 print "====================="969 print bgpRunning970 netnsDump = subprocess.check_output("ip " + "netns " + "list", shell=True)971 if (len(netnsDump) > 1):972 netnsList = string.split(netnsDump, '\n')973 for entry in netnsList:974 if (len(entry) > 1):975 bgpViewDump = subprocess.check_output("vtysh " + "-d bgpd " + "-c \"show ip bgp view " + entry + " \"", shell=True)976 if len(bgpViewDump) > 0:977 print "BGP View for entr ID: " + entry978 print "========================================"979 print bgpViewDump980 981 bgpOutput = subprocess.check_output("vtysh " + "-d bgpd " + "-c \"show ip bgp view " + entry + " summary\"", shell=True)982 if len(bgpOutput) > 0:983 print "BGP View summary for entr ID: " + entry984 print "========================================"985 print bgpOutput986 bgpOutput = subprocess.check_output("vtysh " + "-d bgpd " + "-c \"show ip bgp view " + entry + " scan\"", shell=True)987 if len(bgpOutput) > 0:988 print "BGP View scan for entr ID: " + entry989 print "========================================"990 print bgpOutput991class netnsDumpAction(argparse.Action):992 def __call__(self, parser, namespace, values, option_string=None):993 netnsDump = subprocess.check_output("ip " + "netns " + "list", shell=True)994 if (len(netnsDump) > 1):995 print "Netns dump"996 print "====================="997 print netnsDump998 netnsList = string.split(netnsDump, '\n')999 for entry in netnsList:1000 if (len(entry) > 1):1001 netnsOutput = subprocess.check_output("ip " + "netns " + "exec " + entry + " ifconfig -a", shell=True)1002 if len(netnsOutput) > 0:1003 print "Netns ifconfig for entr ID: " + entry1004 print "========================================"1005 print netnsOutput1006 1007 netnsOutput = subprocess.check_output("ip " + "netns " + "exec " + entry + " netstat -an", shell=True)1008 if len(netnsOutput) > 0:1009 print "Netns netstat for entr ID: " + entry1010 print "========================================"1011 print netnsOutput1012 1013class vcgMode(argparse.Action):1014 def __call__(self, parser, namespace, values, option_string=None):1015 params = {"debug":"vcg_mode"}1016 reply = remote_server.vcgMode(**params) 1017 print json.dumps(reply, sort_keys = True, indent = 2)1018class vrfDump(argparse.Action):1019 def __call__(self, parser, namespace, values, option_string=None):1020 params = {"debug":"vrf_dump"}1021 reply = remote_server.vrfDump(**params) 1022 print json.dumps(reply, sort_keys = True, indent = 2)1023class verboseArpDumpAction(argparse.Action):1024 def __call__(self, parser, namespace, values, option_string=None):1025 params = {"debug":"arp"}1026 reply = remote_server.arpTableDebugDump(**params)1027 print json.dumps(reply, sort_keys = True, indent = 2)1028class pkiDumpAction(argparse.Action):1029 def __call__(self, parser, namespace, values, option_string=None):1030 params = {"debug":"pki"}1031 reply = remote_server.pkiDebugDump(**params)1032 if reply is not None:1033 reply["pkiSettings"] = pki.get_pki_settings()1034 else:1035 reply = {}1036 reply["pkiSettings"] = pki.get_pki_settings()1037 print json.dumps(reply, sort_keys = True, indent = 2)1038class dumpPathPortsAction(argparse.Action):1039 def __call__(self, parser, namespace, values, option_string=None):1040 params = {"debug":"ports"}1041 reply = remote_server.dumpPathPorts(**params)1042 print json.dumps(reply, sort_keys = True, indent = 2)1043class icmpMonitorDumpAction(argparse.Action):1044 def __call__(self, parser, namespace, values, option_string=None):1045 params = {"debug":"icmp"}1046 reply = remote_server.icmpMonitorDump(**params)1047 print json.dumps(reply, sort_keys = True, indent = 2)1048class probeFlapEvent(argparse.Action):1049 def __call__(self, parser, namespace, values, option_string=None):1050 params = {"debug" : "probe_flap_event", "flap_threshold" : values[0], "event_window_in_minutes" : values[1]}1051 reply = remote_server.probeFlapEventParams(**params)1052 print json.dumps(reply, sort_keys = True, indent = 2)1053 return 01054class resetProbesCounters(argparse.Action):1055 def __call__(self, parser, namespace, values, option_string=None):1056 params = {"debug":"icmpResetCounters"}1057 reply = remote_server.icmpResetCounters(**params)1058 print json.dumps(reply, sort_keys = True, indent = 2)1059class mallocTrim(argparse.Action):1060 def __call__(self, parser, namespace, values, option_string=None):1061 params = {"debug":"run_malloc_trim"}1062 reply = remote_server.mallocTrim(**params)1063class mallocStats(argparse.Action):1064 def __call__(self, parser, namespace, values, option_string=None):1065 params = {"debug":"run_malloc_stats"}1066 reply = remote_server.mallocStats(**params)1067class memoryDebugDump(argparse.Action):1068 def __call__(self, parser, namespace, values, option_string=None):1069 params = {"debug":"memory_dump"}1070 reply = remote_server.memoryDebugDump(**params)1071 print reply1072class bgpNeighborSummaryAction(argparse.Action):1073 def __call__(self, parser, namespace, values, option_string=None):1074 params = {"debug":"bgpNeighborSummary"}1075 reply = remote_server.bgpNeighborSummaryDump(**params)1076 bgp_view_summary = []1077 bgp_view_summary.append(["enterpriseLogicalId", "neighborIp", "neighborAS", "msgRcvd", "msgSent", "upDownTime", "state", "pfxRcvd"])1078 for entry in reply["bgpNeighborSummary"]:1079 bgp_view_summary.append([entry["enterpriseLogicalId"], entry["neighborIp"], entry["neighborAS"], entry["msgRcvd"], entry["msgSent"], entry["upDownTime"], entry["state"], entry["pfxRcvd"]])1080 pretty_print_table(bgp_view_summary)1081 print ""1082 print "dispEntries", reply["dispEntries"], "startEntryIdx", reply["startEntryIdx"], "totalEntries", reply["totalEntries"]1083class bgpViewDump(argparse.Action):1084 def __call__(self, parser, namespace, values, option_string=None):1085 params = {"debug":"bgp_view"}1086 reply = remote_server.bgpViewDump(**params)1087 if namespace.verbose:1088 print json.dumps(reply, sort_keys = True, indent = 2)1089 return1090 bgp_view = []1091 bgp_view.append(["Enterprise", "Address", "Netmask", "Gateway", "Nbr IP", "Nbr ID", "Metric", 1092 "Type", "Intf", "Sync'd", "Advertise", "Inbound", "Age", "Communities"])1093 for entry in reply["bgp_view"]:1094 bgp_view.append([entry["enterprise"], entry["addr"], entry["netmask"], entry["gateway"], 1095 entry["neighbor_ip"], entry["neighbor_id"], str(entry["metric"]), 1096 str(entry["metric_type"]), entry["intf"], entry["sync'd"], entry["advertise"], 1097 entry["inbound"], str(entry["age_s"]), 1098 str(entry["communities"])])1099 pretty_print_table(bgp_view)1100class bgpRedisDump(argparse.Action):1101 def __call__(self, parser, namespace, values, option_string=None):1102 params = {"debug":"bgp_redis_dump"}1103 reply = remote_server.bgpRedisDump(**params)1104 if namespace.verbose:1105 print json.dumps(reply, sort_keys = True, indent = 2)1106 return1107 bgp_redis_dump = []1108 bgp_redis_dump.append(["Enterprise", "Address", "Netmask", "Gateway", "Nbr IP", "Nbr ID", 1109 "Metric", "Type", "Intf", "route_id", "Communities"])1110 for entry in reply["bgp_redis_dump"]:1111 bgp_redis_dump.append([entry["enterprise"], entry["addr"], entry["netmask"], entry["gateway"],1112 entry["neighbor_ip"], entry["neighbor_id"], str(entry["metric"]), 1113 str(entry["metric_type"]), entry["intf"], entry["route_id"], 1114 str(entry["communities"])])1115 pretty_print_table(bgp_redis_dump)1116 print "O - Intra Area, IA - Inter Area, OE1 - External 1, OE2 - External 2"1117class oneToOneNatDumpAction(argparse.Action):1118 def __call__(self, parser, namespace, values, option_string=None):1119 params = {"debug":"one_to_one_nat"}1120 reply = remote_server.oneToOneNatDump(**params)1121 print json.dumps(reply, sort_keys = True, indent = 2)1122class dpdkPortEnable(argparse.Action):1123 def __call__(self, parser, namespace, values, option_string=None):1124 params = {"debug":"dpdk_port_enable", "intf": values[0]}1125 reply = remote_server.dpdkPortEnable(**params)1126 print json.dumps(reply, sort_keys = True, indent = 2)1127class dpdkPortDisable(argparse.Action):1128 def __call__(self, parser, namespace, values, option_string=None):1129 params = {"debug":"dpdk_port_disable", "intf": values[0]}1130 reply = remote_server.dpdkPortDisable(**params)1131 print json.dumps(reply, sort_keys = True, indent = 2)1132class dpdkBondDump(argparse.Action):1133 def __call__(self, parser, namespace, values, option_string=None):1134 params = {"debug":"dpdk_bond_dump", "intf": values[0]}1135 reply = remote_server.dpdkBondDump(**params)1136 ports = []1137 ports.append(["PCI", "Port", "Link"])1138 for p in reply:1139 ports.append([p['name'], str(p['port']), str(p['link'])])1140 pretty_print_table(ports)1141class dpdkPortsDump(argparse.Action):1142 def __call__(self, parser, namespace, values, option_string=None):1143 params = {"debug":"dpdk_ports_dump"}1144 reply = remote_server.dpdkPortsDump(**params)1145 ports = []1146 ports.append(["Name", "Port", "ArrayIndex", "Link", "VlanStrip"])1147 for p in reply:1148 ports.append([p['name'], str(p['port']), str(p['index']), str(p['link']), str(p['strip'])])1149 pretty_print_table(ports)1150class edgeClusterInfoDump(argparse.Action):1151 def __call__(self, parser, namespace, values, option_string=None):1152 params = {"debug":"edge_cluster_info_dump"}1153 reply = remote_server.edgeClusterInfoDump(**params)1154 print json.dumps(reply, sort_keys = True, indent = 2)1155class enableEdgeClusterOverride(argparse.Action):1156 def __call__(self, parser, namespace, values, option_string=None):1157 params = {"logical_id" : values[0], "cpu_pct" : int(values[1]), "mem_pct" : int(values[2]), "tunnel_pct" : int(values[3])}1158 reply = remote_server.enableEdgeClusterOverride(**params)1159 print json.dumps(reply, sort_keys = True, indent = 2)1160 1161class disableEdgeClusterOverride(argparse.Action):1162 def __call__(self, parser, namespace, values, option_string=None):1163 params = {"logical_id" : values[0]}...
gridworld.py
Source:gridworld.py
...58 for j in range(self.ncols):59 raw_print_row.append("%s"%self.gridmap[i][j])60 raw_print_table.append(raw_print_row)61 display(Markdown("**Raw World Layout**"))62 self.pretty_print_table(raw_print_table)63 64 def enumerate_states(self):65 return [i for i in range(len(self.all_states))]66 67 def enumerate_valid_states(self):68 return list(self.valid_states.keys())69 70 def coord_print(self):71 index_printer_table = []72 for i in range(self.nrows):73 index_printer_row = []74 for j in range(self.ncols):75 index_printer_row.append("(%s,%s)"%(i,j))76 index_printer_table.append(index_printer_row)77 display(Markdown("**Indexes of each grid location as a tuple**"))78 self.pretty_print_table(index_printer_table)79 def index_print(self):80 coord_printer_table = np.zeros((self.nrows, self.ncols))81 for i in range(self.nrows):82 for j in range(self.ncols):83 coord_printer_table[i][j] = self.coord_to_index((i,j))84 display(Markdown("**Indexes of each grid location as an id number**"))85 self.pretty_print_table(coord_printer_table)86 def up(self, state):87 i,j = self.index_to_coord(state)88 # if you are goal state or a wall do nothing89 if self.gridmap[i][j]=='x' or self.gridmap[i][j]=='g':90 return state 91 elif (i==0): # if walking of top, return to start state92 return self.start_state_idx93 elif self.gridmap[i-1][j]=='x': # OR if you'll hit a wall do nothing94 return self.coord_to_index((i,j))95 else:96 return self.coord_to_index((i-1,j))97 def down(self, state):98 i,j = self.index_to_coord(state)99 if self.gridmap[i][j]=='x' or self.gridmap[i][j]=='g': #if you are a wall or goal state(do nothing)100 return state101 elif (i==self.nrows-1): # if in bottom row return to start state102 return self.start_state_idx103 elif self.gridmap[i+1][j]=='x': # OR if you'll hit a wall104 return state105 else:106 return self.coord_to_index((i+1,j))107 108 def left(self, state):109 i,j = self.index_to_coord(state)110 if self.gridmap[i][j]=='x' or self.gridmap[i][j]=='g': #if you are a wall or goal state(do nothing)111 return state112 elif (j==0): # if in left-most column return to start state113 return self.start_state_idx114 elif self.gridmap[i][j-1]=='x': #if you'll hit a wall115 return state116 else:117 return self.coord_to_index((i,j-1))118 def right(self, state):119 i,j = self.index_to_coord(state)120 if self.gridmap[i][j]=='x' or self.gridmap[i][j]=='g': #if you are a wall or goal state(do nothing)121 return state122 elif (j==self.ncols-1): # if in right-most column return to start state123 return self.start_state_idx124 elif self.gridmap[i][j+1]=='x': #if you'll hit a wall125 return state126 else:127 return self.coord_to_index((i,j+1))128 def build_transitions(self):129 for i in self.enumerate_valid_states():130 x,y = self.index_to_coord(i)131 if self.gridmap[x][y] != 'x' and self.gridmap[x][y] != 'g': # no transitions for goal or barriers132 self.transitions[i] = {"up": self.up(i), "right": self.right(i), "down": self.down(i), "left": self.left(i)}133 else:134 self.transitions[i] = {}135 136 def pretty_print_table(self, table):137 display(HTML(tabulate(table, tablefmt="html")))138 139 def pretty_print_policy_table(self, policy_table):140 pretty_policy = deepcopy(self.gridmap)141 for i in range(len(self.gridmap)):142 for j in range(len(self.gridmap[i])):143 if self.gridmap[i][j]=='x':144 pretty_policy[i][j]='â'145 else:146 if policy_table[i][j] == {"up": 1.0, "right": 0.0, "down": 0.0, "left": 0.0}:147 pretty_policy[i][j]='â'148 elif policy_table[i][j] == {"up": 0.0, "right": 1.0, "down": 0.0, "left": 0.0}:149 pretty_policy[i][j]='â'150 elif policy_table[i][j] == {"up": 0.0, "right": 0.0, "down": 1.0, "left": 0.0}:151 pretty_policy[i][j]='â'152 elif policy_table[i][j] == {"up": 0.0, "right": 0.0, "down": 0.0, "left": 1.0}:153 pretty_policy[i][j]='â'154 self.pretty_print_table(pretty_policy)155def random_policy():156 policy = {"up": 0.0, "right": 0.0, "down": 0.0, "left": 0.0}157 idx = random.choice(["up","right","down","left"])158 policy[idx]=1.0159 return policy160def zero_q_values():161 qvals = {"up": 0.0, "right": 0.0, "down": 0.0, "left": 0.0}...
table-pretty-print.py
Source:table-pretty-print.py
...67 """68 for row in bordered_rows:69 joinable_row = [''] + row + ['']70 print('|'.join(joinable_row))71def pretty_print_table(rows):72 """Pretty an entire table with left justified columns.73 >>> pretty_print_table([['a', 'aa'], ['bbb', 'b']])74 |---|--|75 |a |aa|76 |bbb|b |77 |---|--|78 """79 cols = transpose(rows)80 padded_cols = pad_cols(cols)81 bordered_padded_cols = border_cols(padded_cols)82 bordered_padded_rows = transpose(bordered_padded_cols)83 print_rows(bordered_padded_rows)84def main():85 """Read in a table file and pretty print it."""86 rows = read_file_into_rows('test-table.txt')87 pretty_print_table(rows)88if __name__ == '__main__':...
midi_lut.py
Source:midi_lut.py
...17def ca65_low_byte_literal(value):18 return "$%02x" % (value & 0xFF)19def ca65_high_byte_literal(value):20 return "$%02x" % ((value & 0xFF00) >> 8)21def pretty_print_table(table_name, ca65_byte_literals):22 """ Formats a list of byte strings, 8 per line23 Just for style purposes, I'd like to collapse the table so that 24 only 8 bytes are printed on each line. This is nicer than one 25 giant line or 128 individual .byte statements.26 """27 print("%s:" % table_name)28 for table_row in range(0, int(len(ca65_byte_literals) / 8)):29 row_text = ", ".join(ca65_byte_literals[table_row * 8 : table_row * 8 + 8])30 print(" .byte %s" % row_text)31# Put it all together and write it to stdout32def generate_lookup_table(base_frequency_hz, ca65_byte_converter):33 return [ca65_byte_converter(pulse_period(base_frequency_hz, midi_frequency(midi_index + 24 - 1))) for midi_index in range(0, 128)]34pretty_print_table("ntsc_period_low", generate_lookup_table(NTSC_CPU_FREQUENCY_HZ, ca65_low_byte_literal))35pretty_print_table("ntsc_period_high", generate_lookup_table(NTSC_CPU_FREQUENCY_HZ, ca65_high_byte_literal))36pretty_print_table("pal_period_low", generate_lookup_table(PAL_CPU_FREQUENCY_HZ, ca65_low_byte_literal))...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!