This file is indexed.

/usr/lib/python2.7/dist-packages/asrun/run.py is in code-aster-run 1.13.1-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
# -*- coding: utf-8 -*-

# ==============================================================================
# COPYRIGHT (C) 1991 - 2003  EDF R&D                  WWW.CODE-ASTER.ORG
# 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 2 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, WRITE TO EDF R&D CODE_ASTER,
#    1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
# ==============================================================================

"""
Definition of AsterRun class.
"""

import sys
import os
import os.path as osp
import re
import time
import getpass
import traceback
import pprint
from ConfigParser import SafeConfigParser, NoOptionError
from optparse import OptionGroup
from warnings import warn

from asrun.core          import magic, RunAsterError
from asrun.common.i18n   import _
from asrun.mystring      import print3, convert_list, to_unicode, ufmt
from asrun.parser        import (define_parser, default_options, get_option_value,
                                SUPPRESS_HELP)
from asrun.timer         import AsterTimer
from asrun.common.rcfile import read_rcfile
from asrun.installation  import aster_root, confdir, localedir
from asrun.thread        import is_main_thread, TaskAbort
from asrun.common.sysutils import get_home_directory, local_host, local_full_host, get_exec_name
from asrun.common.utils  import get_subdirs, get_unique_id
from asrun.common_func   import get_limits

from asrun.backward_compatibility import bwc_config_rc, bwc_deprecate_class


class AsterRun:
    """Main class to manage execution.
    """

    def __init__(self, **kwargs):
        """Initializations"""
        self.ExitOnFatalError = True
        self.PrintExitCode    = True
        self.__initialized    = False
        self._val_pid         = 0
        self.rcdir = kwargs.get('rcdir')
        # ----- verification de la version de Python
        if sys.hexversion < 0x020600F0:
            print3(_(u"This script requires Python 2.6 or higher, sorry !"))
            self.Sortie(4)

        # ----- package informations
        from asrun.__pkginfo__ import version, copyright
        self.program     = 'as_run'
        self.__version__ = version

        # ----- options, liste des options du parser à stocker dans options
        self.options = default_options
        # always use _add_option to extend options_list
        self.options_list = ['debug', 'verbose', 'silent', 'force', 'num_job',
            'debug_stderr', 'stdout', 'stderr', 'log_progress',
            'remote_shell_protocol', 'remote_copy_protocol']

        # ----- informations about actions : module, method
        # always use set_action to define a new action
        self.actions_info = {}
        # store current action
        self.current_action = ''

        # ----- user preferences and defaults
        self.user_vars = {
            'editor' :
                {  'val'  : 'nedit',
                   'help' : _(u'editor command') },
            'devel_server_user' :
                {  'val'  : '',
                    'help' : _(u'login on the development server') + os.linesep + \
                    _(u'# (name/ip address is usually set in /etc/codeaster/asrun)') },
        }

        # ----- formats
        self.fmt = {
            'usage'     : u'   - %s :'+os.linesep+'      %s'+os.linesep,
            'verb1'     : u' %-15s = %s',
            'msg+cod'   : os.linesep+u'%-18s %s'+os.linesep,
            'msg_info'  : u'<INFO>%s %s',
            'silent'    : u'      %s %s',
            'title'     : os.linesep+u'-'*80+os.linesep+u'%s %s'+os.linesep,
            'diag'      : os.linesep+u'-'*60+os.linesep+\
                       u'--- DIAGNOSTIC JOB : %s'+\
                       os.linesep+'-'*60+os.linesep,
            'exit'      : os.linesep+u'EXIT_CODE='+'%d'
        }

        # ----- diagnostic
        self.diag = ''

        # ----- list of files/directories to delete on exit
        self.to_delete = []

        # ----- lists of text to print on exit depending on diagnostic
        # this allows to keep important messages when a lot of output is generated
        # and to print them once again at end
        self.print_on_exit = {}

        # ----- do not print timer info on exit by default
        self.timer = None
        self.print_timer = False

        # ----- parser
        self.parser = define_parser(self)

        # ----- user resource directory
        # if self.rcdir is set, it's supposed to start with ".astkrc_"
        # or to be an absolute directory name.
        # if it's an absolute pathname it may be unusable on the remote host
        if self.rcdir is None:
            self.rcdir = get_option_value(sys.argv, "--rcdir", default=".astkrc")
        assert self.rcdir.startswith(".astkrc") or osp.abspath(self.rcdir) == self.rcdir, \
            u"absolute path or similar to '.astkrc_xxx' expected not: %s" % self.rcdir

        # ----- read master configuration file and user preferences
        self.config = {}
        oldrc = osp.join(get_home_directory(), self.rcdir, 'config')
        bwc_config_rc(oldrc, self._read_rc)

        self.user_rc = osp.join(get_home_directory(), self.rcdir, 'prefs')
        self._read_rc(osp.join(confdir, 'asrun'), self.config, mcsimp=['noeud',])
        self._read_rc(osp.join(confdir, 'aster'), self.config, optional=True, mcsimp=['vers',])
        self._read_rc(osp.join(confdir, 'agla'),  self.config, optional=True)
        self._init_rc()

        # add user plugins directory
        sys.path.append(osp.join(get_home_directory(), self.rcdir))
        # ----- prepare tmp_user and cache_dir
        # no folder in cache_dir
        tmp_user = osp.join(self.config['rep_tmp'],
                'astk_'+getpass.getuser())
        self.config['tmp_user'] = tmp_user
        self.config['cache_dir'] = osp.join(tmp_user, 'cache')
        # safer as osp.exists for multiple executions
        try:
            os.makedirs(tmp_user)
        except OSError:
            pass
        if not os.access(tmp_user, os.W_OK):
            print3(ufmt(_(u'no write access to %s'), tmp_user))
            self.Sortie(4)

        # safer as osp.exists for multiple executions
        try:
            os.mkdir(self.config['cache_dir'])
        except OSError:
            pass

        # ----- check for 'flasheur'
        flash = osp.join(get_home_directory(), "flasheur")
        self.config['flasheur'] = flash
        # safer as osp.exists for multiple executions
        try:
            os.makedirs(flash)
        except OSError:
            pass
        if not os.access(flash, os.W_OK):
            print3(ufmt(_(u'no write access to %s'), flash))
            self.Sortie(4)

        # ----- init timer
        self.timer = AsterTimer()
        self.LoadExtensions()
        self.CheckExtensions()


    def ParseArgs(self):
        """Call the arguments parser, returns options and arguments."""
        opts, args = self.parser.parse_args()
        # ----- all should have been initialized !
        self.__initialized = True
        os.environ['ASTER_ROOT'] = aster_root

        # ----- stocke les options
        for option in self.options_list:
            self.options[option] = getattr(opts, option)

        if opts.display != None:
            os.environ['DISPLAY'] = opts.display
            self.DBG(u'set DISPLAY to', opts.display)

        # ----- migration
        if self.options['version_dev'] is not None:
            warn('--version_dev=... is deprecated. Use --vers=... instead.', DeprecationWarning, stacklevel=2)
            if self.options['aster_vers'] != self.options['version_dev']:
                warn('--vers=%s will be overwritten by --version_dev into --vers=%s' \
                 % (self.options['aster_vers'], self.options['version_dev']), DeprecationWarning, stacklevel=2)
            self.options['aster_vers'] = self.options['version_dev']

        args = [to_unicode(arg) for arg in args]
        return opts, args


    def _init_rc(self):
        """Read user preferences or create the file the first time"""
        ficrc = self.user_rc
        dname = osp.dirname(ficrc)
        # ----- check for ressources directory
        # safer as osp.exists for multiple executions
        try:
            os.makedirs(dname)
        except OSError:
            pass

        if not osp.isfile(ficrc):
            # create ressources file
            from asrun.client import ClientConfig
            try:
                client = ClientConfig(self.rcdir)
                client.init_user_resource(osp.basename(ficrc))
            except (OSError, IOError):
                # permission denied into rcdir
                pass
        if osp.isfile(ficrc):
            # read user ressource file if exists
            self._read_rc(ficrc, self.config, mcsimp=['vers', 'noeud'], optional=True)
        self._check_config()


    def _read_rc(self, ficrc, destdict, optional=False, mcsimp=None):
        """Read a ressource file and store variables to 'destdict'."""
        if osp.isfile(ficrc):
            read_rcfile(ficrc, destdict, mcsimp=mcsimp)
        elif not optional:
            print3(ufmt(_(u'file not found : %s'), ficrc))
            self.Sortie(4)


    def _check_config(self):
        """Check configuration for deprecated fields or arguments."""
        for key in ("editor", "editeur", "terminal"):
            value = self.config.get(key, None)
            # always used current display (eventually set by "ssh -X")
            if value and value.find('@D') > -1:
                warn("'%s' : the argument '@D' is deprecated. "
                     "Remove it from your configuration file." % key,
                     DeprecationWarning, stacklevel=2)
                # remove display
                self.config[key] = re.sub('\-+display[ =]+@D', '', value)


    def _add_action(self, action, info):
        """Set informations about an action
        Prefer use this method over extend manually the dictionnary."""
        if not type(action) in (str, unicode):
            self.Mess(_(u'invalid type (expect %s not %s)') % \
                    ('string', type(action)), '<F>_PROGRAM_ERROR')
        if not type(info) is dict:
            self.Mess(_(u'invalid type (expect %s not %s)') % \
                    ('dict', type(info)), '<F>_PROGRAM_ERROR')
        if action in self.actions_info.keys():
            self.Mess(_(u'action already defined : %s') % action,
                    '<F>_PROGRAM_ERROR')
        else:
            self.actions_info[action] = info


    def _add_option(self, *args):
        """Add one or more option which will be available through getitem.
        Prefer use this method over extending manually the list."""
        if not type(args) in (list, tuple):
            self.Mess(_(u'invalid type (expect %s not %s)') % \
                    ('string', type(args)), '<F>_PROGRAM_ERROR')
        for opt in args:
            if opt in self.options_list:
                self.Mess(_(u'option already defined : %s') % opt,
                    '<F>_PROGRAM_ERROR')
            else:
                self.options_list.append(opt)


    def LoadExtensions(self):
        """Initialisations des extensions."""
        import asrun.maintenance
        import asrun.execute
        import asrun.services
        import asrun.job
        import asrun.rex
        import asrun.bddetudes
        asrun.execute.SetParser(self)
        asrun.maintenance.SetParser(self)
        asrun.services.SetParser(self)
        asrun.job.SetParser(self)
        asrun.rex.SetParser(self)
        asrun.bddetudes.SetParser(self)


    def CheckExtensions(self):
        """Initialisations des éventuelles extensions."""
        user_extensions    = osp.join(get_home_directory(), self.rcdir, 'as_run.extensions')
        cwd_extensions     = 'as_run.extensions'
        config = SafeConfigParser()
        l_read = config.read([user_extensions, cwd_extensions])

        l_ext = config.sections()
        for extension in l_ext:
            try:
                filename = osp.splitext(config.get(extension, 'module'))[0]
                if self['verbose']:
                    print3(ufmt(_(u'Loading extension %s from %s...'), extension, filename))
                module = __import__(filename, globals(), locals(), ['SetParser'])
                init_function = getattr(module, 'SetParser')
                init_function(self)
                if self['verbose']:
                    print3(_(u'Extension %s loaded') % extension)
            except (ImportError, NoOptionError), msg:
                print3(_(u'Extension %s not loaded (reason : %s)') % (extension, msg))


    def SetActions(self, actions_descr, **dico):
        """Add new actions to the parser configuration
            actions_descr  : description of each action :
                key   = action name,
                value = {syntax, help, method}
        optional arguments :
            actions_order  : order to display actions in help (default to '' :
                arbitrary order of dico.keys method)
            group_options  : add a option group to list options (default to True)
            group_title    : title of the option group (default to '')
            actions_group_title : list actions names in the title between
                parenthesis (default to True)
            options_descr  : description of each option (default to {}) :
                key   = option name,
                value = {args, kwargs} passed to add_option parser method
            stored_options : list of options which should be available using
                getitem (default to all "dest" from options_descr)"""
        # ----- default values
        # actions_order
        if dico.has_key('actions_order'):
            lacts = dico['actions_order']
        else:
            lacts = actions_descr.keys()
            lacts.sort()
        # title
        if dico.has_key('group_title'):
            title = dico['group_title']+' ('
        else:
            title = ''
        # actions_group_title
        if not dico.has_key('actions_group_title'):
            dico['actions_group_title'] = True
        #  group_options
        if not dico.has_key('group_options'):
            dico['group_options'] = True
        # options_descr
        if not dico.has_key('options_descr'):
            dico['options_descr'] = {}
        # stored_options
        if not dico.has_key('stored_options'):
            dico['stored_options'] = [d.values()[1]['dest'] \
                    for d in dico['options_descr'].values()]
        # ----- check types
        # dict
        for obj in (actions_descr, dico['options_descr']):
            if not type(obj) is dict:
                self.Mess(_(u'invalid type (expect %s not %s)') % \
                        ('dict', type(obj)), '<F>_PROGRAM_ERROR')
        # list
        for obj in (lacts, dico['stored_options']):
            if not type(obj) is list:
                self.Mess(_(u'invalid type (expect %s not %s)') % \
                        ('list', type(obj)), '<F>_PROGRAM_ERROR')
        prem = True
        for act in lacts:
            descr = actions_descr[act]
            # ----- actions_info
            self._add_action(act, { 'method' : descr['method'] })
            # ----- parser
            if descr['help'] != SUPPRESS_HELP:
                new_usage = self.parser.get_usage()+ \
                    (self.fmt['usage'] % \
                        (descr['help'], u'as_run --'+act+' '+descr['syntax']))
                self.parser.set_usage(new_usage)
            self.parser.add_option('--'+act,
                    action='store_const_once', dest='action', const=act,
                    help=SUPPRESS_HELP)
            if not prem:
                title = title+', '
            prem = False
            title = title+('%r' % act)
        title = title+') '
        if not dico['actions_group_title']:
            title = dico['group_title']
        # ----- specific options
        if dico['group_options']:
            group = OptionGroup(self.parser, title=title)
            self.parser.add_option_group(group)
        else:
            group = self.parser
        for opt, descr in dico['options_descr'].items():
            group.add_option(*descr['args'], **descr['kwargs'])
        # ----- add options to the options list to store
        self._add_option(*dico['stored_options'])


    def PrintConfig(self):
        """Imprime la liste et la valeur des paramètres"""
        self.parser.print_version()
        print3(os.linesep+_(u'Parameters (config attribute)')+' :')
        for key, val in self.config.items():
            print3(self.fmt['verb1'] % (key, val))
        print3(os.linesep+_(u'Options (options attribute)')+' :')
        for key, val in self.options.items():
            print3(self.fmt['verb1'] % (key, val))


    def ToDelete(self, path):
        """Add 'path' to to_delete list."""
        if not path in self.to_delete:
            self.to_delete.append(path)


    def DoNotDelete(self, path):
        """Remove 'path' from to_delete list."""
        if path in self.to_delete:
            self.to_delete.remove(path)


    def _clear_tmp(self):
        """Empty cache directory if necessary (remove files for which last access
        is older than 'deltat' seconds), and delete all directories
        from 'self.to_delete'."""
        # to avoid to delete current directory (it may freeze some systems...)
        try:
            os.chdir(get_home_directory())
        except OSError:
            print3(_(u"Can not change to the home directory ('%s'). "
                      "Temporay files have not been deleted.") % get_home_directory())
            return
        ct = time.time()
        deltat = 24*3600
        # ----- config is not set during __init__
        if self.__initialized:
            if self['verbose']:
                print3(_(u'Clear cache directory')+' '+self['cache_dir']+'...')
            # ----- avoid deleting such folders : /, /usr or /home !!!
            if re.search('^/.+/.*', self['cache_dir']):
                for root, dirs, files in os.walk(self['cache_dir'], topdown=False):
                    for name in files:
                        if ct - os.stat(osp.join(root, name)).st_atime > deltat:
                            os.remove(osp.join(root, name))
                        for name in dirs:
                            try:
                                os.rmdir(osp.join(root, name))
                            except OSError:
                                pass
            # ----- delete each directory in list_dirs
            if self['verbose']:
                print3(_(u'Clear temporary files/directories'))
            # if a Delete system function has been added
            if hasattr(self, 'Delete'):
                to_del = [d for d in get_subdirs(self.to_delete) if d.startswith('/')]
                for d in to_del:
                    getattr(self, 'Delete')(d)


    def __getitem__(self, key):
        """Méthode pour accéder facilement aux paramètres de configuration ou à la
        valeur d'une option.
        Les options surchargent les paramètres de configuration."""
        UNDEF = "__undefined__"
        if hasattr(self, '__'+key+'__'):
            return getattr(self, '__'+key+'__')
        elif self.options.get(key, UNDEF) != UNDEF:
            return self.options[key]
        elif self.config.get(key, UNDEF) != UNDEF:
            return self.config[key]
        elif self.__initialized:
            self.Mess(_(u"""'%s' does not exist in config or options.
 Perhaps it must be defined in %s.""") % (key, self.user_rc), \
                    '<F>_PROGRAM_ERROR')


    def get(self, key, default=None):
        """Semblable à getitem avec la possibilité de retourner une valeur par défaut
        si la valeur n'est pas trouvée."""
        if hasattr(self, '__'+key+'__'):
            return getattr(self, '__'+key+'__')
        elif self.options.get(key) != None:
            return self.options[key]
        elif self.config.get(key) != None:
            return self.config[key]
        else:
            return default


    def get_pid(self, num=None):
        """Return a jobid based on self['num_job'].
        Counter is incremented at each call."""
        return get_unique_id(self['num_job'], num)


    def get_versions_dict(self):
        """Return a dict of the available versions indexed with their label.
        The versions are defined in etc/codeaster/aster + $HOME/.astkrc/prefs."""
        dict_vers = {}
        if self['vers']:
            for vname in self['vers'].split():
                if len(vname.split(':')) == 2:
                    key, vname = vname.split(':')
                else:
                    key = osp.basename(vname)
                if dict_vers.get(key) is not None:
                    self.Mess(_(u"%s is already known as %s (%s is ignored). Check your configuration file : %s") \
                        % (key, dict_vers[key], vname, osp.join(confdir, "aster")), "<A>_ALARM")
                    continue
                dict_vers[key] = vname
        return dict_vers

    def get_ordered_versions(self):
        """Return the version labels ordered as defined in the
        configuration files."""
        lv = []
        if self['vers']:
            for vname in self['vers'].split():
                if len(vname.split(':')) == 2:
                    key, vname = vname.split(':')
                else:
                    key = osp.basename(vname)
                if key not in lv:
                    lv.append(key)
        return lv

    def get_version_path(self, label, root=aster_root):
        """Return full path to the version named 'label'."""
        if not label:
            return None
        dict_vers = self.get_versions_dict()
        return osp.join(root, dict_vers.get(label, label))


    def PostConf(self):
        """Ajuste la configuration dynamiquement (car dépendance au contexte et
        pas seulement au fichier 'config').
        Paramètres déclenchants :
            serv_as_node, only_serv_as_node, limits"""
        if not self.__initialized or not hasattr(self, 'GetHostName'):
            print3(_(u'Warning : AsterRun object not ready for dynamic adjustement !'))
            return

        # add localhost as a compute node
        if self.config.get('serv_as_node', False):
            l_node = self.config.get('noeud', '').split()
            if not local_full_host in l_node and not local_host in l_node:
                l_node.insert(0, local_host)
            if self.config.get('only_serv_as_node', False):
                l_node = [local_host,]
            self.config['noeud'] = ' '.join(l_node)

        # hard limits
        self.SetAutoLimit()
        # trace installation parameter
        self.DBG(u'installation dirs (aster_root, confdir, localedir, LANG)',
                    aster_root, confdir, localedir, os.environ.get('LANG', 'undefined'))


    def SetAutoLimit(self):
        """Set memory & cpu limits.
        Must be called after the initialization of the system object."""
        dlim_i = get_limits(self, 'interactif')
        dlim_b = get_limits(self, 'batch')
        self.config.update(dlim_i)
        self.config.update(dlim_b)


    def GetGrav(self, cod):
        """Return the severity behind 'cod' as a number to allow comparison"""
        dgrav = { '?' : -9, '_' : -9, 'OK' : 0, 'A' : 1,
                'NOOK' : 2, 'NO_TEST_RESU' : -1,
                'S' : 4,
                'E' : 6, 'NO_RESU_FILE' : 6,
                'F' : 10 }
        g = dgrav['?']
        mat = re.search('<(.)>', cod)
        if cod in dgrav.keys():
            g = dgrav[cod]
        elif re.search('NOOK', cod):
            g = dgrav['NOOK']
        elif mat != None:
            try:
                g = dgrav[mat.group(1)]
            except KeyError:
                pass
        return g


    def Mess(self, msg, cod='', store=False):
        """Print a message sur stdout,
        'cod' is an error code (format "<.>_...")
            <E> : continue,
            <F> : stop,
            <A> : alarm, continue,
            '' or INFO : for an info,
            SILENT : like an info without <INFO> string,
            TITLE : add a separator.
        If cod='<F>' (without a description), if exists last <E> error is
        transformed into <F>, else <F>_ABNORMAL_ABORT.
        If store is True, 'msg' is stored in print_on_exit dictionnary."""
        # ----- gravite
        g0 = self.GetGrav(self.diag)
        g1 = self.GetGrav(cod)
        coderr = cod
        if cod == '<F>':
            if g0 < self.GetGrav('<E>'):
                coderr =  '<F>_ABNORMAL_ABORT'
            else:
                coderr = self.diag.replace('<E>', '<F>')
        if g1 >= self.GetGrav('<A>'):
            self.DBG(u'Warning or error raised :', '%s %s' % (cod, msg),
                        print_traceback=True)

        # ----- message
        if cod == '' or cod == 'INFO':
            fmt = self.fmt['msg_info']
            coderr = ''
        elif cod == 'SILENT':
            fmt = self.fmt['silent']
            coderr = ''
        elif cod == 'TITLE':
            fmt = self.fmt['title']
            coderr = ''
        else:
            fmt = self.fmt['msg+cod']
            # unknown flag
            if g1 == -9:
                coderr = '<I> '+coderr
        print3(ufmt(fmt, coderr, msg))
        magic.get_stdout().flush()
        # ----- store in print_on_exit
        if store or (not self.ExitOnFatalError and g1 >= self.GetGrav('<S>')):
            k = '?'
            msg2 = msg
            mat = re.search('<(.)>', cod)
            if mat != None and mat.group(1) in ('A', 'S', 'E', 'F'):
                k = mat.group(1)
                msg2 = self.fmt['msg+cod'] % (coderr, msg)
            elif cod in ('OK', 'NOOK'):
                k = cod
            self.print_on_exit[k] = self.print_on_exit.get(k, []) + [msg2, ]

        # ----- diagnostic le plus défavorable
        if g1 > g0:
            self.diag = coderr
            if g1 == self.GetGrav('<F>'):
                self.Sortie(4)


    def get_important_messages(self, reinit=False):
        """Return the important messages previously emitted."""
        titles = {
            '?'      : _(u'Important messages previously printed :')+os.linesep,
            'OK'     : _(u'Successful messages previously printed:')+os.linesep,
            'NOOK'   : _(u'NOOK messages previously printed:')+os.linesep,
            'A'      : _(u'<A> Alarms previously raised :')+os.linesep,
            'S'      : _(u'<S> errors previously raised :')+os.linesep,
            'E'      : _(u'<E> errors previously raised :')+os.linesep,
            'F'      : _(u'<F> errors previously raised :')+os.linesep,
        }
        msg = []
        for k, tit in titles.items():
            lmsg = self.print_on_exit.get(k, [])
            if len(lmsg) > 0:
                msg.append(self.fmt['title'] % (tit, ""))
                msg.extend(lmsg)
        if reinit:
            self.print_on_exit = {}
        return os.linesep.join(msg)


    def Sortie(self, exit_code):
        """Exit by printing diagnostic if defined or exit code if not null"""
        # print important messages
        msg = self.get_important_messages()
        if len(msg) > 0:
            print3(msg)

        # raise an exception to be catched by the Worker object
        if not is_main_thread():
            raise TaskAbort(msg)

        # helps to locate error in PROGRAM_ERROR case or in verbose mode
        if self.diag == '<F>_PROGRAM_ERROR' \
                or (exit_code != 0 and (self['debug'] or self['verbose'] or not self.ExitOnFatalError)):
            self.DBG(u'### Raise RunAsterError exception because of program error or debug mode ###')
            raise RunAsterError, exit_code

        # stop all timers
        if self.print_timer and hasattr(self, 'timer'):
            print3(os.linesep, self.timer)
        if self.print_timer: # related to non silent actions
            print3(self.program + ' ' + self.__version__)

        if self.diag:
            # change <E> to <F>
            self.diag = self.diag.replace('<E>', '<F>')
            print3(self.fmt['diag'] % self.diag)
        if self.PrintExitCode or exit_code != 0:
            print3(self.fmt['exit'] % exit_code)
        self._clear_tmp()
        self.DBG("exit %s" % exit_code)
        sys.exit(exit_code)


    def CheckOK(self, tole='<S>'):
        """Exit one error more severe than 'tole' occurred."""
        if self.GetGrav(self.diag) >= self.GetGrav(tole):
            self.Sortie(4)


    def ReinitDiag(self, diag='?'):
        """Reinitialize diagnostic (for example if a global diagnostic is stored)"""
        self.diag = diag


    def check_version_setting(self):
        """Check version is defined."""
        if not self.get('aster_vers'):
            self.parser.error(_(u"You must define 'default_vers' in 'aster' configuration " \
                                "file or use '--vers' option."))

    def _get_msecs(self):
        ct =  time.time()
        return (ct - long(ct)) * 1000


    def _printDBG(self, *args, **kargs):
        """Print debug information to stderr."""
        print_traceback = kargs.get('print_traceback', True)
        file            = kargs.get('file', magic.get_stderr())
        stack_id        = -3 - kargs.get('stack_id', 0)      # -1 : _printDBG, -2 : DBG ou ASSERT
        all             = kargs.get('all', False)
        prefix = kargs.get('prefix', '')
        try:
            form = """
>>> %(time)12s  %(orig)s
%(content)s%(traceback)s"""
            formTB = """
Traceback:
%s
"""
            stack = traceback.format_stack(limit=10)
            try:
                ls = []
                for a in args:
                    if type(a) in (str, unicode):
                        ls.append(a)
                    else:
                        ls.append(pprint.pformat(a))
                content = os.linesep.join(convert_list(ls))
                if not all and len(content) > 800:
                    content = content[:800] + os.linesep + '[...]'
            except None:
                content = str(args)
            if prefix:
                content = os.linesep.join([prefix + lin for lin in content.splitlines()])
            dinfo = {
                'time'      : time.strftime('%H:%M:%S') + '.%03d' % self._get_msecs(),
                'orig'      : stack[stack_id],
                'content'   : content,
                'traceback' : '',
            }
            try:
                mat = re.search('File [\'\"]*(.*?)[\'\"]*, *line ([0-9]+), *in (.*)', dinfo['orig'])
                dinfo['orig'] = '[%s@%s:%s]' % (mat.group(3), mat.group(1), mat.group(2))
            except None:
                pass
            if print_traceback:
                dinfo['traceback'] = formTB % (''.join(stack))
            print3(form % dinfo, file=file)
            file.flush()
        except None:
            pass


    def DBG(self, *args, **kargs):
        """Print debug information to stderr."""
        print_traceback = kargs.get('print_traceback', False)
        file            = kargs.get('file', magic.get_stderr())
        stack_id        = kargs.get('stack_id', 0)
        all             = kargs.get('all', False)
        prefix = kargs.get('prefix', '')
        if ((not hasattr(file, "isatty") or not file.isatty()) or self['debug'] or self['verbose']) \
                and (self['debug_stderr'] or file != sys.stderr):
            self._printDBG(print_traceback=print_traceback, file=file,
                           stack_id=stack_id, all=all, prefix=prefix, *args)

    def ASSERT(self, condition):
        """Print errors to stdout and stderr."""
        if not condition:
            for f in (magic.get_stdout(), magic.get_stderr()):
                self._printDBG(u'Assertion failed', print_traceback=True, file=f, stack_id=0)

    def get_as_run_cmd(self, with_args=True):
        """Return as_run command line (type list)."""
        cmd = [osp.join(aster_root, "bin", get_exec_name("as_run")),]
        if with_args:
            cmd.extend(self.get_as_run_args())
        return cmd

    def get_as_run_args(self):
        """Return arguments for as_run command line (type list)."""
        args = []
        args.extend(self.get_rcdir_arg())
        args.extend(self.get_remote_args())
        return args

    def get_rcdir_arg(self):
        """Return rcdir argument for as_run command line (type list)."""
        args = []
        if self.rcdir != ".astkrc":
            args.append("--rcdir=%s" % get_option_value(["--rcdir=%s" % self.rcdir], "--rcdir"))
        return args

    def get_remote_args(self):
        """Return remote arguments for as_run command line."""
        #XXX should be deprecated in future
        return ["--remote_shell_protocol=%s" % self['remote_shell_protocol'],
                "--remote_copy_protocol=%s" % self['remote_copy_protocol'],]


def AsRunFactory(*args, **kargs):
    """Initialization of an AsterRun object"""
    # pre 1.8 backward compatibility : astk_serv_root argument removed
    if len(args) != 0:
        warn('AsRunFactory : astk_serv_root argument is deprecated', DeprecationWarning, stacklevel=2)

    from asrun.system import AsterSystem

    run = AsterRun(**kargs)
    run.options['debug']   = False
    run.options['debug_stderr'] = True
    run.options['verbose'] = False
    run.options['force']   = False
    run.options['num_job'] = str(os.getpid())
    run.options['log_progress'] = None
    for opt, value in kargs.items():
        if run.options.has_key(opt):
            run.options[opt] = value
        elif run.config.has_key(opt):
            run.config[opt] = value
    run.system = AsterSystem(run, **kargs)
    run.print_timer = False
    run.SetAutoLimit()
    magic.run = run
    magic.init_logger(filename=run['log_progress'], debug=run['debug'])
    return run

ASTER_RUN = bwc_deprecate_class('ASTER_RUN', AsterRun)