# Path: pUtil.py
# def tolog(msg, tofile=True, label='INFO', essential=False):
#     """ Write date+msg to pilot log and to stdout """
# 
#     try:
#         import inspect
# 
#         MAXLENGTH = 12
#         # getting the name of the module that is invoking tolog() and adjust the length
#         try:
#             module_name = os.path.basename(inspect.stack()[1][1])
#         except Exception, e:
#             module_name = "unknown"
#             #print "Exception caught by tolog(): ", e,
#         module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH)
#         msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg)
# 
#         t = timeStampUTC(format='%Y-%m-%d %H:%M:%S')
#         if tofile:
#             appendToLog("%s|%s\n" % (t, msg))
# 
#         # remove backquotes from the msg since they cause problems with batch submission of pilot
#         # (might be present in error messages from the OS)
#         msg = msg.replace("`","'")
#         msg = msg.replace('"','\\"')
#         print "%s| %s" % (t, msg)
# 
#         # write any FAILED messages to stderr
#         if "!!FAILED!!" in msg:
#             try:
#                 print >> sys.stderr, "%s| %s" % (t, msg)
#             except:
#                 print "Failed to print to sys.stderr: %s" % (t, msg)
#     except:
#         print "!!WARNING!!4000!! %s" % traceback.format_exc()
# 
# Path: FileHandling.py
# def getExtension(alternative='pickle'):
#     """ get the file extension (json or whatever 'alternative' is set to, pickle by default) """
# 
#     try:
#         from json import load
#     except:
#         extension = alternative
#     else:
#         extension = "json"
# 
#     return extension


import os
import commands
from pUtil import tolog
from FileHandling import getExtension
                    from json import load
                from pickle import load
                from json import dump
                from pickle import dump
        from glob import glob

class JobState:
    """
    This class is used to set the current job state.
    When the job is running, the file jobState-<JobID>.[pickle|json]
    is created which contains the state of the Site, Job and Node
    objects. The job state file is updated at every heartbeat.
    """
    def __init__(self):
        """ Default init """
        self.job = None            # Job class object
        self.site = None           # Site class object
        self.node = None           # Node class object
        self.filename = ""         # jobState-<jobId>.[pickle|json]
        self.recoveryAttempt = 0   # recovery attempt number
        self.objectDictionary = {} # file dictionary holding all objects

    def decode(self):
        """ Decode the job state file """

        if self.objectDictionary:
            try:
                # setup the internal structure (needed for cleanup)
                self.job = self.objectDictionary['job']
                self.site = self.objectDictionary['site']
                self.node = self.objectDictionary['node']
            except:

# Path: pUtil.py
# def tolog(msg, tofile=True, label='INFO', essential=False):
#     """ Write date+msg to pilot log and to stdout """
# 
#     try:
#         import inspect
# 
#         MAXLENGTH = 12
#         # getting the name of the module that is invoking tolog() and adjust the length
#         try:
#             module_name = os.path.basename(inspect.stack()[1][1])
#         except Exception, e:
#             module_name = "unknown"
#             #print "Exception caught by tolog(): ", e,
#         module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH)
#         msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg)
# 
#         t = timeStampUTC(format='%Y-%m-%d %H:%M:%S')
#         if tofile:
#             appendToLog("%s|%s\n" % (t, msg))
# 
#         # remove backquotes from the msg since they cause problems with batch submission of pilot
#         # (might be present in error messages from the OS)
#         msg = msg.replace("`","'")
#         msg = msg.replace('"','\\"')
#         print "%s| %s" % (t, msg)
# 
#         # write any FAILED messages to stderr
#         if "!!FAILED!!" in msg:
#             try:
#                 print >> sys.stderr, "%s| %s" % (t, msg)
#             except:
#                 print "Failed to print to sys.stderr: %s" % (t, msg)
#     except:
#         print "!!WARNING!!4000!! %s" % traceback.format_exc()
# 
# Path: FileHandling.py
# def getExtension(alternative='pickle'):
#     """ get the file extension (json or whatever 'alternative' is set to, pickle by default) """
# 
#     try:
#         from json import load
#     except:
#         extension = alternative
#     else:
#         extension = "json"
# 
#     return extension


# Path: JobState.py
import os
import commands
from pUtil import tolog
from FileHandling import getExtension
                    from json import load
                from pickle import load
                from json import dump
                from pickle import dump
        from glob import glob


class JobState:
    """
    This class is used to set the current job state.
    When the job is running, the file jobState-<JobID>.[pickle|json]
    is created which contains the state of the Site, Job and Node
    objects. The job state file is updated at every heartbeat.
    """
    def __init__(self):
        """ Default init """
        self.job = None            # Job class object
        self.site = None           # Site class object
        self.node = None           # Node class object
        self.filename = ""         # jobState-<jobId>.[pickle|json]
        self.recoveryAttempt = 0   # recovery attempt number
        self.objectDictionary = {} # file dictionary holding all objects

    def decode(self):
        """ Decode the job state file """

        if self.objectDictionary:
            try:
                # setup the internal structure (needed for cleanup)
                self.job = self.objectDictionary['job']
                self.site = self.objectDictionary['site']
                self.node = self.objectDictionary['node']
            except:

                tolog("JOBSTATE WARNING: Objects are missing in the recovery file (abort recovery)")