Fix a deadlock when receiving shutdown mode
[profile/ivi/persistence-client-library.git] / src / persistence_client_library_dbus_cmd.c
1 /******************************************************************************
2  * Project         Persistency
3  * (c) copyright   2012
4  * Company         XS Embedded GmbH
5  *****************************************************************************/
6 /******************************************************************************
7  * This Source Code Form is subject to the terms of the
8  * Mozilla Public License, v. 2.0. If a  copy of the MPL was not distributed
9  * with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 ******************************************************************************/
11  /**
12  * @file           persistence_client_library_dbus_cmd.c
13  * @ingroup        Persistence client library
14  * @author         Ingo Huerner
15  * @brief          Implementation of the persistence client library dbus commands.
16  * @see
17  */
18
19 #include "persistence_client_library_dbus_cmd.h"
20
21 #include "persistence_client_library_handle.h"
22 #include "persistence_client_library_itzam_errors.h"
23 #include "persistence_client_library_custom_loader.h"
24 #include "persistence_client_library_prct_access.h"
25
26 #include "../include_protected/persistence_client_library_data_organization.h"
27 #include "../include_protected/persistence_client_library_db_access.h"
28
29 #include <itzam.h>
30
31
32 // function prototype
33 void msg_pending_func(DBusPendingCall *call, void *data);
34
35
36
37 void process_reg_notification_signal(DBusConnection* conn)
38 {
39    char ruleChanged[DbusMatchRuleSize] = {0};
40    char ruleDeleted[DbusMatchRuleSize] = {0};
41    char ruleCreated[DbusMatchRuleSize] = {0};
42
43    // add match for  c h a n g e
44    snprintf(ruleChanged, DbusMatchRuleSize,
45             "type='signal',interface='org.genivi.persistence.adminconsumer',member='PersistenceResChange',path='/org/genivi/persistence/adminconsumer',arg0='%s',arg1='%u',arg2='%u',arg3='%u'",
46             gNotifykey, gNotifyLdbid, gNotifyUserNo, gNotifySeatNo);
47
48    // add match for  d e l e t e
49    snprintf(ruleDeleted, DbusMatchRuleSize,
50             "type='signal',interface='org.genivi.persistence.adminconsumer',member='PersistenceResDelete',path='/org/genivi/persistence/adminconsumer',arg0='%s',arg1='%u',arg2='%u',arg3='%u'",
51             gNotifykey, gNotifyLdbid, gNotifyUserNo, gNotifySeatNo);
52
53    // add match for  c r e a t e
54    snprintf(ruleCreated, DbusMatchRuleSize,
55             "type='signal',interface='org.genivi.persistence.adminconsumer',member='PersistenceResCreate',path='/org/genivi/persistence/adminconsumer',arg0='%s',arg1='%u',arg2='%u',arg3='%u'",
56             gNotifykey, gNotifyLdbid, gNotifyUserNo, gNotifySeatNo);
57
58    if(gNotifyPolicy == Notify_register)
59    {
60       dbus_bus_add_match(conn, ruleChanged, NULL);
61       dbus_bus_add_match(conn, ruleDeleted, NULL);
62       dbus_bus_add_match(conn, ruleCreated, NULL);
63    }
64    else if(gNotifyPolicy == Notify_unregister)
65    {
66       dbus_bus_remove_match(conn, ruleChanged, NULL);
67       dbus_bus_remove_match(conn, ruleDeleted, NULL);
68       dbus_bus_remove_match(conn, ruleCreated, NULL);
69    }
70
71    dbus_connection_flush(conn);  // flush the connection to add the match
72 }
73
74
75
76 void process_send_notification_signal(DBusConnection* conn)
77 {
78    dbus_bool_t ret;
79    DBusMessage* message;
80    const char* notifyReason = NULL;
81
82    char ldbidArray[DbusSubMatchSize] = {0};
83    char userArray[DbusSubMatchSize]  = {0};
84    char seatArray[DbusSubMatchSize]  = {0};
85    char* pldbidArra = ldbidArray;
86    char* puserArray = userArray;
87    char* pseatArray = seatArray;
88    char* pnotifyKey = gNotifykey;
89
90    switch(gNotifyReason)
91    {
92       case pclNotifyStatus_deleted:
93          notifyReason = gDeleteSignal;
94          break;
95       case  pclNotifyStatus_created:
96          notifyReason = gCreateSignal;
97          break;
98       case pclNotifyStatus_changed:
99          notifyReason = gChangeSignal;
100          break;
101       default:
102          notifyReason = NULL;
103          break;
104    }
105
106    if(notifyReason != NULL)
107    {
108       // dbus_bus_add_match is used for the notification mechanism,
109       // and this works only for type DBUS_TYPE_STRING as message arguments
110       // this is the reason to use string instead of integer types directly
111       snprintf(ldbidArray, DbusSubMatchSize, "%u", gNotifyLdbid);
112       snprintf(userArray,  DbusSubMatchSize, "%u", gNotifyUserNo);
113       snprintf(seatArray,  DbusSubMatchSize, "%u", gNotifySeatNo);
114
115       //printf("process_send_Notification_Signal => key: %s | lbid: %d | gUserNo: %d | gSeatNo: %d | gReason: %d \n", gNotifykey, gLdbid, gUserNo, gSeatNo, gReason);
116       message = dbus_message_new_signal("/org/genivi/persistence/adminconsumer",    // const char *path,
117                                         "org.genivi.persistence.adminconsumer",     // const char *interface,
118                                         notifyReason);                                 // const char *name
119
120       ret = dbus_message_append_args(message, DBUS_TYPE_STRING, &pnotifyKey,
121                                               DBUS_TYPE_STRING, &pldbidArra,
122                                               DBUS_TYPE_STRING, &puserArray,
123                                               DBUS_TYPE_STRING, &pseatArray,
124                                               DBUS_TYPE_INVALID);
125       if(ret == TRUE)
126       {
127          // Send the signal
128          if(conn != NULL)
129          {
130             if(dbus_connection_send(conn, message, 0) == TRUE)
131             {
132                // Free the signal now we have finished with it
133                dbus_message_unref(message);
134             }
135             else
136             {
137                DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("process_send_Notification_Signal ==> failed to send dbus message!!"));
138             }
139          }
140          else
141          {
142             DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("process_send_Notification_Signal ==> E R R O R  C O N E C T I O N  NULL!!"));
143          }
144       }
145       else
146       {
147          DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("process_send_Notification_Signal ==> ERROR dbus_message_append_args"));
148       }
149    }
150    else
151    {
152       DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("process_send_Notification_Signal ==> ERROR invalid notification reason"));
153    }
154 }
155
156
157
158 void process_block_and_write_data_back(unsigned int requestID, unsigned int status)
159 {
160    // lock persistence data access
161    pers_lock_access();
162    // sync data back to memory device
163    pers_data_sync();
164    // send complete notification
165    pers_admin_service_data_sync_complete(requestID, status);
166 }
167
168
169
170 void process_prepare_shutdown(unsigned char requestId, unsigned int status)
171 {
172    int i = 0;
173    itzam_btree* resourceTable = NULL;
174    itzam_state  state = ITZAM_FAILED;
175
176    // block write
177    pers_lock_access();
178
179    // flush open files to disk
180    for(i=0; i<MaxPersHandle; i++)
181    {
182       int tmp = i;
183       if(gOpenFdArray[tmp] == FileOpen)
184       {
185          fsync(tmp);
186          close(tmp);
187       }
188    }
189
190    // close open gvdb persistence resource configuration table
191    for(i=0; i< PrctDbTableSize; i++)
192    {
193      resourceTable = get_resource_cfg_table_by_idx(i);
194      // dereference opend database
195      if(resourceTable != NULL &&  get_resource_cfg_table_status(i) == 1)
196      {
197         state = itzam_btree_close(resourceTable);
198         invalidate_resource_cfg_table(i);
199         if (state != ITZAM_OKAY)
200         {
201            DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("process_prepare_shutdown => itzam_btree_close: Itzam problem"), DLT_STRING(STATE_MESSAGES[state]));
202         }
203      }
204    }
205
206    //close opend database
207    pers_db_close_all();
208
209
210    // unload custom client libraries
211    for(i=0; i<PersCustomLib_LastEntry; i++)
212    {
213       if(gPersCustomFuncs[i].custom_plugin_deinit != NULL)
214       {
215          // deinitialize plugin
216          gPersCustomFuncs[i].custom_plugin_deinit();
217          // close library handle
218          dlclose(gPersCustomFuncs[i].handle);
219
220          gPersCustomFuncs[i].custom_plugin_deinit = NULL;
221       }
222    }
223
224    // notify lifecycle shutdown OK
225    send_prepare_shutdown_complete((int)requestId, (int)status);
226 }
227
228
229
230 void process_send_pas_request(DBusConnection* conn, unsigned int requestID, int status)
231 {
232    DBusError error;
233    DBusPendingCall* pending = NULL;
234    dbus_error_init (&error);
235    int rval = 0;
236
237    DBusMessage* message = dbus_message_new_method_call("org.genivi.persistence.admin",       // destination
238                                                       "/org/genivi/persistence/admin",       // path
239                                                        "org.genivi.persistence.admin",       // interface
240                                                        "PersistenceAdminRequestCompleted");  // method
241    if(message != NULL)
242    {
243       dbus_message_append_args(message, DBUS_TYPE_UINT32, &requestID,
244                                         DBUS_TYPE_INT32,  &status,
245                                         DBUS_TYPE_INVALID);
246
247       if(conn != NULL)
248       {
249          //replyMsg = dbus_connection_send_with_reply_and_block(conn, message, gTimeoutMs, &error);
250          dbus_connection_send_with_reply(conn,        //    the connection
251                                          message,       // the message to write
252                                          &pending,      // pending
253                                          gTimeoutMs);   // timeout in milliseconds or -1 for default
254
255          dbus_connection_flush(conn);
256
257          if(!dbus_pending_call_set_notify(pending, msg_pending_func, "PersistenceAdminRequestCompleted", NULL))
258          {
259             DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("process_send_pas_request => dbus_pending_call_set_notify: FAILED\n"));
260          }
261          dbus_pending_call_unref(pending);
262       }
263       else
264       {
265          DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("send_pas_request => ERROR: Invalid connection") );
266       }
267       dbus_message_unref(message);
268    }
269    else
270    {
271       DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("send_pas_request => ERROR: Invalid message") );
272    }
273 }
274
275
276 void process_send_pas_register(DBusConnection* conn, int regType, int notificationFlag)
277 {
278    DBusError error;
279    dbus_error_init (&error);
280    DBusPendingCall* pending = NULL;
281
282    char* method = NULL;
283
284    if(regType == 0)
285       method = "UnRegisterPersAdminNotification";
286    else if(regType == 1)
287       method = "RegisterPersAdminNotification";
288
289    if(conn != NULL)
290    {
291       const char* objName = "/org/genivi/persistence/adminconsumer";
292       const char* busName = dbus_bus_get_unique_name(conn);
293
294       if(busName != NULL)
295       {
296          DBusMessage* message = dbus_message_new_method_call("org.genivi.persistence.admin",    // destination
297                                                             "/org/genivi/persistence/admin",    // path
298                                                              "org.genivi.persistence.admin",    // interface
299                                                              method);                           // method
300
301          if(message != NULL)
302          {
303             dbus_message_append_args(message, DBUS_TYPE_STRING, &busName,  // bus name
304                                               DBUS_TYPE_STRING, &objName,
305                                               DBUS_TYPE_INT32,  &notificationFlag,
306                                               DBUS_TYPE_UINT32, &gTimeoutMs,
307                                               DBUS_TYPE_INVALID);
308
309             dbus_connection_send_with_reply(conn,           //    the connection
310                                             message,        // the message to write
311                                             &pending,       // pending
312                                             gTimeoutMs);    // timeout in milliseconds or -1 for default
313
314             dbus_connection_flush(conn);
315
316             if(!dbus_pending_call_set_notify(pending, msg_pending_func, method, NULL))
317             {
318                printf("process_send_pas_register => dbus_pending_call_set_notify: FAILED\n");
319             }
320             dbus_pending_call_unref(pending);
321          }
322          else
323          {
324             DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("send_pas_register =>  ERROR: Invalid message") );
325          }
326          dbus_message_unref(message);
327       }
328       else
329       {
330          DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("send_pas_register =>  ERROR: Invalid busname") );
331       }
332    }
333    else
334    {
335       DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("send_pas_register =>  ERROR: Invalid connection") );
336    }
337 }
338
339
340 void process_send_lifecycle_register(DBusConnection* conn, int regType, int shutdownMode)
341 {
342    int rval = 0;
343
344    DBusError error;
345    dbus_error_init (&error);
346
347    char* method = NULL;
348
349    if(regType == 1)
350       method = "RegisterShutdownClient";
351    else if(regType == 0)
352       method = "UnRegisterShutdownClient";
353
354    if(conn != NULL)
355    {
356       const char* objName = "/org/genivi/NodeStateManager/LifeCycleConsumer";
357       const char* busName = dbus_bus_get_unique_name(conn);
358
359       DBusMessage* message = dbus_message_new_method_call("org.genivi.NodeStateManager",           // destination
360                                                           "/org/genivi/NodeStateManager/Consumer", // path
361                                                           "org.genivi.NodeStateManager.Consumer",  // interface
362                                                           method);                                 // method
363       if(message != NULL)
364       {
365          if(regType == 1)   // register
366          {
367             dbus_message_append_args(message, DBUS_TYPE_STRING, &busName,
368                                               DBUS_TYPE_STRING, &objName,
369                                               DBUS_TYPE_UINT32, &shutdownMode,
370                                               DBUS_TYPE_UINT32, &gTimeoutMs, DBUS_TYPE_INVALID);
371          }
372          else           // unregister
373          {
374             dbus_message_append_args(message, DBUS_TYPE_STRING, &busName,
375                                               DBUS_TYPE_STRING, &objName,
376                                               DBUS_TYPE_UINT32, &shutdownMode, DBUS_TYPE_INVALID);
377          }
378
379                  if(!dbus_connection_send(conn, message, 0))
380                  {
381                     DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("send_lifecycle_register => Access denied"), DLT_STRING(error.message) );
382                     rval = -1;
383                  }
384                  dbus_connection_flush(conn);
385          dbus_message_unref(message);
386       }
387       else
388       {
389          DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("send_lifecycle_register => ERROR: Invalid message"));
390       }
391    }
392    else
393    {
394       DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("send_lifecycle_register => ERROR: connection isn NULL"));
395    }
396 }
397
398
399
400 void process_send_lifecycle_request(DBusConnection* conn, int requestId, int status)
401 {
402    int rval = 0;
403    DBusError error;
404    dbus_error_init (&error);
405
406    if(conn != NULL)
407    {
408       DBusMessage* message = dbus_message_new_method_call("org.genivi.NodeStateManager",           // destination
409                                                          "/org/genivi/NodeStateManager/Consumer",  // path
410                                                           "org.genivi.NodeStateManager.Consumer",  // interface
411                                                           "LifecycleRequestComplete");             // method
412       if(message != NULL)
413       {
414          dbus_message_append_args(message, DBUS_TYPE_INT32, &requestId,
415                                            DBUS_TYPE_INT32, &status,
416                                            DBUS_TYPE_INVALID);
417
418
419                  if(!dbus_connection_send(conn, message, 0))
420                  {
421                     DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("send_lifecycle_request => Access denied"), DLT_STRING(error.message) );
422                     rval = -1;
423                  }
424
425                  dbus_connection_flush(conn);
426          dbus_message_unref(message);
427       }
428       else
429       {
430          DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("send_lifecycle_request => ERROR: Invalid message"));
431          rval = -1;
432       }
433    }
434    else
435    {
436       DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("send_lifecycle_request => ERROR: connection isn NULL"));
437       rval = -1;
438    }
439 }
440
441
442
443 void msg_pending_func(DBusPendingCall *call, void *data)
444 {
445    int replyArg = -1;
446    DBusError err;
447    dbus_error_init(&err);
448
449    DBusMessage *message = dbus_pending_call_steal_reply(call);
450
451    if (dbus_set_error_from_message(&err, message))
452    {
453       DLT_LOG(gDLTContext, DLT_LOG_ERROR, DLT_STRING("msg_pending_func ==> Access denied") );
454    }
455    else
456    {
457       //DLT_LOG(gDLTContext, DLT_LOG_INFO, DLT_STRING("msg_pending_func ==> UNlock mutex") );
458       dbus_message_get_args(message, &err, DBUS_TYPE_INT32, &replyArg, DBUS_TYPE_INVALID);
459    }
460
461    gDbusPendingRvalue = replyArg;   // set the return value
462    dbus_message_unref(message);
463
464    // unlock the mutex because we have received the reply to the dbus message
465    pthread_mutex_unlock(&gDbusPendingRegMtx);
466 }
467
468
469
470