Package Products :: Package ZenModel :: Module zendmd
[hide private]
[frames] | no frames]

Source Code for Module Products.ZenModel.zendmd

  1  #!/usr/bin/env python2.4 
  2  ########################################################################### 
  3  # 
  4  # This program is part of Zenoss Core, an open source monitoring platform. 
  5  # Copyright (C) 2007, Zenoss Inc. 
  6  # 
  7  # This program is free software; you can redistribute it and/or modify it 
  8  # under the terms of the GNU General Public License version 2 as published by 
  9  # the Free Software Foundation. 
 10  # 
 11  # For complete information please visit: http://www.zenoss.com/oss/ 
 12  # 
 13  ########################################################################### 
 14   
 15  import os 
 16  import code 
 17  import atexit 
 18  from optparse import OptionParser 
 19  try: 
 20      import readline 
 21      from rlcompleter import Completer 
 22  except ImportError: 
 23      readline = rlcompleter = None 
 24      Completer = object 
 25   
 26  # Parse the command line for host and port; have to do it before Zope 
 27  # configuration, because it hijacks option parsing. 
 28  parser = OptionParser() 
 29  parser.add_option('--host', 
 30              dest="host",default=None, 
 31              help="hostname of zeo server") 
 32  parser.add_option('--port', 
 33              dest="port",type="int", default=None, 
 34              help="port of zeo server") 
 35  opts, args = parser.parse_args() 
 36   
 37  # Zope magic ensues! 
 38  import Zope2 
 39  CONF_FILE = os.path.join(os.environ['ZENHOME'], 'etc', 'zope.conf') 
 40  Zope2.configure(CONF_FILE) 
 41   
 42  # Now we have the right paths, so we can do the rest of the imports 
 43  from Products.CMFCore.utils import getToolByName 
 44  from AccessControl.SecurityManagement import newSecurityManager 
 45  from AccessControl.SecurityManagement import noSecurityManager 
 46  from Products.ZenUtils.Utils import zenPath, set_context 
 47   
 48  _CUSTOMSTUFF = [] 
 49   
 50   
51 -def set_db_config(host=None, port=None):
52 # Modify the database configuration manually 53 from App.config import getConfiguration 54 serverconfig = getConfiguration().databases[1].config.storage.config 55 xhost, xport = serverconfig.server[0].address 56 if host: xhost = host 57 if port: xport = port 58 serverconfig.server[0].address = (xhost, xport)
59 60
61 -def _customStuff():
62 """ 63 Everything available in the console is defined here. 64 """ 65 66 import socket 67 from transaction import commit 68 from pprint import pprint 69 70 # Connect to the database, set everything up 71 app = Zope2.app() 72 app = set_context(app) 73 74 def login(username='admin'): 75 utool = getToolByName(app, 'acl_users') 76 user = utool.getUserById(username) 77 if user is None: 78 user = app.zport.acl_users.getUserById(username) 79 user = user.__of__(utool) 80 newSecurityManager(None, user)
81 82 login('admin') 83 84 # Useful references 85 zport = app.zport 86 dmd = zport.dmd 87 sync = zport._p_jar.sync 88 find = dmd.Devices.findDevice 89 devices = dmd.Devices 90 me = find(socket.getfqdn()) 91 92 def reindex(): 93 sync() 94 dmd.Devices.reIndex() 95 dmd.Events.reIndex() 96 dmd.Manufacturers.reIndex() 97 dmd.Networks.reIndex() 98 commit() 99 100 def logout(): 101 noSecurityManager() 102 103 def zhelp(): 104 cmds = filter(lambda x: not x.startswith("_"), _CUSTOMSTUFF) 105 cmds.sort() 106 for cmd in cmds: print cmd 107 108 def grepdir(obj, regex=""): 109 if regex: 110 import re 111 pattern = re.compile(regex) 112 for key in dir(obj): 113 if pattern.search(key): 114 print key 115 116 def cleandir(obj): 117 portaldir = set(dir(dmd)) 118 objdir = set(dir(obj)) 119 appdir = set(dir(app)) 120 result = list(objdir - portaldir - appdir) 121 result.sort() 122 pprint(result) 123 124 125 _CUSTOMSTUFF = locals() 126 return _CUSTOMSTUFF 127
128 -class ZenCompleter(Completer):
129 """ 130 Provides the abiility to specify *just* the zendmd-specific 131 stuff when you first enter and hit tab-tab, and also the 132 ability to remove junk that we don't need to see. 133 """ 134 ignored_names = [ 135 "COPY", "DELETE", "HEAD", "HistoricalRevisions", 136 "LOCK", "MKCOL", "MOVE", "OPTIONS", 137 "Open", "PROPFIND", "PROPPATCH", 138 "PUT", "REQUEST", "SQLConnectionIDs", 139 "SiteRootAdd", "TRACE", "UNLOCK", 140 "ac_inherited_permissions", 141 "access_debug_info", 142 "bobobase_modification_time", 143 "manage_historyCompare", 144 "manage_historyCopy", 145 "manage_addDTMLDocument", 146 "manage_addDTMLMethod", 147 "manage_clone", 148 "manage_copyObjects", 149 "manage_copyright", 150 "manage_cutObjects", 151 "manage_historicalComparison", 152 "validClipData", 153 "manage_CopyContainerAllItems", 154 "manage_CopyContainerFirstItem", 155 "manage_DAVget", 156 "manage_FTPlist", 157 "manage_UndoForm", 158 "manage_access", 159 ] 160 ignored_prefixes = [ 161 '_', 'wl_', 'cb_', 'acl', 'http__', 'dav_', 162 'manage_before', 'manage_after', 163 'manage_acquired', 164 ] 165
166 - def global_matches(self, text):
167 """ 168 Compute matches when text is a simple name. 169 """ 170 matches = [] 171 for name in self.namespace: 172 if name.startswith(text): 173 matches.append(name) 174 175 return matches
176
177 - def attr_matches(self, text):
178 """ 179 Compute matches when text contains a dot. 180 """ 181 matches = [] 182 for name in Completer.attr_matches(self, text): 183 if name.endswith("__roles__"): 184 continue 185 component = name.split('.')[-1] 186 if component in self.ignored_names: 187 continue 188 ignore = False 189 for prefix in self.ignored_prefixes: 190 if component.startswith(prefix): 191 ignore = True 192 break 193 194 if not ignore: 195 matches.append(name) 196 197 return matches
198 #return filter(lambda x: not x.endswith("__roles__"), 199 #Completer.attr_matches(self, text)) 200 201 202
203 -class HistoryConsole(code.InteractiveConsole):
204 """ 205 Subclass the default InteractiveConsole to get readline history 206 """
207 - def __init__(self, locals=None, filename="<console>", 208 histfile=zenPath('.pyhistory')):
209 code.InteractiveConsole.__init__(self, locals, filename) 210 if readline is not None: 211 completer = ZenCompleter(locals) 212 readline.set_completer(completer.complete) 213 readline.parse_and_bind("tab: complete") 214 self.init_history(histfile)
215 216
217 - def init_history(self, histfile):
218 if hasattr(readline, "read_history_file"): 219 try: 220 readline.read_history_file(histfile) 221 except IOError: 222 pass 223 atexit.register(self.save_history, histfile)
224
225 - def save_history(self, histfile):
226 readline.write_history_file(histfile)
227 228 229 if __name__=="__main__": 230 # Do we want to connect to a database other than the one specified in 231 # zope.conf? 232 if opts.host or opts.port: 233 set_db_config(opts.host, opts.port) 234 235 _banner = ["Welcome to the Zenoss dmd command shell!\n" 236 "'dmd' is bound to the DataRoot. 'zhelp()' to get a list of " 237 "commands." ] 238 if readline is not None: 239 _banner = '\n'.join( [ _banner[0], 240 "Use TAB-TAB to see a list of zendmd related commands.", 241 "Tab completion also works for objects -- hit tab after" 242 " an object name and '.'", " (eg dmd. + tab-key)."]) 243 244 # Start up the console 245 myconsole = HistoryConsole(locals=_customStuff()) 246 myconsole.interact(_banner) 247