Package ZenModel :: Module ZenModelRM
[hide private]
[frames] | no frames]

Source Code for Module ZenModel.ZenModelRM

  1  ########################################################################### 
  2  # 
  3  # This program is part of Zenoss Core, an open source monitoring platform. 
  4  # Copyright (C) 2007, Zenoss Inc. 
  5  # 
  6  # This program is free software; you can redistribute it and/or modify it 
  7  # under the terms of the GNU General Public License version 2 as published by 
  8  # the Free Software Foundation. 
  9  # 
 10  # For complete information please visit: http://www.zenoss.com/oss/ 
 11  # 
 12  ########################################################################### 
 13   
 14  __doc__="""ZenModelRM 
 15   
 16  $Id: ZenModelRM.py,v 1.50 2004/05/10 20:49:09 edahl Exp $""" 
 17   
 18  __version__ = "$Revision: 1.50 $"[11:-2] 
 19   
 20  import os 
 21  import time 
 22   
 23  from DateTime import DateTime 
 24  from Globals import DTMLFile 
 25  from Globals import InitializeClass 
 26  from OFS.History import Historical 
 27  from Acquisition import aq_base 
 28  from AccessControl import ClassSecurityInfo 
 29  from ZPublisher.Converters import type_converters 
 30  #from Products.ZCatalog.CatalogAwareness import CatalogAware 
 31   
 32  from ZenModelBase import ZenModelBase 
 33  from ZenPacker import ZenPacker 
 34  from Products.ZenUtils.Utils import getSubObjects, zenPath 
 35  from Products.ZenRelations.ImportRM import ImportRM 
 36  from Products.ZenRelations.RelationshipManager import RelationshipManager 
 37   
38 -class ZenModelRM(ZenModelBase, RelationshipManager, Historical, ZenPacker):
39 """ 40 Base class for all Persistent classes that have relationships. 41 Provides RelationshipManagement, Customized PropertyManagement, 42 Catalog Indexing, and Historical change tracking. 43 """ 44 45 meta_type = 'ZenModelRM' 46 47 default_catalog = '' 48 49 isInTree = 0 #should this class show in left nav tree 50 51 security = ClassSecurityInfo() 52
53 - def __init__(self, id, title=None, buildRelations=True):
54 self.createdTime = DateTime(time.time()) 55 RelationshipManager.__init__(self, id, title, buildRelations)
56 57 security.declareProtected('Manage DMD', 'rename')
58 - def rename(self, newId, REQUEST=None):
59 """Delete device from the DMD""" 60 renamed = False 61 if newId and newId != self.getId(): 62 parent = self.getPrimaryParent() 63 parent.manage_renameObject(self.getId(), newId) 64 renamed = True 65 if REQUEST: 66 if renamed: REQUEST['message'] = "Object renamed" 67 return self.callZenScreen(REQUEST, renamed) 68 return renamed
69 70 71 security.declareProtected('Manage DMD', 'zmanage_editProperties')
72 - def zmanage_editProperties(self, REQUEST=None):
73 """Edit a ZenModel object and return its proper page template 74 """ 75 redirect = False 76 if REQUEST.form.has_key("newId"): 77 redirect = self.rename(REQUEST.form["newId"]) 78 return ZenModelBase.zmanage_editProperties(self, REQUEST, redirect)
79 80
81 - def zmanage_addProperty(self, id, value, type, label, visible, 82 prefix='c', REQUEST=None):
83 """Add a new property via the web. 84 Sets a new property with the given id, type, and value. 85 Id must start with a 'c' for custom attributes added via the 86 Custom Schema tab. 87 """ 88 if type_converters.has_key(type): 89 value=type_converters[type](value) 90 if prefix and not id.startswith(prefix): 91 id = prefix + id 92 self._setProperty(id.strip(), value, type, label, visible) 93 if REQUEST: 94 REQUEST['message'] = "Property added" 95 return self.callZenScreen(REQUEST)
96
97 - def zmanage_exportObject(self, context=None, REQUEST=None):
98 """Export objects to specific locations. 99 """ 100 if not context: 101 context = self 102 redirect = False 103 dest = 'filesystem' 104 if REQUEST: 105 dest = REQUEST.form.get('dest') 106 fileBase = '%s_%s.xml' % (context.getNodeName(), context.id) 107 if dest == 'filesystem': 108 filename = zenPath('export', fileBase) 109 msg = "Item has been exported to: %s at " % filename 110 elif dest == 'zenossdotnet': 111 # create temp file 112 filename = '' 113 # get username and password from configuration 114 username = '' 115 password = '' 116 # get https URL for user space at Zenoss.net 117 url = 'https://%s:%[email protected]/' 118 # build XML-RPC proxy object for publishing to Zenoss.net 119 import xmlrpclib 120 server = xmlrpclib.ProxyServer(url) 121 msg = "Item has been exported to: %s. Note that you will need to " 122 msg += "login at Zenoss.net and publish this template in order to " 123 msg += "share it with others. Exported at " 124 msg %= url 125 # open file 126 exportFile = open(filename, 'w+') 127 # export object to file 128 context.exportXml(exportFile) 129 # cleanup 130 exportFile.close() 131 if dest == 'zenossdotnet': 132 # get data 133 exportFile = open(filename) 134 dataToSend = exportFile.read() 135 exportFile.close() 136 # push data up to Zenoss.net 137 server.postUserTemplate(dataToSend) 138 if REQUEST: 139 REQUEST['message'] = msg 140 return self.callZenScreen(REQUEST, redirect)
141 142
143 - def zmanage_importObjects(self, context=None, REQUEST=None):
144 """Import an XML file as the Zenoss objects and properties it 145 represents. 146 """ 147 # XXX 148 # for right now, we're only using this through the web, so a REQUEST is 149 # always define; when we have a use-case for imports via command line, 150 # we will add that code here 151 if not context: 152 context = self.getPhysicalRoot() 153 # get the submitted data 154 filenames = REQUEST.form.get('filenames') 155 urlnames = REQUEST.form.get('urlnames') 156 doDelete = REQUEST.form.get('dodelete') 157 xmlfiles = [] 158 for collection in [filenames, urlnames]: 159 if collection: 160 if isinstance(collection, list): 161 xmlfiles.extend(collection) 162 else: 163 xmlfiles.append(collection) 164 # load the objects into Zenoss 165 im = ImportRM(noopts=True, app=self.getPhysicalRoot()) 166 for xmlfile in xmlfiles: 167 im.loadObjectFromXML(context, xmlfile) 168 if doDelete and xmlfile in filenames: 169 os.unlink(xmlfile) 170 if REQUEST: 171 REQUEST['message'] = "Objects imported" 172 return self.callZenScreen(REQUEST)
173 174
175 - def zmanage_importObject(self, REQUEST=None):
176 """Import objects into Zenoss. 177 """ 178 pass
179
180 - def zmanage_delProperties(self, ids=(), REQUEST=None):
181 """Delete properties from an object. 182 """ 183 for id in ids: 184 self._delProperty(id) 185 if REQUEST: 186 REQUEST['message'] = "Properties deleted" 187 return self.callZenScreen(REQUEST)
188 189
190 - def zmanage_delObjects(self, ids=(), relation="", REQUEST=None):
191 """Delete objects from this object or one of its relations. 192 """ 193 target = self 194 if relation: target = self._getOb(relation) 195 for id in ids: 196 target._delObject(id) 197 if REQUEST: 198 REQUEST['message'] = "Objects deleted" 199 return self.callZenScreen(REQUEST)
200 201 202 security.declareProtected('View', 'getDmdKey')
203 - def getDmdKey(self):
204 """ 205 Hook to get the name of an object. Usually its self.getId() but is 206 overridden by Organizer to be getOrganizerName. 207 208 >>> dmd.Manufacturers.Cisco.getDmdKey() 209 'Cisco' 210 >>> dmd.Devices.Server.getDmdKey() 211 '/Server' 212 """ 213 return self.getId()
214 215 216 security.declareProtected('View', 'primarySortKey')
217 - def primarySortKey(self):
218 """ 219 Hook for the value used to sort this object. Defaults to self.getId(). 220 IpNetwork for instance overrides to allow it to sort by the IP numeric 221 value not its string value. 222 223 >>> n = dmd.Networks.createNet('1.2.3.0', 24) 224 >>> n.primarySortKey() 225 16909056L 226 """ 227 return self.getId()
228 229 230 security.declareProtected('View', 'viewName')
231 - def viewName(self):
232 return self.getId()
233 234 235 #actions?
236 - def getTreeItems(self):
237 nodes = [] 238 for item in self.objectValues(): 239 if hasattr(aq_base(item), "isInTree") and item.isInTree: 240 nodes.append(item) 241 return nodes
242 243
244 - def getSubObjects(self, filter=None, decend=None, retobjs=None):
245 return getSubObjects(self, filter, decend, retobjs)
246 247
248 - def getCreatedTimeString(self):
249 """return the creation time as a string""" 250 return self.createdTime.strftime('%Y/%m/%d %H:%M:%S')
251 252
254 """return the modification time as a string""" 255 return self.bobobase_modification_time().strftime('%Y/%m/%d %H:%M:%S')
256 257
258 - def changePythonClass(self, newPythonClass, container):
259 """change the python class of a persistent object""" 260 id = self.id 261 nobj = newPythonClass(id) #make new instance from new class 262 nobj = nobj.__of__(container) #make aq_chain same as self 263 nobj.oldid = self.id 264 nobj.setPrimaryPath() #set up the primarypath for the copy 265 #move all sub objects to new object 266 nrelations = self.ZenSchemaManager.getRelations(nobj).keys() 267 for sobj in self.objectValues(): 268 RelationshipManager._delObject(self,sobj.getId()) 269 if not hasattr(nobj, sobj.id) and sobj.id in nrelations: 270 RelationshipManager._setObject(nobj, sobj.id, sobj) 271 nobj.buildRelations() #build out any missing relations 272 # copy properties to new object 273 noprop = getattr(nobj, 'zNoPropertiesCopy', []) 274 for name in nobj.getPropertyNames(): 275 if (getattr(self, name, None) and name not in noprop and 276 hasattr(nobj, "_updateProperty")): 277 val = getattr(self, name) 278 nobj._updateProperty(name, val) 279 return aq_base(nobj)
280 281
282 - def getZenRootNode(self):
283 """Return the root node for our zProperties.""" 284 return self.getDmdRoot(self.dmdRootName)
285 286
287 - def editableDeviceList(self):
288 """ 289 Return true if user has Manager role and self has a deviceList. 290 """ 291 user = self.REQUEST.get('AUTHENTICATED_USER', None) 292 if user: 293 return "Manager" in user.getRoles() and \ 294 getattr(aq_base(self), "deviceMoveTargets", False)
295 296
297 - def creator(self):
298 """ 299 Method needed for CatalogAwarnessInterface. Implemented here so that 300 Subclasses (who would have the same implementation) don't need to. 301 Other methods (except reindex_all) are implemented on the concreate 302 class. 303 """ 304 users=[] 305 for user, roles in self.get_local_roles(): 306 if 'Owner' in roles: 307 users.append(user) 308 return ', '.join(users)
309 310
311 - def index_object(self):
312 """A common method to allow Findables to index themselves.""" 313 cat = getattr(self, self.default_catalog, None) 314 if cat != None: 315 cat.catalog_object(self, self.getPrimaryId())
316 317
318 - def unindex_object(self):
319 """A common method to allow Findables to unindex themselves.""" 320 cat = getattr(self, self.default_catalog, None) 321 if cat != None: 322 cat.uncatalog_object(self.getPrimaryId())
323 324
325 - def reindex_all(self, obj=None):
326 """ 327 Called for in the CataLogAwarenessInterface not sure this is needed. 328 """ 329 if obj is None: obj=self 330 if hasattr(aq_base(obj), 'index_object'): 331 obj.index_object() 332 if hasattr(aq_base(obj), 'objectValues'): 333 sub=obj.objectValues() 334 for item in sub: 335 self.reindex_all(item) 336 return 'done!'
337