]> git.apps.os.sepia.ceph.com Git - ceph.git/commitdiff
rgw/lua: allow read access to object data 46550/head
authorYuval Lifshitz <ylifshit@redhat.com>
Tue, 7 Jun 2022 11:27:53 +0000 (14:27 +0300)
committeryuval Lifshitz <ylifshit@redhat.com>
Thu, 4 Aug 2022 16:22:13 +0000 (19:22 +0300)
Signed-off-by: Yuval Lifshitz <ylifshit@redhat.com>
19 files changed:
doc/radosgw/lua-scripting.rst
src/rgw/CMakeLists.txt
src/rgw/rgw_admin.cc
src/rgw/rgw_common.h
src/rgw/rgw_lua.cc
src/rgw/rgw_lua.h
src/rgw/rgw_lua_background.cc
src/rgw/rgw_lua_background.h
src/rgw/rgw_lua_data_filter.cc [new file with mode: 0644]
src/rgw/rgw_lua_data_filter.h [new file with mode: 0644]
src/rgw/rgw_lua_request.cc
src/rgw/rgw_lua_request.h
src/rgw/rgw_lua_utils.cc
src/rgw/rgw_lua_utils.h
src/rgw/rgw_op.cc
src/rgw/rgw_op.h
src/rgw/rgw_process.cc
src/test/cli/radosgw-admin/help.t
src/test/rgw/test_rgw_lua.cc

index 750a91397ac25d4b5c6b70c805f7f217964de0c8..9f42f20c18fcac905047aa46d0083e6033a9534d 100644 (file)
@@ -6,18 +6,26 @@ Lua Scripting
 
 .. contents::
 
-This feature allows users to assign execution context to Lua scripts. The three supported contexts are ``preRequest``" which will execute a script before each
-operation is performed, ``postRequest`` which will execute after each operation is performed, and ``background`` which will execute within a specified time interval.
-A request context script may be constrained to operations belonging to a specific tenant's users.
-The request context script can also access fields in the request and modify some fields. All Lua language features can be used.
+This feature allows users to assign execution context to Lua scripts. The supported contexts are:
 
-By default, all lua standard libraries are available in the script, however, in order to allow for other lua modules to be used in the script, we support adding packages to an allowlist:
+ - ``prerequest`` which will execute a script before each operation is performed
+ - ``postrequest`` which will execute after each operation is performed
+ - ``background`` which will execute within a specified time interval
+ - ``getdata`` which will execute on objects' data when objects are downloaded
+ - ``putdata`` which will execute on objects' data when objects are uploaded
+
+A request (pre or post) or data (get or put) context script may be constrained to operations belonging to a specific tenant's users.
+The request context script can also access fields in the request and modify certain fields, as well as the `Global RGW Table`_.
+The data context script can access the content of the object as well as the request fields and the `Global RGW Table`_. 
+All Lua language features can be used in all contexts.
+
+By default, all Lua standard libraries are available in the script, however, in order to allow for other Lua modules to be used in the script, we support adding packages to an allowlist:
 
   - All packages in the allowlist are being re-installed using the luarocks package manager on radosgw restart. Therefore a restart is needed for adding or removing of packages to take effect 
-  - To add a package that contains C source code that needs to be compiled, use the `--allow-compilation` flag. In this case a C compiler needs to be available on the host
-  - Lua packages are installed in, and used from, a directory local to the radosgw. Meaning that lua packages in the allowlist are separated from any lua packages available on the host.
-    By default, this directory would be `/tmp/luarocks/<entity name>`. Its prefix part (`/tmp/luarocks/`) could be set to a different location via the `rgw_luarocks_location` configuration parameter. 
-    Note that this parameter should not be set to one of the default locations where luarocks install packages (e.g. `$HOME/.luarocks`, `/usr/lib64/lua`, `/usr/share/lua`)
+  - To add a package that contains C source code that needs to be compiled, use the ``--allow-compilation`` flag. In this case a C compiler needs to be available on the host
+  - Lua packages are installed in, and used from, a directory local to the radosgw. Meaning that Lua packages in the allowlist are separated from any Lua packages available on the host.
+    By default, this directory would be ``/tmp/luarocks/<entity name>``. Its prefix part (``/tmp/luarocks/``) could be set to a different location via the ``rgw_luarocks_location`` configuration parameter. 
+    Note that this parameter should not be set to one of the default locations where luarocks install packages (e.g. ``$HOME/.luarocks``, ``/usr/lib64/lua``, ``/usr/share/lua``).
        
 
 .. toctree::
@@ -32,7 +40,7 @@ To upload a script:
 
 ::
    
-   # radosgw-admin script put --infile={lua-file} --context={preRequest|postRequest|background} [--tenant={tenant-name}]
+   # radosgw-admin script put --infile={lua-file} --context={prerequest|postrequest|background|getdata|putdata} [--tenant={tenant-name}]
 
 
 * When uploading a script with the ``background`` context, a tenant name may not be specified.
@@ -42,14 +50,14 @@ To print the content of the script to standard output:
 
 ::
    
-   # radosgw-admin script get --context={preRequest|postRequest|background} [--tenant={tenant-name}]
+   # radosgw-admin script get --context={prerequest|postrequest|background|getdata|putdata} [--tenant={tenant-name}]
 
 
 To remove the script:
 
 ::
    
-   # radosgw-admin script rm --context={preRequest|postRequest|background} [--tenant={tenant-name}]
+   # radosgw-admin script rm --context={prerequest|postrequest|background|getdata|putdata} [--tenant={tenant-name}]
 
 
 Package Management via CLI
@@ -149,7 +157,7 @@ Request Fields
 +----------------------------------------------------+----------+--------------------------------------------------------------+----------+-----------+----------+
 | ``Request.Bucket.Tenant``                          | string   | tenant of the bucket                                         | no       | no        | yes      |
 +----------------------------------------------------+----------+--------------------------------------------------------------+----------+-----------+----------+
-| ``Request.Bucket.Name``                            | string   | bucket name (writeable only in `preRequest` context)         | no       | yes       | no       |
+| ``Request.Bucket.Name``                            | string   | bucket name (writeable only in ``prerequest`` context)       | no       | yes       | no       |
 +----------------------------------------------------+----------+--------------------------------------------------------------+----------+-----------+----------+
 | ``Request.Bucket.Marker``                          | string   | bucket marker (initial id)                                   | no       | no        | yes      |
 +----------------------------------------------------+----------+--------------------------------------------------------------+----------+-----------+----------+
@@ -306,12 +314,32 @@ Operations Log
 ~~~~~~~~~~~~~~
 The ``Request.Log()`` function prints the requests into the operations log. This function has no parameters. It returns 0 for success and an error code if it fails.
 
+Tracing
+~~~~~~~
+Tracing functions can be used only in the ``postrequest`` context.
+
+- ``Request.Trace.SetAttribute(<key>, <value>)`` - sets the attribute for the request's trace.
+  The function takes two arguments: the first is the ``key``, which should be a string, and the second is the ``value``, which can either be a string or a number (integer or double).
+  You may then locate specific traces by using this attribute.
+
+- ``Request.Trace.AddEvent(<name>, <attributes>)`` - adds an event to the first span of the request's trace
+  An event is defined by event name, event time, and zero or more event attributes.
+  The function accepts one or two arguments: A string containing the event ``name`` should be the first argument, followed by the event ``attributes``, which is optional for events without attributes.
+  An event's attributes must be a table of strings.
+
 Background Context
 --------------------
 The ``background`` context may be used for purposes that include analytics, monitoring, caching data for other context executions.
 - Background script execution default interval is 5 seconds.
 
-Global ``RGW`` Table
+Data Context
+--------------------
+Both ``getdata`` and ``putdata`` contexts have the following fields:
+- ``Data`` which is read-only and iterable (byte by byte). In case that an object is uploaded or retrieved in multiple chunks, the ``Data`` field will hold data of one chunk at a time.
+- ``Offset`` which is holding the offset of the chunk within the entire object.
+- The ``Request`` fields and the background ``RGW`` table are also available in these contexts.
+
+Global RGW Table
 --------------------
 The ``RGW`` Lua table is accessible from all contexts and saves data written to it
 during execution so that it may be read and used later during other executions, from the same context of a different one.
@@ -330,19 +358,6 @@ to atomically increment and decrement numeric values in it. For that the followi
 - if we try to increment or decrement by non-numeric values, the execution of the script would fail
 
 
-Tracing
-~~~~~~~
-Tracing functions can be used only in `postRequest` context.
-
-- ``Request.Trace.SetAttribute()`` - sets the attribute for the request's trace.
-  Takes two arguments. The first is the `key`, which should be a string. The second is the value, which can either be a string or a number.
-  Using the attribute, you can locate specific traces.
-
-- ``Request.Trace.AddEvent()`` - adds an event to the first span of the request's trace
-  An event is defined by event name, event time, and zero or more event attributes.
-  Therefore, the function accepts one or two arguments. A string containing the event name should be the first argument, followed by the event attributes, which is optional for events without attributes.
-  An event's attributes must be a table of strings.
-
 Lua Code Samples
 ----------------
 - Print information on source and destination objects in case of copy:
@@ -419,7 +434,7 @@ Lua Code Samples
 
 - Add metadata to objects that was not originally sent by the client:
 
-In the `preRequest` context we should add:
+In the ``prerequest`` context we should add:
 
 .. code-block:: lua
 
@@ -427,7 +442,7 @@ In the `preRequest` context we should add:
     Request.HTTP.Metadata["x-amz-meta-mydata"] = "my value"
   end
 
-In the `postRequest` context we look at the metadata:
+In the ``postrequest`` context we look at the metadata:
 
 .. code-block:: lua
 
@@ -446,7 +461,7 @@ First we should add the following packages to the allowlist:
   # radosgw-admin script-package add --package=luasocket --allow-compilation
 
 
-Then, do a restart for the radosgw and upload the following script to the `postRequest` context:
+Then, do a restart for the radosgw and upload the following script to the ``postrequest`` context:
 
 .. code-block:: lua
 
@@ -483,7 +498,7 @@ Tracing is disabled by default, so we should enable tracing for this specific bu
 
 
 If `tracing is enabled <https://docs.ceph.com/en/latest/jaegertracing/#how-to-enable-tracing-in-ceph/>`_ on the RGW, the value of Request.Trace.Enable is true, so we should disable tracing for all other requests that do not match the bucket name.
-In the `preRequest` context:
+In the ``prerequest`` context:
 
 .. code-block:: lua
 
@@ -491,12 +506,12 @@ In the `preRequest` context:
       Request.Trace.Enable = false
   end
 
-Note that changing `Request.Trace.Enable` does not change the tracer's state, but disables or enables the tracing for the request only.
+Note that changing ``Request.Trace.Enable`` does not change the tracer's state, but disables or enables the tracing for the request only.
 
 
 - Add Information for requests traces
 
-in `postRequest` context, we can add attributes and events to the request's trace.
+in ``postrequest`` context, we can add attributes and events to the request's trace.
 
 .. code-block:: lua
 
@@ -511,3 +526,40 @@ in `postRequest` context, we can add attributes and events to the request's trac
 
   Request.Trace.AddEvent("second event", event_attrs)
 
+- The entropy value of an object could be used to detect whether the object is encrypted. 
+  The following script calculates the entropy and size of uploaded objects and print to debug log
+
+in the ``putdata`` context, add the following script
+
+.. code-block:: lua
+
+       function object_entropy()
+               local byte_hist = {}
+               local byte_hist_size = 256 
+               for i = 1,byte_hist_size do
+                       byte_hist[i] = 0 
+               end 
+               local total = 0 
+
+               for i, c in pairs(Data)  do
+                       local byte = c:byte() + 1 
+                       byte_hist[byte] = byte_hist[byte] + 1 
+                       total = total + 1 
+               end 
+
+               entropy = 0 
+
+               for _, count in ipairs(byte_hist) do
+                       if count ~= 0 then
+                               local p = 1.0 * count / total
+                               entropy = entropy - (p * math.log(p)/math.log(byte_hist_size))
+                       end 
+               end 
+
+               return entropy
+       end
+
+       local full_name = Request.Bucket.Name.."\\"..Request.Object.Name
+       RGWDebugLog("entropy of chunk of: " .. full_name .. " at offset:" .. tostring(Offset)  ..  " is: " .. tostring(object_entropy()))
+       RGWDebugLog("payload size of chunk of: " .. full_name .. " is: " .. #Data)
+
index a127b54a622395ea1b8b46a721d4de7c61853a63..ed483cd481f235f1bb8738229b81a6afcc0e116b 100644 (file)
@@ -161,8 +161,11 @@ set(librgw_common_srcs
   rgw_datalog.cc
   rgw_datalog_notify.cc
   cls_fifo_legacy.cc
+  rgw_log.cc
+  rgw_lua_request.cc
   rgw_lua_utils.cc
   rgw_lua.cc
+  rgw_lua_data_filter.cc
   rgw_bucket_encryption.cc
   rgw_tracer.cc
   rgw_lua_background.cc)
@@ -276,8 +279,6 @@ set(rgw_a_srcs
   rgw_frontend.cc
   rgw_http_client_curl.cc
   rgw_loadgen.cc
-  rgw_log.cc
-  rgw_lua_request.cc
   rgw_period_pusher.cc
   rgw_realm_reloader.cc
   rgw_realm_watcher.cc
index c726fa1b41e94b7463399e308149d0c279598305..1ed453b500b108f78082c5268c93c2af5dad0b35 100644 (file)
@@ -121,6 +121,9 @@ static inline int posix_errortrans(int r)
   return r;
 }
 
+
+static const std::string LUA_CONTEXT_LIST("prerequest, postrequest, background, getdata, putdata");
+
 void usage()
 {
   cout << "usage: radosgw-admin <cmd> [options...]" << std::endl;
@@ -478,7 +481,7 @@ void usage()
   cout << "   --subscription            pubsub subscription name\n";
   cout << "   --event-id                event id in a pubsub subscription\n";
   cout << "\nScript options:\n";
-  cout << "   --context                 context in which the script runs. one of: preRequest, postRequest, background\n";
+  cout << "   --context                 context in which the script runs. one of: "+LUA_CONTEXT_LIST+"\n";
   cout << "   --package                 name of the lua package that should be added/removed to/from the allowlist\n";
   cout << "   --allow-compilation       package is allowed to compile C code as part of its installation\n";
   cout << "\nradoslist options:\n";
@@ -10378,7 +10381,7 @@ next:
     }
     const rgw::lua::context script_ctx = rgw::lua::to_context(*str_script_ctx);
     if (script_ctx == rgw::lua::context::none) {
-      cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: preRequest, postRequest, background" << std::endl;
+      cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: " << LUA_CONTEXT_LIST << std::endl;
       return EINVAL;
     }
     if (script_ctx == rgw::lua::context::background && !tenant.empty()) {
@@ -10399,7 +10402,7 @@ next:
     }
     const rgw::lua::context script_ctx = rgw::lua::to_context(*str_script_ctx);
     if (script_ctx == rgw::lua::context::none) {
-      cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: preRequest, postRequest, background" << std::endl;
+      cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: " << LUA_CONTEXT_LIST << std::endl;
       return EINVAL;
     }
     std::string script;
@@ -10422,7 +10425,7 @@ next:
     }
     const rgw::lua::context script_ctx = rgw::lua::to_context(*str_script_ctx);
     if (script_ctx == rgw::lua::context::none) {
-      cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: preRequest, postRequest, background" << std::endl;
+      cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: " << LUA_CONTEXT_LIST << std::endl;
       return EINVAL;
     }
     const auto rc = rgw::lua::delete_script(dpp(), store, tenant, null_yield, script_ctx);
index 4bc18b2413630dbb9aa9d5d1ba446acf63eb6c77..c146a531a44f1077dbae4a5b7bd31674d1f3d85e 100644 (file)
@@ -51,6 +51,10 @@ namespace rgw::sal {
   using Attrs = std::map<std::string, ceph::buffer::list>;
 }
 
+namespace rgw::lua {
+  class Background;
+}
+
 using ceph::crypto::MD5;
 
 #define RGW_ATTR_PREFIX  "user.rgw."
@@ -1696,6 +1700,8 @@ struct req_state : DoutPrefixProvider {
   //Principal tags that come in as part of AssumeRoleWithWebIdentity
   std::vector<std::pair<std::string, std::string>> principal_tags;
 
+  rgw::lua::Background* lua_background = nullptr;
+
   req_state(CephContext* _cct, RGWEnv* e, uint64_t id);
   ~req_state();
 
index 323cc5ed0f62deecad445f4844198f2941f1f8f6..39846715284374e052a31a521f2cbc5a2a9c5aa7 100644 (file)
@@ -26,6 +26,12 @@ context to_context(const std::string& s)
   if (strcasecmp(s.c_str(), "background") == 0) {
     return context::background;
   }
+  if (strcasecmp(s.c_str(), "getdata") == 0) {
+    return context::getData;
+  }
+  if (strcasecmp(s.c_str(), "putdata") == 0) {
+    return context::putData;
+  }
   return context::none;
 }
 
@@ -38,6 +44,10 @@ std::string to_string(context ctx)
       return "postrequest";
     case context::background:
       return "background";
+    case context::getData:
+      return "getdata";
+    case context::putData:
+      return "putdata";
     case context::none:
       break;
   }
index 1eb14c605ffd44c8940a6ed3fb294b1c02c02cb6..ecc583bd41ba7ab36acce386eb9c6cb8d8281401 100644 (file)
@@ -4,6 +4,7 @@
 #include "common/async/yield_context.h"
 #include "rgw_sal_fwd.h"
 
+class DoutPrefixProvider;
 class lua_State;
 class rgw_user;
 namespace rgw::sal {
@@ -16,6 +17,8 @@ enum class context {
   preRequest,
   postRequest,
   background,
+  getData,
+  putData,
   none
 };
 
index ea85193edf7c4a7a66a6857fc93ae3b8a11a71f7..bfd6d6d59ef743b9d9359548814f335920248080 100644 (file)
@@ -176,5 +176,5 @@ void Background::create_background_metatable(lua_State* L) {
   create_metatable<rgw::lua::RGWTable>(L, true, &rgw_map, &table_mutex);
 }
 
-} //namespace lua
+} //namespace rgw::lua
 
index c6051164eb4212536a3d0d945670a46ccbd46829..1940d7f80488770ba34d7580b461f8745da1e604 100644 (file)
@@ -226,5 +226,5 @@ public:
     void resume(rgw::sal::Store* _store) override;
 };
 
-} //namepsace lua
+} //namepsace rgw::lua
 
diff --git a/src/rgw/rgw_lua_data_filter.cc b/src/rgw/rgw_lua_data_filter.cc
new file mode 100644 (file)
index 0000000..45cb877
--- /dev/null
@@ -0,0 +1,142 @@
+#include "rgw_lua_data_filter.h"
+#include "rgw_lua_utils.h"
+#include "rgw_lua_request.h"
+#include "rgw_lua_background.h"
+#include <lua.hpp>
+
+namespace rgw::lua {
+
+void push_bufferlist_byte(lua_State* L, bufferlist::iterator& it) {
+    char byte[1];
+    it.copy(1, byte);
+    lua_pushlstring(L, byte, 1);
+}
+
+struct BufferlistMetaTable : public EmptyMetaTable {
+
+  static std::string TableName() {return "Data";}
+  static std::string Name() {return TableName() + "Meta";}
+  
+  static int IndexClosure(lua_State* L) {
+    auto bl = reinterpret_cast<bufferlist*>(lua_touserdata(L, lua_upvalueindex(1)));
+    const auto index = luaL_checkinteger(L, 2);
+    if (index <= 0 || index > bl->length()) {
+      // lua arrays start from 1
+      lua_pushnil(L);
+      return ONE_RETURNVAL;
+    }
+    auto it = bl->begin(index-1);
+    if (it != bl->end()) {
+      push_bufferlist_byte(L, it);
+    } else {
+      lua_pushnil(L);
+    }
+    
+    return ONE_RETURNVAL;
+  }
+
+  static int PairsClosure(lua_State* L) {
+    auto bl = reinterpret_cast<bufferlist*>(lua_touserdata(L, lua_upvalueindex(1)));
+    ceph_assert(bl);
+    lua_pushlightuserdata(L, bl);
+    lua_pushcclosure(L, stateless_iter, ONE_UPVAL); // push the stateless iterator function
+    lua_pushnil(L);                                 // indicate this is the first call
+    // return stateless_iter, nil
+
+    return TWO_RETURNVALS;
+  }
+  
+  static int stateless_iter(lua_State* L) {
+    // based on: http://lua-users.org/wiki/GeneralizedPairsAndIpairs
+    auto bl = reinterpret_cast<bufferlist*>(lua_touserdata(L, lua_upvalueindex(1)));
+    lua_Integer index;
+    if (lua_isnil(L, -1)) {
+      index = 1;
+    } else {
+      index = luaL_checkinteger(L, -1) + 1;
+    }
+
+    // lua arrays start from 1
+    auto it = bl->begin(index-1);
+
+    if (index > bl->length()) {
+      // index of the last element was provided
+      lua_pushnil(L);
+      lua_pushnil(L);
+      // return nil, nil
+    } else {
+      lua_pushinteger(L, index);
+      push_bufferlist_byte(L, it);
+      // return key, value
+    }
+
+    return TWO_RETURNVALS;
+  }
+  
+  static int LenClosure(lua_State* L) {
+    const auto bl = reinterpret_cast<bufferlist*>(lua_touserdata(L, lua_upvalueindex(1)));
+
+    lua_pushinteger(L, bl->length());
+
+    return ONE_RETURNVAL;
+  }
+};
+
+int RGWObjFilter::execute(bufferlist& bl, off_t offset, const char* op_name) const {
+  auto L = luaL_newstate();
+  lua_state_guard lguard(L);
+
+  open_standard_libs(L);
+
+  create_debug_action(L, s->cct);  
+
+  // create the "Data" table
+  create_metatable<BufferlistMetaTable>(L, true, &bl);
+  lua_getglobal(L, BufferlistMetaTable::TableName().c_str());
+  ceph_assert(lua_istable(L, -1));
+
+  // create the "Request" table
+  request::create_top_metatable(L, s, op_name);
+
+  // create the "Offset" variable
+  lua_pushinteger(L, offset);
+  lua_setglobal(L, "Offset");
+
+  if (s->lua_background) {
+    // create the "RGW" table
+    s->lua_background->create_background_metatable(L);
+    lua_getglobal(L, rgw::lua::RGWTable::TableName().c_str());
+    ceph_assert(lua_istable(L, -1));
+  }
+
+  try {
+    // execute the lua script
+    if (luaL_dostring(L, script.c_str()) != LUA_OK) {
+      const std::string err(lua_tostring(L, -1));
+      ldpp_dout(s, 1) << "Lua ERROR: " << err << dendl;
+      return -EINVAL;
+    }
+  } catch (const std::runtime_error& e) {
+    ldpp_dout(s, 1) << "Lua ERROR: " << e.what() << dendl;
+    return -EINVAL;
+  }
+
+  return 0;
+}
+
+int RGWGetObjFilter::handle_data(bufferlist& bl,
+                  off_t bl_ofs,
+                  off_t bl_len) {
+  filter.execute(bl, bl_ofs, "get_obj");
+  // return value is ignored since we don't want to fail execution if lua script fails
+  return RGWGetObj_Filter::handle_data(bl, bl_ofs, bl_len);
+}
+
+int RGWPutObjFilter::process(bufferlist&& data, uint64_t logical_offset) {
+  filter.execute(data, logical_offset, "put_obj");
+  // return value is ignored since we don't want to fail execution if lua script fails
+  return rgw::putobj::Pipe::process(std::move(data), logical_offset); 
+}
+
+} // namespace rgw::lua
+
diff --git a/src/rgw/rgw_lua_data_filter.h b/src/rgw/rgw_lua_data_filter.h
new file mode 100644 (file)
index 0000000..75596b6
--- /dev/null
@@ -0,0 +1,52 @@
+#pragma once
+
+#include "rgw_op.h"
+
+class DoutPrefixProvider;
+
+namespace rgw::lua {
+
+class RGWObjFilter {
+  req_state* const s;
+  const std::string script;
+
+public:
+  RGWObjFilter(req_state* s,
+      const std::string& script) : 
+    s(s), script(script) {}
+
+  int execute(bufferlist& bl, off_t offset, const char* op_name) const;
+};
+
+class RGWGetObjFilter : public RGWGetObj_Filter {
+  const RGWObjFilter filter;
+
+public:
+  RGWGetObjFilter(req_state* s,
+      const std::string& script,
+      RGWGetObj_Filter* next) : RGWGetObj_Filter(next), filter(s, script) 
+  {}
+
+  ~RGWGetObjFilter() override = default;
+
+  int handle_data(bufferlist& bl,
+                  off_t bl_ofs,
+                  off_t bl_len) override;
+
+};
+
+class RGWPutObjFilter : public rgw::putobj::Pipe {
+  const RGWObjFilter filter;
+
+public:
+  RGWPutObjFilter(req_state* s,
+      const std::string& script,
+      rgw::sal::DataProcessor* next) : rgw::putobj::Pipe(next), filter(s, script) 
+  {}
+
+  ~RGWPutObjFilter() override = default;
+
+  int process(bufferlist&& data, uint64_t logical_offset) override;
+};
+} // namespace rgw::lua
+
index 3e9e0521b27ead7a996782956737fe0856b29e9b..a6f56b5f96d524f15f6cdc432c9114c408fae043 100644 (file)
@@ -839,14 +839,19 @@ struct RequestMetaTable : public EmptyMetaTable {
   }
 };
 
+void create_top_metatable(lua_State* L, req_state* s, const char* op_name) {
+  create_metatable<RequestMetaTable>(L, true, s, const_cast<char*>(op_name));
+  lua_getglobal(L, RequestMetaTable::TableName().c_str());
+  ceph_assert(lua_istable(L, -1));
+}
+
 int execute(
     rgw::sal::Store* store,
     RGWREST* rest,
     OpsLogSink* olog,
     req_state* s, 
     const char* op_name,
-    const std::string& script,
-    rgw::lua::Background* background)
+    const std::string& script)
 
 {
   auto L = luaL_newstate();
@@ -873,8 +878,8 @@ int execute(
   lua_pushcclosure(L, RequestLog, FOUR_UPVALS);
   lua_rawset(L, -3);
   
-  if (background) {
-    background->create_background_metatable(L);
+  if (s->lua_background) {
+    s->lua_background->create_background_metatable(L);
     lua_getglobal(L, rgw::lua::RGWTable::TableName().c_str());
     ceph_assert(lua_istable(L, -1));
   }
@@ -898,4 +903,5 @@ int execute(
   return rc;
 }
 
-}
+} // namespace rgw::lua::request
+
index f7569a3e764d7c4ad8c012a30936c7a9b21bef77..908d160eb3e9b184a19f940b79ac668d140e2d59 100644 (file)
@@ -4,15 +4,16 @@
 #include "include/common_fwd.h"
 #include "rgw_sal_fwd.h"
 
-struct req_state;
+struct lua_State;
+class req_state;
 class RGWREST;
 class OpsLogSink;
-namespace rgw::lua {
-  class Background;
-}
 
 namespace rgw::lua::request {
 
+// create the request metatable
+void create_top_metatable(lua_State* L, req_state* s, const char* op_name);
+
 // execute a lua script in the Request context
 int execute(
     rgw::sal::Store* store,
@@ -20,8 +21,7 @@ int execute(
     OpsLogSink* olog,
     req_state *s, 
     const char* op_name,
-    const std::string& script,
-    rgw::lua::Background* background = nullptr);
+    const std::string& script);
 
-}
+} // namespace rgw::lua::request
 
index 9b116269d9ead60f0019df1eb89882a0b725aa51..3ffe23662116eb1cbf48d04416324dc078c2b3be 100644 (file)
@@ -73,4 +73,5 @@ void open_standard_libs(lua_State* L) {
   lua_settable(L, -3);
 }
 
-}
+} // namespace rgw::lua
+
index 0071b71c2b47f051ecb7399f3e0e3e9ca8e4dc2d..cc77dae7a896af214acf174be6586b84a4c4813d 100644 (file)
@@ -310,5 +310,6 @@ struct StringMapMetaTable : public EmptyMetaTable {
     return ONE_RETURNVAL;
   }
 };
-}
+
+} // namespace rgw::lua
 
index 5c3e50d3ee0a2749bf08618c9bf1e959f497a163..91c283640958ab2162d8ba7c95654bb0fdd38f70 100644 (file)
@@ -52,6 +52,8 @@
 #include "rgw_notify_event_type.h"
 #include "rgw_sal.h"
 #include "rgw_sal_rados.h"
+#include "rgw_lua_data_filter.h"
+#include "rgw_lua.h"
 
 #include "services/svc_zone.h"
 #include "services/svc_quota.h"
@@ -2084,6 +2086,20 @@ int RGWGetObj::get_data_cb(bufferlist& bl, off_t bl_ofs, off_t bl_len)
   return send_response_data(bl, bl_ofs, bl_len);
 }
 
+int RGWGetObj::get_lua_filter(std::unique_ptr<RGWGetObj_Filter>* filter, RGWGetObj_Filter* cb) {
+  std::string script;
+  const auto rc = rgw::lua::read_script(s, store, s->bucket_tenant, s->yield, rgw::lua::context::getData, script);
+  if (rc == -ENOENT) {
+    // no script, nothing to do
+    return 0;
+  } else if (rc < 0) {
+    ldpp_dout(this, 5) << "WARNING: failed to read data script. error: " << rc << dendl;
+    return rc;
+  }
+  filter->reset(new rgw::lua::RGWGetObjFilter(s, script, cb));
+  return 0;
+}
+
 bool RGWGetObj::prefetch_data()
 {
   /* HEAD request, stop prefetch*/
@@ -2135,6 +2151,7 @@ void RGWGetObj::execute(optional_yield y)
   RGWGetObj_Filter* filter = (RGWGetObj_Filter *)&cb;
   boost::optional<RGWGetObj_Decompress> decompress;
   std::unique_ptr<RGWGetObj_Filter> decrypt;
+  std::unique_ptr<RGWGetObj_Filter> run_lua;
   map<string, bufferlist>::iterator attr_iter;
 
   perfcounter->inc(l_rgw_get);
@@ -2202,6 +2219,15 @@ void RGWGetObj::execute(optional_yield y)
   }
   /* end gettorrent */
 
+  // run lua script on decompressed and decrypted data - first filter runs last
+  op_ret = get_lua_filter(&run_lua, filter);
+  if (run_lua != nullptr) {
+    filter = run_lua.get();
+  }
+  if (op_ret < 0) {
+    goto done_err;
+  }
+
   op_ret = rgw_compression_info_from_attrset(attrs, need_decompress, cs_info);
   if (op_ret < 0) {
     ldpp_dout(this, 0) << "ERROR: failed to decode compression info, cannot decompress" << dendl;
@@ -2284,6 +2310,7 @@ void RGWGetObj::execute(optional_yield y)
     goto done_err;
   }
 
+
   if (!get_data || ofs > end) {
     send_response_data(bl, 0, 0);
     return;
@@ -3842,6 +3869,20 @@ static CompressorRef get_compressor_plugin(const req_state *s,
   return Compressor::create(s->cct, alg);
 }
 
+int RGWPutObj::get_lua_filter(std::unique_ptr<rgw::sal::DataProcessor>* filter, rgw::sal::DataProcessor* cb) {
+  std::string script;
+  const auto rc = rgw::lua::read_script(s, store, s->bucket_tenant, s->yield, rgw::lua::context::putData, script);
+  if (rc == -ENOENT) {
+    // no script, nothing to do
+    return 0;
+  } else if (rc < 0) {
+    ldpp_dout(this, 5) << "WARNING: failed to read data script. error: " << rc << dendl;
+    return rc;
+  }
+  filter->reset(new rgw::lua::RGWPutObjFilter(s, script, cb));
+  return 0;
+}
+
 void RGWPutObj::execute(optional_yield y)
 {
   char supplied_md5_bin[CEPH_CRYPTO_MD5_DIGESTSIZE + 1];
@@ -4039,6 +4080,7 @@ void RGWPutObj::execute(optional_yield y)
   boost::optional<RGWPutObj_Compress> compressor;
 
   std::unique_ptr<rgw::sal::DataProcessor> encrypt;
+  std::unique_ptr<rgw::sal::DataProcessor> run_lua;
 
   if (!append) { // compression and encryption only apply to full object uploads
     op_ret = get_encrypt_filter(&encrypt, filter);
@@ -4059,6 +4101,14 @@ void RGWPutObj::execute(optional_yield y)
         s->object->set_compressed();
       }
     }
+    // run lua script before data is compressed and encrypted - last filter runs first
+    op_ret = get_lua_filter(&run_lua, filter);
+    if (op_ret < 0) {
+      return;
+    }
+    if (run_lua) {
+      filter = &*run_lua;
+    }
   }
   tracepoint(rgw_op, before_data_transfer, s->req_id.c_str());
   do {
index 9176d2389350a0314827e163fa39b1e32cafc548..f99ea23edc40ca0ce95057584fab8d47c978adf9 100644 (file)
@@ -437,6 +437,11 @@ public:
     *filter = nullptr;
     return 0;
   }
+
+  // get lua script to run as a "get object" filter 
+  int get_lua_filter(std::unique_ptr<RGWGetObj_Filter>* filter, 
+      RGWGetObj_Filter* cb);
+
   dmc::client_id dmclock_client() override { return dmc::client_id::data; }
 };
 
@@ -1276,6 +1281,10 @@ public:
     return 0;
   }
 
+  // get lua script to run as a "put object" filter 
+  int get_lua_filter(std::unique_ptr<rgw::sal::DataProcessor>* filter, 
+      rgw::sal::DataProcessor* cb);
+
   int get_data_cb(bufferlist& bl, off_t bl_ofs, off_t bl_len);
   int get_data(const off_t fst, const off_t lst, bufferlist& bl);
 
index 1d4c8014c1fdd9cb1fde62c71cfbf36d960352ce..dc6a26b832fe29e645774aa5a58a9526d273efb0 100644 (file)
@@ -327,6 +327,7 @@ int process_request(rgw::sal::Store* const store,
     abort_early(s, NULL, -ERR_METHOD_NOT_ALLOWED, handler, yield);
     goto done;
   }
+  s->lua_background = lua_background;
   {
     s->trace_enabled = tracing::rgw::tracer.is_enabled();
     std::string script;
@@ -336,7 +337,7 @@ int process_request(rgw::sal::Store* const store,
     } else if (rc < 0) {
       ldpp_dout(op, 5) << "WARNING: failed to read pre request script. error: " << rc << dendl;
     } else {
-      rc = rgw::lua::request::execute(store, rest, olog, s, op->name(), script, lua_background);
+      rc = rgw::lua::request::execute(store, rest, olog, s, op->name(), script);
       if (rc < 0) {
         ldpp_dout(op, 5) << "WARNING: failed to execute pre request script. error: " << rc << dendl;
       }
@@ -419,7 +420,7 @@ done:
     } else if (rc < 0) {
       ldpp_dout(op, 5) << "WARNING: failed to read post request script. error: " << rc << dendl;
     } else {
-      rc = rgw::lua::request::execute(store, rest, olog, s, op->name(), script, lua_background);
+      rc = rgw::lua::request::execute(store, rest, olog, s, op->name(), script);
       if (rc < 0) {
         ldpp_dout(op, 5) << "WARNING: failed to execute post request script. error: " << rc << dendl;
       }
index 2ea1ceda25a64b334a03440d1bc5568cfaf04a3f..36c6996b88d9c61cac7f69891fa12581dd00a33b 100644 (file)
      --event-id                event id in a pubsub subscription
   
   Script options:
-     --context                 context in which the script runs. one of: preRequest, postRequest, background
+     --context                 context in which the script runs. one of: prerequest, postrequest, background, getdata, putdata
      --package                 name of the lua package that should be added/removed to/from the allowlist
      --allow-compilation       package is allowed to compile C code as part of its installation
   
index 110e6addd84cd8d0dfce7e42b05ea357b8b73313..5e86e54b292173ea1778e4fa612425f268047b82 100644 (file)
@@ -6,6 +6,7 @@
 #include "rgw/rgw_sal_rados.h"
 #include "rgw/rgw_lua_request.h"
 #include "rgw/rgw_lua_background.h"
+#include "rgw/rgw_lua_data_filter.h"
 
 using namespace std;
 using namespace rgw;
@@ -764,10 +765,11 @@ TEST(TestRGWLuaBackground, RequestScript)
   )";
 
   DEFINE_REQ_STATE;
+  s.lua_background = &lua_background;
 
   // to make sure test is consistent we have to puase the background
   lua_background.pause();
-  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_EQ(rc, 0);
   EXPECT_EQ(get_table_value<std::string>(lua_background, "hello"), "from request");
   // now we resume and let the background set the value
@@ -908,8 +910,9 @@ TEST(TestRGWLuaBackground, TableValues)
   )";
 
   DEFINE_REQ_STATE;
+  s.lua_background = &lua_background;
 
-  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_EQ(rc, 0);
   EXPECT_EQ(get_table_value<std::string>(lua_background, "key1"), "string value");
   EXPECT_EQ(get_table_value<long long int>(lua_background, "key2"), 42);
@@ -927,8 +930,9 @@ TEST(TestRGWLuaBackground, TablePersist)
   )";
 
   DEFINE_REQ_STATE;
+  s.lua_background = &lua_background;
 
-  auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_EQ(rc, 0);
   EXPECT_EQ(get_table_value<std::string>(lua_background, "key1"), "string value");
   EXPECT_EQ(get_table_value<long long int>(lua_background, "key2"), 42);
@@ -938,7 +942,7 @@ TEST(TestRGWLuaBackground, TablePersist)
     RGW["key4"] = RGW["key2"]
   )";
   
-  rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_EQ(rc, 0);
   EXPECT_EQ(get_table_value<std::string>(lua_background, "key1"), "string value");
   EXPECT_EQ(get_table_value<long long int>(lua_background, "key2"), 42);
@@ -959,12 +963,14 @@ TEST(TestRGWLuaBackground, TableValuesFromRequest)
   )";
 
   DEFINE_REQ_STATE;
+  s.lua_background = &lua_background;
+
   s.tagset.add_tag("key1", "val1");
   s.tagset.add_tag("key2", "val1");
   s.err.ret = -99;
   s.err.message = "hi";
 
-  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_EQ(rc, 0);
   EXPECT_EQ(get_table_value<long long int>(lua_background, "key1"), -99);
   EXPECT_EQ(get_table_value<std::string>(lua_background, "key2"), "hi");
@@ -986,10 +992,11 @@ TEST(TestRGWLuaBackground, TableInvalidValue)
   )";
 
   DEFINE_REQ_STATE;
+  s.lua_background = &lua_background;
   s.tagset.add_tag("key1", "val1");
   s.tagset.add_tag("key2", "val2");
 
-  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_NE(rc, 0);
   EXPECT_EQ(get_table_value<std::string>(lua_background, "key1"), "val1");
   EXPECT_EQ(get_table_value<long long int>(lua_background, "key2"), 42);
@@ -1010,8 +1017,9 @@ TEST(TestRGWLuaBackground, TableErase)
   )";
 
   DEFINE_REQ_STATE;
+  s.lua_background = &lua_background;
 
-  auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_EQ(rc, 0);
   EXPECT_EQ(get_table_value<std::string>(lua_background, "key1"), "string value");
   EXPECT_EQ(get_table_value<long long int>(lua_background, "key2"), 42);
@@ -1026,7 +1034,7 @@ TEST(TestRGWLuaBackground, TableErase)
     RGW["size"] = #RGW
   )";
   
-  rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_EQ(rc, 0);
   EXPECT_EQ(get_table_value<std::string>(lua_background, "key1"), "");
   EXPECT_EQ(get_table_value<long long int>(lua_background, "key2"), 42);
@@ -1050,8 +1058,9 @@ TEST(TestRGWLuaBackground, TableIterate)
   )";
 
   DEFINE_REQ_STATE;
+  s.lua_background = &lua_background;
 
-  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_EQ(rc, 0);
   EXPECT_EQ(get_table_value<std::string>(lua_background, "key1"), "string value");
   EXPECT_EQ(get_table_value<long long int>(lua_background, "key2"), 42);
@@ -1074,8 +1083,9 @@ TEST(TestRGWLuaBackground, TableIncrement)
   )";
 
   DEFINE_REQ_STATE;
+  s.lua_background = &lua_background;
 
-  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_EQ(rc, 0);
 }
 
@@ -1095,8 +1105,9 @@ TEST(TestRGWLuaBackground, TableIncrementBy)
   )";
 
   DEFINE_REQ_STATE;
+  s.lua_background = &lua_background;
 
-  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_EQ(rc, 0);
 }
 
@@ -1114,8 +1125,9 @@ TEST(TestRGWLuaBackground, TableDecrement)
   )";
 
   DEFINE_REQ_STATE;
+  s.lua_background = &lua_background;
 
-  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_EQ(rc, 0);
 }
 
@@ -1135,8 +1147,9 @@ TEST(TestRGWLuaBackground, TableDecrementBy)
   )";
 
   DEFINE_REQ_STATE;
+  s.lua_background = &lua_background;
 
-  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_EQ(rc, 0);
 }
 
@@ -1151,8 +1164,9 @@ TEST(TestRGWLuaBackground, TableIncrementValueError)
   )";
 
   DEFINE_REQ_STATE;
+  s.lua_background = &lua_background;
 
-  auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_NE(rc, 0);
   
   request_script = R"(
@@ -1161,7 +1175,7 @@ TEST(TestRGWLuaBackground, TableIncrementValueError)
     RGW.increment("key1")
   )";
 
-  rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_NE(rc, 0);
   
   request_script = R"(
@@ -1170,7 +1184,7 @@ TEST(TestRGWLuaBackground, TableIncrementValueError)
     RGW.increment("key1", "kaboom")
   )";
 
-  rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_NE(rc, 0);
 }
 
@@ -1185,8 +1199,9 @@ TEST(TestRGWLuaBackground, TableIncrementError)
   )";
 
   DEFINE_REQ_STATE;
+  s.lua_background = &lua_background;
 
-  auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_NE(rc, 0);
   
   request_script = R"(
@@ -1194,7 +1209,7 @@ TEST(TestRGWLuaBackground, TableIncrementError)
     RGW.increment = 11
   )";
 
-  rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script, &lua_background);
+  rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "", request_script);
   ASSERT_NE(rc, 0);
 }
 
@@ -1245,3 +1260,52 @@ TEST(TestRGWLua, TracingAddEvent)
   const auto rc = lua::request::execute(nullptr, nullptr, nullptr, &s, "put_obj", script);
   ASSERT_EQ(rc, 0);
 }
+
+TEST(TestRGWLua, Data)
+{
+  const std::string script = R"(
+    local expected = "The quick brown fox jumps over the lazy dog"
+    local actual = ""
+    RGW["key1"] = 0
+    
+    for i, c in pairs(Data) do
+      actual = actual .. c
+      RGW.increment("key1")
+    end 
+    assert(expected == actual)
+    assert(#Data == #expected);
+    assert(RGW["key1"] == #Data)
+    assert(Request.RGWId == "foo")
+    assert(Offset == 12345678)
+  )";
+
+  TestBackground lua_background("");
+  DEFINE_REQ_STATE;
+  s.host_id = "foo";
+  s.lua_background = &lua_background;
+  lua::RGWObjFilter filter(&s, script);
+  bufferlist bl;
+  bl.append("The quick brown fox jumps over the lazy dog");
+  off_t offset = 12345678;
+  const auto rc = filter.execute(bl, offset, "put_obj");
+  ASSERT_EQ(rc, 0);
+}
+
+TEST(TestRGWLua, WriteDataFail)
+{
+  const std::string script = R"(
+    Data[1] = "h"
+    Data[2] = "e"
+    Data[3] = "l"
+    Data[4] = "l"
+    Data[5] = "o"
+  )";
+
+  DEFINE_REQ_STATE;
+  lua::RGWObjFilter filter(&s, script);
+  bufferlist bl;
+  bl.append("The quick brown fox jumps over the lazy dog");
+  const auto rc = filter.execute(bl, 0, "put_obj");
+  ASSERT_NE(rc, 0);
+}
+