Exemplo n.º 1
0
def win_check_cpu_use(cpulim, pid):
    global winlastcpuinfo

    # get use information and time...
    now = getruntime()

    # Get the total cpu time
    usertime = windows_api.get_process_cpu_time(pid)

    useinfo = [usertime, now]

    # get the previous time and cpu so we can compute the percentage
    oldusertime = winlastcpuinfo[0]
    oldnow = winlastcpuinfo[1]

    if winlastcpuinfo == [0, 0]:
        winlastcpuinfo = useinfo
        # give them a free pass if it's their first time...
        return 0

    # save this data for next time...
    winlastcpuinfo = useinfo

    # Get the elapsed time...
    elapsedtime = now - oldnow

    # This is a problem
    if elapsedtime == 0:
        return -1  # Error condition

    # percent used is the amount of change divided by the time...
    percentused = (usertime - oldusertime) / elapsedtime

    # Calculate amount of time to sleep for
    stoptime = nanny.calculate_cpu_sleep_interval(cpulim, percentused,
                                                  elapsedtime)

    if stoptime > 0.0:
        # Try to timeout the process
        if windows_api.timeout_process(pid, stoptime):
            # Log the stoptime
            process_stopped_timeline.append((now, stoptime))

            # Drop the first element if the length is greater than the maximum entries
            if len(process_stopped_timeline) > process_stopped_max_entries:
                process_stopped_timeline.pop(0)

            # Return how long we slept so parent knows whether it should sleep
            return stoptime

        else:
            # Process must have been making system call, try again next time
            return -1

    # If the stop time is 0, then avoid calling timeout_process
    else:
        return 0.0
Exemplo n.º 2
0
def win_check_cpu_use(cpulim, pid):
  global winlastcpuinfo
  
  # get use information and time...
  now = getruntime()

  # Get the total cpu time
  usertime = windows_api.get_process_cpu_time(pid)

  useinfo = [usertime, now]

  # get the previous time and cpu so we can compute the percentage
  oldusertime = winlastcpuinfo[0]
  oldnow = winlastcpuinfo[1]

  if winlastcpuinfo == [0,0]:
    winlastcpuinfo = useinfo
    # give them a free pass if it's their first time...
    return 0

  # save this data for next time...
  winlastcpuinfo = useinfo

  # Get the elapsed time...
  elapsedtime = now - oldnow

  # This is a problem
  if elapsedtime == 0:
    return -1 # Error condition
    
  # percent used is the amount of change divided by the time...
  percentused = (usertime - oldusertime) / elapsedtime

  # Calculate amount of time to sleep for
  stoptime = nanny_resource_limits.calculate_cpu_sleep_interval(cpulim, percentused,elapsedtime)

  if stoptime > 0.0:
    # Try to timeout the process
    if windows_api.timeout_process(pid, stoptime):
      # Log the stoptime
      process_stopped_timeline.append((now, stoptime))

      # Drop the first element if the length is greater than the maximum entries
      if len(process_stopped_timeline) > process_stopped_max_entries:
        process_stopped_timeline.pop(0)

      # Return how long we slept so parent knows whether it should sleep
      return stoptime
  
    else:
      # Process must have been making system call, try again next time
      return -1
  
  # If the stop time is 0, then avoid calling timeout_process
  else:
    return 0.0
Exemplo n.º 3
0
Arquivo: crepy.py Projeto: taol/crepy
def calculate_sleeptimes():
  ''' 
  <Purpose>
      calculate amount of sleep time for each process
  ''' 
  global pid_list
  global process_cpu_info

  ## calculate ecalapsed time of the last "period"
  global last_runtime
  global cpu_limit

  this_runtime = nonportable.getruntime()
  # print "Debug - this_runtime: ", this_runtime
  # if this_runtime == 0.0:
  #   print "Debug - this_runtime == 0.0 "
  #   return

  elapsedtime = this_runtime - last_runtime
  # print "Debug - last_runtime: ", last_runtime
  # print "Debug - this_runtime: ", this_runtime
  # print "\n"
  # print "Debug1 - elapsedtime: ", elapsedtime

  if elapsedtime < 0.0:
    print "Error: elapsed time < 0" 

  last_runtime = this_runtime


  for pid in pid_list:
    last_user_time = process_cpu_info[pid][0]
    if ostype == 'Windows':
      this_user_time = windows_api.get_process_cpu_time(pid)
    elif ostype == 'Linux':
      this_user_time = linux_api.get_process_cpu_time(pid)
    else:
      raise UnsupportedSystemException, "Unsupported system type: '"+osrealtype+"' (alias: "+ostype+")"
    # percent used is the amount of change divided by the time...
    percentused = (this_user_time - last_user_time) / elapsedtime 
    # print "Debug1 - pid:",pid, "percentused: ",percentused
    # Calculate amount of time to sleep for
    # print "Debug - cpu_limit: ",cpu_limit[pid]
    sleeptime = nanny.calculate_cpu_sleep_interval(cpu_limit[pid], percentused,elapsedtime)
    # print "Debug1 - pid:",pid,"sleeptime: ",sleeptime
    process_cpu_info[pid][1] = sleeptime
    process_cpu_info[pid][0] = this_user_time
Exemplo n.º 4
0
def get_resources():
  """
  <Purpose>
    Returns the resource utilization limits as well
    as the current resource utilization.

  <Arguments>
    None.

  <Returns>
    A tuple of dictionaries and an array (limits, usage, stoptimes).

    Limits is the dictionary which maps the resource name
    to its maximum limit.

    Usage is the dictionary which maps the resource name
    to its current usage.

    Stoptimes is an array of tuples with the times which the Repy process
    was stopped and for how long, due to CPU over-use.
    Each entry in the array is a tuple (TOS, Sleep Time) where TOS is the
    time of stop (respective to getruntime()) and Sleep Time is how long the
    repy process was suspended.

    The stop times array holds a fixed number of the last stop times.
    Currently, it holds the last 100 stop times.
  """
  # Acquire the lock...
  get_resources_lock.acquire()

  # ...but always release it
  try:
    # Construct the dictionaries as copies from nanny
    (limits,usage) = 0, 0 #nanny.get_resource_information()


    # Calculate all the usage's
    pid = os.getpid()

    # Get CPU and memory, this is thread specific
    if ostype in ["Linux", "Darwin"]:
    
      # Get CPU first, then memory
      usage["cpu"] = os_api.get_process_cpu_time(pid)

      # This uses the cached PID data from the CPU check
      usage["memory"] = os_api.get_process_rss()

      # Get the thread specific CPU usage
      usage["threadcpu"] = os_api.get_current_thread_cpu_time() 


    # Windows Specific versions
    elif ostype in ["Windows"]:
    
      # Get the CPU time
      usage["cpu"] = windows_api.get_process_cpu_time(pid)

      # Get the memory, use the resident set size
      usage["memory"] = windows_api.process_memory_info(pid)['WorkingSetSize'] 

      # Get thread-level CPU 
      usage["threadcpu"] = windows_api.get_current_thread_cpu_time()

    # Unknown OS
    else:
      raise EnvironmentError("Unsupported Platform!")

    # Use the cached disk used amount
    usage["diskused"] = cached_disk_used

  finally:
    # Release the lock
    get_resources_lock.release()

  # Copy the stop times
  stoptimes = process_stopped_timeline[:]

  # Return the dictionaries and the stoptimes
  return (limits,usage,stoptimes)
Exemplo n.º 5
0
def get_resources():
  """
  <Purpose>
    Returns the resouce utilization limits as well
    as the current resource utilization.

  <Arguments>
    None.

  <Returns>
    A tuple of dictionaries and an array (limits, usage, stoptimes).

    Limits is the dictionary which maps the resouce name
    to its maximum limit.

    Usage is the dictionary which maps the resource name
    to its current usage.

    Stoptimes is an array of tuples with the times which the Repy proces
    was stopped and for how long, due to CPU over-use.
    Each entry in the array is a tuple (TOS, Sleep Time) where TOS is the
    time of stop (respective to getruntime()) and Sleep Time is how long the
    repy process was suspended.

    The stop times array holds a fixed number of the last stop times.
    Currently, it holds the last 100 stop times.
  """
  # Acquire the lock
  get_resources_lock.acquire()

  # Construct the dictionaries as copies from nanny
  limits = nanny_resource_limits.resource_restriction_table.copy()
  usage = nanny_resource_limits.resource_consumption_table.copy()

  # These are the type we need to copy or flatten
  check_types = set([list,dict,set])

  # Check the limits dictionary for bad keys
  for resource in limits.keys():
    # Remove any resources we should not expose
    if resource not in exposed_resources:
      del limits[resource]

    # Check the type
    if type(limits[resource]) in check_types:
      # Copy the data structure
      limits[resource] = limits[resource].copy()

  # Check the usage dictionary
  for resource in usage.keys():
    # Remove any resources that are not exposed
    if resource not in exposed_resources:
      del usage[resource]

    # Check the type, copy any data structures
    # Flatten any structures using len() other than
    # "connport" and "messport"
    if type(usage[resource]) in check_types:
      # Check if they are exempt from flattening, store a shallow copy
      if resource in flatten_exempt_resources:
        usage[resource] = usage[resource].copy()

      # Store the size of the data set
      else:
        usage[resource] = len(usage[resource])
    


  # Calculate all the usage's
  pid = os.getpid()

  # Get CPU and memory, this is thread specific
  if ostype in ["Linux", "Darwin"]:
    
    # Get CPU first, then memory
    usage["cpu"] = os_api.get_process_cpu_time(pid)

    # This uses the cached PID data from the CPU check
    usage["memory"] = os_api.get_process_rss()

    # Get the thread specific CPU usage
    usage["threadcpu"] = os_api.get_current_thread_cpu_time() 


  # Windows Specific versions
  elif ostype in ["Windows","WindowsCE"]:
    
    # Get the CPU time
    usage["cpu"] = windows_api.get_process_cpu_time(pid)

    # Get the memory, use the resident set size
    usage["memory"] = windows_api.process_memory_info(pid)['WorkingSetSize'] 

    # Get thread-level CPU 
    usage["threadcpu"] = windows_api.get_current_thread_cpu_time()

  # Unknown OS
  else:
    raise EnvironmentError("Unsupported Platform!")

  # Use the cached disk used amount
  usage["diskused"] = cached_disk_used

  # Release the lock
  get_resources_lock.release()

  # Copy the stop times
  stoptimes = process_stopped_timeline[:]

  # Return the dictionaries and the stoptimes
  return (limits,usage,stoptimes)
Exemplo n.º 6
0
def get_resources():
  """
  <Purpose>
    Returns the resource utilization limits as well
    as the current resource utilization.

  <Arguments>
    None.

  <Returns>
    A tuple of dictionaries and an array (limits, usage, stoptimes).

    Limits is the dictionary which maps the resource name
    to its maximum limit.

    Usage is the dictionary which maps the resource name
    to its current usage.

    Stoptimes is an array of tuples with the times which the Repy process
    was stopped and for how long, due to CPU over-use.
    Each entry in the array is a tuple (TOS, Sleep Time) where TOS is the
    time of stop (respective to getruntime()) and Sleep Time is how long the
    repy process was suspended.

    The stop times array holds a fixed number of the last stop times.
    Currently, it holds the last 100 stop times.
  """
  # Acquire the lock...
  get_resources_lock.acquire()

  # ...but always release it
  try:
    # Construct the dictionaries as copies from nanny
    (limits,usage) = nanny.get_resource_information()


    # Calculate all the usage's
    pid = os.getpid()

    # Get CPU and memory, this is thread specific
    if ostype in ["Linux", "Darwin"]:
    
      # Get CPU first, then memory
      usage["cpu"] = os_api.get_process_cpu_time(pid)

      # This uses the cached PID data from the CPU check
      usage["memory"] = os_api.get_process_rss()

      # Get the thread specific CPU usage
      usage["threadcpu"] = os_api.get_current_thread_cpu_time() 


    # Windows Specific versions
    elif ostype in ["Windows","WindowsCE"]:
    
      # Get the CPU time
      usage["cpu"] = windows_api.get_process_cpu_time(pid)

      # Get the memory, use the resident set size
      usage["memory"] = windows_api.process_memory_info(pid)['WorkingSetSize'] 

      # Get thread-level CPU 
      usage["threadcpu"] = windows_api.get_current_thread_cpu_time()

    # Unknown OS
    else:
      raise EnvironmentError("Unsupported Platform!")

    # Use the cached disk used amount
    usage["diskused"] = cached_disk_used

  finally:
    # Release the lock
    get_resources_lock.release()

  # Copy the stop times
  stoptimes = process_stopped_timeline[:]

  # Return the dictionaries and the stoptimes
  return (limits,usage,stoptimes)