Skip to contentSkip to conversation

pynfs: fix nfs4.1/nfs4server.py

PATCH Superseded Jianhong Yin 1 participant 4 messages Mar 27

Subsystems (2)

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/4 pynfs: fix nfs4.1/nfs4server.py

From: Scott Mayhew <[email protected]>

---
 nfs4.1/config.py                 | 20 ++++-----
 nfs4.1/dataserver.py             | 30 ++++++-------
 nfs4.1/fs.py                     | 37 ++++++++--------
 nfs4.1/nfs4client.py             |  2 +-
 nfs4.1/nfs4server.py             | 73 ++++++++++++++++----------------
 nfs4.1/nfs4state.py              | 18 ++++----
 nfs4.1/sample_code/ds_exports.py |  2 +-
 nfs4.1/server_exports.py         | 12 +++---
 8 files changed, 93 insertions(+), 101 deletions(-)
nfs4.1/config.py +8 -12
index 3777e31..8691e1c 100644
@@ -117,8 +117,7 @@ class MetaConfig(type):
             setattr(cls, attr.name, property(make_get(i), make_set(i),
                                              None, attr.comment))
 
-class ServerConfig(object):
-    __metaclass__ = MetaConfig
+class ServerConfig(metaclass=MetaConfig):
     attrs =  [ConfigLine("allow_null_data", False,
                          "Server allows NULL calls to contain data"),
               ConfigLine("tag_info", True,
@@ -131,17 +130,16 @@ class ServerConfig(object):
 
     def __init__(self):
         self.minor_id = os.getpid()
-        self.major_id = "PyNFSv4.1"
+        self.major_id = b"PyNFSv4.1"
         self._owner = server_owner4(self.minor_id, self.major_id)
-        self.scope = "Default_Scope"
-        self.impl_domain = "citi.umich.edu"
-        self.impl_name = "pynfs X.X"
+        self.scope = b"Default_Scope"
+        self.impl_domain = b"citi.umich.edu"
+        self.impl_name = b"pynfs X.X"
         self.impl_date = 1172852767 # int(time.time())
         self.impl_id = nfs_impl_id4(self.impl_domain, self.impl_name,
                                  nfs4lib.get_nfstime(self.impl_date))
 
-class ServerPerClientConfig(object):
-    __metaclass__ = MetaConfig
+class ServerPerClientConfig(metaclass=MetaConfig):
     attrs = [ConfigLine("maxrequestsize", 16384,
                         "Maximum request size the server will accept"),
              ConfigLine("maxresponsesize", 16384,
@@ -175,15 +173,13 @@ _invalid_ops = [
     OP_RELEASE_LOCKOWNER, OP_ILLEGAL,
     ]
 
-class OpsConfigServer(object):
-    __metaclass__ = MetaConfig
+class OpsConfigServer(metaclass=MetaConfig):
     value = ['ERROR', 0, 0] # Note must have value == _opline(value)
     attrs = (lambda value=value: [ConfigLine(name.lower()[3:], value, "Generic comment", _opline)
                                   for name in nfs_opnum4.values()])()
 
 
-class Actions(object):
-    __metaclass__ = MetaConfig
+class Actions(metaclass=MetaConfig):
     attrs = [ConfigLine("reboot", 0,
                         "Any write here will simulate a server reboot",
                         _action),
nfs4.1/dataserver.py +15 -15
index f76ca5a..74ca864 100644
@@ -59,27 +59,27 @@ class DataServer(object):
 
     def get_netaddr4(self):
         # STUB server multipathing not supported yet
-        uaddr = '.'.join([self.server,
-                          str(self.port >> 8),
-                          str(self.port & 0xff)])
-        return type4.netaddr4(self.proto, uaddr)
+        uaddr = b'.'.join([self.server.encode("utf-8"),
+                          str(self.port >> 8).encode("utf-8"),
+                          str(self.port & 0xff).encode("utf-8")])
+        return type4.netaddr4(self.proto.encode("utf-8"), uaddr)
 
     def get_multipath_netaddr4s(self):
         netaddr4s = []
         for addr in self.multipath_servers:
             server, port = addr
-            uaddr = '.'.join([server,
-                            str(port >> 8),
-                            str(port & 0xff)])
-            proto = "tcp"
+            uaddr = b'.'.join([server.encode("utf-8"),
+                            str(port >> 8).encode("utf-8"),
+                            str(port & 0xff).encode("utf-8")])
+            proto = b"tcp"
             if server.find(':') >= 0:
-                proto = "tcp6"
+                proto = b"tcp6"
 
             netaddr4s.append(type4.netaddr4(proto, uaddr))
         return netaddr4s
 
     def fh_to_name(self, mds_fh):
-        return hashlib.sha1("%r" % mds_fh).hexdigest()
+        return hashlib.sha1(mds_fh).hexdigest()
 
     def connect(self):
         raise NotImplemented
@@ -122,7 +122,7 @@ class DataServer41(DataServer):
                                         summary=self.summary)
         self.c1.set_cred(self.cred1)
         self.c1.null()
-        c = self.c1.new_client("DS.init_%s" % self.server)
+        c = self.c1.new_client(b"DS.init_%s" % self.server.encode("utf-8"))
         # This is a hack to ensure MDS/DS communication path is at least
         # as wide as the client/MDS channel (at least for linux client)
         fore_attrs = type4.channel_attrs4(0, 16384, 16384, 2868, 8, 8, [])
@@ -154,11 +154,11 @@ class DataServer41(DataServer):
         access = const4.OPEN4_SHARE_ACCESS_BOTH
         deny = const4.OPEN4_SHARE_DENY_NONE
         attrs = {const4.FATTR4_MODE: 0o777}
-        owner = "mds"
+        owner = b"mds"
         mode = const4.GUARDED4
         verifier = self.sess.c.verifier
         openflag = type4.openflag4(const4.OPEN4_CREATE, type4.createhow4(mode, attrs, verifier))
-        name = self.fh_to_name(mds_fh)
+        name = self.fh_to_name(mds_fh).encode("utf-8")
         while True:
             if mds_fh in self.filehandles:
                 return
@@ -338,14 +338,14 @@ class DSDevice(object):
                 server_list = server_list[:-1]
                 try:
                     log.info("Adding dataserver ip:%s port:%s path:%s" %
-                             (server, port, '/'.join(path)))
+                             (server, port, b'/'.join(path)))
                     ds = DataServer41(server, port, path, mdsds=self.mdsds,
                                     multipath_servers=server_list,
                                     summary=server_obj.summary)
                     self.list.append(ds)
                 except socket.error:
                     log.critical("cannot access %s:%i/%s" %
-                                 (server, port, '/'.join(path)))
+                                 (server, port, b'/'.join(path)))
                     sys.exit(1)
         self.active = 1
         self.address_body = self._get_address_body()
nfs4.1/fs.py +17 -20
index 7f690bb..41149f1 100644
@@ -6,10 +6,7 @@ from nfs4lib import NFS4Error
 import struct
 import logging
 from locking import Lock, RWLock
-try:
-    import cStringIO.StringIO as StringIO
-except:
-    from io import StringIO
+from io import BytesIO
 import time
 from xdrdef.nfs4_pack import NFS4Packer
 
@@ -182,7 +179,7 @@ class FSObject(object):
 
     def init_file(self):
         """Hook for subclasses that want to use their own file class"""
-        return StringIO()
+        return BytesIO()
 
     def _init_hook(self):
         pass
@@ -671,7 +668,7 @@ class RootFS(FileSystem):
         self.fattr4_supported_attrs |= 1 << FATTR4_MAXWRITE
         self.fattr4_supported_attrs |= 1 << FATTR4_MAXREAD
         self.fsid = (0,0)
-        self.read_only = True
+        self.read_only = False
 
     def alloc_id(self):
         self._nextid += 1
@@ -711,7 +708,7 @@ class ConfigObj(FSObject):
         self._reset()
 
     def _reset(self):
-        self.file = StringIO()
+        self.file = BytesIO()
         self.file.write("# %s\n" % self.configline.comment)
         value = self.configline.value
         if type(value) is list:
@@ -931,7 +928,7 @@ import shutil
 import shelve
 
 class StubFS_Disk(FileSystem):
-    _fs_data_name = "fs_info" # DB name where we store persistent data
+    _fs_data_name = b"fs_info" # DB name where we store persistent data
     def __init__(self, path, reset=False, fsid=None):
         self._nextid = 0
         self.path = path
@@ -991,17 +988,17 @@ class StubFS_Disk(FileSystem):
         self.root = self.find(d["root"])
 
     def find_on_disk(self, id):
-        fd = open(os.path.join(self.path, "m_%i" % id), "r")
+        fd = open(os.path.join(self.path, b"m_%i" % id), "rb")
         # BUG - need to trap for file not found error
         meta = pickle.load(fd)
         fd.close()
         obj = self.objclass(self, id, meta)
         if obj.type == NF4REG:
-            fd = open(os.path.join(self.path, "d_%i" % id), "r")
-            obj.file = StringIO(fd.read())
+            fd = open(os.path.join(self.path, b"d_%i" % id), "rb")
+            obj.file = BytesIO(fd.read())
             fd.close()
         elif obj.type == NF4DIR:
-            fd = open(os.path.join(self.path, "d_%i" % id), "r")
+            fd = open(os.path.join(self.path, b"d_%i" % id), "rb")
             obj.entries = pickle.load(fd)
             fd.close()
         return obj
@@ -1018,10 +1015,10 @@ class StubFS_Disk(FileSystem):
             self._fs_data["_nextid"] = id
             self._fs_data.sync()
             # Create meta-data file
-            fd = open(os.path.join(self.path, "m_%i" % id), "w")
+            fd = open(os.path.join(self.path, b"m_%i" % id), "wb")
             fd.close()
             # Create data file
-            # fd = open(os.path.join(self.path, "d_%i" % id), "w")
+            # fd = open(os.path.join(self.path, b"d_%i" % id), "wb")
             # fd.close()
         finally:
             self._disk_lock.release()
@@ -1032,11 +1029,11 @@ class StubFS_Disk(FileSystem):
         self._disk_lock.acquire()
         try:
             # Remove meta-data file
-            meta = os.path.join(self.path, "m_%i" % id)
+            meta = os.path.join(self.path, b"m_%i" % id)
             if os.path.isfile(meta):
                 os.remove(meta)
             # Remove data file
-            data = os.path.join(self.path, "d_%i" % id)
+            data = os.path.join(self.path, b"d_%i" % id)
             if os.path.isfile(data):
                 os.remove(data)
         finally:
@@ -1049,20 +1046,20 @@ class StubFS_Disk(FileSystem):
         try:
             # Create meta-data file
             log_fs.debug("writing metadata for id=%i" % id)
-            fd = open(os.path.join(self.path, "m_%i" % id), "w")
+            fd = open(os.path.join(self.path, b"m_%i" % id), "wb")
             log_fs.debug("%r" % obj.meta.__dict__)
             pickle.dump(obj.meta, fd)
             fd.close()
             if obj.type == NF4REG:
                 # Create data file
-                fd = open(os.path.join(self.path, "d_%i" % id), "w")
+                fd = open(os.path.join(self.path, b"d_%i" % id), "wb")
                 obj.file.seek(0)
                 fd.write(obj.file.read())
                 fd.close()
             elif obj.type == NF4DIR:
                 # Create dir entries
                 log_fs.debug("writing dir %r" % obj.entries.keys())
-                fd = open(os.path.join(self.path, "d_%i" % id), "w")
+                fd = open(os.path.join(self.path, b"d_%i" % id), "wb")
                 pickle.dump(obj.entries, fd)
                 fd.close()
         finally:
@@ -1408,7 +1405,7 @@ class FSLayoutFSObj(FSObject):
     def init_file(self):
         self.stripe_size = NFL4_UFLG_STRIPE_UNIT_SIZE_MASK & 0x4000
         if self.fs.dsdevice.mdsds:
-            return StringIO()
+            return BytesIO()
         else:
             return FileLayoutFile(self)
 
nfs4.1/nfs4client.py +1 -1
index f4fabcc..073ea8b 100644
@@ -183,7 +183,7 @@ class NFS4Client(rpc.Client, rpc.Server):
                 return env
         try:
             self.check_utf8str_cs(args.tag)
-        except NFS4Errror as e:
+        except NFS4Error as e:
             env.results.set_empty_return(e.status, "Invalid utf8 tag")
             return env
         # Handle the individual operations
nfs4.1/nfs4server.py +36 -37

253 lines not on this page · raw message

nfs4.1/nfs4state.py +9 -9
index e57b90a..d675a6b 100644
@@ -215,10 +215,10 @@ class DictTree(object):
     def itervalues(self):
         def myiter(d, depth):
             if depth == 1:
-                for value in d.itervalues():
+                for value in d.values():
                     yield value
             else:
-                for sub_d in d.itervalues():
+                for sub_d in d.values():
                     for i in myiter(sub_d, depth - 1):
                         yield i
         for i in myiter(self._data, self._depth):
@@ -250,7 +250,7 @@ class FileStateTyped(object):
         # NOTE we are only using 9 bytes of 12
         # NOTE this needs to be client-wide, since keys of client.state[]
         # must be unique
-        return "%s%s" % (struct.pack("!xxxB", self.type),
+        return b"%s%s" % (struct.pack("!xxxB", self.type),
                          client.get_new_other())
 
     def grab_entry(self, key, klass):
@@ -290,13 +290,13 @@ class DelegState(FileStateTyped):
             return True
         # Find any delegation - use fact that all are of same type
         for e in self._tree.itervalues():
+            # The only thing that doesn't conflict is access==READ with READ deleg
+            if e.deleg_type == OPEN_DELEGATE_READ and \
+                    not (access & OPEN4_SHARE_ACCESS_WRITE):
+                return False
+            else:
+                return True
             break
-        # The only thing that doesn't conflict is access==READ with READ deleg
-        if e.deleg_type == OPEN_DELEGATE_READ and \
-                not (access & OPEN4_SHARE_ACCESS_WRITE):
-            return False
-        else:
-            return True
 
     def recall_conflicting_delegations(self, dispatcher, client, access, deny):
         # NOTE OK to have extra access/deny flags
nfs4.1/sample_code/ds_exports.py +1 -1
index 5d31148..1975e16 100644
@@ -6,4 +6,4 @@ from fs import StubFS_Mem
 
 def mount_stuff(server, opts):
     B = StubFS_Mem(2)
-    server.mount(B, path="/pynfs_mds")
+    server.mount(B, path=b"/pynfs_mds")
nfs4.1/server_exports.py +6 -6
index ef857ee..1271c4a 100644
@@ -4,22 +4,22 @@ from dataserver import DSDevice
 def mount_stuff(server, opts):
     """Mount some filesystems to the server"""
     # STUB - just testing stuff out
-    A = StubFS_Disk("/tmp/py41/fs1", opts.reset, 1)
+    A = StubFS_Disk(b"/tmp/py41/fs1", opts.reset, 1)
     B = StubFS_Mem(2)
     C = StubFS_Mem(3)
-    server.mount(A, path="/a")
-    server.mount(B, path="/b")
-    server.mount(C, path="/foo/bar/c")
+    server.mount(A, path=b"/a")
+    server.mount(B, path=b"/b")
+    server.mount(C, path=b"/foo/bar/c")
     if opts.use_block:
         dev = _create_simple_block_dev()
         E = BlockLayoutFS(5, backing_device=dev)
-        server.mount(E, path="/block")
+        server.mount(E, path=b"/block")
     if opts.use_files:
         dservers = _load_dataservers(opts.dataservers, server)
         if dservers is None:
             return
         F = FileLayoutFS(6, dservers)
-        server.mount(F, path="/files")
+        server.mount(F, path=b"/files")
 
 def _create_simple_block_dev():
     from block import Simple, Slice, Concat, Stripe, BlockVolume
Signature · 1 line
2.53.0
#1 lore raw

PATCH 2/4 pynfs: more nfs4.1/nfs4server.py fixes

From: Scott Mayhew <[email protected]>

---
 nfs4.1/dataserver.py |  2 +-
 nfs4.1/fs.py         | 17 +++++++++++++----
 nfs4.1/nfs4server.py | 12 ++++++++++--
 nfs4.1/nfs4state.py  | 28 ++++++++++++++--------------
 4 files changed, 38 insertions(+), 21 deletions(-)
nfs4.1/dataserver.py +1 -1
index 74ca864..4d3a305 100644
@@ -111,7 +111,7 @@ class DataServer41(DataServer):
                 self.reset()
             else:
                 log.error("Unhandled status %s from DS %s" %
-                          (nfsstat4[res.status], self.server))
+                          (const4.nfsstat4[res.status], self.server))
                 raise Exception("Dataserver communication error")
 
     def connect(self):
nfs4.1/fs.py +13 -4
index 41149f1..305326b 100644
@@ -14,6 +14,14 @@ log_o = logging.getLogger("fs.obj")
 log_fs = logging.getLogger("fs")
 logging.addLevelName(5, "FUNCT")
 
+def _hasattr(obj, attr):
+    try:
+        getattr(obj, attr)
+        return True
+    except:
+        pass
+    return False
+
 class MetaData(object):
     """Contains everything that needs to be stored
 
@@ -58,7 +66,7 @@ class FSObject(object):
     def _getsize_locked(self):
         # STUB
         if self.fattr4_type == NF4REG:
-            if hasattr(self.file, "__len__"):
+            if _hasattr(self.file, "__len__"):
                 return len(self.file)
             else:
                 orig = self.file.tell()
@@ -185,7 +193,7 @@ class FSObject(object):
         pass
 
     def __setattr__(self, name, value):
-        if name != "meta" and hasattr(self.meta, name):
+        if name != "meta" and _hasattr(self.meta, name):
             setattr(self.meta, name, value)
         else:
             object.__setattr__(self, name, value)
@@ -317,7 +325,8 @@ class FSObject(object):
                                     tag = "attr %i not writable" % attr)
                 name = "fattr4_%s" % nfs4lib.attr_name(attr)
                 # Note all writable attrs are object attrs
-                if hasattr(self, name):
+
+                if _hasattr(self, name):
                     base = self
                 else:
                     base = self.meta
@@ -961,7 +970,7 @@ class StubFS_Disk(FileSystem):
         d["root"] = self.root.id
         d["fsid"] = self.fsid
         for attr in dir(self):
-            if attr.startswith("fattr4_") and not hasattr(self.__class__, attr):
+            if attr.startswith("fattr4_") and not _hasattr(self.__class__, attr):
                 d[attr] = getattr(self, attr)
         d.sync()
 
nfs4.1/nfs4server.py +10 -2
index 47d6cba..6422008 100755
@@ -16,7 +16,7 @@ import random
 import struct
 import collections
 import logging
-from nfs4state import find_state
+from nfs4state import find_state, SHARE, BYTE
 from nfs4commoncode import CompoundState, encode_status, encode_status_by_name
 from fs import RootFS, ConfigFS
 from config import ServerConfig, ServerPerClientConfig, OpsConfigServer, Actions
@@ -27,6 +27,14 @@ log_41 = logging.getLogger("nfs.server")
 
 log_cfg = logging.getLogger("nfs.server.opconfig")
 
+def _hasattr(obj, attr):
+    try:
+        getattr(obj, attr)
+        return True
+    except:
+        pass
+    return False
+
 ##################################################
 # Set various global constants and magic numbers #
 ##################################################
@@ -1510,7 +1518,7 @@ class NFS4Server(rpc.Server):
             else:
                 base = obj
             name = "fattr4_%s" % nfs4lib.attr_name(attr)
-            if hasattr(base, name) and (obj.fs.fattr4_supported_attrs & 1<<attr): # STUB we should be able to remove hasattr
+            if _hasattr(base, name) and (obj.fs.fattr4_supported_attrs & 1<<attr): # STUB we should be able to remove hasattr
                 ret_dict[attr] = getattr(base, name)
             else:
                 if ignore:
nfs4.1/nfs4state.py +14 -14
index d675a6b..3ff6cdf 100644
@@ -21,7 +21,7 @@ POSIXLOCK = False
 SHARE, BYTE, DELEG, LAYOUT, ANON = range(5) # State types
 NORMAL, CB_INIT, CB_SENT, CB_RECEIVED, INVALID = range(5) # delegation/layout states
 
-DS_MAGIC = "\xa5" # STUB part of HACK code to ignore DS stateid
+DS_MAGIC = b"\xa5" # STUB part of HACK code to ignore DS stateid
 
 @contextmanager
 def find_state(env, stateid, allow_0=True, allow_bypass=False):
@@ -34,7 +34,7 @@ def find_state(env, stateid, allow_0=True, allow_bypass=False):
         # Could meddle with state.other here if needed
         anon = True
     # First we convert special stateids, see draft22 8.2.3
-    if stateid.other == "\0" * 12:
+    if stateid.other == b"\0" * 12:
         if allow_0 and stateid.seqid == 0:
             state = env.cfh.state.anon0
             anon = True
@@ -43,10 +43,10 @@ def find_state(env, stateid, allow_0=True, allow_bypass=False):
             # Special stateids must be passed in explicitly
             if stateid in [None, nfs4lib.state00, nfs4lib.state11]:
                 raise NFS4Error(NFS4ERR_BAD_STATEID,
-                                tag="Current stateid not useable")
+                                tag=b"Current stateid not useable")
         else:
             raise NFS4Error(NFS4ERR_BAD_STATEID)
-    elif stateid.other == "\xff" * 12:
+    elif stateid.other == b"\xff" * 12:
         if allow_0 and stateid.seqid == 0xffffffff:
             stateid = nfs4lib.state00 # Needed to pass seqid checks below
             state = (env.cfh.state.anon1 if allow_bypass else env.cfh.state.anon0)
@@ -57,31 +57,31 @@ def find_state(env, stateid, allow_0=True, allow_bypass=False):
         # Now map stateid to find state
         state = env.session.client.state.get(stateid.other, None)
         if state is None:
-            raise NFS4Error(NFS4ERR_BAD_STATEID, tag="stateid not known")
+            raise NFS4Error(NFS4ERR_BAD_STATEID, tag=b"stateid not known")
         if state.file != env.cfh:
             raise NFS4Error(NFS4ERR_BAD_STATEID,
-                            tag="cfh %r does not match stateid %r" %
+                            tag=b"cfh %r does not match stateid %r" %
                             (state.file.fh, env.cfh.fh))
     state.lock.acquire()
     # It is possible that while waiting to get the lock, the state has been
     # removed.  In that case, the removal sets the invalid flag.
     if state.invalid:
         state.release()
-        raise NFS4Error(NFS4ERR_BAD_STATEID, tag="stateid not known (race)")
+        raise NFS4Error(NFS4ERR_BAD_STATEID, tag=b"stateid not known (race)")
     if state.type != LAYOUT:
         # See draft22 8.2.2
         if stateid.seqid != 0 and stateid.seqid != state.seqid:
             old = (stateid.seqid < state.seqid)
             state.lock.release()
             if old:
-                raise NFS4Error(NFS4ERR_OLD_STATEID, tag="bad stateid.seqid")
+                raise NFS4Error(NFS4ERR_OLD_STATEID, tag=b"bad stateid.seqid")
             else:
-                raise NFS4Error(NFS4ERR_BAD_STATEID, tag="bad stateid.seqid")
+                raise NFS4Error(NFS4ERR_BAD_STATEID, tag=b"bad stateid.seqid")
     else:
         # See draft22 12.5.3
         if stateid.seqid == 0:
             state.lock.release()
-            raise NFS4Error(NFS4ERR_BAD_STATEID, tag="layout stateid.seqid==0")
+            raise NFS4Error(NFS4ERR_BAD_STATEID, tag=b"layout stateid.seqid==0")
     try:
         yield state
     finally:
@@ -342,8 +342,8 @@ class AnonState(FileStateTyped):
     def __init__(self, *args, **kwargs):
         kwargs["depth"] = 1 # key = (int,)
         FileStateTyped.__init__(self, *args, **kwargs)
-        self._tree[(0 ,)] = AnonEntry("\x00" * 12, self, (0,))
-        self._tree[(1 ,)] = AnonEntry("\xff" * 12, self, (1,))
+        self._tree[(0 ,)] = AnonEntry(b"\x00" * 12, self, (0,))
+        self._tree[(1 ,)] = AnonEntry(b"\xff" * 12, self, (1,))
         self._tree[(DS_MAGIC, )] = DSEntry(DS_MAGIC * 12, self, (DS_MAGIC, ))
 
 class ShareState(FileStateTyped):
@@ -686,9 +686,9 @@ class ShareEntry(StateTableEntry):
 #             # This test is the whole reason for the silly 3-bit
 #             # representation.  It basically prevents the seqence
 #             # OPEN(share=BOTH), OPENDOWNGRADE(share=SINGLE).
-#             raise NFS4Error(NFS4ERR_INVAL, tag="Failed history test")
+#             raise NFS4Error(NFS4ERR_INVAL, tag=b"Failed history test")
 #         if access == 0 and deny != 0:
-#             raise NFS4Error(NFS4ERR_INVAL, tag="access==0")
+#             raise NFS4Error(NFS4ERR_INVAL, tag=b"access==0")
 #         self.access_hist, self.deny_hist = new_access, new_deny
 #         self.share_access, self.share_deny = access, deny
 
Signature · 1 line
2.53.0
#2 lore raw

PATCH 3/4 pynfs: fix nfs4.1/nfs4server.py error with python3.12+

In reply to Jianhong Yin

force use gdbm as the backend of shelve module, to avoid error:
'''
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. '''

test pass on RHEL-9 RHEL-10 and Fedora-43

---
 nfs4.1/fs.py | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)
nfs4.1/fs.py +16 -4
index 305326b..c5b1d2d 100644
@@ -932,9 +932,11 @@ class ConfigFS(FileSystem):
 ###################################################
 
 import os
+import sys
 import pickle
 import shutil
 import shelve
+import dbm.gnu as gdbm
 
 class StubFS_Disk(FileSystem):
     _fs_data_name = b"fs_info" # DB name where we store persistent data
@@ -948,6 +950,16 @@ class StubFS_Disk(FileSystem):
             self._init(path)
         # XXX Note shelve DB is still open
 
+    def _dbpath(self, path):
+        """
+        generate proper dbpath format according python version.
+        see: https://docs.python.org/3.13/library/dbm.html#module-dbm.gnu
+        """
+        dbpath = os.path.join(path, self._fs_data_name)
+        if sys.version_info < (3, 11):
+            dbpath = dbpath.decode("utf-8")
+        return dbpath
+
     def _reset(self, path, fsid):
         """Create an empty fs, overwriting all existing data."""
         # Check path exists
@@ -959,8 +971,8 @@ class StubFS_Disk(FileSystem):
         shutil.rmtree(path)
         os.makedirs(path)
         # This needs to be open before calling __init__
-        d = self._fs_data = shelve.open(os.path.join(path, self._fs_data_name),
-                                        "n")
+        db = gdbm.open(self._dbpath(path), "n")
+        d = self._fs_data = shelve.Shelf(db)
         d["_nextid"] = self._nextid
         # normal __init__
         FileSystem.__init__(self)
@@ -980,8 +992,8 @@ class StubFS_Disk(FileSystem):
         if not os.path.isdir(path):
             raise RuntimeError("Path doesn't exist, try using '--reset' option")
         # Ensure persistent fs data exists there
-        d = self._fs_data = shelve.open(os.path.join(path, self._fs_data_name),
-                                        "w") # w needed for later allocation
+        db = gdbm.open(self._dbpath(path), "w") # w needed for later allocation
+        d = self._fs_data = shelve.Shelf(db)
         # Do __init__ portion that is needed
         self.objclass = FSObject
         self._disk_lock = Lock("FSLock(Disk)")
Signature · 1 line
2.53.0
#3 lore raw

PATCH 4/4 pynfs: fix various types of errors in nfs4.1/nfs4proxy.py

In reply to Jianhong Yin

test pass on Fedora-43

---
 nfs4.1/nfs4proxy.py | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)
nfs4.1/nfs4proxy.py +8 -8
index 1b935fa..8cc4002 100755
@@ -46,7 +46,7 @@ class NFS4Proxy(rpc.Server):
             self.cb_versions = [cb_version]
             # currently support only root (? fix ? )
             rpcsec = rpc.security.instance(rpc.AUTH_SYS)
-            self.default_cred = rpcsec.init_cred(uid=0,gid=0,name="root")
+            self.default_cred = rpcsec.init_cred(uid=0,gid=0,name=b"root")
             if pipe: #reuse connection
                 self.pipe = pipe
             else:
@@ -60,7 +60,7 @@ class NFS4Proxy(rpc.Server):
             return (min(self.cb_versions), max(self.cb_versions))
 
         def _find_method(self, msg):
-            method = getattr(self.proxy, 'handle_cb_%i' % msg.proc, None)
+            method = getattr(self.proxy, b'handle_cb_%i' % msg.proc, None)
             if method is not None:
                 return method
             return None
@@ -162,8 +162,8 @@ class NFS4Proxy(rpc.Server):
             log.debug("** CALLBACK **")
         log.debug("Handling NULL")
         try:
-            self.forward_call(calldata="", callback=callback, procedure=0)
-            return rpc.SUCCESS, ''
+            self.forward_call(calldata=b"", callback=callback, procedure=0)
+            return rpc.SUCCESS, b''
         except rpc.RPCTimeout:
             log.critical("Error: cannot connect to destination server")
             return rpc.GARBAGE_ARGS, None
@@ -192,7 +192,7 @@ class NFS4Proxy(rpc.Server):
             env = CompoundState(args, cred)
         for arg in args.argarray:
             env.index += 1
-            opname = nfs_opnum4.get(arg.argop, 'op_illegal')
+            opname = nfs_opnum4.get(arg.argop, b'op_illegal')
             log.info("*** %s (%d) ***" % (opname, arg.argop))
             # look for functions implemented by the proxy
             # that override communication
@@ -210,7 +210,7 @@ class NFS4Proxy(rpc.Server):
             if error is not None:
                 result = encode_status_by_name(opname.lower()[3:],
                                             int(error),
-                                            msg="Proxy Rewrite Error")
+                                            msg=b"Proxy Rewrite Error")
                 env.results.append(result)
                 p = nfs4lib.FancyNFS4Packer()
                 if callback:
@@ -288,7 +288,7 @@ class NFS4Proxy(rpc.Server):
                     attrs.ca_maxoperations = chan.maxoperations
                 if chan.maxrequests < attrs.ca_maxrequests:
                     attrs.ca_maxrequests = chan.maxrequests
-            if direction is 0: # client to proxy
+            if direction == 0: # client to proxy
                 # XXX: this might be buggy with more than one clients (?)
                 self.start_cb_proxy(arg.opcreate_session.csa_cb_program,
                                     version=1, client_pipe=cred.connection)
@@ -296,7 +296,7 @@ class NFS4Proxy(rpc.Server):
                                        self.fchannel)
                 _adjust_channel_values(arg.opcreate_session.csa_back_chan_attrs,
                                        self.bchannel)
-            elif direction is 1: # proxy to client
+            elif direction == 1: # proxy to client
                 pass
 #FUNCTION OVERRIDING END
 
Signature · 1 line
2.53.0