Make dbus method name shorter
[apps/native/tizen-things-daemon.git] / daemon / src / ttd-cmd-mgr.c
1 /*
2  * Copyright (c) 2018 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Flora License, Version 1.1 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://floralicense.org/license/
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <glib.h>
18 #include "ttd-log.h"
19 #include "ttd-cmd-mgr.h"
20 #include "ttd-cmd.h"
21 #include "ttd-cmd-type.h"
22 #include "ttd-cmd-func.h"
23 #include "ttd-http.h"
24 #include "ttd-parse-cmd.h"
25 #include "ttd-build-json.h"
26 #include "common-util.h"
27
28 #define CMD_MGR_GET_INTERVAL_SEC (3600 * 3)
29 #define RESULT_WAIT_IN_SEC (10)
30 #define RESULT_WAIT_TIME (RESULT_WAIT_IN_SEC * 1000000)
31 #define RESULT_WAIT_TRY_MAX (10)
32
33 // #define CMD_FETCH_TEST
34
35 typedef struct _ttd_result_data_s {
36         char *cmd_id;
37         ttd_cmd_result_e result;
38         char *data;
39 } ttd_result_data_s;
40
41 struct __cmd_mgr_h {
42         GAsyncQueue *cmd_id_queue;
43         GHashTable *cmd_hash;
44         GAsyncQueue *result_queue;
45         const char *current_cmd_id;
46         GMutex mutex;
47         GThread *get_thread;
48         int get_thread_running;
49         int get_by_request;
50         GMutex get_mutex;
51         GCond get_cond;
52         GThread *launch_thread;
53 };
54
55 /* Just a pointer value to make unblocking async queue and exiting thread,
56  * it could be any address as long, as it isn't a valid queue item
57  */
58 static const gpointer quit_marker = (gpointer) &ttd_cmd_mgr_init;
59
60 /* Use singleton */
61 static struct __cmd_mgr_h *g_handle = NULL;
62
63 static void __cmd_id_item_free(gpointer data)
64 {
65         if (!data)
66                 return;
67
68         if (data == quit_marker)
69                 return;
70
71         g_free(data);
72 }
73
74 static void __result_item_free(gpointer data)
75 {
76         ttd_result_data_s *item = data;
77
78         if (!data)
79                 return;
80
81         if (data == quit_marker)
82                 return;
83
84         if (item->cmd_id)
85                 _D("free result item[%s]", item->cmd_id);
86         g_free(item->cmd_id);
87         g_free(item->data);
88
89         g_free(item);
90 }
91
92 int ttd_cmd_mgr_push_result(const char *id,
93         ttd_cmd_result_e result, const char *data)
94 {
95         ttd_result_data_s *result_item = NULL;
96         const char *curr_id = NULL;
97
98         retvm_if(!g_handle, -1, "cmd mgr is not initialized yet");
99         retvm_if(!id, -1, "cmd id is NULL");
100
101         g_mutex_lock(&g_handle->mutex);
102         curr_id = g_handle->current_cmd_id;
103         g_mutex_unlock(&g_handle->mutex);
104
105         retvm_if(!curr_id, -1, "current cmd id is NULL");
106
107         if (0 != g_strcmp0(id, curr_id)) {
108                 _E("invaild cmd id[%s] - current cmd id[%s]", id, curr_id);
109                 return -1;
110         }
111
112         result_item = g_try_new0(ttd_result_data_s, 1);
113
114         result_item->cmd_id = g_strdup(id);
115         result_item->result = result;
116         if (data)
117                 result_item->data = g_strdup(data);
118
119         g_async_queue_push(g_handle->result_queue, result_item);
120
121         return 0;
122 }
123
124 int ttd_cmd_mgr_get_cmd(void)
125 {
126         retvm_if(!g_handle, -1, "cmd mgr is not initialized yet");
127         _D("unblocking get_thread");
128         g_mutex_lock(&g_handle->get_mutex);
129         g_handle->get_by_request = 1;
130         g_cond_broadcast(&g_handle->get_cond);
131         g_mutex_unlock(&g_handle->get_mutex);
132         // wait here to get result of getting cmd or not ???
133
134         return 0;
135 }
136
137 static int _get_cloud_cmd(struct __cmd_mgr_h *handle, long *res_code)
138 {
139         int ret  = 0;
140         char *cmd = NULL;
141         long r_code = 0;
142         GList *cmd_list = NULL;
143         GList *l = NULL;
144
145         retv_if(!handle, -1);
146
147         ret = ttd_http_command_get(&cmd, &r_code);
148         if (ret) {
149                 _E("failed to get cmd [%ld]", r_code);
150                 if (res_code)
151                         *res_code = r_code;
152                 return -1;
153         }
154
155         if (res_code)
156                 *res_code = r_code;
157
158         retvm_if(!cmd, 0, "there is no new cmd now");
159
160         ret = ttd_parse_json_to_cmd(cmd, &cmd_list);
161         if (ret) {
162                 _E("failed to parse cmd");
163                 g_free(cmd);
164                 return -1;
165         }
166         g_free(cmd);
167         cmd = NULL;
168
169         for (l = cmd_list; l != NULL; l = l->next) {
170                 ttd_cmd_data *cmd_data = NULL;
171                 ttd_cmd_data *item = NULL;
172                 const char *cmd_id = NULL;
173
174                 cmd_data = (ttd_cmd_data *)l->data;
175                 continue_if(!cmd_data);
176
177                 cmd_id = ttd_cmd_get_id(cmd_data);
178
179                 g_mutex_lock(&handle->mutex);
180                 item = g_hash_table_lookup(handle->cmd_hash, cmd_id);
181                 if (!item) {
182                         _D("cmd[%s] is pushed in cmd queue", cmd_id);
183                         g_async_queue_push(handle->cmd_id_queue, g_strdup(cmd_id));
184                         g_hash_table_insert(handle->cmd_hash, g_strdup(cmd_id), cmd_data);
185                 } else {
186                         _D("cmd[%s] is already in cmd queue", cmd_id);
187                         ttd_cmd_free(cmd_data);
188                 }
189                 g_mutex_unlock(&handle->mutex);
190         }
191         g_list_free(cmd_list);
192
193         return 0;
194 }
195
196 static gpointer _get_thread(gpointer data)
197 {
198         struct __cmd_mgr_h *handle = data;
199
200         g_mutex_lock(&handle->get_mutex);
201         while (TRUE) {
202                 int ret  = 0;
203                 guint64 until = 0;
204                 unsigned int retry = 0;
205
206                 until = common_get_monotonic_coarse_time() +
207                         CMD_MGR_GET_INTERVAL_SEC * G_TIME_SPAN_SECOND;
208                 _D("thread blocked for 3 hours");
209                 g_cond_wait_until(&handle->get_cond, &handle->get_mutex, until);
210                 _D("thread unblocked");
211
212                 if (!handle->get_thread_running)
213                         break;
214
215                 if (handle->get_by_request)
216                         retry = 5;
217                 else
218                         retry = 1;
219
220                 while(retry) {
221                         long res_code = 0;
222
223                         ret = _get_cloud_cmd(handle, &res_code);
224                         if (ret)
225                                 _E("failed to get cmd - %ld", res_code);
226                         else
227                                 _D("res_code: %ld", res_code);
228
229                         if (res_code == TTD_HTTP_OK) // HTTP OK - success to get cmd
230                                 break;
231
232                         retry--;
233                         if (retry)
234                                 g_usleep(G_USEC_PER_SEC); // sleep in 1 second before retry
235                 };
236
237                 handle->get_by_request = 0;
238         }
239         g_mutex_unlock(&handle->get_mutex);
240         _D("thread terminated");
241         return NULL;
242 }
243
244 static gpointer _launch_thread(gpointer data)
245 {
246         struct __cmd_mgr_h *handle = data;
247
248         while (TRUE) {
249                 char *cmd_id = NULL;
250                 ttd_cmd_data *cmd_data = NULL;
251                 char *report = NULL;
252                 long r_code = 0;
253                 int ret  = 0;
254                 ttd_cmd_launch_func launch_func = NULL;
255                 ttd_cmd_type_e cmd_type = TTD_CMD_TYPE_UNKNOWN;
256                 int result_wait = 1;
257
258                 // get pop oldest cmd from cmd_id_queue
259                 _D("block launch thread");
260                 cmd_id = g_async_queue_pop(handle->cmd_id_queue);
261                 if (!cmd_id) {
262                         _D("unblock launch thread");
263                         _D("cmd queue is empty");
264                         goto DONE_N_WAIT;
265                 }
266                 _D("unblock launch thread");
267
268                 if (cmd_id == quit_marker)
269                         goto THREAD_EXIT;
270
271                 // get cmd data from cmd_hash
272                 g_mutex_lock(&handle->mutex);
273                 cmd_data = g_hash_table_lookup(handle->cmd_hash, cmd_id);
274                 g_mutex_unlock(&handle->mutex);
275                 if (!cmd_data) {
276                         _E("data for cmd[%s] is not exist", cmd_id);
277                         goto DONE_N_WAIT;
278                 }
279
280                 // report 'running' state of the cmd id to cloud
281                 cmd_type = ttd_cmd_get_type(cmd_data);
282                 report = ttd_build_json_create_report(cmd_id, cmd_type,
283                         TTD_CMD_STATE_RUNNING, 0, "state update", NULL);
284                 ret = ttd_http_report_post(report, &r_code);
285                 if (r_code != TTD_HTTP_OK) {
286                         _E("failed to post report [%ld]", r_code);
287                         g_free(report);
288                         goto DONE_N_WAIT;
289                 }
290                 g_free(report);
291                 report = NULL;
292                 ttd_cmd_set_state(cmd_data, TTD_CMD_STATE_RUNNING);
293
294                 // execute cmd
295                 launch_func = ttd_cmd_get_launch_func(cmd_type);
296                 if (!launch_func) {
297                         _E("cmd[%s] no proper launch function", cmd_id);
298                         report = ttd_build_json_create_report(cmd_id, cmd_type,
299                                 TTD_CMD_STATE_FAILED, 0, "no proper launch function", NULL);
300                         ttd_http_report_post(report, NULL);
301                         g_free(report);
302                         report = NULL;
303                         goto DONE_N_WAIT;
304                 }
305
306                 g_mutex_lock(&handle->mutex);
307                 g_handle->current_cmd_id = cmd_id;
308                 g_mutex_unlock(&handle->mutex);
309                 ret = launch_func(cmd_data);
310                 if (ret) {
311                         _E("cmd[%s] launch failed", cmd_id);
312                         report = ttd_build_json_create_report(cmd_id, cmd_type,
313                                 TTD_CMD_STATE_FAILED, 0, "command launch failed", NULL);
314                         ttd_http_report_post(report, NULL);
315                         g_free(report);
316                         report = NULL;
317                         goto DONE_N_WAIT;
318                 }
319
320                 while (result_wait) {
321                         ttd_result_data_s *result_item = NULL;
322                         static unsigned int count = 0;
323
324                         result_item = g_async_queue_timeout_pop(
325                                 g_handle->result_queue, RESULT_WAIT_TIME); /* 10 sec */
326
327                         if (!result_item) {
328                                 count++;
329
330                                 if (count <= RESULT_WAIT_TRY_MAX) /* 10 times */
331                                         continue;
332
333                                 /* Wait 100 sec to receive a result,
334                                  * IS IT(100 sec) "ENOUGH" to install pkgs or task monitoring ???
335                                  */
336                                 /* timeout to wait result, report fail */
337                                 report = ttd_build_json_create_report(cmd_id, cmd_type,
338                                         TTD_CMD_STATE_FAILED, 0, "timeout to wait result ", NULL);
339                                 ttd_http_report_post(report, NULL);
340                                 g_free(report);
341                                 report = NULL;
342
343                                 result_wait = 0;
344                                 break;
345                         }
346
347                         if (result_item == quit_marker)
348                                 goto THREAD_EXIT;
349
350                         switch (result_item->result) {
351                         case TTD_CMD_RESULT_RUNNING:
352                                 /* report running and wait more result */
353                                 report = ttd_build_json_create_report(cmd_id, cmd_type,
354                                         TTD_CMD_STATE_RUNNING, 0,
355                                         "report in progress", result_item->data);
356                                 ttd_http_report_post(report, NULL);
357                                 break;
358                         case TTD_CMD_RESULT_SUCCESS:
359                                 /* report done */
360                                 report = ttd_build_json_create_report(cmd_id, cmd_type,
361                                         TTD_CMD_STATE_DONE, 0,
362                                         "done", result_item->data);
363                                 ttd_http_report_post(report, NULL);
364                                 result_wait = 0;
365                                 break;
366                         case TTD_CMD_RESULT_FAIL:
367                                 /* report fail */
368                                 report = ttd_build_json_create_report(cmd_id, cmd_type,
369                                         TTD_CMD_STATE_FAILED, 0,
370                                         "failed to process command", result_item->data);
371                                 ttd_http_report_post(report, NULL);
372                                 result_wait = 0;
373                                 break;
374                         /* unhandled states */
375                         default:
376                                 break;
377                         }
378                         g_free(report);
379                         report = NULL;
380                         __result_item_free(result_item);
381                 }
382
383 DONE_N_WAIT:
384                 if (cmd_id) {
385                         g_mutex_lock(&handle->mutex);
386                         g_handle->current_cmd_id = NULL;
387                         g_hash_table_remove(handle->cmd_hash, cmd_id);
388                         g_mutex_unlock(&handle->mutex);
389                         g_free(cmd_id);
390                 }
391                 continue;
392
393 THREAD_EXIT:
394                 _D("get quit_marker");
395                 break;
396         }
397         _D("thread terminated");
398         return NULL;
399 }
400
401 static void __free_cmd_mgr_handle(void)
402 {
403         if (!g_handle)
404                 return;
405
406         if (g_handle->get_thread) {
407                 g_mutex_lock(&g_handle->get_mutex);
408                 g_handle->get_thread_running = 0;
409                 g_cond_broadcast(&g_handle->get_cond);
410                 g_mutex_unlock(&g_handle->get_mutex);
411
412                 g_thread_join(g_handle->get_thread);
413         }
414         g_mutex_clear(&g_handle->get_mutex);
415         g_cond_clear(&g_handle->get_cond);
416
417         if (g_handle->launch_thread) {
418                 g_async_queue_push(g_handle->cmd_id_queue, quit_marker);
419                 g_async_queue_push(g_handle->result_queue, quit_marker);
420
421                 g_thread_join(g_handle->launch_thread);
422         }
423
424         g_mutex_clear(&g_handle->mutex);
425
426         if (g_handle->result_queue)
427                 g_async_queue_unref(g_handle->result_queue);
428
429         if (g_handle->cmd_id_queue)
430                 g_async_queue_unref(g_handle->cmd_id_queue);
431
432         if (g_handle->cmd_hash) {
433                 g_hash_table_remove_all(g_handle->cmd_hash);
434                 g_hash_table_unref(g_handle->cmd_hash);
435         }
436
437         g_free(g_handle);
438         g_handle = NULL;
439 }
440
441 #ifdef CMD_FETCH_TEST
442 static gboolean __get_cmd_first_time(gpointer data)
443 {
444         ttd_cmd_mgr_get_cmd();
445
446         return G_SOURCE_REMOVE;
447 }
448 #endif /* CMD_FETCH_TEST */
449
450 int ttd_cmd_mgr_init(void)
451 {
452         GError *error = NULL;
453
454         retvm_if(g_handle, -1, "cmd mgr already initialized, finalized it first");
455
456         g_handle = g_try_malloc0(sizeof(struct __cmd_mgr_h));
457         retvm_if(!g_handle, -1, "failed to malloc");
458
459         g_handle->cmd_id_queue = g_async_queue_new_full(__cmd_id_item_free);
460         goto_if(!g_handle->cmd_id_queue, ERROR_N_EXIT);
461
462         g_handle->cmd_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
463                         g_free, (GDestroyNotify)ttd_cmd_free);
464         goto_if(!g_handle->cmd_hash, ERROR_N_EXIT);
465
466         g_handle->result_queue = g_async_queue_new_full(__result_item_free);
467         goto_if(!g_handle->result_queue, ERROR_N_EXIT);
468
469         g_mutex_init(&g_handle->mutex);
470
471         g_mutex_init(&g_handle->get_mutex);
472         g_cond_init(&g_handle->get_cond);
473         g_handle->get_thread_running = 1;
474
475         g_handle->get_thread =
476                 g_thread_try_new(NULL, (GThreadFunc)_get_thread, g_handle, &error);
477         if (!g_handle->get_thread) {
478                 _E("failed to create get thread - %s",
479                         error && error->message ? error->message : "Unknown Error");
480                 goto ERROR_N_EXIT;
481         }
482
483         g_handle->launch_thread =
484                 g_thread_try_new(NULL, (GThreadFunc)_launch_thread, g_handle, &error);
485         if (!g_handle->launch_thread) {
486                 _E("failed to create launch_thread - %s",
487                         error && error->message ? error->message : "Unknown Error");
488                 goto ERROR_N_EXIT;
489         }
490
491 #ifdef CMD_FETCH_TEST
492         g_idle_add(__get_cmd_first_time, NULL);
493 #endif /* CMD_FETCH_TEST */
494
495         return 0;
496
497 ERROR_N_EXIT:
498         if (error)
499                 g_error_free(error);
500         __free_cmd_mgr_handle();
501         return -1;
502 }
503
504 int ttd_cmd_mgr_fini(void)
505 {
506         __free_cmd_mgr_handle();
507         return 0;
508 }