diff options
author | Sol Jerome <solj@ices.utexas.edu> | 2008-12-22 04:09:48 +0000 |
---|---|---|
committer | Sol Jerome <solj@ices.utexas.edu> | 2008-12-22 04:09:48 +0000 |
commit | e3fb140c8d44d751766535eedefcc4ada6544bd1 (patch) | |
tree | 9cfe7aa923ec2b1f2e17df1ced892508987b9a6f /src | |
parent | 5ab6c7a56e1cb16fee6b04a2b74e615f8f4c557e (diff) | |
download | bcfg2-e3fb140c8d44d751766535eedefcc4ada6544bd1.tar.gz bcfg2-e3fb140c8d44d751766535eedefcc4ada6544bd1.tar.bz2 bcfg2-e3fb140c8d44d751766535eedefcc4ada6544bd1.zip |
Update dictionary accesses to work with Python 3.0
git-svn-id: https://svn.mcs.anl.gov/repos/bcfg/trunk/bcfg2@4999 ce84e21b-d406-0410-9b95-82705330c041
Diffstat (limited to 'src')
25 files changed, 219 insertions, 219 deletions
diff --git a/src/lib/Client/Frame.py b/src/lib/Client/Frame.py index 014a1cf16..dca4516f6 100644 --- a/src/lib/Client/Frame.py +++ b/src/lib/Client/Frame.py @@ -133,7 +133,7 @@ class Frame: for tool in self.tools: ret += getattr(tool, name) return ret - elif self.__dict__.has_key(name): + elif name in self.__dict__: return self.__dict__[name] raise AttributeError, name diff --git a/src/lib/Client/Tools/APT.py b/src/lib/Client/Tools/APT.py index 1acd70cae..231b69adb 100644 --- a/src/lib/Client/Tools/APT.py +++ b/src/lib/Client/Tools/APT.py @@ -87,7 +87,7 @@ class APT(Bcfg2.Client.Tools.Tool): def VerifyPackage(self, entry, modlist, checksums=True): '''Verify package for entry''' - if not entry.attrib.has_key('version'): + if not 'version' in entry.attrib: self.logger.info("Cannot verify unversioned package %s" % (entry.attrib['name'])) return False @@ -140,7 +140,7 @@ class APT(Bcfg2.Client.Tools.Tool): ipkgs = [] bad_pkgs = [] for pkg in packages: - if not self.pkg_cache.has_key(pkg.get('name')): + if not pkg.get('name') in self.pkg_cache: self.logger.error("APT has no information about package %s" % (pkg.get('name'))) continue if pkg.get('version') == 'auto': diff --git a/src/lib/Client/Tools/FreeBSDPackage.py b/src/lib/Client/Tools/FreeBSDPackage.py index 117873c9f..dbd32a122 100644 --- a/src/lib/Client/Tools/FreeBSDPackage.py +++ b/src/lib/Client/Tools/FreeBSDPackage.py @@ -29,11 +29,11 @@ class FreeBSDPackage(Bcfg2.Client.Tools.PkgTool): self.installed[name] = version def VerifyPackage(self, entry, modlist): - if not entry.attrib.has_key('version'): + if not 'version' in entry.attrib: self.logger.info("Cannot verify unversioned package %s" % (entry.attrib['name'])) return False - if self.installed.has_key(entry.attrib['name']): + if entry.attrib['name'] in self.installed: if self.installed[entry.attrib['name']] == entry.attrib['version']: # TODO: verfification return True diff --git a/src/lib/Client/Tools/Portage.py b/src/lib/Client/Tools/Portage.py index b0599a60a..936dc25cb 100644 --- a/src/lib/Client/Tools/Portage.py +++ b/src/lib/Client/Tools/Portage.py @@ -35,11 +35,11 @@ class Portage(Bcfg2.Client.Tools.PkgTool): def VerifyPackage(self, entry, modlist): '''Verify package for entry''' - if not entry.attrib.has_key('version'): + if not 'version' in entry.attrib: self.logger.info("Cannot verify unversioned package %s" % (entry.attrib['name'])) return False - if self.installed.has_key(entry.attrib['name']): + if entry.attrib['name'] in self.installed: if self.installed[entry.attrib['name']] == entry.attrib['version']: if not self.setup['quick'] and \ entry.get('verify', 'true') == 'true': diff --git a/src/lib/Client/Tools/RPM.py b/src/lib/Client/Tools/RPM.py index be8bb95b9..1ccffb4a8 100644 --- a/src/lib/Client/Tools/RPM.py +++ b/src/lib/Client/Tools/RPM.py @@ -40,7 +40,7 @@ class RPM(Bcfg2.Client.Tools.PkgTool): self.logger.debug("Skipping mtime verification for package %s" % \ (entry.get('name'))) rpm_options.append("--nomtime") - if self.installed.has_key(entry.get('name')): + if entry.get('name') in self.installed: if entry.get('version') == self.installed[entry.get('name')]: if entry.get('multiarch'): archs = entry.get('multiarch').split() diff --git a/src/lib/Client/Tools/RPMng.py b/src/lib/Client/Tools/RPMng.py index 1a7a0e21f..fd440e415 100644 --- a/src/lib/Client/Tools/RPMng.py +++ b/src/lib/Client/Tools/RPMng.py @@ -192,7 +192,7 @@ class RPMng(Bcfg2.Client.Tools.PkgTool): package_fail = False qtext_versions = '' - if self.installed.has_key(entry.get('name')): + if entry.get('name') in self.installed: # There is at least one instance installed. if self.pkg_checks == 'true' and entry.get('pkg_checks', 'true') == 'true': if entry.get('name') in self.installOnlyPkgs: diff --git a/src/lib/Client/Tools/SMF.py b/src/lib/Client/Tools/SMF.py index 28f6c830c..399418986 100644 --- a/src/lib/Client/Tools/SMF.py +++ b/src/lib/Client/Tools/SMF.py @@ -14,7 +14,7 @@ class SMF(Bcfg2.Client.Tools.Tool): def GetFMRI(self, entry): '''Perform FMRI resolution for service''' - if not entry.attrib.has_key('FMRI'): + if not 'FMRI' in entry.attrib: name = self.cmd.run("/usr/bin/svcs -H -o FMRI %s 2>/dev/null" % \ entry.get('name'))[1] if name: diff --git a/src/lib/Client/Tools/Yum.py b/src/lib/Client/Tools/Yum.py index 0986fca33..73506af14 100644 --- a/src/lib/Client/Tools/Yum.py +++ b/src/lib/Client/Tools/Yum.py @@ -43,5 +43,5 @@ class Yum(Bcfg2.Client.Tools.RPM.RPM): def VerifyPackage(self, entry, modlist): if entry.get('version') == 'noverify': - return self.installed.has_key(entry.get('name')) + return entry.get('name') in self.installed return Bcfg2.Client.Tools.RPM.RPM.VerifyPackage(self, entry, modlist) diff --git a/src/lib/Client/Tools/rpmtools.py b/src/lib/Client/Tools/rpmtools.py index d751270e6..8e3473239 100755 --- a/src/lib/Client/Tools/rpmtools.py +++ b/src/lib/Client/Tools/rpmtools.py @@ -184,7 +184,7 @@ def getindexbykeyword(index_ts, **kwargs): else: index_mi = index_ts.dbMatch() - if kwargs.has_key('epoch'): + if 'epoch' in kwargs: if kwargs['epoch'] != None and kwargs['epoch'] != 'None': kwargs['epoch'] = int(kwargs['epoch']) else: @@ -222,7 +222,7 @@ def getheadersbykeyword(header_ts, **kwargs): else: header_mi = header_ts.dbMatch() - if kwargs.has_key('epoch'): + if 'epoch' in kwargs: if kwargs['epoch'] != None and kwargs['epoch'] != 'None': kwargs['epoch'] = int(kwargs['epoch']) else: diff --git a/src/lib/Server/Admin/Pull.py b/src/lib/Server/Admin/Pull.py index 837298432..b5f869d07 100644 --- a/src/lib/Server/Admin/Pull.py +++ b/src/lib/Server/Admin/Pull.py @@ -93,7 +93,7 @@ class Pull(Bcfg2.Server.Admin.MetadataCore): meta = self.bcore.metadata.get_metadata(client) # find appropriate plugin in bcore glist = [gen for gen in self.bcore.generators if - gen.Entries.get(etype, {}).has_key(ename)] + ename in gen.Entries.get(etype, {})] if len(glist) != 1: self.errExit("Got wrong numbers of matching generators for entry:" \ + "%s" % ([g.__name__ for g in glist])) diff --git a/src/lib/Server/Core.py b/src/lib/Server/Core.py index bd09dc53b..e25bec4b2 100644 --- a/src/lib/Server/Core.py +++ b/src/lib/Server/Core.py @@ -55,7 +55,7 @@ class Core(object): for plugin in structures + generators + plugins: - if not self.plugins.has_key(plugin): + if not plugin in self.plugins: self.init_plugins(plugin) chk_plugins = self.plugins.values() @@ -162,7 +162,7 @@ class Core(object): entry.get('name'))) glist = [gen for gen in self.generators if - gen.Entries.get(entry.tag, {}).has_key(entry.get('name'))] + entry.get('name') in gen.Entries.get(entry.tag, {})] if len(glist) == 1: return glist[0].Entries[entry.tag][entry.get('name')](entry, metadata) elif len(glist) > 1: @@ -190,7 +190,7 @@ class Core(object): logger.error("error in GetStructures", exc_info=1) return lxml.etree.Element("error", type='structure error') - if self.plugins.has_key('Deps'): + if 'Deps' in self.plugins: # do prereq processing prereqs = self.plugins['Deps'].GeneratePrereqs(structures, meta) structures.append(prereqs) diff --git a/src/lib/Server/FileMonitor.py b/src/lib/Server/FileMonitor.py index 73ae8b8a2..0840019e8 100644 --- a/src/lib/Server/FileMonitor.py +++ b/src/lib/Server/FileMonitor.py @@ -68,7 +68,7 @@ class FamFam(object): else: collapsed += 1 for event in unique: - if self.users.has_key(event.requestID): + if event.requestID in self.users: try: self.users[event.requestID].HandleEvent(event) except: @@ -95,7 +95,7 @@ class GaminEvent(Event): Event.__init__(self, request_id, filename, code) action_map = {GAMCreated: 'created', GAMExists: 'exists', GAMChanged: 'changed', GAMDeleted: 'deleted', GAMEndExist: 'endExist', GAMMoved: 'moved'} - if action_map.has_key(code): + if code in action_map: self.action = action_map[code] class GaminFam(object): @@ -211,7 +211,7 @@ class PseudoFam(object): rawevents.append(event) self.pending = [] for event in rawevents: - if self.users.has_key(event.requestID): + if event.requestID in self.users: self.users[event.requestID].HandleEvent(event) return count diff --git a/src/lib/Server/Hostbase/hostbase/views.py b/src/lib/Server/Hostbase/hostbase/views.py index e8a204417..a4bddb857 100644 --- a/src/lib/Server/Hostbase/hostbase/views.py +++ b/src/lib/Server/Hostbase/hostbase/views.py @@ -43,7 +43,7 @@ def search(request): """Search for hosts in the database If more than one field is entered, logical AND is used """ - if request.GET.has_key('sub'): + if 'sub' in request.GET: querystring = """SELECT DISTINCT h.hostname, h.id, h.status FROM (((((hostbase_host h INNER JOIN hostbase_interface i ON h.id = i.host_id) @@ -204,7 +204,7 @@ def edit(request, host_id): text = do_log(text, attrib, host.__dict__[attrib], request.POST[attrib]) host.__dict__[attrib] = request.POST[attrib] - if request.POST.has_key('expiration_date'): + if 'expiration_date' in request.POST: ymd = request.POST['expiration_date'].split("-") if date(int(ymd[0]), int(ymd[1]), int(ymd[2])) != host.__dict__['expiration_date']: text = do_log(text, 'expiration_date', host.__dict__['expiration_date'], @@ -222,8 +222,8 @@ def edit(request, host_id): text = do_log(text, 'hdwr_type', oldtype, request.POST['hdwr_type%d' % inter.id]) inter.hdwr_type = request.POST['hdwr_type%d' % inter.id] changetype = True - if (request.POST.has_key('dhcp%d' % inter.id) and not inter.dhcp or - not request.POST.has_key('dhcp%d' % inter.id) and inter.dhcp): + if (('dhcp%d' % inter.id) in request.POST and not inter.dhcp or + not ('dhcp%d' % inter.id) in request.POST and inter.dhcp): text = do_log(text, 'dhcp', inter.dhcp, int(not inter.dhcp)) inter.dhcp = not inter.dhcp for ip in ips: @@ -357,7 +357,7 @@ def edit(request, host_id): def confirm(request, item, item_id, host_id=None, name_id=None, zone_id=None): """Asks if the user is sure he/she wants to remove an item""" - if request.GET.has_key('sub'): + if 'sub' in request.GET: if item == 'interface': for ip in Interface.objects.get(id=item_id).ip_set.all(): for name in ip.name_set.all(): @@ -455,7 +455,7 @@ def dnsedit(request, host_id): """Edits specific DNS information Data is validated before committed to the database""" text = '' - if request.GET.has_key('sub'): + if 'sub' in request.GET: hostdata = gethostdata(host_id, True) for ip in hostdata['names']: ipaddr = IP.objects.get(id=ip) @@ -550,7 +550,7 @@ def dnsedit(request, host_id): def new(request): """Function for creating a new host in hostbase Data is validated before committed to the database""" - if request.GET.has_key('sub'): + if 'sub' in request.GET: try: Host.objects.get(hostname=request.POST['hostname'].lower()) return render_to_response('errors.html', @@ -566,13 +566,13 @@ def new(request): host = Host() # this is the stuff that validate() should take care of # examine the check boxes for any changes - host.outbound_smtp = request.POST.has_key('outbound_smtp') + host.outbound_smtp = 'outbound_smtp' in request.POST for attrib in attribs: - if request.POST.has_key(attrib): + if attrib in request.POST: host.__dict__[attrib] = request.POST[attrib].lower() - if request.POST.has_key('comments'): + if 'comments' in request.POST: host.comments = request.POST['comments'] - if request.POST.has_key('expiration_date'): + if 'expiration_date' in request.POST: # ymd = request.POST['expiration_date'].split("-") # host.__dict__['expiration_date'] = date(int(ymd[0]), int(ymd[1]), int(ymd[2])) host.__dict__['expiration_date'] = date(2000, 1, 1) @@ -585,9 +585,9 @@ def new(request): if request.POST['mac_addr_new']: new_inter = Interface(host=host, - mac_addr=request.POST['mac_addr_new'].lower().replace('-',':'), - hdwr_type=request.POST['hdwr_type_new'], - dhcp=request.POST.has_key('dhcp_new')) + mac_addr = request.POST['mac_addr_new'].lower().replace('-',':'), + hdwr_type = request.POST['hdwr_type_new'], + dhcp = 'dhcp_new' in request.POST) new_inter.save() if request.POST['mac_addr_new'] and request.POST['ip_addr_new']: new_ip = IP(interface=new_inter, ip_addr=request.POST['ip_addr_new']) @@ -643,9 +643,9 @@ def new(request): name.mxs.add(mx) if request.POST['mac_addr_new2']: new_inter = Interface(host=host, - mac_addr=request.POST['mac_addr_new2'].lower().replace('-',':'), - hdwr_type=request.POST['hdwr_type_new2'], - dhcp=request.POST.has_key('dhcp_new2')) + mac_addr = request.POST['mac_addr_new2'].lower().replace('-',':'), + hdwr_type = request.POST['hdwr_type_new2'], + dhcp = 'dhcp_new2' in request.POST) new_inter.save() if request.POST['mac_addr_new2'] and request.POST['ip_addr_new2']: new_ip = IP(interface=new_inter, ip_addr=request.POST['ip_addr_new2']) @@ -714,7 +714,7 @@ def new(request): def copy(request, host_id): """Function for creating a new host in hostbase Data is validated before committed to the database""" - if request.GET.has_key('sub'): + if 'sub' in request.GET: try: Host.objects.get(hostname=request.POST['hostname'].lower()) return render_to_response('errors.html', @@ -730,13 +730,13 @@ def copy(request, host_id): host = Host() # this is the stuff that validate() should take care of # examine the check boxes for any changes - host.outbound_smtp = request.POST.has_key('outbound_smtp') + host.outbound_smtp = 'outbound_smtp' in request.POST for attrib in attribs: - if request.POST.has_key(attrib): + if attrib in request.POST: host.__dict__[attrib] = request.POST[attrib].lower() - if request.POST.has_key('comments'): + if 'comments' in request.POST: host.comments = request.POST['comments'] - if request.POST.has_key('expiration_date'): + if 'expiration_date' in request.POST: # ymd = request.POST['expiration_date'].split("-") # host.__dict__['expiration_date'] = date(int(ymd[0]), int(ymd[1]), int(ymd[2])) host.__dict__['expiration_date'] = date(2000, 1, 1) @@ -749,9 +749,9 @@ def copy(request, host_id): if request.POST['mac_addr_new']: new_inter = Interface(host=host, - mac_addr=request.POST['mac_addr_new'].lower().replace('-',':'), - hdwr_type=request.POST['hdwr_type_new'], - dhcp=request.POST.has_key('dhcp_new')) + mac_addr = request.POST['mac_addr_new'].lower().replace('-',':'), + hdwr_type = request.POST['hdwr_type_new'], + dhcp = 'dhcp_new' in request.POST) new_inter.save() if request.POST['mac_addr_new'] and request.POST['ip_addr_new']: new_ip = IP(interface=new_inter, ip_addr=request.POST['ip_addr_new']) @@ -807,9 +807,9 @@ def copy(request, host_id): name.mxs.add(mx) if request.POST['mac_addr_new2']: new_inter = Interface(host=host, - mac_addr=request.POST['mac_addr_new2'].lower().replace('-',':'), - hdwr_type=request.POST['hdwr_type_new2'], - dhcp=request.POST.has_key('dhcp_new2')) + mac_addr = request.POST['mac_addr_new2'].lower().replace('-',':'), + hdwr_type = request.POST['hdwr_type_new2'], + dhcp = 'dhcp_new2' in request.POST) new_inter.save() if request.POST['mac_addr_new2'] and request.POST['ip_addr_new2']: new_ip = IP(interface=new_inter, ip_addr=request.POST['ip_addr_new2']) @@ -879,7 +879,7 @@ def copy(request, host_id): def remove(request, host_id): host = Host.objects.get(id=host_id) - if request.has_key('sub'): + if 'sub' in request: for interface in host.interface_set.all(): for ip in interface.ip_set.all(): for name in ip.name_set.all(): @@ -935,10 +935,10 @@ def validate(request, new=False, host_id=None): and request.POST['mac_addr_new']): failures.append('mac_addr (#1)') if ((request.POST['mac_addr_new'] or request.POST['ip_addr_new']) and - not request.has_key('hdwr_type_new')): + not 'hdwr_type_new' in request): failures.append('hdwr_type (#1)') if ((request.POST['mac_addr_new2'] or request.POST['ip_addr_new2']) and - not request.has_key('hdwr_type_new2')): + not 'hdwr_type_new2' in request): failures.append('hdwr_type (#2)') if (not regex.macaddr.match(request.POST['mac_addr_new2']) diff --git a/src/lib/Server/Plugin.py b/src/lib/Server/Plugin.py index 9424e085f..002709c2c 100644 --- a/src/lib/Server/Plugin.py +++ b/src/lib/Server/Plugin.py @@ -166,7 +166,7 @@ class DirectoryBacked(object): '''Add new entry to data structures upon file creation''' if name == '': logger.info("got add for empty name") - elif self.entries.has_key(name): + elif name in self.entries: self.entries[name].HandleEvent() else: if ((name[-1] == '~') or (name[:2] == '.#') or (name[-4:] == '.swp') or (name in ['SCCS', '.svn'])): @@ -188,10 +188,10 @@ class DirectoryBacked(object): elif action == 'created': self.AddEntry(event.filename) elif action == 'changed': - if self.entries.has_key(event.filename): + if event.filename in self.entries: self.entries[event.filename].HandleEvent(event) elif action == 'deleted': - if self.entries.has_key(event.filename): + if event.filename in self.entries: del self.entries[event.filename] elif action in ['endExist']: pass @@ -402,8 +402,8 @@ class PrioDir(GeneratorPlugin, XMLDirectoryBacked): self.logger.error("Called before data loaded") raise PluginExecutionError matching = [src for src in self.entries.values() - if src.cache and src.cache[1].has_key(entry.tag) - and src.cache[1][entry.tag].has_key(name)] + if src.cache and entry.tag in src.cache[1] + and name in src.cache[1][entry.tag]] if len(matching) == 0: raise PluginExecutionError elif len(matching) == 1: @@ -419,9 +419,9 @@ class PrioDir(GeneratorPlugin, XMLDirectoryBacked): index = prio.index(max(prio)) data = matching[index].cache[1][entry.tag][name] - if data.has_key('__text__'): + if '__text__' in data: entry.text = data['__text__'] - if data.has_key('__children__'): + if '__children__' in data: [entry.append(copy.deepcopy(item)) for item in data['__children__']] [entry.attrib.__setitem__(key, data[key]) for key in data.keys() \ if not key.startswith('__')] diff --git a/src/lib/Server/Plugins/Account.py b/src/lib/Server/Plugins/Account.py index 8cab47b01..dd44390e1 100644 --- a/src/lib/Server/Plugins/Account.py +++ b/src/lib/Server/Plugins/Account.py @@ -62,7 +62,7 @@ class Account(Bcfg2.Server.Plugin.GeneratorPlugin): rdata = self.repository.entries entry.text = "".join([rdata["%s.key" % user].data for user \ in superusers if \ - rdata.has_key("%s.key" % user)]) + ("%s.key" % user) in rdata]) perms = {'owner':'root', 'group':'root', 'perms':'0600'} [entry.attrib.__setitem__(key, value) for (key, value) \ in perms.iteritems()] diff --git a/src/lib/Server/Plugins/BB.py b/src/lib/Server/Plugins/BB.py index 858ab8102..70b90016b 100644 --- a/src/lib/Server/Plugins/BB.py +++ b/src/lib/Server/Plugins/BB.py @@ -55,7 +55,7 @@ class BB(Bcfg2.Server.Plugin.GeneratorPlugin, viz_str = "" egroups = groups.findall("Group") + groups.findall('.//Groups/Group') for group in egroups: - if not categories.has_key(group.get('category')): + if not group.get('category') in categories: categories[group.get('category')] = colors.pop() group.set('color', categories[group.get('category')]) if None in categories: @@ -63,7 +63,7 @@ class BB(Bcfg2.Server.Plugin.GeneratorPlugin, if hosts: clients = self.clients for client, profile in clients.iteritems(): - if instances.has_key(profile): + if profile in instances: instances[profile].append(client) else: instances[profile] = [client] @@ -160,7 +160,7 @@ class BB(Bcfg2.Server.Plugin.GeneratorPlugin, entry.text = self.entries["static.dhcpd.conf"].data for host, data in self.nodes.iteritems(): entry.text += "host %s {\n" % (host + DOMAIN_SUFFIX) - if data.has_key('mac') and data.has_key('ip'): + if 'mac' in data and 'ip' in data: entry.text += " hardware ethernet %s;\n" % (data['mac']) entry.text += " fixed-address %s;\n" % (data['ip']) entry.text += " filename \"%s\";\n}\n" % (PXE_CONFIG) @@ -175,7 +175,7 @@ class BB(Bcfg2.Server.Plugin.GeneratorPlugin, entry = self.entries["static.dhcpd.conf"].data for host, data in self.nodes.iteritems(): entry += "host %s {\n" % (host + DOMAIN_SUFFIX) - if data.has_key('mac') and data.has_key('ip'): + if 'mac' in data and 'ip' in data: entry += " hardware ethernet %s;\n" % (data['mac']) entry += " fixed-address %s;\n" % (data['ip']) entry += " filename \"%s\";\n}\n" % (PXE_CONFIG) @@ -190,7 +190,7 @@ class BB(Bcfg2.Server.Plugin.GeneratorPlugin, users = self.get_users(metadata) rdata = self.entries entry.text = "".join([rdata["%s.key" % user].data for user - in users if rdata.has_key("%s.key" % user)]) + in users if ("%s.key" % user) in rdata]) perms = {'owner':'root', 'group':'root', 'perms':'0600'} [entry.attrib.__setitem__(key, value) for (key, value) in perms.iteritems()] @@ -220,7 +220,7 @@ class BB(Bcfg2.Server.Plugin.GeneratorPlugin, users = [] for host, host_dict in self.nodes.iteritems(): if host == metadata.hostname.split('.')[0]: - if host_dict.has_key('user'): + if 'user' in host_dict: if host_dict['user'] != "none": users.append(host_dict['user']) return users @@ -266,7 +266,7 @@ class BB(Bcfg2.Server.Plugin.GeneratorPlugin, '''Handle events''' Bcfg2.Server.Plugin.DirectoryBacked.HandleEvent(self, event) # static.dhcpd.conf hack - if self.entries.has_key('static.dhcpd.conf'): + if 'static.dhcpd.conf' in self.entries: self.dhcpd_loaded = True if self.need_update and self.dhcpd_loaded: self.update_dhcpd() @@ -285,7 +285,7 @@ class BB(Bcfg2.Server.Plugin.GeneratorPlugin, if node.findall("Interface"): iface = node.findall("Interface")[0] node_dict['mac'] = iface.attrib['mac'] - if iface.attrib.has_key('ip'): + if 'ip' in iface.attrib: node_dict['ip'] = iface.attrib['ip'] # populate self.clients dict full_hostname = host + DOMAIN_SUFFIX @@ -308,7 +308,7 @@ class BB(Bcfg2.Server.Plugin.GeneratorPlugin, profile = "basic" self.clients[full_hostname] = profile # get ip address from bb.mxl, if available - if node_dict.has_key('ip'): + if 'ip' in node_dict: ip = node_dict['ip'] self.addresses[ip] = [host] else: @@ -319,7 +319,7 @@ class BB(Bcfg2.Server.Plugin.GeneratorPlugin, self.nodes[host] = node_dict # update symlinks and /etc/dhcp3/dhcpd.conf if self.write_to_disk: - if not node_dict.has_key('mac'): + if not 'mac' in node_dict: self.logger.error("no mac address for %s" % host) continue mac = node_dict['mac'].replace(':','-').lower() diff --git a/src/lib/Server/Plugins/Bundler.py b/src/lib/Server/Plugins/Bundler.py index f771d4016..5cc881167 100644 --- a/src/lib/Server/Plugins/Bundler.py +++ b/src/lib/Server/Plugins/Bundler.py @@ -23,7 +23,7 @@ class Bundler(Bcfg2.Server.Plugin.StructurePlugin, '''Build all structures for client (metadata)''' bundleset = [] for bundlename in metadata.bundles: - if not self.entries.has_key("%s.xml"%(bundlename)): + if not ("%s.xml" % bundlename) in self.entries: self.logger.error("Client %s requested nonexistent bundle %s" % \ (metadata.hostname, bundlename)) continue diff --git a/src/lib/Server/Plugins/Deps.py b/src/lib/Server/Plugins/Deps.py index 21ff302fe..8749f2a31 100644 --- a/src/lib/Server/Plugins/Deps.py +++ b/src/lib/Server/Plugins/Deps.py @@ -61,7 +61,7 @@ class Deps(Bcfg2.Server.Plugin.PrioDir): gdata = metadata.groups[:] gdata.sort() gdata = tuple(gdata) - if self.cache.has_key((entries, gdata)): + if (entries, gdata) in self.cache: prereqs = self.cache[(entries, gdata)] else: [src.Cache(metadata) for src in self.entries.values()] @@ -70,8 +70,8 @@ class Deps(Bcfg2.Server.Plugin.PrioDir): while toexamine: entry = toexamine.pop() matching = [src for src in self.entries.values() - if src.cache and src.cache[1].has_key(entry[0]) - and src.cache[1][entry[0]].has_key(entry[1])] + if src.cache and entry[0] in src.cache[1] + and entry[1] in src.cache[1][entry[0]]] if len(matching) > 1: prio = [int(src.priority) for src in matching] if prio.count(max(prio)) > 1: diff --git a/src/lib/Server/Plugins/Hostbase.py b/src/lib/Server/Plugins/Hostbase.py index 08a521545..b08e847da 100644 --- a/src/lib/Server/Plugins/Hostbase.py +++ b/src/lib/Server/Plugins/Hostbase.py @@ -78,7 +78,7 @@ class Hostbase(StructurePlugin,GeneratorPlugin): def FetchFile(self, entry, metadata): '''Return prebuilt file data''' fname = entry.get('name').split('/')[-1] - if not self.filedata.has_key(fname): + if not fname in self.filedata: raise PluginExecutionError perms = {'owner':'root', 'group':'root', 'perms':'644'} [entry.attrib.__setitem__(key, value) for (key, value) in perms.iteritems()] diff --git a/src/lib/Server/Plugins/Metadata.py b/src/lib/Server/Plugins/Metadata.py index f17f52ed4..5ab1a9252 100644 --- a/src/lib/Server/Plugins/Metadata.py +++ b/src/lib/Server/Plugins/Metadata.py @@ -250,7 +250,7 @@ class Metadata(Bcfg2.Server.Plugin.MetadataPlugin, clname = client.get('name').lower() if 'address' in client.attrib: caddr = client.get('address') - if self.addresses.has_key(caddr): + if caddr in self.addresses: self.addresses[caddr].append(clname) else: self.addresses[caddr] = [clname] @@ -264,7 +264,7 @@ class Metadata(Bcfg2.Server.Plugin.MetadataPlugin, self.passwords[clname] = client.get('password') for alias in [alias for alias in client.findall('Alias')\ if 'address' in alias.attrib]: - if self.addresses.has_key(alias.get('address')): + if alias.get('address') in self.addresses: self.addresses[alias.get('address')].append(clname) else: self.addresses[alias.get('address')] = [clname] @@ -289,7 +289,7 @@ class Metadata(Bcfg2.Server.Plugin.MetadataPlugin, self.profiles.append(group.get('name')) if group.get('public', 'false') == 'true': self.public.append(group.get('name')) - if group.attrib.has_key('category'): + if 'category' in group.attrib: self.categories[group.get('name')] = group.get('category') for group in grouptmp: # self.groups[group] => (bundles, groups, categories) @@ -300,14 +300,14 @@ class Metadata(Bcfg2.Server.Plugin.MetadataPlugin, now = tocheck.pop() if now not in self.groups[group][1]: self.groups[group][1].append(now) - if grouptmp.has_key(now): + if now in grouptmp: (bundles, groups) = grouptmp[now] for ggg in [ggg for ggg in groups if ggg not in self.groups[group][1]]: if ggg not in self.categories or \ self.categories[ggg] not in self.groups[group][2]: self.groups[group][1].append(ggg) tocheck.append(ggg) - if self.categories.has_key(ggg): + if ggg in self.categories: group_cat[self.categories[ggg]] = ggg elif ggg in self.categories: self.logger.info("Group %s: %s cat-suppressed %s" % \ @@ -341,14 +341,14 @@ class Metadata(Bcfg2.Server.Plugin.MetadataPlugin, if profile not in self.public: self.logger.error("Failed to set client %s to private group %s" % (client, profile)) raise MetadataConsistencyError - if self.clients.has_key(client): + if client in self.clients: self.logger.info("Changing %s group from %s to %s" % (client, self.clients[client], profile)) cli = self.clientdata_original.xpath('.//Client[@name="%s"]' % (client)) cli[0].set('profile', profile) else: self.logger.info("Creating new client: %s, profile %s" % \ (client, profile)) - if self.session_cache.has_key(addresspair): + if addresspair in self.session_cache: # we are working with a uuid'd client lxml.etree.SubElement(self.clientdata_original.getroot(), 'Client', name=client, @@ -424,12 +424,12 @@ class Metadata(Bcfg2.Server.Plugin.MetadataPlugin, def resolve_client(self, addresspair): '''Lookup address locally or in DNS to get a hostname''' #print self.session_cache - if self.session_cache.has_key(addresspair): + if addresspair in self.session_cache: (stamp, uuid) = self.session_cache[addresspair] if time.time() - stamp < 60: return self.uuid[uuid] address = addresspair[0] - if self.addresses.has_key(address): + if address in self.addresses: if len(self.addresses[address]) != 1: self.logger.error("Address %s has multiple reverse assignments; a uuid must be used" % (address)) raise MetadataConsistencyError @@ -447,9 +447,9 @@ class Metadata(Bcfg2.Server.Plugin.MetadataPlugin, def get_metadata(self, client): '''Return the metadata for a given client''' client = client.lower() - if self.aliases.has_key(client): + if client in self.aliases: client = self.aliases[client] - if self.clients.has_key(client): + if client in self.clients: (bundles, groups, categories) = self.groups[self.clients[client]] else: if self.default == None: @@ -462,7 +462,7 @@ class Metadata(Bcfg2.Server.Plugin.MetadataPlugin, newbundles = bundles[:] newcategories = {} newcategories.update(categories) - if self.passwords.has_key(client): + if client in self.passwords: password = self.passwords[client] else: password = None @@ -472,7 +472,7 @@ class Metadata(Bcfg2.Server.Plugin.MetadataPlugin, else: uuid = None for group in self.cgroups.get(client, []): - if self.groups.has_key(group): + if group in self.groups: nbundles, ngroups, ncategories = self.groups[group] else: nbundles, ngroups, ncategories = ([], [group], {}) @@ -500,7 +500,7 @@ class Metadata(Bcfg2.Server.Plugin.MetadataPlugin, def ReceiveDataItem(self, client, data): '''Receive probe results pertaining to client''' - if not self.cgroups.has_key(client.hostname): + if not client.hostname in self.cgroups: self.cgroups[client.hostname] = [] if data.text == None: self.logger.error("Got null response to probe %s from %s" % \ @@ -561,7 +561,7 @@ class Metadata(Bcfg2.Server.Plugin.MetadataPlugin, self.logger.error("Client %s used incorrect global password" % (address[0])) return False if client not in self.secure: - if self.passwords.has_key(client): + if client in self.passwords: plist = [self.password, self.passwords[client]] else: plist = [self.password] @@ -599,7 +599,7 @@ class Metadata(Bcfg2.Server.Plugin.MetadataPlugin, viz_str = "" egroups = groups.findall("Group") + groups.findall('.//Groups/Group') for group in egroups: - if not categories.has_key(group.get('category')): + if not group.get('category') in categories: categories[group.get('category')] = colors.pop() group.set('color', categories[group.get('category')]) if None in categories: @@ -607,7 +607,7 @@ class Metadata(Bcfg2.Server.Plugin.MetadataPlugin, if hosts: clients = self.clients for client, profile in clients.iteritems(): - if instances.has_key(profile): + if profile in instances: instances[profile].append(client) else: instances[profile] = [client] diff --git a/src/lib/Server/Plugins/SSHbase.py b/src/lib/Server/Plugins/SSHbase.py index e1d80b0bc..4910cb6f4 100644 --- a/src/lib/Server/Plugins/SSHbase.py +++ b/src/lib/Server/Plugins/SSHbase.py @@ -108,7 +108,7 @@ class SSHbase(Bcfg2.Server.Plugin.GeneratorPlugin, Bcfg2.Server.Plugin.Director def get_ipcache_entry(self, client): '''build a cache of dns results''' - if self.ipcache.has_key(client): + if client in self.ipcache: if self.ipcache[client]: return self.ipcache[client] else: @@ -133,7 +133,7 @@ class SSHbase(Bcfg2.Server.Plugin.GeneratorPlugin, Bcfg2.Server.Plugin.Director client = metadata.hostname entry.text = self.skn hostkeys = [keytmpl % client for keytmpl in self.pubkeys \ - if self.entries.has_key(keytmpl % client)] + if (keytmpl % client) in self.entries] hostkeys.sort() for hostkey in hostkeys: entry.text += "localhost,localhost.localdomain,127.0.0.1 %s" % ( @@ -147,7 +147,7 @@ class SSHbase(Bcfg2.Server.Plugin.GeneratorPlugin, Bcfg2.Server.Plugin.Director filename = "%s.H_%s" % (entry.get('name').split('/')[-1], client) if filename not in self.entries.keys(): self.GenerateHostKeys(client) - if not self.entries.has_key(filename): + if not filename in self.entries: self.logger.error("%s still not registered" % filename) raise Bcfg2.Server.Plugin.PluginExecutionError keydata = self.entries[filename].data diff --git a/src/lib/Server/Reports/importscript.py b/src/lib/Server/Reports/importscript.py index 78d1af4d0..763056c20 100755 --- a/src/lib/Server/Reports/importscript.py +++ b/src/lib/Server/Reports/importscript.py @@ -61,7 +61,7 @@ def load_stats(cdata, sdata, vlevel, quick=False, location=''): for node in sdata.findall('Node'): name = node.get('name') - if not clients.has_key(name): + if not name in clients: cursor.execute(\ "INSERT INTO reports_client VALUES (NULL, %s, %s, NULL, NULL)", [datetime.now(), name]) diff --git a/src/lib/tlslite/BaseDB.py b/src/lib/tlslite/BaseDB.py index ca8dff6b4..f4914fb7e 100755 --- a/src/lib/tlslite/BaseDB.py +++ b/src/lib/tlslite/BaseDB.py @@ -1,120 +1,120 @@ -"""Base class for SharedKeyDB and VerifierDB."""
-
-import anydbm
-import thread
-
-class BaseDB:
- def __init__(self, filename, type):
- self.type = type
- self.filename = filename
- if self.filename:
- self.db = None
- else:
- self.db = {}
- self.lock = thread.allocate_lock()
-
- def create(self):
- """Create a new on-disk database.
-
- @raise anydbm.error: If there's a problem creating the database.
- """
- if self.filename:
- self.db = anydbm.open(self.filename, "n") #raises anydbm.error
- self.db["--Reserved--type"] = self.type
- self.db.sync()
- else:
- self.db = {}
-
- def open(self):
- """Open a pre-existing on-disk database.
-
- @raise anydbm.error: If there's a problem opening the database.
- @raise ValueError: If the database is not of the right type.
- """
- if not self.filename:
- raise ValueError("Can only open on-disk databases")
- self.db = anydbm.open(self.filename, "w") #raises anydbm.error
- try:
- if self.db["--Reserved--type"] != self.type:
- raise ValueError("Not a %s database" % self.type)
- except KeyError:
- raise ValueError("Not a recognized database")
-
- def __getitem__(self, username):
- if self.db == None:
- raise AssertionError("DB not open")
-
- self.lock.acquire()
- try:
- valueStr = self.db[username]
- finally:
- self.lock.release()
-
- return self._getItem(username, valueStr)
-
- def __setitem__(self, username, value):
- if self.db == None:
- raise AssertionError("DB not open")
-
- valueStr = self._setItem(username, value)
-
- self.lock.acquire()
- try:
- self.db[username] = valueStr
- if self.filename:
- self.db.sync()
- finally:
- self.lock.release()
-
- def __delitem__(self, username):
- if self.db == None:
- raise AssertionError("DB not open")
-
- self.lock.acquire()
- try:
- del(self.db[username])
- if self.filename:
- self.db.sync()
- finally:
- self.lock.release()
-
- def __contains__(self, username):
- """Check if the database contains the specified username.
-
- @type username: str
- @param username: The username to check for.
-
- @rtype: bool
- @return: True if the database contains the username, False
- otherwise.
-
- """
- if self.db == None:
- raise AssertionError("DB not open")
-
- self.lock.acquire()
- try:
- return self.db.has_key(username)
- finally:
- self.lock.release()
-
- def check(self, username, param):
- value = self.__getitem__(username)
- return self._checkItem(value, username, param)
-
- def keys(self):
- """Return a list of usernames in the database.
-
- @rtype: list
- @return: The usernames in the database.
- """
- if self.db == None:
- raise AssertionError("DB not open")
-
- self.lock.acquire()
- try:
- usernames = self.db.keys()
- finally:
- self.lock.release()
- usernames = [u for u in usernames if not u.startswith("--Reserved--")]
- return usernames
\ No newline at end of file +"""Base class for SharedKeyDB and VerifierDB.""" + +import anydbm +import thread + +class BaseDB: + def __init__(self, filename, type): + self.type = type + self.filename = filename + if self.filename: + self.db = None + else: + self.db = {} + self.lock = thread.allocate_lock() + + def create(self): + """Create a new on-disk database. + + @raise anydbm.error: If there's a problem creating the database. + """ + if self.filename: + self.db = anydbm.open(self.filename, "n") #raises anydbm.error + self.db["--Reserved--type"] = self.type + self.db.sync() + else: + self.db = {} + + def open(self): + """Open a pre-existing on-disk database. + + @raise anydbm.error: If there's a problem opening the database. + @raise ValueError: If the database is not of the right type. + """ + if not self.filename: + raise ValueError("Can only open on-disk databases") + self.db = anydbm.open(self.filename, "w") #raises anydbm.error + try: + if self.db["--Reserved--type"] != self.type: + raise ValueError("Not a %s database" % self.type) + except KeyError: + raise ValueError("Not a recognized database") + + def __getitem__(self, username): + if self.db == None: + raise AssertionError("DB not open") + + self.lock.acquire() + try: + valueStr = self.db[username] + finally: + self.lock.release() + + return self._getItem(username, valueStr) + + def __setitem__(self, username, value): + if self.db == None: + raise AssertionError("DB not open") + + valueStr = self._setItem(username, value) + + self.lock.acquire() + try: + self.db[username] = valueStr + if self.filename: + self.db.sync() + finally: + self.lock.release() + + def __delitem__(self, username): + if self.db == None: + raise AssertionError("DB not open") + + self.lock.acquire() + try: + del(self.db[username]) + if self.filename: + self.db.sync() + finally: + self.lock.release() + + def __contains__(self, username): + """Check if the database contains the specified username. + + @type username: str + @param username: The username to check for. + + @rtype: bool + @return: True if the database contains the username, False + otherwise. + + """ + if self.db == None: + raise AssertionError("DB not open") + + self.lock.acquire() + try: + return username in self.db + finally: + self.lock.release() + + def check(self, username, param): + value = self.__getitem__(username) + return self._checkItem(value, username, param) + + def keys(self): + """Return a list of usernames in the database. + + @rtype: list + @return: The usernames in the database. + """ + if self.db == None: + raise AssertionError("DB not open") + + self.lock.acquire() + try: + usernames = self.db.keys() + finally: + self.lock.release() + usernames = [u for u in usernames if not u.startswith("--Reserved--")] + return usernames diff --git a/src/sbin/bcfg2-info b/src/sbin/bcfg2-info index 96da82bf7..c0c2673a5 100755 --- a/src/sbin/bcfg2-info +++ b/src/sbin/bcfg2-info @@ -190,7 +190,7 @@ Usage: [quit|exit]""" prof = 'yes' else: prof = 'no' - if self.metadata.categories.has_key(group): + if group in self.metadata.categories: cat = self.metadata.categories[group] else: cat = '' @@ -256,7 +256,7 @@ Usage: [quit|exit]""" else: interested = [(etype, generator.Entries[etype]) \ for etype in etypes \ - if generator.Entries.has_key(etype)] + if etype in generator.Entries] for etype, names in interested: for name in [name for name in names if name in \ generator.Entries.get(etype, {})]: diff --git a/src/sbin/bcfg2-reports b/src/sbin/bcfg2-reports index 16b9cd11e..abe24d037 100755 --- a/src/sbin/bcfg2-reports +++ b/src/sbin/bcfg2-reports @@ -232,7 +232,7 @@ else: for item in baditems: if item.name == badentry[1] and item.kind == badentry[0]: result.append(c_inst) - if entrydict.has_key(c_inst): + if c_inst in entrydict: entrydict.get(c_inst).append(badentry[1]) else: entrydict[c_inst] = [badentry[1]] @@ -254,7 +254,7 @@ else: for item in extraitems: if item.name == extraentry[1] and item.kind == extraentry[0]: result.append(c_inst) - if entrydict.has_key(c_inst): + if c_inst in entrydict: entrydict.get(c_inst).append(extraentry[1]) else: entrydict[c_inst] = [extraentry[1]] |