# Path: myDevices/utils/logger.py
# def exception(message):
#     if checkFlood(message):
#         return
#     LOGGER.exception(message)
# 
# def info(message):
#     # if checkFlood(message):
#     #     return
#     LOGGER.info(message)
# 
# def warn(message):
#     if checkFlood(message):
#         return
#     LOGGER.warn(message)
# 
# def error(message, *args, **kwargs):
#     if checkFlood(message):
#         return
#     LOGGER.error(message, *args, **kwargs)
# 
# def debug(message):
#     outerFrame = getouterframes(currentframe())[1][0]
#     (args, _, _, values) = getargvalues(outerFrame)
#     argsValue = ''
#     
#     for i in args:
#         if i is 'self':
#             continue
#         argsValue += "(%s=%s)" % (i, str(values[i]))
#     
#     stack = extract_stack()
#     (filename, line, procname, text) = stack[-2]
#     LOGGER.debug(str(filename) + ' ' + str(procname) + str(argsValue) + ':' + str(line) + '> '  + str(message))
# 
# def setDebug():
#     LOGGER.setLevel(DEBUG)
#     return
# 
# Path: myDevices/utils/config.py
# class Config:
#     def __init__(self, path):
#         self.mutex = RLock()
#         self.path = path
#         self.config = RawConfigParser()
#         self.config.optionxform = str
#         try:
#             with open(path) as fp:
#                 self.config.read_file(fp)
#         except:
#             pass
#             
#     def set(self, section, key, value):
#         with self.mutex:
#             try:
#                 self.config.set(section, key, value)
#             except NoSectionError:
#                 self.config.add_section(section)
#                 self.config.set(section, key, value)
#         self.save()
# 
#     def get(self, section, key, fallback=_UNSET):
#         return self.config.get(section, key, fallback=fallback)
# 
#     def getInt(self, section, key, fallback=_UNSET):
#         return self.config.getint(section, key, fallback=fallback)
#     
#     def remove(self, section, key):
#         with self.mutex:
#             result = self.config.remove_option(section, key)       
#         self.save()
# 
#     def save(self):
#         with self.mutex:
#             with open(self.path, 'w') as configfile:
#                 self.config.write(configfile)
# 
#     def sections(self):
#         return self.config.sections()
# 
# Path: myDevices/utils/subprocess.py
# def executeCommand(command, increaseMemoryLimit=False, disablePipe=False):
#     """Execute a specified command, increasing the processes memory limits if specified"""
#     debug('executeCommand: ' +  command)
#     output = ''
#     returncode = 1
#     try:
#         preexec = None
#         pipe = PIPE
#         if increaseMemoryLimit:
#             preexec = setMemoryLimits
#         if disablePipe:
#             debug('Disable pipe to prevent child exiting when parent exits')
#             pipe = DEVNULL
#         process = Popen(command, stdout=pipe, stderr=pipe, shell=True, preexec_fn=preexec)
#         (stdout_data, stderr_data) = process.communicate()
#         returncode = process.wait()
#         returncode = process.returncode
#         # debug('executeCommand: stdout_data {}, stderr_data {}'.format(stdout_data, stderr_data))
#         if stdout_data:
#             output = stdout_data.decode('utf-8')
#             stdout_data = None
#     except:
#         exception('executeCommand failed: ' + command)
#     return (output, returncode)


from myDevices.utils.logger import exception, info, warn, error, debug, setDebug
from time import time, sleep
from sched import scheduler
from distutils.version import LooseVersion, StrictVersion
from os import mkdir, path
from threading import Thread
from shutil import rmtree
from datetime import datetime, timedelta
from myDevices.utils.config import Config
from myDevices.utils.subprocess import executeCommand
    from urllib.request import urlopen
    from urllib2 import urlopen
import random
            error('Update version cannot be retrieved. Cannot update agent.')
            self.UpdateCleanup()
            return
        sleep(1)
        retValue = self.CheckVersion(self.currentVersion, self.newVersion)
        if retValue is True:
            info('Update needed, current version: {}, update version: {}'.format(self.currentVersion, self.newVersion))
            retValue = self.ExecuteUpdate()
            if retValue is False:
                self.UpdateCleanup()
                error('Agent failed to update')
                return
        else:
            info('Update not needed, current version: {}, update version: {}'.format(self.currentVersion, self.newVersion))
        sleep(1)
        self.UpdateCleanup()

    def SetupUpdater(self):
        # global TIME_TO_CHECK
        # TIME_TO_CHECK = self.appSettings.get('Agent', 'UpdateCheckRate', TIME_TO_CHECK)
        self.scheduler.enter(TIME_TO_CHECK, 1, self.CheckUpdate, ())

    def RetrieveUpdate(self):
        try:
            info('Checking update version')
            debug('Retrieve update config: {} {}'.format(UPDATE_URL, UPDATE_CFG))
            retValue = self.DownloadFile(UPDATE_URL, UPDATE_CFG)
            if retValue is False:
                error('Failed to download update file')
                return retValue

# Path: myDevices/utils/logger.py
# def exception(message):
#     if checkFlood(message):
#         return
#     LOGGER.exception(message)
# 
# def info(message):
#     # if checkFlood(message):
#     #     return
#     LOGGER.info(message)
# 
# def warn(message):
#     if checkFlood(message):
#         return
#     LOGGER.warn(message)
# 
# def error(message, *args, **kwargs):
#     if checkFlood(message):
#         return
#     LOGGER.error(message, *args, **kwargs)
# 
# def debug(message):
#     outerFrame = getouterframes(currentframe())[1][0]
#     (args, _, _, values) = getargvalues(outerFrame)
#     argsValue = ''
#     
#     for i in args:
#         if i is 'self':
#             continue
#         argsValue += "(%s=%s)" % (i, str(values[i]))
#     
#     stack = extract_stack()
#     (filename, line, procname, text) = stack[-2]
#     LOGGER.debug(str(filename) + ' ' + str(procname) + str(argsValue) + ':' + str(line) + '> '  + str(message))
# 
# def setDebug():
#     LOGGER.setLevel(DEBUG)
#     return
# 
# Path: myDevices/utils/config.py
# class Config:
#     def __init__(self, path):
#         self.mutex = RLock()
#         self.path = path
#         self.config = RawConfigParser()
#         self.config.optionxform = str
#         try:
#             with open(path) as fp:
#                 self.config.read_file(fp)
#         except:
#             pass
#             
#     def set(self, section, key, value):
#         with self.mutex:
#             try:
#                 self.config.set(section, key, value)
#             except NoSectionError:
#                 self.config.add_section(section)
#                 self.config.set(section, key, value)
#         self.save()
# 
#     def get(self, section, key, fallback=_UNSET):
#         return self.config.get(section, key, fallback=fallback)
# 
#     def getInt(self, section, key, fallback=_UNSET):
#         return self.config.getint(section, key, fallback=fallback)
#     
#     def remove(self, section, key):
#         with self.mutex:
#             result = self.config.remove_option(section, key)       
#         self.save()
# 
#     def save(self):
#         with self.mutex:
#             with open(self.path, 'w') as configfile:
#                 self.config.write(configfile)
# 
#     def sections(self):
#         return self.config.sections()
# 
# Path: myDevices/utils/subprocess.py
# def executeCommand(command, increaseMemoryLimit=False, disablePipe=False):
#     """Execute a specified command, increasing the processes memory limits if specified"""
#     debug('executeCommand: ' +  command)
#     output = ''
#     returncode = 1
#     try:
#         preexec = None
#         pipe = PIPE
#         if increaseMemoryLimit:
#             preexec = setMemoryLimits
#         if disablePipe:
#             debug('Disable pipe to prevent child exiting when parent exits')
#             pipe = DEVNULL
#         process = Popen(command, stdout=pipe, stderr=pipe, shell=True, preexec_fn=preexec)
#         (stdout_data, stderr_data) = process.communicate()
#         returncode = process.wait()
#         returncode = process.returncode
#         # debug('executeCommand: stdout_data {}, stderr_data {}'.format(stdout_data, stderr_data))
#         if stdout_data:
#             output = stdout_data.decode('utf-8')
#             stdout_data = None
#     except:
#         exception('executeCommand failed: ' + command)
#     return (output, returncode)


# Path: myDevices/cloud/updater.py
from myDevices.utils.logger import exception, info, warn, error, debug, setDebug
from time import time, sleep
from sched import scheduler
from distutils.version import LooseVersion, StrictVersion
from os import mkdir, path
from threading import Thread
from shutil import rmtree
from datetime import datetime, timedelta
from myDevices.utils.config import Config
from myDevices.utils.subprocess import executeCommand
    from urllib.request import urlopen
    from urllib2 import urlopen
import random

            error('Update version cannot be retrieved. Cannot update agent.')
            self.UpdateCleanup()
            return
        sleep(1)
        retValue = self.CheckVersion(self.currentVersion, self.newVersion)
        if retValue is True:
            info('Update needed, current version: {}, update version: {}'.format(self.currentVersion, self.newVersion))
            retValue = self.ExecuteUpdate()
            if retValue is False:
                self.UpdateCleanup()
                error('Agent failed to update')
                return
        else:
            info('Update not needed, current version: {}, update version: {}'.format(self.currentVersion, self.newVersion))
        sleep(1)
        self.UpdateCleanup()

    def SetupUpdater(self):
        # global TIME_TO_CHECK
        # TIME_TO_CHECK = self.appSettings.get('Agent', 'UpdateCheckRate', TIME_TO_CHECK)
        self.scheduler.enter(TIME_TO_CHECK, 1, self.CheckUpdate, ())

    def RetrieveUpdate(self):
        try:
            info('Checking update version')
            debug('Retrieve update config: {} {}'.format(UPDATE_URL, UPDATE_CFG))
            retValue = self.DownloadFile(UPDATE_URL, UPDATE_CFG)
            if retValue is False:
                error('Failed to download update file')
                return retValue

            updateConfig = Config(UPDATE_CFG)