1 #include <opensrf/osrf_application.h>
4 @file osrf_application.c
5 @brief Load and manage shared object libraries.
7 Maintain a registry of applications, using an osrfHash keyed on application name,
9 For each application, load a shared object library so that we can call
10 application-specific functions dynamically. In order to map method names to the
11 corresponding functions (i.e. symbol names in the library), maintain a registry of
12 methods, using an osrfHash keyed on method name.
15 // The following macro is commented out because it ia no longer used.
17 // Used internally to make sure the method description provided is OK
19 #define OSRF_METHOD_VERIFY_DESCRIPTION(app, d) \
23 osrfLogError( OSRF_LOG_MARK, "No method name provided in description" ), \
27 osrfLogError( OSRF_LOG_MARK, "No method symbol provided in description" ), \
39 @name Well known method names
40 @brief These methods are automatically implemented for every application.
43 #define OSRF_SYSMETHOD_INTROSPECT "opensrf.system.method"
44 #define OSRF_SYSMETHOD_INTROSPECT_ATOMIC "opensrf.system.method.atomic"
45 #define OSRF_SYSMETHOD_INTROSPECT_ALL "opensrf.system.method.all"
46 #define OSRF_SYSMETHOD_INTROSPECT_ALL_ATOMIC "opensrf.system.method.all.atomic"
47 #define OSRF_SYSMETHOD_ECHO "opensrf.system.echo"
48 #define OSRF_SYSMETHOD_ECHO_ATOMIC "opensrf.system.echo.atomic"
53 @brief Macros that get OR'd together to form method options.
55 These options are in addition to the ones stipulated by the caller of
56 osrfRegisterMethod(), and are not externally visible.
60 @brief Marks a method as a system method.
62 System methods are implemented by generic functions, called via static linkage. They
63 are not loaded or executed from shared objects.
65 #define OSRF_METHOD_SYSTEM 1
67 @brief Combines all responses into a single RESULT message.
69 For a @em non-atomic method, the server returns each response to the client in a
70 separate RESULT message. It sends a STATUS message at the end to signify the end of the
73 For an @em atomic method, the server buffers all responses until the method returns,
74 and then sends them all at once in a single RESULT message (followed by a STATUS message).
75 Each individual response is encoded as an entry in a JSON array. This buffering is
76 transparent to the function that implements the method.
78 Atomic methods incur less networking overhead than non-atomic methods, at the risk of
79 creating excessively large RESULT messages. The HTTP gateway requires the atomic versions
80 of streaming methods because of the stateless nature of the HTTP protocol.
82 If OSRF_METHOD_STREAMING is set for a method, the application generates both an atomic
83 and a non-atomic method, whose names are identical except that the atomic one carries a
86 #define OSRF_METHOD_ATOMIC 4
90 @brief Default size of output buffer.
92 #define OSRF_MSG_BUFFER_SIZE 10240
95 @brief Represent an Application.
98 void* handle; /**< Handle to the shared object library. */
99 osrfHash* methods; /**< Registry of method names. */
100 void (*onExit) (void); /**< Exit handler for the application. */
103 static void register_method( osrfApplication* app, const char* methodName,
104 const char* symbolName, const char* notes, int argc, int options, void * user_data );
105 static osrfMethod* build_method( const char* methodName, const char* symbolName,
106 const char* notes, int argc, int options, void* );
107 static void osrfAppSetOnExit(osrfApplication* app, const char* appName);
108 static void register_system_methods( osrfApplication* app );
109 static inline osrfApplication* _osrfAppFindApplication( const char* name );
110 static inline osrfMethod* osrfAppFindMethod( osrfApplication* app, const char* methodName );
111 static int _osrfAppRespond( osrfMethodContext* context, const jsonObject* data, int complete );
112 static int _osrfAppPostProcess( osrfMethodContext* context, int retcode );
113 static int _osrfAppRunSystemMethod(osrfMethodContext* context);
114 static void _osrfAppSetIntrospectMethod( osrfMethodContext* ctx, const osrfMethod* method,
116 static int osrfAppIntrospect( osrfMethodContext* ctx );
117 static int osrfAppIntrospectAll( osrfMethodContext* ctx );
118 static int osrfAppEcho( osrfMethodContext* ctx );
119 static void osrfMethodFree( char* name, void* p );
120 static void osrfAppFree( char* name, void* p );
123 @brief Registry of applications.
125 The key of the hash is the application name, and the associated data is an osrfApplication.
127 static osrfHash* _osrfAppHash = NULL;
130 @brief Register an application.
131 @param appName Name of the application.
132 @param soFile Name of the shared object file to be loaded for this application.
133 @return Zero if successful, or -1 upon error.
135 Open the shared object file and call its osrfAppInitialize() function, if it has one.
136 Register the standard system methods for it. Arrange for the application name to
137 appear in subsequent log messages.
139 int osrfAppRegisterApplication( const char* appName, const char* soFile ) {
140 if( !appName || ! soFile ) return -1;
143 osrfLogSetAppname( appName );
145 if( !_osrfAppHash ) {
146 _osrfAppHash = osrfNewHash();
147 osrfHashSetCallback( _osrfAppHash, osrfAppFree );
150 osrfLogInfo( OSRF_LOG_MARK, "Registering application %s with file %s", appName, soFile );
152 // Open the shared object.
153 void* handle = dlopen( soFile, RTLD_NOW );
155 const char* msg = dlerror();
156 osrfLogWarning( OSRF_LOG_MARK, "Failed to dlopen library file %s: %s", soFile, msg );
160 // Construct the osrfApplication.
161 osrfApplication* app = safe_malloc(sizeof(osrfApplication));
162 app->handle = handle;
163 app->methods = osrfNewHash();
164 osrfHashSetCallback( app->methods, osrfMethodFree );
167 // Add the newly-constructed app to the list.
168 osrfHashSet( _osrfAppHash, app, appName );
170 // Try to run the initialize method. Typically it will register one or more
171 // methods of the application.
173 *(void **) (&init) = dlsym( handle, "osrfAppInitialize" );
175 if( (error = dlerror()) != NULL ) {
176 osrfLogWarning( OSRF_LOG_MARK,
177 "! Unable to locate method symbol [osrfAppInitialize] for app %s: %s",
184 if( (ret = (*init)()) ) {
185 osrfLogWarning( OSRF_LOG_MARK, "Application %s returned non-zero value from "
186 "'osrfAppInitialize', not registering...", appName );
187 osrfHashRemove( _osrfAppHash, appName );
192 register_system_methods( app );
193 osrfLogInfo( OSRF_LOG_MARK, "Application %s registered successfully", appName );
194 osrfAppSetOnExit( app, appName );
200 @brief Save a pointer to the application's exit function.
201 @param app Pointer to the osrfApplication.
202 @param appName Application name (used only for log messages).
204 Look in the shared object for a symbol named "osrfAppChildExit". If you find one, save
205 it as a pointer to the application's exit function. If present, this function will be
206 called when a server's child process (a so-called "drone") is shutting down.
208 static void osrfAppSetOnExit(osrfApplication* app, const char* appName) {
209 if(!(app && appName)) return;
211 /* see if we can run the initialize method */
213 void (*onExit) (void);
214 *(void **) (&onExit) = dlsym(app->handle, "osrfAppChildExit");
216 if( (error = dlerror()) != NULL ) {
217 osrfLogDebug(OSRF_LOG_MARK, "No exit handler defined for %s", appName);
221 osrfLogInfo(OSRF_LOG_MARK, "registering exit handler for %s", appName);
222 app->onExit = (*onExit);
226 @brief Run the application-specific child initialization function for a given application.
227 @param appname Name of the application.
228 @return Zero if successful, or if the application has no child initialization function; -1
229 if the application is not registered, or if the function returns non-zero.
231 The child initialization function must be named "osrfAppChildInit" within the shared
232 object library. It initializes a drone process of a server.
234 int osrfAppRunChildInit(const char* appname) {
235 osrfApplication* app = _osrfAppFindApplication(appname);
240 int (*childInit) (void);
242 *(void**) (&childInit) = dlsym(app->handle, "osrfAppChildInit");
244 if( (error = dlerror()) != NULL ) {
245 osrfLogInfo( OSRF_LOG_MARK, "No child init defined for app %s : %s", appname, error);
249 if( (ret = (*childInit)()) ) {
250 osrfLogError(OSRF_LOG_MARK, "App %s child init failed", appname);
254 osrfLogInfo(OSRF_LOG_MARK, "%s child init succeeded", appname);
259 @brief Call the exit handler for every application that has one.
261 Normally a server's child process (a so-called "drone") calls this function just before
264 void osrfAppRunExitCode( void ) {
265 osrfHashIterator* itr = osrfNewHashIterator(_osrfAppHash);
266 osrfApplication* app;
267 while( (app = osrfHashIteratorNext(itr)) ) {
269 osrfLogInfo(OSRF_LOG_MARK, "Running onExit handler for app %s",
270 osrfHashIteratorKey(itr) );
274 osrfHashIteratorFree(itr);
278 @brief Register a method for a specified application.
280 @param appName Name of the application that implements the method.
281 @param methodName The fully qualified name of the method.
282 @param symbolName The symbol name (function name) that implements the method.
283 @param notes Public documentation for this method.
284 @param argc The minimum number of arguments for the function.
285 @param options Bit switches setting various options.
286 @return Zero on success, or -1 on error.
288 Registering a method enables us to call the right function when a client requests a
291 The @a options parameter is zero or more of the following macros, OR'd together:
293 - OSRF_METHOD_STREAMING method may return more than one response
294 - OSRF_METHOD_CACHABLE cache results in memcache
296 If the OSRF_METHOD_STREAMING bit is set, also register an ".atomic" version of the method.
298 int osrfAppRegisterMethod( const char* appName, const char* methodName,
299 const char* symbolName, const char* notes, int argc, int options ) {
301 return osrfAppRegisterExtendedMethod(
313 @brief Register an extended method for a specified application.
315 @param appName Name of the application that implements the method.
316 @param methodName The fully qualified name of the method.
317 @param symbolName The symbol name (function name) that implements the method.
318 @param notes Public documentation for this method.
319 @param argc How many arguments this method expects.
320 @param options Bit switches setting various options.
321 @param user_data Opaque pointer to be passed to the dynamically called function.
322 @return Zero if successful, or -1 upon error.
324 This function is identical to osrfAppRegisterMethod(), except that it also installs
325 a method-specific opaque pointer. When we call the corresponding function at
326 run time, this pointer will be available to the function via the method context.
328 int osrfAppRegisterExtendedMethod( const char* appName, const char* methodName,
329 const char* symbolName, const char* notes, int argc, int options, void * user_data ) {
331 if( !appName || ! methodName ) return -1;
333 osrfApplication* app = _osrfAppFindApplication(appName);
335 osrfLogWarning( OSRF_LOG_MARK, "Unable to locate application %s", appName );
339 osrfLogDebug( OSRF_LOG_MARK, "Registering method %s for app %s", methodName, appName );
341 // Extract the only valid option bits, and ignore the rest.
342 int opts = options & ( OSRF_METHOD_STREAMING | OSRF_METHOD_CACHABLE );
344 // Build and install a non-atomic method.
346 app, methodName, symbolName, notes, argc, opts, user_data );
348 if( opts & OSRF_METHOD_STREAMING ) {
349 // Build and install an atomic version of the same method.
351 app, methodName, symbolName, notes, argc, opts | OSRF_METHOD_ATOMIC, user_data );
358 @brief Register a single method for a specified application.
360 @param appName Pointer to the application that implements the method.
361 @param methodName The fully qualified name of the method.
362 @param symbolName The symbol name (function name) that implements the method.
363 @param notes Public documentation for this method.
364 @param argc How many arguments this method expects.
365 @param options Bit switches setting various options.
366 @param user_data Opaque pointer to be passed to the dynamically called function.
368 static void register_method( osrfApplication* app, const char* methodName,
369 const char* symbolName, const char* notes, int argc, int options, void * user_data ) {
371 if( !app || ! methodName ) return;
373 // Build a method and add it to the list of methods
374 osrfMethod* method = build_method(
375 methodName, symbolName, notes, argc, options, user_data );
376 osrfHashSet( app->methods, method, method->name );
380 @brief Allocate and populate an osrfMethod.
381 @param methodName Name of the method.
382 @param symbolName Name of the function that implements the method.
383 @param notes Remarks documenting the method.
384 @param argc Minimum number of arguments to the method.
385 @param options Bit switches setting various options.
386 @param user_data An opaque pointer to be passed in the method context.
387 @return Pointer to the newly allocated osrfMethod.
389 If OSRF_METHOD_ATOMIC is set, append ".atomic" to the method name.
391 static osrfMethod* build_method( const char* methodName, const char* symbolName,
392 const char* notes, int argc, int options, void* user_data ) {
394 osrfMethod* method = safe_malloc(sizeof(osrfMethod));
397 methodName = ""; // should never happen
399 if( options & OSRF_METHOD_ATOMIC ) {
400 // Append ".atomic" to the name.
401 char mb[ strlen( methodName ) + 8 ];
402 sprintf( mb, "%s.atomic", methodName );
403 method->name = strdup( mb );
405 method->name = strdup(methodName);
409 method->symbol = strdup(symbolName);
411 method->symbol = NULL;
414 method->notes = strdup(notes);
416 method->notes = NULL;
419 method->options = options;
422 method->userData = user_data;
424 method->bufsize = OSRF_MSG_BUFFER_SIZE;
429 @brief Set the effective output buffer size for a given method.
430 @param appName Name of the application.
431 @param methodName Name of the method.
432 @param bufsize Desired size of the output buffer, in bytes.
433 @return Zero if successful, or -1 if the specified method cannot be found.
435 A smaller buffer size may result in a lower latency for the first response, since we don't
436 wait for as many messages to accumulate before flushing the output buffer. On the other
437 hand a larger buffer size may result in higher throughput due to lower network overhead.
439 Since the buffer size is not an absolute limit, it may be set to zero, in which case each
440 output transport message will contain no more than one RESULT message.
442 This function has no effect on atomic methods, because all responses are sent in a single
443 message anyway. Likewise it has no effect on a method that returns only a single response.
445 int osrfMethodSetBufferSize( const char* appName, const char* methodName, size_t bufsize ) {
446 osrfMethod* method = _osrfAppFindMethod( appName, methodName );
448 osrfLogInfo( OSRF_LOG_MARK,
449 "Setting outbuf buffer size to %lu for method %s of application %s",
450 (unsigned long) bufsize, methodName, appName );
451 method->bufsize = bufsize;
454 osrfLogWarning( OSRF_LOG_MARK,
455 "Unable to set outbuf buffer size to %lu for method %s of application %s",
456 (unsigned long) bufsize, methodName, appName );
462 @brief Register all of the system methods for this application.
463 @param app Pointer to the application.
465 A client can call these methods the same way it calls application-specific methods,
466 but they are implemented by functions here in this module, not by functions in the
469 static void register_system_methods( osrfApplication* app ) {
474 app, OSRF_SYSMETHOD_INTROSPECT, NULL,
475 "Return a list of methods whose names have the same initial "
476 "substring as that of the provided method name PARAMS( methodNameSubstring )",
477 1, OSRF_METHOD_SYSTEM | OSRF_METHOD_STREAMING,
481 app, OSRF_SYSMETHOD_INTROSPECT, NULL,
482 "Return a list of methods whose names have the same initial "
483 "substring as that of the provided method name PARAMS( methodNameSubstring )",
484 1, OSRF_METHOD_SYSTEM | OSRF_METHOD_STREAMING | OSRF_METHOD_ATOMIC,
488 app, OSRF_SYSMETHOD_INTROSPECT_ALL, NULL,
489 "Returns a complete list of methods. PARAMS()",
490 0, OSRF_METHOD_SYSTEM | OSRF_METHOD_STREAMING,
494 app, OSRF_SYSMETHOD_INTROSPECT_ALL, NULL,
495 "Returns a complete list of methods. PARAMS()",
496 0, OSRF_METHOD_SYSTEM | OSRF_METHOD_STREAMING | OSRF_METHOD_ATOMIC,
500 app, OSRF_SYSMETHOD_ECHO, NULL,
501 "Echos all data sent to the server back to the client. PARAMS([a, b, ...])",
502 0, OSRF_METHOD_SYSTEM | OSRF_METHOD_STREAMING,
506 app, OSRF_SYSMETHOD_ECHO, NULL,
507 "Echos all data sent to the server back to the client. PARAMS([a, b, ...])",
508 0, OSRF_METHOD_SYSTEM | OSRF_METHOD_STREAMING | OSRF_METHOD_ATOMIC,
513 @brief Look up an application by name in the application registry.
514 @param name The name of the application.
515 @return Pointer to the corresponding osrfApplication if found, or NULL if not.
517 static inline osrfApplication* _osrfAppFindApplication( const char* name ) {
518 return (osrfApplication*) osrfHashGet(_osrfAppHash, name);
522 @brief Look up a method by name for a given application.
523 @param app Pointer to the osrfApplication that owns the method.
524 @param methodName Name of the method to find.
525 @return Pointer to the corresponding osrfMethod if found, or NULL if not.
527 static inline osrfMethod* osrfAppFindMethod( osrfApplication* app, const char* methodName ) {
528 if( !app ) return NULL;
529 return (osrfMethod*) osrfHashGet( app->methods, methodName );
533 @brief Look up a method by name for an application with a given name.
534 @param appName Name of the osrfApplication.
535 @param methodName Name of the method to find.
536 @return Pointer to the corresponding osrfMethod if found, or NULL if not.
538 osrfMethod* _osrfAppFindMethod( const char* appName, const char* methodName ) {
539 if( !appName ) return NULL;
540 return osrfAppFindMethod( _osrfAppFindApplication(appName), methodName );
544 @brief Call the function that implements a specified method.
545 @param appName Name of the application.
546 @param methodName Name of the method.
547 @param ses Pointer to the current application session.
548 @param reqId The request id of the request invoking the method.
549 @param params Pointer to a jsonObject encoding the parameters to the method.
550 @return Zero if successful, or -1 upon failure.
552 If we can't find a function corresponding to the method, or if we call it and it returns
553 a negative return code, send a STATUS message to the client to report an exception.
555 A return code of -1 means that the @a appName, @a methodName, or @a ses parameter was NULL.
557 int osrfAppRunMethod( const char* appName, const char* methodName,
558 osrfAppSession* ses, int reqId, jsonObject* params ) {
560 if( !(appName && methodName && ses) ) return -1;
562 // Find the application, and then find the method for it
563 osrfApplication* app = _osrfAppFindApplication(appName);
565 return osrfAppRequestRespondException( ses,
566 reqId, "Application not found: %s", appName );
568 osrfMethod* method = osrfAppFindMethod( app, methodName );
570 return osrfAppRequestRespondException( ses, reqId,
571 "Method [%s] not found for service %s", methodName, appName );
573 #ifdef OSRF_STRICT_PARAMS
574 if( method->argc > 0 ) {
575 // Make sure that the client has passed at least the minimum number of arguments.
576 if(!params || params->type != JSON_ARRAY || params->size < method->argc )
577 return osrfAppRequestRespondException( ses, reqId,
578 "Not enough params for method %s / service %s", methodName, appName );
582 // Build an osrfMethodContext, which we will pass by pointer to the function.
583 osrfMethodContext context;
585 context.session = ses;
586 context.method = method;
587 context.params = params;
588 context.request = reqId;
589 context.responses = NULL;
593 if( method->options & OSRF_METHOD_SYSTEM ) {
594 retcode = _osrfAppRunSystemMethod(&context);
598 // Function pointer through which we will call the function dynamically
599 int (*meth) (osrfMethodContext*);
601 // Open the function that implements the method
602 meth = dlsym(app->handle, method->symbol);
604 const char* error = dlerror();
605 if( error != NULL ) {
606 return osrfAppRequestRespondException( ses, reqId,
607 "Unable to execute method [%s] for service %s", methodName, appName );
611 retcode = meth( &context );
615 return osrfAppRequestRespondException(
616 ses, reqId, "An unknown server error occurred" );
618 retcode = _osrfAppPostProcess( &context, retcode );
620 if( context.responses )
621 jsonObjectFree( context.responses );
626 @brief Either send or enqueue a response to a client.
627 @param ctx Pointer to the current method context.
628 @param data Pointer to the response, in the form of a jsonObject.
629 @return Zero if successful, or -1 upon error. The only recognized errors are if either
630 the @a context pointer or its method pointer is NULL.
632 For an atomic method, add a copy of the response data to a cache within the method
633 context, to be sent later. Otherwise, send a RESULT message to the client, with the
636 Note that, for an atomic method, this function is equivalent to osrfAppRespondComplete():
637 we send the STATUS message after the method returns, and not before.
639 int osrfAppRespond( osrfMethodContext* ctx, const jsonObject* data ) {
640 return _osrfAppRespond( ctx, data, 0 );
644 @brief Either send or enqueue a response to a client, with a completion notice.
645 @param context Pointer to the current method context.
646 @param data Pointer to the response, in the form of a jsonObject.
647 @return Zero if successful, or -1 upon error. The only recognized errors are if either
648 the @a context pointer or its method pointer is NULL.
650 For an atomic method, add a copy of the response data to a cache within the method
651 context, to be sent later. Otherwise, send a RESULT message to the client, with the
652 results in @a data. Also send a STATUS message to indicate that the response is complete.
654 Note that, for an atomic method, this function is equivalent to osrfAppRespond(): we
655 send the STATUS message after the method returns, and not before.
657 int osrfAppRespondComplete( osrfMethodContext* context, const jsonObject* data ) {
658 return _osrfAppRespond( context, data, 1 );
662 @brief Send any response messages that have accumulated in the output buffer.
663 @param ses Pointer to the current application session.
664 @param outbuf Pointer to the output buffer.
665 @return Zero if successful, or -1 if not.
667 Used only by servers to respond to clients.
669 static int flush_responses( osrfAppSession* ses, growing_buffer* outbuf ) {
671 // Collect any inbound traffic on the socket(s). This doesn't accomplish anything for the
672 // immediate task at hand, but it may help to keep TCP from getting clogged in some cases.
673 osrf_app_session_queue_wait( ses, 0, NULL );
676 if( buffer_length( outbuf ) > 0 ) { // If there's anything to send...
677 buffer_add_char( outbuf, ']' ); // Close the JSON array
678 if( osrfSendTransportPayload( ses, OSRF_BUFFER_C_STR( ses->outbuf ))) {
679 osrfLogError( OSRF_LOG_MARK, "Unable to flush response buffer" );
683 buffer_reset( ses->outbuf );
688 @brief Add a message to an output buffer.
689 @param outbuf Pointer to the output buffer.
690 @param msg Pointer to the message to be added, in the form of a JSON string.
692 Since the output buffer is in the form of a JSON array, prepend a left bracket to the
693 first message, and a comma to subsequent ones.
695 Used only by servers to respond to clients.
697 static inline void append_msg( growing_buffer* outbuf, const char* msg ) {
698 if( outbuf && msg ) {
699 char prefix = buffer_length( outbuf ) > 0 ? ',' : '[';
700 buffer_add_char( outbuf, prefix );
701 buffer_add( outbuf, msg );
706 @brief Either send or enqueue a response to a client, optionally with a completion notice.
707 @param ctx Pointer to the method context.
708 @param data Pointer to the response, in the form of a jsonObject.
709 @param complete Boolean: if true, we will accompany the RESULT message with a STATUS
710 message indicating that the response is complete.
711 @return Zero if successful, or -1 upon error.
713 For an atomic method, add a copy of the response data to a cache within the method
714 context, to be sent later. In this case the @a complete parameter has no effect,
715 because we'll send the STATUS message later when we send the cached results.
717 If the method is not atomic, translate the message into JSON and append it to a buffer,
718 flushing the buffer as needed to avoid overflow. If @a complete is true, append
719 a STATUS message (as JSON) to the buffer and flush the buffer.
721 static int _osrfAppRespond( osrfMethodContext* ctx, const jsonObject* data, int complete ) {
722 if(!(ctx && ctx->method)) return -1;
724 if( ctx->method->options & OSRF_METHOD_ATOMIC ) {
725 osrfLogDebug( OSRF_LOG_MARK,
726 "Adding responses to stash for atomic method %s", ctx->method->name );
728 // If we don't already have one, create a JSON_ARRAY to serve as a cache.
729 if( ctx->responses == NULL )
730 ctx->responses = jsonNewObjectType( JSON_ARRAY );
732 // Add a copy of the data object to the cache.
734 jsonObjectPush( ctx->responses, jsonObjectClone(data) );
736 osrfLogDebug( OSRF_LOG_MARK,
737 "Adding responses to stash for method %s", ctx->method->name );
740 // If you want to flush the intput buffers for every output message,
741 // this is the place to do it.
742 //osrf_app_session_queue_wait( ctx->session, 0, NULL );
744 // Create an OSRF message
745 osrfMessage* msg = osrf_message_init( RESULT, ctx->request, 1 );
746 osrf_message_set_status_info( msg, NULL, "OK", OSRF_STATUS_OK );
747 osrf_message_set_result( msg, data );
749 // Serialize the OSRF message into JSON text
750 char* json = jsonObjectToJSON( osrfMessageToJSON( msg ));
751 osrfMessageFree( msg );
753 // If the new message would overflow the buffer, flush the output buffer first
754 int len_so_far = buffer_length( ctx->session->outbuf );
755 if( len_so_far && (strlen( json ) + len_so_far + 3 >= ctx->method->bufsize )) {
756 if( flush_responses( ctx->session, ctx->session->outbuf ))
760 // Append the JSON text to the output buffer
761 append_msg( ctx->session->outbuf, json );
766 // Create a STATUS message
767 osrfMessage* status_msg = osrf_message_init( STATUS, ctx->request, 1 );
768 osrf_message_set_status_info( status_msg, "osrfConnectStatus", "Request Complete",
769 OSRF_STATUS_COMPLETE );
771 // Serialize the STATUS message into JSON text
772 char* json = jsonObjectToJSON( osrfMessageToJSON( status_msg ));
773 osrfMessageFree( status_msg );
775 // Add the STATUS message to the output buffer.
776 // It's short, so don't worry about avoiding overflow.
777 append_msg( ctx->session->outbuf, json );
780 // Flush the output buffer, sending any accumulated messages.
781 if( flush_responses( ctx->session, ctx->session->outbuf ))
790 @brief Finish up the processing of a request.
791 @param ctx Pointer to the method context.
792 @param retcode The return code from the method's function.
793 @return 0 if successfull, or -1 upon error.
795 For an atomic method: send whatever responses we have been saving up, together with a
796 STATUS message to say that we're finished.
798 For a non-atomic method: if the return code from the method is greater than zero, just
799 send the STATUS message. If the return code is zero, do nothing; the method presumably
800 sent the STATUS message on its own.
802 static int _osrfAppPostProcess( osrfMethodContext* ctx, int retcode ) {
803 if(!(ctx && ctx->method)) return -1;
805 osrfLogDebug( OSRF_LOG_MARK, "Postprocessing method %s with retcode %d",
806 ctx->method->name, retcode );
809 // We have cached atomic responses to return, collected in a JSON ARRAY (we
810 // haven't sent any responses yet). Now send them all at once, followed by
811 // a STATUS message to say that we're finished.
812 osrfAppRequestRespondComplete( ctx->session, ctx->request, ctx->responses );
815 // We have no cached atomic responses to return, but we may have some
816 // non-atomic messages waiting in the buffer.
818 // Send a STATUS message to say that we're finished, and to force a
819 // final flush of the buffer.
820 osrfAppRespondComplete( ctx, NULL );
827 @brief Send a STATUS message to the client, notifying it of an error.
828 @param ses Pointer to the current application session.
829 @param request Request ID of the request.
830 @param msg A printf-style format string defining an explanatory message to be sent to
831 the client. Subsequent parameters, if any, will be formatted and inserted into the
832 resulting output string.
833 @return -1 if the @a ses parameter is NULL; otherwise zero.
835 int osrfAppRequestRespondException( osrfAppSession* ses, int request, const char* msg, ... ) {
838 VA_LIST_TO_STRING(msg);
839 osrfLogWarning( OSRF_LOG_MARK, "Returning method exception with message: %s", VA_BUF );
840 osrfAppSessionStatus( ses, OSRF_STATUS_NOTFOUND, "osrfMethodException", request, VA_BUF );
845 @brief Introspect a specified method.
846 @param ctx Pointer to the method context.
847 @param method Pointer to the osrfMethod for the specified method.
848 @param resp Pointer to the jsonObject into which method information will be placed.
850 Treating the @a resp object as a JSON_HASH, insert entries for various bits of information
851 about the specified method.
853 static void _osrfAppSetIntrospectMethod( osrfMethodContext* ctx, const osrfMethod* method,
855 if(!(ctx && resp)) return;
857 jsonObjectSetKey(resp, "api_name", jsonNewObject(method->name));
858 jsonObjectSetKey(resp, "method", jsonNewObject(method->symbol));
859 jsonObjectSetKey(resp, "service", jsonNewObject(ctx->session->remote_service));
860 jsonObjectSetKey(resp, "notes", jsonNewObject(method->notes));
861 jsonObjectSetKey(resp, "argc", jsonNewNumberObject(method->argc));
863 jsonObjectSetKey(resp, "sysmethod",
864 jsonNewNumberObject( (method->options & OSRF_METHOD_SYSTEM) ? 1 : 0 ));
865 jsonObjectSetKey(resp, "atomic",
866 jsonNewNumberObject( (method->options & OSRF_METHOD_ATOMIC) ? 1 : 0 ));
867 jsonObjectSetKey(resp, "cachable",
868 jsonNewNumberObject( (method->options & OSRF_METHOD_CACHABLE) ? 1 : 0 ));
872 @brief Run the requested system method.
873 @param ctx The method context.
874 @return Zero if the method is run successfully; -1 if the method was not run; 1 if the
875 method was run and the application code now needs to send a 'request complete' message.
877 A system method is a well known method implemented here for all servers. Instead of
878 looking in the shared object, branch on the method name and call the corresponding
881 static int _osrfAppRunSystemMethod(osrfMethodContext* ctx) {
882 if( osrfMethodVerifyContext( ctx ) < 0 ) {
883 osrfLogError( OSRF_LOG_MARK, "_osrfAppRunSystemMethod: Received invalid method context" );
887 if( !strcmp(ctx->method->name, OSRF_SYSMETHOD_INTROSPECT_ALL ) ||
888 !strcmp(ctx->method->name, OSRF_SYSMETHOD_INTROSPECT_ALL_ATOMIC )) {
889 return osrfAppIntrospectAll(ctx);
892 if( !strcmp(ctx->method->name, OSRF_SYSMETHOD_INTROSPECT ) ||
893 !strcmp(ctx->method->name, OSRF_SYSMETHOD_INTROSPECT_ATOMIC )) {
894 return osrfAppIntrospect(ctx);
897 if( !strcmp(ctx->method->name, OSRF_SYSMETHOD_ECHO ) ||
898 !strcmp(ctx->method->name, OSRF_SYSMETHOD_ECHO_ATOMIC )) {
899 return osrfAppEcho(ctx);
902 osrfAppRequestRespondException( ctx->session,
903 ctx->request, "System method implementation not found");
909 @brief Run the introspect method for a specified method or group of methods.
910 @param ctx Pointer to the method context.
911 @return 1 if successful, or if no search target is specified as a parameter; -1 if unable
912 to find a pointer to the application.
914 Traverse the list of methods, and report on each one whose name starts with the specified
915 search target. In effect, the search target ends with an implicit wild card.
917 static int osrfAppIntrospect( osrfMethodContext* ctx ) {
919 // Get the name of the method to introspect
920 const char* methodSubstring = jsonObjectGetString( jsonObjectGetIndex(ctx->params, 0) );
921 if( !methodSubstring )
922 return 1; /* respond with no methods */
924 // Get a pointer to the application
925 osrfApplication* app = _osrfAppFindApplication( ctx->session->remote_service );
927 return -1; // Oops, no application...
930 osrfHashIterator* itr = osrfNewHashIterator(app->methods);
933 while( (method = osrfHashIteratorNext(itr)) ) {
934 if( (len = strlen(methodSubstring)) <= strlen(method->name) ) {
935 if( !strncmp( method->name, methodSubstring, len) ) {
936 jsonObject* resp = jsonNewObject(NULL);
937 _osrfAppSetIntrospectMethod( ctx, method, resp );
938 osrfAppRespond(ctx, resp);
939 jsonObjectFree(resp);
944 osrfHashIteratorFree(itr);
949 @brief Run the implement_all method.
950 @param ctx Pointer to the method context.
951 @return 1 if successful, or -1 if unable to find a pointer to the application.
953 Report on all of the methods of the application.
955 static int osrfAppIntrospectAll( osrfMethodContext* ctx ) {
956 osrfApplication* app = _osrfAppFindApplication( ctx->session->remote_service );
959 osrfHashIterator* itr = osrfNewHashIterator(app->methods);
961 while( (method = osrfHashIteratorNext(itr)) ) {
962 jsonObject* resp = jsonNewObject(NULL);
963 _osrfAppSetIntrospectMethod( ctx, method, resp );
964 osrfAppRespond(ctx, resp);
965 jsonObjectFree(resp);
967 osrfHashIteratorFree(itr);
974 @brief Run the echo method.
975 @param ctx Pointer to the method context.
976 @return -1 if the method context is invalid or corrupted; otherwise 1.
978 Send the client a copy of each parameter.
980 static int osrfAppEcho( osrfMethodContext* ctx ) {
981 if( osrfMethodVerifyContext( ctx ) < 0 ) {
982 osrfLogError( OSRF_LOG_MARK, "osrfAppEcho: Received invalid method context" );
987 for( i = 0; i < ctx->params->size; i++ ) {
988 const jsonObject* str = jsonObjectGetIndex(ctx->params,i);
989 osrfAppRespond(ctx, str);
995 @brief Perform a series of sanity tests on an osrfMethodContext.
996 @param ctx Pointer to the osrfMethodContext to be checked.
997 @return Zero if the osrfMethodContext passes all tests, or -1 if it doesn't.
999 int osrfMethodVerifyContext( osrfMethodContext* ctx )
1002 osrfLogError( OSRF_LOG_MARK, "Context is NULL in app request" );
1006 if( !ctx->session ) {
1007 osrfLogError( OSRF_LOG_MARK, "Session is NULL in app request" );
1013 osrfLogError( OSRF_LOG_MARK, "Method is NULL in app request" );
1017 if( ctx->method->argc ) {
1018 if( !ctx->params ) {
1019 osrfLogError( OSRF_LOG_MARK,
1020 "Params is NULL in app request %s", ctx->method->name );
1023 if( ctx->params->type != JSON_ARRAY ) {
1024 osrfLogError( OSRF_LOG_MARK,
1025 "'params' is not a JSON array for method %s", ctx->method->name );
1030 if( !ctx->method->name ) {
1031 osrfLogError( OSRF_LOG_MARK, "Method name is NULL" );
1035 // Log the call, with the method and parameters
1036 char* params_str = jsonObjectToJSON( ctx->params );
1038 osrfLogInfo( OSRF_LOG_MARK, "CALL:\t%s %s - %s",
1039 ctx->session->remote_service, ctx->method->name, params_str );
1046 @brief Free an osrfMethod.
1047 @param name Name of the method (not used).
1048 @param p Void pointer pointing to the osrfMethod.
1050 This function is designed to be installed as a callback for an osrfHash (hence the
1051 unused @a name parameter and the void pointer).
1053 static void osrfMethodFree( char* name, void* p ) {
1054 osrfMethod* method = p;
1056 free( method->name );
1057 free( method->symbol );
1058 free( method->notes );
1064 @brief Free an osrfApplication
1065 @param name Name of the application (not used).
1066 @param p Void pointer pointing to the osrfApplication.
1068 This function is designed to be installed as a callback for an osrfHash (hence the
1069 unused @a name parameter and the void pointer).
1071 static void osrfAppFree( char* name, void* p ) {
1072 osrfApplication* app = p;
1074 dlclose( app->handle );
1075 osrfHashFree( app->methods );