tizen 2.3.1 release
[kernel/api/system-resource.git] / src / network / main.c
1 /*
2  * resourced
3  *
4  * Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  */
19
20 /**
21  * @file main.c
22  * @desc Implement resource API. Initialization routines.
23  *
24  */
25
26 #include <dbus/dbus.h>
27 #include <sqlite3.h>
28 #include <unistd.h>
29
30 #include "const.h"
31 #include "cgroup.h"
32 #include "datausage-foreach.h"
33 #include "datausage-quota.h"
34 #include "datausage-reset.h"
35 #include "datausage-restriction.h"
36 #include "macro.h"
37 #include "trace.h"
38
39 static void __attribute__ ((constructor)) librsml_initialize(void);
40 static void __attribute__ ((destructor)) librsml_deinitialize(void);
41
42 static sqlite3 *database;
43
44
45 static void librsml_initialize(void)
46 {
47         _D("librsml_initialize");
48
49         if (dbus_threads_init_default() != TRUE)
50                 _E("Failed to initialize dbus threads support");
51 }
52
53 #define SQLITE_BUSY_TIMEOUT 500000
54
55 static int resourced_db_busy(void UNUSED *user, int attempts)
56 {
57         _E("DB locked by another process, attempts number %d", attempts);
58
59         usleep(SQLITE_BUSY_TIMEOUT); /* wait for a half second*/
60         return 1;
61 }
62
63 API void libresourced_db_initialize_once(void)
64 {
65         int res = 0;
66         if (database != NULL)
67                 return;
68
69         _D("libresourced_db_initialize_once");
70
71         res = sqlite3_open(DATABASE_FULL_PATH, &database);
72         if (res != SQLITE_OK) {
73                 _D("Can't open database %s: %s\n", DATABASE_FULL_PATH,
74                    sqlite3_errmsg(database));
75                 sqlite3_close(database);
76                 return;
77         }
78
79         /* Set how many times we'll repeat our attempts for sqlite_step */
80         if (sqlite3_busy_handler(database, resourced_db_busy, NULL) != SQLITE_OK) {
81                 _E("Couldn't set busy handler!");
82         }
83 }
84
85 static void librsml_deinitialize(void)
86 {
87         finalize_datausage_reset();
88         finalize_datausage_foreach();
89         finalize_datausage_restriction();
90         sqlite3_close(database);
91 }
92
93 API sqlite3 *resourced_get_database(void)
94 {
95         libresourced_db_initialize_once();
96         return database;
97 }