home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2012 January / maximum-cd-2012-01.iso / DiscContents / digsby_setup.exe / lib / plugins / researchdriver / driver.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-10-05  |  14.3 KB  |  488 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. from __future__ import with_statement
  5. from fileutil import cd
  6. from path import path
  7. from subprocess import Popen, PIPE
  8. from threading import RLock
  9. from util import default_timer
  10. import ctypes
  11. import logging
  12. import os
  13. import time
  14. import traceback
  15. import sys
  16. log = logging.getLogger('research')
  17. DEFAULT_IDLE_MINUTES = 5
  18. DEFAULT_REVIVE_INTERVAL = 3600
  19.  
  20. def REVIVE_INTERVAL():
  21.     pref = pref
  22.     import common
  23.     return pref('research.revive_interval_seconds', default = DEFAULT_REVIVE_INTERVAL, type = int)
  24.  
  25.  
  26. def MAX_PERCENT():
  27.     return 0.75
  28.  
  29. DEFAULT_CPU_PERCENT = 0.75
  30. DEFAULT_BANDWIDTH_PERCENT = 0.9
  31. STARTED = True
  32. FAILED_TO_START = False
  33. ALREADY_RUNNING = 'ALREADY_RUNNING'
  34. KEY_WOW64_64KEY = 256
  35. DEBUG_PLURA = False
  36. KIBIBYTE = 1024
  37. MEBIBYTE = 1048576
  38. GIBIBYTE = 1073741824
  39. PERMGEN_SPACE = 32 * MEBIBYTE
  40. MEMORY_LIMIT_BUFFER = 1.2
  41.  
  42. def expected_memory(size):
  43.     return (size + PERMGEN_SPACE) * MEMORY_LIMIT_BUFFER
  44.  
  45.  
  46. def find_java_home():
  47.     k = None
  48.     k2 = None
  49.     if not sys.platform.startswith('win'):
  50.         if 'JAVA_HOME' in os.environ:
  51.             path = os.environ['JAVA_HOME']
  52.             if os.path.exists(path):
  53.                 return path
  54.         else:
  55.             return '/usr'
  56.     'JAVA_HOME' in os.environ
  57.     
  58.     try:
  59.         import _winreg
  60.     except ImportError:
  61.         return False
  62.     else:
  63.         
  64.         try:
  65.             
  66.             try:
  67.                 k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\JavaSoft\\Java Runtime Environment\\\\', 0, _winreg.KEY_READ | KEY_WOW64_64KEY)
  68.             except Exception:
  69.                 k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\JavaSoft\\Java Runtime Environment\\\\', 0, _winreg.KEY_READ)
  70.  
  71.             (ver, tp) = _winreg.QueryValueEx(k, 'CurrentVersion')
  72.         except Exception:
  73.             return False
  74.  
  75.         if tp != _winreg.REG_SZ:
  76.             return False
  77.         
  78.         try:
  79.             if float(ver[:3]) <= 1.5:
  80.                 return False
  81.         except ValueError:
  82.             tp != _winreg.REG_SZ
  83.             tp != _winreg.REG_SZ
  84.             return False
  85.  
  86.         
  87.         try:
  88.             k2 = _winreg.OpenKey(k, ver, 0, _winreg.KEY_READ)
  89.             (java_home, tp) = _winreg.QueryValueEx(k2, 'JavaHome')
  90.         except Exception:
  91.             tp != _winreg.REG_SZ
  92.             tp != _winreg.REG_SZ
  93.             return False
  94.  
  95.         if tp != _winreg.REG_SZ:
  96.             return False
  97.         return java_home
  98.     if k2 is not None:
  99.         k2.Close()
  100.     
  101.  
  102.     if k is not None:
  103.         k.Close()
  104.     
  105.  
  106.  
  107. def java_exe(java_home):
  108.     
  109.     def exe(filename):
  110.         if sys.platform.startswith('win'):
  111.             return filename + '.exe'
  112.         return filename
  113.  
  114.     java = path(java_home) / 'bin' / exe('java')
  115.     javaw = path(java_home) / 'bin' / exe('javaw')
  116.     if javaw.isfile():
  117.         return javaw
  118.     return java
  119.  
  120. IDLE_PRIORITY_CLASS = 64
  121.  
  122. class Driver(object):
  123.     profile = None
  124.     instance = None
  125.     lock = RLock()
  126.     numstarts = 0
  127.     numfounddead = 0
  128.     dead_at = 0
  129.     dead = False
  130.     
  131.     def __init__(self):
  132.         pass
  133.  
  134.     
  135.     def res_path(cls):
  136.         pth = path(__file__).parent
  137.         return pth / 'res'
  138.  
  139.     res_path = classmethod(res_path)
  140.     
  141.     def jar_path(cls):
  142.         return cls.res_path() / 'process.jar'
  143.  
  144.     jar_path = classmethod(jar_path)
  145.     
  146.     def jar2_path(cls):
  147.         return cls.res_path() / 'security.jar'
  148.  
  149.     jar2_path = classmethod(jar2_path)
  150.     
  151.     def policy_path(cls):
  152.         return cls.res_path() / 'java.policy'
  153.  
  154.     policy_path = classmethod(policy_path)
  155.     
  156.     def java_path(cls):
  157.         return java_exe(find_java_home())
  158.  
  159.     java_path = classmethod(java_path)
  160.     
  161.     def username(cls):
  162.         uname = getattr(getattr(cls, 'profile', None), 'username', None)
  163.         if uname:
  164.             to_hex = to_hex
  165.             string_xor = string_xor
  166.             import util.primitives.strings
  167.             uname = to_hex(string_xor(x = 'digsbygrid', y = uname.encode('utf-8'), adjustx = True), '')
  168.             return [
  169.                 '-u',
  170.                 uname]
  171.         return []
  172.  
  173.     username = classmethod(username)
  174.     
  175.     def chassis_desired_cpuUsage(cls):
  176.         
  177.         try:
  178.             chassis_types = getattr(cls, 'chassis_types', None)
  179.             if chassis_types is None:
  180.                 if sys.platform.startswith('win'):
  181.                     import comtypes.client as comtypes
  182.                     wmi = comtypes.client.CoGetObject('winmgmts:')
  183.                     encs = wmi.InstancesOf('Win32_SystemEnclosure')
  184.                     enc = list(encs)[0]
  185.                     cls.chassis_types = chassis_types = enc.Properties_(strName = 'ChassisTypes').Value
  186.                     log.info('chassis types (success): %r', cls.chassis_types)
  187.                 else:
  188.                     log.warning('hardcoding chassis type for this platform')
  189.                     cls.chassis_types = chassis_types = [
  190.                         2]
  191.             
  192.             rpm = rpm
  193.             import engine
  194.             speeds = [ rpm.get(chassis, DEFAULT_CPU_PERCENT) for chassis in chassis_types ] + [
  195.                 MAX_PERCENT()]
  196.             lowest = min(speeds)
  197.             if lowest != sys.maxint:
  198.                 return lowest
  199.             return min(DEFAULT_CPU_PERCENT, MAX_PERCENT())
  200.         except Exception:
  201.             traceback.print_exc()
  202.             cls.chassis_types = [
  203.                 2]
  204.             log.info('chassis types (fail): %r', cls.chassis_types)
  205.             return min(DEFAULT_CPU_PERCENT, MAX_PERCENT())
  206.  
  207.  
  208.     chassis_desired_cpuUsage = classmethod(chassis_desired_cpuUsage)
  209.     
  210.     def cpuUsage(cls):
  211.         default = cls.chassis_desired_cpuUsage()
  212.         
  213.         try:
  214.             return get_cpu_percent(default) / 100
  215.         except ImportError:
  216.             pass
  217.  
  218.         return default
  219.  
  220.     cpuUsage = classmethod(cpuUsage)
  221.     
  222.     def cpuUsageStr(cls):
  223.         return [
  224.             '-p',
  225.             str(int(cls.cpuUsage() * 1000))]
  226.  
  227.     cpuUsageStr = classmethod(cpuUsageStr)
  228.     
  229.     def numCpus(cls):
  230.         return []
  231.  
  232.     numCpus = classmethod(numCpus)
  233.     
  234.     def bandwidthUsage(cls):
  235.         default = DEFAULT_BANDWIDTH_PERCENT * 100
  236.         
  237.         try:
  238.             pref = pref
  239.             import common
  240.             percent = pref('research.bandwidth_percent', default, type = float)
  241.             if percent >= 0 and percent <= 100:
  242.                 percent = percent / 100
  243.             
  244.             if percent >= 0:
  245.                 return percent
  246.         except ImportError:
  247.             pass
  248.  
  249.         return default
  250.  
  251.     bandwidthUsage = classmethod(bandwidthUsage)
  252.     
  253.     def bandwidthUsageStr(cls):
  254.         return [
  255.             '-b',
  256.             str(int(cls.bandwidthUsage() * 1000))]
  257.  
  258.     bandwidthUsageStr = classmethod(bandwidthUsageStr)
  259.     
  260.     def memoryLimits(cls):
  261.         if not sys.platform.startswith('win'):
  262.             return [
  263.                 '-Xmx512m']
  264.         
  265.         try:
  266.             import gui.native.sysinfo as gui
  267.             s = gui.native.sysinfo.SystemInformation()
  268.             ram = s._ram()
  269.         except Exception:
  270.             sys.platform.startswith('win')
  271.             sys.platform.startswith('win')
  272.             return [
  273.                 '-Xmx256m']
  274.  
  275.         AvailPhys = ram.get('ullAvailPhys')
  276.         TotalPhys = ram.get('ullTotalPhys')
  277.         if AvailPhys >= expected_memory(GIBIBYTE) and TotalPhys >= 2 * GIBIBYTE:
  278.             return [
  279.                 '-Xmx1024m']
  280.         if AvailPhys >= expected_memory(512 * MEBIBYTE) and TotalPhys >= GIBIBYTE:
  281.             return [
  282.                 '-Xmx512m']
  283.         if AvailPhys >= expected_memory(256 * MEBIBYTE):
  284.             return [
  285.                 '-Xmx256m']
  286.         if TotalPhys >= GIBIBYTE:
  287.             return [
  288.                 '-Xmx256m']
  289.         return [
  290.             '-Xmx128m']
  291.  
  292.     memoryLimits = classmethod(memoryLimits)
  293.     
  294.     def commandline(cls):
  295.         return [
  296.             str(cls.java_path()),
  297.             '-Djava.security.manager=com.pluraprocessing.node.security.PluraSecurityManager',
  298.             '-Djava.security.policy=' + str(cls.policy_path()) + ''] + cls.memoryLimits() + [
  299.             '-jar',
  300.             str(cls.jar_path())] + cls.username() + cls.cpuUsageStr() + cls.bandwidthUsageStr()
  301.  
  302.     commandline = classmethod(commandline)
  303.     
  304.     def running(cls):
  305.         cls.lock.__enter__()
  306.         
  307.         try:
  308.             proc = getattr(cls, 'proc', None)
  309.             if proc is not None:
  310.                 pass
  311.             return proc.poll() is None
  312.         finally:
  313.             pass
  314.  
  315.  
  316.     running = classmethod(running)
  317.     
  318.     def set_dead(cls):
  319.         cls.dead = True
  320.         cls.dead_at = default_timer()
  321.  
  322.     set_dead = classmethod(set_dead)
  323.     
  324.     def is_dead(cls):
  325.         if cls.dead:
  326.             revive_at = cls.dead_at + REVIVE_INTERVAL()
  327.             now = default_timer()
  328.             if now > revive_at or now < cls.dead_at:
  329.                 cls.dead = False
  330.                 cls.numfounddead = 0
  331.                 cls.dead_at = 0
  332.                 return False
  333.             return True
  334.         return False
  335.  
  336.     is_dead = classmethod(is_dead)
  337.     
  338.     def start(cls, profile):
  339.         return FAILED_TO_START
  340.  
  341.     start = classmethod(start)
  342.     
  343.     def kill(cls):
  344.         cls.lock.__enter__()
  345.         
  346.         try:
  347.             start = time.clock()
  348.             proc = getattr(cls, 'proc', None)
  349.             end = time.clock()
  350.             return end - start
  351.         finally:
  352.             pass
  353.  
  354.  
  355.     kill = classmethod(kill)
  356.     stop = kill
  357.     _start_time = 0
  358.  
  359.  
  360. def get_process_runtime_secs(handle):
  361.     f = ctypes.wintypes.FILETIME()
  362.     ctypes.windll.kernel32.GetSystemTimeAsFileTime(ctypes.byref(f))
  363.     (c, e, k, u) = (ctypes.wintypes.FILETIME(), ctypes.wintypes.FILETIME(), ctypes.wintypes.FILETIME(), ctypes.wintypes.FILETIME())
  364.     ctypes.windll.kernel32.GetProcessTimes(handle, ctypes.byref(c), ctypes.byref(e), ctypes.byref(k), ctypes.byref(u))
  365.     seconds_run = ((f.dwHighDateTime << 32) + f.dwLowDateTime - ((c.dwHighDateTime << 32) + c.dwLowDateTime)) / (1 * 10000000)
  366.     return seconds_run
  367.  
  368.  
  369. def test_conditions(useridlems):
  370.     pref = pref
  371.     import common
  372.     idle_time = pref('research.idle_time_ms', default = pref('research.idle_time_min', default = DEFAULT_IDLE_MINUTES, type = int) * 60 * 1000, type = int)
  373.     if useridlems < idle_time:
  374.         if not pref('research.always_on', default = False):
  375.             return False
  376.     
  377.     import wx
  378.     if wx.GetPowerType() != wx.POWER_SOCKET and not pref('research.battery_override', False):
  379.         return False
  380.     return bool(get_research_pref())
  381.  
  382.  
  383. def get_research_pref():
  384.     import common
  385.     return common.profile.localprefs['research.enabled']
  386.  
  387.  
  388. def set_research_pref(val):
  389.     import common
  390.     common.profile.localprefs['research.enabled'] = val
  391.  
  392.  
  393. def get_cpu_percent(chassis_percent = None):
  394.     if chassis_percent is None:
  395.         chassis_percent = Driver.chassis_desired_cpuUsage()
  396.     
  397.     import common
  398.     
  399.     try:
  400.         return int(common.profile.localprefs['research.cpu_percent'])
  401.     except (KeyError, AttributeError):
  402.         _e = None
  403.         chassis_percent = float(chassis_percent)
  404.         chassis_percent *= 100
  405.         
  406.         try:
  407.             if chassis_percent < common.profile.defaultprefs.get('research.cpu_percent', chassis_percent):
  408.                 return min(chassis_percent, common.pref('research.cpu_percent', chassis_percent, type = float))
  409.             return common.pref('research.cpu_percent', chassis_percent, type = float)
  410.         except AttributeError:
  411.             _e2 = None
  412.             return common.pref('research.cpu_percent', chassis_percent, type = float)
  413.         
  414.  
  415.         None<EXCEPTION MATCH>AttributeError
  416.  
  417.  
  418.  
  419. def get_bandwidth_percent():
  420.     import common
  421.     
  422.     try:
  423.         return common.profile.localprefs['research.bandwidth_percent']
  424.     except KeyError:
  425.         return common.pref('research.bandwidth_percent', DEFAULT_BANDWIDTH_PERCENT * 100, type = float)
  426.  
  427.  
  428.  
  429. def control(useridlems):
  430.     if Driver.is_dead():
  431.         return 2000
  432.     if not test_conditions(useridlems):
  433.         
  434.         try:
  435.             Driver.stop()
  436.         except Exception:
  437.             Driver.is_dead()
  438.             Driver.is_dead()
  439.             traceback.print_exc()
  440.         except:
  441.             Driver.is_dead()
  442.  
  443.         if Driver._start_time != 0:
  444.             log.debug('tried to run for %s', default_timer() - Driver._start_time)
  445.         
  446.         Driver._start_time = 0
  447.     else:
  448.         
  449.         try:
  450.             profile = profile
  451.             import common
  452.             ret = Driver.start(profile)
  453.         except Exception:
  454.             Driver.is_dead()
  455.             Driver.is_dead()
  456.             traceback.print_exc()
  457.         except:
  458.             Driver.is_dead()
  459.  
  460.         if ret == STARTED:
  461.             Driver._start_time = default_timer()
  462.         elif ret == FAILED_TO_START:
  463.             Driver._start_time = 0
  464.         elif ret == ALREADY_RUNNING:
  465.             return 500
  466.         return 500
  467.     return test_conditions(useridlems)
  468.  
  469.  
  470. def check_cli_args(*a):
  471.     import sys
  472.     set_val = sys.opts.set_plura_option
  473.     if set_val is None:
  474.         return None
  475.     log.info('setting intial research pref to %r', set_val)
  476.     set_research_pref(set_val)
  477.  
  478. inited = False
  479.  
  480. def init(*a, **k):
  481.     global inited
  482.     if not inited:
  483.         inited = True
  484.         import atexit
  485.         atexit.register(Driver.kill)
  486.     
  487.  
  488.