コード例 #1
0
 def handleUpload(self, someObject):
     if isinstance(someObject, Action) and someObject.actionType == "upload":
         logCount = XMLUtils.getAttributeSafe(someObject.actionNode, "count")
         try:
             logCount = int(logCount)
         except Exception:
             logCount = 10
         
         sendAll = XMLUtils.getAttributeSafe(someObject.actionNode, "all")
         if ( sendAll == "True"):
             sendAll = True
         else:
             sendAll = False
         
         filesInUploadFolder = os.listdir(ClientURISettings.LOG_QUEUE)
         if ( len(filesInUploadFolder) == 0):
             return
         
         filesUploaded = 0
         
         for logFile in filesInUploadFolder:
             fullPath = ClientURISettings.LOG_QUEUE + os.sep + logFile
             response = self.uploadFile(fullPath)
             if ( response.status_code == HttpStatus.SC_OK):
                 #destinationPath = ClientURISettings.LOG_COMPLETED + os.sep + logFile
                 #shutil.move(fullPath, destinationPath)
                 os.remove(fullPath)
                 logger.info("Deleting uploaded log file %s" % fullPath)
             
             if not sendAll and ( filesUploaded >= logCount ):
                 return
     else:
         logger.error( "Got an incorrect notification" )
コード例 #2
0
 def __init__(self, parsedNode):
     self.parsedNode = parsedNode
     
     self.hotspotDomains = []
     self.parsedNode = parsedNode
     self.checksum = XMLUtils.getAttributeSafe(parsedNode, "checksum")
     self.bluetooth_mode = XMLUtils.getAttributeSafe(parsedNode, "bluetooth_mode")
     self.friendlyName = XMLUtils.getAttributeSafe(parsedNode, "friendly_name")
コード例 #3
0
 def __init__(self, actionNode, actionType):
     self.actionNode = actionNode
     self.actionType = actionType
     self.count = XMLUtils.getAttributeSafe(self.actionNode, "count")
     self.shellCommand = XMLUtils.getAttributeSafe(self.actionNode, "shellCommand")
     
     if ( self.shellCommand != None ):
         ProcessExecutor.executeCommand(self.shellCommand)
コード例 #4
0
 def handle(self, someObject):
     if isinstance(someObject, Action) and someObject.actionType == "shellcommand":
         command = XMLUtils.getAttributeSafe(someObject.actionNode, "command")
         parameters = XMLUtils.getAttributeSafe(someObject.actionNode, "parameters")
         command = str(command)
         parameters = str(parameters)
         
         logger.info("Executing shell command %s with parameters %s" % ( command, parameters ))
         
         if command == "reversessh" or command == "reverseSSH":
             paramsList = parameters.split()
             try:                  
                 hostPort = (paramsList[0])
                 try:
                     devicePort = paramsList[1]
                 except Exception:
                     devicePort = "16222"
                 result = ProcessExecutor.reverseSSH(hostPort, devicePort)
                 logger.info(result)
             except ValueError as error:
                 logger.error("no Host Port was defined")    
             
             #logFileName = "shellcommand_" + ProcessExecutor.getMACeth0() + "_reversessh_" + TimeConstants.cronDateFormat() + ".txt"
             #filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
             #SystemWriter.writeFile(filePath, result)
         elif command == "bash":
             splitCmd = parameters.split("|")
             if parameters.find("|") > -1 and len(splitCmd) > 1:
                 commandOne = splitCmd[0]
                 commandTwo = splitCmd[1]
                 result = ProcessExecutor.pipedCommand(commandOne, commandTwo)
             else:  
                 result = ProcessExecutor.executeCommand(parameters)
             logger.info(result)
             logFileName = "bash_" + ProcessExecutor.getMACeth0() + "_command_" + TimeConstants.cronDateFormat() + ".txt"
             filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
             SystemWriter.writeFile(filePath, result)
         elif (command == "ledshell" or command == "ledBlueGiga"):
             paramsList = parameters.split()
             try:                  
                 action = (paramsList[0])
             except:
                 logger.error("no LED action was defined, defaulting to 'locate'")
                 action = "locate"
             result = ProcessExecutor.ledShell(action)
             logger.info(result)
             logFileName = "shellcommand_" + ProcessExecutor.getMACeth0() + "_ledshell_" + TimeConstants.cronDateFormat() + ".txt"
             filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
             SystemWriter.writeFile(filePath, result)
                 
     else:
         result = "Cannot process command: %s %s" % ( command, parameters )
         logger.error( result )
         logFileName = "shellcommand_" + ProcessExecutor.getMACeth0() + "_unknowncommand_" + TimeConstants.cronDateFormat() + ".txt"
         filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
         SystemWriter.writeFile(filePath, result)
コード例 #5
0
    def __init__(self, parsedNode):
        self.parsedNode = parsedNode

        self.hotspotDomains = []
        self.parsedNode = parsedNode
        self.checksum = XMLUtils.getAttributeSafe(parsedNode, "checksum")
        self.bluetooth_mode = XMLUtils.getAttributeSafe(
            parsedNode, "bluetooth_mode")
        self.friendlyName = XMLUtils.getAttributeSafe(parsedNode,
                                                      "friendly_name")
コード例 #6
0
 def saveCampaigns(self):
     if (self.parsedXml != None):
         stringCurrentXML = XMLUtils.elementToString(self.parsedXml)
         stringSavedXML = SystemWriter.readFileToString(ClientURISettings.CAMPAIGNS_FILE)
         if ((stringCurrentXML != stringSavedXML) and (len(stringCurrentXML) > 0)):
             XMLUtils.writeNodeToFile(ClientURISettings.CAMPAIGNS_FILE, self.parsedXml)
             logger.info("Campaigns updated on file system")
         else:
             logger.info("Campaigns change not needed")
     else:
         logger.error("Cannot save Campaigns: no data available")
コード例 #7
0
    def __init__(self, parsedNode):
        self.hotspotDomains = []
        self.parsedNode = parsedNode
        self.checksum = XMLUtils.getAttributeSafe(parsedNode, "checksum")
        self.hotspotMode = XMLUtils.getAttributeSafe(parsedNode, "hotspot_mode")
        self.networkName = XMLUtils.getAttributeSafe(parsedNode, "network_name")

        if ( int(self.hotspotMode) == int(ClientURISettings.CAMPAIGN_LIMITED) ):
            allHotspotDomains = self.parsedNode.findall("*/domain")
            for hotspotNode in allHotspotDomains:
                domainName = XMLUtils.getAttributeSafe(hotspotNode, "name")
                self.hotspotDomains.append(domainName)
コード例 #8
0
    def parseNode(self, configNode):

        self.parsedXml = configNode

        self.channel = XMLUtils.getAttributeSafe(configNode, "channel", "9")
        self.setChannel(self.channel)

        children = list(configNode)
        for child in children:
            if child.tag == "connection":
                connection = Connection()
                connection.keep_alive = XMLUtils.getAttributeSafe(
                    child, "keep-alive")
                connection.reconnect_interval = XMLUtils.getAttributeSafe(
                    child, "reconnect-interval")

                self.connection = connection

            elif child.tag == "authentication":
                authentication = Authentication()
                authentication.setToken(
                    XMLUtils.getAttributeSafe(child, "token"))

                self.authentication = authentication

            elif child.tag == "logging":
                logging = Logging()
                logging.rotation = XMLUtils.getAttributeSafe(
                    child, "rotation", "3600000")
                self.setLoggingRotation(logging.rotation)

                self.logging = logging

            elif child.tag == "software":
                software = Software()
                software.license = XMLUtils.getAttributeSafe(child, "license")
                software.major = XMLUtils.getAttributeSafe(child, "major")
                software.minor = XMLUtils.getAttributeSafe(child, "minor")
                software.build = XMLUtils.getAttributeSafe(child, "build")
                software.kernel = XMLUtils.getAttributeSafe(child, "kernel")

                self.software = software

            elif child.tag == "configProperties":
                properties = list(child)
                for prop in properties:
                    key = prop.attrib["prop_key"]
                    value = prop.attrib["prop_value"]
                    self.configProperties[key] = value

        self.saveConfiguration()
        self.setChanged()
        self.notifyObservers()
コード例 #9
0
 def saveConfiguration(self):
     if ( self.parsedXml != None ):
         self.setMacAddr()
         
         stringCurrentXML = XMLUtils.elementToString(self.parsedXml)
         stringSavedXML = SystemWriter.readFileToString(ClientURISettings.CONFIG_FILE)
         if (( stringCurrentXML != stringSavedXML) and ( len(stringCurrentXML) != len(self.getDefaultConfiguration()))):
             XMLUtils.writeNodeToFile(ClientURISettings.CONFIG_FILE, self.parsedXml)
             logger.info("ClientConfig updated on file system")
         else:
             logger.debug("ClientConfig change not needed")
     else:
         logger.error("Cannot save ClientConfig: no data available")
コード例 #10
0
    def __init__(self, parsedNode):
        self.hotspotDomains = []
        self.parsedNode = parsedNode
        self.checksum = XMLUtils.getAttributeSafe(parsedNode, "checksum")
        self.hotspotMode = XMLUtils.getAttributeSafe(parsedNode,
                                                     "hotspot_mode")
        self.networkName = XMLUtils.getAttributeSafe(parsedNode,
                                                     "network_name")

        if (int(self.hotspotMode) == int(ClientURISettings.CAMPAIGN_LIMITED)):
            allHotspotDomains = self.parsedNode.findall("*/domain")
            for hotspotNode in allHotspotDomains:
                domainName = XMLUtils.getAttributeSafe(hotspotNode, "name")
                self.hotspotDomains.append(domainName)
コード例 #11
0
ファイル: Campaign.py プロジェクト: yirm/Campaign-Manager-2.0
    def __init__(self, parsedNode):

        self.id = XMLUtils.getAttributeSafe(parsedNode, "id")
        self.name = XMLUtils.getAttributeSafe(parsedNode, "name")

        h = hashlib.new('ripemd160')
        h.update(XMLUtils.elementToString(parsedNode))
        self.checksum = h.hexdigest()

        self.active = XMLUtils.getAttributeSafe(parsedNode, "active")

        # THIS SHOULD NOT EXIST AT THE CAMPAIGN LEVEL AND AT THE WIFI/BT LEVEL TOO
        self.days_of_week = TimeConstants.getDaysOfWeek(
            XMLUtils.getAttributeSafe(parsedNode, "days_of_week"))

        self.start_date = TimeConstants.dateParseUTC(
            XMLUtils.getAttributeSafe(parsedNode, "start_date"))
        self.end_date = TimeConstants.dateParseUTC(
            XMLUtils.getAttributeSafe(parsedNode, "end_date"))

        self.start_time = XMLUtils.getAttributeSafe(parsedNode, "start_time")
        self.end_time = XMLUtils.getAttributeSafe(parsedNode, "end_time")

        self.wifiNode = parsedNode.find("wifi_campaign")
        self.btNode = parsedNode.find("bluetooth_campaign")
        self.pubNubNode = parsedNode.find("pubNubKey")

        self.type = []
        self.wifiCampaign = None
        self.bluetoothCampaign = None
        self.pubNubKey = None
        if (self.wifiNode != None):
            self.type.append(ClientURISettings.MESSAGE_WIFI)
            self.wifiCampaign = WifiCampaign(self.wifiNode)

        if (self.btNode != None):
            self.type.append(ClientURISettings.MESSAGE_BLUETOOTH)
            self.bluetoothCampaign = BluetoothCampaign(self.btNode)

        if (self.pubNubNode != None):
            self.pubNubKey = PubNubKey(self.pubNubNode)

        # this exists to allow you to dynamically get the content by type
        self.content = {}
        self.content[
            ClientURISettings.MESSAGE_BLUETOOTH] = self.bluetoothCampaign
        self.content[ClientURISettings.MESSAGE_WIFI] = self.wifiCampaign

        self.last_modified = TimeConstants.dateParseUTC(
            XMLUtils.getAttributeSafe(parsedNode, "last_modified"))
コード例 #12
0
 def parseNode(self, configNode):
     
     self.parsedXml = configNode
     
     self.channel = XMLUtils.getAttributeSafe(configNode, "channel", "9")
     self.setChannel(self.channel)
     
     children = list(configNode)
     for child in children:
         if child.tag == "connection":
             connection = Connection()
             connection.keep_alive = XMLUtils.getAttributeSafe(child, "keep-alive")
             connection.reconnect_interval = XMLUtils.getAttributeSafe(child, "reconnect-interval")
             
             self.connection = connection
             
         elif child.tag == "authentication":
             authentication = Authentication()
             authentication.setToken(XMLUtils.getAttributeSafe(child, "token"))
             
             self.authentication = authentication
             
         elif child.tag == "logging":
             logging = Logging()
             logging.rotation = XMLUtils.getAttributeSafe(child, "rotation", "3600000")
             self.setLoggingRotation(logging.rotation)
             
             self.logging = logging
             
         elif child.tag == "software":
             software = Software()
             software.license = XMLUtils.getAttributeSafe(child, "license")
             software.major = XMLUtils.getAttributeSafe(child, "major")
             software.minor = XMLUtils.getAttributeSafe(child, "minor")
             software.build = XMLUtils.getAttributeSafe(child, "build")
             software.kernel = XMLUtils.getAttributeSafe(child, "kernel")
             
             self.software = software
             
         elif child.tag == "configProperties":
             properties = list(child)
             for prop in properties:
                 key = prop.attrib["prop_key"]
                 value = prop.attrib["prop_value"]
                 self.configProperties[key] = value
     
     self.saveConfiguration()
     self.setChanged()
     self.notifyObservers()        
コード例 #13
0
    def loadConfiguration(self):
        logger.info("Loading configuration from:" +
                    ClientURISettings.CONFIG_FILE)
        if not (os.path.exists(ClientURISettings.CONFIG_FILE)
                and os.path.isfile(ClientURISettings.CONFIG_FILE)):
            outf = open(ClientURISettings.CONFIG_FILE, "w")
            outf.write(self.getDefaultConfiguration())
            outf.close()

        try:
            xmlContent = SystemWriter.readFileToString(
                ClientURISettings.CONFIG_FILE)

            if (xmlContent.strip() == ""):
                logger.error(
                    "Client config was empty, putting device into limbo with default config"
                )
                os.remove(ClientURISettings.CONFIG_FILE)
                outf = open(ClientURISettings.CONFIG_FILE, "w")
                outf.write(self.getDefaultConfiguration())
                outf.close()
                xmlContent = SystemWriter.readFileToString(
                    ClientURISettings.CONFIG_FILE)

            configNode = XMLUtils.stringToElement(xmlContent)
            self.parseNode(configNode)
        except Exception as err:
            logger.error(err)
コード例 #14
0
    def saveConfiguration(self):
        if (self.parsedXml != None):
            self.setMacAddr()

            stringCurrentXML = XMLUtils.elementToString(self.parsedXml)
            stringSavedXML = SystemWriter.readFileToString(
                ClientURISettings.CONFIG_FILE)
            if ((stringCurrentXML != stringSavedXML)
                    and (len(stringCurrentXML) != len(
                        self.getDefaultConfiguration()))):
                XMLUtils.writeNodeToFile(ClientURISettings.CONFIG_FILE,
                                         self.parsedXml)
                logger.info("ClientConfig updated on file system")
            else:
                logger.debug("ClientConfig change not needed")
        else:
            logger.error("Cannot save ClientConfig: no data available")
コード例 #15
0
    def __init__(self, parsedNode):
        
        self.id = XMLUtils.getAttributeSafe(parsedNode, "id")
        self.name = XMLUtils.getAttributeSafe(parsedNode, "name")
        
        h = hashlib.new('ripemd160')
        h.update(XMLUtils.elementToString(parsedNode))
        self.checksum = h.hexdigest()
        
        self.active = XMLUtils.getAttributeSafe(parsedNode, "active")
        
        # THIS SHOULD NOT EXIST AT THE CAMPAIGN LEVEL AND AT THE WIFI/BT LEVEL TOO
        self.days_of_week = TimeConstants.getDaysOfWeek( XMLUtils.getAttributeSafe(parsedNode, "days_of_week") )
        
        self.start_date = TimeConstants.dateParseUTC( XMLUtils.getAttributeSafe(parsedNode, "start_date") )
        self.end_date = TimeConstants.dateParseUTC( XMLUtils.getAttributeSafe(parsedNode, "end_date") )

        self.start_time = XMLUtils.getAttributeSafe(parsedNode, "start_time")
        self.end_time = XMLUtils.getAttributeSafe(parsedNode, "end_time")
        
        self.wifiNode = parsedNode.find("wifi_campaign")
        self.btNode = parsedNode.find("bluetooth_campaign")
        self.pubNubNode = parsedNode.find("pubNubKey")
        
        self.type = []
        self.wifiCampaign = None
        self.bluetoothCampaign = None
        self.pubNubKey = None
        if ( self.wifiNode != None ):
            self.type.append(ClientURISettings.MESSAGE_WIFI)
            self.wifiCampaign = WifiCampaign(self.wifiNode)
            
        if ( self.btNode != None ):
            self.type.append(ClientURISettings.MESSAGE_BLUETOOTH)
            self.bluetoothCampaign = BluetoothCampaign(self.btNode)
                      
        if ( self.pubNubNode != None ):
            self.pubNubKey = PubNubKey(self.pubNubNode)
        
        # this exists to allow you to dynamically get the content by type
        self.content = {}
        self.content[ClientURISettings.MESSAGE_BLUETOOTH] = self.bluetoothCampaign
        self.content[ClientURISettings.MESSAGE_WIFI] = self.wifiCampaign
        
        self.last_modified = TimeConstants.dateParseUTC( XMLUtils.getAttributeSafe(parsedNode, "last_modified") )
コード例 #16
0
 def loadCampaigns(self):
     
     logger.info("Loading configuration from:" + ClientURISettings.CAMPAIGNS_FILE)
     if not (os.path.exists(ClientURISettings.CAMPAIGNS_FILE) and os.path.isfile(ClientURISettings.CAMPAIGNS_FILE)):
         return
     try:
         self.parsedXml = XMLUtils.readNodeFromFile(ClientURISettings.CAMPAIGNS_FILE)
         self.parseNode(self.parsedXml)
     except Exception as err:
         logger.error(err)
コード例 #17
0
    def register(self):

        rest = RESTClient()

        if (not self.mac):
            self.mac = ProcessExecutor.getMACeth0()
        if (not self.serialNumber):
            self.serialNumber = ProcessExecutor.getSerialNumber()

        while not self.isRegistered():
            try:
                logger.debug("Starting REGISTER Request, MAC %s, serial %s" %
                             (self.mac, self.serialNumber))
                formparams = {}
                formparams["mac"] = self.mac
                formparams["serialNumber"] = self.serialNumber
                formparams[
                    "major"] = self.mainParent.clientConfig.software.major
                formparams[
                    "minor"] = self.mainParent.clientConfig.software.minor
                formparams[
                    "build"] = self.mainParent.clientConfig.software.build
                formparams["kernel"] = ProcessExecutor.getKernelVersion()
                formparams["platform"] = "BGAX4"

                r = rest.PUTRequest(uri=ClientURISettings.getRegistrationUri(),
                                    content=formparams)

                if (r == None):
                    logger.error("No response from server, check connectivity")
                elif (r.status_code == HttpStatus.SC_FORBIDDEN):
                    logger.error(
                        "Device %s already registered in database, please remedy"
                        % self.mac)
                elif (r.status_code == HttpStatus.SC_OK):
                    xmlNode = XMLUtils.stringToElement(r.content)
                    token = XMLParser.getTokenFromRegisterResponse(xmlNode)
                    self.mainParent.clientConfig.setToken(token)
                    self.mainParent.clientConfig.authentication.setToken(token)
                    self.mainParent.clientConfig.saveConfiguration()
                    logger.info("Successful registration, token %s received" %
                                token)
                    return
                else:
                    logger.error("Status: %d, content: %s" %
                                 (r.status_code, r.content))
            except Exception as err:
                logger.error(err)

            # If registration failed sleep 60 seconds before retrying
            logger.debug("Registration failed, sleeping %d s" %
                         TimeConstants.ONE_MINUTE_SECONDS)
            time.sleep(TimeConstants.ONE_MINUTE_SECONDS)
コード例 #18
0
    def handleStatusResponse(self, response, deviceClient):

        if (response == None):
            # no connectivity
            logger.info("Internet access unavailable")
            return

        code = response.status_code
        content = response.content

        if (code == HttpStatus.SC_OK):
            logger.info("Status API completed successfully")

            xmlNode = XMLUtils.stringToElement(content)

            configNode = XMLParser.getClientConfigFromStatusResponse(xmlNode)
            actionsNode = XMLParser.getActionsFromStatusResponse(xmlNode)
            campaignsNode = XMLParser.getCampaignsFromStatusResponseNode(
                xmlNode)
            pubNubNode = XMLParser.getPubNubKeysFromStatusResponse(xmlNode)

            deviceClient.clientConfig.parseNode(configNode)
            deviceClient.actionHandler.parseNode(actionsNode)
            deviceClient.campaignHandler.parseNode(campaignsNode)
            deviceClient.pubNubHandler.parseNode(pubNubNode)

        elif (code == HttpStatus.SC_NO_CONTENT):
            # git Nothing hast changed
            logger.warn("No Content")
        elif (code == HttpStatus.SC_NOT_MODIFIED):
            #Nothing changed and NO STATUS on Config moving on
            logger.warn("Not Modified")
        elif (code == HttpStatus.SC_NOT_FOUND):
            logger.warn(
                "404 Response from Server (Unable to find device in Database)")
        elif (code == HttpStatus.SC_FORBIDDEN):
            logger.warn(
                "403 Response from Server (Forbidden - Access to this device License has expired) "
                + content)
        elif (code == HttpStatus.SC_INTERNAL_SERVER_ERROR):
            logger.error("Status: %d, content: %s" %
                         (response.status_code, content))
        else:
            logger.warn(
                "Non 200 Response from server unable to handle response: %d" %
                code)
コード例 #19
0
 def __init__(self, parsedNode):
     self.channel = XMLUtils.getAttributeSafe(parsedNode, "channel")
     origin = XMLUtils.getAttributeSafe(parsedNode, "origin")
     publish_key = XMLUtils.getAttributeSafe(parsedNode, "pubkey")
     secret_key = XMLUtils.getAttributeSafe(parsedNode, "secret")
     subscribe_key = XMLUtils.getAttributeSafe(parsedNode, "subkey")
     ssl_on = XMLUtils.getAttributeSafe(parsedNode, "sslon")
     if origin == None:
         origin = "pubsub.pubnub.com"
     if ssl_on == None:
         ssl_on = False
     self.pubnub = Pubnub(publish_key, subscribe_key, secret_key, ssl_on, origin)
コード例 #20
0
 def __init__(self, parsedNode):
     self.channel = XMLUtils.getAttributeSafe(parsedNode, "channel")
     origin = XMLUtils.getAttributeSafe(parsedNode, "origin")
     publish_key = XMLUtils.getAttributeSafe(parsedNode, "pubkey")
     secret_key = XMLUtils.getAttributeSafe(parsedNode, "secret")
     subscribe_key = XMLUtils.getAttributeSafe(parsedNode, "subkey")
     ssl_on = XMLUtils.getAttributeSafe(parsedNode, "sslon")
     if (origin == None):
         origin = 'pubsub.pubnub.com'
     if (ssl_on == None):
         ssl_on = False
     self.pubnub = Pubnub(publish_key, subscribe_key, secret_key, ssl_on,
                          origin)
コード例 #21
0
 def register(self):
     
     rest = RESTClient()
     
     if ( not self.mac ):
         self.mac = ProcessExecutor.getMACeth0()
     if ( not self.serialNumber ):
         self.serialNumber = ProcessExecutor.getSerialNumber()
    
     while not self.isRegistered():
         try:
             logger.debug("Starting REGISTER Request, MAC %s, serial %s" % (self.mac, self.serialNumber))
             formparams = {}
             formparams["mac"] = self.mac
             formparams["serialNumber"] = self.serialNumber
             formparams["major"] = self.mainParent.clientConfig.software.major
             formparams["minor"] = self.mainParent.clientConfig.software.minor
             formparams["build"] = self.mainParent.clientConfig.software.build
             formparams["kernel"] = ProcessExecutor.getKernelVersion()
             formparams["platform"] = "BGAX4"
             
             r = rest.PUTRequest(uri=ClientURISettings.getRegistrationUri(), content=formparams)
             
             if ( r == None ):
                 logger.error("No response from server, check connectivity")
             elif ( r.status_code == HttpStatus.SC_FORBIDDEN ):
                 logger.error("Device %s already registered in database, please remedy" % self.mac)
             elif ( r.status_code == HttpStatus.SC_OK ):
                 xmlNode = XMLUtils.stringToElement(r.content)
                 token = XMLParser.getTokenFromRegisterResponse(xmlNode)
                 self.mainParent.clientConfig.setToken(token)
                 self.mainParent.clientConfig.authentication.setToken(token)
                 self.mainParent.clientConfig.saveConfiguration()
                 logger.info("Successful registration, token %s received" % token)
                 return
             else:
                 logger.error("Status: %d, content: %s" % (r.status_code, r.content))
         except Exception as err:
             logger.error(err)
         
         # If registration failed sleep 60 seconds before retrying
         logger.debug("Registration failed, sleeping %d s" % TimeConstants.ONE_MINUTE_SECONDS)
         time.sleep(TimeConstants.ONE_MINUTE_SECONDS)
コード例 #22
0
 def loadConfiguration(self):
     logger.info("Loading configuration from:" + ClientURISettings.CONFIG_FILE)
     if not (os.path.exists(ClientURISettings.CONFIG_FILE) and os.path.isfile(ClientURISettings.CONFIG_FILE)):
         outf = open(ClientURISettings.CONFIG_FILE, "w")
         outf.write(self.getDefaultConfiguration())
         outf.close()
     
     try:
         xmlContent = SystemWriter.readFileToString(ClientURISettings.CONFIG_FILE)
         
         if ( xmlContent.strip() == "" ):
             logger.error("Client config was empty, putting device into limbo with default config")
             os.remove(ClientURISettings.CONFIG_FILE)
             outf = open(ClientURISettings.CONFIG_FILE, "w")
             outf.write(self.getDefaultConfiguration())
             outf.close()
             xmlContent = SystemWriter.readFileToString(ClientURISettings.CONFIG_FILE)
         
         configNode = XMLUtils.stringToElement(xmlContent)
         self.parseNode(configNode)
     except Exception as err:
         logger.error(err)
コード例 #23
0
    def handleStatusResponse(self, response, deviceClient):
        
        if ( response == None ):
            # no connectivity
            logger.info("Internet access unavailable")
            return
        
        code = response.status_code
        content = response.content
        
        if ( code == HttpStatus.SC_OK ):
            logger.info("Status API completed successfully")
            
            xmlNode = XMLUtils.stringToElement(content)
            
            configNode = XMLParser.getClientConfigFromStatusResponse(xmlNode)
            actionsNode = XMLParser.getActionsFromStatusResponse(xmlNode)
            campaignsNode = XMLParser.getCampaignsFromStatusResponseNode(xmlNode)
            pubNubNode = XMLParser.getPubNubKeysFromStatusResponse(xmlNode)
            
            deviceClient.clientConfig.parseNode(configNode)
            deviceClient.actionHandler.parseNode(actionsNode)
            deviceClient.campaignHandler.parseNode(campaignsNode)
            deviceClient.pubNubHandler.parseNode(pubNubNode)

        elif ( code ==  HttpStatus.SC_NO_CONTENT ):
            # git Nothing hast changed
            logger.warn("No Content")
        elif ( code ==  HttpStatus.SC_NOT_MODIFIED ):
            #Nothing changed and NO STATUS on Config moving on
            logger.warn("Not Modified")
        elif ( code ==  HttpStatus.SC_NOT_FOUND ):
            logger.warn("404 Response from Server (Unable to find device in Database)")
        elif ( code ==  HttpStatus.SC_FORBIDDEN ):
            logger.warn("403 Response from Server (Forbidden - Access to this device License has expired) " + content)
        elif ( code ==  HttpStatus.SC_INTERNAL_SERVER_ERROR ):
            logger.error("Status: %d, content: %s" % (response.status_code, content))
        else:
            logger.warn("Non 200 Response from server unable to handle response: %d" % code)
コード例 #24
0
    def handle(self, action):
        logging.info("Got software update action")
        path = XMLUtils.getAttributeSafe(action.actionNode, "path", None)
        if (path != None):
            # download the file
            restClient = RESTClient()

            url = ClientURISettings.getSoftwareUpdateURI()
            if path.find("/") != 0:
                url += "/"
            url += path

            filename = os.path.basename(path)

            FileSystemChecker.initDir(ClientURISettings.SWUPDATE_ROOT_DIR)
            downloadPath = ClientURISettings.SWUPDATE_ROOT_DIR + os.sep + filename

            if (os.path.exists(downloadPath)):
                success = True
            else:
                success = restClient.GETFile(url, downloadPath)

            if (not success):
                logger.error(
                    "Failed to download software update at URL '%s' to file '%s'"
                    % (url, downloadPath))
            elif (success and not os.path.exists(downloadPath)):
                success = False
                logger.error("Failure in saving downloaded wpk file to %s" %
                             downloadPath)
            else:
                # success, move to /tmp/obex to make it auto-install the WPK file
                logger.info("Installation of %s beginning" % downloadPath)
                fileName = os.path.basename(downloadPath)
                FileSystemChecker.initDir("/tmp/obex")
                destination = "/tmp/obex/%s" % fileName
                shutil.copy(downloadPath, destination)
コード例 #25
0
    def handle(self, action):
        logging.info("Got software update action")
        path = XMLUtils.getAttributeSafe(action.actionNode, "path", None)
        if ( path != None ):
            # download the file
            restClient = RESTClient()
            
            url =  ClientURISettings.getSoftwareUpdateURI()
            if path.find("/") != 0:
                url += "/"
            url += path
            
            filename = os.path.basename(path)
            
            FileSystemChecker.initDir(ClientURISettings.SWUPDATE_ROOT_DIR )
            downloadPath = ClientURISettings.SWUPDATE_ROOT_DIR + os.sep + filename

            if ( os.path.exists(downloadPath )):
                success = True
            else:
                success = restClient.GETFile(url, downloadPath)
            
            if ( not success ):
                logger.error("Failed to download software update at URL '%s' to file '%s'" % (url, downloadPath))
            elif ( success and not os.path.exists(downloadPath)):
                success = False
                logger.error("Failure in saving downloaded wpk file to %s" % downloadPath)  
            else:
                # success, move to /tmp/obex to make it auto-install the WPK file
                logger.info("Installation of %s beginning" % downloadPath)
                fileName = os.path.basename(downloadPath)
                FileSystemChecker.initDir("/tmp/obex")
                destination = "/tmp/obex/%s" % fileName
                shutil.copy(downloadPath, destination)
                
                
                
コード例 #26
0
 def getConfigurationXml(self):
     return XMLUtils.elementToString(self.parsedXml)
コード例 #27
0
 def getConfigurationXml(self):
     return XMLUtils.elementToString(self.parsedXml)
コード例 #28
0
    def handle(self, someObject):
        if isinstance(someObject,
                      Action) and someObject.actionType == "shellcommand":
            command = XMLUtils.getAttributeSafe(someObject.actionNode,
                                                "command")
            parameters = XMLUtils.getAttributeSafe(someObject.actionNode,
                                                   "parameters")
            command = str(command)
            parameters = str(parameters)

            logger.info("Executing shell command %s with parameters %s" %
                        (command, parameters))

            if command == "reversessh" or command == "reverseSSH":
                paramsList = parameters.split()
                try:
                    hostPort = (paramsList[0])
                    try:
                        devicePort = paramsList[1]
                    except Exception:
                        devicePort = "16222"
                    result = ProcessExecutor.reverseSSH(hostPort, devicePort)
                    logger.info(result)
                except ValueError as error:
                    logger.error("no Host Port was defined")

                #logFileName = "shellcommand_" + ProcessExecutor.getMACeth0() + "_reversessh_" + TimeConstants.cronDateFormat() + ".txt"
                #filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
                #SystemWriter.writeFile(filePath, result)
            elif command == "bash":
                splitCmd = parameters.split("|")
                if parameters.find("|") > -1 and len(splitCmd) > 1:
                    commandOne = splitCmd[0]
                    commandTwo = splitCmd[1]
                    result = ProcessExecutor.pipedCommand(
                        commandOne, commandTwo)
                else:
                    result = ProcessExecutor.executeCommand(parameters)
                logger.info(result)
                logFileName = "bash_" + ProcessExecutor.getMACeth0(
                ) + "_command_" + TimeConstants.cronDateFormat() + ".txt"
                filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
                SystemWriter.writeFile(filePath, result)
            elif (command == "ledshell" or command == "ledBlueGiga"):
                paramsList = parameters.split()
                try:
                    action = (paramsList[0])
                except:
                    logger.error(
                        "no LED action was defined, defaulting to 'locate'")
                    action = "locate"
                result = ProcessExecutor.ledShell(action)
                logger.info(result)
                logFileName = "shellcommand_" + ProcessExecutor.getMACeth0(
                ) + "_ledshell_" + TimeConstants.cronDateFormat() + ".txt"
                filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
                SystemWriter.writeFile(filePath, result)

        else:
            result = "Cannot process command: %s %s" % (command, parameters)
            logger.error(result)
            logFileName = "shellcommand_" + ProcessExecutor.getMACeth0(
            ) + "_unknowncommand_" + TimeConstants.cronDateFormat() + ".txt"
            filePath = ClientURISettings.LOG_QUEUE + os.sep + logFileName
            SystemWriter.writeFile(filePath, result)