docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Outputs a Go code that jumps to the appropriate except handler. Args: exc: Go variable holding the current exception. tb: Go variable holding the current exception's traceback. handlers: A list of ast.ExceptHandler nodes. Returns: A list of Go labels indexes corresponding to the exception handlers. Raises: ParseError: Except handlers are in an invalid order.
def _write_except_dispatcher(self, exc, tb, handlers): handler_labels = [] for i, except_node in enumerate(handlers): handler_labels.append(self.block.genlabel()) if except_node.type: with self.visit_expr(except_node.type) as type_,\ self.block.alloc_temp('bool') as is_inst: self.writer.write_checked_call2( is_inst, 'πg.IsInstance(πF, {}.ToObject(), {})', exc, type_.expr) self.writer.write_tmpl(textwrap.dedent(), is_inst=is_inst.expr, label=handler_labels[-1]) else: # This is a bare except. It should be the last handler. if i != len(handlers) - 1: msg = "default 'except:' must be last" raise util.ParseError(except_node, msg) self.writer.write('goto Label{}'.format(handler_labels[-1])) if handlers[-1].type: # There's no bare except, so the fallback is to re-raise. self.writer.write( 'πE = πF.Raise({}.ToObject(), nil, {}.ToObject())'.format(exc, tb)) self.writer.write('continue') return handler_labels
128,127
Outputs the boilerplate necessary for code blocks like functions. Args: block_: The Block object representing the code block. body: String containing Go code making up the body of the code block.
def write_block(self, block_, body): self.write('for ; πF.State() >= 0; πF.PopCheckpoint() {') with self.indent_block(): self.write('switch πF.State() {') self.write('case 0:') for checkpoint in block_.checkpoints: self.write_tmpl('case $state: goto Label$state', state=checkpoint) self.write('default: panic("unexpected function state")') self.write('}') # Assume that body is aligned with goto labels. with self.indent_block(-1): self.write(body) self.write('}')
128,394
Wait until `what` return True Args: what (Callable[bool]): Call `wait()` again and again until it returns True times (int): Maximum times of trials before giving up Returns: True if success, False if times threshold reached
def wait_until(what, times=-1): while times: logger.info('Waiting times left %d', times) try: if what() is True: return True except: logger.exception('Wait failed') else: logger.warning('Trial[%d] failed', times) times -= 1 time.sleep(1) return False
128,799
Discover all test cases and skip those passed Args: pattern (str): Pattern to match case modules, refer python's unittest documentation for more details skip (str): types cases to skip
def discover(names=None, pattern=['*.py'], skip='efp', dry_run=False, blacklist=None, name_greps=None, manual_reset=False, delete_history=False, max_devices=0, continue_from=None, result_file='./result.json', auto_reboot=False, keep_explorer=False, add_all_devices=False): if not os.path.exists(settings.OUTPUT_PATH): os.mkdir(settings.OUTPUT_PATH) if delete_history: os.system('del history.json') if blacklist: try: excludes = [line.strip('\n') for line in open(blacklist, 'r').readlines() if not line.startswith('#')] except: logger.exception('Failed to open test case black list file') raise else: excludes = [] log = None if os.path.isfile(result_file): try: log = json.load(open(result_file, 'r')) except: logger.exception('Failed to open result file') if not log: log = {} json.dump(log, open(result_file, 'w'), indent=2) suite = unittest.TestSuite() discovered = unittest.defaultTestLoader.discover('cases', pattern) if names and continue_from: names = names[names.index(continue_from):] for s1 in discovered: for s2 in s1: for case in s2: if case.__class__ is HarnessCase: continue case_name = unicode(case.__class__.__name__) # grep name if name_greps and not any(fnmatch.fnmatch(case_name, name_grep) for name_grep in name_greps): logger.info('case[%s] skipped by name greps', case_name) continue # whitelist if len(names) and case_name not in names: logger.info('case[%s] skipped', case_name) continue # skip cases if case_name in log.keys(): if (log[case_name]['passed'] and ('p' in skip)) \ or (log[case_name]['passed'] is False and ('f' in skip)) \ or (log[case_name]['passed'] is None and ('e' in skip)): logger.warning('case[%s] skipped for its status[%s]', case_name, log[case_name]['passed']) continue # continue from if continue_from: if continue_from != case_name: logger.warning('case[%s] skipped for continue from[%s]', case_name, continue_from) continue else: continue_from = None # black list if case_name in excludes: logger.warning('case[%s] skipped for blacklist', case_name) continue # max devices if max_devices and case.golden_devices_required > max_devices: logger.warning('case[%s] skipped for exceeding max golden devices allowed[%d]', case_name, max_devices) continue suite.addTest(case) logger.info('case[%s] added', case_name) if auto_reboot: argv = [] argv.append('"%s"' % os.sep.join([os.getcwd(), 'start.bat'])) argv.extend(['-p', pattern]) argv.extend(['-k', skip]) argv.extend(['-o', result_file]) argv.append('-a') if manual_reset: argv.append('-m') if delete_history: argv.append('-d') auto_reboot_args = argv + names else: auto_reboot_args = None os.system('del "%s"' % RESUME_SCRIPT_PATH) # manual reset if manual_reset: settings.PDU_CONTROLLER_TYPE = 'MANUAL_PDU_CONTROLLER' settings.PDU_CONTROLLER_OPEN_PARAMS = {} settings.PDU_CONTROLLER_REBOOT_PARAMS = {} result = SimpleTestResult(result_file, auto_reboot_args, keep_explorer, add_all_devices) for case in suite: logger.info(case.__class__.__name__) if dry_run: return suite.run(result) return result
128,817
Record test results in json file Args: path (str): File path to record the results auto_reboot (bool): Whether reboot when harness die
def __init__(self, path, auto_reboot_args=None, keep_explorer=False, add_all_devices=False): super(SimpleTestResult, self).__init__() self.path = path self.auto_reboot_args = auto_reboot_args self.result = json.load(open(self.path, 'r')) self.log_handler = None self.started = None self.keep_explorer = keep_explorer self.add_all_devices = add_all_devices SimpleTestResult.executions += 1 logger.info('Initial state is %s', json.dumps(self.result, indent=2))
128,819
Record test result into json file Args: test (TestCase): The test just run passed (bool): Whether the case is passed
def add_result(self, test, passed, error=None): self.result[unicode(test.__class__.__name__)] = { 'started': self.started, 'stopped': time.strftime('%Y-%m-%dT%H:%M:%S'), 'passed': passed, 'error': error, 'executions': SimpleTestResult.executions } if self.auto_reboot_args: os.system('del "%s"' % RESUME_SCRIPT_PATH) json.dump(OrderedDict(sorted(self.result.items(), key=lambda t: t[0])), open(self.path, 'w'), indent=2) # save logs logger.removeHandler(self.log_handler) self.log_handler.close() self.log_handler = None time.sleep(2) # close explorers if not self.keep_explorer: os.system('taskkill /f /im explorer.exe && start explorer.exe')
128,821
initialize the serial port and default network parameters Args: **kwargs: Arbitrary keyword arguments Includes 'EUI' and 'SerialPort'
def __init__(self, **kwargs): try: self.UIStatusMsg = '' self.mac = kwargs.get('EUI') self.port = kwargs.get('SerialPort') self.handle = None self.AutoDUTEnable = False self._is_net = False # whether device is through ser2net self.logStatus = {'stop':'stop', 'running':'running', "pauseReq":'pauseReq', 'paused':'paused'} self.joinStatus = {'notstart':'notstart', 'ongoing':'ongoing', 'succeed':'succeed', "failed":'failed'} self.logThreadStatus = self.logStatus['stop'] self.intialize() except Exception, e: ModuleHelper.WriteIntoDebugLogger("initialize() Error: " + str(e))
128,830
Find the `expected` line within `times` trials. Args: expected str: the expected string times int: number of trials
def _expect(self, expected, times=50): print '[%s] Expecting [%s]' % (self.port, expected) retry_times = 10 while times > 0 and retry_times > 0: line = self._readline() print '[%s] Got line [%s]' % (self.port, line) if line == expected: print '[%s] Expected [%s]' % (self.port, expected) return if not line: retry_times -= 1 time.sleep(0.1) times -= 1 raise Exception('failed to find expected string[%s]' % expected)
128,831
Send exactly one line to the device Args: line str: data send to device
def _sendline(self, line): logging.info('%s: sending line', self.port) # clear buffer self._lines = [] try: self._read() except socket.error: logging.debug('%s: Nothing cleared', self.port) print 'sending [%s]' % line self._write(line + '\r\n') # wait for write to complete time.sleep(0.1)
128,835
send specific command to reference unit over serial port Args: cmd: OpenThread CLI string Returns: Done: successfully send the command to reference unit and parse it Value: successfully retrieve the desired value from reference unit Error: some errors occur, indicates by the followed specific error number
def __sendCommand(self, cmd): logging.info('%s: sendCommand[%s]', self.port, cmd) if self.logThreadStatus == self.logStatus['running']: self.logThreadStatus = self.logStatus['pauseReq'] while self.logThreadStatus != self.logStatus['paused'] and self.logThreadStatus != self.logStatus['stop']: pass try: # command retransmit times retry_times = 3 while retry_times > 0: retry_times -= 1 try: self._sendline(cmd) self._expect(cmd) except Exception as e: logging.exception('%s: failed to send command[%s]: %s', self.port, cmd, str(e)) if retry_times == 0: raise else: break line = None response = [] retry_times = 10 while retry_times > 0: line = self._readline() logging.info('%s: the read line is[%s]', self.port, line) if line: response.append(line) if line == 'Done': break else: retry_times -= 1 time.sleep(0.2) if line != 'Done': raise Exception('%s: failed to find end of response' % self.port) logging.info('%s: send command[%s] done!', self.port, cmd) return response except Exception, e: ModuleHelper.WriteIntoDebugLogger("sendCommand() Error: " + str(e)) raise
128,836
get specific type of IPv6 address configured on thread device Args: addressType: the specific type of IPv6 address link local: link local unicast IPv6 address that's within one-hop scope global: global unicast IPv6 address rloc: mesh local unicast IPv6 address for routing in thread network mesh EID: mesh Endpoint Identifier Returns: IPv6 address string
def __getIp6Address(self, addressType): addrType = ['link local', 'global', 'rloc', 'mesh EID'] addrs = [] globalAddr = [] linkLocal64Addr = '' rlocAddr = '' meshEIDAddr = '' addrs = self.__sendCommand('ipaddr') for ip6Addr in addrs: if ip6Addr == 'Done': break ip6AddrPrefix = ip6Addr.split(':')[0] if ip6AddrPrefix == 'fe80': # link local address if ip6Addr.split(':')[4] != '0': linkLocal64Addr = ip6Addr elif ip6Addr.startswith(self.meshLocalPrefix): # mesh local address if ip6Addr.split(':')[4] == '0': # rloc rlocAddr = ip6Addr else: # mesh EID meshEIDAddr = ip6Addr else: # global ipv6 address if ip6Addr != None: globalAddr.append(ip6Addr) else: pass if addressType == addrType[0]: return linkLocal64Addr elif addressType == addrType[1]: return globalAddr elif addressType == addrType[2]: return rlocAddr elif addressType == addrType[3]: return meshEIDAddr else: pass
128,837
set router upgrade threshold Args: iThreshold: the number of active routers on the Thread network partition below which a REED may decide to become a Router. Returns: True: successful to set the ROUTER_UPGRADE_THRESHOLD False: fail to set ROUTER_UPGRADE_THRESHOLD
def __setRouterUpgradeThreshold(self, iThreshold): print 'call __setRouterUpgradeThreshold' try: cmd = 'routerupgradethreshold %s' % str(iThreshold) print cmd return self.__sendCommand(cmd) == 'Done' except Exception, e: ModuleHelper.WriteIntoDebugLogger("setRouterUpgradeThreshold() Error: " + str(e))
128,838
set ROUTER_SELECTION_JITTER parameter for REED to upgrade to Router Args: iRouterJitter: a random period prior to request Router ID for REED Returns: True: successful to set the ROUTER_SELECTION_JITTER False: fail to set ROUTER_SELECTION_JITTER
def __setRouterSelectionJitter(self, iRouterJitter): print 'call _setRouterSelectionJitter' try: cmd = 'routerselectionjitter %s' % str(iRouterJitter) print cmd return self.__sendCommand(cmd) == 'Done' except Exception, e: ModuleHelper.WriteIntoDebugLogger("setRouterSelectionJitter() Error: " + str(e))
128,839
mapping Rloc16 to router id Args: xRloc16: hex rloc16 short address Returns: actual router id allocated by leader
def __convertRlocToRouterId(self, xRloc16): routerList = [] routerList = self.__sendCommand('router list')[0].split() print routerList print xRloc16 for index in routerList: router = [] cmd = 'router %s' % index router = self.__sendCommand(cmd) for line in router: if 'Done' in line: break elif 'Router ID' in line: routerid = line.split()[2] elif 'Rloc' in line: rloc16 = line.split()[1] else: pass # process input rloc16 if isinstance(xRloc16, str): rloc16 = '0x' + rloc16 if rloc16 == xRloc16: return routerid elif isinstance(xRloc16, int): if int(rloc16, 16) == xRloc16: return routerid else: pass return None
128,843
convert IPv6 prefix string to IPv6 dotted-quad format for example: 2001000000000000 -> 2001:: Args: strIp6Prefix: IPv6 address string Returns: IPv6 address dotted-quad format
def __convertIp6PrefixStringToIp6Address(self, strIp6Prefix): prefix1 = strIp6Prefix.rstrip('L') prefix2 = prefix1.lstrip("0x") hexPrefix = str(prefix2).ljust(16,'0') hexIter = iter(hexPrefix) finalMac = ':'.join(a + b + c + d for a,b,c,d in zip(hexIter, hexIter,hexIter,hexIter)) prefix = str(finalMac) strIp6Prefix = prefix[:20] return strIp6Prefix +':'
128,844
convert a long hex integer to string remove '0x' and 'L' return string Args: iValue: long integer in hex format Returns: string of this long integer without "0x" and "L"
def __convertLongToString(self, iValue): string = '' strValue = str(hex(iValue)) string = strValue.lstrip('0x') string = string.rstrip('L') return string
128,845
read logs during the commissioning process Args: durationInSeconds: time duration for reading commissioning logs Returns: Commissioning logs
def __readCommissioningLogs(self, durationInSeconds): self.logThreadStatus = self.logStatus['running'] logs = Queue() t_end = time.time() + durationInSeconds while time.time() < t_end: time.sleep(0.3) if self.logThreadStatus == self.logStatus['pauseReq']: self.logThreadStatus = self.logStatus['paused'] if self.logThreadStatus != self.logStatus['running']: continue try: line = self._readline() if line: print line logs.put(line) if "Join success" in line: self.joinCommissionedStatus = self.joinStatus['succeed'] break elif "Join failed" in line: self.joinCommissionedStatus = self.joinStatus['failed'] break except Exception: pass self.logThreadStatus = self.logStatus['stop'] return logs
128,846
convert channelsArray to bitmask format Args: channelsArray: channel array (i.e. [21, 22]) Returns: bitmask format corresponding to a given channel array
def __convertChannelMask(self, channelsArray): maskSet = 0 for eachChannel in channelsArray: mask = 1 << eachChannel maskSet = (maskSet | mask) return maskSet
128,847
set the Key switch guard time Args: iKeySwitchGuardTime: key switch guard time Returns: True: successful to set key switch guard time False: fail to set key switch guard time
def __setKeySwitchGuardTime(self, iKeySwitchGuardTime): print '%s call setKeySwitchGuardTime' % self.port print iKeySwitchGuardTime try: cmd = 'keysequence guardtime %s' % str(iKeySwitchGuardTime) if self.__sendCommand(cmd)[0] == 'Done': time.sleep(1) return True else: return False except Exception, e: ModuleHelper.WriteIntoDebugLogger("setKeySwitchGuardTime() Error; " + str(e))
128,850
set Thread Network name Args: networkName: the networkname string to be set Returns: True: successful to set the Thread Networkname False: fail to set the Thread Networkname
def setNetworkName(self, networkName='GRL'): print '%s call setNetworkName' % self.port print networkName try: cmd = 'networkname %s' % networkName datasetCmd = 'dataset networkname %s' % networkName self.hasActiveDatasetToCommit = True return self.__sendCommand(cmd)[0] == 'Done' and self.__sendCommand(datasetCmd)[0] == 'Done' except Exception, e: ModuleHelper.WriteIntoDebugLogger("setNetworkName() Error: " + str(e))
128,854
set channel of Thread device operates on. Args: channel: (0 - 10: Reserved) (11 - 26: 2.4GHz channels) (27 - 65535: Reserved) Returns: True: successful to set the channel False: fail to set the channel
def setChannel(self, channel=11): print '%s call setChannel' % self.port print channel try: cmd = 'channel %s' % channel datasetCmd = 'dataset channel %s' % channel self.hasActiveDatasetToCommit = True return self.__sendCommand(cmd)[0] == 'Done' and self.__sendCommand(datasetCmd)[0] == 'Done' except Exception, e: ModuleHelper.WriteIntoDebugLogger("setChannel() Error: " + str(e))
128,855
get one specific type of MAC address currently OpenThread only supports Random MAC address Args: bType: indicate which kind of MAC address is required Returns: specific type of MAC address
def getMAC(self, bType=MacType.RandomMac): print '%s call getMAC' % self.port print bType # if power down happens, return extended address assigned previously if self.isPowerDown: macAddr64 = self.mac else: if bType == MacType.FactoryMac: macAddr64 = self.__sendCommand('eui64')[0] elif bType == MacType.HashMac: macAddr64 = self.__sendCommand('joinerid')[0] else: macAddr64 = self.__sendCommand('extaddr')[0] print macAddr64 return int(macAddr64, 16)
128,856
send ICMPv6 echo request with a given length to a unicast destination address Args: destination: the unicast destination address of ICMPv6 echo request length: the size of ICMPv6 echo request payload
def ping(self, destination, length=20): print '%s call ping' % self.port print 'destination: %s' %destination try: cmd = 'ping %s %s' % (destination, str(length)) print cmd self._sendline(cmd) self._expect(cmd) # wait echo reply time.sleep(1) except Exception, e: ModuleHelper.WriteIntoDebugLogger("ping() Error: " + str(e))
128,863
set custom LinkQualityIn for all receiving messages from the any address Args: LinkQuality: a given custom link quality link quality/link margin mapping table 3: 21 - 255 (dB) 2: 11 - 20 (dB) 1: 3 - 9 (dB) 0: 0 - 2 (dB) Returns: True: successful to set the link quality False: fail to set the link quality
def setOutBoundLinkQuality(self, LinkQuality): print '%s call setOutBoundLinkQuality' % self.port print LinkQuality try: cmd = 'macfilter rss add-lqi * %s' % str(LinkQuality) print cmd return self.__sendCommand(cmd)[0] == 'Done' except Exception, e: ModuleHelper.WriteIntoDebugLogger("setOutBoundLinkQuality() Error: " + str(e))
128,867
remove the configured prefix on a border router Args: prefixEntry: a on-mesh prefix entry Returns: True: successful to remove the prefix entry from border router False: fail to remove the prefix entry from border router
def removeRouterPrefix(self, prefixEntry): print '%s call removeRouterPrefix' % self.port print prefixEntry prefix = self.__convertIp6PrefixStringToIp6Address(str(prefixEntry)) try: prefixLen = 64 cmd = 'prefix remove %s/%d' % (prefix, prefixLen) print cmd if self.__sendCommand(cmd)[0] == 'Done': # send server data ntf to leader return self.__sendCommand('netdataregister')[0] == 'Done' else: return False except Exception, e: ModuleHelper.WriteIntoDebugLogger("removeRouterPrefix() Error: " + str(e))
128,868
reset and join back Thread Network with a given timeout delay Args: timeout: a timeout interval before rejoin Thread Network Returns: True: successful to reset and rejoin Thread Network False: fail to reset and rejoin the Thread Network
def resetAndRejoin(self, timeout): print '%s call resetAndRejoin' % self.port print timeout try: self._sendline('reset') self.isPowerDown = True time.sleep(timeout) if self.deviceRole == Thread_Device_Role.SED: self.setPollingRate(self.sedPollingRate) self.__startOpenThread() time.sleep(3) if self.__sendCommand('state')[0] == 'disabled': print '[FAIL] reset and rejoin' return False return True except Exception, e: ModuleHelper.WriteIntoDebugLogger("resetAndRejoin() Error: " + str(e))
128,869
set networkid timeout for Thread device Args: iNwkIDTimeOut: a given NETWORK_ID_TIMEOUT Returns: True: successful to set NETWORK_ID_TIMEOUT False: fail to set NETWORK_ID_TIMEOUT
def setNetworkIDTimeout(self, iNwkIDTimeOut): print '%s call setNetworkIDTimeout' % self.port print iNwkIDTimeOut iNwkIDTimeOut /= 1000 try: cmd = 'networkidtimeout %s' % str(iNwkIDTimeOut) print cmd return self.__sendCommand(cmd)[0] == 'Done' except Exception, e: ModuleHelper.WriteIntoDebugLogger("setNetworkIDTimeout() Error: " + str(e))
128,870
set whether the Thread device requires the full network data or only requires the stable network data Args: eDataRequirement: is true if requiring the full network data Returns: True: successful to set the network requirement
def setNetworkDataRequirement(self, eDataRequirement): print '%s call setNetworkDataRequirement' % self.port print eDataRequirement if eDataRequirement == Device_Data_Requirement.ALL_DATA: self.networkDataRequirement = 'n' return True
128,871
get expected global unicast IPv6 address of Thread device Args: filterByPrefix: a given expected global IPv6 prefix to be matched Returns: a global IPv6 address
def getGUA(self, filterByPrefix=None): print '%s call getGUA' % self.port print filterByPrefix globalAddrs = [] try: # get global addrs set if multiple globalAddrs = self.getGlobal() if filterByPrefix is None: return globalAddrs[0] else: for line in globalAddrs: fullIp = ModuleHelper.GetFullIpv6Address(line) if fullIp.startswith(filterByPrefix): return fullIp print 'no global address matched' return str(globalAddrs[0]) except Exception, e: ModuleHelper.WriteIntoDebugLogger("getGUA() Error: " + str(e))
128,876
force to set a slaac IPv6 address to Thread interface Args: slaacAddress: a slaac IPv6 address to be set Returns: True: successful to set slaac address to Thread interface False: fail to set slaac address to Thread interface
def forceSetSlaac(self, slaacAddress): print '%s call forceSetSlaac' % self.port print slaacAddress try: cmd = 'ipaddr add %s' % str(slaacAddress) print cmd return self.__sendCommand(cmd)[0] == 'Done' except Exception, e: ModuleHelper.WriteIntoDebugLogger("forceSetSlaac() Error: " + str(e))
128,878
scan Joiner Args: xEUI: Joiner's EUI-64 strPSKd: Joiner's PSKd for commissioning Returns: True: successful to add Joiner's steering data False: fail to add Joiner's steering data
def scanJoiner(self, xEUI='*', strPSKd='threadjpaketest'): print '%s call scanJoiner' % self.port # long timeout value to avoid automatic joiner removal (in seconds) timeout = 500 if not isinstance(xEUI, str): eui64 = self.__convertLongToString(xEUI) # prepend 0 at the beginning if len(eui64) < 16: eui64 = eui64.zfill(16) print eui64 else: eui64 = xEUI cmd = 'commissioner joiner add %s %s %s' % (eui64, strPSKd, str(timeout)) print cmd if self.__sendCommand(cmd)[0] == 'Done': if self.logThreadStatus == self.logStatus['stop']: self.logThread = ThreadRunner.run(target=self.__readCommissioningLogs, args=(120,)) return True else: return False
128,882
start joiner Args: strPSKd: Joiner's PSKd Returns: True: successful to start joiner False: fail to start joiner
def joinCommissioned(self, strPSKd='threadjpaketest', waitTime=20): print '%s call joinCommissioned' % self.port self.__sendCommand('ifconfig up') cmd = 'joiner start %s %s' %(strPSKd, self.provisioningUrl) print cmd if self.__sendCommand(cmd)[0] == "Done": maxDuration = 150 # seconds self.joinCommissionedStatus = self.joinStatus['ongoing'] if self.logThreadStatus == self.logStatus['stop']: self.logThread = ThreadRunner.run(target=self.__readCommissioningLogs, args=(maxDuration,)) t_end = time.time() + maxDuration while time.time() < t_end: if self.joinCommissionedStatus == self.joinStatus['succeed']: break elif self.joinCommissionedStatus == self.joinStatus['failed']: return False time.sleep(1) self.__sendCommand('thread start') time.sleep(30) return True else: return False
128,883
send MGMT_PANID_QUERY message to a given destination Args: xPanId: a given PAN ID to check the conflicts Returns: True: successful to send MGMT_PANID_QUERY message. False: fail to send MGMT_PANID_QUERY message.
def MGMT_PANID_QUERY(self, sAddr, xCommissionerSessionId, listChannelMask, xPanId): print '%s call MGMT_PANID_QUERY' % self.port panid = '' channelMask = '' channelMask = '0x' + self.__convertLongToString(self.__convertChannelMask(listChannelMask)) if not isinstance(xPanId, str): panid = str(hex(xPanId)) try: cmd = 'commissioner panid %s %s %s' % (panid, channelMask, sAddr) print cmd return self.__sendCommand(cmd) == 'Done' except Exception, e: ModuleHelper.writeintodebuglogger("MGMT_PANID_QUERY() error: " + str(e))
128,886
set Joiner UDP Port Args: portNumber: Joiner UDP Port number Returns: True: successful to set Joiner UDP Port False: fail to set Joiner UDP Port
def setUdpJoinerPort(self, portNumber): print '%s call setUdpJoinerPort' % self.port cmd = 'joinerport %d' % portNumber print cmd return self.__sendCommand(cmd)[0] == 'Done'
128,892
Initialize the controller Args: port (str): serial port's path or name(windows)
def __init__(self, port, log=False): super(OpenThreadController, self).__init__() self.port = port self.handle = None self.lines = [] self._log = log self._is_net = False self._init()
128,898
Find the `expected` line within `times` trials. Args: expected str: the expected string times int: number of trials
def _expect(self, expected, times=50): logger.debug('[%s] Expecting [%s]', self.port, expected) retry_times = 10 while times: if not retry_times: break line = self._readline() if line == expected: return if not line: retry_times -= 1 time.sleep(0.1) times -= 1 raise Exception('failed to find expected string[%s]' % expected)
128,903
Send exactly one line to the device Args: line str: data send to device
def _sendline(self, line): self.lines = [] try: self._read() except socket.error: logging.debug('Nothing cleared') logger.debug('sending [%s]', line) self._write(line + '\r\n') # wait for write to complete time.sleep(0.5)
128,905
Send command and wait for response. The command will be repeated 3 times at most in case data loss of serial port. Args: req (str): Command to send, please do not include new line in the end. Returns: [str]: The output lines
def _req(self, req): logger.debug('DUT> %s', req) self._log and self.pause() times = 3 res = None while times: times = times - 1 try: self._sendline(req) self._expect(req) line = None res = [] while True: line = self._readline() logger.debug('Got line %s', line) if line == 'Done': break if line: res.append(line) break except: logger.exception('Failed to send command') self.close() self._init() self._log and self.resume() return res
128,906
Add network prefix. Args: prefix (str): network prefix. flags (str): network prefix flags, please refer thread documentation for details prf (str): network prf, please refer thread documentation for details
def add_prefix(self, prefix, flags, prf): self._req('prefix add %s %s %s' % (prefix, flags, prf)) time.sleep(1) self._req('netdataregister')
128,909
Open telnet connection Args: params (dict), must contain two parameters "ip" - ip address or hostname and "port" - port number Example: params = {'port': 23, 'ip': 'localhost'}
def open(self, **params): logger.info('opening telnet') self.port = params['port'] self.ip = params['ip'] self.tn = None self._init()
128,929
Reboot outlet Args: params (dict), must contain parameter "outlet" - outlet number Example: params = {'outlet': 1}
def reboot(self, **params): outlet = params['outlet'] # main menu self.tn.write('\x1b\r\n') self.until_done() # Device Manager self.tn.write('1\r\n') self.until_done() # Outlet Management self.tn.write('2\r\n') self.until_done() # Outlet Control self.tn.write('1\r\n') self.until_done() # Select outlet self.tn.write('%d\r\n' % outlet) self.until_done() # Control self.tn.write('1\r\n') self.until_done() # off self.tn.write('2\r\n') self.until('to cancel') self.tn.write('YES\r\n') self.until('to continue') self.tn.write('\r\n') self.until_done() time.sleep(5) # on self.tn.write('1\r\n') self.until('to cancel') self.tn.write('YES\r\n') self.until('to continue') self.tn.write('\r\n') self.until_done()
128,931
initialize the serial port and default network parameters Args: **kwargs: Arbitrary keyword arguments Includes 'EUI' and 'SerialPort'
def __init__(self, **kwargs): try: self.UIStatusMsg = '' self.mac = kwargs.get('EUI') self.handle = None self.AutoDUTEnable = False self._is_net = False # whether device is through ser2net self.logStatus = {'stop':'stop', 'running':'running', 'pauseReq':'pauseReq', 'paused':'paused'} self.logThreadStatus = self.logStatus['stop'] self.connectType = (kwargs.get('Param5')).strip().lower() if kwargs.get('Param5') is not None else 'usb' if self.connectType == 'ip': self.dutIpv4 = kwargs.get('TelnetIP') self.dutPort = kwargs.get('TelnetPort') self.port = self.dutIpv4 + ':' + self.dutPort else: self.port = kwargs.get('SerialPort') self.intialize() except Exception, e: ModuleHelper.WriteIntoDebugLogger('initialize() Error: ' + str(e))
128,943
send specific command to reference unit over serial port Args: cmd: OpenThread_WpanCtl command string Returns: Fail: Failed to send the command to reference unit and parse it Value: successfully retrieve the desired value from reference unit Error: some errors occur, indicates by the followed specific error number
def __sendCommand(self, cmd): logging.info('%s: sendCommand[%s]', self.port, cmd) if self.logThreadStatus == self.logStatus['running']: self.logThreadStatus = self.logStatus['pauseReq'] while self.logThreadStatus != self.logStatus['paused'] and self.logThreadStatus != self.logStatus['stop']: pass ssh_stdin = None ssh_stdout = None ssh_stderr = None try: # command retransmit times retry_times = 3 while retry_times > 0: retry_times -= 1 try: if self._is_net: ssh_stdin, ssh_stdout, ssh_stderr = self.handle.exec_command(cmd) else: self._sendline(cmd) self._expect(cmd) except Exception as e: logging.exception('%s: failed to send command[%s]: %s', self.port, cmd, str(e)) if retry_times == 0: raise else: break line = None response = [] retry_times = 20 stdout_lines = [] stderr_lines = [] if self._is_net: stdout_lines = ssh_stdout.readlines() stderr_lines = ssh_stderr.readlines() if stderr_lines: for stderr_line in stderr_lines: if re.search(r'Not\s+Found|failed\s+with\s+error', stderr_line.strip(), re.M | re.I): print "Command failed:" + stderr_line return 'Fail' print "Got line: " + stderr_line logging.info('%s: the read line is[%s]', self.port, stderr_line) response.append(str(stderr_line.strip())) elif stdout_lines: for stdout_line in stdout_lines: logging.info('%s: the read line is[%s]', self.port, stdout_line) if re.search(r'Not\s+Found|failed\s+with\s+error', stdout_line.strip(), re.M | re.I): print "Command failed" return 'Fail' print "Got line: " + stdout_line logging.info('%s: send command[%s] done!', self.port, cmd) response.append(str(stdout_line.strip())) response.append(WPAN_CARRIER_PROMPT) return response else: while retry_times > 0: line = self._readline() print "read line: %s" % line logging.info('%s: the read line is[%s]', self.port, line) if line: response.append(line) if re.match(WPAN_CARRIER_PROMPT, line): break elif re.search(r'Not\s+Found|failed\s+with\s+error', line, re.M | re.I): print "Command failed" return 'Fail' retry_times -= 1 time.sleep(0.1) if retry_times == 0: raise Exception('%s: failed to find end of response' % self.port) logging.info('%s: send command[%s] done!', self.port, cmd) return response except Exception, e: ModuleHelper.WriteIntoDebugLogger('sendCommand() Error: ' + str(e)) raise
128,945
strip the special characters in the value Args: value: value string Returns: value string without special characters
def __stripValue(self, value): if isinstance(value, str): if ( value[0] == '"' and value[-1] == '"' ) or ( value[0] == '[' and value[-1] == ']' ): return value[1:-1] return value
128,946
get specific type of IPv6 address configured on OpenThread_WpanCtl Args: addressType: the specific type of IPv6 address link local: link local unicast IPv6 address that's within one-hop scope global: global unicast IPv6 address rloc: mesh local unicast IPv6 address for routing in thread network mesh EID: mesh Endpoint Identifier Returns: IPv6 address string
def __getIp6Address(self, addressType): addrType = ['link local', 'global', 'rloc', 'mesh EID'] addrs = [] globalAddr = [] linkLocal64Addr = '' rlocAddr = '' meshEIDAddr = '' addrs = self.__sendCommand(WPANCTL_CMD + 'getprop -v IPv6:AllAddresses') for ip6AddrItem in addrs: if re.match('\[|\]', ip6AddrItem): continue if re.match(WPAN_CARRIER_PROMPT, ip6AddrItem, re.M|re.I): break ip6AddrItem = ip6AddrItem.strip() ip6Addr = self.__stripValue(ip6AddrItem).split(' ')[0] ip6AddrPrefix = ip6Addr.split(':')[0] if ip6AddrPrefix == 'fe80': # link local address if ip6Addr.split(':')[4] != '0': linkLocal64Addr = ip6Addr elif ip6Addr.startswith(self.meshLocalPrefix): # mesh local address if ip6Addr.split(':')[4] == '0': # rloc rlocAddr = ip6Addr else: # mesh EID meshEIDAddr = ip6Addr print 'meshEIDAddr:' + meshEIDAddr else: # global ipv6 address if ip6Addr: print 'globalAddr: ' + ip6Addr globalAddr.append(ip6Addr) else: pass if addressType == addrType[0]: return linkLocal64Addr elif addressType == addrType[1]: return globalAddr elif addressType == addrType[2]: return rlocAddr elif addressType == addrType[3]: return meshEIDAddr else: pass
128,948
set thread device mode: Args: mode: thread device mode. 15=rsdn, 13=rsn, 4=s r: rx-on-when-idle s: secure IEEE 802.15.4 data request d: full thread device n: full network data Returns: True: successful to set the device mode False: fail to set the device mode
def __setDeviceMode(self, mode): print 'call __setDeviceMode' try: cmd = WPANCTL_CMD + 'setprop Thread:DeviceMode %d' % mode return self.__sendCommand(cmd)[0] != 'Fail' except Exception, e: ModuleHelper.WriteIntoDebugLogger('setDeviceMode() Error: ' + str(e))
128,949
mapping Rloc16 to router id Args: xRloc16: hex rloc16 short address Returns: actual router id allocated by leader
def __convertRlocToRouterId(self, xRloc16): routerList = [] routerList = self.__sendCommand(WPANCTL_CMD + 'getprop -v Thread:RouterTable') print routerList print xRloc16 for line in routerList: if re.match('\[|\]', line): continue if re.match(WPAN_CARRIER_PROMPT, line, re.M|re.I): break router = [] router = self.__stripValue(line).split(',') for item in router: if 'RouterId' in item: routerid = item.split(':')[1] elif 'RLOC16' in line: rloc16 = line.split(':')[1] else: pass # process input rloc16 if isinstance(xRloc16, str): rloc16 = '0x' + rloc16 if rloc16 == xRloc16: return routerid elif isinstance(xRloc16, int): if int(rloc16, 16) == xRloc16: return routerid else: pass return None
128,954
convert a channel list to a string Args: channelList: channel list (i.e. [21, 22, 23]) Returns: a comma separated channel string (i.e. '21, 22, 23')
def __ChannelMaskListToStr(self, channelList): chan_mask_range = '' if isinstance(channelList, list): if len(channelList): chan_mask_range = ",".join(str(chan) for chan in channelList) else: print 'empty list' else: print 'not a valid channel list:', channelList return chan_mask_range
128,955
set the extended addresss of Thread device Args: xEUI: extended address in hex format Returns: True: successful to set the extended address False: fail to set the extended address
def setMAC(self, xEUI): print '%s call setMAC' % self.port address64 = '' try: if not xEUI: address64 = self.mac if not isinstance(xEUI, str): address64 = self.__convertLongToString(xEUI) # prepend 0 at the beginning if len(address64) < 16: address64 = address64.zfill(16) print address64 else: address64 = xEUI cmd = WPANCTL_CMD + 'setprop NCP:MACAddress %s' % address64 if self.__sendCommand(cmd)[0] != 'Fail': self.mac = address64 return True else: return False except Exception, e: ModuleHelper.WriteIntoDebugLogger('setMAC() Error: ' + str(e))
128,961
get one specific type of MAC address currently OpenThreadWpan only supports Random MAC address Args: bType: indicate which kind of MAC address is required Returns: specific type of MAC address
def getMAC(self, bType=MacType.RandomMac): print '%s call getMAC' % self.port # if power down happens, return extended address assigned previously if self.isPowerDown: macAddr64 = self.mac else: if bType == MacType.FactoryMac: macAddr64 = self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:HardwareAddress')[0]) elif bType == MacType.HashMac: macAddr64 = self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:MACAddress')[0]) else: macAddr64 = self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:ExtendedAddress')[0]) return int(macAddr64, 16)
128,962
set Thread Network master key Args: key: Thread Network master key used in secure the MLE/802.15.4 packet Returns: True: successful to set the Thread Network master key False: fail to set the Thread Network master key
def setNetworkKey(self, key): masterKey = '' print '%s call setNetworkKey' % self.port try: if not isinstance(key, str): masterKey = self.__convertLongToString(key) # prpend '0' at the beginning if len(masterKey) < 32: masterKey = masterKey.zfill(32) cmd = WPANCTL_CMD + 'setprop Network:Key %s' % masterKey datasetCmd = WPANCTL_CMD + 'setprop Dataset:MasterKey %s' % masterKey else: masterKey = key cmd = WPANCTL_CMD + 'setprop Network:Key %s' % masterKey datasetCmd = WPANCTL_CMD + 'setprop Dataset:MasterKey %s' % masterKey self.networkKey = masterKey self.hasActiveDatasetToCommit = True return self.__sendCommand(cmd)[0] != 'Fail' and self.__sendCommand(datasetCmd)[0] != 'Fail' except Exception, e: ModuleHelper.WriteIntoDebugLogger('setNetworkkey() Error: ' + str(e))
128,965
add a given extended address to the whitelist addressfilter Args: xEUI: a given extended address in hex format Returns: True: successful to add a given extended address to the whitelist entry False: fail to add a given extended address to the whitelist entry
def addAllowMAC(self, xEUI): print '%s call addAllowMAC' % self.port print xEUI if isinstance(xEUI, str): macAddr = xEUI else: macAddr = self.__convertLongToString(xEUI) try: if self._addressfilterMode != 'whitelist': if self.__setAddressfilterMode('Whitelist'): self._addressfilterMode = 'whitelist' cmd = WPANCTL_CMD + 'insert MAC:Whitelist:Entries %s' % macAddr ret = self.__sendCommand(cmd)[0] != 'Fail' self._addressfilterSet.add(macAddr) print 'current whitelist entries:' for addr in self._addressfilterSet: print addr return ret except Exception, e: ModuleHelper.WriteIntoDebugLogger('addAllowMAC() Error: ' + str(e))
128,966
make device ready to join the Thread Network with a given role Args: eRoleId: a given device role id Returns: True: ready to set Thread Network parameter for joining desired Network
def joinNetwork(self, eRoleId): print '%s call joinNetwork' % self.port print eRoleId self.deviceRole = eRoleId mode = 15 try: if ModuleHelper.LeaderDutChannelFound: self.channel = ModuleHelper.Default_Channel # FIXME: when Harness call setNetworkDataRequirement()? # only sleep end device requires stable networkdata now if eRoleId == Thread_Device_Role.Leader: print 'join as leader' #rsdn mode = 15 if self.AutoDUTEnable is False: # set ROUTER_DOWNGRADE_THRESHOLD self.__setRouterDowngradeThreshold(33) elif eRoleId == Thread_Device_Role.Router: print 'join as router' #rsdn mode = 15 if self.AutoDUTEnable is False: # set ROUTER_DOWNGRADE_THRESHOLD self.__setRouterDowngradeThreshold(33) elif eRoleId == Thread_Device_Role.SED: print 'join as sleepy end device' #s mode = 4 self.setPollingRate(self.sedPollingRate) elif eRoleId == Thread_Device_Role.EndDevice: print 'join as end device' #rsn mode = 13 elif eRoleId == Thread_Device_Role.REED: print 'join as REED' #rsdn mode = 15 # set ROUTER_UPGRADE_THRESHOLD self.__setRouterUpgradeThreshold(0) elif eRoleId == Thread_Device_Role.EndDevice_FED: # always remain an ED, never request to be a router print 'join as FED' #rsdn mode = 15 # set ROUTER_UPGRADE_THRESHOLD self.__setRouterUpgradeThreshold(0) elif eRoleId == Thread_Device_Role.EndDevice_MED: print 'join as MED' #rsn mode = 13 else: pass # set Thread device mode with a given role self.__setDeviceMode(mode) self.__setKeySwitchGuardTime(0) #temporally time.sleep(0.1) # start OpenThreadWpan self.__startOpenThreadWpan() time.sleep(3) return True except Exception, e: ModuleHelper.WriteIntoDebugLogger('joinNetwork() Error: ' + str(e))
128,969
send ICMPv6 echo request with a given length to a unicast destination address Args: destination: the unicast destination address of ICMPv6 echo request length: the size of ICMPv6 echo request payload
def ping(self, destination, length=20): print '%s call ping' % self.port print 'destination: %s' %destination try: cmd = 'ping %s -c 1 -s %s -I %s' % (destination, str(length), WPAN_INTERFACE) if self._is_net: ssh_stdin, ssh_stdout, ssh_stderr = self.handle.exec_command(cmd) else: self._sendline(cmd) self._expect(cmd) # wait echo reply time.sleep(1) except Exception, e: ModuleHelper.WriteIntoDebugLogger('ping() Error: ' + str(e))
128,975
set Thread Network PAN ID Args: xPAN: a given PAN ID in hex format Returns: True: successful to set the Thread Network PAN ID False: fail to set the Thread Network PAN ID
def setPANID(self, xPAN): print '%s call setPANID' % self.port print xPAN panid = '' try: if not isinstance(xPAN, str): panid = str(hex(xPAN)) print panid cmd = WPANCTL_CMD + 'setprop -s Network:PANID %s' % panid datasetCmd = WPANCTL_CMD + 'setprop Dataset:PanId %s' % panid self.hasActiveDatasetToCommit = True return self.__sendCommand(cmd)[0] != 'Fail' and self.__sendCommand(datasetCmd)[0] != 'Fail' except Exception, e: ModuleHelper.WriteIntoDebugLogger('setPANID() Error: ' + str(e))
128,977
kick router with a given router id from the Thread Network Args: xRouterId: a given router id in hex format Returns: True: successful to remove the router from the Thread Network False: fail to remove the router from the Thread Network
def removeRouter(self, xRouterId): print '%s call removeRouter' % self.port print xRouterId routerId = '' routerId = self.__convertRlocToRouterId(xRouterId) print routerId if routerId == None: print 'no matched xRouterId' return False try: cmd = 'releaserouterid %s' % routerId return self.__sendCommand(cmd)[0] != 'Fail' except Exception, e: ModuleHelper.WriteIntoDebugLogger('removeRouter() Error: ' + str(e))
128,979
set data polling rate for sleepy end device Args: iPollingRate: data poll period of sleepy end device Returns: True: successful to set the data polling rate for sleepy end device False: fail to set the data polling rate for sleepy end device
def setPollingRate(self, iPollingRate): print '%s call setPollingRate' % self.port print iPollingRate try: cmd = WPANCTL_CMD + 'setprop NCP:SleepyPollInterval %s' % str(iPollingRate*1000) print cmd return self.__sendCommand(cmd)[0] != 'Fail' except Exception, e: ModuleHelper.WriteIntoDebugLogger('setPollingRate() Error: ' + str(e))
128,981
reset and join back Thread Network with a given timeout delay Args: timeout: a timeout interval before rejoin Thread Network Returns: True: successful to reset and rejoin Thread Network False: fail to reset and rejoin the Thread Network
def resetAndRejoin(self, timeout): print '%s call resetAndRejoin' % self.port print timeout try: if self.__sendCommand(WPANCTL_CMD + 'setprop Daemon:AutoAssociateAfterReset false')[0] != 'Fail': time.sleep(0.5) if self.__sendCommand(WPANCTL_CMD + 'reset')[0] != 'Fail': self.isPowerDown = True else: return False else: return False time.sleep(timeout) if self.deviceRole == Thread_Device_Role.SED: self.setPollingRate(self.sedPollingRate) if self.__sendCommand(WPANCTL_CMD + 'attach')[0] != 'Fail': time.sleep(3) else: return False if self.__sendCommand(WPANCTL_CMD + 'setprop Daemon:AutoAssociateAfterReset true')[0] == 'Fail': return False if self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v NCP:State')[0]) != 'associated': print '[FAIL] reset and rejoin' return False return True except Exception, e: ModuleHelper.WriteIntoDebugLogger('resetAndRejoin() Error: ' + str(e))
128,982
set keep alive timeout for device has been deprecated and also set SED polling rate Args: iTimeOut: data poll period for sleepy end device Returns: True: successful to set the data poll period for SED False: fail to set the data poll period for SED
def setKeepAliveTimeOut(self, iTimeOut): print '%s call setKeepAliveTimeOut' % self.port print iTimeOut try: cmd = WPANCTL_CMD + 'setprop NCP:SleepyPollInterval %s' % str(iTimeOut*1000) print cmd return self.__sendCommand(cmd)[0] != 'Fail' except Exception, e: ModuleHelper.WriteIntoDebugLogger('setKeepAliveTimeOut() Error: ' + str(e))
128,984
set the Key sequence counter corresponding to Thread Network master key Args: iKeySequenceValue: key sequence value Returns: True: successful to set the key sequence False: fail to set the key sequence
def setKeySequenceCounter(self, iKeySequenceValue): print '%s call setKeySequenceCounter' % self.port print iKeySequenceValue try: cmd = WPANCTL_CMD + 'setprop Network:KeyIndex %s' % str(iKeySequenceValue) if self.__sendCommand(cmd)[0] != 'Fail': time.sleep(1) return True else: return False except Exception, e: ModuleHelper.WriteIntoDebugLogger('setKeySequenceCounter() Error: ' + str(e))
128,985
increment the key sequence with a given value Args: iIncrementValue: specific increment value to be added Returns: True: successful to increment the key sequence with a given value False: fail to increment the key sequence with a given value
def incrementKeySequenceCounter(self, iIncrementValue=1): print '%s call incrementKeySequenceCounter' % self.port print iIncrementValue currentKeySeq = '' try: currentKeySeq = self.getKeySequenceCounter() keySequence = int(currentKeySeq, 10) + iIncrementValue print keySequence return self.setKeySequenceCounter(keySequence) except Exception, e: ModuleHelper.WriteIntoDebugLogger('incrementKeySequenceCounter() Error: ' + str(e))
128,987
set extended PAN ID of Thread Network Args: xPanId: extended PAN ID in hex format Returns: True: successful to set the extended PAN ID False: fail to set the extended PAN ID
def setXpanId(self, xPanId): xpanid = '' print '%s call setXpanId' % self.port print xPanId try: if not isinstance(xPanId, str): xpanid = self.__convertLongToString(xPanId) # prepend '0' at the beginning if len(xpanid) < 16: xpanid = xpanid.zfill(16) print xpanid cmd = WPANCTL_CMD + 'setprop Network:XPANID %s' % xpanid datasetCmd = WPANCTL_CMD + 'setprop Dataset:ExtendedPanId %s' % xpanid else: xpanid = xPanId cmd = WPANCTL_CMD + 'setprop Network:XPANID %s' % xpanid datasetCmd = WPANCTL_CMD + 'setprop Dataset:ExtendedPanId %s' % xpanid self.xpanId = xpanid self.hasActiveDatasetToCommit = True return self.__sendCommand(cmd)[0] != 'Fail' and self.__sendCommand(datasetCmd)[0] != 'Fail' except Exception, e: ModuleHelper.WriteIntoDebugLogger('setXpanId() Error: ' + str(e))
128,988
set Thread Network Partition ID Args: partitionId: partition id to be set by leader Returns: True: successful to set the Partition ID False: fail to set the Partition ID
def setPartationId(self, partationId): print '%s call setPartationId' % self.port print partationId cmd = WPANCTL_CMD + 'setprop Network:PartitionId %s' %(str(hex(partationId)).rstrip('L')) print cmd return self.__sendCommand(cmd)[0] != 'Fail'
128,989
get expected global unicast IPv6 address of OpenThreadWpan Args: filterByPrefix: a given expected global IPv6 prefix to be matched Returns: a global IPv6 address
def getGUA(self, filterByPrefix=None): print '%s call getGUA' % self.port print filterByPrefix globalAddrs = [] try: # get global addrs set if multiple globalAddrs = self.getGlobal() if filterByPrefix is None: return self.__padIp6Addr(globalAddrs[0]) else: for line in globalAddrs: line = self.__padIp6Addr(line) print "Padded IPv6 Address:" + line if line.startswith(filterByPrefix): return line print 'no global address matched' return str(globalAddrs[0]) except Exception, e: ModuleHelper.WriteIntoDebugLogger('getGUA() Error: ' + str(e)) return e
128,990
scan Joiner Args: xEUI: Joiner's EUI-64 strPSKd: Joiner's PSKd for commissioning Returns: True: successful to add Joiner's steering data False: fail to add Joiner's steering data
def scanJoiner(self, xEUI='*', strPSKd='threadjpaketest'): print '%s call scanJoiner' % self.port if not isinstance(xEUI, str): eui64 = self.__convertLongToString(xEUI) # prepend 0 at the beginning if len(eui64) < 16: eui64 = eui64.zfill(16) print eui64 else: eui64 = xEUI # long timeout value to avoid automatic joiner removal (in seconds) timeout = 500 cmd = WPANCTL_CMD + 'commissioner joiner-add %s %s %s' % (eui64, str(timeout), strPSKd) print cmd if not self.isActiveCommissioner: self.startCollapsedCommissioner() if self.__sendCommand(cmd)[0] != 'Fail': return True else: return False
128,994
set provisioning Url Args: strURL: Provisioning Url string Returns: True: successful to set provisioning Url False: fail to set provisioning Url
def setProvisioningUrl(self, strURL='grl.com'): print '%s call setProvisioningUrl' % self.port self.provisioningUrl = strURL if self.deviceRole == Thread_Device_Role.Commissioner: cmd = WPANCTL_CMD + 'setprop Commissioner:ProvisioningUrl %s' %(strURL) print cmd return self.__sendCommand(cmd)[0] != "Fail" return True
128,995
start joiner Args: strPSKd: Joiner's PSKd Returns: True: successful to start joiner False: fail to start joiner
def joinCommissioned(self, strPSKd='threadjpaketest', waitTime=20): print '%s call joinCommissioned' % self.port cmd = WPANCTL_CMD + 'joiner --start %s %s' %(strPSKd, self.provisioningUrl) print cmd if self.__sendCommand(cmd)[0] != "Fail": if self.__getJoinerState(): self.__sendCommand(WPANCTL_CMD + 'joiner --attach') time.sleep(30) return True else: return False else: return False
128,997
send MGMT_PANID_QUERY message to a given destination Args: xPanId: a given PAN ID to check the conflicts Returns: True: successful to send MGMT_PANID_QUERY message. False: fail to send MGMT_PANID_QUERY message.
def MGMT_PANID_QUERY(self, sAddr, xCommissionerSessionId, listChannelMask, xPanId): print '%s call MGMT_PANID_QUERY' % self.port panid = '' channelMask = '' channelMask = self.__ChannelMaskListToStr(listChannelMask) if not isinstance(xPanId, str): panid = str(hex(xPanId)) try: cmd = WPANCTL_CMD + 'commissioner pan-id-query %s %s %s' % (panid, channelMask, sAddr) print cmd return self.__sendCommand(cmd) != 'Fail' except Exception, e: ModuleHelper.WriteIntoDebugLogger('MGMT_PANID_QUERY() error: ' + str(e))
128,998
Run the task for the given host. Arguments: host (:obj:`nornir.core.inventory.Host`): Host we are operating with. Populated right before calling the ``task`` nornir(:obj:`nornir.core.Nornir`): Populated right before calling the ``task`` Returns: host (:obj:`nornir.core.task.MultiResult`): Results of the task and its subtasks
def start(self, host, nornir): self.host = host self.nornir = nornir try: logger.debug("Host %r: running task %r", self.host.name, self.name) r = self.task(self, **self.params) if not isinstance(r, Result): r = Result(host=host, result=r) except NornirSubTaskError as e: tb = traceback.format_exc() logger.error( "Host %r: task %r failed with traceback:\n%s", self.host.name, self.name, tb, ) r = Result(host, exception=e, result=str(e), failed=True) except Exception as e: tb = traceback.format_exc() logger.error( "Host %r: task %r failed with traceback:\n%s", self.host.name, self.name, tb, ) r = Result(host, exception=e, result=tb, failed=True) r.name = self.name r.severity_level = logging.ERROR if r.failed else self.severity_level self.results.insert(0, r) return self.results
129,013
Netbox plugin Arguments: nb_url: Netbox url, defaults to http://localhost:8080. You can also use env variable NB_URL nb_token: Netbokx token. You can also use env variable NB_TOKEN use_slugs: Whether to use slugs or not flatten_custom_fields: Whether to assign custom fields directly to the host or not filter_parameters: Key-value pairs to filter down hosts
def __init__( self, nb_url: Optional[str] = None, nb_token: Optional[str] = None, use_slugs: bool = True, flatten_custom_fields: bool = True, filter_parameters: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> None: filter_parameters = filter_parameters or {} nb_url = nb_url or os.environ.get("NB_URL", "http://localhost:8080") nb_token = nb_token or os.environ.get( "NB_TOKEN", "0123456789abcdef0123456789abcdef01234567" ) headers = {"Authorization": "Token {}".format(nb_token)} # Create dict of hosts using 'devices' from NetBox r = requests.get( "{}/api/dcim/devices/?limit=0".format(nb_url), headers=headers, params=filter_parameters, ) r.raise_for_status() nb_devices = r.json() hosts = {} for d in nb_devices["results"]: host: HostsDict = {"data": {}} # Add value for IP address if d.get("primary_ip", {}): host["hostname"] = d["primary_ip"]["address"].split("/")[0] # Add values that don't have an option for 'slug' host["data"]["serial"] = d["serial"] host["data"]["vendor"] = d["device_type"]["manufacturer"]["name"] host["data"]["asset_tag"] = d["asset_tag"] if flatten_custom_fields: for cf, value in d["custom_fields"].items(): host["data"][cf] = value else: host["data"]["custom_fields"] = d["custom_fields"] # Add values that do have an option for 'slug' if use_slugs: host["data"]["site"] = d["site"]["slug"] host["data"]["role"] = d["device_role"]["slug"] host["data"]["model"] = d["device_type"]["slug"] # Attempt to add 'platform' based of value in 'slug' host["platform"] = d["platform"]["slug"] if d["platform"] else None else: host["data"]["site"] = d["site"]["name"] host["data"]["role"] = d["device_role"] host["data"]["model"] = d["device_type"] host["platform"] = d["platform"] # Assign temporary dict to outer dict hosts[d["name"]] = host # Pass the data back to the parent class super().__init__(hosts=hosts, groups={}, defaults={}, **kwargs)
129,021
Gather information with napalm and validate it: http://napalm.readthedocs.io/en/develop/validate/index.html Arguments: src: file to use as validation source validation_source (list): data to validate device's state Returns: Result object with the following attributes set: * result (``dict``): dictionary with the result of the validation * complies (``bool``): Whether the device complies or not
def napalm_validate( task: Task, src: Optional[str] = None, validation_source: ValidationSourceData = None, ) -> Result: device = task.host.get_connection("napalm", task.nornir.config) r = device.compliance_report( validation_file=src, validation_source=validation_source ) return Result(host=task.host, result=r)
129,022
Execute Netmiko save_config method Arguments: cmd(str, optional): Command used to save the configuration. confirm(bool, optional): Does device prompt for confirmation before executing save operation confirm_response(str, optional): Response send to device when it prompts for confirmation Returns: :obj: `nornir.core.task.Result`: * result (``str``): String showing the CLI output from the save operation
def netmiko_save_config( task: Task, cmd: str = "", confirm: bool = False, confirm_response: str = "" ) -> Result: conn = task.host.get_connection("netmiko", task.nornir.config) if cmd: result = conn.save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response ) else: result = conn.save_config(confirm=confirm, confirm_response=confirm_response) return Result(host=task.host, result=result, changed=True)
129,023
Returns the value ``item`` from the host or hosts group variables. Arguments: item(``str``): The variable to get default(``any``): Return value if item not found
def get(self, item, default=None): if hasattr(self, item): return getattr(self, item) try: return self.__getitem__(item) except KeyError: return default
129,039
Renders contants of a file with jinja2. All the host data is available in the template Arguments: template: filename path: path to dir with templates jinja_filters: jinja filters to enable. Defaults to nornir.config.jinja2.filters **kwargs: additional data to pass to the template Returns: Result object with the following attributes set: * result (``string``): rendered string
def template_file( task: Task, template: str, path: str, jinja_filters: FiltersDict = None, **kwargs: Any ) -> Result: jinja_filters = jinja_filters or {} or task.nornir.config.jinja2.filters text = jinja_helper.render_from_file( template=template, path=path, host=task.host, jinja_filters=jinja_filters, **kwargs ) return Result(host=task.host, result=text)
129,062
Execute Netmiko send_config_set method (or send_config_from_file) Arguments: config_commands: Commands to configure on the remote network device. config_file: File to read configuration commands from. kwargs: Additional arguments to pass to method. Returns: Result object with the following attributes set: * result (``str``): string showing the CLI from the configuration changes.
def netmiko_send_config( task: Task, config_commands: Optional[List[str]] = None, config_file: Optional[str] = None, **kwargs: Any ) -> Result: net_connect = task.host.get_connection("netmiko", task.nornir.config) net_connect.enable() if config_commands: result = net_connect.send_config_set(config_commands=config_commands, **kwargs) elif config_file: result = net_connect.send_config_from_file(config_file=config_file, **kwargs) else: raise ValueError("Must specify either config_commands or config_file") return Result(host=task.host, result=result, changed=True)
129,065
Loads a json file. Arguments: file: path to the file containing the json file to load Examples: Simple example with ``ordered_dict``:: > nr.run(task=load_json, file="mydata.json") file: path to the file containing the json file to load Returns: Result object with the following attributes set: * result (``dict``): dictionary with the contents of the file
def load_json(task: Task, file: str) -> Result: kwargs: Dict[str, Type[MutableMapping[str, Any]]] = {} with open(file, "r") as f: data = json.loads(f.read(), **kwargs) return Result(host=task.host, result=data)
129,072
Prints the :obj:`nornir.core.task.Result` from a previous task to screen Arguments: result: from a previous task host: # TODO vars: Which attributes you want to print failed: if ``True`` assume the task failed severity_level: Print only errors with this severity level or higher
def print_result( result: Result, host: Optional[str] = None, vars: List[str] = None, failed: bool = False, severity_level: int = logging.INFO, ) -> None: LOCK.acquire() try: _print_result(result, host, vars, failed, severity_level) finally: LOCK.release()
129,077
Executes a command locally Arguments: command: command to execute Returns: Result object with the following attributes set: * result (``str``): stderr or stdout * stdout (``str``): stdout * stderr (``str``): stderr Raises: :obj:`nornir.core.exceptions.CommandError`: when there is a command error
def command(task: Task, command: str) -> Result: cmd = subprocess.Popen( shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, ) stdout, stderr = cmd.communicate() stdout = stdout.decode() stderr = stderr.decode() if cmd.poll(): raise CommandError(command, cmd.returncode, stdout, stderr) result = stderr if stderr else stdout return Result(result=result, host=task.host, stderr=stderr, stdout=stdout)
129,079
Execute Netmiko file_transfer method Arguments: source_file: Source file. dest_file: Destination file. kwargs: Additional arguments to pass to file_transfer Returns: Result object with the following attributes set: * result (``bool``): file exists and MD5 is valid * changed (``bool``): the destination file was changed
def netmiko_file_transfer( task: Task, source_file: str, dest_file: str, **kwargs: Any ) -> Result: net_connect = task.host.get_connection("netmiko", task.nornir.config) kwargs.setdefault("direction", "put") scp_result = file_transfer( net_connect, source_file=source_file, dest_file=dest_file, **kwargs ) if kwargs.get("disable_md5") is True: file_valid = scp_result["file_exists"] else: file_valid = scp_result["file_exists"] and scp_result["file_verified"] return Result( host=task.host, result=file_valid, changed=scp_result["file_transferred"] )
129,106
Run commands on remote devices using napalm Arguments: commands: commands to execute Returns: Result object with the following attributes set: * result (``dict``): result of the commands execution
def napalm_cli(task: Task, commands: List[str]) -> Result: device = task.host.get_connection("napalm", task.nornir.config) result = device.cli(commands) return Result(host=task.host, result=result)
129,107
Dummy task that echoes the data passed to it. Useful in grouped_tasks to debug data passed to tasks. Arguments: ``**kwargs``: Any <key,value> pair you want Returns: Result object with the following attributes set: * result (``dict``): ``**kwargs`` passed to the task
def echo_data(task: Task, **kwargs: Any) -> Result: return Result(host=task.host, result=kwargs)
129,129
Renders a string with jinja2. All the host data is available in the template Arguments: template (string): template string jinja_filters (dict): jinja filters to enable. Defaults to nornir.config.jinja2.filters **kwargs: additional data to pass to the template Returns: Result object with the following attributes set: * result (``string``): rendered string
def template_string( task: Task, template: str, jinja_filters: FiltersDict = None, **kwargs: Any ) -> Result: jinja_filters = jinja_filters or {} or task.nornir.config.jinja2.filters text = jinja_helper.render_from_string( template=template, host=task.host, jinja_filters=jinja_filters, **kwargs ) return Result(host=task.host, result=text)
129,134
Loads a yaml file. Arguments: file: path to the file containing the yaml file to load Examples: Simple example with ``ordered_dict``:: > nr.run(task=load_yaml, file="mydata.yaml") Returns: Result object with the following attributes set: * result (``dict``): dictionary with the contents of the file
def load_yaml(task: Task, file: str) -> Result: with open(file, "r") as f: yml = ruamel.yaml.YAML(typ="safe") data = yml.load(f) return Result(host=task.host, result=data)
129,138
Tests connection to a tcp port and tries to establish a three way handshake. To be used for network discovery or testing. Arguments: ports (list of int): tcp ports to ping timeout (int, optional): defaults to 2 host (string, optional): defaults to ``hostname`` Returns: Result object with the following attributes set: * result (``dict``): Contains port numbers as keys with True/False as values
def tcp_ping( task: Task, ports: List[int], timeout: int = 2, host: Optional[str] = None ) -> Result: if isinstance(ports, int): ports = [ports] if isinstance(ports, list): if not all(isinstance(port, int) for port in ports): raise ValueError("Invalid value for 'ports'") else: raise ValueError("Invalid value for 'ports'") host = host or task.host.hostname result = {} for port in ports: s = socket.socket() s.settimeout(timeout) try: status = s.connect_ex((host, port)) if status == 0: connection = True else: connection = False except (socket.gaierror, socket.timeout, socket.error): connection = False finally: s.close() result[port] = connection return Result(host=task.host, result=result)
129,139
Executes a command remotely on the host Arguments: command (``str``): command to execute Returns: Result object with the following attributes set: * result (``str``): stderr or stdout * stdout (``str``): stdout * stderr (``str``): stderr Raises: :obj:`nornir.core.exceptions.CommandError`: when there is a command error
def remote_command(task: Task, command: str) -> Result: client = task.host.get_connection("paramiko", task.nornir.config) connection_state = task.host.get_connection_state("paramiko") chan = client.get_transport().open_session() if connection_state["ssh_forward_agent"]: AgentRequestHandler(chan) chan.exec_command(command) with chan.makefile() as f: stdout = f.read().decode() with chan.makefile_stderr() as f: stderr = f.read().decode() exit_status_code = chan.recv_exit_status() if exit_status_code: raise CommandError(command, exit_status_code, stdout, stderr) result = stderr if stderr else stdout return Result(result=result, host=task.host, stderr=stderr, stdout=stdout)
129,142
Registers a connection plugin with a specified name Args: name: name of the connection plugin to register plugin: defined connection plugin class Raises: :obj:`nornir.core.exceptions.ConnectionPluginAlreadyRegistered` if another plugin with the specified name was already registered
def register(cls, name: str, plugin: Type[ConnectionPlugin]) -> None: existing_plugin = cls.available.get(name) if existing_plugin is None: cls.available[name] = plugin elif existing_plugin != plugin: raise ConnectionPluginAlreadyRegistered( f"Connection plugin {plugin.__name__} can't be registered as " f"{name!r} because plugin {existing_plugin.__name__} " f"was already registered under this name" )
129,153
Deregisters a registered connection plugin by its name Args: name: name of the connection plugin to deregister Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered`
def deregister(cls, name: str) -> None: if name not in cls.available: raise ConnectionPluginNotRegistered( f"Connection {name!r} is not registered" ) cls.available.pop(name)
129,154
Fetches the connection plugin by name if already registered Args: name: name of the connection plugin Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered`
def get_plugin(cls, name: str) -> Type[ConnectionPlugin]: if name not in cls.available: raise ConnectionPluginNotRegistered( f"Connection {name!r} is not registered" ) return cls.available[name]
129,155
Write contents to a file (locally) Arguments: dry_run: Whether to apply changes or not filename: file you want to write into content: content you want to write append: whether you want to replace the contents or append to it Returns: Result object with the following attributes set: * changed (``bool``): * diff (``str``): unified diff
def write_file( task: Task, filename: str, content: str, append: bool = False, dry_run: Optional[bool] = None, ) -> Result: diff = _generate_diff(filename, content, append) if not task.is_dry_run(dry_run): mode = "a+" if append else "w+" with open(filename, mode=mode) as f: f.write(content) return Result(host=task.host, diff=diff, changed=bool(diff))
129,162
Iterates over values of a given column. Args: column_name: A nome of the column to retrieve the values for. Yields: Values of the specified column. Raises: KeyError: If given column is not present in the table.
def Column(self, column_name): column_idx = None for idx, column in enumerate(self.header.columns): if column.name == column_name: column_idx = idx break if column_idx is None: raise KeyError("Column '{}' not found".format(column_name)) for row in self.rows: yield row.values[column_idx]
129,723
Constructor. Args: queues: The queues we use to fetch new messages from. threadpool_prefix: A name for the thread pool used by this worker. threadpool_size: The number of workers to start in this thread pool. token: The token to use for the worker. Raises: RuntimeError: If the token is not provided.
def __init__(self, queues=queues_config.WORKER_LIST, threadpool_prefix="grr_threadpool", threadpool_size=None, token=None): logging.info("started worker with queues: %s", str(queues)) self.queues = queues # self.queued_flows is a timed cache of locked flows. If this worker # encounters a lock failure on a flow, it will not attempt to grab this flow # until the timeout. self.queued_flows = utils.TimeBasedCache(max_size=10, max_age=60) if token is None: raise RuntimeError("A valid ACLToken is required.") if threadpool_size is None: threadpool_size = config.CONFIG["Threadpool.size"] self.thread_pool = threadpool.ThreadPool.Factory( threadpool_prefix, min_threads=2, max_threads=threadpool_size) self.thread_pool.Start() self.token = token self.last_active = 0 self.last_mh_lease_attempt = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(0) # Well known flows are just instantiated. self.well_known_flows = flow.WellKnownFlow.GetAllWellKnownFlows(token=token)
129,732
Wait until the operation is done. Args: timeout: timeout in seconds. None means default timeout (1 hour). 0 means no timeout (wait forever). Returns: Operation object with refreshed target_file. Raises: PollTimeoutError: if timeout is reached.
def WaitUntilDone(self, timeout=None): utils.Poll( generator=self.GetState, condition=lambda s: s != self.__class__.STATE_RUNNING, timeout=timeout) self.target_file = self.target_file.Get() return self
129,744
Returns stat information of a specific path. Args: path: A unicode string containing the path. ext_attrs: Whether the call should also collect extended attributes. Returns: a StatResponse proto Raises: IOError when call to os.stat() fails
def _Stat(self, path, ext_attrs=False): # Note that the encoding of local path is system specific local_path = client_utils.CanonicalPathToLocalPath(path) result = client_utils.StatEntryFromPath( local_path, self.pathspec, ext_attrs=ext_attrs) # Is this a symlink? If so we need to note the real location of the file. try: result.symlink = utils.SmartUnicode(os.readlink(local_path)) except (OSError, AttributeError): pass return result
129,815
Call os.statvfs for a given list of rdf_paths. OS X and Linux only. Note that a statvfs call for a network filesystem (e.g. NFS) that is unavailable, e.g. due to no network, will result in the call blocking. Args: path: a Unicode string containing the path or None. If path is None the value in self.path is used. Returns: posix.statvfs_result object Raises: RuntimeError: if called on windows
def StatFS(self, path=None): if platform.system() == "Windows": raise RuntimeError("os.statvfs not available on Windows") local_path = client_utils.CanonicalPathToLocalPath(path or self.path) return os.statvfs(local_path)
129,817
Walk back from the path to find the mount point. Args: path: a Unicode string containing the path or None. If path is None the value in self.path is used. Returns: path string of the mount point
def GetMountPoint(self, path=None): path = os.path.abspath( client_utils.CanonicalPathToLocalPath(path or self.path)) while not os.path.ismount(path): path = os.path.dirname(path) return path
129,818
Run all the actions specified in the rule. Args: rule: Rule which actions are to be executed. client_id: Id of a client where rule's actions are to be executed. Returns: Number of actions started.
def _RunAction(self, rule, client_id): actions_count = 0 try: if self._CheckIfHuntTaskWasAssigned(client_id, rule.hunt_id): logging.info( "Foreman: ignoring hunt %s on client %s: was started " "here before", client_id, rule.hunt_id) else: logging.info("Foreman: Starting hunt %s on client %s.", rule.hunt_id, client_id) # hunt_name is only used for legacy hunts. if rule.hunt_name: flow_cls = registry.AFF4FlowRegistry.FlowClassByName(rule.hunt_name) hunt_urn = rdfvalue.RDFURN("aff4:/hunts/%s" % rule.hunt_id) flow_cls.StartClients(hunt_urn, [client_id]) else: hunt.StartHuntFlowOnClient(client_id, rule.hunt_id) actions_count += 1 # There could be all kinds of errors we don't know about when starting the # hunt so we catch everything here. except Exception as e: # pylint: disable=broad-except logging.exception("Failure running foreman action on client %s: %s", rule.hunt_id, e) return actions_count
129,845
Examines our rules and starts up flows based on the client. Args: client_id: Client id of the client for tasks to be assigned. Returns: Number of assigned tasks.
def AssignTasksToClient(self, client_id): rules = data_store.REL_DB.ReadAllForemanRules() if not rules: return 0 last_foreman_run = self._GetLastForemanRunTime(client_id) latest_rule_creation_time = max(rule.creation_time for rule in rules) if latest_rule_creation_time <= last_foreman_run: return 0 # Update the latest checked rule on the client. self._SetLastForemanRunTime(client_id, latest_rule_creation_time) relevant_rules = [] expired_rules = False now = rdfvalue.RDFDatetime.Now() for rule in rules: if rule.expiration_time < now: expired_rules = True continue if rule.creation_time <= last_foreman_run: continue relevant_rules.append(rule) actions_count = 0 if relevant_rules: client_data = data_store.REL_DB.ReadClientFullInfo(client_id) if client_data is None: return for rule in relevant_rules: if rule.Evaluate(client_data): actions_count += self._RunAction(rule, client_id) if expired_rules: data_store.REL_DB.RemoveExpiredForemanRules() return actions_count
129,848
Fetches metadata for the given binary from the datastore. Args: binary_type: ApiGrrBinary.Type of the binary. relative_path: Relative path of the binary, relative to the canonical URN roots for signed binaries (see _GetSignedBlobsRoots()). Returns: An ApiGrrBinary RDFProtoStruct containing metadata for the binary.
def _GetSignedBinaryMetadata(binary_type, relative_path): root_urn = _GetSignedBlobsRoots()[binary_type] binary_urn = root_urn.Add(relative_path) blob_iterator, timestamp = signed_binary_utils.FetchBlobsForSignedBinary( binary_urn) binary_size = 0 has_valid_signature = True for blob in blob_iterator: binary_size += len(blob.data) if not has_valid_signature: # No need to check the signature if a previous blob had an invalid # signature. continue try: blob.Verify(config.CONFIG["Client.executable_signing_public_key"]) except rdf_crypto.Error: has_valid_signature = False return ApiGrrBinary( path=relative_path, type=binary_type, size=binary_size, timestamp=timestamp, has_valid_signature=has_valid_signature)
129,851
Returns a unicode object. This function will always return a unicode object. It should be used to guarantee that something is always a unicode object. Args: string: The string to convert. Returns: a unicode object.
def SmartUnicode(string): if isinstance(string, Text): return string if isinstance(string, bytes): return string.decode("utf-8", "ignore") # TODO: We need to call `__native__` because otherwise one of the # Selenium tests becomes flaky. This should be investigated. if compatibility.PY2: return str(string).__native__() else: return str(string)
129,862
A sane version of os.path.join. The intention here is to append the stem to the path. The standard module removes the path if the stem begins with a /. Args: stem: The stem to join to. *parts: parts of the path to join. The first arg is always the root and directory traversal is not allowed. Returns: a normalized path.
def JoinPath(stem="", *parts): # Ensure all path components are unicode parts = [SmartUnicode(path) for path in parts] result = (stem + NormalizePath(u"/".join(parts))).replace("//", "/") result = result.rstrip("/") return result or "/"
129,866