'''
rlimit.py - An "service" to set resource limits in sagator.

(c) 2004-2008 Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>

 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.

'''

from aglib import *

__all__ = ['rlimit']

class rlimit(service):
  '''
  Resource limit virtual service.
  
  This service can be used to set resource limits for sagator.
  
  Usage: rlimit(PARAM1=value1, PARAM2=value1, ...)
  
  Where: PARAM1,... are resource parameter names
         value1,... are resource values

  For example you can use there resource parameter names:
    AS for the maximum area (in bytes) of address space which may be
        taken by the process.
    NOFILE for the maximum number of open file descriptors for the
        current process.
    VMEM for the largest area of mapped memory which the process may occupy.
    DATA for the maximum size (in bytes) of the process's heap.
    RSS for the maximum resident set size that should be made available
        to the process.
    STACK for the maximum size (in bytes) of the call stack for the current
        process.
    FSIZE for the maximum size of a file which the process may create.
        This only affects the stack of the main thread in a multi-threaded
        process.
    CPU for the maximum amount of processor time (in seconds) that a process
        can use
  
  Aprox. 100 MB address space is required only for libclamav database.

  Example: rlimit(AS=30000000)
  '''
  name = 'rlimit()'
  def __init__(self, **args):
      self.ARGS = args
  def start(self):
      import resource
      debug.echo(1, "rlimit(): LIMITS:", str(self.ARGS))
      for res,limit in self.ARGS.items():
        try:
          eres=getattr(resource, 'RLIMIT_'+res)
          resource.setrlimit(eres, (limit, limit))
          debug.echo(7,"rlimit(): Limit %s set to %s"
            % (res, str(resource.getrlimit(eres))))
        except:
          debug.echo(1, "rlimit(): ERROR: Can't set limit for resource: "+res)
          raise
      return []
