def __init__(self, data, logger=None):
     """Creates a new instance of MakoDataTransporter."""
     self._log = logger if logger else Logger(self)
     self._data = data if data else dict()
     self._traces = []
     self._warns = []
     self._rootData = None
Beispiel #2
0
    def __init__(self,
                 targetPackageOrPath,
                 rootPath,
                 verbose=True,
                 debug=False,
                 trace=False,
                 force=False,
                 compress=False,
                 buildOnly=False):
        """Creates a new instance of CoffeescriptBuilder."""

        self.buildOnly = buildOnly

        self._imports = dict()
        self._requires = dict()
        self._includes = dict()
        self._report = dict()
        self._warnings = []
        self._dependencyReport = dict()
        self._verbose = verbose
        self._log = Logger(self, printOut=True)
        self._trace = trace
        self._debug = debug
        self._targets = []
        self._force = force
        self._compress = compress
        self._rootPath = rootPath

        if not isinstance(targetPackageOrPath, CoffeescriptDependency):
            target = CoffeescriptDependency(targetPackageOrPath, rootPath,
                                            None)
        else:
            target = targetPackageOrPath

        if target.exists:
            self._targets.append(target)
        else:
            csFiles = CoffeescriptBuilder.getScriptsInPath(target.packagePath)

            # Look for exec matches first
            for f in csFiles:
                testTarget = CoffeescriptDependency(f, rootPath, None)
                if testTarget.isExec:
                    self._targets.append(testTarget)

            # Look for lib matches second. Lib matches are tested as a second pass because
            # constructing all exec files first potentially optimizes the import process for
            # the libraries.
            for f in csFiles:
                testTarget = CoffeescriptDependency(f, rootPath, None)
                if testTarget.isLib:
                    self._targets.append(testTarget)

        if len(self._targets) == 0:
            print('\n\n')
            self._log.write('No targets exist for: %s. Compilation aborted.' %
                            targetPackageOrPath)
            print('\n')
Beispiel #3
0
 def __init__(self, template, rootPath, data =None, logger =None, minify =False, source =None):
     """Creates a new instance of ClassTemplate."""
     self._template = template
     self._data     = data if data else dict()
     self._error    = None
     self._minify   = minify
     self._errorMsg = ''
     self._rootDir  = rootPath
     self._result   = None
     self._source   = source
     self._log      = logger if logger else Logger(self)
Beispiel #4
0
    def __init__(self, contextRunner, socketHandler):
        """Creates a new instance of SystemSocketDaemon.

        @@@param contextRunner:DaemonRunner
            The running context that wraps this execution within a systemd service or orphan daemon.
        """
        SystemDaemon.__init__(self, contextRunner,
                              Logger(socketHandler.__name__))

        self._server = None
        self._socketHandler = socketHandler
        self._socket = os.path.join(self.SOCKET_ROOT_PATH,
                                    contextRunner.uid + '.sock')
Beispiel #5
0
    def getLogger(logIdentifier,
                  kwargs=None,
                  args=None,
                  index=None,
                  name='logger',
                  extract=False,
                  trace=None):
        if extract:
            res = ArgsUtils.extract(name, None, kwargs, args, index)
        else:
            res = ArgsUtils.get(name, None, kwargs, args, index)

        if res is None:
            from pyaid.debug.Logger import Logger
            res = Logger(logIdentifier)

        if trace is not None:
            res.trace = trace

        return res
Beispiel #6
0
 def getLogger(cls):
     """getLogger doc..."""
     return Logger(cls, printOut=False, logFolder=cls.LOG_PATH)
Beispiel #7
0
    def __init__(self, request, client_address, server):
        self._log = Logger(self)
        self._log.write('Socket handler created')

        SocketServer.StreamRequestHandler.__init__(self, request,
                                                   client_address, server)
Beispiel #8
0
 def __init__(self, compileCoffee=False):
     self._log = Logger('IncludeCompressor')
     self._compileCoffee = compileCoffee
Beispiel #9
0
class NimbleEnvironment(object):
    """A class for..."""

    #===================================================================================================
    #                                                                                       C L A S S

    # Default flags sent with client requests to nimble server
    CONNECTION_FLAGS = 0x00000000

    SERVER_HOST = None
    CONNECTION_HOST = None

    # When true NimbleRemoteScripts are run in the remote environment by default instead of
    # within Maya. Makes it possible to debug without reloading Maya's Python interpreter for
    # each change. Disable when running in production.
    TEST_REMOTE_MODE = False

    # Enables gzip compression of the communication to and/or from the nimble server
    ENABLE_COMPRESSION = False

    # Size of a single chunk of data sent over the socket during communication. Larger messages
    # are broken into multiple chunks of sizes less than or equal to this length
    SOCKET_CHUNK_SIZE = 8192

    # Number of times socket calls should be attempted before returning in failure
    REMOTE_RETRY_COUNT = 3

    # Termination string used to identify the end of a nimble message
    TERMINATION_IDENTIFIER = '#@!NIMBLE_MSG_ENDS!@#'

    # Dictionary key in remote script file's globals() that contain the payload to be returned
    # to the remote Nimble environment once script execution is complete
    REMOTE_RESULT_KEY = '__nimbleRemoteResponse__'

    # Dictionary key in remote script file's globals() that contain the arguments send by the
    # remote Nimble environment when the script file action is requested
    REMOTE_KWARGS_KEY = '__nimbleRemoteKwargs__'

    # Error key within the REMOTE_RESULT dictionary in remote scripts that contains an error
    # message for the remote execution. When this key is set the NimbleResultData is set to failure
    # and the error message included in the result
    REMOTE_RESULT_ERROR_KEY = '__nimbleRemoteError__'
    REMOTE_RESULT_WARNING_KEY = '__nimbleRemoteWarning__'

    logger = Logger('nimble', printOut=True)

    _inMaya = None
    _mayaPort = 7800
    _externalPort = 7801

    _logLevel = 0
    _mayaUtils = None
    _connectionLifetime = 10

    #===================================================================================================
    #                                                                                   G E T / S E T

    @ClassGetter
    def CONNECTION_LIFETIME(cls):
        return cls._connectionLifetime

    @ClassGetter
    def SOCKET_RESPONSE_CHUNK_SIZE(cls):
        return 200 if cls.isWindows else cls.SOCKET_CHUNK_SIZE

    @ClassGetter
    def isWindows(cls):
        return sys.platform.startswith('win')

#===================================================================================================
#                                                                                     P U B L I C

    @classmethod
    def inMaya(cls, override=None):
        if override is not None:
            cls._inMaya = override

        if cls._inMaya is not None:
            return cls._inMaya

        if os.name == 'posix':
            pattern = re.compile('/(M|m)aya20[0-9]*/Maya.app')
        else:
            pattern = re.compile('[\\/]+(M|m)aya20[0-9]*[\\/]+Python')
        if pattern.search(sys.prefix):
            try:
                # noinspection PyUnresolvedReferences
                from maya import utils as mu
                cls._mayaUtils = mu
                cls._inMaya = True
            except Exception as err:
                cls._inMaya = False
            return cls._inMaya

        return cls._inMaya

    @classmethod
    def logError(cls, *args, **kwargs):
        isInMaya = cls.inMaya() and cls._mayaUtils is not None
        if isInMaya and not threading.currentThread().name.lower(
        ) == 'mainthread':
            execution.executeWithResult(cls._logError, *args, **kwargs)
        else:
            cls.logger.writeError(*args, **kwargs)

    @classmethod
    def log(cls, message):
        isInMaya = cls.inMaya() and cls._mayaUtils is not None
        if isInMaya and not threading.currentThread().name.lower(
        ) == 'mainthread':
            execution.executeWithResult(cls._logMessage, message)
        else:
            cls._logMessage(message)

    @classmethod
    def getServerLogLevel(cls):
        return cls._logLevel

    @classmethod
    def setServerLogLevel(cls, level=0):
        cls._logLevel = level
        return cls._logLevel

    @classmethod
    def getServerPort(cls, inMaya=None):
        return cls._mayaPort if cls.inMaya(
            override=inMaya) else cls._externalPort

    @classmethod
    def getServerHost(cls):
        return cls.SERVER_HOST if cls.SERVER_HOST else 'localhost'

    @classmethod
    def getConnectionPort(cls, inMaya=None):
        return cls._externalPort if cls.inMaya(
            override=inMaya) else cls._mayaPort

    @classmethod
    def getConnectionHost(cls):
        return cls.CONNECTION_HOST if cls.CONNECTION_HOST else 'localhost'

#===================================================================================================
#                                                                               P R O T E C T E D

    @classmethod
    def _logMessage(cls, *args, **kwargs):
        cls.logger.write(*args, **kwargs)

    @classmethod
    def _logError(cls, *args, **kwargs):
        cls.logger.writeError(*args, **kwargs)
Beispiel #10
0
def runPythonExec(script, kwargs=None):
    from nimble.NimbleEnvironment import NimbleEnvironment
    from nimble.data.NimbleResponseData import NimbleResponseData
    from nimble.data.enum.DataKindEnum import DataKindEnum

    try:
        nimble.cmds.undoInfo(openChunk=True)
    except Exception as err:
        return False

    try:
        # Create a new, temporary module in which to run the script
        module = imp.new_module('runExecTempModule')

        # Initialize the script with script inputs
        setattr(module, NimbleEnvironment.REMOTE_KWARGS_KEY,
                kwargs if kwargs is not None else dict())
        setattr(module, NimbleEnvironment.REMOTE_RESULT_KEY, dict())

        # Executes the script in the new module
        exec_(script, module.__dict__)

        # Find a NimbleScriptBase derived class definition and if it exists, run it to populate the
        # results
        for name, value in Reflection.getReflectionDict(module).iteritems():
            if not inspect.isclass(value):
                continue

            if NimbleScriptBase in value.__bases__:
                getattr(module, name)().run()
                break

        # Retrieve the results object that contains all results set by the execution of the script
        result = getattr(module, NimbleEnvironment.REMOTE_RESULT_KEY)
    except Exception as err:
        logger = Logger('runPythonExec', printOut=True)
        logger.writeError('ERROR: Failed Remote Script Execution', err)
        result = NimbleResponseData(
            kind=DataKindEnum.PYTHON_SCRIPT,
            response=NimbleResponseData.FAILED_RESPONSE,
            error=str(err))

    # If a result dictionary contains an error key format the response as a failure
    try:
        errorMessage = ArgsUtils.extract(
            NimbleEnvironment.REMOTE_RESULT_ERROR_KEY, None, result)
        if errorMessage:
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_SCRIPT,
                response=NimbleResponseData.FAILED_RESPONSE,
                error=errorMessage,
                payload=result)
    except Exception as err:
        pass

    try:
        nimble.cmds.undoInfo(closeChunk=True)
    except Exception as err:
        return False

    return result
Beispiel #11
0
 def __init__(self):
     """Creates a new instance of ClassTemplate."""
     self._type = None
     self._src  = None
     self._log  = Logger('DataFormatConverter')
     self._path = None
Beispiel #12
0
    printResult(u'Interpreter', u'PASSED')

# Check for PyAid
try:
    from pyaid.ArgsUtils import ArgsUtils
    printResult(u'PyAid', u'PASSED')
except Exception, err:
    printResult(u'PyAid', u'FAILED')
    print u'Unable to continue without PyAid'
    raise err

from pyaid.debug.Logger import Logger
from pyaid.file.FileUtils import FileUtils
from pyaid.system.SystemUtils import SystemUtils

logger = Logger('environmentCheck', printOut=True)

# Check for Qt 4.X
foundLocation = None
for p in os.listdir(u'/usr/local/'):
    if p.startswith(u'Qt4.'):
        foundLocation = p
printResult(
    u'Qt (%s)' % (foundLocation if foundLocation else u'4.x'),
    u'PASSED' if foundLocation else u'FAILED' )

# Check for PySide system dynamic libraries
paths = []
for p in os.listdir(u'/usr/lib'):
    if p.endswith(u'.dylib') and p.startswith(u'libpyside-'):
        paths.append(p)