This file is indexed.

/usr/share/pyshared/asrun/repart.py is in code-aster-run 1.13.1-1.

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
# -*- coding: utf-8 -*-
#pylint: disable-msg=R0902

# ==============================================================================
# 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.
# ==============================================================================

"""
Allow to manage jobs on several hosts according to the available
cpu and memory resources.
"""

import os
import traceback
from pprint import pprint, pformat

from asrun.common.i18n   import _
from asrun.mystring      import print3
from asrun.thread        import Lock, Task, Dispatcher
from asrun.system        import local_host
from asrun.common_func   import get_tmpname
from asrun.common.utils  import now
from asrun.common.rcfile import parse_config


_DBG_TRI   = False
_DBG_CRIT  = False
_DBG_ALLOC = False


def isnum(val):
    """Return True if `val` is a number."""
    return type(val) in (int, long, float)


# constants
NORESOURCE, ALLOCATED, OVERLIMIT = [9001, 9002, 9003]


class ResourceManagerError(Exception):
    """Local exception"""


class ResourceManager:
    """Class to manage resources to run a lot of calculations of several hosts.
    """
    lock = Lock()

    def __init__(self, hostinfo):
        """Initializations.
        """
        self.hostinfo = hostinfo.copy()
        self.all_hosts = self.hostinfo.keys()

        self.d_crit = {# numkey,   default, reverse order
            # criteria
            'cpurun' : ('000_cpurun',  0,     False, ),
            'memrun' : ('010_memrun',  0,     False, ),
            # characteristics of hosts (constant)
            'mem'    : ('101_mem',     0,     True,  ),
            'cpu'    : ('102_cpu',     0,     True,  ),
            'nomjob' : ('998_job',    '',     False, ),
            'host'   : ('999_host',   '',     False, ),
            'user'   : ('999_user',   '',     False, ),
        }
        self.l_crit = [(v[0], v[2]) for v in self.d_crit.values()]
        self.l_crit.sort()
        self.job_keys = [k for k, v in self.d_crit.items() if v[0] > '100_']
        # build the list of all infos
        self.infos = []
        self.limit = {}
        # to store host availability
        self.host_connection = {}
        for host, info in self.hostinfo.items():
            self.host_connection[host] = True
            info['host'] = host
            dico = {}
            for crit, val in self.d_crit.items():
                numkey, default, reverse = val
                dico[numkey] = info[crit] = info.get(crit, default)
                if numkey > '100_' and numkey < '900_' \
                and ( \
                    self.limit.get(crit) is None or (reverse and self.limit[crit] < dico[numkey]) \
                    or  (not reverse and self.limit[crit] > dico[numkey]) \
                ):
                    self.limit[crit] = dico[numkey]
            self.infos.append(dico)
        # to store job parameters
        self.history = {}

    def get(self, host, key, default=None):
        """Return a current value.
        """
        res = default
        if self.d_crit[key][0] > '100_':
            res = self.hostinfo[host][key]
        else:
            nkey = self.d_crit[key][0]
            for info in self.infos:
                if info['999_host'] == host:
                    res = info[nkey]
                    break
        return res

    def set(self, host, key, value):
        """Set a value.
        """
        done = False
        if self.d_crit[key][0] > '100_':
            raise ResourceManagerError, "can not be changed : '%s'" % key
        else:
            nkey = self.d_crit[key][0]
            for info in self.infos:
                if info['999_host'] == host:
                    info[nkey] = value
                    done = True
        if not done:
            raise ResourceManagerError, "can't set '%s'" % key

    def add(self, host, key, value):
        """Add 'value' to the current value.
        """
        current = self.get(host, key)
        self.set(host, key, current + value)

    def sub(self, host, key, value):
        """Substract 'value' to the current value.
        """
        current = self.get(host, key)
        self.set(host, key, current - value)

    def store_job(self, host='unknown', **kwjob):
        """Store 'kwjob' in history.
        """
        if host is None:
            return
        dico = kwjob.copy()
        dico['host'] = host
        dico['allocated'] = now(datefmt="%a")
        self.history[kwjob['nomjob']] = dico

    def get_job(self, jobname):
        """Get 'jobname' from history.
        """
        dico = self.history.get(jobname)
        if dico is None:
            return {}
        dico['released'] = now(datefmt="%a")
        return dico.copy()

    def get_history(self):
        """Return a copy of the jobs's 'history'.
        """
        dico = self.history.copy()
        return dico

    def action(self, what, *args, **kwargs):
        """Run safely a method which access to infos attribute.
        """
        result = None
        self.lock.acquire()
        tberr = None
        try:
            result = getattr(self, what)(*args, **kwargs)
        except Exception:
            tberr = traceback.format_exc()
        self.lock.release()
        if tberr:
            raise ResourceManagerError, tberr
        return result

    def get_first(self, values=None):
        """Return the most available host.
        """
        if values is None:
            values = self.infos[:]
        if len(values) == 0:
            return {}
        for crit, rev in self.l_crit:
            values.sort(reverse=rev)
            if _DBG_TRI:
                print3(crit)
                pprint(values)
            val0 = values[0][crit]
            new = [values[0], ]
            for info in values[1:]:
                if info[crit] != val0:
                    break
                new.append(info)
            values = new
            if len(values) == 1:
                break
        if _DBG_TRI:
            print3('--- FIN ---')
            pprint(values)
        return values[0]

    def is_connected(self, host):
        """Tell if 'host' is connected.
        """
        return self.host_connection[host]

    def get_all_connected_hosts(self):
        """Return all connected hosts.
        """
        return [h for h in self.all_hosts if self.is_connected(h)]

    def suitable_host(self, **kwjob):
        """Limit infos to capable hosts.
        """
        values = []
        for info in self.infos:
            if not self.is_connected(info[self.d_crit['host'][0]]):
                continue
            isok = True
            for par, val in kwjob.items():
                if not self.isok(par, val, info):
                    isok = False
                    break
            if isok:
                values.append(info)
        return values

    def available_host(self, **kwjob):
        """Return the most available host accepting job parameters.
        """
        if _DBG_CRIT:
            print3('job parameters : ', end=' ')
            pprint(kwjob)
        values = self.suitable_host(**kwjob)
        if _DBG_CRIT:
            print '%d suitable hosts : %s' \
                % (len(values), [info[self.d_crit['host'][0]] for info in values])
        avail = self.get_first(values)
        return avail

    def isok(self, key, value, info):
        """Tell if 'value' is under the limit vs 'info[par]'.
        """
        if not key in self.job_keys:
            return False
        val_ref = info[self.d_crit[key][0]]
        if not self.d_crit.has_key(key + 'run'):
            return True
        val_run = info[self.d_crit[key + 'run'][0]]
        ok = (value + val_run) <= val_ref
        if _DBG_CRIT:
            rep = '-'
            if ok:
                rep = 'ok'
            print3('%-2s host=%-24s para=%-4s allocated=%-4s requested=%-4s ref=%-4s' % \
                (rep, info[self.d_crit['host'][0]], key, val_run, value, val_ref))
        return ok

    def CheckHosts(self, run, silent=False, numthread="auto"):
        """Check connection to known hosts, update host_connection attribute.
        """
        try:
            numthread = int(numthread)
        except (TypeError, ValueError):
            numthread = run.GetCpuInfo('numthread')
        if numthread > 1:
            numthread = numthread * 8
        task = CheckHostsTask(run=run, silent=silent, success_connection=self.host_connection)
        users = [self.get(h, 'user') for h in self.all_hosts]
        couples = zip(users, self.all_hosts)
        check = Dispatcher(couples, task, min(numthread, len(couples)))
        run.DBG(check.report())
        nbok = len([host for host, success in self.host_connection.items() if success])
        return nbok, len(self.all_hosts)


    def Request(self, run=None, **kwjob):
        """Ask for an available host and block resources.
        """
        info = self.action('available_host', **kwjob)
        host = info.get(self.d_crit['host'][0], None)
        if _DBG_ALLOC:
            print3('job allocated on %s : %s' % (host, pformat(kwjob)))
        if host is not None:
            status = ALLOCATED
            for key in self.job_keys:
                if isnum(kwjob.get(key)):
                    self.action('add', host, key + 'run', kwjob[key])
        else:
            status = NORESOURCE
            for key, lim in self.limit.items():
                if kwjob.get(key) and (\
                    (self.d_crit[key][2]     and kwjob[key] > lim) or \
                    (not self.d_crit[key][2] and kwjob[key] < lim) ):
                    status = OVERLIMIT
                    if run:
                        run.DBG("OVERLIMIT %s : requested = %s  limit = %s  (reverse = %s)" \
                            % (key, kwjob[key], lim, self.d_crit[key][2]))
                    break
        self.action('store_job', host, **kwjob)
        if _DBG_ALLOC:
            print3(self.Load())
        return host, status

    def Free(self, jobname):
        """Free job resources on 'host'.
        """
        kwjob = self.action('get_job', jobname)
        if not kwjob:
            return
        host = kwjob['host']
        ddbg = {}
        for key in self.job_keys:
            if isnum(kwjob.get(key)):
                self.action('sub', host, key + 'run', kwjob[key])
                ddbg[key] = kwjob[key]
        if _DBG_ALLOC:
            print3('job released : %s' % (pformat(ddbg)))

    def repr_history(self):
        """Return jobs's history.
        """
        dico = self.action('get_history')
        ljob = [(v['allocated'], k) for k, v in dico.items()]
        ljob.sort()
        head = '%s %s %s %s %s %s' % (_(u"job").center(14), _(u"host").center(16),
                                                _(u"started").center(12), _(u"cpu").rjust(6),
                                                _(u"memory").rjust(6), _(u"ended").rjust(12))
        fmt  = '%(job_)-14s %(host_)-16s %(allocated)12s %(cpu)6d %(mem)6d %(released)12s'
        dini = { 'job_' : '', 'host_' : '', 'allocated' : '', 'cpu' : 0,
                 'mem' : 0, 'released' : '' }
        txt = [head, ]
        for dummy, job in ljob:
            dval = dini.copy()
            dval.update(dico[job])
            dval.update({ 'job_' : job[:14], 'host_' : dval['host'][:16] })
            txt.append(fmt % dval)
        return os.linesep.join(txt)

    def Load(self):
        """Return current load.
        """
        infos = self.infos[:]
        lkey = ['cpu', 'mem']
        head = '    host      cpu    mem'
        fmt = '%(host_)-16s %(cpu)6d %(mem)6d'
        txt = [head, ]
        for info in infos:
            dval = { 'host_' : info[self.d_crit['host'][0]][:16] }
            for k in lkey:
                dval[k] = info[self.d_crit[k + 'run'][0]]
            txt.append(fmt % dval)
        return os.linesep.join(txt)

    def GetConfig(self, host):
        """Return the configuration of 'host'.
        """
        return self.hostinfo.get(host, {}).copy()

    def get_sum(self, key):
        """Return the sum of a resource.
        """
        return sum([self.get(host, key, 0) for host in self.get_all_connected_hosts()])

    def __repr__(self):
        return self.hostinfo_repr()

    def hostinfo_repr(self, title=""):
        """Return a hostfile representing the content of the 'hostinfo' attribute.
        """
        if not title:
            title = "from ResourceManager object"
        content = ["# GENERATED %s - %s" % (title, now())]
        for mach, res in self.hostinfo.items():
            cpu = res["cpu"]
            mem = res["mem"]
            if cpu == mem == 0:
                content.append("# %s is not responding" % mach)
            else:
                content.append("[%s]" % mach)
                if cpu > 0:
                    content.append("cpu=%d" % cpu)
                if mem > 0:
                    content.append("mem=%d" % mem)
            content.append("")
        return os.linesep.join(content)


class PureLocalResource(ResourceManager):
    """Derived class to run only on local host.
    """
    def __init__(self, run):
        """Initialization using AsterRun object."""
        cpu  = run.GetCpuInfo('numcpu')
        mem  = run.GetMemInfo('memtotal') or 9999999
        dico = { local_host : { 'host' : local_host, 'cpu' : cpu, 'mem' : mem }}
        ResourceManager.__init__(self, hostinfo=dico)



class CheckHostsTask(Task):
    """Task to check a host.
    """
    # declare attrs
    run = None
    silent = False
    success_connection = {}

    def execute(self, item, **kwargs):
        """Function called for each item of the stack
        (up to 'nbmaxitem' at each called).
        Warning : 'execute' should not modify attributes.
        """
        user, host = item
        success = False
        if self.run.Ping(host):
            iret, output = self.run.Shell('echo hello', mach=host, user=user)
            if output.find('hello') >= 0:
                self.run.DBG(u"CheckHosts success on %s" % host)
                success = True
        return host, success


    def result(self, host, success, **kwargs):
        """Function called after each task to treat results of 'execute'.
        Arguments are 'execute' results + keywords args.
        'result' is called thread-safely, so can store results in attributes.
        """
        if not self.silent:
            print3(_(u"checking connection to %s... ") % host, end="")
            if success:
                print3(_(u"connected"))
            else:
                print3(_(u"failed"))
        self.success_connection[host] = success



def get_hostrc(run, prof):
    """Return hostrc object from profile or config.
    """
    mode = prof['mode'][0]
    hostrc = None
    if prof.Get('D', 'hostfile'):
        fhost = prof.Get('D', 'hostfile')[0]['path']
        if run.IsRemote(fhost) or True:
            tmphost = get_tmpname(run, run['tmp_user'], basename='hostfile')
            run.ToDelete(tmphost)
            iret = run.Copy(tmphost, fhost)
            fhost = tmphost
        else:
            fhost = run.PathOnly(fhost)
    elif run.get('%s_distrib_hostfile' % mode):
        fhost = run['%s_distrib_hostfile' % mode]
    else:
        fhost = None
    if fhost:
        hostinfo = parse_config(fhost)
        run.DBG('hostinfo : %s' % hostinfo, all=True)
        hostrc = ResourceManager(hostinfo)
    else:
        hostrc = PureLocalResource(run)
    run.DBG(hostrc)
    return hostrc