Enforces a process memory limit.

    Args:
      memory_limit (int): maximum number of bytes the process is allowed
          to allocate, where 0 represents no limit and None a default of
          4 GiB.
425336
def _EnforceProcessMemoryLimit(self, memory_limit):
    
    # Resource is not supported on Windows.
    if resource:
      if memory_limit is None:
        memory_limit = 4 * 1024 * 1024 * 1024
      elif memory_limit == 0:
        memory_limit = resource.RLIM_INFINITY

      resource.setrlimit(resource.RLIMIT_DATA, (memory_limit, memory_limit))
567034
def check_mem_usage(soft_percent=None, hard_percent=None):
    
    soft_percent = soft_percent or config.memory.soft_mem_limit
    hard_percent = hard_percent or config.memory.hard_mem_limit
    used_mem_percent = psutil.virtual_memory().percent
    if used_mem_percent > hard_percent:
        raise MemoryError('Using more memory than allowed by configuration '
                          '(Used: %d%% / Allowed: %d%%)! Shutting down.' %
                          (used_mem_percent, hard_percent))
    elif used_mem_percent > soft_percent:
        msg = 'Using over %d%% of the memory in %s!'
        return msg % (used_mem_percent, socket.gethostname())
171712
def set_file_limits(n):
    '''
    

    '''

    try:
        resource.setrlimit(resource.RLIMIT_NOFILE, (n, n))
        return True
    except ValueError:
        return False
1001662
def memory_full():
    """"""
    current_process = psutil.Process(os.getpid())
    return (current_process.memory_percent() >
            config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)
1024648
boolean isProcessTreeOverLimit(ProcfsBasedProcessTree pTree, 
                                    String tId, long limit) {
    long currentMemUsage = pTree.getCumulativeVmem();
    // as processes begin with an age 1, we want to see if there are processes
    // more than 1 iteration old.
    long curMemUsageOfAgedProcesses = pTree.getCumulativeVmem(1);
    return isProcessTreeOverLimit(tId, currentMemUsage, 
                                  curMemUsageOfAgedProcesses, limit);
  }
438937
private function checkDaemonLimits(): void
    {
        if ($this->isShutdown) {
            throw new ShutdownException($this->shutdownMessage);
        }

        pcntl_signal_dispatch();

        if (DaemonOptions::NO_LIMIT !== $this->requestLimit) {
            if ($this->requestLimit <= $this->requestCount) {
                throw new ShutdownException('Daemon request limit reached ('.$this->requestCount.' of '.$this->requestLimit.')');
            }
        }

        if (DaemonOptions::NO_LIMIT !== $this->memoryLimit) {
            $memoryUsage = memory_get_usage(true);

            if ($this->memoryLimit <= $memoryUsage) {
                throw new ShutdownException('Daemon memory limit reached ('.$memoryUsage.' of '.$this->memoryLimit.' bytes)');
            }
        }
    }
1141392
def _setup_file_hierarchy_limit(
            self, files_count_limit, files_size_limit, temp_dir, cgroups, pid_to_kill):
        """"""
        if files_count_limit is not None or files_size_limit is not None:
            file_hierarchy_limit_thread = FileHierarchyLimitThread(
                self._get_result_files_base(temp_dir),
                files_count_limit=files_count_limit,
                files_size_limit=files_size_limit,
                cgroups=cgroups,
                pid_to_kill=pid_to_kill,
                callbackFn=self._set_termination_reason,
                kill_process_fn=self._kill_process)
            file_hierarchy_limit_thread.start()
            return file_hierarchy_limit_thread
        return None
1137965
def mps_device_memory_limit():
    
    lib = _load_tcmps_lib()
    if lib is None:
        return None

    c_size = _ctypes.c_uint64()
    ret = lib.TCMPSMetalDeviceMemoryLimit(_ctypes.byref(c_size))
    return c_size.value if ret == 0 else None
51406
def _enforce_size_limit(self, capacity):
        """"""
        while len(self._cache) > capacity:
            key, value = self._cache.popitem(last=False)
            if self._on_evict is not None:
                self._on_evict(key, value)
1323296
public function limit( $new_limit ) {
		$this->limit = $new_limit;
		if ( false === starts_with( $new_limit . '', ':' ) ) {
			$this->limit = (int) $new_limit;
		}
	}
647109
private function do_raise_php_limits()
    {
        $php_limits = array(
            'memory_limit' => $this->memory_limit,
            'max_execution_time' => $this->max_execution_time,
            'pcre.backtrack_limit' => $this->pcre_backtrack_limit,
            'pcre.recursion_limit' =>  $this->pcre_recursion_limit
        );

        // If current settings are higher respect them.
        foreach ($php_limits as $name => $suggested) {
            $current = $this->normalize_int(ini_get($name));
            // memory_limit exception: allow -1 for "no memory limit".
            if ($current > -1 && ($suggested == -1 || $current < $suggested)) {
                ini_set($name, $suggested);
            }
        }
    }
482147
def MemoryExceeded(self):
    """"""
    rss_size = self.proc.memory_info().rss
    return rss_size // 1024 // 1024 > config.CONFIG["Client.rss_max"]
78821
def getToLimit(clus, limit)
      # Init.
      out = MemoryBuffer.create(limit)
      pos = 0
      cur_clus = clus

      # How many clusters fill request.
      num = limit.divmod(@bytesPerCluster)
      num_clus = num[0]; num_clus += 1 if num[1] > 0

      # Loop until done or EOF.
      while num_clus > 0

        # Find number of contiguous clusters & trim by num_clus.
        contig = countContigClusters(cur_clus)
        red_clus = num_clus > contig ? contig : num_clus

        # Get data.
        chunk = red_clus * @bytesPerCluster
        @stream.seek(clusToByte(cur_clus))
        out[pos, chunk] = @stream.read(chunk)
        pos += chunk

        # Inc current & dec number to read.
        cur_clus += (red_clus - 1); num_clus -= red_clus

        # Get next cluster & abort if end of chain.
        cur_clus = getFatEntry(cur_clus)
        break if cur_clus > CC_END_OF_CHAIN
      end

      # Return next cluster & data.
      [cur_clus, out]
    end
753452
def limit(self, limit):
        
        query = self._copy()
        query._limit = limit
        return query
187802
def recheck_limits(self):
        

        limit_data = self.control_daemon.get_limits()

        try:
            # Get the new checksum and list of limits
            new_sum, new_limits = limit_data.get_limits(self.limit_sum)

            # Convert the limits list into a list of objects
            lims = database.limits_hydrate(self.db, new_limits)

            # Save the new data
            self.limits = lims
            self.limit_map = dict((lim.uuid, lim) for lim in lims)
            self.limit_sum = new_sum
        except control.NoChangeException:
            # No changes to process; just keep going...
            return
        except Exception:
            # Log an error
            LOG.exception("Could not load limits")

            # Get our error set and publish channel
            control_args = self.conf['control']
            error_key = control_args.get('errors_key', 'errors')
            error_channel = control_args.get('errors_channel', 'errors')

            # Get an informative message
            msg = "Failed to load limits: " + traceback.format_exc()

            # Store the message into the error set.  We use a set
            # here because it's likely that more than one node
            # will generate the same message if there is an error,
            # and this avoids an explosion in the size of the set.
            with utils.ignore_except():
                self.db.sadd(error_key, msg)

            # Publish the message to a channel
            with utils.ignore_except():
                self.db.publish(error_channel, msg)
345615
def write_memory(self, addr, value, transfer_size=32):
        
        self.ap.write_memory(addr, value, transfer_size)
542524
def rate_limit(self, name, limit=5, per=60, debug=False):
        
        return RateLimit(self, name, limit, per, debug)