# 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))
# 
# Path: myDevices/utils/daemon.py
# class Daemon:
#     """class for restarting the agent if errors occur and exiting on critical failures."""
# 
#     @staticmethod
#     def OnFailure(component, error=0):
#         """Handle error in component and restart the agent if necessary"""
#         #-3=Temporary failure in name resolution
#         info('Daemon failure handling ' + str(error))
#         if error in errorList:
#             Daemon.Restart()
#         if component not in failureCount:
#             Daemon.Reset(component)
#         failureCount[component] += 1
#         now = datetime.now()
#         if startFailure[component] == 0:
#             startFailure[component] = now
#         elapsedTime = now - startFailure[component]
#         if (elapsedTime.total_seconds() >= RESET_TIMEOUT) or (failureCount[component] > FAILURE_COUNT):
#             warn('Daemon::OnFailure myDevices is going to restart after ' + str(component) + ' failed: ' + str(elapsedTime.total_seconds()) + ' seconds and ' + str(failureCount) + ' times')
#             Daemon.Restart()
# 
#     @staticmethod
#     def Reset(component):
#         """Reset failure count for component"""
#         startFailure[component] = 0
#         failureCount[component] = 0
# 
#     @staticmethod
#     def Restart():
#         """Restart the agent daemon"""
#         try:
#             info('Daemon restarting myDevices' )
#             (output, returncode) = executeCommand('sudo service myDevices restart')
#             debug(str(output) + ' ' + str(returncode))
#             del output
#         except:
#             exception("Daemon::Restart unexpected error")
#             Daemon.Exit()
# 
#     @staticmethod
#     def Exit():
#         """Stop the agent daemon"""
#         error('Critical failure. Closing myDevices process.')
#         raise SystemExit
# 
# Path: myDevices/utils/threadpool.py
# class ThreadPool(Singleton):
#     """Singleton thread pool class"""
# 
#     @staticmethod
#     def Submit(func):
#         """Submit a function for the thread pool to run"""
#         executor.submit(func)
# 
#     @staticmethod
#     def Shutdown():
#         """Shutdown the thread pool"""
#         executor.shutdown()


from datetime import datetime, timedelta
from os import path, remove
from urllib import request, error
from myDevices.utils.logger import exception, info, warn, error, debug
from time import sleep
from random import randint
from socket import error as socket_error
from myDevices.utils.daemon import Daemon
from myDevices.utils.threadpool import ThreadPool
    from myDevices.utils.config import Config    
        """Run speed test"""
        if self.isRunning:
            return False
        self.isRunning = True
        sleep(1)
        self.TestDownload()
        sleep(1)
        self.testTime = datetime.now()
        self.isRunning = False
        return True

    def TestDownload(self):
        """Test download speed by retrieving a file"""
        try:
            info('Executing regular download test for network speed')
            url = self.config.get('Agent', 'DownloadSpeedTestUrl', defaultUrl)
            debug(url + ' ' + download_path)
            a = datetime.now()
            request.urlretrieve(url, download_path)
            b = datetime.now()
            request.urlcleanup()
            c = b - a
            if path.exists(download_path):
                size = path.getsize(download_path)/mb
                self.downloadSpeed = size/c.total_seconds() * 8 #Convert to megabits per second
                remove(download_path)
                return True
        except socket_error as serr:
            error ('TestDownload:' + str(serr))
            ret = False

# 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))
# 
# Path: myDevices/utils/daemon.py
# class Daemon:
#     """class for restarting the agent if errors occur and exiting on critical failures."""
# 
#     @staticmethod
#     def OnFailure(component, error=0):
#         """Handle error in component and restart the agent if necessary"""
#         #-3=Temporary failure in name resolution
#         info('Daemon failure handling ' + str(error))
#         if error in errorList:
#             Daemon.Restart()
#         if component not in failureCount:
#             Daemon.Reset(component)
#         failureCount[component] += 1
#         now = datetime.now()
#         if startFailure[component] == 0:
#             startFailure[component] = now
#         elapsedTime = now - startFailure[component]
#         if (elapsedTime.total_seconds() >= RESET_TIMEOUT) or (failureCount[component] > FAILURE_COUNT):
#             warn('Daemon::OnFailure myDevices is going to restart after ' + str(component) + ' failed: ' + str(elapsedTime.total_seconds()) + ' seconds and ' + str(failureCount) + ' times')
#             Daemon.Restart()
# 
#     @staticmethod
#     def Reset(component):
#         """Reset failure count for component"""
#         startFailure[component] = 0
#         failureCount[component] = 0
# 
#     @staticmethod
#     def Restart():
#         """Restart the agent daemon"""
#         try:
#             info('Daemon restarting myDevices' )
#             (output, returncode) = executeCommand('sudo service myDevices restart')
#             debug(str(output) + ' ' + str(returncode))
#             del output
#         except:
#             exception("Daemon::Restart unexpected error")
#             Daemon.Exit()
# 
#     @staticmethod
#     def Exit():
#         """Stop the agent daemon"""
#         error('Critical failure. Closing myDevices process.')
#         raise SystemExit
# 
# Path: myDevices/utils/threadpool.py
# class ThreadPool(Singleton):
#     """Singleton thread pool class"""
# 
#     @staticmethod
#     def Submit(func):
#         """Submit a function for the thread pool to run"""
#         executor.submit(func)
# 
#     @staticmethod
#     def Shutdown():
#         """Shutdown the thread pool"""
#         executor.shutdown()


# Path: myDevices/cloud/download_speed.py
from datetime import datetime, timedelta
from os import path, remove
from urllib import request, error
from myDevices.utils.logger import exception, info, warn, error, debug
from time import sleep
from random import randint
from socket import error as socket_error
from myDevices.utils.daemon import Daemon
from myDevices.utils.threadpool import ThreadPool
    from myDevices.utils.config import Config    

        """Run speed test"""
        if self.isRunning:
            return False
        self.isRunning = True
        sleep(1)
        self.TestDownload()
        sleep(1)
        self.testTime = datetime.now()
        self.isRunning = False
        return True

    def TestDownload(self):
        """Test download speed by retrieving a file"""
        try:
            info('Executing regular download test for network speed')
            url = self.config.get('Agent', 'DownloadSpeedTestUrl', defaultUrl)
            debug(url + ' ' + download_path)
            a = datetime.now()
            request.urlretrieve(url, download_path)
            b = datetime.now()
            request.urlcleanup()
            c = b - a
            if path.exists(download_path):
                size = path.getsize(download_path)/mb
                self.downloadSpeed = size/c.total_seconds() * 8 #Convert to megabits per second
                remove(download_path)
                return True
        except socket_error as serr:
            error ('TestDownload:' + str(serr))
            ret = False

            Daemon.OnFailure('cloud', serr.errno)