s4-samba-tool: fixed exception handling in subcommands
authorAndrew Tridgell <tridge@samba.org>
Mon, 29 Nov 2010 03:15:57 +0000 (14:15 +1100)
committerAndrew Tridgell <tridge@samba.org>
Mon, 29 Nov 2010 07:04:42 +0000 (18:04 +1100)
this switches to the new pattern of:

 except Exception, e:
  raise CommandError("some error message", e)

13 files changed:
source4/scripting/python/samba/netcmd/drs.py
source4/scripting/python/samba/netcmd/gpo.py
source4/scripting/python/samba/netcmd/group.py
source4/scripting/python/samba/netcmd/newuser.py
source4/scripting/python/samba/netcmd/ntacl.py
source4/scripting/python/samba/netcmd/pwsettings.py
source4/scripting/python/samba/netcmd/rodc.py
source4/scripting/python/samba/netcmd/setpassword.py
source4/scripting/python/samba/ntacls.py
source4/scripting/python/samba/provision/__init__.py
source4/scripting/python/samba/samdb.py
source4/scripting/python/samba/schema.py
source4/scripting/python/samba/upgradehelpers.py

index 387524b94383383ac19d61cbab5042cfa106a582..6f5b5b8ed3f7904da7f0e6e5a672a800becd86fd 100644 (file)
@@ -44,8 +44,8 @@ def drsuapi_connect(ctx):
     try:
         ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
         (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
-    except Exception, estr:
-        raise CommandError("DRS connection to %s failed - %s" % (ctx.server, estr))
+    except Exception, e:
+        raise CommandError("DRS connection to %s failed" % ctx.server, e)
 
 
 def samdb_connect(ctx):
@@ -54,8 +54,8 @@ def samdb_connect(ctx):
         ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
                           session_info=system_session(),
                           credentials=ctx.creds, lp=ctx.lp)
-    except Exception, estr:
-        raise CommandError("LDAP connection to %s failed - %s" % (ctx.server, estr))
+    except Exception, e:
+        raise CommandError("LDAP connection to %s failed" % ctx.server, e)
 
 
 def drs_errmsg(werr):
@@ -119,8 +119,8 @@ class cmd_drs_showrepl(Command):
         req1.info_type = info_type
         try:
             (info_type, info) = ctx.drsuapi.DsReplicaGetInfo(ctx.drsuapi_handle, 1, req1)
-        except Exception, estr:
-            raise CommandError("DsReplicaGetInfo failed : %s" % estr)
+        except Exception, e:
+            raise CommandError("DsReplicaGetInfo of type %u failed" % info_type, e)
         return (info_type, info)
 
 
@@ -221,8 +221,8 @@ class cmd_drs_kcc(Command):
         req1 = drsuapi.DsExecuteKCC1()
         try:
             self.drsuapi.DsExecuteKCC(self.drsuapi_handle, 1, req1)
-        except Exception, (ecode, estr):
-            raise CommandError("DsExecuteKCC failed - %s" % estr)
+        except Exception, e:
+            raise CommandError("DsExecuteKCC failed", e)
         print("Consistency check on %s successful." % DC)
 
 
@@ -289,8 +289,8 @@ class cmd_drs_replicate(Command):
 
         try:
             self.drsuapi.DsReplicaSync(self.drsuapi_handle, 1, req1)
-        except Exception, (ecode, estr):
-            raise CommandError("DsReplicaSync failed - %s" % estr)
+        except Exception, e:
+            raise CommandError("DsReplicaSync failed", estr)
        print("Replicate from %s to %s was successful." % (SOURCE_DC, DEST_DC))
 
 
index 90b7a5efaa0da0393e578f43ef8fa4f0e2b70db2..5e8748adc53a004eb58a2ea474185d40c0e2260c 100644 (file)
@@ -41,8 +41,8 @@ def samdb_connect(ctx):
         ctx.samdb = SamDB(url=ctx.url,
                           session_info=system_session(),
                           credentials=ctx.creds, lp=ctx.lp)
-    except Exception, estr:
-        raise CommandError("LDAP connection to %s failed - %s" % (ctx.url, estr))
+    except Exception, e:
+        raise CommandError("LDAP connection to %s failed " % ctx.url, e)
 
 
 def attr_default(msg, attrname, default):
@@ -114,9 +114,12 @@ class cmd_listall(Command):
             ("GPO_FLAG_USER_DISABLE", dsdb.GPO_FLAG_USER_DISABLE ),
             ( "GPO_FLAG_MACHINE_DISABLE", dsdb.GPO_FLAG_MACHINE_DISABLE ) ]
 
-        msg = self.samdb.search(base=policies_dn, scope=ldb.SCOPE_ONELEVEL,
-                                expression="(objectClass=groupPolicyContainer)",
-                                attrs=['nTSecurityDescriptor', 'versionNumber', 'flags', 'name', 'displayName', 'gPCFileSysPath'])
+        try:
+            msg = self.samdb.search(base=policies_dn, scope=ldb.SCOPE_ONELEVEL,
+                                    expression="(objectClass=groupPolicyContainer)",
+                                    attrs=['nTSecurityDescriptor', 'versionNumber', 'flags', 'name', 'displayName', 'gPCFileSysPath'])
+        except Exception, e:
+            raise CommandError("Failed to list policies in %s" % policies_dn, e)
         for m in msg:
             print("GPO          : %s" % m['name'][0])
             print("display name : %s" % m['displayName'][0])
@@ -158,15 +161,15 @@ class cmd_list(Command):
 
         try:
             user_dn = self.samdb.search(expression='(&(samAccountName=%s)(objectclass=User))' % username)[0].dn
-        except Exception, estr:
-            raise CommandError("Failed to find user %s - %s" % (username, estr))
+        except Exception, e:
+            raise CommandError("Failed to find user %s" % username, e)
 
         # check if its a computer account
         try:
             msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
             is_computer = 'computer' in msg['objectClass']
-        except Exception, estr:
-            raise CommandError("Failed to find objectClass for user %s - %s" % (username, estr))
+        except Exception, e:
+            raise CommandError("Failed to find objectClass for user %s" % username, e)
 
         print("TODO: get user token")
         # token = self.samdb.get_user_token(username)
index 3a467fb28ce9bc2c738a232a0c5ff5eb35d3c6a9..57f31cd511f3fbc24ea705aaa46aea9f7e26ea1a 100644 (file)
@@ -83,9 +83,8 @@ class cmd_group_add(Command):
                           credentials=creds, lp=lp)
             samdb.newgroup(groupname, groupou=groupou, grouptype = gtype,
                           description=description, mailaddress=mail_address, notes=notes)
-        except ldb.LdbError, (num, msg):
-            raise CommandError('Failed to create group "%s" : %s' % (
-                groupname, msg))
+        except Exception, e:
+            raise CommandError('Failed to create group "%s"' % groupname, e)
 
 
 class cmd_group_delete(Command):
@@ -114,9 +113,8 @@ class cmd_group_delete(Command):
             samdb = SamDB(url=H, session_info=system_session(),
                           credentials=creds, lp=lp)
             samdb.deletegroup(groupname)
-        except ldb.LdbError, (num, msg):
-            raise CommandError('Failed to remove group "%s": %s' % (
-                groupname , msg))
+        except Exception, e:
+            raise CommandError('Failed to remove group "%s"' % groupname, e)
 
 
 class cmd_group_add_members(Command):
@@ -146,9 +144,8 @@ class cmd_group_add_members(Command):
             samdb = SamDB(url=H, session_info=system_session(),
                           credentials=creds, lp=lp)
             samdb.add_remove_group_members(groupname, listofmembers, add_members_operation=True)
-        except ldb.LdbError, (num, msg):
-            raise CommandError('Failed to add members "%s" to group "%s": %s' % (
-                listofmembers, groupname , msg))
+        except Exception, e:
+            raise CommandError('Failed to add members "%s" to group "%s"' % (listofmembers, groupname), e)
 
 
 class cmd_group_remove_members(Command):
@@ -178,9 +175,8 @@ class cmd_group_remove_members(Command):
             samdb = SamDB(url=H, session_info=system_session(),
                           credentials=creds, lp=lp)
             samdb.add_remove_group_members(groupname, listofmembers, add_members_operation=False)
-        except ldb.LdbError, (num, msg):
-            raise CommandError('Failed to remove members "%s" from group "%s": %s' % (
-                listofmembers, groupname , msg))
+        except Exception, e:
+            raise CommandError('Failed to remove members "%s" from group "%s"' % (listofmembers, groupname), e)
 
 
 class cmd_group(SuperCommand):
index 693568dee275fae849338a3eb2d88d54775f7cf5..05c7bfc1bbf78cf008f643378dac1a99ec56f2da 100644 (file)
@@ -91,7 +91,6 @@ class cmd_newuser(Command):
                           jobtitle=job_title, department=department, company=company, description=description,
                           mailaddress=mail_address, internetaddress=internet_address,
                           telephonenumber=telephone_number, physicaldeliveryoffice=physical_delivery_office)
-        except ldb.LdbError, (num, msg):
-            raise CommandError('Failed to create user "%s" : %s' % (
-                username, msg))
+        except Exception, e:
+            raise CommandError('Failed to create user "%s"' % username, e)
 
index 83656587612c65d0109dffc39064cc74282fdf7c..49f8fbc77f0118f2dca7fd6b60ac243723e64a6b 100644 (file)
@@ -65,9 +65,8 @@ class cmd_acl_set(Command):
         try:
             ldb = Ldb(path, session_info=system_session(), credentials=creds,
                       lp=lp)
-        except:
-            # XXX: Should catch a particular exception type
-            raise CommandError("Unable to read domain SID from configuration files")
+        except Exception, e:
+            raise CommandError("Unable to read domain SID from configuration files", e)
         attrs = ["objectSid"]
         print lp.get("realm")
         res = ldb.search(expression="(objectClass=*)",
index 4a1645dd91bf88ee83903275a0b8ddfdeeabae3f..3f1a8e189d46b404dcfc2bbd188c3aa1c7cc55ed 100644 (file)
@@ -86,8 +86,8 @@ class cmd_pwsettings(Command):
             # ticks -> days
             cur_min_pwd_age = int(abs(int(res[0]["minPwdAge"][0])) / (1e7 * 60 * 60 * 24))
             cur_max_pwd_age = int(abs(int(res[0]["maxPwdAge"][0])) / (1e7 * 60 * 60 * 24))
-        except KeyError:
-            raise CommandError("Could not retrieve password properties!")
+        except Exception, e:
+            raise CommandError("Could not retrieve password properties!", e)
 
         if subcommand == "show":
             self.message("Password informations for domain '%s'" % domain_dn)
index 5f97c32b282cb01e339f657a01d61f1b7985e4ef..b1f9d66d1fe98897e05f3df6f35da8202ffd783f 100644 (file)
@@ -106,12 +106,8 @@ class cmd_rodc_preload(Command):
         try:
             repl.replicate(dn, source_dsa_invocation_id, destination_dsa_guid,
                            exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
-        except RuntimeError, (ecode, estring):
-            if estring == 'WERR_DS_DRA_ACCESS_DENIED':
-                local_samdb.transaction_cancel()
-                raise CommandError("Access denied replicating DN %s" % dn)
-            else:
-                raise
+        except Exception, e:
+            raise CommandError("Error replicating DN %s" % dn, e)
         local_samdb.transaction_commit()
 
 
index 047a95afae2413741286d3d893e4757b14151d85..b32b6518229d514126b7e6eca107469a5e70c819 100644 (file)
@@ -75,7 +75,6 @@ class cmd_setpassword(Command):
             samdb.setpassword(filter, password,
                               force_change_at_next_login=must_change_at_next_login,
                               username=username)
-        except ldb.LdbError, (num, msg):
-            raise CommandError('Failed to set password for user "%s" - %s' %
-                               (username, msg))
+        except Exception, e:
+            raise CommandError('Failed to set password for user "%s"' % username, e)
         print "Changed password OK"
index 0667a5199c0f3d07a41e5363ce33edc4d0d2bd7d..78365e98b85163b7446afe80be757295c8ef51e0 100644 (file)
@@ -51,7 +51,7 @@ def getntacl(lp, file, backend=None, eadbfile=None):
         try:
             attribute = samba.xattr_tdb.wrap_getxattr(eadbname, file, 
                 xattr.XATTR_NTACL_NAME)
-        except:
+        except Exception:
             # FIXME: Don't catch all exceptions, just those related to opening 
             # xattrdb
             print "Fail to open %s" % eadbname
@@ -75,7 +75,7 @@ def setntacl(lp, file, sddl, domsid, backend=None, eadbfile=None):
         try:
             samba.xattr_tdb.wrap_setxattr(eadbname,
                 file, xattr.XATTR_NTACL_NAME, ndr_pack(ntacl))
-        except:
+        except Exception:
             # FIXME: Don't catch all exceptions, just those related to opening 
             # xattrdb
             print "Fail to open %s" % eadbname
index 37d99a519d1ffebeec3abe31c45522eeebfebe36..e184ad83409d794c7621f4f08c7906c91006c6f8 100644 (file)
@@ -404,7 +404,7 @@ def setup_ldb(ldb, ldif_path, subst_vars):
     ldb.transaction_start()
     try:
         setup_add_ldif(ldb, ldif_path, subst_vars)
-    except:
+    except Exception:
         ldb.transaction_cancel()
         raise
     else:
@@ -728,7 +728,7 @@ def setup_samdb_partitions(samdb_path, setup_path, logger, lp, session_info,
 
         logger.info("Setting up sam.ldb rootDSE")
         setup_samdb_rootdse(samdb, setup_path, names)
-    except:
+    except Exception:
         samdb.transaction_cancel()
         raise
     else:
@@ -899,7 +899,7 @@ def setup_secretsdb(paths, setup_path, session_info, backend_credentials, lp):
                         })
 
         return secrets_ldb
-    except:
+    except Exception:
         secrets_ldb.transaction_cancel()
         raise
 
@@ -1200,7 +1200,7 @@ def setup_samdb(path, setup_path, session_info, provision_backend, lp, names,
                        {"SCHEMADN": names.schemadn})
 
         logger.info("Reopening sam.ldb with new schema")
-    except:
+    except Exception:
         samdb.transaction_cancel()
         raise
     else:
@@ -1302,7 +1302,7 @@ def setup_samdb(path, setup_path, session_info, provision_backend, lp, names,
             names.ntdsguid = samdb.searchone(basedn=ntds_dn,
                 attribute="objectGUID", expression="", scope=ldb.SCOPE_BASE)
             assert isinstance(names.ntdsguid, str)
-    except:
+    except Exception:
         samdb.transaction_cancel()
         raise
     else:
@@ -1369,7 +1369,7 @@ def setsysvolacl(samdb, netlogon, sysvol, gid, domainsid, dnsdomain, domaindn,
 
     try:
         os.chown(sysvol, -1, gid)
-    except:
+    except OSError:
         canchown = False
     else:
         canchown = True
@@ -1641,9 +1641,11 @@ def provision(setup_dir, logger, session_info, credentials, smbconf=None,
                     elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE,
                     name="msDS-SupportedEncryptionTypes")
                 samdb.modify(msg)
-            except ldb.LdbError, (ldb.ERR_NO_SUCH_ATTRIBUTE, _):
-                # It might be that this attribute does not exist in this schema
-                pass
+            except ldb.LdbError, (enum, estr):
+                if enum == ldb.ERR_NO_SUCH_ATTRIBUTE:
+                    # It might be that this attribute does not exist in this schema
+                    pass
+                raise
 
             if serverrole == "domain controller":
                 secretsdb_setup_dns(secrets_ldb, setup_path, names,
@@ -1694,7 +1696,7 @@ def provision(setup_dir, logger, session_info, credentials, smbconf=None,
 
         create_phpldapadmin_config(paths.phpldapadminconfig, setup_path,
                                    ldapi_url)
-    except:
+    except Exception:
         secrets_ldb.transaction_cancel()
         raise
 
index 43b1938a0ed92d2986da893c597f68702858bf05..67e77e303b3cbcf1cc5a9191ed3e92477b089cc8 100644 (file)
@@ -169,7 +169,7 @@ pwdLastSet: 0
                 raise Exception('Unable to find group "%s"' % groupname)
             assert(len(targetgroup) == 1)
             self.delete(targetgroup[0].dn)
-        except:
+        except Exception:
             self.transaction_cancel()
             raise
         else:
@@ -225,7 +225,7 @@ member: %s
             if modified is True:
                 self.modify_ldif(addtargettogroup)
 
-        except:
+        except Exception:
             self.transaction_cancel()
             raise
         else:
@@ -351,7 +351,7 @@ member: %s
             if setpassword:
                 self.setpassword("(samAccountName=%s)" % username, password,
                                  force_password_change_at_next_login_req)
-        except:
+        except Exception:
             self.transaction_cancel()
             raise
         else:
@@ -389,7 +389,7 @@ unicodePwd:: %s
 
             #  modify the userAccountControl to remove the disabled bit
             self.enable_account(search_filter)
-        except:
+        except Exception:
             self.transaction_cancel()
             raise
         else:
@@ -430,7 +430,7 @@ accountExpires: %u
 """ % (user_dn, userAccountControl, accountExpires)
 
             self.modify_ldif(setexp)
-        except:
+        except Exception:
             self.transaction_cancel()
             raise
         else:
index 0bc60fa3214f71c74486791222796ba9b68ff469..c82e70daf6a89559b084aa9a43ebe37d2c57dd5b 100644 (file)
@@ -136,7 +136,7 @@ dn: @INDEXLIST
             self.ldb.add_ldif(self.schema_dn_add)
             self.ldb.modify_ldif(self.schema_dn_modify)
             self.ldb.add_ldif(self.schema_data)
-        except:
+        except Exception:
             self.ldb.transaction_cancel()
             raise
         else:
index b6e7de8c8f8e5c627eaecb3a0608017b178cdf64..ded3ff13070f904722b4c6202494824ed5135f4c 100755 (executable)
@@ -91,22 +91,22 @@ class ProvisionLDB(object):
         ok = True
         try:
             self.sam.transaction_cancel()
-        except:
+        except Exception:
             ok = False
 
         try:
             self.secrets.transaction_cancel()
-        except:
+        except Exception:
             ok = False
 
         try:
             self.idmap.transaction_cancel()
-        except:
+        except Exception:
             ok = False
 
         try:
             self.privilege.transaction_cancel()
-        except:
+        except Exception:
             ok = False
 
         return ok
@@ -122,7 +122,7 @@ class ProvisionLDB(object):
             self.secrets.transaction_prepare_commit()
             self.idmap.transaction_prepare_commit()
             self.privilege.transaction_prepare_commit()
-        except:
+        except Exception:
             return self.groupedRollback()
 # TO BE DONE
 #        self.hkcr.transaction_prepare_commit()
@@ -134,7 +134,7 @@ class ProvisionLDB(object):
             self.secrets.transaction_commit()
             self.idmap.transaction_commit()
             self.privilege.transaction_commit()
-        except:
+        except Exception:
             return self.groupedRollback()
 
 # TO BE DONE
@@ -688,13 +688,13 @@ def update_gpo(paths, samdb, names, lp, message, force=0):
             try:
                 attribute = samba.xattr_tdb.wrap_getxattr(eadbname,
                                 paths.sysvol, xattr.XATTR_NTACL_NAME)
-            except:
+            except Exception:
                 attribute = samba.xattr_native.wrap_getxattr(paths.sysvol,
                                 xattr.XATTR_NTACL_NAME)
         else:
             attribute = samba.xattr_native.wrap_getxattr(paths.sysvol,
                                 xattr.XATTR_NTACL_NAME)
-    except:
+    except Exception:
        resetacls = True
 
     if force: