1 Star 0 Fork 29

kefeng / libsearpc

forked from lins05 / libsearpc 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
LGPL-3.0

Introduction

Searpc is a simple C language RPC framework based on GObject system. Searpc handles the serialization/deserialization part of RPC, the transport part is left to users.

The serialization/deserialization uses JSON format via json-glib library. A serialized json object is returned from server to client after executing the RPC function. Each RPC function defined in the server side should take an extra GError argument to report error. The returned json object contains three fields:

  • ret: the return value of the RPC function
  • err_code: error code. This field is only set if the RPC function reports an error.
  • err_msg: error message. This field is only set if the RPC function reports an error.

Compile

Just

./autogen.sh; ./configure; make; make install

To enable profile, Use

CFLAGS="-DPROFILE" ./configure

When profile is enabled, the time spend in each rpc call will be printed.

Example

Client

In the client side, you need to:

  • Create a rpc_client and supply the transport function.
  • write code to send the request to server and get the resonpse from it.

Create rpc_client

The client needs to create a SearpcClient object and supply a transport function. For example:

/* create an rpc_client and supply the transport function. */
SearpcClient *rpc_client;
rpc_client = searpc_client_new();
rpc_client->transport = transport_callback;
rpc_client->arg = &sockfd;

Suppose we have a get_substring function defined in server as follows:

gchar *get_substring (const gchar *orig_str, int sub_len, GError **error)

To call this function, we type:

gchar* result;
GError *error = NULL;
result = searpc_client_call__string (client, "get_substring", &error,
                                     2, "string", "hello", "int", 2);

string in searpc_client_call__string specify the return type. "get_substring" is the function name. The remain parameters specify the number of parameters the rpc function took and the type of each parameter and its value. So

2, "string", "hello", "int", 2

means "get_substring" takes 2 parameters, the first is of type "string", the value is "hello", the second is of type "int", the value is 2.

Transport function

When the client-side function is called, Searpc does the following work:

  • Pack the function name and the params into JSON data format.
  • Call your transport function to send the JSON data to the server, and get the returned data from the server.
  • Unpack the returned JSON data and return the value as the return value of the client-side function.

Your transport function is supposed to:

  • Send the request data to the server.
  • Receive the returned data from the server.

The prototype of the transport function is:

/* 
 * arg: rpc_client->arg. Normally a socket number.
 * fcall_str: the JSON data stream generated by Searpc.
 * fcall_len: the length of `fcall_str`.
 * ret_len: place to get the length of the returned json data stream.
 * Returns: A newly allocated string stores the JSON data stream.
 */
static char *transport_callback (void *arg, const char *fcall_str, size_t fcall_len, size_t *ret_len);

Server

In the server side, you need to:

  • Init searpc server
  • Create services and register your functions
  • write code to receive the request and send the result

And Searpc handles the others for you.

Concepts

  • Marshal: The process of unpacking the function arguments from JSON data, call the RPC function and packing the result into JSON data format is called marshalling. The function used to pack the result is called a marshal.

  • Signature: Every function has a signature determined by its return type and parameter types. Knowning a function's signature enable us to use a corresponding marshal to call it and convert the result into json string.

Init Searpc Server

First write rpc_table.py to contain the rpc function signatures as follows:

# [ <ret-type>, [<arg_types>] ]
func_table = [
     [ "int", ["string"] ],
     [ "string", ["int", "string"] ],
]

Add makefile rule:

searpc-signature.h searpc-marshal.h: rpc_table.py
    python searpc-codegen.py rpc_table.py

searpc-signature.h and searpc-marshal.h will be created containing the function signatures and corresponding marshals. searpc-marshal.h also contains a function called register_marshals.

Then we init the server as follows:

#include "searpc-signature.h"
#include "searpc-marshal.h"

static void
init_rpc_service(void)
{
    /* register_marshals is defined in searpc-marshal.h */
    searpc_server_init(register_marshals);
}

Register Functions

To register a function we first need to create a service. A service is a set of functions.

Suppose we want to make searpc_strlen callable from some network clients, we can do this by putting the following code somewhere:

static int
searpc_strlen(const char *str)
{
    if (str == NULL)
        return -1;
    else
        return strlen(str);
}

static void
register_functions()
{

    searpc_create_service("searpc-demo");

    /* The first parameter is the implementation function.
     * The second parameter is the name of the rpc function the 
     * client would call.
     * The third parameter is the signature.
     */
    searpc_server_register_function("searpc-demo",
                                    searpc_strlen,
                                    "searpc_strlen",
                                    searpc_signature_int__string());
 }

The seaprc_server_register_function routine registers a function as a RPC function. The prototype of this function is:

/*
 * service:     the name of the service
 * func:        pointer to the function you want to register
 * fname:       the name of the function. It would be the key of your 
 *              function in the fucntion hash table.
 * signature:   the identifier used to get the corresponding marshal.
 * Returns:     a gboolean value indicating success or failure
 */
 gboolean searpc_server_register_function (const char *service,
                                           void* func,
                                           const gchar *fname,
                                           gchar *signature);

Call the RPC fucntion

After the registration, you should listen to the socket and wait for the incoming request data stream. Once you get a valid request, call the searpc_server_call_function() routine, which will automatically do the following work for you:

  • Parse the JSON data stream to resolve the function name and the data.
  • Lookup the function in internal function table according to the funcname.
  • If a proper function is found, call the function with the given params.
  • Packing the result into a JSON data string.

The prototype of searpc_server_call_function is:

/*
 * service: Service name.
 * data:    The incoming JSON data stream.
 * len:     The length of **`data`**.
 * ret_len: Place to hold the length of the JSON data stream to be returned
 * Returns: The JSON data containing the result of the RPC
 */
gchar* searpc_server_call_function (const char *service,
                                    gchar *data, gsize len, gsize *ret_len)

The value returned by searpc_server_call_function() is the JSON data ready to send back to the client.

Note, the JSON data stream from client does not contain the service name, it's left to the transport layer to solve the problem. There are several ways, for example:

  1. You may listen on different sockets and determine the service by the incoming socket.
  2. The client transport function prepend the service name into the request before the json data, and the server transport function first read the service name and read the json data.

Pysearpc

Pysearpc is the Python binding of Searpc. Only the client side function is supported. To use it, simply define a class which inherits SearpcClient, and provide a call_remote_func_sync method, which is equivalent to the transport_callback.

To define your RPC funtion, use the @searpc_func decorator. It is equivalent to SEARPC_CLIENT_DEFUN_XXX__YYY macro. To define a RPC function which accepts multiple params, here is an example:

class SampeSearpcClient(SearpcClient):
    def call_remote_func_sync(self, fcall_str):
        # your transport code here
        ...
    
    @searpc_func("int", ["string", "string"])
    def searpc_demo_func(self):
        # this is enough for the client side
        pass

See the demo program for a more detailed example.

Demos

There are well-commented demos in both C and Python.

  • searpc-demo-server.c: The server side demo program
  • searpc-demo-client.c: The client side demo in C
  • pysearpc-demo-client.py: The client side demo in Python

To run the demo, run the server demo in a shell, and run the client demo in another. To run the python demo, you should first install the package and setup the PYTHONPATH appropriately.

Dependency

The following packages are required to build libsearpc:

  • glib-2.0 >= 2.26.0
  • gobject-2.0 >= 2.26.0
  • jansson >= 2.2.1
  • python simplejson (for pysearpc)
GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.

简介

简单易用的 C 语言 RPC 框架,包括客户端和服务器端(包括 Python实现) 展开 收起
LGPL-3.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/autotrade/libsearpc.git
git@gitee.com:autotrade/libsearpc.git
autotrade
libsearpc
libsearpc
master

搜索帮助