home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 February / maximum-cd-2011-02.iso / DiscContents / digsby_setup85.exe / lib / plugins / researchdriver / driver.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-11-24  |  16.2 KB  |  581 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 = 60 * 60
  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.75
  31. STARTED = True
  32. FAILED_TO_START = False
  33. ALREADY_RUNNING = 'ALREADY_RUNNING'
  34. KEY_WOW64_64KEY = 256
  35. DEBUG_PLURA = False
  36. KIBIBYTE = 2 ** 10
  37. MEBIBYTE = 2 ** 20
  38. GIBIBYTE = 2 ** 30
  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
  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.         cls.lock.__enter__()
  340.         
  341.         try:
  342.             if cls.numfounddead > 10:
  343.                 return FAILED_TO_START
  344.             if cls.running():
  345.                 return ALREADY_RUNNING
  346.             if getattr(cls, 'proc', None) is not None:
  347.                 if cls.numfounddead == 10:
  348.                     log.info("found process dead 10 times, won't try again for a while")
  349.                     cls.numfounddead += 1
  350.                     cls.set_dead()
  351.                     cls.stop()
  352.                     return FAILED_TO_START
  353.                 cls.numfounddead += 1
  354.                 cls.stop()
  355.                 return cls.start(profile)
  356.             cls.profile = profile
  357.             java_home = find_java_home()
  358.             if not java_home:
  359.                 log.info('java home not found, will not try starting again for a while')
  360.                 cls.set_dead()
  361.                 return FAILED_TO_START
  362.             java = java_exe(java_home)
  363.             if not java.isfile():
  364.                 log.info('java not found, will not try starting again for a while')
  365.                 cls.set_dead()
  366.                 return FAILED_TO_START
  367.             desired_cpu = cls.cpuUsage()
  368.             if desired_cpu <= 0 or desired_cpu > 1:
  369.                 log.info('cpuUsage was not in valid range (was: %r), will not try starting again for a while', desired_cpu)
  370.                 cls.set_dead()
  371.                 return FAILED_TO_START
  372.             import subprocess
  373.             startupinfo = subprocess.STARTUPINFO()
  374.             startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  375.             startupinfo.wShowWindow = subprocess.SW_HIDE
  376.             cmdline = cls.commandline()
  377.             log.info('running: %s %r', cmdline, cls.numstarts)
  378.             pref = pref
  379.             import common
  380.             use_pipes = not pref('research.debug_output', type = bool, default = DEBUG_PLURA)
  381.             
  382.             try:
  383.                 cd(cls.res_path()).__enter__()
  384.                 
  385.                 try:
  386.                     pass
  387.                 finally:
  388.                     pass
  389.  
  390.             except Exception:
  391.                 startupinfo
  392.                 startupinfo
  393.                 desired_cpu > 1
  394.                 log.info('failed Popen')
  395.                 traceback.print_exc()
  396.                 cls.numfounddead += 1
  397.                 return FAILED_TO_START
  398.                 cls
  399.  
  400.             
  401.             try:
  402.                 if use_pipes:
  403.                     proc.stderr.close()
  404.                     proc.stdout.close()
  405.             except Exception:
  406.                 startupinfo
  407.                 startupinfo
  408.                 desired_cpu > 1
  409.                 log.error('error closing stderr or stdout')
  410.                 traceback.print_exc()
  411.                 cls.kill()
  412.                 return FAILED_TO_START
  413.                 java.isfile()
  414.  
  415.             log.debug('successfully started')
  416.             
  417.             try:
  418.                 import hooks
  419.                 hooks.notify('digsby.research.started')
  420.             except Exception:
  421.                 startupinfo
  422.                 startupinfo
  423.                 desired_cpu > 1
  424.                 traceback.print_exc()
  425.             except:
  426.                 java.isfile()
  427.  
  428.             cls.numstarts += 1
  429.             return STARTED
  430.         finally:
  431.             pass
  432.  
  433.  
  434.     start = classmethod(start)
  435.     
  436.     def kill(cls):
  437.         cls.lock.__enter__()
  438.         
  439.         try:
  440.             start = time.clock()
  441.             proc = getattr(cls, 'proc', None)
  442.             end = time.clock()
  443.             return end - start
  444.         finally:
  445.             pass
  446.  
  447.  
  448.     kill = classmethod(kill)
  449.     stop = kill
  450.     _start_time = 0
  451.  
  452.  
  453. def get_process_runtime_secs(handle):
  454.     f = ctypes.wintypes.FILETIME()
  455.     ctypes.windll.kernel32.GetSystemTimeAsFileTime(ctypes.byref(f))
  456.     (c, e, k, u) = (ctypes.wintypes.FILETIME(), ctypes.wintypes.FILETIME(), ctypes.wintypes.FILETIME(), ctypes.wintypes.FILETIME())
  457.     ctypes.windll.kernel32.GetProcessTimes(handle, ctypes.byref(c), ctypes.byref(e), ctypes.byref(k), ctypes.byref(u))
  458.     seconds_run = ((f.dwHighDateTime << 32) + f.dwLowDateTime - ((c.dwHighDateTime << 32) + c.dwLowDateTime)) / (1 * 10000000)
  459.     return seconds_run
  460.  
  461.  
  462. def test_conditions(useridlems):
  463.     pref = pref
  464.     import common
  465.     idle_time = pref('research.idle_time_ms', default = pref('research.idle_time_min', default = DEFAULT_IDLE_MINUTES, type = int) * 60 * 1000, type = int)
  466.     if useridlems < idle_time:
  467.         if not pref('research.always_on', default = False):
  468.             return False
  469.     
  470.     import wx
  471.     if wx.GetPowerType() != wx.POWER_SOCKET and not pref('research.battery_override', False):
  472.         return False
  473.     return bool(get_research_pref())
  474.  
  475.  
  476. def get_research_pref():
  477.     import common
  478.     return common.profile.localprefs['research.enabled']
  479.  
  480.  
  481. def set_research_pref(val):
  482.     import common
  483.     common.profile.localprefs['research.enabled'] = val
  484.  
  485.  
  486. def get_cpu_percent(chassis_percent = None):
  487.     if chassis_percent is None:
  488.         chassis_percent = Driver.chassis_desired_cpuUsage()
  489.     
  490.     import common
  491.     
  492.     try:
  493.         return int(common.profile.localprefs['research.cpu_percent'])
  494.     except (KeyError, AttributeError):
  495.         _e = None
  496.         chassis_percent = float(chassis_percent)
  497.         chassis_percent *= 100
  498.         
  499.         try:
  500.             if chassis_percent < common.profile.defaultprefs.get('research.cpu_percent', chassis_percent):
  501.                 return min(chassis_percent, common.pref('research.cpu_percent', chassis_percent, type = float))
  502.             return common.pref('research.cpu_percent', chassis_percent, type = float)
  503.         except AttributeError:
  504.             _e2 = None
  505.             return common.pref('research.cpu_percent', chassis_percent, type = float)
  506.         
  507.  
  508.         None<EXCEPTION MATCH>AttributeError
  509.  
  510.  
  511.  
  512. def get_bandwidth_percent():
  513.     import common
  514.     
  515.     try:
  516.         return common.profile.localprefs['research.bandwidth_percent']
  517.     except KeyError:
  518.         return common.pref('research.bandwidth_percent', DEFAULT_BANDWIDTH_PERCENT, type = float)
  519.  
  520.  
  521.  
  522. def control(useridlems):
  523.     if Driver.is_dead():
  524.         return 2000
  525.     if not test_conditions(useridlems):
  526.         
  527.         try:
  528.             Driver.stop()
  529.         except Exception:
  530.             Driver.is_dead()
  531.             Driver.is_dead()
  532.             traceback.print_exc()
  533.         except:
  534.             Driver.is_dead()
  535.  
  536.         if Driver._start_time != 0:
  537.             log.debug('tried to run for %s', default_timer() - Driver._start_time)
  538.         
  539.         Driver._start_time = 0
  540.     else:
  541.         
  542.         try:
  543.             profile = profile
  544.             import common
  545.             ret = Driver.start(profile)
  546.         except Exception:
  547.             Driver.is_dead()
  548.             Driver.is_dead()
  549.             traceback.print_exc()
  550.         except:
  551.             Driver.is_dead()
  552.  
  553.         if ret == STARTED:
  554.             Driver._start_time = default_timer()
  555.         elif ret == FAILED_TO_START:
  556.             Driver._start_time = 0
  557.         elif ret == ALREADY_RUNNING:
  558.             return 500
  559.         return 500
  560.     return test_conditions(useridlems)
  561.  
  562.  
  563. def check_cli_args(*a):
  564.     import sys
  565.     set_val = sys.opts.set_plura_option
  566.     if set_val is None:
  567.         return None
  568.     log.info('setting intial research pref to %r', set_val)
  569.     set_research_pref(set_val)
  570.  
  571. inited = False
  572.  
  573. def init(*a, **k):
  574.     global inited
  575.     if not inited:
  576.         inited = True
  577.         import atexit
  578.         atexit.register(Driver.kill)
  579.     
  580.  
  581.