summaryrefslogtreecommitdiff
path: root/Administrator/src/ssw_pers_admin_dbus.c
blob: e24ec9341800eeab943866ec7c587e495361b3db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
/*********************************************************************************************************************
*
* Copyright (C) 2012 Continental Automotive Systems, Inc.
*
* Author: Petrica.Manoila@continental-corporation.com
*
* Implementation of DBus for Persistence Administration Service
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Date       Author             Reason
* 2016-06-02 Cosmin Cernat      Bugzilla Bug 437:  Used glib for watchdog re-triggering
* 2013-09-17 Petrica Manoila    CSP_WZ#5633:       Wait for NSM to start before registration.
* 2013-03-09 Petrica Manoila    CSP_WZ#4480:       Added persadmin_QuitDBusMainLoop function
* 2013-04-04 Petrica Manoila    CSP_WZ#2739:       Moved PAS<->PCL communication to common part under PersCommonIPC.
* 2013.03.26 Petrica Manoila    CSP_WZ#3171:       Update PAS registration to NSM
* 2013.02.15 Petrica Manoila    CSP_WZ#8849:       Modified PAS<->PCL communication interface
* 2013.02.04 Petrica Manoila    CSP_WZ#2211:       Rework for QAC compliancy
* 2012.11.28 Petrica Manoila    CSP_WZ#1280:       Updated implementation according to the updated org.genivi.persistence.admin interface
* 2012.11.13 Petrica Manoila    CSP_WZ#1280:       Initial version
*
**********************************************************************************************************************/ 


#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include <pthread.h>
#include <dlt.h>
#include <systemd/sd-daemon.h>        /* Systemd wdog    */

#include "persComErrors.h"

#include "ssw_pers_admin_dbus.h"
#include "ssw_pers_admin_service.h"
#include "NodeStateTypes.h"
#include "NodeStateConsumer.h"
#include "NodeStateLifecycleConsumer.h"


/**********************************************************************************************************************
*
* Local defines, macros, constants and type definitions.
*
**********************************************************************************************************************/

#define        ONE_SEC_IN_US                             ((uint64_t)1000000)                   /* microseconds */
#define        ONE_SEC_IN_MS                             (uint64_t)(1000)                      /* ms */
#define        PAS_WATCHDOG_TIMEOUT_DEFAULT_VALUE_US    ((uint64_t)(5 * ONE_SEC_IN_US))        /* microseconds */
#define        PAS_SHUTDOWN_TIMEOUT_MS                             (60 * ONE_SEC_IN_MS)        /* 60 sec */

/**********************************************************************************************************************
*
* Global variables. Initialization of global contexts.
*
**********************************************************************************************************************/
DLT_IMPORT_CONTEXT(persAdminSvcDLTCtx);

static GMainLoop                                 *g_pMainLoop                = NIL;
static GDBusConnection                           *g_pBusConnection           = NIL;
static NodeStateLifeCycleConsumerSkeleton        *g_pNSLCSkeleton            = NIL;
static NodeStateConsumerProxy                    *g_pNSCProxy                = NIL;

static volatile bool_t                            g_bDBusConnInit            = false;
static bool_t                                     g_bRegisteredToNSM         = false;    /* registration to NSM status */


/**********************************************************************************************************************
*
* Prototypes for local functions (see implementation for description)
*
**********************************************************************************************************************/

static void OnBusAcquired_cb(    GDBusConnection *connection, const gchar     *name, gpointer user_data);
static void OnNameAcquired_cb(    GDBusConnection *connection, const gchar     *name, gpointer user_data);
static void OnNameLost_cb(    GDBusConnection *connection, const gchar     *name, gpointer     user_data);
static void OnNameAppeared(    GDBusConnection *connection, const gchar     *name, const gchar     *name_owner, gpointer     user_data);


/* LifecycleRequest DBus handler - signature based on generated code */
static gboolean OnHandleLifecycleRequest(NodeStateLifeCycleConsumer   *object,
                                         GDBusMethodInvocation        *invocation,
                                         guint                         arg_Request,
                                         guint                         arg_RequestId);

/* Export NSM Consumer IF on DBus */
static bool_t persadmin_ExportNSMConsumerIF(GDBusConnection *connection);

/**
 * \brief  Get re-trigger rate from environment variable (from .service file)
 *
 * \return re-trigger rate (in seconds)
 **/
static uint32_t persadmin_GetWdogRetriggerRate(void);

/**
 * \brief Performs WDOG re-triggering based on the value defined
 *
 * \param user_data : unused, can be NIL
 *
 * \return TRUE if successfulls, FALSE otherwise
 */
static gboolean persadmin_WDogRetriggerCB(gpointer user_data);


/**********************************************************************************************************************
*
* The function is called when a connection to the D-Bus could be established.
* According to the documentation the objects should be exported here.
*
* \param connection:  Connection, which was acquired
* \param name:        Bus name
* \param user_data:   Optionally user data
*
* \return void
*
**********************************************************************************************************************/
static void OnBusAcquired_cb(GDBusConnection *connection,
                             const gchar     *name,
                             gpointer         user_data)
{
    bool_t    bRetVal;

    DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_INFO, DLT_STRING("Successfully connected to D-Bus."));

    /* Store the connection. */
    g_pBusConnection = connection;

    /* Export the org.genivi.NodeStateManager.LifeCycleConsumer interface over DBus trough the PAS object */
    bRetVal = persadmin_ExportNSMConsumerIF(connection);
    if(true == bRetVal)
    {
        DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_INFO, DLT_STRING("Successfully connected to D-Bus and exported object."));
    }
}



/**********************************************************************************************************************
*
* The function is called when the "bus name" could be acquired on the D-Bus.
*
* \param connection:  Connection over which the bus name was acquired
* \param name:        Acquired bus name
* \param user_data:   Optionally user data
*
* \return void
*
**********************************************************************************************************************/

static void OnNameAcquired_cb(GDBusConnection *connection,
                              const gchar     *name,
                              gpointer         user_data)
{
    uint32_t u32RetriggerRate;

    DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_INFO,     DLT_STRING("Successfully obtained D-Bus name:");
                                                DLT_STRING(name));

    /* Get watchdog retrigger rate */
    u32RetriggerRate = persadmin_GetWdogRetriggerRate();

    /* Add WDOG re-triggering callback */
    g_timeout_add(    u32RetriggerRate * ONE_SEC_IN_MS,
                    &persadmin_WDogRetriggerCB,
                    NIL);

    /* DBus connection initialized */
    g_bDBusConnInit = true;
}



/**********************************************************************************************************************
*
* The function is called if either no connection to D-Bus could be established or
* the bus name could not be acquired.
*
* \param connection:  Connection. If it is NIL, no D-Bus connection could be established.
*                     Otherwise the bus name was lost.
* \param name:        Bus name
* \param user_data:   Optionally user data
*
* \return void
*
**********************************************************************************************************************/
static void OnNameLost_cb(GDBusConnection *connection,
                          const gchar     *name,
                          gpointer         user_data )
{
    if(connection == NIL)
    {
        /* Error: the connection could not be established. */
        DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_ERROR, DLT_STRING("Failed to establish D-Bus connection."));
    }
    else
    {
        /* Error: connection established, but name not obtained. This might be a second instance of the application */
        DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_ERROR,     DLT_STRING("Failed to obtain bus name ");
                                                    DLT_STRING(name);
                                                    DLT_STRING("."));
    }

    /* In both cases leave the main loop. */
    g_main_loop_quit(g_pMainLoop);

    /* DBus connection lost */
    g_bDBusConnInit = false;
}


/**********************************************************************************************************************
*
* Invoked when the name being watched is known to have an owner.
*
* \param connection:  The GDBusConnection the name is being watched on.
* \param name:        The name being watched.
* \param name_owner:  Unique name of the owner of the name being watched.
* \param user_data:   Optionally user data
*
* \return void
*
**********************************************************************************************************************/
static void OnNameAppeared(GDBusConnection *connection,
                           const gchar     *name,
                           const gchar     *name_owner,
                           gpointer         user_data )
{
    GError                *pError         = NIL;
    gboolean            gbRetVal;
    gint                gErrorCode        = NsmErrorStatus_NotSet;

    if(false == g_bRegisteredToNSM)
    {
        /* Register to NSM as shutdown client */
        g_pNSCProxy = NIL;
        g_pNSCProxy = (NodeStateConsumerProxy *) node_state_consumer_proxy_new_sync(g_pBusConnection,
                                                                                    G_DBUS_PROXY_FLAGS_NONE,
                                                                                    NSM_BUS_NAME,
                                                                                    NSM_CONSUMER_OBJECT,
                                                                                    NIL,
                                                                                    &pError);
        if(NIL == g_pNSCProxy)
        {
            DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_DEBUG,     DLT_STRING("Failed to create proxy for NSC. Error :"),
                                                        DLT_STRING(pError->message));

            DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_ERROR,     DLT_STRING("Failed to register to NSM as shutdown client."));
            g_error_free (pError);
        }
        else
        {
            /* Synchronous call to "RegisterShutdownClient" */
            gbRetVal = node_state_consumer_call_register_shutdown_client_sync(    (NodeStateConsumer *)g_pNSCProxy,
                                                                                PERSISTENCE_ADMIN_SVC_BUS_NAME,
                                                                                PERSISTENCE_ADMIN_SVC_OBJ_PATH,
                                                                                NSM_SHUTDOWNTYPE_NORMAL|NSM_SHUTDOWNTYPE_FAST,
                                                                                PAS_SHUTDOWN_TIMEOUT_MS,
                                                                                &gErrorCode,
                                                                                NIL,
                                                                                &pError);
            if(FALSE == gbRetVal)
            {
                DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_DEBUG,     DLT_STRING("RegisterShutdownClient call failed. Error :"),
                                                            DLT_STRING(pError->message));
                DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_ERROR, DLT_STRING("Failed to register to NSM as shutdown client."));

                g_error_free (pError);
                g_object_unref(g_pNSCProxy);
                g_pNSCProxy = NIL;
            }
            else
            {
                if(NsmErrorStatus_Ok != gErrorCode)
                {
                    DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_ERROR,     DLT_STRING("Failed to register to NSM as shutdown client. Error code :"),
                                                                DLT_INT(gErrorCode));
                    g_object_unref(g_pNSCProxy);
                    g_pNSCProxy = NIL;
                }
                else
                {
                    DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_INFO, DLT_STRING("Successfully registered to NSM as shutdown client."));

                    g_bRegisteredToNSM = true;
                }
            }
        }
    }
}

/**********************************************************************************************************************
*
* Handler for LifecycleRequest.
* Signature based on generated code.
*
**********************************************************************************************************************/
static gboolean OnHandleLifecycleRequest(NodeStateLifeCycleConsumer   *object,
                                         GDBusMethodInvocation        *invocation,
                                         guint                         arg_Request,
                                         guint                         arg_RequestId)
{
    DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_INFO,     DLT_STRING("Received NSM shutdown notification."));

    /* send a NsmErrorStatus_ResponsePending response and wait for PAS to
     * finish any operation in progress */
    node_state_life_cycle_consumer_complete_lifecycle_request( object,
                                                               invocation,
                                                               NsmErrorStatus_ResponsePending);


    if( (0 != (NSM_SHUTDOWNTYPE_NORMAL & arg_Request)) ||
        (0 != (NSM_SHUTDOWNTYPE_FAST & arg_Request)))
    {
        /* set shutdown state and wait for the current operation to finish*/
        /* Any other PAS request is denied after this point
         * (unless a cancel shutdown notification is received)
         */
        (void)persadmin_set_shutdown_state(true);
    }
    else
    {
        if(0 != (NSM_SHUTDOWNTYPE_RUNUP & arg_Request))
        {
            (void)persadmin_set_shutdown_state(false);
        }
        else
        {
            DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_WARN,     DLT_STRING("Invalid NSM notification received:"),
                                                        DLT_UINT(arg_Request));
        }
    }


    /* Notify NSM that the request was finished  */
    node_state_consumer_call_lifecycle_request_complete((NodeStateConsumer *)g_pNSCProxy,
                                                        arg_RequestId,
                                                        NsmErrorStatus_Ok,
                                                        NIL,
                                                        NIL,
                                                        NIL);

    DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_INFO,     DLT_STRING("Finished preparing for shutdown."));

    return (TRUE);
}/*DG C8ISQP-ISQP Metric 10-SSW_Administrator_0001*/



/**********************************************************************************************************************
*
* Function that exports the org.genivi.NodeStateManager.LifeCycleConsumer interface over DBus trough the PAS object.
*
* \param connection:  Connection over which the interface should be exported
*
* \return true if successful, false otherwise
*
**********************************************************************************************************************/
static bool_t persadmin_ExportNSMConsumerIF(GDBusConnection *connection)
{
    GError *pError = NIL;

    /* Create object to offer on the DBus (for NSMConsumer) */
    g_pNSLCSkeleton            = (NodeStateLifeCycleConsumerSkeleton*) node_state_life_cycle_consumer_skeleton_new();

    (void)g_signal_connect(g_pNSLCSkeleton, "handle-lifecycle-request", G_CALLBACK(&OnHandleLifecycleRequest), NIL);

    /* Attach interface to the object and export it */
    if(FALSE == g_dbus_interface_skeleton_export(    G_DBUS_INTERFACE_SKELETON(g_pNSLCSkeleton),
                                                    g_pBusConnection,
                                                    PERSISTENCE_ADMIN_SVC_OBJ_PATH,
                                                    &pError))
    {
        /* Error: NSM Consumer object could not be exported. */
        DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_ERROR,     DLT_STRING("Failed to export LifeCycleConsumer interface. Error :"),
                                                    DLT_STRING(pError->message));
        g_error_free(pError);
        return false;
    }

    return true;
}


static uint32_t persadmin_GetWdogRetriggerRate(void)
{
    const char    *sWdogUSec       = NIL;
    uint64_t       u64WdogUSec     = 0;

    sWdogUSec = getenv("WATCHDOG_USEC");
    if(NIL == sWdogUSec)
    {
        /* use default watchdog re-trigger rate */
        u64WdogUSec = PAS_WATCHDOG_TIMEOUT_DEFAULT_VALUE_US;

        DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_INFO,    DLT_STRING("Using default watchdog re-trigger rate :");
                                                    DLT_UINT64(u64WdogUSec / 1000);
                                                    DLT_STRING("ms."));
    }
    else
    {
        u64WdogUSec = strtoul(sWdogUSec, NULL, 10);

        /* The min. valid value for systemd is 1 s => WATCHDOG_USEC at least needs to contain 1.000.000 us */
        if(u64WdogUSec < ONE_SEC_IN_US)
        {
            DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_ERROR,     DLT_STRING("Error: Invalid WDOG config: WATCHDOG_USEC:");
                                                        DLT_STRING(sWdogUSec);
                                                        DLT_STRING(".Using default watchdog re-trigger rate :");
                                                        DLT_UINT32(PAS_WATCHDOG_TIMEOUT_DEFAULT_VALUE_US / 1000);
                                                        DLT_STRING("ms"));

            u64WdogUSec = PAS_WATCHDOG_TIMEOUT_DEFAULT_VALUE_US;
        }
        else
        {
            u64WdogUSec /= 2;
            DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_INFO,     DLT_STRING("WDOG retrigger rate [ms]:");
                                                        DLT_UINT32(u64WdogUSec/1000));
        }
    }

    return (uint32_t)(u64WdogUSec / ONE_SEC_IN_US);
}


static gboolean persadmin_WDogRetriggerCB(gpointer user_data)
{
    sd_notify(0, "WATCHDOG=1");

    DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_INFO,     DLT_STRING("Triggered systemd WDOG"));

    return (TRUE);
}


/**
 * \brief Starts the main DBus loop. Returns when the DBus connection is closed
 *
 * \return void
 */
void persadmin_RunDBusMainLoop(void)
{
    uint32_t                u32ConnectionId;
    guint                     watcherId;

    GBusNameWatcherFlags     flags =  G_BUS_NAME_WATCHER_FLAGS_NONE;

    /* Initialize GLib */
    g_type_init();            /* deprecated. Since GLib 2.36, the type system is initialized automatically and this function does nothing.*/

    DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_INFO,     DLT_STRING("Creating a new DBus connection..."));

    /* Connect to the D-Bus. Obtain a bus name to offer PAS objects */
    u32ConnectionId = g_bus_own_name( PERSISTENCE_ADMIN_SVC_BUS_TYPE
                                    , PERSISTENCE_ADMIN_SVC_BUS_NAME
                                    , G_BUS_NAME_OWNER_FLAGS_NONE
                                    , &OnBusAcquired_cb
                                    , &OnNameAcquired_cb
                                    , &OnNameLost_cb
                                    , NIL
                                    , NIL);

    DLT_LOG(persAdminSvcDLTCtx, DLT_LOG_INFO, DLT_STRING("D-Bus connection Id: "), DLT_UINT32(u32ConnectionId));

    /* Watch the NSM bus name */
    watcherId = g_bus_watch_name (    PERSISTENCE_ADMIN_SVC_BUS_TYPE, /* NSM uses the same bus type as PAS  */
                                    NSM_BUS_NAME,
                                    flags,
                                    &OnNameAppeared,
                                    NIL,
                                    NIL,
                                    NIL);

    /* Create the main loop */
    g_pMainLoop = g_main_loop_new(NIL, FALSE);

    /* The main loop is only canceled if the Node is completely shut down or the D-Bus connection fails */
    g_main_loop_run(g_pMainLoop);

    g_bus_unwatch_name (watcherId);

    /* If the main loop returned, clean up. Release bus name and main loop */
    g_bus_unown_name(u32ConnectionId);

    g_main_loop_unref(g_pMainLoop);
    g_pMainLoop = NIL;

    /* Release the (created) skeleton object */
    if(NIL != g_pNSLCSkeleton)
    {
        g_object_unref(g_pNSLCSkeleton);
        g_pNSLCSkeleton = NIL;
    }

    /* Release the (created) proxy object */
    if(NIL != g_pNSCProxy)
    {
        g_object_unref(g_pNSCProxy);
        g_pNSCProxy = NIL;
    }
}


/**
 * \brief Quits the main DBus loop
 *
 * \return void
 */
void persadmin_QuitDBusMainLoop(void)
{
    if(true == g_bDBusConnInit)
    {
        if(NIL != g_pMainLoop)
        {
            g_main_loop_quit(g_pMainLoop);
            g_bDBusConnInit = false;
        }
    }
}


/**
 * \brief Check if the registration to NSM was performed successfully.
 *
 * \return true if registered to NSM, false otherwise
 */
bool_t persadmin_IsRegisteredToNSM(void)
{
    return g_bRegisteredToNSM;
}