def __safe_call__ (self): app_id = CTK.cfg.get_val('tmp!market!install!app!application_id') app_name = CTK.cfg.get_val('tmp!market!install!app!application_name') info = {'cherokee_version': VERSION, 'system': SystemInfo.get_info()} xmlrpc = XmlRpcServer (OWS_APPS_INSTALL, user=OWS_Login.login_user, password=OWS_Login.login_password) install_info = xmlrpc.get_install_info (app_id, info) Install_Log.log ("Waiting for the payment acknowledge…") box = CTK.Box() if install_info.get('due_payment'): set_timeout_js = "setTimeout (reload_druid, %s);" %(PAYMENT_CHECK_TIMEOUT) box += CTK.RawHTML ("<h2>%s %s</h2>"%(_('Checking out'), app_name)) box += CTK.RawHTML ('<h1>%s</h1>' %(_("Waiting for the payment acknowledge…"))) box += CTK.RawHTML (js="function reload_druid() {%s %s}" %(CTK.DruidContent__JS_to_goto (box.id, URL_INSTALL_PAY_CHECK), set_timeout_js)) box += CTK.RawHTML (js=set_timeout_js) buttons = CTK.DruidButtonsPanel() buttons += CTK.DruidButton_Close(_('Cancel')) box += buttons else: Install_Log.log ("Payment ACK!") # Invalidate 'My Library' cache MyLibrary.Invalidate_Cache() # Move on CTK.cfg['tmp!market!install!download'] = install_info['url'] box += CTK.DruidContent__JS_to_goto (box.id, URL_INSTALL_DOWNLOAD) return box.Render().toStr()
def launch_service(service): """Launch the system service specified as parameter. launch_service() returns a dictionary with the following keys: command: command retcode: return code of the execution of specified command. 0 on success. error: error message stdout: standard output of execution stderr: error buffer of execution""" # System info retrival system_info = SystemInfo.get_info() OS = system_info.get("system", "").lower() distro = system_info.get("linux_distro_id", "").lower() # Select the command if distro in ("fedora", "redhat", "centos", "suse", "opensuse"): cmd = "service %(service)s start" % (locals()) elif OS == "linux": cmd = "/etc/init.d/%(service)s start" % (locals()) elif OS == "darwin": cmd = "launchctl start %(service)s" % (locals()) elif OS == "freebsd": if os.path.isfile("/usr/local/etc/rc.d/%(service)s" % (locals())): cmd = "/usr/local/etc/rc.d/%(service)s start" % (locals()) else: cmd = "/etc/rc.d/%(service)s start" % (locals()) # Execution ret = _exe(cmd, _("Could not launch <em>%(service)s</em> service.") % (locals())) return ret
def monitorHardSpace(monitorSystemObject,saveDbMsgDict): """ 1.根据硬盘配置的告警阀值,发送报警信息 @monitorSystemObject {'cpu_idle_limit':cpu_idle_limit,'memory_avi_limit':memory_avi_limit,'hardspace_name':hardspace_name,'hardspace_limit':hardspace_limit} """ hardSpaceList=SystemInfo.getHardSpace()#[(文件系统,总计大小,已用空间,可用空间,已用%,挂载点)] saveDbMsgDict['hardSpace']=hardSpaceList warnToPersonList=[] monitorDiskObjectList=[] if monitorSystemObject.has_key('hardspace_name')==False or monitorSystemObject.has_key('hardspace_limit')==False: return warnToPersonList elif len(monitorSystemObject['hardspace_name'].split('||'))<>len(monitorSystemObject['hardspace_limit'].split('||')): log.info('磁盘监控:monitor_pt_system_info表的hardspace_name值与hardspace_limit值配置的不完全匹配') return warnToPersonList for i in range(len(monitorSystemObject['hardspace_name'].split('||'))): monitorDiskObjectList.append({'hardspace_name':monitorSystemObject['hardspace_name'].split('||')[i],'hardspace_limit':monitorSystemObject['hardspace_limit'].split('||')[i]}) for monitorDiskObject in monitorDiskObjectList: try: if monitorDiskObject.has_key('hardspace_name') and monitorDiskObject['hardspace_limit'].isdigit(): for hardSpace in hardSpaceList:#(文件系统,已用空间,可用空间,已用%,挂载点) if monitorDiskObject['hardspace_name']==hardSpace[0] and float(hardSpace[4])>=float(monitorDiskObject['hardspace_limit']): log.info("磁盘空间告警: hardspace_name:%s,limit_used_percent:%s,real_used_percent:%s",monitorDiskObject['hardspace_name'],monitorDiskObject['hardspace_limit'],hardSpace[4]) warnStr=MONITOR_NAME+' 磁盘空间告警:hardspace_name:'+monitorDiskObject['hardspace_name']+' limit_used_percent:'+monitorDiskObject['hardspace_limit']+' real_used_percent:'+hardSpace[4] warnToPersonList.append(warnStr) elif monitorDiskObject['hardspace_name']==hardSpace[0]: log.info("磁盘空间:达不到告警阀值 hardspace_name:%s,limit_used_percent:%s,real_used_percent:%s",monitorDiskObject['hardspace_name'],monitorDiskObject['hardspace_limit'],hardSpace[4]) except Exception: log.exception('磁盘监控报错:%s,告警阀值为:%s',monitorDiskObject['hardspace_name'],monitorDiskObject['hardspace_limit']) return warnToPersonList
def launch_service(service): """Launch the system service specified as parameter. launch_service() returns a dictionary with the following keys: command: command retcode: return code of the execution of specified command. 0 on success. error: error message stdout: standard output of execution stderr: error buffer of execution""" # System info retrival system_info = SystemInfo.get_info() OS = system_info.get('system', '').lower() distro = system_info.get('linux_distro_id', '').lower() # Select the command if distro in ('fedora', 'redhat', 'centos', 'suse', 'opensuse'): cmd = 'service %(service)s start' % (locals()) elif OS == 'linux': cmd = '/etc/init.d/%(service)s start' % (locals()) elif OS == 'darwin': cmd = 'launchctl start %(service)s' % (locals()) elif OS == 'freebsd': if os.path.isfile('/usr/local/etc/rc.d/%(service)s' % (locals())): cmd = '/usr/local/etc/rc.d/%(service)s start' % (locals()) else: cmd = '/etc/rc.d/%(service)s start' % (locals()) # Execution ret = _exe( cmd, _('Could not launch <em>%(service)s</em> service.') % (locals())) return ret
def make_install_init (self): # System Info system_info = SystemInfo.get_info() OS = system_info.get('system','').lower() # Fetch Parameters root = CTK.cfg.get_val ('%s!root' %(PRE)) nagiosuser = CTK.cfg.get_val ('%s!nagiosuser' %(PRE)) if OS == 'linux': ret = popen.popen_sync ("make install-init", cd="%(root)s/nagios_core"%(locals())) if ret['retcode']: return ret elif OS == 'darwin': path_pre = os.path.join (root, 'nrpe.plist.pre') path_plist = os.path.join (root, 'nrpe.plist') # Build plist file plist = open (path_pre, 'r').read() plist = plist.replace ('${UserName}', nagiosuser) plist = plist.replace ('${WorkingDirectory}', os.path.join (root, 'nagios')) f = open (path_plist, 'w+') f.write (plist) f.close() else: # Default case. ret = popen.popen_sync ("make install-init", cd="%(root)s/nagios_core"%(locals())) if ret['retcode']: return ret return {'retcode': 0}
def get_installation_GID(): root_group = SystemInfo.get_info()['group_root'] try: groups = os.getgroups() groups.sort() first_group = str(groups[0]) except OSError as e: # os.getgroups can fail when run as root (MacOS X 10.6) if os.getuid() != 0: raise e first_group = str(root_group) # Systems if sys.platform.startswith('linux'): if os.getuid() == 0: return root_group return first_group elif sys.platform == 'darwin': if os.getuid() == 0: return root_group return first_group # Solaris RBAC, TODO if os.getuid() == 0: return root_group return first_group
def monitorProcExist(monitorObjectList): """ 判断指定的线程是否有存在。 @monitorObjectList: [{'proc_name':procName,'proc_cpu_limit':procCpuLimit}] """ warnToPersonList=[] procNameMap={} for monitorProcObject in monitorObjectList: if procNameMap.has_key(monitorProcObject['proc_name'])==False: procNameMap[monitorProcObject['proc_name']]=False pidObjectList=SystemInfo.getCPUUsedByPidName(procNameMap.keys()) if pidObjectList==None: log.info('psutil的插件没有安装,或者不支持psutil的低版本的linux。') return warnToPersonList for pidObject in pidObjectList:#如果线程已经存在,将状态设置成True procNameMap[pidObject[0]]=True warnStr='' for procName,isExist in procNameMap.iteritems(): if isExist==False and len(warnStr)==0: warnStr=MONITOR_NAME+' 线程告警:线程名称:'+procName+'不存在.' elif isExist==False: warnStr+=',线程名称:'++procName+'不存在.' if len(warnStr)>0: log.info('线程告警: %s',warnStr) warnToPersonList.append(warnStr) return warnToPersonList
def __safe_call__ (self): box = CTK.Box() buttons = CTK.DruidButtonsPanel() pre = 'tmp!market!install' root = CTK.cfg.get_val ('%s!root' %(pre)) project = os.path.join (root, 'project') trac_src = os.path.join (root, 'trac') trac_admin = os.path.join (root, 'bin', 'trac-admin') easy_bin = os.path.join (root, 'bin', 'easy_install') group_root = SystemInfo.get_info()['group_root'] server_user = CTK.cfg.get_val ('server!user', 'root') server_group = CTK.cfg.get_val ('server!group', group_root) # Figure out PYTHONPATH ret = popen.popen_sync ('python setup.py install --prefix=%(root)s'%(locals()), cd = '%(root)s/Genshi-0.6'%(locals())) err = ret['stderr'] + ret['stdout'] # Python 2.4.3 actually succeeds tmp = re.findall (r' (%(root)s.+site-packages)'%(locals()), err) PYTHONPATH = tmp[0] CTK.cfg['tmp!market!install!trac!PYTHONPATH'] = PYTHONPATH # Create site-packages if not os.path.isdir (PYTHONPATH): os.makedirs (PYTHONPATH) # Build PYTHONPATH env = os.environ.copy() if 'PYTHONPATH' in env: env['PYTHONPATH'] = '%s:%s' %(PYTHONPATH, env['PYTHONPATH']) else: env['PYTHONPATH'] = PYTHONPATH # Installation tasks = [ # Install dependencies ({'command': "python setup.py install --prefix=${app_root}", 'env': env, 'cd': '%(root)s/flup-1.0.2' %(locals())}), ({'command': "python setup.py install --prefix=${app_root}", 'env': env, 'cd': '%(root)s/Genshi-0.6' %(locals())}), #({'command': "python setup.py install --prefix=${app_root}", 'env': env, 'cd': '%(root)s/pysqlite-2.6.0'%(locals())}), ({'function': tools.install_pysqlite, 'description': _('Satisfying pysqlite requirements'), 'params' : {'root':root, 'env':str(env)}}), ({'command': "python %(trac_src)s/setup.py install --prefix=${app_root}" %(locals()), 'env': env, 'cd': trac_src}), # Create Project ({'command': "%(trac_admin)s %(project)s initenv <<EOF\nTrac\n\nEOF\n" %(locals()), 'env': env}), ({'command': "chown -R %(server_user)s:%(server_group)s %(project)s" %(locals())})] box += CTK.RawHTML ('<h2>%s</h2>' %(_('Installing Trac'))) box += CTK.RawHTML ('<p>%s</p>' %(_('This process may take a while. Please, hold on.'))) box += CommandProgress (tasks, URL_USER_CONFIG) buttons = CTK.DruidButtonsPanel() buttons += CTK.DruidButton_Close(_('Cancel')) box += buttons return box.Render().toStr()
def get_installation_GID(): groups = os.getgroups() root_group = SystemInfo.get_info()['group_root'] if sys.platform == 'linux2': return (str(groups[0]), root_group)[0 in groups] elif sys.platform == 'darwin': return (str(groups[0]), root_group)[0 in groups] # Solaris RBAC, TODO return (str(whoami), root_group)[whoami == 0]
def get_installation_GID(): root_group = SystemInfo.get_info()['group_root'] try: groups = os.getgroups() groups.sort() first_group = str(groups[0]) except OSError,e: # os.getgroups can fail when run as root (MacOS X 10.6) if os.getuid() != 0: raise e first_group = str(root_group)
def get_installation_GID(): root_group = SystemInfo.get_info()['group_root'] try: groups = os.getgroups() groups.sort() first_group = str(groups[0]) except OSError, e: # os.getgroups can fail when run as root (MacOS X 10.6) if os.getuid() != 0: raise e first_group = str(root_group)
def __safe_call__(self): box = CTK.Box() box += CTK.RawHTML('<h2>%s</h2>' % (_("Nagios start up"))) system_info = SystemInfo.get_info() OS = system_info.get('system', '').lower() root = CTK.cfg.get_val('%s!root' % (PRE)) startup = CTK.cfg.get_val('%s!nagiosstartup' % (PRE)) plist = os.path.join(root, 'nrpe.plist') # Register service: init.d, launchd, etc. ret = services.register_service('nagios', macos_plist=plist) if ret['retcode'] == 0: # Launch if startup: if OS == 'darwin': services.launch_service('org.nagios.nrpe') else: services.launch_service('nagios') box += CTK.RawHTML( js=CTK.DruidContent__JS_to_goto(box.id, URL_SERVER_CONFIG)) return box.Render().toStr() # Error handling notice = CTK.Notice() notice += CTK.RawHTML('<p>%s</p>' % (_( 'The installer could not successfully execute the following command:' ))) notice += CTK.RawHTML('<pre>%s</pre>' % (ret['command'])) notice += CTK.RawHTML('<p>%s</p>' % (_('The reported error was:'))) notice += CTK.RawHTML('<pre>%s</pre>' % (ret['stderr'])) box += CTK.RawHTML('<p>%s</p>' % (ret['error'])) box += notice box += CTK.RawHTML('<p>%s</p>' % (_( 'You can either manually fix the problem and retry, or you can skip the step knowing that the Nagios system service will not be launched at boot time.' ))) buttons = CTK.DruidButtonsPanel() buttons += CTK.DruidButton_Close(_('Cancel')) buttons += CTK.DruidButton_Goto(_('Retry'), URL_LAUNCH_SERVICE, do_submit=True) buttons += CTK.DruidButton_Goto(_('Skip'), URL_SERVER_CONFIG, do_submit=True) box += buttons return box.Render().toStr()
def add_group(group_name, group_id=None): """Add group to the system in a platform independent manner. Currently supports Linux, MacOS X, and FreeBSD. A group ID can be specified optionally. Returns the result of a call to _exe() """ error_msg = _('Could not create group.') # Build system command system_info = SystemInfo.get_info() OS = system_info.get('system', '').lower() if OS == 'linux': raw = '/usr/sbin/groupadd %(group_name)s' if group_id: raw += ' --gid %(group_id)s' cmd = raw % (locals()) ret = _exe(cmd, error_msg) return ret elif OS == 'darwin': if not group_id: group_id = find_new_UID_GID_pair() ret = _exe('dscl . -create /Groups/%(group_name)s' % (locals()), error_msg) if ret['retcode']: return ret ret = _exe( 'dscl . -create /Groups/%(group_name)s PrimaryGroupID %(group_id)s' % (locals()), error_msg) if ret['retcode']: return ret ret = _exe( 'dscl . -create /Groups/%(group_name)s RecordName %(group_name)s' % (locals()), error_msg) if ret['retcode']: return ret return ret elif OS == 'freebsd': raw = '/usr/sbin/pw groupadd %(group_name)s' if group_id: raw += ' -g %(group_id)s' cmd = raw % (locals()) ret = _exe(cmd, error_msg) return ret else: assert False, "Not implemented"
def Exception_Handler_Apply(): # Collect information info = {} info['log'] = Install_Log.get_full_log() info['user'] = OWS_Login.login_user info['comments'] = CTK.post['comments'] info['platform'] = SystemInfo.get_info() info['tmp!market!install'] = CTK.cfg['tmp!market!install'].serialize() # Send it xmlrpc = XmlRpcServer (OWS_APPS_INSTALL, user=OWS_Login.login_user, password=OWS_Login.login_password) install_info = xmlrpc.report_exception (info) return CTK.cfg_reply_ajax_ok()
def monitorCpu(cpuIdleLimit,saveDbMsgDict): """ 1.根据CPU Idle的告警阀值,发送告警信息 """ warnToPersonList=[] cpuIdle=SystemInfo.getCpuIdle() if cpuIdle==None: log.info('psutil的插件没有安装,或者不支持psutil的低版本的linux。') return warnToPersonList saveDbMsgDict['cpuIdle']=cpuIdle if cpuIdleLimit.isdigit() and cpuIdle<float(cpuIdleLimit): log.info("CPU Idle告警: cpuIdle_limit:%s,real_cpuIdle:%s",cpuIdleLimit,str(cpuIdle)) warnStr=MONITOR_NAME+' CPU Idle告警:cpuIdle_limit:'+cpuIdleLimit+' real_cpuIdle:'+str(cpuIdle) warnToPersonList.append(warnStr) return warnToPersonList
def __safe_call__ (self): app_id = CTK.cfg.get_val('tmp!market!install!app!application_id') app_name = CTK.cfg.get_val('tmp!market!install!app!application_name') info = {'cherokee_version': VERSION, 'system': SystemInfo.get_info()} cont = CTK.Box() xmlrpc = XmlRpcServer (OWS_APPS_INSTALL, user=OWS_Login.login_user, password=OWS_Login.login_password) install_info = xmlrpc.get_install_info (app_id, info) if install_info.get('error'): title = install_info['error']['error_title'] errors = install_info['error']['error_strings'] cont += CTK.RawHTML ("<h2>%s</h2>"%(_(title))) for error in errors: cont += CTK.RawHTML ("<p>%s</p>"%(_(error))) buttons = CTK.DruidButtonsPanel() buttons += CTK.DruidButton_Close(_('Close')) cont += buttons elif install_info['installable']: # Do not change this log line. It is used by the # Maintenance.py file to figure out the app name Install_Log.log ("Checking: %s, ID: %s = Installable, URL=%s" %(app_name, app_id, install_info['url'])) CTK.cfg['tmp!market!install!download'] = install_info['url'] cont += CTK.RawHTML (js = CTK.DruidContent__JS_to_goto (cont.id, URL_INSTALL_DOWNLOAD)) else: Install_Log.log ("Checking: %s, ID: %s = Must check out first" %(app_name, app_id)) cont += CTK.RawHTML ("<h2>%s %s</h2>"%(_('Checking out'), app_name)) cont += CTK.RawHTML ("<p>%s</p>" %(_(NOTE_ALL_READY_TO_BUY_1))) cont += CTK.RawHTML ("<p>%s</p>" %(_(NOTE_ALL_READY_TO_BUY_2))) checkout = CTK.Button (_("Check Out")) checkout.bind ('click', CTK.DruidContent__JS_to_goto (cont.id, URL_INSTALL_PAY_CHECK) + CTK.JS.OpenWindow('%s/order/%s' %(OWS_STATIC, app_id))) buttons = CTK.DruidButtonsPanel() buttons += CTK.DruidButton_Close(_('Cancel')) buttons += checkout cont += buttons return cont.Render().toStr()
def monitorMemory(aviPhymenLimit,saveDbMsgDict): """ 1.根据内存的告警阀值,发送告警信息 2.将内存信息保存到数据库中. """ warnToPersonList=[] memoryObject=SystemInfo.getMemoryInfo() if memoryObject==None: log.info('psutil的插件没有安装,或者不支持psutil的低版本的linux。') return warnToPersonList saveDbMsgDict['memory']=memoryObject if aviPhymenLimit.isdigit() and memoryObject[1]<float(aviPhymenLimit): log.info("内存告警: aviPhymenLimit:%sKB,real_aviPhymen:%sKB",aviPhymenLimit,str(memoryObject[1])) warnStr=MONITOR_NAME+' 内存告警:aviPhymenLimit:'+aviPhymenLimit+'KB real_aviPhymen:'+str(memoryObject[1])+'KB' warnToPersonList.append(warnStr) return warnToPersonList
def Exception_Handler_Apply(): # Collect information info = {} info['log'] = Install_Log.get_full_log() info['user'] = OWS_Login.login_user info['comments'] = CTK.post['comments'] info['platform'] = SystemInfo.get_info() info['cfg'] = CTK.cfg.serialize() info['tmp!market!install'] = CTK.cfg['tmp!market!install'].serialize() # Send it xmlrpc = XmlRpcServer(OWS_APPS_INSTALL, user=OWS_Login.login_user, password=OWS_Login.login_password) install_info = xmlrpc.report_exception(info) return CTK.cfg_reply_ajax_ok()
def add_user_to_group(user, group, primary_group=True): """Add user to an existing group on the system, in a platform independent manner. Currently supports Linux, MacOS X, and FreeBSD. A primary group can be provided optionally, which will be used for MacOS X systems. Returns the result of a call to _exe() """ # Error message error = _( 'Could not add <em>%(user)s</em> user to <em>%(group)s</em> group.' ) % (locals()) # Build system command system_info = SystemInfo.get_info() OS = system_info.get('system', '').lower() if OS == 'linux': cmd = '/usr/sbin/usermod -a -G %(group)s %(user)s' % (locals()) ret = _exe(cmd, error) if ret['retcode'] == 2: # some distros don't need the -a parameter (some SUSE versions) return _exe(cmd.replace('/usermod -a -G', '/usermod -G'), error) return ret elif OS == 'darwin': if primary_group: id_group = group_to_GID(group) cmd = 'dscl localhost -create /Local/Default/Users/%(user)s PrimaryGroupID %(id_group)s' % ( locals()) else: cmd = 'dscl localhost -append /Groups/%(group)s GroupMembership %(user)s' % ( locals()) ret = _exe(cmd, error) return ret elif OS == 'freebsd': cmd = '/usr/sbin/pw usermod %(user)s -G %(group)s' % (locals()) ret = _exe(cmd, error) return ret else: assert False, "Not implemented"
def Report_Apply(): app_id = CTK.post.get_val('app_id') report = CTK.post.get_val('report') app_logs = get_logs (app_id) sysinfo = SystemInfo.get_info() cfg = str(CTK.cfg) # OWS Open xmlrpc = XmlRpcServer(OWS_APPS_CENTER, OWS_Login.login_user, OWS_Login.login_password) try: ok = xmlrpc.report_application (app_id, # int CTK.util.to_unicode(report), # string CTK.util.to_unicode(app_logs), # list CTK.util.to_unicode(sysinfo), # dict CTK.util.to_unicode(cfg)) # string except: ok = False return {'ret': ('error','ok')[ok]}
def __safe_call__ (self): box = CTK.Box() box += CTK.RawHTML ('<h2>%s</h2>' %(_("Nagios start up"))) system_info = SystemInfo.get_info() OS = system_info.get('system','').lower() root = CTK.cfg.get_val ('%s!root' %(PRE)) startup = CTK.cfg.get_val ('%s!nagiosstartup' %(PRE)) plist = os.path.join (root, 'nrpe.plist') # Register service: init.d, launchd, etc. ret = services.register_service ('nagios', macos_plist=plist) if ret['retcode'] == 0: # Launch if startup: if OS == 'darwin': services.launch_service ('org.nagios.nrpe') else: services.launch_service ('nagios') box += CTK.RawHTML (js = CTK.DruidContent__JS_to_goto (box.id, URL_SERVER_CONFIG)) return box.Render().toStr() # Error handling notice = CTK.Notice () notice += CTK.RawHTML ('<p>%s</p>' %(_('The installer could not successfully execute the following command:'))) notice += CTK.RawHTML ('<pre>%s</pre>' %(ret['command'])) notice += CTK.RawHTML ('<p>%s</p>' %(_('The reported error was:'))) notice += CTK.RawHTML ('<pre>%s</pre>' %(ret['stderr'])) box += CTK.RawHTML ('<p>%s</p>' %(ret['error'])) box += notice box += CTK.RawHTML ('<p>%s</p>' %(_('You can either manually fix the problem and retry, or you can skip the step knowing that the Nagios system service will not be launched at boot time.'))) buttons = CTK.DruidButtonsPanel() buttons += CTK.DruidButton_Close(_('Cancel')) buttons += CTK.DruidButton_Goto (_('Retry'), URL_LAUNCH_SERVICE, do_submit=True) buttons += CTK.DruidButton_Goto (_('Skip'), URL_SERVER_CONFIG, do_submit=True) box += buttons return box.Render().toStr()
def get_installation_GID(): root_group = SystemInfo.get_info()['group_root'] groups = os.getgroups() groups.sort() # Systems if sys.platform == 'linux2': if os.getuid() == 0: return root_group return str(groups[0]) elif sys.platform == 'darwin': if os.getuid() == 0: return root_group return str(groups[0]) # Solaris RBAC, TODO if os.getuid() == 0: return root_group return str(groups[0])
def monitorProcCpu(monitorObjectList,saveDbMsgDict): """ 1.根据线程名称获取相应线程的告警信息. @monitorObjectList: [{'proc_name':procName,'proc_cpu_limit':procCpuLimit}] """ warnToPersonList=[] procNameMap={} for monitorProcObject in monitorObjectList: if procNameMap.has_key(monitorProcObject['proc_name'])==False and monitorProcObject['proc_cpu_limit'].isdigit(): procNameMap[monitorProcObject['proc_name']]=monitorProcObject['proc_cpu_limit'] pidObjectList=SystemInfo.getCPUUsedByPidName(procNameMap.keys()) if pidObjectList==None: log.info('psutil的插件没有安装,或者不支持psutil的低版本的linux。') return warnToPersonList saveDBMsgDict['procCpu']=pidObjectList for pidObject in pidObjectList: if pidObject[2]>=float(procNameMap[pidObject[0]]): log.info('线程CPU告警: pid:%s,pid_name:%s,cpu_limit:%s,real_cpu:%s',pidObject[0],pidObject[1],procNameMap[pidObject[0]],str(pidObject[2])) warnStr=MONITOR_NAME+' 线程CPU告警:线程名称:'+pidObject[0]+' 线程ID:'+pidObject[1]+' 阀值:'+procNameMap[pidObject[0]]++' 时间值:'+str(pidObject[2]) warnToPersonList.append(warnStr) return warnToPersonList
def Report_Apply(): app_id = CTK.post.get_val('app_id') report = CTK.post.get_val('report') app_logs = get_logs(app_id) sysinfo = SystemInfo.get_info() cfg = str(CTK.cfg) # OWS Open xmlrpc = XmlRpcServer(OWS_APPS_CENTER, OWS_Login.login_user, OWS_Login.login_password) try: ok = xmlrpc.report_application( app_id, # int CTK.util.to_unicode(report), # string CTK.util.to_unicode(app_logs), # list CTK.util.to_unicode(sysinfo), # dict CTK.util.to_unicode(cfg)) # string except: ok = False return {'ret': ('error', 'ok')[ok]}
def ListApps_Apply(): system_info = SystemInfo.get_info() OS = system_info.get('system','').lower() # Check the apps to remove apps_to_remove = [] for k in CTK.post.keys(): if k.startswith ('remove_'): app = k[7:] if CTK.post.get_val(k) == '1': apps_to_remove.append (app) if not apps_to_remove: return {'ret': 'fail'} # Store databases to remove for n in range (len(apps_to_remove)): CTK.cfg ['admin!market!maintenance!remove!%s!del' %(app)] = '1' # Remove services for app in apps_to_remove: service = CTK.cfg.get_val ('admin!market!maintenance!remove!%s!service'%(app)) if service: if OS == 'darwin': popen.popen_sync ('launchctl unload %(service)s' %(locals())) elif OS == 'linux': popen.popen_sync ('rm -f /etc/rcS.d/S99%(service)s' %(locals())) print "Remove service", service # Perform the app removal for app in apps_to_remove: fp = os.path.join (CHEROKEE_OWS_ROOT, app) popen.popen_sync ("rm -rf '%s'" %(fp)) # The cache is no longer valid Invalidate_Cache() return CTK.cfg_reply_ajax_ok()
def ListApps_Apply(): system_info = SystemInfo.get_info() OS = system_info.get('system', '').lower() # Check the apps to remove apps_to_remove = [] for k in CTK.post.keys(): if k.startswith('remove_'): app = k[7:] if CTK.post.get_val(k) == '1': apps_to_remove.append(app) # Something to do? if not apps_to_remove: return {'ret': 'fail'} # Store apps to remove for app in apps_to_remove: CTK.cfg['tmp!market!maintenance!remove!%s!del' % (app)] = '1' return CTK.cfg_reply_ajax_ok()
def ListApps_Apply(): system_info = SystemInfo.get_info() OS = system_info.get('system','').lower() # Check the apps to remove apps_to_remove = [] for k in CTK.post.keys(): if k.startswith ('remove_'): app = k[7:] if CTK.post.get_val(k) == '1': apps_to_remove.append (app) # Something to do? if not apps_to_remove: return {'ret': 'fail'} # Store apps to remove for app in apps_to_remove: CTK.cfg ['tmp!market!maintenance!remove!%s!del' %(app)] = '1' return CTK.cfg_reply_ajax_ok()
def choose_instructions (self, instructions): data = SystemInfo.get_info() system = data.get('system','').lower() distro = data.get('linux_distro_id','').lower() info = instructions.get('generic') # OS specific if instructions.has_key(system): return instructions[system] # Linux distro specific if instructions.has_key(distro): return instructions[distro] # Linux distro generic for x in ('red hat', 'redhat', 'fedora', 'centos', 'suse'): if x in distro: return instructions.get('yum', info) for x in ('debian', 'ubuntu', 'knoppix', 'mint'): if x in distro: return instructions.get('apt', info)
def monitorDisk(monitorSystemObject,saveDbMsgDict): """ @monitorSystemObject {'cpu_idle_limit':cpu_idle_limit,'memory_avi_limit':memory_avi_limit,'hardspace_name':hardspace_name,'hardspace_limit':hardspace_limit} hardspace_name:有可能是用||分隔的多行参数.hardspace_limit:有可能是ongoing||分隔的多行. windows 版本的磁盘空间检查,monitorDiskOjectList [{'hardspace_name':hardspace_name,'hardspace_limit':hardspace_limit}] """ warnToPersonList=[] monitorDiskObjectList=[] saveToDBList=[]#[(文件系统,总计大小,已用空间,可用空间,已用%,挂载点)] if monitorSystemObject.has_key('hardspace_name')==False or monitorSystemObject.has_key('hardspace_limit')==False: return warnToPersonList elif len(monitorSystemObject['hardspace_name'].split('||'))<>len(monitorSystemObject['hardspace_limit'].split('||')): log.info('磁盘监控:monitor_pt_system_info表的hardspace_name值与hardspace_limit值配置的不完全匹配') return warnToPersonList for i in range(len(monitorSystemObject['hardspace_name'].split('||'))): monitorDiskObjectList.append({'hardspace_name':monitorSystemObject['hardspace_name'].split('||')[i],'hardspace_limit':monitorSystemObject['hardspace_limit'].split('||')[i]}) saveDbMsgDict['hardSpace']=saveToDBList for monitorDiskObject in monitorDiskObjectList: try: log.info('磁盘告警配置:%s',str(monitorDiskObject)) if monitorDiskObject['hardspace_name'].strip()=='': break #if monitorDiskObject['hardspace_limit'].isdigit(): try: total,used,free,usedPecent=SystemInfo.getdiskByPath(monitorDiskObject['hardspace_name']) saveToDBList.append((monitorDiskObject['hardspace_name'],str(total/1024),str(used/1024),str(free/1024),str(usedPecent),'')) limitPercent=float(monitorDiskObject['hardspace_limit']) if usedPecent>=limitPercent: log.info("磁盘空间告警: hardspace_name:%s,limit_used_percent:%s,real_used_percent:%s",monitorDiskObject['hardspace_name'],monitorDiskObject['hardspace_limit'],str(round(usedPecent,2))) warnStr=MONITOR_NAME+' 磁盘空间告警:hardspace_name:'+monitorDiskObject['hardspace_name']+' limit_used_percent:'+monitorDiskObject['hardspace_limit']+' real_used_percent:'+str(round(usedPecent,2)) warnToPersonList.append(warnStr) except ValueError: log.info('磁盘告警配置,磁盘空间%s的阀值非数值=%s',monitorDiskObject['hardspace_name'],monitorDiskObject['hardspace_limit']) except Exception: log.exception('获取磁盘空间报错。磁盘为:'+monitorDiskObject['hardspace_name']) return warnToPersonList
def Heart(): magicNumber = RandomMagicString() while True: sysInfoDict = SystemInfo.SystemDetail() params = urllib.parse.urlencode(sysInfoDict) url = 'http://' + IPAdress + ':' + str( Port) + "/heart?%s" % params + "&magicnumber=" + magicNumber #print(url) f = urllib.request.urlopen(url) returnMessage = f.read().decode('utf-8') if returnMessage == 'true': pass elif returnMessage.startswith('command'): print(returnMessage[7:]) result = Command.RunExe(returnMessage[7:]) url = 'http://' + IPAdress + ':' + str( Port) + "/commandresult?result=" + str( result) + "&magicnumber=" + str(magicNumber) f = urllib.request.urlopen(url) returnMessage = f.read().decode('utf-8') print("commandresult" + returnMessage) time.sleep(Interval)
def make_install_init(self): # System Info system_info = SystemInfo.get_info() OS = system_info.get('system', '').lower() # Fetch Parameters root = CTK.cfg.get_val('%s!root' % (PRE)) nagiosuser = CTK.cfg.get_val('%s!nagiosuser' % (PRE)) if OS == 'linux': ret = popen.popen_sync("make install-init", cd="%(root)s/nagios_core" % (locals())) if ret['retcode']: return ret elif OS == 'darwin': path_pre = os.path.join(root, 'nrpe.plist.pre') path_plist = os.path.join(root, 'nrpe.plist') # Build plist file plist = open(path_pre, 'r').read() plist = plist.replace('${UserName}', nagiosuser) plist = plist.replace('${WorkingDirectory}', os.path.join(root, 'nagios')) f = open(path_plist, 'w+') f.write(plist) f.close() else: # Default case. ret = popen.popen_sync("make install-init", cd="%(root)s/nagios_core" % (locals())) if ret['retcode']: return ret return {'retcode': 0}
from wxHelper import GUI_ID, XrcControls, getAccelPairFromKeyDown, ModalDialogMixin, WindowUpdateLocker from StringOps import unescapeForIni import SystemInfo import Utilities from TempFileSet import TempFileSet try: import WindowsHacks except: if SystemInfo.isWindows(): traceback.print_exc() WindowsHacks = None class IncrementalSearchDialog(wx.Frame): COLOR_YELLOW = wx.Colour(255, 255, 0) COLOR_GREEN = wx.Colour(0, 255, 0) def __init__(self, parent, id, txtCtrl, rect, font, mainControl, searchInit=None): # Frame title is invisible but is helpful for workarounds with # third-party tools wx.Frame.__init__( self, parent,
ShowRec(10,10,width-20,height-80,White,1) ShowLine(10,height/5,width-10,height/5) ShowLine(10,height/5*3,width-10,height/5*3) ShowLine(width/2,height/5,width/2,height-70) ShowLine(width/4,height/5*3,width/4,height-70) ShowLine(width/4*3,height/5*3,width/4*3,height-70) #time show mylocaltime=time.localtime() myclock=time.strftime("%H:%M:%S",mylocaltime)#13:15:03 2017-04-21 ShowStr(myclock,0,0,200) mydate=time.strftime("%Y-%m-%d",mylocaltime)#2017-04-21 ShowStr(mydate,810,5,90) mytime=time.strftime("%A",mylocaltime)#Thursday ShowStr(mytime,810,100,90) #cpu_usage show ip = SystemInfo.get_ip('wlan0') cpu_usage =SystemInfo.getCPUuse() ShowStr(ip,width/2+20,height/5*2+160,48) ShowRec(width/2+20,height/5*2+110,cpu_usage/100*600+20,48,Yellow,0) ShowStr("CPU usage:"+str("%2d"%cpu_usage)+"%",width/2+20,height/5*2+110,48) #netspeed show NetInfoOld=SystemInfo.net_stat() time.sleep(1) NetInfoNew=SystemInfo.net_stat() DownloadSpeed=(NetInfoNew[0]["ReceiveBytes"]-NetInfoOld[0]["ReceiveBytes"])/1048576 #last second total flow -current second total flow UploadSpeed=(NetInfoNew[0]["TransmitBytes"]-NetInfoOld[0]["TransmitBytes"])/1048576 ShowRec(width/2+20,height/5*2+10,DownloadSpeed/10*600+20,48,Green,0) ShowRec(width/2+20,height/5*2+60,UploadSpeed/10*600+20,48,LightBlue,0) ShowStr("↓:"+str("%3.2f"%(DownloadSpeed))+"MB/s",width/2+20,height/5*2+10,48) ShowStr("↑:"+str("%3.2f"%(UploadSpeed))+"MB/s",width/2+20,height/5*2+60,48)
def register_service(service, macos_plist=None): """Register system service so that it is started at boot time. The name of the service should be provided. On MacOS X, an additional Launchd service file must be specified. register_service() returns a dictionary with the following keys: command: command retcode: return code of the execution of specified command. 0 on success. error: error message stdout: standard output of execution stderr: error buffer of execution""" # System info retrival system_info = SystemInfo.get_info() OS = system_info.get("system", "").lower() distro = system_info.get("linux_distro_id", "").lower() # Execute command error_msg = _("Could not add <em>%(service)s</em> to list of system services.") % (locals()) if distro in ("fedora", "redhat", "centos", "suse", "opensuse"): ret = _exe("chkconfig --add %(service)s" % (locals()), error_msg) if ret["retcode"]: return ret ret = _exe("chkconfig %(service)s on" % (locals()), error_msg) if ret["retcode"]: return ret # Log (do not change string, check Maintenance.py) Install_Log.log("Registered system service: %(service)s" % (locals())) return ret elif OS == "linux": cmd = "ln -s /etc/init.d/%(service)s /etc/rcS.d/S99%(service)s" % (locals()) ret = _exe(cmd, error_msg) if ret["retcode"]: return ret # Log (do not change string, check Maintenance.py) Install_Log.log("Registered system service: %(service)s" % (locals())) return ret elif OS == "darwin": assert macos_plist, "Launchd service file not provided" cmd = "launchctl load %(macos_plist)s" % (locals()) ret = _exe(cmd, error_msg) if ret["retcode"]: return ret # Log (do not change string, check Maintenance.py) Install_Log.log("Registered Launchd service: %(macos_plist)s" % (locals())) return ret elif OS == "freebsd": # Find out variable name for rc (coded in init script) cmd = None for path in ("/usr/local/etc/rc.d", "/etc/rc.d"): if os.path.exists("%(path)s/%(service)s" % (locals())) and os.access( "%(path)s/%(service)s" % (locals()), os.X_OK ): cmd = "%(path)s/%(service)s rcvar" % (locals()) assert cmd, "Init script not present on /etc/rc.d or /usr/local/etc/rc.d" ret = _exe(cmd, error_msg) rcvar = re.findall("^([^#].*)=", ret["stdout"], re.M)[0] # Read init file (to add or modify if entry already present) lines = open("/etc/rc.conf", "r").readlines() content = "" for line in lines: if re.findall(r"%(rcvar)s=.+" % (locals()), line): content += '%(rcvar)s="YES"\n' % (locals()) else: content += line if content == "".join(lines): content += '%(rcvar)s="YES"\n' % (locals()) # Write try: open("/etc/rc.conf", "w").write(content) # Log (do not change string, check Maintenance.py) Install_Log.log("Registered BSD service: %(rcvar)s" % (locals())) except: raise return ret assert False, "Unknown platform: %s" % (str(system_info))
def choose_instructions(self, instructions, kwargs={}): data = SystemInfo.get_info() system = data.get("system", "").lower() distro = data.get("linux_distro_id", "").lower() default = instructions.get("default") # Optional parameters bin_path = kwargs.get("bin_path") # MacPorts if system == "darwin" and data.get("macports"): macports_path = data.get("macports_path") # Do not suggest macports if the bin is outside its scope: # /usr/local, for instance. if (not bin_path) or (macports_path and bin_path.startswith(macports_path)): return [instructions.get("macports", default)] # FreeBSD: pkg_add *and* ports if system == "freebsd": choices = [] if instructions.has_key("freebsd_pkg"): choices += [instructions.get("freebsd_pkg")] if data.get("freebsd_ports_path") and instructions.has_key("freebsd_ports"): choices += [instructions.get("freebsd_ports")] if choices: return choices # Solaris' IPS if system.startswith("sunos"): if os.path.exists("/usr/bin/pkg"): return [instructions.get("ips", default)] # OS specific if instructions.has_key(system): return [instructions.get(system, default)] # Linux distro specific if instructions.has_key(distro): return [instructions.get(distro, default)] # Linux distro generic for x in ("red hat", "redhat", "centos"): if x in distro: return [instructions.get("yum", default)] for x in ("fedora",): if x in distro: return [instructions.get("yumfedora", instructions.get("yum", default))] for x in ("suse",): if x in distro: return [instructions.get("zypper", default)] for x in ("debian", "ubuntu", "knoppix", "mint"): if x in distro: return [instructions.get("apt", default)] # Default return [default]
def add_user_and_group(user, **kw): """Add user and group to the system in a platform independent manner. Currently supports Linux, MacOS X, and FreeBSD. If only a user-name is specified, it will also be used as group-name. The following named arguments are taken into account: group, homedir, shell. Returns the result of a call to _exe() """ assert user error_msg = _('Could not create user.') # Extract parameters group = kw.get('group', user) homedir = kw.get('homedir') shell = kw.get('shell') # Build system command system_info = SystemInfo.get_info() OS = system_info.get('system', '').lower() if OS == 'linux': # Ensure group is present. if not group_exists(group): ret = add_group(group) if ret['retcode']: return ret # Create the user raw = '/usr/sbin/useradd --gid %(group)s -r %(user)s' # -r == --system, but --system is not supported everywhere if homedir: raw += ' -d %(homedir)s ' # --home-dir not recognized on SuSE if shell: raw += ' -s %(shell)s ' # --shell not recognized on SuSE cmd = raw % (locals()) # Run it ret = _exe(cmd, error_msg) if ret['retcode']: return ret elif OS == 'darwin': # Take care of the GID if not group_exists(group): dual_id = find_new_UID_GID_pair() id_user = dual_id id_group = dual_id # Create Group ret = add_group(group, id_group) if ret['retcode']: return ret else: id_group = group_to_GID(group) # Figure the new UID if not UID_exists(id_group): id_user = id_group else: id_user = find_new_UID(start=id_group) # Create user shell = shell or '/usr/bin/false' base = 'dscl localhost -create /Local/Default/Users/%(user)s' ret = _exe(base % locals(), error_msg) if ret['retcode']: return ret # Set user details ret = _exe((base + ' UniqueID %(id_user)s') % locals(), error_msg) if ret['retcode']: return ret ret = _exe((base + ' PrimaryGroupID %(id_group)s') % locals(), error_msg) if ret['retcode']: return ret ret = _exe((base + ' RecordName %(user)s') % locals(), error_msg) if ret['retcode']: return ret ret = _exe((base + ' UserShell %(shell)s') % locals(), error_msg) if ret['retcode']: return ret elif OS == 'freebsd': # Ensure group is present. if not group_exists(group): ret = add_group(group) if ret['retcode']: return ret # Create the user raw = '/usr/sbin/pw useradd %(user)s -g %(group)s' if homedir: raw += ' -d %(homedir)s ' if shell: raw += ' -s %(shell)s ' cmd = raw % (locals()) # Run it ret = _exe(cmd, error_msg) return ret else: assert False, "Not implemented" return ret
def choose_instructions(self, instructions, kwargs={}): data = SystemInfo.get_info() system = data.get('system', '').lower() distro = data.get('linux_distro_id', '').lower() default = instructions.get('default') # Optional parameters bin_path = kwargs.get('bin_path') # MacPorts if system == 'darwin' and data.get('macports'): macports_path = data.get('macports_path') # Do not suggest macports if the bin is outside its scope: # /usr/local, for instance. if ((not bin_path) or (macports_path and bin_path.startswith(macports_path))): return [instructions.get('macports', default)] # FreeBSD: pkg_add *and* ports if system == 'freebsd': choices = [] if instructions.has_key('freebsd_pkg'): choices += [instructions.get('freebsd_pkg')] if data.get('freebsd_ports_path') and instructions.has_key( 'freebsd_ports'): choices += [instructions.get('freebsd_ports')] if choices: return choices # Solaris' IPS if system.startswith('sunos'): if os.path.exists("/usr/bin/pkg"): return [instructions.get('ips', default)] # OS specific if instructions.has_key(system): return [instructions.get(system, default)] # Linux distro specific if instructions.has_key(distro): return [instructions.get(distro, default)] # Linux distro generic for x in ('red hat', 'redhat', 'centos'): if x in distro: return [instructions.get('yum', default)] for x in ('fedora', ): if x in distro: return [ instructions.get('yumfedora', instructions.get('yum', default)) ] for x in ('suse', ): if x in distro: return [instructions.get('zypper', default)] for x in ('debian', 'ubuntu', 'knoppix', 'mint'): if x in distro: return [instructions.get('apt', default)] # Default return [default]
class IncrementalSearchDialog(wx.Frame): COLOR_YELLOW = wx.Colour(255, 255, 0) COLOR_GREEN = wx.Colour(0, 255, 0) def __init__(self, parent, id, txtCtrl, rect, font, mainControl, searchInit=None): # Frame title is invisible but is helpful for workarounds with # third-party tools wx.Frame.__init__(self, parent, id, u"WikidPad i-search", rect.GetPosition(), rect.GetSize(), wx.NO_BORDER | wx.FRAME_FLOAT_ON_PARENT) self.txtCtrl = txtCtrl self.mainControl = mainControl self.tfInput = wx.TextCtrl( self, GUI_ID.INC_SEARCH_TEXT_FIELD, _(u"Incremental search (ENTER/ESC to finish)"), style=wx.TE_PROCESS_ENTER | wx.TE_RICH) self.tfInput.SetFont(font) self.tfInput.SetBackgroundColour(IncrementalSearchDialog.COLOR_YELLOW) mainsizer = wx.BoxSizer(wx.HORIZONTAL) mainsizer.Add(self.tfInput, 1, wx.ALL | wx.EXPAND, 0) self.SetSizer(mainsizer) self.Layout() self.tfInput.SelectAll() #added for Mac compatibility self.tfInput.SetFocus() config = self.mainControl.getConfig() self.closeDelay = 1000 * config.getint( "main", "incSearch_autoOffDelay", 0) # Milliseconds to close or 0 to deactivate wx.EVT_TEXT(self, GUI_ID.INC_SEARCH_TEXT_FIELD, self.OnText) wx.EVT_KEY_DOWN(self.tfInput, self.OnKeyDownInput) wx.EVT_KILL_FOCUS(self.tfInput, self.OnKillFocus) wx.EVT_TIMER(self, GUI_ID.TIMER_INC_SEARCH_CLOSE, self.OnTimerIncSearchClose) wx.EVT_MOUSE_EVENTS(self.tfInput, self.OnMouseAnyInput) if searchInit: self.tfInput.SetValue(searchInit) self.tfInput.SetSelection(-1, -1) if self.closeDelay: self.closeTimer = wx.Timer(self, GUI_ID.TIMER_INC_SEARCH_CLOSE) self.closeTimer.Start(self.closeDelay, True) # def Close(self): # wx.Frame.Close(self) # self.txtCtrl.SetFocus() def OnKillFocus(self, evt): self.txtCtrl.forgetIncrementalSearch() self.Close() def OnText(self, evt): self.txtCtrl.searchStr = self.tfInput.GetValue() foundPos = self.txtCtrl.executeIncrementalSearch() if foundPos == -1: # Nothing found self.tfInput.SetBackgroundColour( IncrementalSearchDialog.COLOR_YELLOW) else: # Found self.tfInput.SetBackgroundColour( IncrementalSearchDialog.COLOR_GREEN) def OnMouseAnyInput(self, evt): # if evt.Button(wx.MOUSE_BTN_ANY) and self.closeDelay: # Workaround for name clash in wx.MouseEvent.Button: if wx._core_.MouseEvent_Button(evt, wx.MOUSE_BTN_ANY) and self.closeDelay: # If a mouse button was pressed/released, restart timer self.closeTimer.Start(self.closeDelay, True) evt.Skip() def OnKeyDownInput(self, evt): if self.closeDelay: self.closeTimer.Start(self.closeDelay, True) key = evt.GetKeyCode() accP = getAccelPairFromKeyDown(evt) matchesAccelPair = self.mainControl.keyBindings.matchesAccelPair foundPos = -2 if accP in ((wx.ACCEL_NORMAL, wx.WXK_NUMPAD_ENTER), (wx.ACCEL_NORMAL, wx.WXK_RETURN)): # Return pressed self.txtCtrl.endIncrementalSearch() self.Close() elif accP == (wx.ACCEL_NORMAL, wx.WXK_ESCAPE): # Esc -> Abort inc. search, go back to start self.txtCtrl.resetIncrementalSearch() self.Close() elif matchesAccelPair("ContinueSearch", accP): foundPos = self.txtCtrl.executeIncrementalSearch(next=True) # do the next search on another ctrl-f elif matchesAccelPair("StartIncrementalSearch", accP): foundPos = self.txtCtrl.executeIncrementalSearch(next=True) elif accP in ((wx.ACCEL_NORMAL, wx.WXK_DOWN), (wx.ACCEL_NORMAL, wx.WXK_PAGEDOWN), (wx.ACCEL_NORMAL, wx.WXK_NUMPAD_DOWN), (wx.ACCEL_NORMAL, wx.WXK_NUMPAD_PAGEDOWN), (wx.ACCEL_NORMAL, wx.WXK_NEXT)): foundPos = self.txtCtrl.executeIncrementalSearch(next=True) elif matchesAccelPair("BackwardSearch", accP): foundPos = self.txtCtrl.executeIncrementalSearchBackward() elif accP in ((wx.ACCEL_NORMAL, wx.WXK_UP), (wx.ACCEL_NORMAL, wx.WXK_PAGEUP), (wx.ACCEL_NORMAL, wx.WXK_NUMPAD_UP), (wx.ACCEL_NORMAL, wx.WXK_NUMPAD_PAGEUP), (wx.ACCEL_NORMAL, wx.WXK_PRIOR)): foundPos = self.txtCtrl.executeIncrementalSearchBackward() elif matchesAccelPair("ActivateLink", accP) or \ matchesAccelPair("ActivateLinkNewTab", accP) or \ matchesAccelPair("ActivateLink2", accP) or \ matchesAccelPair("ActivateLinkBackground", accP) or \ matchesAccelPair("ActivateLinkNewWindow", accP): # ActivateLink is normally Ctrl-L # ActivateLinkNewTab is normally Ctrl-Alt-L # ActivateLink2 is normally Ctrl-Return self.txtCtrl.endIncrementalSearch() self.Close() self.txtCtrl.OnKeyDown(evt) # handle the other keys else: evt.Skip() if foundPos == -1: # Nothing found self.tfInput.SetBackgroundColour( IncrementalSearchDialog.COLOR_YELLOW) elif foundPos >= 0: # Found self.tfInput.SetBackgroundColour( IncrementalSearchDialog.COLOR_GREEN) # Else don't change if SystemInfo.isOSX(): # Fix focus handling after close def Close(self): wx.Frame.Close(self) wx.CallAfter(self.txtCtrl.SetFocus) def OnTimerIncSearchClose(self, evt): self.txtCtrl.endIncrementalSearch( ) # TODO forgetIncrementalSearch() instead? self.Close()
from wxHelper import GUI_ID, XrcControls, getAccelPairFromKeyDown, \ ModalDialogMixin, WindowUpdateLocker from StringOps import unescapeForIni import SystemInfo import Utilities from TempFileSet import TempFileSet try: import WindowsHacks except: if SystemInfo.isWindows(): traceback.print_exc() WindowsHacks = None class IncrementalSearchDialog(wx.Frame): COLOR_YELLOW = wx.Colour(255, 255, 0) COLOR_GREEN = wx.Colour(0, 255, 0) def __init__(self, parent, id, txtCtrl, rect, font,
class DocPagePresenter(wx.Panel, BasicDocPagePresenter): """ Controls the group of all widgets (subcontrols) used to present/edit a particular doc page, currently only WikiTxtCtrl and WikiHtmlView. This version is a panel and contains the children itself. """ def __init__(self, parent, mainControl, id=-1): wx.Panel.__init__(self, parent, id) BasicDocPagePresenter.__init__(self, mainControl) self.SetSizer(LayerSizer()) res = xrc.XmlResource.Get() self.tabContextMenu = res.LoadMenu("MenuDocPagePresenterTabPopup") self.mainTreePositionHint = None # The tree ctrl uses this to remember # which element was selected if same page appears multiple # times in tree. DocPagePresenter class itself does not modify it. wx.GetApp().getMiscEvent().addListener(self) wx.EVT_MENU(self, GUI_ID.CMD_PAGE_HISTORY_LIST, lambda evt: self.viewPageHistory()) wx.EVT_MENU(self, GUI_ID.CMD_PAGE_HISTORY_LIST_UP, lambda evt: self.viewPageHistory(-1)) wx.EVT_MENU(self, GUI_ID.CMD_PAGE_HISTORY_LIST_DOWN, lambda evt: self.viewPageHistory(1)) wx.EVT_MENU(self, GUI_ID.CMD_PAGE_HISTORY_GO_BACK, lambda evt: self.pageHistory.goInHistory(-1)) wx.EVT_MENU(self, GUI_ID.CMD_PAGE_HISTORY_GO_FORWARD, lambda evt: self.pageHistory.goInHistory(1)) wx.EVT_MENU(self, GUI_ID.CMD_PAGE_GO_UPWARD_FROM_SUBPAGE, lambda evt: self.goUpwardFromSubpage()) def close(self): wx.GetApp().getMiscEvent().removeListener(self) BasicDocPagePresenter.close(self) def setSubControl(self, scName, sc): oldSc = self.getSubControl(scName) if oldSc is not None: self.GetSizer().Detach(oldSc) oldSc.close() BasicDocPagePresenter.setSubControl(self, scName, sc) if sc is not None: self.GetSizer().Add(sc) self.Layout() def switchSubControl(self, scName, gainFocus=False): """ Make the chosen subcontrol visible, all other invisible """ try: subControl = self.subControls[scName] except KeyError: traceback.print_exc() return # First show subControl scName, then hide the others # to avoid flicker if self.visible and self.lastVisibleCtrlName != scName: subControl.setLayerVisible(True) subControl.Show(True) if gainFocus: subControl.SetFocus() for n, c in self.subControls.iteritems(): # if n != scName: if c is not subControl: if self.visible: c.setLayerVisible(False) c.Show(False) self.lastVisibleCtrlName = scName self.setTitle(self.shortTitle) #? if SystemInfo.isLinux(): def SetFocus(self): try: ctrl = self.subControls[self.lastVisibleCtrlName] wx.CallAfter(ctrl.SetFocus) except KeyError: wx.Panel.SetFocus(self) else: def SetFocus(self): try: self.subControls[self.lastVisibleCtrlName].SetFocus() except KeyError: wx.Panel.SetFocus(self) def viewPageHistory(self, posDelta=0): if not self.getMainControl().requireReadAccess(): return try: hist = self.pageHistory.getHrHistoryList() histpos = self.pageHistory.getPosition() except (IOError, OSError, DbAccessError), e: self.getMainControl().lostAccess(e) raise historyLen = len(hist) dlg = wx.SingleChoiceDialog(self, _(u"History"), _(u"History"), hist, wx.CHOICEDLG_STYLE | wx.OK | wx.CANCEL) if historyLen > 0: position = histpos + posDelta - 1 if (position < 0): position = 0 elif (position >= historyLen): position = historyLen-1 dlg.SetSelection(position) if dlg.ShowModal() == wx.ID_OK and dlg.GetSelection() > -1: self.pageHistory.goInHistory(dlg.GetSelection() - (histpos - 1)) dlg.Destroy()
def __safe_call__(self): box = CTK.Box() buttons = CTK.DruidButtonsPanel() pre = 'tmp!market!install' root = CTK.cfg.get_val('%s!root' % (pre)) project = os.path.join(root, 'project') trac_src = os.path.join(root, 'trac') trac_admin = os.path.join(root, 'bin', 'trac-admin') easy_bin = os.path.join(root, 'bin', 'easy_install') group_root = SystemInfo.get_info()['group_root'] server_user = CTK.cfg.get_val('server!user', 'root') server_group = CTK.cfg.get_val('server!group', group_root) # Figure out PYTHONPATH ret = popen.popen_sync('python setup.py install --prefix=%(root)s' % (locals()), cd='%(root)s/Genshi-0.6' % (locals())) err = ret['stderr'] + ret['stdout'] # Python 2.4.3 actually succeeds tmp = re.findall(r' (%(root)s.+site-packages)' % (locals()), err) PYTHONPATH = tmp[0] CTK.cfg['tmp!market!install!trac!PYTHONPATH'] = PYTHONPATH # Create site-packages if not os.path.isdir(PYTHONPATH): os.makedirs(PYTHONPATH) # Build PYTHONPATH env = os.environ.copy() if 'PYTHONPATH' in env: env['PYTHONPATH'] = '%s:%s' % (PYTHONPATH, env['PYTHONPATH']) else: env['PYTHONPATH'] = PYTHONPATH # Installation tasks = [ # Install dependencies ({ 'command': "python setup.py install --prefix=${app_root}", 'env': env, 'cd': '%(root)s/flup-1.0.2' % (locals()) }), ({ 'command': "python setup.py install --prefix=${app_root}", 'env': env, 'cd': '%(root)s/Genshi-0.6' % (locals()) }), #({'command': "python setup.py install --prefix=${app_root}", 'env': env, 'cd': '%(root)s/pysqlite-2.6.0'%(locals())}), ({ 'function': tools.install_pysqlite, 'description': _('Satisfying pysqlite requirements'), 'params': { 'root': root, 'env': str(env) } }), ({ 'command': "python %(trac_src)s/setup.py install --prefix=${app_root}" % (locals()), 'env': env, 'cd': trac_src }), # Create Project ({ 'command': "%(trac_admin)s %(project)s initenv <<EOF\nTrac\n\nEOF\n" % (locals()), 'env': env }), ({ 'command': "chown -R %(server_user)s:%(server_group)s %(project)s" % (locals()) }) ] box += CTK.RawHTML('<h2>%s</h2>' % (_('Installing Trac'))) box += CTK.RawHTML( '<p>%s</p>' % (_('This process may take a while. Please, hold on.'))) box += CommandProgress(tasks, URL_USER_CONFIG) buttons = CTK.DruidButtonsPanel() buttons += CTK.DruidButton_Close(_('Cancel')) box += buttons return box.Render().toStr()
def deBugOutPut(): pids = psutil.pids() systemInfo.getMemInfo(pids) print systemInfo.processInfo_mem if __name__ == '__main__': # config setter config = Configure.Configure('./config.xml') # log file logFileName = time.strftime('%Y-%m-%d', time.localtime(time.time())) logger = Loger.Loger('Monitor-' + logFileName + '.log') # system info get systemInfo = SystemInfo.SystemInfo(pids=None, processName=None) # alert center alertcenter = Alert.Alert() # process names processNames = [] # email info mailInfo = None receiver = [] # alert limit define # region # alert limit configure
# -*- coding: utf-8 -*- import SystemInfo print("System Start Time : %ss" % SystemInfo.get_start_time()) print("System Now Time : %s" % SystemInfo.get_now_time()) print("CPU Used Percent : %.1f%%" % SystemInfo.get_cpu_used_percent()) # print("CPU free Percent : %.1f%%" % SystemInfo.get_cpu_free_percent()) print("CPU free Percent No Blocking : %.1f%%" % SystemInfo.get_cpu_free_percent_no_blocking()) print("Memory Used Percent : %.1f%%" % SystemInfo.get_mem_used_percent()) print("Memory free Percent : %.1f%%" % SystemInfo.get_mem_free_percent()) print("Disk free : %dB === %dKB === %dMB === %dGB" % (SystemInfo.get_disk_free(), SystemInfo.get_disk_free() / 1024, SystemInfo.get_disk_free() / 1024 / 1024, SystemInfo.get_disk_free() / 1024 / 1024 / 1024)) print("Disk used : %dB === %dKB === %dMB === %dGB" % (SystemInfo.get_disk_used(), SystemInfo.get_disk_used() / 1024, SystemInfo.get_disk_used() / 1024 / 1024, SystemInfo.get_disk_used() / 1024 / 1024 / 1024)) print("Disk free percent : %.1f%%" % SystemInfo.get_disk_free_percent()) print("Disk used percent : %.1f%%" % SystemInfo.get_disk_used_percent()) print("ipaddr : %s\nnetmask : %s\ngateway : %s\n" % (SystemInfo.get_ip_info())) # print("Set Time Status : %d" % SystemInfo.set_now_time(2019, 5, 4, 12, 50, 54)) # print("System Now Time : %s" % SystemInfo.get_now_time()) # print("Set Time Status : %d" % SystemInfo.set_now_time(2019, 5, 14, 14, 10, 54)) # print("System Now Time : %s" % SystemInfo.get_now_time()) # SystemInfo.set_ip_info('10.255.88.83', '255.255.248.0', '10.255.95.254')
def register_service(service, macos_plist=None): """Register system service so that it is started at boot time. The name of the service should be provided. On MacOS X, an additional Launchd service file must be specified. register_service() returns a dictionary with the following keys: command: command retcode: return code of the execution of specified command. 0 on success. error: error message stdout: standard output of execution stderr: error buffer of execution""" # System info retrival system_info = SystemInfo.get_info() OS = system_info.get('system', '').lower() distro = system_info.get('linux_distro_id', '').lower() # Execute command error_msg = _( 'Could not add <em>%(service)s</em> to list of system services.') % ( locals()) if distro in ('fedora', 'redhat', 'centos', 'suse', 'opensuse'): ret = _exe('chkconfig --add %(service)s' % (locals()), error_msg) if ret['retcode']: return ret ret = _exe('chkconfig %(service)s on' % (locals()), error_msg) if ret['retcode']: return ret # Log (do not change string, check Maintenance.py) Install_Log.log('Registered system service: %(service)s' % (locals())) return ret elif OS == 'linux': cmd = 'ln -s /etc/init.d/%(service)s /etc/rcS.d/S99%(service)s' % ( locals()) ret = _exe(cmd, error_msg) if ret['retcode']: return ret # Log (do not change string, check Maintenance.py) Install_Log.log('Registered system service: %(service)s' % (locals())) return ret elif OS == 'darwin': assert macos_plist, "Launchd service file not provided" cmd = 'launchctl load %(macos_plist)s' % (locals()) ret = _exe(cmd, error_msg) if ret['retcode']: return ret # Log (do not change string, check Maintenance.py) Install_Log.log('Registered Launchd service: %(macos_plist)s' % (locals())) return ret elif OS == 'freebsd': # Find out variable name for rc (coded in init script) cmd = None for path in ('/usr/local/etc/rc.d', '/etc/rc.d'): if os.path.exists ('%(path)s/%(service)s' %(locals())) and \ os.access ('%(path)s/%(service)s' %(locals()), os.X_OK): cmd = '%(path)s/%(service)s rcvar' % (locals()) assert cmd, "Init script not present on /etc/rc.d or /usr/local/etc/rc.d" ret = _exe(cmd, error_msg) rcvar = re.findall('^([^#].*)=', ret['stdout'], re.M)[0] # Read init file (to add or modify if entry already present) lines = open('/etc/rc.conf', 'r').readlines() content = '' for line in lines: if re.findall(r'%(rcvar)s=.+' % (locals()), line): content += '%(rcvar)s="YES"\n' % (locals()) else: content += line if content == ''.join(lines): content += '%(rcvar)s="YES"\n' % (locals()) # Write try: open('/etc/rc.conf', 'w').write(content) # Log (do not change string, check Maintenance.py) Install_Log.log('Registered BSD service: %(rcvar)s' % (locals())) except: raise return ret assert False, 'Unknown platform: %s' % (str(system_info))
def __init__(self): super().__init__() self.object_list.append(SystemInfo.SystemInfo()) self.object_list.append(SystemInfo.ServiceInfo())
def __init__(self): self.dir_check = Filestat.DirCheck() self.system_info = SystemInfo.SystemInfo()
def choose_instructions (self, instructions, kwargs={}): data = SystemInfo.get_info() system = data.get('system','').lower() distro = data.get('linux_distro_id','').lower() default = instructions.get('default') # Optional parameters bin_path = kwargs.get('bin_path') # MacPorts if system == 'darwin' and data.get('macports'): macports_path = data.get('macports_path') # Do not suggest macports if the bin is outside its scope: # /usr/local, for instance. if ((not bin_path) or (macports_path and bin_path.startswith (macports_path))): return [instructions.get('macports', default)] # FreeBSD: pkg_add *and* ports if system == 'freebsd': choices = [] if instructions.has_key('freebsd_pkg'): choices += [instructions.get('freebsd_pkg')] if data.get('freebsd_ports_path') and instructions.has_key('freebsd_ports'): choices += [instructions.get('freebsd_ports')] if choices: return choices # Solaris' IPS if system.startswith ('sunos'): if os.path.exists ("/usr/bin/pkg"): return [instructions.get ('ips', default)] # OS specific if instructions.has_key(system): return [instructions.get (system, default)] # Linux distro specific if instructions.has_key(distro): return [instructions.get (distro, default)] # Linux distro generic for x in ('red hat', 'redhat', 'centos'): if x in distro: return [instructions.get ('yum', default)] for x in ('fedora',): if x in distro: return [instructions.get ('yumfedora', instructions.get('yum', default))] for x in ('suse',): if x in distro: return [instructions.get ('zypper', default)] for x in ('debian', 'ubuntu', 'knoppix', 'mint'): if x in distro: return [instructions.get ('apt', default)] # Default return [default]