environment.py 11.8 KB
Newer Older
Maude Le Jeune's avatar
Maude Le Jeune committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
## Copyright (C) 2008, 2009, 2010 APC LPNHE CNRS Universite Paris Diderot <lejeune@apc.univ-paris7.fr>  <betoule@apc.univ-paris7.fr>
## 
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, see http://www.gnu.org/licenses/gpl.html

import os.path as path
import subprocess
import threading
from glob import glob
from datetime import datetime
import logging
from utils import str_web
from contextlib import closing
import cPickle as pickle
from pipelet.utils import init_logger

class NullHandler(logging.Handler):
    """ Extension of the logging handler class. 
    """
    def emit(self, record):
        """ Avoid warnings. 
        """
        pass



class EnvironmentBase():
    """ Basic segment's facilities.
    
    An environment contains all segment's facilities provided to the
    user. The base class is almost empty, and should be extended to
    define a completely new environment. The default class can be
    extended to complete the default environment with new utilities.
    """

    

    def __init__(self, w):
        """ Initialize the base environment with task input. 
        
        Parameters
        ----------
        w: a worker instance
        """
Maude Le Jeune's avatar
Maude Le Jeune committed
55 56
        self._worker    = w
        self._seg_input = w.task.task_input
Maude Le Jeune's avatar
Maude Le Jeune committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

    def _get_data_fn(self, x):
        """ Complete the filename with the path to the working
        directory.
        
        Parameters
        ----------
        x: string, filename suffix
        
        Returns
        -------
        string, filename
        """
        return path.join(self._worker.pipe.get_data_dir(self._worker.task.seg, prod=self._worker.task.task_input), x)

    def _get_namespace(self):
        """ Prepare the namespace for a segment.

        Returns
        ------- 
        Dictionnary, namespace containing all the
        public methods of the class.
        
        """
81 82 83 84 85
        glo = {}
        for k in dir(self):
            if k[0] != "_":
                glo[k] = getattr(self, k)
        return glo
Maude Le Jeune's avatar
Maude Le Jeune committed
86 87 88 89 90
    
    def _get_log_file(self):
        """ Return the log file name
        
        """
91
        return self._get_data_fn("seg_"+self._worker.task.seg+".log")
Maude Le Jeune's avatar
Maude Le Jeune committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

    def _hook(self, hook_name, glo):
        """ Execute hook code.
        
        Search for an extra segment code file, and update dictionnary
        with the result of its execution.

        Parameters
        ----------
        hook_name: string, hook name
        glo: dict, global dictionnary to update. 
        
        """
        code = self._worker.pipe.repository.get_hook_string(self._worker.task.seg, hook_name)
        if code:
            exec(code, glo)
        else:
            print "No hook file named %s for seg %s"%(self._worker.task.seg,hook_name)
        
    
Maude Le Jeune's avatar
Maude Le Jeune committed
112 113 114 115 116 117 118 119
    def _close(self, glo):
        """ Return segment's output from dictionnary.

        Parameters
        ----------
        glo: segment execution dictionnary
        """
        return None
Maude Le Jeune's avatar
Maude Le Jeune committed
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

class Environment(EnvironmentBase):
    """ Default segment's facilities.

    The default environment contains some basic utilities related to : 
    - filename
    - parameters
    - sub process
    
    The default environment can be extended to complete the
    default environment with new utilities.
    """

    def __init__(self, w):
        """ Initialize the base environment with task input. 
        
        Parameters
        ----------
        w: a worker instance
        """
        self._worker = w
141
        self.seg_input = w.task.task_input
Maude Le Jeune's avatar
Maude Le Jeune committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        ## list of temporary files
        self._tmpf   = []
        self.logger = init_logger (self._get_data_fn(""), self._get_log_file(), level=[])


    def get_data_fn(self, x):
        """ Complete the filename with the path to the working
        directory.
        
        Parameters
        ----------
        x: string, filename suffix
        
        Returns
        -------
        string, filename
        """
        return self._get_data_fn(x)

    
    def hook(self, hook_name, glo):
        """ Execute hook code.
        
        Search for an extra segment code file, and update dictionnary
        with the result of its execution.

        Parameters
        ----------
        hook_name: string, hook name
        glo: dict, global dictionnary to update. 
        
        """
174
        self.logger.info ("hooking %s"%hook_name)
Maude Le Jeune's avatar
Maude Le Jeune committed
175 176 177
        return self._hook(hook_name, glo)
    
    
178
    
Maude Le Jeune's avatar
Maude Le Jeune committed
179 180 181 182 183 184 185 186 187 188 189 190 191
    def glob_seg(self, x, y):
        """ Return the list of filename matching y in the working
        directory of segment x.
        
        Parameters
        ----------
        x: string, segment name
        y: string, regexp of file to glob. 

        Returns
        -------
        list of filenames. 
        """
192
        
Maude Le Jeune's avatar
Maude Le Jeune committed
193
        segx = self._worker.pipe.find_seg(self._worker.task.seg, x)
194 195
        if segx is None:
            self.logger.warning("No parent segment matching %s found"%x)
Maude Le Jeune's avatar
Maude Le Jeune committed
196 197 198 199
        return glob(path.join(self._worker.pipe.get_data_dir(segx),y))\
            +glob(path.join(self._worker.pipe.get_data_dir(segx),path.join('*/',y)))

    
Betoule Marc's avatar
Betoule Marc committed
200
    def logged_subprocess(self, args, shell=False, except_on_failure=True):
Maude Le Jeune's avatar
Maude Le Jeune committed
201 202 203 204 205 206 207
        """ Execute a subprocess and log its output.
        
        Create files process_name.log and process_name.err
        
        Parameters
        ----------
        args: a Task argument
208
        shell: If set to True, the command is run via a shell
Betoule Marc's avatar
Betoule Marc committed
209
        except_on_failure: If set to True, raise an exception when command execution return non zero
Maude Le Jeune's avatar
Maude Le Jeune committed
210 211 212 213 214 215
        
        Returns
        -------
        tuple (outputfile, errorfile)
        """
        proc = args[0]
216 217
        of = self.get_data_fn(proc+'.log')
        ef = self.get_data_fn(proc+'.err')
Maude Le Jeune's avatar
Maude Le Jeune committed
218 219 220 221
        o = file(of,'w')
        e = file(ef,'w')
        o.write('#'+' '.join([str(a) for a in args])+'\n')
        o.flush()
222 223
        p=subprocess.Popen(args, stdout=o, stderr=e, shell=shell)
        p.communicate()[0]
Betoule Marc's avatar
Betoule Marc committed
224
        if except_on_failure:
225 226
            if p.returncode != 0:
                raise subprocess.CalledProcessError(p.returncode, args[0])
Maude Le Jeune's avatar
Maude Le Jeune committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        o.close()
        e.close()
        return (of, ef)

    
    def get_tmp_fn(self):
        """ Obtain a temporary filename
        
        Note : has to be part of the segment execution environment
        The temporary file is added to the intern list for future removal. 

        Returns
        -------
        string, temporary filename. 
        """
        tf = path.join(self._worker.work_dir, str(datetime.now().toordinal()))
        self._tmpf.append(tf)
        return tf

    
    def load_param(self, seg,glo,param_name='*'):
        """ Update the global dictionnary with parameters of a
        segment.
        
        Parameters
        ----------
        seg : string, segment name
        glo : dict, the global dictionnary
        param_name : string list, parameters name. 
        """
        segx = self._worker.pipe.find_seg(self._worker.task.seg, seg)
258 259
        if segx is None:
            self.logger.warning("No parent segment matching %s found"%seg)
Maude Le Jeune's avatar
Maude Le Jeune committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
        if not path.exists(self._worker.pipe.get_param_file(segx)):
            return
        self.load_products(self._worker.pipe.get_param_file(segx), glo, param_name=param_name)

    
    def save_products(self, filename, glo, param_name='*'):
        """ Use pickle to save a part of a given namespace.
        
        Parameters
        ----------
        filename : string, save in this filename.
        glo : dict, the namespace.
        param_name : string list, name of objects to save. If '*' save
        everything in the dictionnary.
        """
        new_dict = {}
        if param_name == '*':
            param_name = glo.keys()
        for k in param_name:
            try:
                new_dict[k] = glo[k]
            except KeyError:
282
                logger.warning('Fail to save object %s in file %s'%(k,filename))
Maude Le Jeune's avatar
Maude Le Jeune committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
        f = file(filename,'w')
        pickle.dump(new_dict,f)
        f.close()
        
    def load_products(self, filename, glo, param_name='*'):
        """ Update a namespace by unpickling requested object from the
        file.
        
        Parameters
        ----------
        filename: string, the pickle filename.
        glo : dict, the namespace to update.
        param_name : string list, names of object to unpickle. If '*',
        everything from the file is loaded.
        """
        try:
            f = file(filename)
            new_dict  = pickle.load(f)
            f.close()
        except IOError:
303
            logger.warning('No such file: %s'%filename)
Maude Le Jeune's avatar
Maude Le Jeune committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
        except UnpicklingError:
            logger.warning('Failed to unpickle from file: %s'%filename)
            f.close()
        if param_name == '*':
            param_name = new_dict.keys()
        for k in param_name:
            try:
                glo[k] = new_dict[k]
            except KeyError:
                logger.warning( 'Fail to load object %s from file %s'%(k,filename) )

    
    def clean_tmp(self):
        """ Delete the list of tmp file created by a segment
        """
        for e in self._tmpf:
            subprocess.Popen(['rm', e]).communicate()[0]
        self._tmpf = []


324
    def _make_tag(self, seg, glo):
Maude Le Jeune's avatar
Maude Le Jeune committed
325 326 327 328 329 330 331 332 333 334 335 336
        """ Write a tag using parameters of a segment. 
        
        Parameters
        ----------
        seg : string, segment name
        glo : dict, the global dictionnary

        Returns
        -------
        string. 
        """
        try:
337
            var_tag = glo['lst_tag']
Maude Le Jeune's avatar
Maude Le Jeune committed
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        except KeyError:
            var_tag = []
        strtag = ''
        for param in var_tag:
            if param in glo:
                strtag = strtag + param + '=' + str_web(glo[param])+'    '
            else:
                logger.warning( 'parameter '+param+' not in dictionary')
        var_tag = strtag + ' <small>(<b>'+ datetime.today().strftime("%e %m - %R")+'</b>)</small>   '
        fn = self._worker.pipe.get_meta_file(seg)
        with closing(file(fn, 'r')) as f:
            d = pickle.load(f)
        d['param'] = var_tag
        with closing(file(fn, 'w')) as f:    
            r = pickle.dump(d,f)
        return var_tag


356
    def _save_param(self, seg, glo,param_name='*'):
Maude Le Jeune's avatar
Maude Le Jeune committed
357 358 359 360 361 362 363 364 365 366 367 368 369
        """ Save parameters of a segment.
        
        Parameters
        ----------
        seg : string, segment name
        glo : dict, the global dictionnary
        param_name : string list, parameters name. 
        """
        if path.exists(self._worker.pipe.get_param_file(seg)):
            return
        self.save_products(self._worker.pipe.get_param_file(seg),glo, param_name=param_name)


Maude Le Jeune's avatar
Maude Le Jeune committed
370
    def _close(self, glo):
Maude Le Jeune's avatar
Maude Le Jeune committed
371 372 373 374 375 376 377
        """ Close environment. 

        This routine performs post processing like saving tag,
        parameters, etc.

        Parameters
        ----------
378 379
        glo : dict, the global dictionnary
        seg : string, segment name
Maude Le Jeune's avatar
Maude Le Jeune committed
380
        """
Maude Le Jeune's avatar
Maude Le Jeune committed
381
        seg = self._worker.task.seg
Maude Le Jeune's avatar
Maude Le Jeune committed
382 383
        self.clean_tmp()
        try: # Save params
384 385
            var_key = glo['lst_par']
            self._save_param(seg, glo, param_name=var_key)
Maude Le Jeune's avatar
Maude Le Jeune committed
386 387 388 389 390
        except KeyError:
            self.logger.warning( 'Nothing to save in param file for seg %s' % seg)
        except Exception:
            self.logger.warning( 'Fail to save the param file for seg %s' % seg)

391
        self._worker.task.param = self._make_tag(seg, glo)
Maude Le Jeune's avatar
Maude Le Jeune committed
392
        try:
393
            res = glo["seg_output"]
Maude Le Jeune's avatar
Maude Le Jeune committed
394
        except:
395
            res = []
396
            self.logger.info("No segment output found, setting seg_output to None")
Maude Le Jeune's avatar
Maude Le Jeune committed
397
        return  res