+ if (mon_req_opt_count(req) == 0) {
+ /* call every handler that matches the command */
+ cookie.opt_type = OPT_TYPE_ANY;
+ g_ptr_array_foreach(mons->handlers, request_helper, &cookie);
+ } else {
+ /* call only those handlers that match an option */
+ for (ii=0; ii < mon_req_opt_count(req); ii++) {
+ cookie.opt_type = mon_req_opt_index(req, ii)->type;
+ /* Loop over all handlers - we know we can only have one match for each opt type */
+ g_ptr_array_foreach(mons->handlers, request_helper, &cookie);
+ }
+ }
+
+ /* We now have an array of results in cookie.results. If any of these failed, return an error. */
+ tr_debug("mons_handle_request: Examining %d handler results", cookie.results->len);
+ resp->code = MON_RESP_SUCCESS; /* tentatively set this to success */
+ for (ii=0; ii < cookie.results->len; ii++) {
+ struct handler_result *this = &g_array_index(cookie.results, struct handler_result, ii);
+ if (this->rc != MON_SUCCESS) {
+ tr_debug("mons_handle_request: Result %d was an error.", ii);
+ resp->code = MON_RESP_ERROR;
+ }
+
+ /* add the JSON response even if there was an error */
+ if (this->json_data) {
+ tr_debug("mons_handle_request: Result %d returned JSON data.", ii);
+ json_object_set_new(payload, mon_opt_type_to_string(this->opt_type), this->json_data);
+ }
+ }
+
+ if (resp->code == MON_RESP_SUCCESS) {
+ if (mon_resp_set_message(resp, "success") == 0) {
+ /* Failed to set the response message to success - fail ironically, don't send
+ * an inconsistent response. */
+ tr_crit("mons_handle_request: Error setting response message to 'success'.");
+ goto cleanup;
+ }
+ } else {
+ /* Failed - send a response indicating that the overall command succeeded */
+ if (mon_resp_set_message(resp, "request processed but an error occurred") == 0) {
+ tr_crit("mons_handle_request: Error setting response message after a handler error.");
+ goto cleanup;
+ }
+ }
+
+ /* Attach the accumulated payload to the response */
+ if (json_object_size(payload) > 0) {
+ tr_debug("mons_handle_request: Attaching payload to response.");
+ mon_resp_set_payload(resp, payload);
+ }
+
+ tr_debug("mons_handle_request: Successfully processed request.");
+
+cleanup:
+ if (payload)
+ json_decref(payload);
+ if (cookie.results)
+ g_array_free(cookie.results, TRUE);
+ return resp;