def postDataDyn(self,receivedData,dynPath,subResource,username): netname = FormatUtils.unquote(dynPath) dld = DustLinkData.DustLinkData() if subResource==['testschedule']: assert isinstance(receivedData,dict) assert receivedData.keys()==['fieldName','fieldValue'] if receivedData['fieldName']=='period (min)': assert type(receivedData['fieldValue'])==int period_seconds = 60*int(receivedData['fieldValue']) dld.setTestPeriod(netname,period_seconds,username=username) elif receivedData['fieldName']==' ': # dummy read to make sure user has GET privileges on testResults dld.getTestPeriod(netname,username=username) # trigger a snapshot secondsToNextRaw = dispatcher.send( signal = 'snapShotNow_{0}'.format(netname), data = None, ) else: raise web.notfound() elif subResource==['testreset']: assert isinstance(receivedData,dict) assert receivedData.keys()==['command'] assert isinstance(receivedData['command'],str) if receivedData['command']=='reset': # log log.info("deleting testResults for network {0}".format(netname)) # erase all test results dld.delete(['testResults',netname,'results'],username=username) # as user (to verify privileges) dld.put( ['testResults',netname,'results'],None) # as ADMIN # reset 'numOperationalEvents' counter of all motes in the network motes = dld.getNetworkMotes(netname) for mote in motes: try: dld.delete(['motes',mote,'info','numOperationalEvents']) except DataVaultException.NotFound: # happens when mote has not 'numOperationalEvents' counter pass else: raise web.notfound()
def postDataDyn(self,receivedData,dynPath,subResource,username): mac = DustLinkData.DustLinkData.stringToMac(dynPath) dld = DustLinkData.DustLinkData() if subResource==['attach']: assert isinstance(receivedData,dict) assert receivedData.keys()==['appname'] assert isinstance(receivedData['appname'],str) dld.attachAppToMote( mac, receivedData['appname'], username=username, ) elif subResource==['detach']: assert isinstance(receivedData,dict) assert receivedData.keys()==['appname'] assert isinstance(receivedData['appname'],str) dld.detachAppFromMote( mac, receivedData['appname'], username=username, ) else: raise web.notfound()
def getDataDyn(self,dynPath,subResource,username): appname = dynPath dld = DustLinkData.DustLinkData() if subResource==['appfields']: with dld.dataLock: return { 'description': dld.getAppDescription(appname,username=username), 'transport': self._transportDbToWeb( dld.getAppTransport( appname, username=username, ) ), 'fromMote': self._fieldsDbToWeb( dld.getAppFields( appname, DustLinkData.DustLinkData.APP_DIRECTION_FROMMOTE, username=username, ) ), 'toMote': self._fieldsDbToWeb( dld.getAppFields( appname, DustLinkData.DustLinkData.APP_DIRECTION_TOMOTE, username=username, ) ), } else: raise web.notfound()
def getData(self,subResource,username): dld = DustLinkData.DustLinkData() if subResource==['padding']: return {'rawHtml':'<div style="position:relative;height:200px;"></div>'} # enable the following code to be able to add/delete network by hand. ''' elif subResource==['add']: return [ { 'name': 'netname', 'value': '', 'type': 'text', }, ] elif subResource==['delete']: netnames = dld.getNetnames(username=username) return [ { 'name': 'netname', 'value': None, 'optionDisplay': netnames, 'optionValue': netnames, 'type': 'select', 'editable': True, }, ] ''' else: raise web.notfound()
def getData(self,subResource,username): dld = DustLinkData.DustLinkData() if subResource==['add']: return [ { 'name': 'newUser', 'value': '', 'type': 'text', }, ] elif subResource==['delete']: usernames = dld.getUserNames(username=username) return [ { 'name': 'username', 'value': None, 'optionDisplay': usernames, 'optionValue': usernames, 'type': 'select', 'editable': True, }, ] else: raise web.notfound()
def getDataDyn(self,dynPath,subResource,username): netname = dynPath dld = DustLinkData.DustLinkData() if subResource==['dataflows']: dataFlows = dld.getNetworkDataFlows(netname,username=username) # columnNames columnNames = ['mac','ip','direction'] # data data = [ [ mac,ip,direction ] for (mac,ip,direction) in dataFlows ] return VizTable.VizTable.formatReturnVal(columnNames,data) else: raise web.notfound()
def postData(self,receivedData,subResource,username): dld = DustLinkData.DustLinkData() # enable the following code to be able to add/delete network by hand. ''' if subResource==['add']: assert isinstance(receivedData,dict) assert receivedData.keys()==['mac'] assert isinstance(receivedData['mac'],str) mac = DustLinkData.DustLinkData.stringToMac(receivedData['mac'], username=username) dld.addMote(mac,username=username) elif subResource==['delete']: assert isinstance(receivedData,dict) assert receivedData.keys()==['mac'] assert isinstance(receivedData['mac'],str) mac = DustLinkData.DustLinkData.stringToMac(receivedData['mac']) dld.deleteMote(mac, username=username) ''' if subResource==['cleanup']: assert isinstance(receivedData,dict) assert receivedData.keys()==['command'] assert isinstance(receivedData['command'],str) # make sure this user had delete privileges on motes dld.authorize(username,['motes'],DustLinkData.DustLinkData.ACTION_DELETE) # do everything as admin from here on command = receivedData['command'] if command=='cleanup': # get all mote MAC address macs = dld.getMoteMacs() # get all netnames netnames = dld.getNetnames() # for each network, remove all motes from 'macs' list for netname in netnames: netmacs = dld.getNetworkMotes(netname) for mac in netmacs: macs.remove(mac) # delete each mote remaining in 'macs' list for mac in macs: dld.deleteMote(mac) else: raise web.notfound()
def getData(self,subResource,username): dld = DustLinkData.DustLinkData() # enable the following code to be able to add/delete network by hand. ''' elif subResource==['add']: return [ { 'name': 'mac', 'value': '', 'type': 'text', }, ] elif subResource==['delete']: macStrings = [DustLinkData.DustLinkData.macToString(mac) \ for mac in dld.getMoteMacs(username=username)] return [ { 'name': 'mac', 'value': None, 'optionDisplay': macStrings, 'optionValue': macStrings, 'type': 'select', 'editable': True, }, ] ''' if subResource==['cleanup']: return [ { 'name': 'command', 'value': '', 'type': 'text', }, ] else: raise web.notfound()
def postDataDyn(self,receivedData,dynPath,subResource,username): appname = dynPath dld = DustLinkData.DustLinkData() if subResource==['appfields']: with dld.dataLock: # description self._postDataDynDescription( appname, receivedData['description'], username, ) # transport self._postDataDynTransport( appname, receivedData['transport'], username, ) # fromMote self._postDataDynFields( appname, DustLinkData.DustLinkData.APP_DIRECTION_FROMMOTE, receivedData['fromMote'], username, ) # toMote self._postDataDynFields( appname, DustLinkData.DustLinkData.APP_DIRECTION_TOMOTE, receivedData['toMote'], username, ) else: raise web.notfound()
def postData(self,receivedData,subResource,username): dld = DustLinkData.DustLinkData() if subResource==['add']: assert isinstance(receivedData,dict) assert receivedData.keys()==['appname'] assert isinstance(receivedData['appname'],str) dld.addApp( receivedData['appname'], username=username, ) elif subResource==['delete']: assert isinstance(receivedData,dict) assert receivedData.keys()==['appname'] assert isinstance(receivedData['appname'],str) dld.deleteApp( receivedData['appname'], username=username, ) else: raise web.notfound()
def getDataDyn(self,dynPath,subResource,username): dld = DustLinkData.DustLinkData() mac = DustLinkData.DustLinkData.stringToMac(dynPath) if subResource==['info']: moteInfo = dld.getMoteInfo(mac,username=username) if moteInfo: returnVal = [ { 'name': k, 'value': v, 'type': 'text', 'editable': False, } for (k,v) in moteInfo.items() ] else: returnVal = [] return returnVal elif subResource==['apps']: with dld.dataLock: appnames = dld.getAttachedApps(mac,username=username) appnames.sort() # columnNames columnNames = ['appnane','numreceived','link'] # data data = [ [ appname, dld.getNumDataPoints(mac,appname,username=username), '<a href="/motedata?mac={0}&app={1}">INTERACT</a>'.format( DustLinkData.DustLinkData.macToString(mac), appname ), ] for appname in appnames ] return VizTable.VizTable.formatReturnVal(columnNames,data) elif subResource==['attach']: with dld.dataLock: appsToAttach = dld.getAppNames(username=username) for app in dld.getAttachedApps(mac,username=username): appsToAttach.remove(app) return [ { 'name': 'appname', 'value': None, 'optionDisplay': appsToAttach, 'optionValue': appsToAttach, 'type': 'select', 'editable': True, }, ] elif subResource==['detach']: appsToDetach = dld.getAttachedApps(mac,username=username) return [ { 'name': 'appname', 'value': None, 'optionDisplay': appsToDetach, 'optionValue': appsToDetach, 'type': 'select', 'editable': True, }, ] else: raise web.notfound()
def getDataDyn(self, dynPath, subResource, username): netname = dynPath dld = DustLinkData.DustLinkData() if subResource == ['defaultrule']: return [ { 'name': 'Default Rule', 'value': dld.getDefaultFirewallRule(netname, username=username), 'optionDisplay': [ c.split()[-1] for c in DustLinkData.DustLinkData.FIREWALL_RULE_ALL ], 'optionValue': DustLinkData.DustLinkData.FIREWALL_RULE_ALL, 'type': 'select', 'editable': True, }, ] elif subResource == ['rules']: rules = dld.getFirewallRules(netname, username=username) # columnNames columnNames = [ 'mote', 'host', 'direction', 'transport', 'resource', 'rule' ] # data if rules: data = [[ DustLinkData.DustLinkData.macToString(k[0]), DustLinkData.DustLinkData.ipToString(k[1]), k[2], k[3], k[4], v, ] for (k, v) in rules.items()] else: data = [] return VizTable.VizTable.formatReturnVal(columnNames, data) elif subResource == ['add']: macsInNetwork = [DustLinkData.DustLinkData.macToString(mac) \ for mac in dld.getNetworkMotes(netname,username=username)] return [ { 'name': 'moteMAC', 'value': None, 'optionDisplay': macsInNetwork, 'optionValue': macsInNetwork, 'type': 'select', 'editable': True, }, { 'name': 'hostIP', 'value': '', 'type': 'text', }, { 'name': 'direction', 'value': None, 'optionDisplay': DustLinkData.DustLinkData.DATA_DIRECTION_ALL, 'optionValue': DustLinkData.DustLinkData.DATA_DIRECTION_ALL, 'type': 'select', 'editable': True, }, { 'name': 'dataType', 'value': None, 'optionDisplay': DustLinkData.DustLinkData.APP_TRANSPORT_ALL, 'optionValue': DustLinkData.DustLinkData.APP_TRANSPORT_ALL, 'type': 'select', 'editable': True, }, { 'name': 'resource', 'value': '', 'type': 'text', }, { 'name': 'rule', 'value': None, 'optionDisplay': DustLinkData.DustLinkData.FIREWALL_RULE_ALL, 'optionValue': DustLinkData.DustLinkData.FIREWALL_RULE_ALL, 'type': 'select', 'editable': True, }, ] elif subResource == ['delete']: rules = dld.getFirewallRules(netname, username=username) ruleStrings = [] if rules: for (k, v) in rules.items(): thisRule = [] thisRule += [ DustLinkData.DustLinkData.macToString(k[0]) ] thisRule += [ DustLinkData.DustLinkData.ipToString(k[1]) ] thisRule += [str(k[2])] thisRule += [str(k[3])] thisRule += [str(k[4])] ruleStrings.append(' '.join(thisRule)) return [ { 'name': 'rule', 'value': None, 'optionDisplay': ruleStrings, 'optionValue': ruleStrings, 'type': 'select', 'editable': True, }, ] else: raise web.notfound()
def postDataDyn(self,receivedData,dynPath,subResource,username): netname = dynPath dld = DustLinkData.DustLinkData() if subResource==['defaultrule']: dld.setDefaultFirewallRule( netname, receivedData['fieldValue'], username=username, ) elif subResource==['add']: assert isinstance(receivedData,dict) keys = receivedData.keys() keys.sort() assert keys==['dataType','direction','hostIP','moteMAC','resource','rule'] receivedData['moteMAC'] = DustLinkData.DustLinkData.stringToMac(receivedData['moteMAC']) receivedData['hostIP'] = DustLinkData.DustLinkData.stringToIp(receivedData['hostIP']) dld.addFirewallRule( netname=netname, username=username, **receivedData ) elif subResource==['delete']: assert isinstance(receivedData,dict) assert receivedData.keys()==['rule'] ruleItems = receivedData['rule'].split() assert len(ruleItems)==5 moteMAC = DustLinkData.DustLinkData.stringToMac(ruleItems[0]) hostIP = DustLinkData.DustLinkData.stringToIp(ruleItems[1]) direction = ruleItems[2] assert direction in DustLinkData.DustLinkData.DATA_DIRECTION_ALL dataType = ruleItems[3] assert dataType in DustLinkData.DustLinkData.DATATYPE_ALL if dataType in [DustLinkData.DustLinkData.APP_TRANSPORT_UDP, DustLinkData.DustLinkData.APP_TRANSPORT_MOTERUNNER]: resource = int(ruleItems[4]) elif dataType in [DustLinkData.DustLinkData.APP_TRANSPORT_OAP]: resource = tuple([int(b) for b in ruleItems[4].split('.')]) elif dataType in [DustLinkData.DustLinkData.APP_TRANSPORT_COAP]: resource = tuple([str(b) for b in ruleItems[4].split('.')]) else: raise SystemError('unexpected dataType={0}'.format(dataType)) output = [] output += ['moteMAC={0}'.format(moteMAC)] output += ['hostIP={0}'.format(hostIP)] output += ['direction={0}'.format(direction)] output += ['dataType={0}'.format(dataType)] output += ['resource={0}'.format(resource)] print '\n'.join(output) dld.deleteFirewallRule( netname = netname, moteMAC = moteMAC, hostIP = hostIP, direction = direction, dataType = dataType, resource = resource, username = username, ) else: raise web.notfound()
def getDataDyn(self,dynPath,subResource,username): netname = dynPath dld = DustLinkData.DustLinkData() if subResource==['defaultrule']: return [ { 'name': 'Default Rule', 'value': dld.getDefaultFirewallRule( netname, username=username ), 'optionDisplay': [c.split()[-1] for c in DustLinkData.DustLinkData.FIREWALL_RULE_ALL], 'optionValue': DustLinkData.DustLinkData.FIREWALL_RULE_ALL, 'type': 'select', 'editable': True, }, ] elif subResource==['rules']: rules = dld.getFirewallRules(netname,username=username) # columnNames columnNames = ['mote','host','direction','transport','resource','rule'] # data if rules: data = [ [ DustLinkData.DustLinkData.macToString(k[0]), DustLinkData.DustLinkData.ipToString(k[1]), k[2], k[3], k[4], v, ] for (k,v) in rules.items() ] else: data = [] return VizTable.VizTable.formatReturnVal(columnNames,data) elif subResource==['add']: macsInNetwork = [DustLinkData.DustLinkData.macToString(mac) \ for mac in dld.getNetworkMotes(netname,username=username)] return [ { 'name': 'moteMAC', 'value': None, 'optionDisplay': macsInNetwork, 'optionValue': macsInNetwork, 'type': 'select', 'editable': True, }, { 'name': 'hostIP', 'value': '', 'type': 'text', }, { 'name': 'direction', 'value': None, 'optionDisplay': DustLinkData.DustLinkData.DATA_DIRECTION_ALL, 'optionValue': DustLinkData.DustLinkData.DATA_DIRECTION_ALL, 'type': 'select', 'editable': True, }, { 'name': 'dataType', 'value': None, 'optionDisplay': DustLinkData.DustLinkData.APP_TRANSPORT_ALL, 'optionValue': DustLinkData.DustLinkData.APP_TRANSPORT_ALL, 'type': 'select', 'editable': True, }, { 'name': 'resource', 'value': '', 'type': 'text', }, { 'name': 'rule', 'value': None, 'optionDisplay': DustLinkData.DustLinkData.FIREWALL_RULE_ALL, 'optionValue': DustLinkData.DustLinkData.FIREWALL_RULE_ALL, 'type': 'select', 'editable': True, }, ] elif subResource==['delete']: rules = dld.getFirewallRules(netname,username=username) ruleStrings = [] if rules: for (k,v) in rules.items(): thisRule = [] thisRule += [DustLinkData.DustLinkData.macToString(k[0])] thisRule += [DustLinkData.DustLinkData.ipToString(k[1])] thisRule += [str(k[2])] thisRule += [str(k[3])] thisRule += [str(k[4])] ruleStrings.append(' '.join(thisRule)) return [ { 'name': 'rule', 'value': None, 'optionDisplay': ruleStrings, 'optionValue': ruleStrings, 'type': 'select', 'editable': True, }, ] else: raise web.notfound()
def postDataDyn(self, receivedData, dynPath, subResource, username): netname = dynPath dld = DustLinkData.DustLinkData() if subResource == ['defaultrule']: dld.setDefaultFirewallRule( netname, receivedData['fieldValue'], username=username, ) elif subResource == ['add']: assert isinstance(receivedData, dict) keys = receivedData.keys() keys.sort() assert keys == [ 'dataType', 'direction', 'hostIP', 'moteMAC', 'resource', 'rule' ] receivedData[ 'moteMAC'] = DustLinkData.DustLinkData.stringToMac( receivedData['moteMAC']) receivedData['hostIP'] = DustLinkData.DustLinkData.stringToIp( receivedData['hostIP']) dld.addFirewallRule(netname=netname, username=username, **receivedData) elif subResource == ['delete']: assert isinstance(receivedData, dict) assert receivedData.keys() == ['rule'] ruleItems = receivedData['rule'].split() assert len(ruleItems) == 5 moteMAC = DustLinkData.DustLinkData.stringToMac(ruleItems[0]) hostIP = DustLinkData.DustLinkData.stringToIp(ruleItems[1]) direction = ruleItems[2] assert direction in DustLinkData.DustLinkData.DATA_DIRECTION_ALL dataType = ruleItems[3] assert dataType in DustLinkData.DustLinkData.DATATYPE_ALL if dataType in [ DustLinkData.DustLinkData.APP_TRANSPORT_UDP, DustLinkData.DustLinkData.APP_TRANSPORT_MOTERUNNER ]: resource = int(ruleItems[4]) elif dataType in [DustLinkData.DustLinkData.APP_TRANSPORT_OAP]: resource = tuple([int(b) for b in ruleItems[4].split('.')]) elif dataType in [ DustLinkData.DustLinkData.APP_TRANSPORT_COAP ]: resource = tuple([str(b) for b in ruleItems[4].split('.')]) else: raise SystemError( 'unexpected dataType={0}'.format(dataType)) output = [] output += ['moteMAC={0}'.format(moteMAC)] output += ['hostIP={0}'.format(hostIP)] output += ['direction={0}'.format(direction)] output += ['dataType={0}'.format(dataType)] output += ['resource={0}'.format(resource)] print '\n'.join(output) dld.deleteFirewallRule( netname=netname, moteMAC=moteMAC, hostIP=hostIP, direction=direction, dataType=dataType, resource=resource, username=username, ) else: raise web.notfound()
def postDataDyn(self,receivedData,dynPath,subResource,username): netname = FormatUtils.unquote(dynPath) raise web.notfound()
def getDataDyn(self,dynPath,subResource,username): netname = FormatUtils.unquote(dynPath) dld = DustLinkData.DustLinkData() if subResource==['info']: netInfo = dld.getNetworkInfo(netname,username=username) if netInfo: return [ { 'name': k, 'value': v, 'type': 'text', 'editable': False, } for (k,v) in netInfo.items() ] else: return [] elif subResource==['topology']: return ( NetworksPages.topologyToDot(netname,username), WebHandler.WebHandler.ALREADY_JSONIFIED, ) elif subResource==['motes']: # data data = [] for mac in dld.getNetworkMotes(netname,username=username): data.append([DustLinkData.DustLinkData.macToString(mac)]) # columnNames columnNames = ['mac'] return VizTable.VizTable.formatReturnVal(columnNames,data) elif subResource==['paths']: with dld.dataLock: pathsToReturn = dld.getNetworkPaths(netname,username=username) # columnNames columnNames = ['from','to','direction','numLinks','quality'] # data if pathsToReturn: data = [] for p in pathsToReturn: pathInfo = dld.getPathInfo(netname,p[0],p[1],username=username) if ( pathInfo and ('direction' in pathInfo) and (pathInfo['direction'] in [2,3]) and ('numLinks' in pathInfo) and ('quality' in pathInfo) ): data += [ [ DustLinkData.DustLinkData.macToString(p[0]), DustLinkData.DustLinkData.macToString(p[1]), IpMgrDefinition.IpMgrDefinition.fieldOptionToShortDesc( 'pathDirection', pathInfo['direction'] ), pathInfo['numLinks'], pathInfo['quality'], ] ] else: data = [] return VizTable.VizTable.formatReturnVal(columnNames,data) else: raise web.notfound()
def postData(self,receivedData,subResource,username): dld = DustLinkData.DustLinkData() if subResource==['send']: mac = DustLinkData.DustLinkData.stringToMac(str(web.input().mac.rstrip('/'))) appName = str(web.input().app.rstrip('/')) assert isinstance(receivedData,dict) assert len(receivedData.keys())==3 assert 'app' in receivedData.keys() del receivedData['app'] assert 'mac' in receivedData.keys() del receivedData['mac'] formData = json.loads(receivedData.keys()[0]) formData = DustWeb.simplifyWebInputFormat(formData) receivedKeys = formData.keys() receivedKeys.sort() fieldNames = dld.getAppFields( appName, DustLinkData.DustLinkData.APP_DIRECTION_TOMOTE, username=username, )['fieldNames'] fieldNames.sort() assert receivedKeys == fieldNames fields = {} for fieldName in fieldNames: fields[fieldName] = formData[fieldName] dispatcher.send( signal = 'fieldsToMesh_{0}'.format(appName), data = { 'mac': mac, 'fields': fields, } ) elif subResource==['clear']: mac = DustLinkData.DustLinkData.stringToMac(str(web.input().mac.rstrip('/'))) appname = str(web.input().app.rstrip('/')) assert isinstance(receivedData,dict) assert len(receivedData.keys())==3 assert 'app' in receivedData.keys() del receivedData['app'] assert 'mac' in receivedData.keys() del receivedData['mac'] formData = json.loads(receivedData.keys()[0]) formData = DustWeb.simplifyWebInputFormat(formData) receivedKeys = formData.keys() assert receivedKeys == ['command'] if formData['command']=='clear': dld.deleteData( mac = mac, appname = appname, username = username, ) else: raise web.notfound()
def getDataDyn(self,dynPath,subResource,username): usernameToExamine = dynPath dld = DustLinkData.DustLinkData() if subResource==['authentication']: with dld.dataLock: ssl = dld.getUserSsl( usernameToAuthenticate=usernameToExamine, username=username ) if not ssl: ssl = '' return [ { 'name': 'Authentication', 'value': dld.getUserAuthlevel( usernameToExamine=usernameToExamine, username=username ), 'optionDisplay': [c.split()[-1] for c in DustLinkData.DustLinkData.AUTHLEVEL_ALL], 'optionValue': [c for c in DustLinkData.DustLinkData.AUTHLEVEL_ALL], 'type': 'select', 'editable': True, }, { 'name': 'ssl', 'value': ssl, 'type': 'text', 'editable': True, }, ] elif subResource==['privileges']: userPrivileges = dld.getUserPrivileges( usernameToExamine=usernameToExamine, username=username ) # columnNames columnNames = ['resource','get','put','delete'] # fill in data if userPrivileges: data = self._formatPrivileges(userPrivileges) else: data = [] return VizTable.VizTable.formatReturnVal(columnNames,data, [.4,0,0,0]) elif subResource==['password']: return [ { 'name': 'old password', 'value': '', 'type': 'password', 'editable': True, }, { 'name': 'new password', 'value': '', 'type': 'password', 'editable': True, }, ] elif subResource==['grant']: # generate all possible resources resources = self._formatAllResources(username) return [ { 'name': 'resource', 'value': None, 'optionDisplay': resources, 'optionValue': resources, 'type': 'select', 'editable': True, }, { 'name': 'action', 'value': None, 'optionDisplay': DustLinkData.DustLinkData.ACTION_ALL, 'optionValue': DustLinkData.DustLinkData.ACTION_ALL, 'type': 'select', 'editable': True, }, ] elif subResource==['deny']: # generate all possible resources resources = self._formatAllResources(username) return [ { 'name': 'resource', 'value': None, 'optionDisplay': resources, 'optionValue': resources, 'type': 'select', 'editable': True, }, { 'name': 'action', 'value': None, 'optionDisplay': DustLinkData.DustLinkData.ACTION_ALL, 'optionValue': DustLinkData.DustLinkData.ACTION_ALL, 'type': 'select', 'editable': True, }, ] else: raise web.notfound()
def postDataDyn(self,receivedData,dynPath,subResource,username): dld = DustLinkData.DustLinkData() usernameToExamine = dynPath if subResource==['authentication']: # filter errors fields = receivedData.keys() fields.sort() if fields!=['fieldName','fieldValue']: raise web.HTTPError('400 bad request',{},'wrong fieldnames') if receivedData['fieldName'] in ['Authentication']: newAuthLevel = receivedData['fieldValue'] if newAuthLevel not in DustLinkData.DustLinkData.AUTHLEVEL_ALL: raise web.HTTPError('400 bad request',{},'invalid authLevel {0}'.format(newAuthLevel)) try: dld.setUserAuthlevel( usernameToExamine=usernameToExamine, newAuthLevel=newAuthLevel, username=username) except ValueError as err: raise web.HTTPError('400 bad request',{},str(err)) elif receivedData['fieldName'] in ['ssl']: dld.setUserSsl( usernameToAuthenticate=usernameToExamine, ssl=receivedData['fieldValue'], username=username) else: raise web.HTTPError('400 bad request',{},'unexpected fieldName {0}'.format(receivedData['fieldName'])) elif subResource==['password']: dld.setUserPassword( usernameToAuthenticate=usernameToExamine, oldPassword=receivedData['old password'], newPassword=receivedData['new password'], username=username) elif subResource==['grant']: resourceTemp = receivedData['resource'].split('.') resource = [] for r in resourceTemp: try: resource.append(DustLinkData.DustLinkData.stringToMac(r)) except ValueError: resource.append(r) action = receivedData['action'] dld.grantPrivilege( resource=resource, usernameToGrant=usernameToExamine, action=action, username=username) elif subResource==['deny']: resourceTemp = receivedData['resource'].split('.') resource = [] for r in resourceTemp: try: resource.append(DustLinkData.DustLinkData.stringToMac(r)) except ValueError: resource.append(r) action = receivedData['action'] dld.denyPrivilege( resource=resource, usernameToDeny=usernameToExamine, action=action, username=username) else: raise web.notfound()
def getDataDyn(self, dynPath, subResource, username): dld = DustLinkData.DustLinkData() mac = DustLinkData.DustLinkData.stringToMac(dynPath) if subResource == ['info']: moteInfo = dld.getMoteInfo(mac, username=username) if moteInfo: returnVal = [{ 'name': k, 'value': v, 'type': 'text', 'editable': False, } for (k, v) in moteInfo.items()] else: returnVal = [] return returnVal elif subResource == ['apps']: with dld.dataLock: appnames = dld.getAttachedApps(mac, username=username) appnames.sort() # columnNames columnNames = ['appnane', 'numreceived', 'link'] # data data = [[ appname, dld.getNumDataPoints(mac, appname, username=username), '<a href="/motedata?mac={0}&app={1}">INTERACT</a>'. format(DustLinkData.DustLinkData.macToString(mac), appname), ] for appname in appnames] return VizTable.VizTable.formatReturnVal(columnNames, data) elif subResource == ['attach']: with dld.dataLock: appsToAttach = dld.getAppNames(username=username) for app in dld.getAttachedApps(mac, username=username): appsToAttach.remove(app) return [ { 'name': 'appname', 'value': None, 'optionDisplay': appsToAttach, 'optionValue': appsToAttach, 'type': 'select', 'editable': True, }, ] elif subResource == ['detach']: appsToDetach = dld.getAttachedApps(mac, username=username) return [ { 'name': 'appname', 'value': None, 'optionDisplay': appsToDetach, 'optionValue': appsToDetach, 'type': 'select', 'editable': True, }, ] else: raise web.notfound()
def postDataDyn(self, receivedData, dynPath, subResource, username): netname = FormatUtils.unquote(dynPath) dld = DustLinkData.DustLinkData() if subResource == ['testschedule']: assert isinstance(receivedData, dict) assert receivedData.keys() == ['fieldName', 'fieldValue'] if receivedData['fieldName'] == 'period (min)': assert type(receivedData['fieldValue']) == int period_seconds = 60 * int(receivedData['fieldValue']) dld.setTestPeriod(netname, period_seconds, username=username) elif receivedData['fieldName'] == ' ': # dummy read to make sure user has GET privileges on testResults dld.getTestPeriod(netname, username=username) # trigger a snapshot secondsToNextRaw = dispatcher.send( signal='snapShotNow_{0}'.format(netname), data=None, ) else: raise web.notfound() elif subResource == ['testreset']: assert isinstance(receivedData, dict) assert receivedData.keys() == ['command'] assert isinstance(receivedData['command'], str) if receivedData['command'] == 'reset': # log log.info( "deleting testResults for network {0}".format(netname)) # erase all test results dld.delete( ['testResults', netname, 'results'], username=username) # as user (to verify privileges) dld.put(['testResults', netname, 'results'], None) # as ADMIN # reset 'numOperationalEvents' counter of all motes in the network motes = dld.getNetworkMotes(netname) for mote in motes: try: dld.delete([ 'motes', mote, 'info', 'numOperationalEvents' ]) except DataVaultException.NotFound: # happens when mote has not 'numOperationalEvents' counter pass else: raise web.notfound()
def getDataDyn(self,dynPath,subResource,username): netname = FormatUtils.unquote(dynPath) dld = DustLinkData.DustLinkData() if subResource==['testschedule']: period_min = float(dld.getTestPeriod(netname,username=username))/60.0 secondsToNextRaw = dispatcher.send( signal = 'timeToNextSnapShot_{0}'.format(netname), data = None, ) assert len(secondsToNextRaw)==1 secondsToNext = secondsToNextRaw[0][1] return [ { 'name': 'period (min)', 'value': period_min, 'type': 'text', 'editable': True, }, { 'name': 'next test in', 'value': '{0}s'.format(secondsToNext), 'type': 'text', 'editable': False, }, { 'name': ' ', 'value': 'Run tests now', 'type': 'button', }, ] elif subResource==['testresults']: testResults = dld.getResults(netname,username=username) # fill in data data = [] if testResults: for (testName,res) in testResults.items(): # outcomeIcon if res['last']['outcome']==dld.TEST_OUTCOME_PASS: outcomeIcon = 'pass.png' elif res['last']['outcome']==dld.TEST_OUTCOME_FAIL: outcomeIcon = 'fail.png' elif res['last']['outcome']==dld.TEST_OUTCOME_NOTRUN: outcomeIcon = 'notrun.png' else: SystemError("outcome {0} not expected".format(res['outcome'])) # outcomeDesc outcomeDesc = res['last']['outcome'] # weatherIcon numPass = res['history'].count(dld.TEST_OUTCOME_PASS) numFail = res['history'].count(dld.TEST_OUTCOME_FAIL) if numFail==0 and numFail==0: weatherScore = 1.0 else: weatherScore = float(numPass)/float(numPass+numFail) if weatherScore>0.8: weatherIcon = 'weather-80plus.png' elif weatherScore>0.6: weatherIcon = 'weather-60to79.png' elif weatherScore>0.4: weatherIcon = 'weather-40to59.png' elif weatherScore>0.2: weatherIcon = 'weather-20to39.png' else: weatherIcon = 'weather-00to19.png' # weatherDesc weatherDesc = [] weatherDesc += ['<ul>'] weatherDesc += ['<li>{0} tests PASS</li>'.format(numPass)] weatherDesc += ['<li>{0} tests FAIL</li>'.format(numFail)] weatherDesc += ['</ul>'] weatherDesc = '\n'.join(weatherDesc) # testName testName = testName.replace('_nettest_','',1) # testDesc testDesc = res['description'] # lastRun lastRun = DustLinkData.DustLinkData.timestampToStringShort( res['last']['timestamp'] ) # lastRunDesc lastRunDesc = res['last']['description'] # lastSuccess if res['lastSuccess']['timestamp']: lastSuccess = DustLinkData.DustLinkData.timestampToStringShort( res['lastSuccess']['timestamp'] ) else: lastSuccess = 'N/A' # lastSuccessDesc lastSuccessDesc = res['lastSuccess']['description'] # lastFailure if res['lastFailure']['timestamp']: lastFailure = DustLinkData.DustLinkData.timestampToStringShort( res['lastFailure']['timestamp'] ) else: lastFailure = 'N/A' # lastFailureDesc lastFailureDesc = res['lastFailure']['description'] data += [ { 'outcomeIcon': outcomeIcon, 'outcomeDesc': outcomeDesc, 'weatherIcon': weatherIcon, 'weatherDesc': weatherDesc, 'testName': testName, 'testDesc': testDesc, 'lastRun': lastRun, 'lastRunDesc': lastRunDesc, 'lastSuccess': lastSuccess, 'lastSuccessDesc': lastSuccessDesc, 'lastFailure': lastFailure, 'lastFailureDesc': lastFailureDesc, }, ] return data elif subResource==['testreset']: return [ { 'name': 'command', 'value': '', 'type': 'text', } ] else: raise web.notfound()
def getData(self,subResource,username): dld = DustLinkData.DustLinkData() mac = DustLinkData.DustLinkData.stringToMac(str(web.input().mac.rstrip('/'))) appName = str(web.input().app.rstrip('/')) if subResource==['description']: # retrieve the description of that application try: appDescription = dld.getAppDescription( appName, username=username, ) except ValueError: return {'rawHtml':''} # happens when no description else: return {'rawHtml':appDescription} elif subResource==['received']: # retrieve the last data received from the mac/application rawData = dld.getLastData(mac,appName,username=username) if rawData: # assume no data received fieldNames = [] timelineData = [] # get field Names fieldNames = rawData[rawData.keys()[0]].keys() # fill in data timestamps = rawData.keys() timestamps.sort() for t in timestamps: thisData = {} thisData['timestamp'] = int(t*1000) for f in fieldNames: thisData[f] = rawData[t][f] timelineData.append(thisData) return { 'metadata': { 'axis': tuple(fieldNames), }, 'datapoints': timelineData, } else: return { 'metadata': { 'axis': ['nodata'], }, 'datapoints': [ {"timestamp": 0, "nodata": 0}, ], } elif subResource==['clear']: return [ { 'name': 'command', 'value': '', 'type': 'text', } ] elif subResource==['send']: return [ { 'name': fieldname, 'value': '', 'type': 'text', } for fieldname in dld.getAppFields( appName, DustLinkData.DustLinkData.APP_DIRECTION_TOMOTE, username=username, )['fieldNames'] ] else: raise web.notfound()