GBSManager.py

Go to the documentation of this file.
00001 import os
00002 import re
00003 import sys
00004 
00005 from GBSConfig import GetConfigValue
00006 from GBSLogger import Log, logger 
00007 from GBSObject import GBSObject
00008 from GBSModelRegistry import GetModelRegistry
00009 from schema_migrator import migrate
00010 
00011 class GBSManager(GBSObject) :
00012 
00013     """Top level object from which to create, list and destroy Tasks.
00014 
00015     This class inherits from GBSObject and adds the following user callable methods
00016       
00017     """
00018 
00019     ######  GBSObject inherited responsibilities   ###### 
00020       
00021 
00022     # Note that for this top level object: parent = None, model = 'default' and model_args = {}
00023     def __init__(self,name,parent,model,model_args):
00024         self.__schemaVersion      = 0    # Incremented each time the schema changes (See schema_migrator.py)
00025         self.__taskManagers       = {}   # Volatile: Hash name -> Task
00026         self.__taskManagersModels = {}   # Volatile: Hash name -> Task models
00027         
00028         GBSObject.__init__(self,name,parent,model)
00029 
00030         self.MakeChildDirectory()
00031         self.__ReloadChildren()
00032 
00033         # Migrate schema
00034         migrate(self)
00035         
00036         # Perform any house-keeping chores.
00037         self.__HouseKeeping()
00038         
00039     def _DoMemberIO(self,ioh):
00040         self.__schemaVersion = ioh("+Schema Version","i",self.__schemaVersion)
00041         GBSObject._DoMemberIO(self,ioh)
00042 
00043     def WriteFamily(self):
00044         self.Write()
00045         for task_name,task in self.__taskManagers.iteritems():task.WriteFamily()
00046 
00047     def GetType(self):          return "GBSManager"
00048 
00049     def __repr__(self) :
00050         return GBSObject.__repr__(self) + "\n"\
00051                + "Schema version " + str(self.__schemaVersion) + "\n"\
00052                + "Managing " + str(len(self.__taskManagers)) + " Tasks"
00053 
00054     
00055     ######  User Callable Methods (Getters then Setters)  ###### 
00056 
00057     def GetTask(self,name) :
00058 
00059         """Retrieve existing Task e.g. task = manager.GetTask("Fred")"""
00060         
00061         if not self.__taskManagers.has_key(name):
00062             print "Sorry, there is no Task named " + str(name)
00063             return None
00064         else : return self.__taskManagers[name]
00065 
00066     def ListModels(self):
00067 
00068         """List all available models"""
00069 
00070         print "The following models are available:-\n"
00071         reg = GetModelRegistry().GetRegistry()
00072         for m_name,m in reg.iteritems():
00073             print "Model: " + m_name
00074             print "*"*(len(m_name)+7) + "\n"
00075             print "Title:" + m.GetTitle() + "\nDescription:"
00076             print m.GetDescription()
00077 
00078     def ListTasks(self):
00079 
00080         """List all existing Tasks"""
00081         
00082         print "The following tasks are setup up:-\n"
00083         first = 1
00084         for task_name,task in self.__taskManagers.iteritems():
00085             if first:
00086                 print task.AsString("Heading") + "\n"
00087                 first = 0
00088             print task.AsString("Brief")
00089 
00090     def GetSchemaVersion(self):
00091 
00092         """Return current schema version number."""
00093 
00094         return self.__schemaVersion
00095 
00096     def AddTask(self,task_name,model_name="default"):
00097 
00098         """Create a new Task called task_name using model model_name e.g. task = manager.AddTask("Joe","default")"""
00099         
00100         #  Check that the name is legal and not already in use.
00101         if re.search(r"[^a-zA-Z0-9_\-]",task_name):
00102             print "Sorry, '" + str(task_name) + "' is an illegal task name (characters other than alphanumeric, '_' and '-')"
00103             return
00104         if self.__taskManagers.has_key(task_name):
00105             print "Sorry, there already is a Task named " + str(task_name)
00106             return None
00107 
00108         #  Check the model is valid
00109         model_name_valid = 0
00110         reg = GetModelRegistry().GetRegistry()
00111         for m_name,m in reg.iteritems():
00112             if model_name == m_name: model_name_valid = 1
00113         if not model_name_valid:
00114             print "Sorry %s is not a valid model, the following are available:-" % model_name
00115             for m_name,m in reg.iteritems():
00116                 print "  " + m_name.ljust(15) + m.GetTitle()
00117             return None        
00118         tm = GetModelRegistry().CreateObject(model_name,"Task",task_name,self)
00119         self.__taskManagers[task_name]       = tm
00120         self.__taskManagersModels[task_name] = model_name
00121         return tm
00122             
00123     ######  Private Methods (not user callable)  ######
00124 
00125     def __HouseKeeping(self):
00126         """Perform start up house-keeping chores."""
00127 
00128         chores = GetConfigValue("HouseKeepingCommands")
00129         if ( chores ):
00130             print "Manager performing start of job house-keeping:-"
00131             for chore in chores.split(' ;'):
00132                 print "  %s " % chore
00133                 exit_code = os.system(chore)
00134                 if exit_code: print "   - command failed with exit code %d" % exit_code
00135             
00136     def __ReloadChildren(self):
00137 
00138         """Reload child Tasks from disk.
00139 
00140         Loop over all *.state files, read their model name and then recreate."""
00141 
00142         import os, re
00143 
00144         child_dir         = self.GetStoreLocation("child_dir")
00145         child_state_files = os.listdir(child_dir)
00146         for child_state_file in child_state_files:
00147 
00148             #  Only look at *.state files
00149             child_state_file_spec = child_dir + "/" + child_state_file
00150             if not os.path.isfile(child_state_file_spec): continue
00151             mo = re.search(r"^(.*)\.state$",child_state_file)
00152             if not mo: continue
00153             child_name = mo.group(1)
00154 
00155             #  Have to sneak a look at the child's state file to get the model.
00156             #  This is the one case where the parent's model may not be the same
00157             #  as the child's; Manager is always the "default" model
00158             child_model = ""
00159             f = open(child_state_file_spec)
00160             for line in f:
00161                 mo = re.search(r"Model Name:\s*(\S+)",line)
00162                 if mo: child_model = mo.group(1)
00163             f.close()
00164             
00165             if not child_model:
00166                 Log(self,logger.ERROR,"GBSManager: Cannot find model for Task in " + str(child_state_file_spec))
00167                 continue
00168             self.AddTask(child_name,child_model)
00169 
00170     def _SetSchemaVersion(self,ver):
00171 
00172         """Set current schema version number."""
00173 
00174         self.__schemaVersion = ver
00175         self.Write()

Generated on Fri Mar 5 09:25:41 2010 for gbs by  doxygen 1.4.7