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 except...
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:...
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)...
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 ...
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): ...
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 s...
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.executio...
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 thro...
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: ...
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(...
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 oc...
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 != se...
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 f...
def __getIp6Address(self, addressType): addrType = ['link local', 'global', 'rloc', 'mesh EID'] addrs = [] globalAddr = [] linkLocal64Addr = '' rlocAddr = '' meshEIDAddr = '' addrs = self.__sendCommand('ipaddr') for ip6Addr in addrs: ...
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 ROU...
def __setRouterUpgradeThreshold(self, iThreshold): print 'call __setRouterUpgradeThreshold' try: cmd = 'routerupgradethreshold %s' % str(iThreshold) print cmd return self.__sendCommand(cmd) == 'Done' except Exception, e: ModuleHelper.Write...
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.Wri...
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.__sendCo...
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,...
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']...
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.slee...
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 re...
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] == ...
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: ...
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 repl...
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 - ...
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 Excepti...
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) ...
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.setPol...
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'...
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 globalAdd...
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: ModuleHel...
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) #...
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": m...
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(xPa...
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 ...
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 ...
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() ...
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':...
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 ...
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 != se...
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 addr...
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') ...
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 ...
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: ' ...
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 ...
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: pri...
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 begin...
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 =...
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: ...
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': ...
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 Harne...
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 = ...
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 ...
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 ...
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' 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_CM...
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' exc...
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': ...
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) + iIncrementV...
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)...
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.__pa...
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) ...
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 ...
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():...
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 = st...
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: ...
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, resul...
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: Whet...
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 = fil...
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: ...
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 ) retur...
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 ...
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 ) ...
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 ...
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, hos...
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 t...
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.sen...
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: ...
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 hig...
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...
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():...
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 ...
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_fi...
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 o...
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...
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: ...
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: Res...
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'") ...
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:...
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"]: AgentRequestHandle...
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 speci...
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"Con...
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 att...
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) a...
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: yiel...
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 to...
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 ...
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...
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 v...
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("F...
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_...
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 metad...
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_iterato...
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: retur...
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. ...
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