提交 924b03da 编写于 作者: Z zhong_ning

modify l2 init

Signed-off-by: Nzhong_ning <zhong_ning@hoperun.com>
上级 cde94033
...@@ -18,21 +18,32 @@ lite_component("initsync") { ...@@ -18,21 +18,32 @@ lite_component("initsync") {
} }
shared_library("libinitsync_shared") { shared_library("libinitsync_shared") {
sources = [ "src/init_sync.c" ] sources = [
"src/init_sync.c",
]
cflags = [ "-Wall" ] cflags = [ "-Wall" ]
include_dirs = [ include_dirs = [
"//base/startup/init_lite/initsync/include", "//base/startup/init_lite/initsync/include",
"//base/startup/init_lite/interfaces/kits", "//base/startup/init_lite/interfaces/kits",
"//base/startup/init_lite/services/log",
]
public_deps = [
"//base/startup/init_lite/services/log:init_log",
"//third_party/bounds_checking_function:libsec_shared",
] ]
public_deps = [ "//third_party/bounds_checking_function:libsec_shared" ]
} }
static_library("libinitsync_static") { static_library("libinitsync_static") {
sources = [ "src/init_sync.c" ] sources = [
"src/init_sync.c",
]
cflags = [ "-Wall" ] cflags = [ "-Wall" ]
include_dirs = [ include_dirs = [
"//base/startup/init_lite/initsync/include", "//base/startup/init_lite/initsync/include",
"//base/startup/init_lite/interfaces/kits", "//base/startup/init_lite/interfaces/kits",
"//base/startup/init_lite/services/log",
]
public_deps = [
"//third_party/bounds_checking_function:libsec_static",
] ]
public_deps = [ "//third_party/bounds_checking_function:libsec_static" ]
} }
...@@ -24,19 +24,19 @@ ...@@ -24,19 +24,19 @@
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/types.h> #include <sys/types.h>
#include <unistd.h> #include <unistd.h>
#include "init_log.h"
static int SendCmd(int cmd, unsigned long arg) static int SendCmd(int cmd, unsigned long arg)
{ {
int fd = open(QUICKSTART_NODE, O_RDONLY); int fd = open(QUICKSTART_NODE, O_RDONLY);
if (fd != -1) { if (fd != -1) {
int ret = ioctl(fd, cmd, arg); int ret = ioctl(fd, cmd, arg);
if (ret == -1) { if (ret == -1) {
printf("[ERR][%s,%d] %s!\n", __FUNCTION__, __LINE__, strerror(errno)); INIT_LOGE("[Init] [ERR] %s!\n", strerror(errno));
} }
close(fd); close(fd);
return ret; return ret;
} }
printf("[ERR][%s,%d] %s!\n", __FUNCTION__, __LINE__, strerror(errno)); INIT_LOGE("[Init] [ERR] %s!\n", strerror(errno));
return fd; return fd;
} }
...@@ -56,7 +56,7 @@ int NotifyInit(unsigned long event) ...@@ -56,7 +56,7 @@ int NotifyInit(unsigned long event)
int SystemInitStage(QuickstartStage stage) int SystemInitStage(QuickstartStage stage)
{ {
if (stage >= QS_STAGE_LIMIT || stage < QS_STAGE1) { if (stage >= QS_STAGE_LIMIT || stage < QS_STAGE1) {
printf("[ERR][%s,%d] the stage(%d) is not expected!\n", __FUNCTION__, __LINE__, stage); INIT_LOGE("[Init] the stage(%d) is not expected!\n", stage);
return -1; return -1;
} }
return SendCmd(QUICKSTART_STAGE(stage), 0); return SendCmd(QUICKSTART_STAGE(stage), 0);
......
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INIT_REBOOT_API_H
#define INIT_REBOOT_API_H
int DoRebootApi(const char *cmdContent);
#endif
文件模式从 100755 更改为 100644
# Copyright (c) 2020 Huawei Device Co., Ltd. # Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at # You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0 # http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, software # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import("//build/ohos.gni") import("//build/ohos.gni")
ohos_static_library("libreboot") {
ohos_static_library("triggerservice") { sources = [
sources = [ "//base/startup/init_lite/interfaces/innerkits/reboot/init_reboot_api.c",
"trigger_manager.c", ]
"trigger_processor.c",
"trigger_checker.c", include_dirs = [
"//base/startup/init_lite/services/src/init_utils.c", "//base/startup/init_lite/interfaces/innerkits/include",
] "//base/startup/init_lite/services/include/param",
"//third_party/bounds_checking_function/include",
include_dirs = [ "//base/startup/init_lite/services/log",
".", ]
"//base/startup/init_lite/services/include/property",
"//base/startup/init_lite/services/include/trigger", deps = [
"//base/startup/init_lite/services/include", "//third_party/bounds_checking_function:libsec_static",
"//base/startup/init_lite/services/property/include", "//base/startup/init_lite/services/param:paramclient",
"//third_party/libuv/include", "//base/startup/init_lite/services/log:init_log",
"//third_party/cJSON", ]
] }
deps = [
"//third_party/libuv:uv_static",
"//third_party/bounds_checking_function:libsec_static",
]
part_name = "startup"
subsystem_name = "startup"
}
\ No newline at end of file
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "init_reboot_api.h"
#include <stdio.h>
#include <string.h>
#include "sys_param.h"
#include "securec.h"
#include "init_log.h"
#define SYS_POWER_CTRL "sys.powerctrl."
#define MAX_REBOOT_NAME_SIZE 100
#define MAX_REBOOT_VAUE_SIZE 500
int DoRebootApi(const char *cmdContent)
{
char name[MAX_REBOOT_VAUE_SIZE];
if (cmdContent == NULL) {
INIT_LOGE("DoReboot api error, cmdContent is NULL.\n");
return -1;
}
int length = strlen(cmdContent);
if (length == 0 || length > MAX_REBOOT_VAUE_SIZE) {
INIT_LOGE("DoReboot api error, cmdContent = %s, length = %d.\n", cmdContent, length);
return -1;
}
if (snprintf_s(name, MAX_REBOOT_NAME_SIZE, MAX_REBOOT_NAME_SIZE - 1, "%s%s", SYS_POWER_CTRL, "reboot") < 0) {
INIT_LOGE("DoReboot api error, MAX_REBOOT_NAME_SIZE is not enough\n");
return -1;
}
if (SystemSetParameter(name, cmdContent) != 0) {
INIT_LOGE("DoRebootApi SystemSetParameter error\n");
return -1;
}
return 0;
}
文件模式从 100755 更改为 100644
...@@ -37,10 +37,10 @@ static int GetControlFromEnv(char *path) ...@@ -37,10 +37,10 @@ static int GetControlFromEnv(char *path)
if (path == NULL) { if (path == NULL) {
return -1; return -1;
} }
printf("GetControlFromEnv path is %s \n", path); INIT_LOGI("GetControlFromEnv path is %s \n", path);
const char *val = getenv(path); const char *val = getenv(path);
if (val == NULL) { if (val == NULL) {
printf("test GetControlFromEnv val is null %d\n", errno); INIT_LOGE("GetControlFromEnv val is null %d\n", errno);
return -1; return -1;
} }
errno = 0; errno = 0;
...@@ -48,9 +48,9 @@ static int GetControlFromEnv(char *path) ...@@ -48,9 +48,9 @@ static int GetControlFromEnv(char *path)
if (errno) { if (errno) {
return -1; return -1;
} }
printf("test GetControlFromEnv fd is %d \n", fd); INIT_LOGI("GetControlFromEnv fd is %d \n", fd);
if (fcntl(fd, F_GETFD) < 0) { if (fcntl(fd, F_GETFD) < 0) {
printf("test GetControlFromEnv errno %d \n", errno); INIT_LOGE("GetControlFromEnv errno %d \n", errno);
return -1; return -1;
} }
return fd; return fd;
...@@ -63,23 +63,23 @@ int GetControlSocket(const char *name) ...@@ -63,23 +63,23 @@ int GetControlSocket(const char *name)
} }
char path[MAX_SOCKET_ENV_PREFIX_LEN] = {0}; char path[MAX_SOCKET_ENV_PREFIX_LEN] = {0};
snprintf(path, sizeof(path), OHOS_SOCKET_ENV_PREFIX"%s", name); snprintf(path, sizeof(path), OHOS_SOCKET_ENV_PREFIX"%s", name);
printf("test GetControlSocket path is %s \n", path); INIT_LOGI("GetControlSocket path is %s \n", path);
int fd = GetControlFromEnv(path); int fd = GetControlFromEnv(path);
if (fd < 0) { if (fd < 0) {
printf("GetControlFromEnv fail \n"); INIT_LOGE("GetControlFromEnv fail \n");
return -1; return -1;
} }
struct sockaddr_un addr; struct sockaddr_un addr;
socklen_t addrlen = sizeof(addr); socklen_t addrlen = sizeof(addr);
int ret = getsockname(fd, (struct sockaddr*)&addr, &addrlen); int ret = getsockname(fd, (struct sockaddr*)&addr, &addrlen);
if (ret < 0) { if (ret < 0) {
printf("test GetControlSocket errno %d \n", errno); INIT_LOGE("GetControlSocket errno %d \n", errno);
return -1; return -1;
} }
char sockDir[MAX_SOCKET_DIR_LEN] = {0}; char sockDir[MAX_SOCKET_DIR_LEN] = {0};
snprintf(sockDir, sizeof(sockDir), OHOS_SOCKET_DIR"/%s", name); snprintf(sockDir, sizeof(sockDir), OHOS_SOCKET_DIR"/%s", name);
printf("test sockDir %s \n", sockDir); INIT_LOGI("sockDir %s \n", sockDir);
printf("addr.sun_path %s \n", addr.sun_path); INIT_LOGI("addr.sun_path %s \n", addr.sun_path);
if (strncmp(sockDir, addr.sun_path, strlen(sockDir)) == 0) { if (strncmp(sockDir, addr.sun_path, strlen(sockDir)) == 0) {
return fd; return fd;
} }
......
文件模式从 100755 更改为 100644
...@@ -20,22 +20,24 @@ if (defined(ohos_lite)) { ...@@ -20,22 +20,24 @@ if (defined(ohos_lite)) {
] ]
sources = [ sources = [
"src/init_adapter.c", "src/init_adapter.c",
"src/init_capability.c",
"src/init_cmds.c", "src/init_cmds.c",
"src/init_import.c",
"src/init_jobs.c", "src/init_jobs.c",
"src/init_read_cfg.c", "src/init_read_cfg.c",
"src/init_service.c", "src/init_service.c",
"src/init_service_manager.c", "src/init_service_manager.c",
"src/init_import.c", "src/init_service_socket.c",
"src/init_signal_handler.c", "src/init_signal_handler.c",
"src/init_utils.c", "src/init_utils.c",
"src/init_service_socket.c",
"src/main.c", "src/main.c",
"src/init_capability.c", "src/init_reboot.c",
] ]
include_dirs = [ include_dirs = [
"//base/startup/init_lite/services/include", "//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/property/include", "//base/startup/init_lite/services/param/include",
"//base/startup/init_lite/services/log",
"//third_party/cJSON", "//third_party/cJSON",
"//third_party/bounds_checking_function/include", "//third_party/bounds_checking_function/include",
"//base/startup/syspara_lite/interfaces/kits", "//base/startup/syspara_lite/interfaces/kits",
...@@ -44,8 +46,9 @@ if (defined(ohos_lite)) { ...@@ -44,8 +46,9 @@ if (defined(ohos_lite)) {
cflags = [ "-Wall" ] cflags = [ "-Wall" ]
deps = [ deps = [
"//base/startup/syspara_lite/frameworks/parameter:parameter",
"//base/startup/init_lite/initsync:initsync", "//base/startup/init_lite/initsync:initsync",
"//base/startup/init_lite/services/log:init_log",
"//base/startup/syspara_lite/frameworks/parameter:parameter",
"//build/lite/config/component/cJSON:cjson_shared", "//build/lite/config/component/cJSON:cjson_shared",
"//third_party/bounds_checking_function:libsec_shared", "//third_party/bounds_checking_function:libsec_shared",
] ]
...@@ -73,8 +76,9 @@ if (defined(ohos_lite)) { ...@@ -73,8 +76,9 @@ if (defined(ohos_lite)) {
if (ohos_build_type == "debug") { if (ohos_build_type == "debug") {
group("unittest") { group("unittest") {
deps = deps = [
[ "//base/startup/init_lite/services/test/unittest/common:unittest" ] "//base/startup/init_lite/services/test/unittest/common:unittest",
]
} }
} }
} else { } else {
...@@ -87,8 +91,12 @@ if (defined(ohos_lite)) { ...@@ -87,8 +91,12 @@ if (defined(ohos_lite)) {
include_dirs = [ include_dirs = [
"include", "include",
"//third_party/bounds_checking_function/include", "//third_party/bounds_checking_function/include",
"//base/startup/init_lite/services/log",
]
deps = [
"//third_party/bounds_checking_function:libsec_static",
"//base/startup/init_lite/services/log:init_log",
] ]
deps = [ "//third_party/bounds_checking_function:libsec_static" ]
install_enable = true install_enable = true
part_name = "init" part_name = "init"
} }
...@@ -97,38 +105,37 @@ if (defined(ohos_lite)) { ...@@ -97,38 +105,37 @@ if (defined(ohos_lite)) {
sources = [ sources = [
"src/device.c", "src/device.c",
"src/init_adapter.c", "src/init_adapter.c",
"src/init_capability.c",
"src/init_cmds.c", "src/init_cmds.c",
"src/init_import.c",
"src/init_jobs.c", "src/init_jobs.c",
"src/init_log.c",
"src/init_read_cfg.c", "src/init_read_cfg.c",
"src/init_service.c", "src/init_service.c",
"src/init_service_manager.c", "src/init_service_manager.c",
"src/init_import.c", "src/init_service_socket.c",
"src/init_signal_handler.c", "src/init_signal_handler.c",
"src/init_utils.c", "src/init_utils.c",
"src/init_service_socket.c",
"src/main.c", "src/main.c",
"src/init_capability.c", "src/init_reboot.c",
] ]
include_dirs = [ include_dirs = [
"//base/startup/init_lite/services/include/property", "//base/startup/init_lite/services/include/param",
"//base/startup/init_lite/services/include/trigger",
"//base/startup/init_lite/services/include", "//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/property/include", "//base/startup/init_lite/services/log",
"//third_party/cJSON", "//third_party/cJSON",
"//third_party/bounds_checking_function/include", "//third_party/bounds_checking_function/include",
"//third_party/libuv/include",
] ]
deps = [ deps = [
"//base/startup/init_lite/services/property:propertyserver", "//base/startup/init_lite/services/param:paramservice",
"//base/startup/init_lite/services/property:propertyclient", "//base/startup/init_lite/services/log:init_log",
"//base/startup/init_lite/services/trigger:triggerservice",
"//third_party/bounds_checking_function:libsec_static", "//third_party/bounds_checking_function:libsec_static",
"//third_party/cJSON:cjson_static", "//third_party/cJSON:cjson_static",
] ]
if (use_musl) { if (use_musl) {
deps += [ deps += [
"//third_party/mksh:sh", "//third_party/mksh:sh",
"//third_party/toybox:toybox" "//third_party/toybox:toybox",
] ]
} }
install_enable = true install_enable = true
...@@ -142,14 +149,14 @@ if (defined(ohos_lite)) { ...@@ -142,14 +149,14 @@ if (defined(ohos_lite)) {
group("startup_init") { group("startup_init") {
deps = [ deps = [
":init.cfg",
":init", ":init",
":init.cfg",
":updaterueventd", ":updaterueventd",
"//base/startup/init_lite/services/trigger:triggerservice", "//base/startup/init_lite/services/param:paramservice",
"//base/startup/init_lite/services/property:propertyserver", "//base/startup/init_lite/services/param:setparam",
"//base/startup/init_lite/services/property:propertyclient", "//base/startup/init_lite/services/param:getparam",
"//base/startup/init_lite/services/property:setparam", "//base/startup/init_lite/services/param:paramclient",
"//base/startup/init_lite/services/property:getparam" "//base/startup/init_lite/services/reboot:reboot",
] ]
} }
} }
文件模式从 100755 更改为 100644
文件模式从 100755 更改为 100644
文件模式从 100755 更改为 100644
文件模式从 100755 更改为 100644
文件模式从 100755 更改为 100644
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INIT_REBOOT_H
#define INIT_REBOOT_H
void DoReboot(const char *value);
#endif
文件模式从 100755 更改为 100644
...@@ -39,6 +39,7 @@ void RegisterServices(Service* services, int servicesCnt); ...@@ -39,6 +39,7 @@ void RegisterServices(Service* services, int servicesCnt);
void StartServiceByName(const char* serviceName); void StartServiceByName(const char* serviceName);
void StopServiceByName(const char* serviceName); void StopServiceByName(const char* serviceName);
void StopAllServices(); void StopAllServices();
void StopAllServicesBeforeReboot();
void ReapServiceByPID(int pid); void ReapServiceByPID(int pid);
void ParseAllServices(const cJSON* fileRoot); void ParseAllServices(const cJSON* fileRoot);
void DumpAllServices(); void DumpAllServices();
......
文件模式从 100755 更改为 100644
文件模式从 100755 更改为 100644
文件模式从 100755 更改为 100644
...@@ -13,71 +13,120 @@ ...@@ -13,71 +13,120 @@
* limitations under the License. * limitations under the License.
*/ */
#ifndef BASE_STARTUP_PROPERTY_SERVICE_H #ifndef BASE_STARTUP_INIT_PARAM_H
#define BASE_STARTUP_PROPERTY_SERVICE_H #define BASE_STARTUP_INIT_PARAM_H
#include <stdio.h> #include <stdio.h>
#include "property.h" #include "cJSON.h"
#include "sys_param.h"
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
extern "C" { extern "C" {
#endif #endif
#endif #endif
typedef enum {
EVENT_PROPERTY, // 参数修改事件
EVENT_BOOT
} EventType;
/** /**
* Init 接口 * Init 接口
* 初始化属性服务 * 初始化参数服务
* *
*/ */
void InitPropertyService(); void InitParamService();
/**
* 对Init接口
* 启动trigger服务。
*
*/
void StartTriggerService();
/** /**
* Init 接口 * Init 接口
* 加载默认的属性值 * 启动参数服务,在main启动的最后调用,阻赛当前线程
* *
*/ */
int LoadDefaultProperty(const char *fileName); int StartParamService();
/** /**
* Init 接口 * Init 接口
* 安全使用,加载属性的信息,包括selinux label 等 * 停止参数服务
* *
*/ */
int LoadPropertyInfo(const char *fileName); void StopParamService();
/** /**
* Init 接口 * Init 接口
* 启动属性服务,在main启动的最后调用,阻赛当前线程 * 加载默认的参数值
* *
*/ */
int StartPropertyService(); int LoadDefaultParams(const char *fileName);
/** /**
* Init 接口 * Init 接口
* 设置属性,主要用于其他进程使用,通过管道修改属性 * 安全使用,加载参数的信息,包括selinux label 等
* *
*/ */
int SystemWriteParameter(const char *name, const char *value); int LoadParamInfos(const char *fileName);
/** /**
* Init 接口 * Init 接口
* 查询属性 * 加载默认参数
* *
*/ */
int SystemReadParameter(const char *name, char *value, unsigned int *len); int LoadPersistParams();
/** /**
* Init 接口 * Init 接口
* 遍历属性。 * 设置参数,主要用于其他进程使用,通过管道修改参数
* *
*/ */
int SystemTraversalParameters(void (*traversalParameter)(PropertyHandle handle, void* cookie), void* cookie); int SystemWriteParam(const char *name, const char *value);
/** /**
* Init 接口 * Init 接口
* 加载默认属性。 * 查询参数。
*
*/
int SystemReadParam(const char *name, char *value, unsigned int *len);
/**
* 对Init接口
* 触发一个trigger操作。
*
*/
void PostTrigger(EventType type, void *content, u_int32_t contentLen);
/**
* 对Init接口
* 触发一个参数trigger操作。
*
*/
void PostParamTrigger(const char *name, const char *value);
/**
* 对Init接口
* 解析trigger文件。
*
*/
int ParseTriggerConfig(cJSON *fileRoot);
/**
* 对Init接口
* 按名字执行对应的trigger。
*
*/
void DoTriggerExec(const char *content);
/**
* 对Init接口
* 按名字执行对应的trigger。
* *
*/ */
int LoadPersistProperties(); int SystemTraversalParam(void (*traversalParameter)(ParamHandle handle, void* cookie), void* cookie);
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
......
...@@ -13,8 +13,8 @@ ...@@ -13,8 +13,8 @@
* limitations under the License. * limitations under the License.
*/ */
#ifndef BASE_STARTUP_PROPERTY_H #ifndef BASE_STARTUP_SYS_PARAM_H
#define BASE_STARTUP_PROPERTY_H #define BASE_STARTUP_SYS_PARAM_H
#include <pthread.h> #include <pthread.h>
#include <stdio.h> #include <stdio.h>
#include <sys/types.h> #include <sys/types.h>
...@@ -25,35 +25,35 @@ extern "C" { ...@@ -25,35 +25,35 @@ extern "C" {
#endif #endif
#endif #endif
#define PROPERTY_VALUE_LEN_MAX 96 #define PARAM_VALUE_LEN_MAX 96
typedef u_int32_t PropertyHandle; typedef u_int32_t ParamHandle;
typedef struct { typedef struct {
u_int32_t serial; u_int32_t serial;
PropertyHandle handle; ParamHandle handle;
char value[PROPERTY_VALUE_LEN_MAX]; char value[PARAM_VALUE_LEN_MAX];
} PropertyCacheNode; } ParamCacheNode;
typedef const char *(*PropertyEvaluatePtr)(u_int32_t cacheCount, PropertyCacheNode *node); typedef const char *(*ParamEvaluatePtr)(u_int32_t cacheCount, ParamCacheNode *node);
typedef struct { typedef struct {
pthread_mutex_t lock; pthread_mutex_t lock;
u_int32_t serial; u_int32_t serial;
u_int32_t cacheCount; u_int32_t cacheCount;
PropertyEvaluatePtr evaluate; ParamEvaluatePtr evaluate;
PropertyCacheNode *cacheNode; ParamCacheNode *cacheNode;
} PropertyCache; } ParamCache;
/** /**
* 对外接口 * 对外接口
* 设置属性,主要用于其他进程使用,通过管道修改属性 * 设置参数,主要用于其他进程使用,通过管道修改参数
* *
*/ */
int SystemSetParameter(const char *name, const char *value); int SystemSetParameter(const char *name, const char *value);
/** /**
* 对外接口 * 对外接口
* 查询属性,主要用于其他进程使用,需要给定足够的内存保存属性 * 查询参数,主要用于其他进程使用,需要给定足够的内存保存参数
* 如果 value == null,获取value的长度 * 如果 value == null,获取value的长度
* 否则value的大小认为是len * 否则value的大小认为是len
* *
...@@ -61,28 +61,27 @@ int SystemSetParameter(const char *name, const char *value); ...@@ -61,28 +61,27 @@ int SystemSetParameter(const char *name, const char *value);
int SystemGetParameter(const char *name, char *value, unsigned int *len); int SystemGetParameter(const char *name, char *value, unsigned int *len);
/** /**
* 对外接口 * 外部接口
* 查询属性,主要用于其他进程使用,需要给定足够的内存保存属性。 * 遍历参数。
* 如果 value == null,获取value的长度
* 否则value的大小认为是len
* *
*/ */
int SystemGetParameterName(PropertyHandle handle, char *name, unsigned int len); int SystemTraversalParameter(void (*traversalParameter)(ParamHandle handle, void* cookie), void* cookie);
/** /**
* 对外接口 * 外部接口
* 遍历所有属性。 * 查询参数,主要用于其他进程使用,需要给定足够的内存保存参数。
* 如果 value == null,获取value的长度
* 否则value的大小认为是len
* *
*/ */
int SystemTraversalParameter(void (*traversalParameter)(PropertyHandle handle, void* cookie), void* cookie); int SystemGetParameterName(ParamHandle handle, char *name, unsigned int len);
/** /**
* 对外接口 * 外部接口
* 获取属性值。 * 获取参数值。
* *
*/ */
int SystemGetParameterValue(PropertyHandle handle, char *value, unsigned int *len); int SystemGetParameterValue(ParamHandle handle, char *value, unsigned int *len);
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
} }
......
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
if (defined(ohos_lite)) {
static_library("init_log") {
sources = [
"init_log.c",
]
public_deps = [
"//third_party/bounds_checking_function:libsec_static",
]
}
} else {
import("//build/ohos.gni")
ohos_static_library("init_log") {
sources = [
"init_log.c",
]
deps = [
"//third_party/bounds_checking_function:libsec_static",
]
part_name = "startup"
subsystem_name = "startup"
}
}
...@@ -28,9 +28,20 @@ ...@@ -28,9 +28,20 @@
#define MAX_LOG_SIZE 2048 #define MAX_LOG_SIZE 2048
#define BASE_YEAR 1900 #define BASE_YEAR 1900
void InitLog(int logLevel, const char *fileName, int line, const char *fmt, ...) static InitLogLevel g_logLevel = INIT_INFO;
static const char *LOG_LEVEL_STR[] = { "DEBUG", "INFO", "WARNING", "ERROR", "FATAL" };
void SetLogLevel(InitLogLevel logLevel)
{
g_logLevel = logLevel;
}
void InitLog(const char *tag, InitLogLevel logLevel, const char *fileName, int line, const char *fmt, ...)
{ {
UNUSED(logLevel); if (logLevel < g_logLevel) {
return;
}
va_list vargs; va_list vargs;
va_start(vargs, fmt); va_start(vargs, fmt);
...@@ -42,11 +53,13 @@ void InitLog(int logLevel, const char *fileName, int line, const char *fmt, ...) ...@@ -42,11 +53,13 @@ void InitLog(int logLevel, const char *fileName, int line, const char *fmt, ...)
time(&logTime); time(&logTime);
struct tm *t = gmtime(&logTime); struct tm *t = gmtime(&logTime);
char logInfo[MAX_LOG_SIZE]; char logInfo[MAX_LOG_SIZE];
if (snprintf_s(logInfo, MAX_LOG_SIZE, MAX_LOG_SIZE, "%d-%d-%d %d:%d %s %d : %s", (t->tm_year + BASE_YEAR), if (snprintf_s(logInfo, MAX_LOG_SIZE, MAX_LOG_SIZE, "%s %d-%d-%d %d:%d %s:%d [%s] [pid=%d] %s", tag,
(t->tm_mon + 1), t->tm_mday, t->tm_hour, t->tm_min, fileName, line, tmpFmt) == -1) { (t->tm_year + BASE_YEAR), (t->tm_mon + 1), t->tm_mday, t->tm_hour, t->tm_min, fileName, line,
LOG_LEVEL_STR[logLevel], getpid(), tmpFmt) == -1) {
return; return;
} }
printf("%s", logInfo );
#if 0
int fd = open("/dev/kmsg", O_WRONLY | O_CLOEXEC | O_APPEND ); int fd = open("/dev/kmsg", O_WRONLY | O_CLOEXEC | O_APPEND );
if (fd < 1) { if (fd < 1) {
printf("xxxxxxxxxxxxxxx open failed. %d\n", errno); printf("xxxxxxxxxxxxxxx open failed. %d\n", errno);
...@@ -54,8 +67,11 @@ void InitLog(int logLevel, const char *fileName, int line, const char *fmt, ...) ...@@ -54,8 +67,11 @@ void InitLog(int logLevel, const char *fileName, int line, const char *fmt, ...)
} }
if (write(fd, logInfo, strlen(logInfo)) < -1) { if (write(fd, logInfo, strlen(logInfo)) < -1) {
printf("xxxxxxxxxxxxxxx write failed.%d\n", errno); printf("xxxxxxxxxxxxxxx write failed.%d\n", errno);
close(fd);
return; return;
} }
close(fd);
#endif
va_end(vargs); va_end(vargs);
} }
...@@ -18,6 +18,7 @@ ...@@ -18,6 +18,7 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <unistd.h>
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
...@@ -25,13 +26,13 @@ extern "C" { ...@@ -25,13 +26,13 @@ extern "C" {
#endif #endif
#endif #endif
typedef enum StatupLogLevel { typedef enum InitLogLevel {
STARTUP_DEBUG = 0, INIT_DEBUG = 0,
STARTUP_INFO, INIT_INFO,
STARTUP_WARN, INIT_WARN,
STARTUP_ERROR, INIT_ERROR,
STARTUP_FATAL INIT_FATAL
} StatupLogLevel; } InitLogLevel;
#define __FILE_NAME__ (strrchr((__FILE__), '/') ? strrchr((__FILE__), '/') + 1 : (__FILE__)) #define __FILE_NAME__ (strrchr((__FILE__), '/') ? strrchr((__FILE__), '/') + 1 : (__FILE__))
...@@ -41,14 +42,17 @@ typedef enum StatupLogLevel { ...@@ -41,14 +42,17 @@ typedef enum StatupLogLevel {
#define INIT_LOGI(format, ...) printf("%s %d: "format, __FILE_NAME__, __LINE__, ##__VA_ARGS__) #define INIT_LOGI(format, ...) printf("%s %d: "format, __FILE_NAME__, __LINE__, ##__VA_ARGS__)
#define INIT_LOGD(format, ...) printf("%s %d: "format, __FILE_NAME__, __LINE__, ##__VA_ARGS__) #define INIT_LOGD(format, ...) printf("%s %d: "format, __FILE_NAME__, __LINE__, ##__VA_ARGS__)
#else #else
#define INIT_LOGE(format, ...) printf("%s %d: "format, __FILE_NAME__, __LINE__, ##__VA_ARGS__) #define INIT_LOGD(format, ...) InitLog("[Init]", INIT_DEBUG, (__FILE_NAME__), (__LINE__), format, ##__VA_ARGS__)
#define INIT_LOGW(format, ...) printf("%s %d: "format, __FILE_NAME__, __LINE__, ##__VA_ARGS__) #define INIT_LOGI(format, ...) InitLog("[Init]", INIT_INFO, (__FILE_NAME__), (__LINE__), format, ##__VA_ARGS__)
#define INIT_LOGI(format, ...) printf("%s %d: "format, __FILE_NAME__, __LINE__, ##__VA_ARGS__) #define INIT_LOGW(format, ...) InitLog("[Init]", INIT_WARN, (__FILE_NAME__), (__LINE__), format, ##__VA_ARGS__)
#define INIT_LOGD(format, ...) printf("%s %d: "format, __FILE_NAME__, __LINE__, ##__VA_ARGS__) #define INIT_LOGE(format, ...) InitLog("[Init]", INIT_ERROR, (__FILE_NAME__), (__LINE__), format, ##__VA_ARGS__)
void InitLog(int logLevel, const char *fileName, int line, const char *fmt, ...); #define INIT_LOGF(format, ...) InitLog("[Init]", INIT_FATAL, (__FILE_NAME__), (__LINE__), format, ##__VA_ARGS__)
void Logger(StatupLogLevel level, const char *format, ...);
#endif void InitLog(const char *tag, InitLogLevel logLevel, const char *fileName, int line, const char *fmt, ...);
void SetLogLevel(InitLogLevel logLevel);
void Logger(InitLogLevel level, const char *format, ...);
#endif
#define INIT_ERROR_CHECK(ret, statement, format, ...) \ #define INIT_ERROR_CHECK(ret, statement, format, ...) \
if (!(ret)) { \ if (!(ret)) { \
...@@ -66,21 +70,21 @@ void Logger(StatupLogLevel level, const char *format, ...); ...@@ -66,21 +70,21 @@ void Logger(StatupLogLevel level, const char *format, ...);
static constexpr OHOS::HiviewDFX::HiLogLabel STARTUP_LABEL = {LOG_CORE, 0, "STARTUP"}; static constexpr OHOS::HiviewDFX::HiLogLabel STARTUP_LABEL = {LOG_CORE, 0, "STARTUP"};
StatupLogLevel level_; InitLogLevel level_;
int JudgeLevel(const StatupLogLevel level) { return return; } int JudgeLevel(const InitLogLevel level) { return return; }
#define STARTUP_LOG(LEVEL, LABEL, Level, fmt, ...) \ #define STARTUP_LOG(LEVEL, LABEL, Level, fmt, ...) \
Logger(__FILE_NAME__, (__LINE__), fmt, ##__VA_ARGS__); \ InitLog("[Init]", LEVEL, __FILE_NAME__, (__LINE__), fmt, ##__VA_ARGS__); \
if (JudgeLevel(StatupLogLevel::LEVEL)) \ if (JudgeLevel(InitLogLevel::LEVEL)) \
OHOS::HiviewDFX::HiLog::Level(STARTUP_LABEL, "[%{public}s(%{public}d)] " fmt, \ OHOS::HiviewDFX::HiLog::Level(STARTUP_LABEL, "[%{public}s(%{public}d)] " fmt, \
__FILE_NAME__, __LINE__, ##__VA_ARGS__) __FILE_NAME__, __LINE__, ##__VA_ARGS__)
#else #else
#define STARTUP_LOG(LEVEL, LABEL, Level, fmt, ...) \ #define STARTUP_LOG(LEVEL, LABEL, Level, fmt, ...) \
printf("[%s][%s:%d] " fmt "\n", LABEL, __FILE_NAME__, __LINE__, ##__VA_ARGS__); printf("[%s:%d][%s:%d] " fmt "\n", LABEL, getpid(), __FILE_NAME__, __LINE__, ##__VA_ARGS__);
#endif #endif
#define STARTUP_LOGI(LABEL, fmt, ...) STARTUP_LOG(STARTUP_INFO, LABEL, Info, fmt, ##__VA_ARGS__) #define STARTUP_LOGI(LABEL, fmt, ...) STARTUP_LOG(INIT_INFO, LABEL, Info, fmt, ##__VA_ARGS__)
#define STARTUP_LOGE(LABEL, fmt, ...) STARTUP_LOG(STARTUP_ERROR, LABEL, Error, fmt, ##__VA_ARGS__) #define STARTUP_LOGE(LABEL, fmt, ...) STARTUP_LOG(INIT_ERROR, LABEL, Error, fmt, ##__VA_ARGS__)
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
......
# Copyright (c) 2020 Huawei Device Co., Ltd. # Copyright (c) 2020 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at # You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0 # http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, software # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import("//build/ohos.gni")
import("//build/ohos.gni")
ohos_static_library("paramservice") {
ohos_static_library("propertyserver") { sources = [
sources = [ "//base/startup/init_lite/services/src/init_utils.c",
"manager/property_manager.c", "manager/param_cache.c",
"manager/property_trie.c", "manager/param_manager.c",
"manager/property_cache.c", "manager/param_trie.c",
"service/property_service.c", "service/param_persist.c",
"service/property_persist.c", "service/param_service.c",
"//base/startup/init_lite/services/src/init_utils.c", "trigger/trigger_checker.c",
] "trigger/trigger_manager.c",
"trigger/trigger_processor.c",
include_dirs = [ ]
"include",
"//base/startup/init_lite/services/include/property", include_dirs = [
"//base/startup/init_lite/services/include/trigger", "include",
"//base/startup/init_lite/services/include", "//base/startup/init_lite/services/include/param",
"//third_party/libuv/include", "//base/startup/init_lite/services/include",
"//third_party/cJSON", "//base/startup/init_lite/services/log",
] "//third_party/libuv/include",
"//third_party/cJSON",
deps = [ ]
"//third_party/libuv:uv_static",
"//base/startup/init_lite/services/trigger:triggerservice", deps = [
"//third_party/bounds_checking_function:libsec_static", "//third_party/bounds_checking_function:libsec_static",
] "//third_party/libuv:uv_static",
part_name = "init" ]
subsystem_name = "startup" part_name = "init"
} subsystem_name = "startup"
}
ohos_static_library("propertyclient") {
sources = [ ohos_static_library("paramclient") {
"manager/property_manager.c", sources = [
"client/property_request.c", "//base/startup/init_lite/services/src/init_utils.c",
"manager/property_trie.c", "client/param_request.c",
"manager/property_cache.c", "manager/param_cache.c",
"//base/startup/init_lite/services/src/init_utils.c", "manager/param_manager.c",
] "manager/param_trie.c",
]
include_dirs = [
"include", include_dirs = [
"//base/startup/init_lite/services/include/property", "include",
"//base/startup/init_lite/services/include/trigger", "//base/startup/init_lite/services/include/param",
"//base/startup/init_lite/services/include", "//base/startup/init_lite/services/include",
"//third_party/libuv/include", "//base/startup/init_lite/services/log",
"//third_party/cJSON", "//third_party/libuv/include",
] "//third_party/cJSON",
]
deps = [
"//third_party/libuv:uv_static", deps = [
"//third_party/bounds_checking_function:libsec_static", "//third_party/bounds_checking_function:libsec_static",
] "//third_party/libuv:uv_static",
part_name = "init" "//base/startup/init_lite/services/log:init_log"
subsystem_name = "startup" ]
} part_name = "init"
subsystem_name = "startup"
ohos_executable("getparam") { }
sources = [
"cmd/property_get.c", ohos_executable("getparam") {
] sources = [
include_dirs = [ "cmd/param_get.c",
"include", ]
"//base/startup/init_lite/services/include/property", include_dirs = [
"//base/startup/init_lite/services/include/trigger", "include",
"//base/startup/init_lite/services/include", "//base/startup/init_lite/services/include/param",
] "//base/startup/init_lite/services/include",
deps = [ "//base/startup/init_lite/services/log",
"//base/startup/init_lite/services/property:propertyclient", ]
"//third_party/bounds_checking_function:libsec_static", deps = [
"//third_party/cJSON:cjson_static", "//base/startup/init_lite/services/param:paramclient",
] "//third_party/bounds_checking_function:libsec_static",
install_enable = true "//third_party/cJSON:cjson_static",
part_name = "init" ]
} install_enable = true
part_name = "init"
ohos_executable("setparam") { }
sources = [
"cmd/property_set.c", ohos_executable("setparam") {
] sources = [
include_dirs = [ "cmd/param_set.c",
"include", ]
"//base/startup/init_lite/services/include/property", include_dirs = [
"//base/startup/init_lite/services/include/trigger", "include",
"//base/startup/init_lite/services/include", "//base/startup/init_lite/services/include/param",
] "//base/startup/init_lite/services/include",
deps = [ "//base/startup/init_lite/services/log",
"//base/startup/init_lite/services/property:propertyclient", ]
"//third_party/bounds_checking_function:libsec_static", deps = [
"//third_party/cJSON:cjson_static", "//base/startup/init_lite/services/param:paramclient",
] "//third_party/bounds_checking_function:libsec_static",
install_enable = true "//third_party/cJSON:cjson_static",
part_name = "init" ]
} install_enable = true
part_name = "init"
}
...@@ -13,57 +13,60 @@ ...@@ -13,57 +13,60 @@
* limitations under the License. * limitations under the License.
*/ */
#include "property_request.h" #include "param_request.h"
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include <time.h> #include <time.h>
#include "property_manager.h" #include "param_manager.h"
#include "uv.h" #include "uv.h"
#define LABEL "Client" #define LABEL "Client"
#define BUFFER_SIZE 200 #define BUFFER_SIZE 200
#define PropertyEntry(ptr, type, member) (type *)((char *)(ptr) - offsetof(type, member)) #define ParamEntry(ptr, type, member) (type *)((char *)(ptr) - offsetof(type, member))
static PropertyWorkSpace g_propertyWorkSpaceReadOnly = {ATOMIC_VAR_INIT(0), {}, {}, {}}; static ParamWorkSpace g_paramWorkSpaceReadOnly = {ATOMIC_VAR_INIT(0), {}, {}, {}};
static void OnWrite(uv_write_t* req, int status) static void OnWrite(uv_write_t *req, int status)
{ {
PROPERTY_LOGI("OnWrite status %d", status); PARAM_LOGI("OnWrite status %d", status);
} }
static void OnReceiveAlloc(uv_handle_t* handle, size_t suggestedSize, uv_buf_t* buf) static void OnReceiveAlloc(uv_handle_t* handle, size_t suggestedSize, uv_buf_t* buf)
{ {
// 这里需要按实际回复大小申请内存,不需要大内存 // 这里需要按实际回复大小申请内存,不需要大内存
buf->base = (char *)malloc(sizeof(ResponseMsg)); buf->base = (char *)malloc(sizeof(ResponseMsg));
buf->len = suggestedSize; buf->len = sizeof(ResponseMsg);
PROPERTY_LOGI("OnReceiveAlloc handle %p %zu", handle, suggestedSize); PARAM_LOGI("OnReceiveAlloc handle %p %zu", handle, suggestedSize);
} }
static void OnReceiveResponse(uv_stream_t *handle, ssize_t nread, const uv_buf_t *buf) static void OnReceiveResponse(uv_stream_t *handle, ssize_t nread, const uv_buf_t *buf)
{ {
RequestNode *req = PropertyEntry(handle, RequestNode, handle); RequestNode *req = ParamEntry(handle, RequestNode, handle);
PROPERTY_LOGI("OnReceiveResponse %p", handle); PARAM_LOGI("OnReceiveResponse %p", handle);
if (nread <= 0 || buf == NULL || buf->base == NULL) { if (nread <= 0 || buf == NULL || handle == NULL || buf->base == NULL) {
free(buf->base); if (buf != NULL && buf->base != NULL) {
uv_close((uv_handle_t*)handle, NULL); free(buf->base);
uv_stop(req->loop); }
if (handle != NULL) {
uv_close((uv_handle_t*)handle, NULL);
uv_stop(req->loop);
}
return; return;
} }
ResponseMsg *response = (ResponseMsg *)(buf->base); ResponseMsg *response = (ResponseMsg *)(buf->base);
PROPERTY_CHECK(response != NULL, return, "The response is null"); PARAM_CHECK(response != NULL, return, "The response is null");
PROPERTY_LOGI("OnReceiveResponse %p cmd %d result: %d", handle, response->type, response->result); PARAM_LOGI("OnReceiveResponse %p cmd %d result: %d", handle, response->type, response->result);
switch (response->type) { switch (response->type) {
case SET_PROPERTY: case SET_PARAM:
req->result = response->result; req->result = response->result;
break; break;
default: default:
PROPERTY_LOGE("not supported the command: %d", response->type); PARAM_LOGE("not supported the command: %d", response->type);
break; break;
} }
PARAM_LOGE("Close handle %p", handle);
PROPERTY_LOGE("Close handle %p", handle);
free(buf->base); free(buf->base);
uv_close((uv_handle_t*)handle, NULL); uv_close((uv_handle_t*)handle, NULL);
uv_stop(req->loop); uv_stop(req->loop);
...@@ -71,28 +74,28 @@ static void OnReceiveResponse(uv_stream_t *handle, ssize_t nread, const uv_buf_t ...@@ -71,28 +74,28 @@ static void OnReceiveResponse(uv_stream_t *handle, ssize_t nread, const uv_buf_t
static void OnConnection(uv_connect_t *connect, int status) static void OnConnection(uv_connect_t *connect, int status)
{ {
PROPERTY_CHECK(status >= 0, return, "Failed to conntect status %s", uv_strerror(status)); PARAM_CHECK(status >= 0, return, "Failed to conntect status %s", uv_strerror(status));
uv_write_t wr; RequestNode *request = ParamEntry(connect, RequestNode, connect);
RequestNode *request = PropertyEntry(connect, RequestNode, connect); PARAM_LOGI("Connect to server handle %p", &(request->handle));
PROPERTY_LOGI("Connect to server handle %p", &(request->handle));
uv_buf_t buf = uv_buf_init((char*)&request->msg, request->msg.contentSize + sizeof(request->msg)); uv_buf_t buf = uv_buf_init((char*)&request->msg, request->msg.contentSize + sizeof(request->msg));
int ret = uv_write2(&wr, (uv_stream_t*)&(request->handle), &buf, 1, (uv_stream_t*)&(request->handle), OnWrite); int ret = uv_write2(&request->wr, (uv_stream_t*)&(request->handle), &buf, 1, (uv_stream_t*)&(request->handle), OnWrite);
PROPERTY_CHECK(ret >= 0, return, "Failed to uv_write2 porperty"); PARAM_CHECK(ret >= 0, return, "Failed to uv_write2 porperty");
// read result // read result
ret = uv_read_start((uv_stream_t*)&(request->handle), OnReceiveAlloc, OnReceiveResponse); ret = uv_read_start((uv_stream_t*)&(request->handle), OnReceiveAlloc, OnReceiveResponse);
PROPERTY_CHECK(ret >= 0, return, "Failed to uv_read_start response"); PARAM_CHECK(ret >= 0, return, "Failed to uv_read_start response");
} }
static int StartRequest(int cmd, RequestNode *request) static int StartRequest(int cmd, RequestNode *request)
{ {
PROPERTY_CHECK(request != NULL, return -1, "Invalid request"); PARAM_CHECK(request != NULL, return -1, "Invalid request");
request->result = -1; request->result = -1;
request->msg.type = cmd; request->msg.type = cmd;
request->loop = uv_loop_new(); request->loop = uv_loop_new();
uv_pipe_init(request->loop, &request->handle, 1); uv_pipe_init(request->loop, &request->handle, 1);
uv_pipe_connect(&request->connect, &request->handle, PIPE_NAME, OnConnection); uv_pipe_connect(&request->connect, &request->handle, PIPE_NAME, OnConnection);
uv_run(request->loop, UV_RUN_DEFAULT); uv_run(request->loop, UV_RUN_DEFAULT);
uv_loop_delete(request->loop);
int result = request->result; int result = request->result;
free(request); free(request);
return result; return result;
...@@ -100,57 +103,58 @@ static int StartRequest(int cmd, RequestNode *request) ...@@ -100,57 +103,58 @@ static int StartRequest(int cmd, RequestNode *request)
int SystemSetParameter(const char *name, const char *value) int SystemSetParameter(const char *name, const char *value)
{ {
PROPERTY_CHECK(name != NULL && value != NULL, return -1, "Invalid param"); PARAM_CHECK(name != NULL && value != NULL, return -1, "Invalid param");
int ret = CheckPropertyName(name, 0); int ret = CheckParamName(name, 0);
PROPERTY_CHECK(ret == 0, return ret, "Illegal property name"); PARAM_CHECK(ret == 0, return ret, "Illegal param name");
PROPERTY_LOGI("StartRequest %s", name); PARAM_LOGI("StartRequest %s", name);
u_int32_t msgSize = sizeof(RequestMsg) + strlen(name) + strlen(value) + 2; u_int32_t msgSize = sizeof(RequestMsg) + strlen(name) + strlen(value) + 2;
RequestNode *request = (RequestNode *)malloc(sizeof(RequestNode) + msgSize); RequestNode *request = (RequestNode *)malloc(sizeof(RequestNode) + msgSize);
PROPERTY_CHECK(request != NULL, return -1, "Failed to malloc for connect"); PARAM_CHECK(request != NULL, return -1, "Failed to malloc for connect");
memset_s(request, sizeof(RequestNode), 0, sizeof(RequestNode));
// 带字符串结束符 // 带字符串结束符
int contentSize = BuildPropertyContent(request->msg.content, msgSize - sizeof(RequestMsg), name, value); int contentSize = BuildParamContent(request->msg.content, msgSize - sizeof(RequestMsg), name, value);
PROPERTY_CHECK(contentSize > 0, return -1, "Failed to copy porperty"); PARAM_CHECK(contentSize > 0, free(request); return -1, "Failed to copy porperty");
request->msg.contentSize = contentSize; request->msg.contentSize = contentSize;
return StartRequest(SET_PROPERTY, request); return StartRequest(SET_PARAM, request);
} }
int SystemGetParameter(const char *name, char *value, unsigned int *len) int SystemGetParameter(const char *name, char *value, unsigned int *len)
{ {
PROPERTY_CHECK(name != NULL && len != NULL, return -1, "The name or value is null"); PARAM_CHECK(name != NULL && len != NULL, return -1, "The name or value is null");
InitPropertyWorkSpace(&g_propertyWorkSpaceReadOnly, 1, NULL); InitParamWorkSpace(&g_paramWorkSpaceReadOnly, 1, NULL);
PropertyHandle handle = 0; ParamHandle handle = 0;
int ret = ReadPropertyWithCheck(&g_propertyWorkSpaceReadOnly, name, &handle); int ret = ReadParamWithCheck(&g_paramWorkSpaceReadOnly, name, &handle);
PROPERTY_CHECK(ret == 0, return ret, "Can not get param for %s", name); PARAM_CHECK(ret == 0, return ret, "Can not get param for %s", name);
return ReadPropertyValue(&g_propertyWorkSpaceReadOnly, handle, value, len); return ReadParamValue(&g_paramWorkSpaceReadOnly, handle, value, len);
} }
int SystemGetParameterName(PropertyHandle handle, char *name, unsigned int len) int SystemGetParameterName(ParamHandle handle, char *name, unsigned int len)
{ {
PROPERTY_CHECK(name != NULL && handle != 0, return -1, "The name is null"); PARAM_CHECK(name != NULL && handle != 0, return -1, "The name is null");
InitPropertyWorkSpace(&g_propertyWorkSpaceReadOnly, 1, NULL); InitParamWorkSpace(&g_paramWorkSpaceReadOnly, 1, NULL);
return ReadPropertyName(&g_propertyWorkSpaceReadOnly, handle, name, len); return ReadParamName(&g_paramWorkSpaceReadOnly, handle, name, len);
} }
int SystemGetParameterValue(PropertyHandle handle, char *value, unsigned int *len) int SystemGetParameterValue(ParamHandle handle, char *value, unsigned int *len)
{ {
PROPERTY_CHECK(len != NULL && handle != 0, return -1, "The value is null"); PARAM_CHECK(len != NULL && handle != 0, return -1, "The value is null");
InitPropertyWorkSpace(&g_propertyWorkSpaceReadOnly, 1, NULL); InitParamWorkSpace(&g_paramWorkSpaceReadOnly, 1, NULL);
return ReadPropertyValue(&g_propertyWorkSpaceReadOnly, handle, value, len); return ReadParamValue(&g_paramWorkSpaceReadOnly, handle, value, len);
} }
int SystemTraversalParameter(void (*traversalParameter)(PropertyHandle handle, void* cookie), void* cookie) int SystemTraversalParameter(void (*traversalParameter)(ParamHandle handle, void* cookie), void* cookie)
{ {
PROPERTY_CHECK(traversalParameter != NULL, return -1, "The param is null"); PARAM_CHECK(traversalParameter != NULL, return -1, "The param is null");
InitPropertyWorkSpace(&g_propertyWorkSpaceReadOnly, 1, NULL); InitParamWorkSpace(&g_paramWorkSpaceReadOnly, 1, NULL);
return TraversalProperty(&g_propertyWorkSpaceReadOnly, traversalParameter, cookie); return TraversalParam(&g_paramWorkSpaceReadOnly, traversalParameter, cookie);
} }
const char *SystemDetectPropertyChange(PropertyCache *cache, const char *SystemDetectParamChange(ParamCache *cache,
PropertyEvaluatePtr evaluate, u_int32_t count, const char *properties[][2]) ParamEvaluatePtr evaluate, u_int32_t count, const char *parameters[][2])
{ {
PROPERTY_CHECK(cache != NULL && evaluate != NULL && properties != NULL, return NULL, "The param is null"); PARAM_CHECK(cache != NULL && evaluate != NULL && parameters != NULL, return NULL, "The param is null");
return DetectPropertyChange(&g_propertyWorkSpaceReadOnly, cache, evaluate, count, properties); return DetectParamChange(&g_paramWorkSpaceReadOnly, cache, evaluate, count, parameters);
} }
...@@ -15,17 +15,17 @@ ...@@ -15,17 +15,17 @@
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#include "property.h" #include "sys_param.h"
#define HELP_PARAM "--help" #define HELP_PARAM "--help"
#define BUFFER_SIZE 256 #define BUFFER_SIZE 256
static void ProcessParam(PropertyHandle handle, void* cookie) static void ProcessParam(ParamHandle handle, void* cookie)
{ {
SystemGetParameterName(handle, (char*)cookie, BUFFER_SIZE); SystemGetParameterName(handle, (char*)cookie, BUFFER_SIZE);
u_int32_t size = BUFFER_SIZE; u_int32_t size = BUFFER_SIZE;
SystemGetParameterValue(handle, ((char*)cookie) + BUFFER_SIZE, &size); SystemGetParameterValue(handle, ((char*)cookie) + BUFFER_SIZE, &size);
printf("\t%s=%s \n", (char*)cookie, ((char*)cookie) + BUFFER_SIZE); printf("\t%s = %s \n", (char*)cookie, ((char*)cookie) + BUFFER_SIZE);
} }
int main(int argc, char* argv[]) int main(int argc, char* argv[])
...@@ -36,19 +36,20 @@ int main(int argc, char* argv[]) ...@@ -36,19 +36,20 @@ int main(int argc, char* argv[])
return 0; return 0;
} }
if (argc == 2 && strncmp(argv[1], HELP_PARAM, strlen(HELP_PARAM)) == 0) { // 显示帮助 if (argc == 2 && strncmp(argv[1], HELP_PARAM, strlen(HELP_PARAM)) == 0) { // 显示帮助
printf("usage: getprop NAME VALUE\n"); printf("usage: getparam NAME VALUE\n");
return 0; return 0;
} }
if (argc != 2) { if (argc != 2) {
printf("usage: getprop NAME VALUE\n"); printf("usage: getparam NAME VALUE\n");
return 0; return 0;
} }
char value[BUFFER_SIZE] = {0}; char value[BUFFER_SIZE] = {0};
u_int32_t size = BUFFER_SIZE; u_int32_t size = BUFFER_SIZE;
int ret = SystemGetParameter(argv[1], value, &size); int ret = SystemGetParameter(argv[1], value, &size);
if (ret == 0) { if (ret == 0) {
printf("getparm %s %s \n", argv[1], value); printf("getparam %s %s \n", argv[1], value);
} else { } else {
printf("getparm %s %s fail\n", argv[1], value); printf("getparam %s %s fail\n", argv[1], value);
} }
} }
...@@ -16,24 +16,24 @@ ...@@ -16,24 +16,24 @@
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#include "property.h" #include "sys_param.h"
#define HELP_PARAM "--help" #define HELP_PARAM "--help"
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ {
if (argc == 1 || argc > 3) { if (argc == 1 || argc > 3) {
printf("setparm: Need 2 arguments (see \"setparm --help\")\n"); printf("setparam: Need 2 arguments (see \"setparam --help\")\n");
return 0; return 0;
} }
if (argc == 2 && strncmp(argv[1], HELP_PARAM, strlen(HELP_PARAM)) == 0) { if (argc == 2 && strncmp(argv[1], HELP_PARAM, strlen(HELP_PARAM)) == 0) {
printf("usage: setprop NAME VALUE\n"); printf("usage: setparam NAME VALUE\n");
return 0; return 0;
} }
int ret = SystemSetParameter(argv[1], argv[2]); int ret = SystemSetParameter(argv[1], argv[2]);
if (ret == 0) { if (ret == 0) {
printf("setparm %s %s success\n", argv[1], argv[2]); printf("setparam %s %s success\n", argv[1], argv[2]);
} else { } else {
printf("setparm %s %s fail\n", argv[1], argv[2]); printf("setparam %s %s fail\n", argv[1], argv[2]);
} }
} }
...@@ -13,16 +13,15 @@ ...@@ -13,16 +13,15 @@
* limitations under the License. * limitations under the License.
*/ */
#ifndef BASE_STARTUP_PROPERTY_MANAGER_H #ifndef BASE_STARTUP_PARAM_MANAGER_H
#define BASE_STARTUP_PROPERTY_MANAGER_H #define BASE_STARTUP_PARAM_MANAGER_H
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "init_log.h" #include "init_log.h"
#include "property.h" #include "sys_param.h"
#include "property_trie.h" #include "param_trie.h"
#include "securec.h" #include "securec.h"
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
extern "C" { extern "C" {
...@@ -30,31 +29,31 @@ extern "C" { ...@@ -30,31 +29,31 @@ extern "C" {
#endif #endif
typedef enum { typedef enum {
PROPERTY_CODE_INVALID_PARAM = 100, PARAM_CODE_INVALID_PARAM = 100,
PROPERTY_CODE_INVALID_NAME, PARAM_CODE_INVALID_NAME,
PROPERTY_CODE_INVALID_VALUE, PARAM_CODE_INVALID_VALUE,
PROPERTY_CODE_REACHED_MAX, PARAM_CODE_REACHED_MAX,
PROPERTY_CODE_PERMISSION_DENIED, PARAM_CODE_PERMISSION_DENIED,
PROPERTY_CODE_READ_ONLY_PROPERTY, PARAM_CODE_READ_ONLY_PROPERTY,
PROPERTY_CODE_NOT_SUPPORT, PARAM_CODE_NOT_SUPPORT,
PROPERTY_CODE_ERROR_MAP_FILE, PARAM_CODE_ERROR_MAP_FILE,
PROPERTY_CODE_NOT_FOUND_PROP, PARAM_CODE_NOT_FOUND_PROP,
PROPERTY_CODE_NOT_INIT PARAM_CODE_NOT_INIT
} PROPERTY_CODE; } PARAM_CODE;
#define IS_READY_ONLY(name) strncmp((name), "ro.", strlen("ro.")) == 0 #define IS_READY_ONLY(name) strncmp((name), "ro.", strlen("ro.")) == 0
#define LABEL_STRING_LEN 128 #define LABEL_STRING_LEN 128
#ifdef STARTUP_LOCAL #ifdef STARTUP_LOCAL
#define PIPE_NAME "/tmp/propertyservice.sock" #define PIPE_NAME "/tmp/paramservice"
#define PROPERTY_STORAGE_PATH "/media/sf_ubuntu/test/__properties__/property_storage" #define PARAM_STORAGE_PATH "/media/sf_ubuntu/test/__parameters__/param_storage"
#define PROPERTY_PERSIST_PATH "/media/sf_ubuntu/test/property/persist_properties.property" #define PARAM_PERSIST_PATH "/media/sf_ubuntu/test/param/persist_parameters"
#define PROPERTY_INFO_PATH "/media/sf_ubuntu/test/__properties__/property_info" #define PARAM_INFO_PATH "/media/sf_ubuntu/test/__parameters__/param_info"
#else #else
#define PIPE_NAME "/dev/unix/socket/PropertyService" #define PIPE_NAME "/dev/unix/socket/paramservice"
#define PROPERTY_STORAGE_PATH "/dev/__properties__/property_storage" #define PARAM_STORAGE_PATH "/dev/__parameters__/param_storage"
#define PROPERTY_PERSIST_PATH "/data/property/persist_properties.property" #define PARAM_PERSIST_PATH "/data/param/persist_parameters"
#define PROPERTY_INFO_PATH "/dev/__properties__/property_info" #define PARAM_INFO_PATH "/dev/__parameters__/param_info"
#endif #endif
#define SUBSTR_INFO_NAME 0 #define SUBSTR_INFO_NAME 0
...@@ -65,12 +64,12 @@ typedef enum { ...@@ -65,12 +64,12 @@ typedef enum {
#define WORKSPACE_FLAGS_INIT 0x01 #define WORKSPACE_FLAGS_INIT 0x01
#define WORKSPACE_FLAGS_LOADED 0x02 #define WORKSPACE_FLAGS_LOADED 0x02
#define PROPERTY_LOGI(fmt, ...) STARTUP_LOGI(LABEL, fmt, ##__VA_ARGS__) #define PARAM_LOGI(fmt, ...) STARTUP_LOGI(LABEL, fmt, ##__VA_ARGS__)
#define PROPERTY_LOGE(fmt, ...) STARTUP_LOGE(LABEL, fmt, ##__VA_ARGS__) #define PARAM_LOGE(fmt, ...) STARTUP_LOGE(LABEL, fmt, ##__VA_ARGS__)
#define PROPERTY_CHECK(retCode, exper, ...) \ #define PARAM_CHECK(retCode, exper, ...) \
if (!(retCode)) { \ if (!(retCode)) { \
PROPERTY_LOGE(__VA_ARGS__); \ PARAM_LOGE(__VA_ARGS__); \
exper; \ exper; \
} }
...@@ -90,72 +89,67 @@ typedef struct UserCred { ...@@ -90,72 +89,67 @@ typedef struct UserCred {
typedef struct { typedef struct {
char label[LABEL_STRING_LEN]; char label[LABEL_STRING_LEN];
UserCred cred; UserCred cred;
} PropertySecurityLabel; } ParamSecurityLabel;
typedef struct PropertyAuditData { typedef struct ParamAuditData {
const UserCred *cr; const UserCred *cr;
const char *name; const char *name;
} PropertyAuditData; } ParamAuditData;
typedef struct { typedef struct {
atomic_uint_least32_t flags; atomic_uint_least32_t flags;
WorkSpace propertyLabelSpace; WorkSpace paramLabelSpace;
WorkSpace propertySpace; WorkSpace paramSpace;
PropertySecurityLabel label; ParamSecurityLabel label;
} PropertyWorkSpace; } ParamWorkSpace;
typedef struct { typedef struct {
atomic_uint_least32_t flags; atomic_uint_least32_t flags;
WorkSpace persistWorkSpace; WorkSpace persistWorkSpace;
} PropertyPersistWorkSpace; } ParamPersistWorkSpace;
typedef struct { typedef struct {
char value[128]; char value[128];
} SubStringInfo; } SubStringInfo;
int InitPropertyWorkSpace(PropertyWorkSpace *workSpace, int onlyRead, const char *context); int InitParamWorkSpace(ParamWorkSpace *workSpace, int onlyRead, const char *context);
void ClosePropertyWorkSpace(PropertyWorkSpace *workSpace); void CloseParamWorkSpace(ParamWorkSpace *workSpace);
int ReadPropertyWithCheck(PropertyWorkSpace *workSpace, const char *name, PropertyHandle *handle); int ReadParamWithCheck(ParamWorkSpace *workSpace, const char *name, ParamHandle *handle);
int ReadPropertyValue(PropertyWorkSpace *workSpace, PropertyHandle handle, char *value, u_int32_t *len); int ReadParamValue(ParamWorkSpace *workSpace, ParamHandle handle, char *value, u_int32_t *len);
int ReadPropertyName(PropertyWorkSpace *workSpace, PropertyHandle handle, char *name, u_int32_t len); int ReadParamName(ParamWorkSpace *workSpace, ParamHandle handle, char *name, u_int32_t len);
u_int32_t ReadPropertySerial(PropertyWorkSpace *workSpace, PropertyHandle handle); u_int32_t ReadParamSerial(ParamWorkSpace *workSpace, ParamHandle handle);
int AddProperty(WorkSpace *workSpace, const char *name, const char *value); int AddParam(WorkSpace *workSpace, const char *name, const char *value);
int WriteProperty(WorkSpace *workSpace, const char *name, const char *value); int WriteParam(WorkSpace *workSpace, const char *name, const char *value);
int WritePropertyWithCheck(PropertyWorkSpace *workSpace, int WriteParamWithCheck(ParamWorkSpace *workSpace,
const PropertySecurityLabel *srcLabel, const char *name, const char *value); const ParamSecurityLabel *srcLabel, const char *name, const char *value);
int WritePropertyInfo(PropertyWorkSpace *workSpace, SubStringInfo *info, int subStrNumber); int WriteParamInfo(ParamWorkSpace *workSpace, SubStringInfo *info, int subStrNumber);
int CheckPropertyValue(WorkSpace *workSpace, const TrieDataNode *node, const char *name, const char *value); int CheckParamValue(WorkSpace *workSpace, const TrieDataNode *node, const char *name, const char *value);
int CheckPropertyName(const char *name, int propInfo); int CheckParamName(const char *name, int paramInfo);
int CanReadProperty(PropertyWorkSpace *workSpace, u_int32_t labelIndex, const char *name); int CanReadParam(ParamWorkSpace *workSpace, u_int32_t labelIndex, const char *name);
int CanWriteProperty(PropertyWorkSpace *workSpace, int CanWriteParam(ParamWorkSpace *workSpace,
const PropertySecurityLabel *srcLabel, const TrieDataNode *node, const char *name, const char *value); const ParamSecurityLabel *srcLabel, const TrieDataNode *node, const char *name, const char *value);
int CheckMacPerms(PropertyWorkSpace *workSpace, int CheckMacPerms(ParamWorkSpace *workSpace,
const PropertySecurityLabel *srcLabel, const char *name, u_int32_t labelIndex); const ParamSecurityLabel *srcLabel, const char *name, u_int32_t labelIndex);
int CheckControlPropertyPerms(PropertyWorkSpace *workSpace, int CheckControlParamPerms(ParamWorkSpace *workSpace,
const PropertySecurityLabel *srcLabel, const char *name, const char *value); const ParamSecurityLabel *srcLabel, const char *name, const char *value);
int GetSubStringInfo(const char *buff, u_int32_t buffLen, char delimiter, SubStringInfo *info, int subStrNumber); int GetSubStringInfo(const char *buff, u_int32_t buffLen, char delimiter, SubStringInfo *info, int subStrNumber);
int BuildPropertyContent(char *content, u_int32_t contentSize, const char *name, const char *value); int BuildParamContent(char *content, u_int32_t contentSize, const char *name, const char *value);
PropertyWorkSpace *GetPropertyWorkSpace(); ParamWorkSpace *GetParamWorkSpace();
typedef void (*TraversalParamPtr)(PropertyHandle handle, void* context); typedef void (*TraversalParamPtr)(ParamHandle handle, void* context);
typedef struct { typedef struct {
TraversalParamPtr traversalParamPtr; TraversalParamPtr traversalParamPtr;
void *context; void *context;
} PropertyTraversalContext; } ParamTraversalContext;
int TraversalProperty(PropertyWorkSpace *workSpace, TraversalParamPtr walkFunc, void *cookie); int TraversalParam(ParamWorkSpace *workSpace, TraversalParamPtr walkFunc, void *cookie);
int InitPersistPropertyWorkSpace(const char *context);
int RefreshPersistProperties(PropertyWorkSpace *workSpace, const char *context);
void ClosePersistPropertyWorkSpace();
int WritePersistProperty(const char *name, const char *value);
const char *DetectPropertyChange(PropertyWorkSpace *workSpace, PropertyCache *cache, const char *DetectParamChange(ParamWorkSpace *workSpace, ParamCache *cache,
PropertyEvaluatePtr evaluate, u_int32_t count, const char *properties[][2]); ParamEvaluatePtr evaluate, u_int32_t count, const char *parameters[][2]);
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
......
...@@ -13,12 +13,12 @@ ...@@ -13,12 +13,12 @@
* limitations under the License. * limitations under the License.
*/ */
#ifndef BASE_STARTUP_PROPERTY_REQUEST_H #ifndef BASE_STARTUP_PARAM_REQUEST_H
#define BASE_STARTUP_PROPERTY_REQUEST_H #define BASE_STARTUP_PARAM_REQUEST_H
#include <stdio.h> #include <stdio.h>
#include "property.h" #include "sys_param.h"
#include "property_manager.h" #include "param_manager.h"
#include "uv.h" #include "uv.h"
#ifdef __cplusplus #ifdef __cplusplus
...@@ -28,12 +28,12 @@ extern "C" { ...@@ -28,12 +28,12 @@ extern "C" {
#endif #endif
typedef enum RequestType { typedef enum RequestType {
SET_PROPERTY, SET_PARAM,
GET_PROPERTY, GET_PARAM,
} RequestType; } RequestType;
typedef struct { typedef struct {
PropertySecurityLabel securitylabel; ParamSecurityLabel securitylabel;
RequestType type; RequestType type;
int contentSize; int contentSize;
char content[0]; char content[0];
...@@ -50,6 +50,7 @@ typedef struct { ...@@ -50,6 +50,7 @@ typedef struct {
uv_loop_t *loop; uv_loop_t *loop;
uv_connect_t connect; uv_connect_t connect;
uv_pipe_t handle; uv_pipe_t handle;
uv_write_t wr;
int result; int result;
RequestMsg msg; RequestMsg msg;
} RequestNode; } RequestNode;
......
...@@ -13,31 +13,21 @@ ...@@ -13,31 +13,21 @@
* limitations under the License. * limitations under the License.
*/ */
#ifndef BASE_STARTUP_TRIGER_H #ifndef BASE_STARTUP_PARAM_SERVICE_H
#define BASE_STARTUP_TRIGER_H #define BASE_STARTUP_PARAM_SERVICE_H
#include <stdio.h> #include <stdio.h>
#include "cJSON.h" #include "sys_param.h"
#include "param_manager.h"
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
extern "C" { extern "C" {
#endif #endif
#endif #endif
typedef enum { int InitPersistParamWorkSpace(const char *context);
EVENT_PROPERTY, // 属性修改事件 int RefreshPersistParams(ParamWorkSpace *workSpace, const char *context);
EVENT_BOOT void ClosePersistParamWorkSpace();
} EventType; int WritePersistParam(const char *name, const char *value);
void PostTrigger(EventType type, void *content, u_int32_t contentLen);
void PostPropertyTrigger(const char *name, const char *value);
void StartTriggerService();
int ParseTriggerConfig(cJSON *fileRoot);
void DoTriggerExec(const char *content);
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
......
...@@ -13,8 +13,8 @@ ...@@ -13,8 +13,8 @@
* limitations under the License. * limitations under the License.
*/ */
#ifndef BASE_STARTUP_PROPERTY_TRIE_H #ifndef BASE_STARTUP_PARAM_TRIE_H
#define BASE_STARTUP_PROPERTY_TRIE_H #define BASE_STARTUP_PARAM_TRIE_H
#include <linux/futex.h> #include <linux/futex.h>
#include <stdatomic.h> #include <stdatomic.h>
#include <stdio.h> #include <stdio.h>
...@@ -22,7 +22,7 @@ ...@@ -22,7 +22,7 @@
#include <sys/syscall.h> #include <sys/syscall.h>
#include "init_log.h" #include "init_log.h"
#include "property.h" #include "sys_param.h"
#include "securec.h" #include "securec.h"
#ifdef __cplusplus #ifdef __cplusplus
...@@ -31,8 +31,7 @@ extern "C" { ...@@ -31,8 +31,7 @@ extern "C" {
#endif #endif
#endif #endif
#define PROPERTY_WORKSPACE_MAX 64*1024 #define PARAM_WORKSPACE_MAX 64*1024
#define TRIE_SERIAL_DIRTY_OFFSET 1 #define TRIE_SERIAL_DIRTY_OFFSET 1
#define TRIE_SERIAL_KEY_LEN_OFFSET 24 #define TRIE_SERIAL_KEY_LEN_OFFSET 24
#define TRIE_SERIAL_DATA_LEN_OFFSET 16 #define TRIE_SERIAL_DATA_LEN_OFFSET 16
...@@ -136,4 +135,4 @@ u_int32_t GetDataSerial(const DataEntry *entry); ...@@ -136,4 +135,4 @@ u_int32_t GetDataSerial(const DataEntry *entry);
} }
#endif #endif
#endif #endif
#endif // BASE_STARTUP_PROPERTY_TRIE_H #endif // BASE_STARTUP_PARAM_TRIE_H
\ No newline at end of file \ No newline at end of file
...@@ -15,7 +15,6 @@ ...@@ -15,7 +15,6 @@
#ifndef STARTUP_TRIGER_MANAGER_H #ifndef STARTUP_TRIGER_MANAGER_H
#define STARTUP_TRIGER_MANAGER_H #define STARTUP_TRIGER_MANAGER_H
#include <pthread.h> #include <pthread.h>
#include <stdatomic.h> #include <stdatomic.h>
#include <stdio.h> #include <stdio.h>
...@@ -23,8 +22,7 @@ ...@@ -23,8 +22,7 @@
#include "cJSON.h" #include "cJSON.h"
#include "init_log.h" #include "init_log.h"
#include "list.h" #include "param_manager.h"
#include "property_service.h"
#include "securec.h" #include "securec.h"
#ifdef __cplusplus #ifdef __cplusplus
...@@ -33,30 +31,21 @@ extern "C" { ...@@ -33,30 +31,21 @@ extern "C" {
#endif #endif
#endif #endif
#define TRIGGER_LOGI(fmt, ...) STARTUP_LOGI("Trigger", fmt, ##__VA_ARGS__)
#define TRIGGER_LOGE(fmt, ...) STARTUP_LOGE("Trigger", fmt, ##__VA_ARGS__)
#define TRIGGER_CHECK(retCode, exper, ...) \
if (!(retCode)) { \
TRIGGER_LOGE(__VA_ARGS__); \
exper; \
}
#define COND_STACK_SIZE 20
#define TRIGGER_CMD "trigger " #define TRIGGER_CMD "trigger "
#define TRIGGER_ARR_NAME_IN_JSON "jobs" #define TRIGGER_ARR_NAME_IN_JSON "jobs"
#define CMDS_ARR_NAME_IN_JSON "cmds" #define CMDS_ARR_NAME_IN_JSON "cmds"
typedef struct { #define MAX_TRIGGER_CMD_NAME_LEN 32
char data[COND_STACK_SIZE]; #define MAX_TRIGGER_NAME_LEN 64
int top; #define MAX_TRIGGER_TYPE_LEN 16
} CONDITION_STACK;
#define TRIGGER_NODE_IN_QUEUE(trigger) \
(atomic_load_explicit(&(trigger)->serial, memory_order_relaxed) & 0x01)
#define TRIGGER_NODE_SET_QUEUE_FLAG(trigger) \
atomic_store_explicit(&(trigger)->serial, (trigger)->serial | 0x01, memory_order_relaxed)
#define TRIGGER_NODE_CLEAR_QUEUE_FLAG(trigger) \
atomic_store_explicit(&(trigger)->serial, (trigger)->serial & ~0x01, memory_order_relaxed)
/*
on boot
exec /system/bin/sleep 4
start telephony_sa
*/
typedef enum { typedef enum {
TRIGGER_BOOT = 0, TRIGGER_BOOT = 0,
TRIGGER_PROPERTY, TRIGGER_PROPERTY,
...@@ -64,10 +53,6 @@ typedef enum { ...@@ -64,10 +53,6 @@ typedef enum {
TRIGGER_MAX TRIGGER_MAX
}TriggerType; }TriggerType;
#define MAX_TRIGGER_CMD_NAME_LEN 16
#define MAX_TRIGGER_NAME_LEN 64
#define MAX_TRIGGER_TYPE_LEN 16
// Command对象列表,主要存储每个triger需要执行那些Command操作。 // Command对象列表,主要存储每个triger需要执行那些Command操作。
typedef struct CommandNode { typedef struct CommandNode {
atomic_uint_least32_t next; atomic_uint_least32_t next;
...@@ -116,27 +101,20 @@ int InitTriggerWorkSpace(TriggerWorkSpace *workSpace); ...@@ -116,27 +101,20 @@ int InitTriggerWorkSpace(TriggerWorkSpace *workSpace);
int ParseTrigger(TriggerWorkSpace *workSpace, cJSON *triggerItem); int ParseTrigger(TriggerWorkSpace *workSpace, cJSON *triggerItem);
typedef int (*TRIGGER_MATCH)(TriggerNode *trigger, void *content, u_int32_t contentSize); typedef int (*TRIGGER_MATCH)(TriggerNode *trigger, void *content, u_int32_t contentSize);
typedef int (*TRIGGER_CHECK_DONE) (TriggerNode *trigger, u_int32_t index); typedef int (*PARAM_CHECK_DONE) (TriggerNode *trigger, u_int32_t index);
typedef int (*CMD_EXECUTE) (TriggerNode *trigger, const char *cmdName, const char *command); typedef int (*CMD_EXECUTE) (TriggerNode *trigger, const char *cmdName, const char *command);
TriggerNode *GetTriggerByName(TriggerWorkSpace *workSpace, const char *triggerName, u_int32_t *triggerIndex); TriggerNode *GetTriggerByName(TriggerWorkSpace *workSpace, const char *triggerName, u_int32_t *triggerIndex);
int ExecuteTrigger(TriggerWorkSpace *workSpace, TriggerNode *trigger, CMD_EXECUTE cmdExecuter); int ExecuteTrigger(TriggerWorkSpace *workSpace, TriggerNode *trigger, CMD_EXECUTE cmdExecuter);
int CheckTrigger(TriggerWorkSpace *workSpace, int CheckTrigger(TriggerWorkSpace *workSpace,
int type, void *content, u_int32_t contentSize, TRIGGER_CHECK_DONE triggerExecuter); int type, void *content, u_int32_t contentSize, PARAM_CHECK_DONE triggerExecuter);
int CheckPropertyTrigger(TriggerWorkSpace *workSpace, int CheckParamTrigger(TriggerWorkSpace *workSpace,
const char *content, u_int32_t contentSize, TRIGGER_CHECK_DONE triggerExecuter); const char *content, u_int32_t contentSize, PARAM_CHECK_DONE triggerExecuter);
TriggerNode *ExecuteQueuePop(TriggerWorkSpace *workSpace); TriggerNode *ExecuteQueuePop(TriggerWorkSpace *workSpace);
int ExecuteQueuePush(TriggerWorkSpace *workSpace, TriggerNode *trigger, u_int32_t index); int ExecuteQueuePush(TriggerWorkSpace *workSpace, TriggerNode *trigger, u_int32_t index);
int ExecuteQueueSize(TriggerWorkSpace *workSpace); int ExecuteQueueSize(TriggerWorkSpace *workSpace);
#define TRIGGER_NODE_IN_QUEUE(trigger) \
(atomic_load_explicit(&(trigger)->serial, memory_order_relaxed) & 0x01)
#define TRIGGER_NODE_SET_QUEUE_FLAG(trigger) \
atomic_store_explicit(&(trigger)->serial, (trigger)->serial | 0x01, memory_order_relaxed)
#define TRIGGER_NODE_CLEAR_QUEUE_FLAG(trigger) \
atomic_store_explicit(&(trigger)->serial, (trigger)->serial & ~0x01, memory_order_relaxed)
TriggerWorkSpace *GetTriggerWorkSpace(); TriggerWorkSpace *GetTriggerWorkSpace();
#ifdef __cplusplus #ifdef __cplusplus
......
...@@ -18,8 +18,8 @@ ...@@ -18,8 +18,8 @@
#include <stdio.h> #include <stdio.h>
#include "property.h" #include "sys_param.h"
#include "trigger.h" #include "init_param.h"
#include "trigger_manager.h" #include "trigger_manager.h"
#include "uv.h" #include "uv.h"
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "property.h" #include "sys_param.h"
#include <ctype.h> #include <ctype.h>
#include <errno.h> #include <errno.h>
...@@ -26,94 +26,94 @@ ...@@ -26,94 +26,94 @@
#include <sys/types.h> #include <sys/types.h>
#include <unistd.h> #include <unistd.h>
#include "property_manager.h" #include "param_manager.h"
#define LABEL "Manager" #define LABEL "Manager"
#define MAX_PROPERT_IN_WATCH 5 #define MAX_PROPERT_IN_WATCH 5
#define NORMAL_MEMORY_FOR_PROPERTY_CACHE 4 * 1024 #define NORMAL_MEMORY_FOR_PARAM_CACHE 4 * 1024
static WorkSpace g_workSpace; static WorkSpace g_workSpace;
static pthread_mutex_t cacheLock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t cacheLock = PTHREAD_MUTEX_INITIALIZER;
static int InitNormalMemory(WorkSpace *workSpace, u_int32_t spaceSize) static int InitNormalMemory(WorkSpace *workSpace, u_int32_t spaceSize)
{ {
PROPERTY_CHECK(workSpace != NULL, return -1, "Invalid param"); PARAM_CHECK(workSpace != NULL, return -1, "Invalid param");
if (workSpace->area != NULL) { if (workSpace->area != NULL) {
return 0; return 0;
} }
void *areaAddr = (void *)mmap(NULL, spaceSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_POPULATE | MAP_ANON, -1, 0); void *areaAddr = (void *)mmap(NULL, spaceSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_POPULATE | MAP_ANON, -1, 0);
PROPERTY_CHECK(areaAddr != MAP_FAILED, return -1, "Failed to map memory error %s", strerror(errno)); PARAM_CHECK(areaAddr != MAP_FAILED, return -1, "Failed to map memory error %s", strerror(errno));
workSpace->area = (WorkArea*)areaAddr; workSpace->area = (WorkArea*)areaAddr;
atomic_init(&workSpace->area->serial, 0); atomic_init(&workSpace->area->serial, 0);
workSpace->area->dataSize = spaceSize; workSpace->area->dataSize = spaceSize;
workSpace->area->currOffset = sizeof(WorkArea); workSpace->area->currOffset = sizeof(WorkArea);
PROPERTY_LOGI("InitNormalMemory success, currOffset %u firstNode %u dataSize %u", PARAM_LOGI("InitNormalMemory success, currOffset %u firstNode %u dataSize %u",
workSpace->area->currOffset, workSpace->area->firstNode, workSpace->area->dataSize); workSpace->area->currOffset, workSpace->area->firstNode, workSpace->area->dataSize);
return 0; return 0;
} }
static PropertyCacheNode *AllocPropertyCacheNode(WorkSpace *workSpace, u_int32_t size) static ParamCacheNode *AllocParamCacheNode(WorkSpace *workSpace, u_int32_t size)
{ {
PROPERTY_CHECK(workSpace != NULL, return 0, "Invalid param"); PARAM_CHECK(workSpace != NULL, return 0, "Invalid param");
PROPERTY_CHECK((workSpace->area->currOffset + size) < workSpace->area->dataSize, return 0, PARAM_CHECK((workSpace->area->currOffset + size) < workSpace->area->dataSize, return 0,
"Failed to allocate currOffset %d, dataSize %d", workSpace->area->currOffset, workSpace->area->dataSize); "Failed to allocate currOffset %d, dataSize %d", workSpace->area->currOffset, workSpace->area->dataSize);
PropertyCacheNode *cache = (PropertyCacheNode *)(workSpace->area->data + workSpace->area->currOffset); ParamCacheNode *cache = (ParamCacheNode *)(workSpace->area->data + workSpace->area->currOffset);
workSpace->area->currOffset += size; workSpace->area->currOffset += size;
return cache; return cache;
} }
static int CreatePropertyCache(PropertyCache *cache, PropertyWorkSpace *workSpace, PropertyEvaluatePtr evaluate) static int CreateParamCache(ParamCache *cache, ParamWorkSpace *workSpace, ParamEvaluatePtr evaluate)
{ {
PROPERTY_CHECK(cache != NULL && evaluate != NULL, return -1, "Invalid param"); PARAM_CHECK(cache != NULL && evaluate != NULL, return -1, "Invalid param");
if (cache->cacheNode != NULL) { if (cache->cacheNode != NULL) {
return 0; return 0;
} }
int ret = InitNormalMemory(&g_workSpace, NORMAL_MEMORY_FOR_PROPERTY_CACHE); int ret = InitNormalMemory(&g_workSpace, NORMAL_MEMORY_FOR_PARAM_CACHE);
PROPERTY_CHECK(ret == 0, return -1, "Failed to init normal memory"); PARAM_CHECK(ret == 0, return -1, "Failed to init normal memory");
pthread_mutex_init(&cache->lock, NULL); pthread_mutex_init(&cache->lock, NULL);
cache->serial = GetWorkSpaceSerial(&workSpace->propertySpace); cache->serial = GetWorkSpaceSerial(&workSpace->paramSpace);
cache->cacheCount = 0; cache->cacheCount = 0;
cache->evaluate = evaluate; cache->evaluate = evaluate;
cache->cacheNode = (PropertyCacheNode *)AllocPropertyCacheNode(&g_workSpace, cache->cacheNode = (ParamCacheNode *)AllocParamCacheNode(&g_workSpace,
sizeof(PropertyCache) * MAX_PROPERT_IN_WATCH); sizeof(ParamCache) * MAX_PROPERT_IN_WATCH);
PROPERTY_CHECK(cache->cacheNode != NULL, return -1, "Failed to malloc memory"); PARAM_CHECK(cache->cacheNode != NULL, return -1, "Failed to malloc memory");
return 0; return 0;
} }
static int AddPropertyNode(PropertyCache *cache, PropertyWorkSpace *workSpace, const char *name, const char *defValue) static int AddParamNode(ParamCache *cache, ParamWorkSpace *workSpace, const char *name, const char *defValue)
{ {
PROPERTY_CHECK(cache != NULL && name != NULL, return -1, "Invalid param"); PARAM_CHECK(cache != NULL && name != NULL, return -1, "Invalid param");
PROPERTY_CHECK(cache->cacheCount < MAX_PROPERT_IN_WATCH, return -1, "Full property in cache"); PARAM_CHECK(cache->cacheCount < MAX_PROPERT_IN_WATCH, return -1, "Full param in cache");
PropertyCacheNode *cacheNode = &cache->cacheNode[cache->cacheCount++]; ParamCacheNode *cacheNode = &cache->cacheNode[cache->cacheCount++];
int ret = memcpy_s(cacheNode->value, sizeof(cacheNode->value), defValue, strlen(defValue)); int ret = memcpy_s(cacheNode->value, sizeof(cacheNode->value), defValue, strlen(defValue));
PROPERTY_CHECK(ret == 0, return -1, "Failed to copy default value"); PARAM_CHECK(ret == 0, return -1, "Failed to copy default value");
ret = ReadPropertyWithCheck(workSpace, name, &cacheNode->handle); ret = ReadParamWithCheck(workSpace, name, &cacheNode->handle);
PROPERTY_CHECK(ret == 0, return -1, "Failed to read property"); PARAM_CHECK(ret == 0, return -1, "Failed to read param");
cacheNode->serial = ReadPropertySerial(workSpace, cacheNode->handle); cacheNode->serial = ReadParamSerial(workSpace, cacheNode->handle);
return ret; return ret;
} }
static int CheckCacheNode(PropertyWorkSpace *workSpace, PropertyCacheNode *cacheNode) static int CheckCacheNode(ParamWorkSpace *workSpace, ParamCacheNode *cacheNode)
{ {
return cacheNode && ReadPropertySerial(workSpace, cacheNode->handle) != cacheNode->serial; return cacheNode && ReadParamSerial(workSpace, cacheNode->handle) != cacheNode->serial;
} }
static void RefreshCacheNode(PropertyWorkSpace *workSpace, PropertyCacheNode *cacheNode) static void RefreshCacheNode(ParamWorkSpace *workSpace, ParamCacheNode *cacheNode)
{ {
cacheNode->serial = ReadPropertySerial(workSpace, cacheNode->handle); cacheNode->serial = ReadParamSerial(workSpace, cacheNode->handle);
u_int32_t len = sizeof(cacheNode->value); u_int32_t len = sizeof(cacheNode->value);
ReadPropertyValue(workSpace, cacheNode->handle, cacheNode->value, &len); ReadParamValue(workSpace, cacheNode->handle, cacheNode->value, &len);
} }
static const char *TestPropertyCache(PropertyCache *cache, PropertyWorkSpace *workSpace) static const char *TestParamCache(ParamCache *cache, ParamWorkSpace *workSpace)
{ {
int changeDetected; int changeDetected = 0;
if (pthread_mutex_trylock(&cache->lock)) { if (pthread_mutex_trylock(&cache->lock)) {
return cache->evaluate(cache->cacheCount, cache->cacheNode); return cache->evaluate(cache->cacheCount, cache->cacheNode);
} }
if (GetWorkSpaceSerial(&workSpace->propertySpace) != cache->serial) { if (GetWorkSpaceSerial(&workSpace->paramSpace) != cache->serial) {
changeDetected = 1; changeDetected = 1;
} }
for (u_int32_t i = 0; (i < cache->cacheCount) && changeDetected == 0; i++) { for (u_int32_t i = 0; (i < cache->cacheCount) && changeDetected == 0; i++) {
...@@ -123,26 +123,26 @@ static const char *TestPropertyCache(PropertyCache *cache, PropertyWorkSpace *wo ...@@ -123,26 +123,26 @@ static const char *TestPropertyCache(PropertyCache *cache, PropertyWorkSpace *wo
for (u_int32_t i = 0; i < cache->cacheCount; i++) { for (u_int32_t i = 0; i < cache->cacheCount; i++) {
RefreshCacheNode(workSpace, &cache->cacheNode[i]); RefreshCacheNode(workSpace, &cache->cacheNode[i]);
} }
cache->serial = GetWorkSpaceSerial(&workSpace->propertySpace); cache->serial = GetWorkSpaceSerial(&workSpace->paramSpace);
} }
pthread_mutex_unlock(&cache->lock); pthread_mutex_unlock(&cache->lock);
return cache->evaluate(cache->cacheCount, cache->cacheNode); return cache->evaluate(cache->cacheCount, cache->cacheNode);
} }
const char *DetectPropertyChange(PropertyWorkSpace *workSpace, PropertyCache *cache, const char *DetectParamChange(ParamWorkSpace *workSpace, ParamCache *cache,
PropertyEvaluatePtr evaluate, u_int32_t count, const char *properties[][2]) ParamEvaluatePtr evaluate, u_int32_t count, const char *parameters[][2])
{ {
pthread_mutex_lock(&cacheLock); pthread_mutex_lock(&cacheLock);
while (cache->cacheCount == 0) { while (cache->cacheCount == 0) {
int ret = CreatePropertyCache(cache, workSpace, evaluate); int ret = CreateParamCache(cache, workSpace, evaluate);
PROPERTY_CHECK(ret == 0, break, "Failed to create cache"); PARAM_CHECK(ret == 0, break, "Failed to create cache");
for (u_int32_t i = 0; i < count; i++) { for (u_int32_t i = 0; i < count; i++) {
ret = AddPropertyNode(cache, workSpace, properties[i][0], properties[i][1]); ret = AddParamNode(cache, workSpace, parameters[i][0], parameters[i][1]);
PROPERTY_CHECK(ret == 0, break, "Failed to add property cache"); PARAM_CHECK(ret == 0, break, "Failed to add param cache");
} }
PROPERTY_CHECK(ret == 0, break, "Failed to add property cache"); PARAM_CHECK(ret == 0, break, "Failed to add param cache");
} }
pthread_mutex_unlock(&cacheLock); pthread_mutex_unlock(&cacheLock);
return TestPropertyCache(cache, workSpace); return TestParamCache(cache, workSpace);
} }
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "property.h" #include "sys_param.h"
#include <ctype.h> #include <ctype.h>
#include <errno.h> #include <errno.h>
...@@ -26,8 +26,8 @@ ...@@ -26,8 +26,8 @@
#include <sys/types.h> #include <sys/types.h>
#include <unistd.h> #include <unistd.h>
#include "property_manager.h" #include "param_manager.h"
#include "property_trie.h" #include "param_trie.h"
#define LABEL "Manager" #define LABEL "Manager"
#define MAX_BUFF 256 #define MAX_BUFF 256
...@@ -38,11 +38,11 @@ typedef struct { ...@@ -38,11 +38,11 @@ typedef struct {
char *buffer; char *buffer;
} PersistContext; } PersistContext;
static PropertyPersistWorkSpace g_persistWorkSpace = {ATOMIC_VAR_INIT(0), }; static ParamPersistWorkSpace g_persistWorkSpace = {ATOMIC_VAR_INIT(0), };
static int ProcessPropertTraversal(WorkSpace *workSpace, TrieNode *node, void *cookie) static int ProcessParamTraversal(WorkSpace *workSpace, TrieNode *node, void *cookie)
{ {
PROPERTY_CHECK(workSpace != 0 && node != NULL && cookie != NULL, return -1, "Invalid param"); PARAM_CHECK(workSpace != 0 && node != NULL && cookie != NULL, return -1, "Invalid param");
TrieDataNode *current = (TrieDataNode *)node; TrieDataNode *current = (TrieDataNode *)node;
if (current == NULL || current->dataIndex == 0) { if (current == NULL || current->dataIndex == 0) {
return 0; return 0;
...@@ -58,10 +58,11 @@ static int ProcessPropertTraversal(WorkSpace *workSpace, TrieNode *node, void *c ...@@ -58,10 +58,11 @@ static int ProcessPropertTraversal(WorkSpace *workSpace, TrieNode *node, void *c
} }
ret |= GetDataValue(entry, persistContext->buffer + MAX_BUFF, MAX_BUFF); ret |= GetDataValue(entry, persistContext->buffer + MAX_BUFF, MAX_BUFF);
if (ret == 0) { // 只支持新建 if (ret == 0) { // 只支持新建
PROPERTY_LOGI("Insert new persist property from normal property %s", persistContext->buffer); //PARAM_LOGI("Insert new persist param from normal param %s %s",
ret = AddProperty(persistContext->persistWorkSpace, persistContext->buffer, persistContext->buffer + MAX_BUFF); // persistContext->buffer, persistContext->buffer + MAX_BUFF);
ret = AddParam(persistContext->persistWorkSpace, persistContext->buffer, persistContext->buffer + MAX_BUFF);
} }
PROPERTY_CHECK(ret == 0, return ret, "Failed to add persist property"); PARAM_CHECK(ret == 0, return ret, "Failed to add persist param");
return ret; return ret;
} }
...@@ -79,53 +80,50 @@ static int ProcessPersistPropertTraversal(WorkSpace *workSpace, TrieNode *node, ...@@ -79,53 +80,50 @@ static int ProcessPersistPropertTraversal(WorkSpace *workSpace, TrieNode *node,
int ret = GetDataName(entry, persistContext->buffer, MAX_BUFF); int ret = GetDataName(entry, persistContext->buffer, MAX_BUFF);
ret |= GetDataValue(entry, persistContext->buffer + MAX_BUFF, MAX_BUFF); ret |= GetDataValue(entry, persistContext->buffer + MAX_BUFF, MAX_BUFF);
if (ret == 0) { if (ret == 0) {
PROPERTY_LOGI("update normal property %s %s from persist property ", //PARAM_LOGI("update normal param %s %s from persist param %u",
persistContext->buffer, persistContext->buffer + MAX_BUFF); // persistContext->buffer, persistContext->buffer + MAX_BUFF, current->dataIndex);
ret = WriteProperty(persistContext->workSpace, persistContext->buffer, persistContext->buffer + MAX_BUFF); ret = WriteParam(persistContext->workSpace, persistContext->buffer, persistContext->buffer + MAX_BUFF);
} }
PROPERTY_CHECK(ret == 0, return ret, "Failed to add persist property"); PARAM_CHECK(ret == 0, return ret, "Failed to add persist param");
return ret; return ret;
} }
int InitPersistPropertyWorkSpace(const char *context) int InitPersistParamWorkSpace(const char *context)
{ {
u_int32_t flags = atomic_load_explicit(&g_persistWorkSpace.flags, memory_order_relaxed); u_int32_t flags = atomic_load_explicit(&g_persistWorkSpace.flags, memory_order_relaxed);
PROPERTY_LOGI("InitPersistPropertyWorkSpace flags %x", flags);
if ((flags & WORKSPACE_FLAGS_INIT) == WORKSPACE_FLAGS_INIT) { if ((flags & WORKSPACE_FLAGS_INIT) == WORKSPACE_FLAGS_INIT) {
return 0; return 0;
} }
g_persistWorkSpace.persistWorkSpace.compareTrieNode = CompareTrieDataNode; g_persistWorkSpace.persistWorkSpace.compareTrieNode = CompareTrieDataNode;
g_persistWorkSpace.persistWorkSpace.allocTrieNode = AllocateTrieDataNode; g_persistWorkSpace.persistWorkSpace.allocTrieNode = AllocateTrieDataNode;
int ret = InitPersistWorkSpace(PROPERTY_PERSIST_PATH, &g_persistWorkSpace.persistWorkSpace); int ret = InitPersistWorkSpace(PARAM_PERSIST_PATH, &g_persistWorkSpace.persistWorkSpace);
PARAM_CHECK(ret == 0, return ret, "Failed to init persist param");
atomic_store_explicit(&g_persistWorkSpace.flags, WORKSPACE_FLAGS_INIT, memory_order_release); atomic_store_explicit(&g_persistWorkSpace.flags, WORKSPACE_FLAGS_INIT, memory_order_release);
return ret; return ret;
} }
int RefreshPersistProperties(PropertyWorkSpace *workSpace, const char *context) int RefreshPersistParams(ParamWorkSpace *workSpace, const char *context)
{ {
int ret = InitPersistParamWorkSpace(context);
PARAM_CHECK(ret == 0, return ret, "Failed to init persist param");
u_int32_t flags = atomic_load_explicit(&g_persistWorkSpace.flags, memory_order_relaxed); u_int32_t flags = atomic_load_explicit(&g_persistWorkSpace.flags, memory_order_relaxed);
if ((flags & WORKSPACE_FLAGS_INIT) != WORKSPACE_FLAGS_INIT) {
int ret = InitPersistPropertyWorkSpace(context);
PROPERTY_CHECK(ret == 0, return ret, "Failed to init persist property");
flags = atomic_load_explicit(&g_persistWorkSpace.flags, memory_order_relaxed);
}
if ((flags & WORKSPACE_FLAGS_LOADED) == WORKSPACE_FLAGS_LOADED) { if ((flags & WORKSPACE_FLAGS_LOADED) == WORKSPACE_FLAGS_LOADED) {
PARAM_LOGE("RefreshPersistParams has been loaded");
return 0; return 0;
} }
// 申请临时的缓存,用于数据读取 // 申请临时的缓存,用于数据读取
char *buffer = (char *)malloc(MAX_BUFF + MAX_BUFF); char *buffer = (char *)malloc(MAX_BUFF + MAX_BUFF);
PROPERTY_CHECK(buffer != NULL, return -1, "Failed to malloc memory for property"); PARAM_CHECK(buffer != NULL, return -1, "Failed to malloc memory for param");
PersistContext persistContext = { PersistContext persistContext = {
&workSpace->propertySpace, &g_persistWorkSpace.persistWorkSpace, buffer &workSpace->paramSpace, &g_persistWorkSpace.persistWorkSpace, buffer
}; };
// 遍历当前的属性,并把persist的写入 // 遍历当前的参数,并把persist的写入
int ret = TraversalTrieDataNode(&workSpace->propertySpace, ret = TraversalTrieDataNode(&workSpace->paramSpace,
(TrieDataNode *)workSpace->propertySpace.rootNode, ProcessPropertTraversal, &persistContext); (TrieDataNode *)workSpace->paramSpace.rootNode, ProcessParamTraversal, &persistContext);
// 修改默认属性 // 修改默认参数
ret = TraversalTrieDataNode(&g_persistWorkSpace.persistWorkSpace, ret = TraversalTrieDataNode(&g_persistWorkSpace.persistWorkSpace,
(TrieDataNode *)g_persistWorkSpace.persistWorkSpace.rootNode, ProcessPersistPropertTraversal, &persistContext); (TrieDataNode *)g_persistWorkSpace.persistWorkSpace.rootNode, ProcessPersistPropertTraversal, &persistContext);
...@@ -134,23 +132,23 @@ int RefreshPersistProperties(PropertyWorkSpace *workSpace, const char *context) ...@@ -134,23 +132,23 @@ int RefreshPersistProperties(PropertyWorkSpace *workSpace, const char *context)
return ret; return ret;
} }
void ClosePersistPropertyWorkSpace() void ClosePersistParamWorkSpace()
{ {
CloseWorkSpace(&g_persistWorkSpace.persistWorkSpace); CloseWorkSpace(&g_persistWorkSpace.persistWorkSpace);
atomic_store_explicit(&g_persistWorkSpace.flags, 0, memory_order_release); atomic_store_explicit(&g_persistWorkSpace.flags, 0, memory_order_release);
} }
int WritePersistProperty(const char *name, const char *value) int WritePersistParam(const char *name, const char *value)
{ {
PROPERTY_CHECK(value != NULL && name != NULL, return PROPERTY_CODE_INVALID_PARAM, "Invalid param"); PARAM_CHECK(value != NULL && name != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param");
if (strncmp(name, "persist.", strlen("persist.")) != 0) {
u_int32_t flags = atomic_load_explicit(&g_persistWorkSpace.flags, memory_order_relaxed);
if ((flags & WORKSPACE_FLAGS_LOADED) != WORKSPACE_FLAGS_LOADED) {
return 0; return 0;
} }
int ret = InitPersistParamWorkSpace("");
if (strncmp(name, "persist.", strlen("persist.")) != 0) { PARAM_CHECK(ret == 0, return ret, "Failed to init persist param");
u_int32_t flags = atomic_load_explicit(&g_persistWorkSpace.flags, memory_order_relaxed);
if ((flags & WORKSPACE_FLAGS_LOADED) != WORKSPACE_FLAGS_LOADED) {
return 0; return 0;
} }
return WriteProperty(&g_persistWorkSpace.persistWorkSpace, name, value); return WriteParam(&g_persistWorkSpace.persistWorkSpace, name, value);
} }
...@@ -13,17 +13,17 @@ ...@@ -13,17 +13,17 @@
* limitations under the License. * limitations under the License.
*/ */
#include "property_service.h" #include "param_service.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include "property.h" #include "sys_param.h"
#include "property_manager.h" #include "param_manager.h"
#include "property_request.h" #include "param_request.h"
#include "trigger.h" #include "init_param.h"
#include "uv.h" #include "uv.h"
...@@ -31,95 +31,90 @@ ...@@ -31,95 +31,90 @@
#define LABEL "Server" #define LABEL "Server"
static char *g_initContext = ""; static char *g_initContext = "";
static PropertyWorkSpace g_propertyWorkSpace = {ATOMIC_VAR_INIT(0), {}, {}, {}}; static ParamWorkSpace g_paramWorkSpace = {ATOMIC_VAR_INIT(0), {}, {}, {}};
void InitPropertyService() void InitParamService()
{ {
int ret = InitPropertyWorkSpace(&g_propertyWorkSpace, 0, g_initContext); int ret = InitParamWorkSpace(&g_paramWorkSpace, 0, g_initContext);
PROPERTY_CHECK(ret == 0, return, "Init propert workspace fail"); PARAM_CHECK(ret == 0, return, "Init parameter workspace fail");
} }
int LoadDefaultProperty(const char *fileName) int LoadDefaultParams(const char *fileName)
{ {
u_int32_t flags = atomic_load_explicit(&g_propertyWorkSpace.flags, memory_order_relaxed); u_int32_t flags = atomic_load_explicit(&g_paramWorkSpace.flags, memory_order_relaxed);
if ((flags & WORKSPACE_FLAGS_INIT) != WORKSPACE_FLAGS_INIT) { if ((flags & WORKSPACE_FLAGS_INIT) != WORKSPACE_FLAGS_INIT) {
return PROPERTY_CODE_NOT_INIT; return PARAM_CODE_NOT_INIT;
} }
FILE *fp = fopen(fileName, "r"); FILE *fp = fopen(fileName, "r");
PROPERTY_CHECK(fp != NULL, return -1, "Open file %s fail", fileName); PARAM_CHECK(fp != NULL, return -1, "Open file %s fail", fileName);
char buff[BUFFER_SIZE]; char buff[BUFFER_SIZE];
SubStringInfo *info = malloc(sizeof(SubStringInfo) * (SUBSTR_INFO_LABEL + 1)); SubStringInfo *info = malloc(sizeof(SubStringInfo) * (SUBSTR_INFO_LABEL + 1));
while(fgets(buff, BUFFER_SIZE, fp) != NULL) { while(fgets(buff, BUFFER_SIZE, fp) != NULL) {
int subStrNumber = GetSubStringInfo(buff, strlen(buff), '\n', info, SUBSTR_INFO_LABEL + 1); int subStrNumber = GetSubStringInfo(buff, strlen(buff), '=', info, SUBSTR_INFO_LABEL + 1);
if (subStrNumber <= SUBSTR_INFO_LABEL) { if (subStrNumber <= SUBSTR_INFO_LABEL) {
continue; continue;
} }
if (strncmp(info[0].value, "ctl.", strlen("ctl.")) == 0) { if (strncmp(info[0].value, "ctl.", strlen("ctl.")) == 0) {
PROPERTY_LOGE("Do not set ctl. properties from init %s", info[0].value); PARAM_LOGE("Do not set ctl. parameters from init %s", info[0].value);
continue; continue;
} }
if (strcmp(info[0].value, "selinux.restorecon_recursive") == 0) { if (strcmp(info[0].value, "selinux.restorecon_recursive") == 0) {
PROPERTY_LOGE("Do not set selinux.restorecon_recursive from init %s", info[0].value); PARAM_LOGE("Do not set selinux.restorecon_recursive from init %s", info[0].value);
continue; continue;
} }
int ret = CheckPropertyName(info[0].value, 0); int ret = CheckParamName(info[0].value, 0);
PROPERTY_CHECK(ret == 0, continue, "Illegal property name %s", info[0].value); PARAM_CHECK(ret == 0, continue, "Illegal param name %s", info[0].value);
ret = WriteProperty(&g_propertyWorkSpace.propertySpace, info[0].value, info[1].value); ret = WriteParam(&g_paramWorkSpace.paramSpace, info[0].value, info[1].value);
PROPERTY_CHECK(ret == 0, continue, "Failed to set property %d %s", ret, buff); PARAM_CHECK(ret == 0, continue, "Failed to set param %d %s", ret, buff);
ret = WritePersistProperty(info[0].value, info[1].value);
PROPERTY_CHECK(ret == 0, continue, "Failed to set persist property %d %s", ret, buff);
} }
fclose(fp); fclose(fp);
free(info); free(info);
PROPERTY_LOGI("LoadDefaultProperty proterty success %s", fileName); PARAM_LOGI("LoadDefaultParams proterty success %s", fileName);
return 0; return 0;
} }
int LoadPropertyInfo(const char *fileName) int LoadParamInfos(const char *fileName)
{ {
u_int32_t flags = atomic_load_explicit(&g_propertyWorkSpace.flags, memory_order_relaxed); u_int32_t flags = atomic_load_explicit(&g_paramWorkSpace.flags, memory_order_relaxed);
if ((flags & WORKSPACE_FLAGS_INIT) != WORKSPACE_FLAGS_INIT) { if ((flags & WORKSPACE_FLAGS_INIT) != WORKSPACE_FLAGS_INIT) {
return PROPERTY_CODE_NOT_INIT; return PARAM_CODE_NOT_INIT;
} }
FILE *fp = fopen(fileName, "r"); FILE *fp = fopen(fileName, "r");
PROPERTY_CHECK(fp != NULL, return -1, "Open file %s fail", fileName); PARAM_CHECK(fp != NULL, return -1, "Open file %s fail", fileName);
SubStringInfo *info = malloc(sizeof(SubStringInfo) * SUBSTR_INFO_MAX); SubStringInfo *info = malloc(sizeof(SubStringInfo) * SUBSTR_INFO_MAX);
char buff[BUFFER_SIZE]; char buff[BUFFER_SIZE];
int propInfoCount = 0; int infoCount = 0;
while(fgets(buff, BUFFER_SIZE, fp) != NULL) { while(fgets(buff, BUFFER_SIZE, fp) != NULL) {
int subStrNumber = GetSubStringInfo(buff, strlen(buff), ' ', info, SUBSTR_INFO_MAX); int subStrNumber = GetSubStringInfo(buff, strlen(buff), ' ', info, SUBSTR_INFO_MAX);
if (subStrNumber <= 0) { if (subStrNumber <= 0) {
continue; continue;
} }
int ret = WritePropertyInfo(&g_propertyWorkSpace, info, subStrNumber); int ret = WriteParamInfo(&g_paramWorkSpace, info, subStrNumber);
PROPERTY_CHECK(ret == 0, continue, "Failed to write property info %d %s", ret, buff); PARAM_CHECK(ret == 0, continue, "Failed to write param info %d %s", ret, buff);
propInfoCount++; infoCount++;
} }
fclose(fp); fclose(fp);
free(info); free(info);
PROPERTY_LOGI("Load proterty info %d success %s", propInfoCount, fileName); PARAM_LOGI("Load parameter info %d success %s", infoCount, fileName);
return 0; return 0;
} }
static int ProcessPropertySet(RequestMsg *msg) static int ProcessParamSet(RequestMsg *msg)
{ {
PROPERTY_CHECK(msg != NULL, return PROPERTY_CODE_INVALID_PARAM, "Failed to check param"); PARAM_CHECK(msg != NULL, return PARAM_CODE_INVALID_PARAM, "Failed to check param");
SubStringInfo info[3]; SubStringInfo info[3];
int ret = GetSubStringInfo(msg->content, msg->contentSize, '=', info, sizeof(info)/sizeof(info[0])); int ret = GetSubStringInfo(msg->content, msg->contentSize, '=', info, sizeof(info)/sizeof(info[0]));
PROPERTY_CHECK(ret >= 2, return ret, "Failed to get name from content %s", msg->content); PARAM_CHECK(ret >= 2, return ret, "Failed to get name from content %s", msg->content);
PROPERTY_LOGI("ProcessPropertySet name %s value: %s", info[0].value, info[1].value);
ret = WritePropertyWithCheck(&g_propertyWorkSpace, &msg->securitylabel, info[0].value, info[1].value);
PROPERTY_CHECK(ret == 0, return ret, "Failed to set property %d name %s %s", ret, info[0].value, info[1].value);
ret = WritePersistProperty(info[0].value, info[1].value);
PROPERTY_CHECK(ret == 0, return ret, "Failed to set property");
PARAM_LOGI("ProcessParamSet name %s value: %s", info[0].value, info[1].value);
ret = WriteParamWithCheck(&g_paramWorkSpace, &msg->securitylabel, info[0].value, info[1].value);
PARAM_CHECK(ret == 0, return ret, "Failed to set param %d name %s %s", ret, info[0].value, info[1].value);
ret = WritePersistParam(info[0].value, info[1].value);
PARAM_CHECK(ret == 0, return ret, "Failed to set param");
// notify event to process trigger // notify event to process trigger
PostTrigger(EVENT_PROPERTY, msg->content, msg->contentSize); PostTrigger(EVENT_PROPERTY, msg->content, msg->contentSize);
return 0; return 0;
...@@ -133,14 +128,14 @@ static void OnClose(uv_handle_t *handle) ...@@ -133,14 +128,14 @@ static void OnClose(uv_handle_t *handle)
static void OnReceiveAlloc(uv_handle_t *handle, size_t suggestedSize, uv_buf_t* buf) static void OnReceiveAlloc(uv_handle_t *handle, size_t suggestedSize, uv_buf_t* buf)
{ {
// 这里需要按实际消息的大小申请内存,取最大消息的长度 // 这里需要按实际消息的大小申请内存,取最大消息的长度
buf->base = (char *)malloc(sizeof(RequestMsg) + BUFFER_SIZE * 2); buf->len = sizeof(RequestMsg) + BUFFER_SIZE * 2;
buf->len = suggestedSize; buf->base = (char *)malloc(buf->len);
} }
static void OnWriteResponse(uv_write_t *req, int status) static void OnWriteResponse(uv_write_t *req, int status)
{ {
// 发送成功,释放请求内存 // 发送成功,释放请求内存
PROPERTY_LOGI("OnWriteResponse status %d", status); PARAM_LOGI("OnWriteResponse status %d", status);
ResponseNode *node = (ResponseNode*)req; ResponseNode *node = (ResponseNode*)req;
free(node); free(node);
} }
...@@ -150,17 +145,17 @@ static void SendResponse(uv_stream_t *handle, RequestType type, int result, void ...@@ -150,17 +145,17 @@ static void SendResponse(uv_stream_t *handle, RequestType type, int result, void
int ret = 0; int ret = 0;
// 申请整块内存,用于回复数据和写请求 // 申请整块内存,用于回复数据和写请求
ResponseNode *response = (ResponseNode *)malloc(sizeof(ResponseNode) + size); ResponseNode *response = (ResponseNode *)malloc(sizeof(ResponseNode) + size);
PROPERTY_CHECK(response != NULL, return, "Failed to alloc memory for response"); PARAM_CHECK(response != NULL, return, "Failed to alloc memory for response");
response->msg.type = type; response->msg.type = type;
response->msg.contentSize = size; response->msg.contentSize = size;
response->msg.result = result; response->msg.result = result;
if (content != NULL && size != 0) { if (content != NULL && size != 0) {
ret = memcpy_s(response->msg.content, size, content, size); ret = memcpy_s(response->msg.content, size, content, size);
PROPERTY_CHECK(ret == 0, return, "Failed to copy content"); PARAM_CHECK(ret == 0, return, "Failed to copy content");
} }
uv_buf_t buf = uv_buf_init((char *)&response->msg, sizeof(response->msg) + size); uv_buf_t buf = uv_buf_init((char *)&response->msg, sizeof(response->msg) + size);
ret = uv_write2(&response->writer, handle, &buf, 1, handle, OnWriteResponse); ret = uv_write2(&response->writer, handle, &buf, 1, handle, OnWriteResponse);
PROPERTY_CHECK(ret >= 0, return, "Failed to uv_write2 ret %s", uv_strerror(ret)); PARAM_CHECK(ret >= 0, return, "Failed to uv_write2 ret %s", uv_strerror(ret));
} }
static void OnReceiveRequest(uv_stream_t *handle, ssize_t nread, const uv_buf_t *buf) static void OnReceiveRequest(uv_stream_t *handle, ssize_t nread, const uv_buf_t *buf)
...@@ -173,110 +168,109 @@ static void OnReceiveRequest(uv_stream_t *handle, ssize_t nread, const uv_buf_t ...@@ -173,110 +168,109 @@ static void OnReceiveRequest(uv_stream_t *handle, ssize_t nread, const uv_buf_t
int freeHandle = 1; int freeHandle = 1;
RequestMsg *msg = (RequestMsg *)buf->base; RequestMsg *msg = (RequestMsg *)buf->base;
switch (msg->type) { switch (msg->type) {
case SET_PROPERTY: { case SET_PARAM: {
freeHandle = 0; freeHandle = 0;
int ret = ProcessPropertySet(msg); int ret = ProcessParamSet(msg);
SendResponse(handle, SET_PROPERTY, ret, NULL, 0); SendResponse(handle, SET_PARAM, ret, NULL, 0);
break; break;
} }
default: default:
PROPERTY_LOGE("not supported the command: %d", msg->type); PARAM_LOGE("not supported the command: %d", msg->type);
break; break;
} }
free(buf->base); free(buf->base);
uv_close((uv_handle_t*)handle, OnClose); uv_close((uv_handle_t*)handle, OnClose);
} }
static void RemoveSocket(int sig)
{
uv_fs_t req;
uv_fs_unlink(uv_default_loop(), &req, PIPE_NAME, NULL);
ClosePropertyWorkSpace(&g_propertyWorkSpace);
ClosePersistPropertyWorkSpace();
uv_stop(uv_default_loop());
exit(0);
}
static void OnConnection(uv_stream_t *server, int status) static void OnConnection(uv_stream_t *server, int status)
{ {
PROPERTY_CHECK(status >= 0, return, "Error status %d", status); PARAM_CHECK(status >= 0, return, "Error status %d", status);
PROPERTY_CHECK(server != NULL, return, "Error server"); PARAM_CHECK(server != NULL, return, "Error server");
uv_pipe_t *stream = (uv_pipe_t*)malloc(sizeof(uv_pipe_t)); uv_pipe_t *stream = (uv_pipe_t*)malloc(sizeof(uv_pipe_t));
PROPERTY_CHECK(stream != NULL, return, "Failed to alloc stream"); PARAM_CHECK(stream != NULL, return, "Failed to alloc stream");
int ret = uv_pipe_init(uv_default_loop(), (uv_pipe_t*)stream, 1); int ret = uv_pipe_init(uv_default_loop(), (uv_pipe_t*)stream, 1);
PROPERTY_CHECK(ret == 0, free(stream); return, "Failed to uv_pipe_init %d", ret); PARAM_CHECK(ret == 0, free(stream); return, "Failed to uv_pipe_init %d", ret);
stream->data = server; stream->data = server;
ret = uv_accept(server, (uv_stream_t *)stream); ret = uv_accept(server, (uv_stream_t *)stream);
PROPERTY_CHECK(ret == 0, uv_close((uv_handle_t*)stream, NULL); free(stream); PARAM_CHECK(ret == 0, uv_close((uv_handle_t*)stream, NULL); free(stream);
return, "Failed to uv_accept %d", ret); return, "Failed to uv_accept %d", ret);
ret = uv_read_start((uv_stream_t *)stream, OnReceiveAlloc, OnReceiveRequest); ret = uv_read_start((uv_stream_t *)stream, OnReceiveAlloc, OnReceiveRequest);
PROPERTY_CHECK(ret == 0, uv_close((uv_handle_t*)stream, NULL); free(stream); PARAM_CHECK(ret == 0, uv_close((uv_handle_t*)stream, NULL); free(stream);
return, "Failed to uv_read_start %d", ret); return, "Failed to uv_read_start %d", ret);
} }
int StartPropertyService() void StopParamService()
{ {
PROPERTY_LOGI("StartPropertyService.");
uv_fs_t req; uv_fs_t req;
uv_fs_unlink(uv_default_loop(), &req, PIPE_NAME, NULL); uv_fs_unlink(uv_default_loop(), &req, PIPE_NAME, NULL);
CloseParamWorkSpace(&g_paramWorkSpace);
ClosePersistParamWorkSpace();
uv_stop(uv_default_loop());
PARAM_LOGI("StopParamService.");
}
signal(SIGINT, RemoveSocket); int StartParamService()
{
PARAM_LOGI("StartParamService.");
uv_fs_t req;
uv_fs_unlink(uv_default_loop(), &req, PIPE_NAME, NULL);
uv_pipe_t pipeServer; uv_pipe_t pipeServer;
int ret = uv_pipe_init(uv_default_loop(), &pipeServer, 0); int ret = uv_pipe_init(uv_default_loop(), &pipeServer, 0);
PROPERTY_CHECK(ret == 0, return ret, "Failed to uv_pipe_init %d", ret); PARAM_CHECK(ret == 0, return ret, "Failed to uv_pipe_init %d", ret);
ret = uv_pipe_bind(&pipeServer, PIPE_NAME); ret = uv_pipe_bind(&pipeServer, PIPE_NAME);
PROPERTY_CHECK(ret == 0, return ret, "Failed to uv_pipe_bind %d %s", ret, uv_err_name(ret)); PARAM_CHECK(ret == 0, return ret, "Failed to uv_pipe_bind %d %s", ret, uv_err_name(ret));
ret = uv_listen((uv_stream_t*)&pipeServer, SOMAXCONN, OnConnection); ret = uv_listen((uv_stream_t*)&pipeServer, SOMAXCONN, OnConnection);
PROPERTY_CHECK(ret == 0, return ret, "Failed to uv_listen %d %s", ret, uv_err_name(ret)); PARAM_CHECK(ret == 0, return ret, "Failed to uv_listen %d %s", ret, uv_err_name(ret));
uv_run(uv_default_loop(), UV_RUN_DEFAULT); uv_run(uv_default_loop(), UV_RUN_DEFAULT);
PROPERTY_LOGI("Start service exit."); PARAM_LOGI("Start service exit.");
return 0; return 0;
} }
int SystemWriteParameter(const char *name, const char *value) int SystemWriteParam(const char *name, const char *value)
{ {
PROPERTY_CHECK(name != NULL && value != NULL, return -1, "The name is null"); PARAM_CHECK(name != NULL && value != NULL, return -1, "The name is null");
PROPERTY_LOGI("SystemWriteParameter name %s value: %s", name, value); PARAM_LOGI("SystemWriteParam name %s value: %s", name, value);
int ret = WritePropertyWithCheck(&g_propertyWorkSpace, &g_propertyWorkSpace.label, name, value); int ret = WriteParamWithCheck(&g_paramWorkSpace, &g_paramWorkSpace.label, name, value);
//PARAM_LOGI("SystemWriteParam name %s value: %s", name, value);
if (ret == 0) { if (ret == 0) {
ret = WritePersistProperty(name, value); ret = WritePersistParam(name, value);
PROPERTY_CHECK(ret == 0, return ret, "Failed to set property"); PARAM_CHECK(ret == 0, return ret, "Failed to set param");
} else { } else {
PROPERTY_LOGE("Failed to set property %d name %s %s", ret, name, value); PARAM_LOGE("Failed to set param %d name %s %s", ret, name, value);
} }
// notify event to process trigger // notify event to process trigger
PostPropertyTrigger(name, value); PostParamTrigger(name, value);
return 0; return 0;
} }
int SystemReadParameter(const char *name, char *value, unsigned int *len) int SystemReadParam(const char *name, char *value, unsigned int *len)
{ {
PROPERTY_CHECK(name != NULL && len != NULL, return -1, "The name is null"); PARAM_CHECK(name != NULL && len != NULL, return -1, "The name is null");
PropertyHandle handle = 0; ParamHandle handle = 0;
int ret = ReadPropertyWithCheck(&g_propertyWorkSpace, name, &handle); int ret = ReadParamWithCheck(&g_paramWorkSpace, name, &handle);
if (ret == 0) { if (ret == 0) {
ret = ReadPropertyValue(&g_propertyWorkSpace, handle, value, len); ret = ReadParamValue(&g_paramWorkSpace, handle, value, len);
} }
return ret; return ret;
} }
int SystemTraversalParameters(void (*traversalParameter)(PropertyHandle handle, void* cookie), void* cookie) ParamWorkSpace *GetParamWorkSpace()
{ {
PROPERTY_CHECK(traversalParameter != NULL, return -1, "The param is null"); return &g_paramWorkSpace;
return TraversalProperty(&g_propertyWorkSpace, traversalParameter, cookie);
} }
PropertyWorkSpace *GetPropertyWorkSpace() int LoadPersistParams()
{ {
return &g_propertyWorkSpace; return RefreshPersistParams(&g_paramWorkSpace, g_initContext);
} }
int LoadPersistProperties() int SystemTraversalParam(void (*traversalParameter)(ParamHandle handle, void* cookie), void* cookie)
{ {
return RefreshPersistProperties(&g_propertyWorkSpace, g_initContext); PARAM_CHECK(traversalParameter != NULL, return -1, "The param is null");
} return TraversalParam(&g_paramWorkSpace, traversalParameter, cookie);
}
\ No newline at end of file
...@@ -16,18 +16,19 @@ ...@@ -16,18 +16,19 @@
#include "trigger_checker.h" #include "trigger_checker.h"
#include <ctype.h> #include <ctype.h>
#include "trigger_manager.h" #include "trigger_manager.h"
#include "property_service.h" #include "param_service.h"
#define LABEL "Trigger"
// 申请整块能存作为计算的节点 // 申请整块能存作为计算的节点
int CalculatorInit(LogicCalculator *calculator, int dataNumber, int dataUnit, int needCondition) int CalculatorInit(LogicCalculator *calculator, int dataNumber, int dataUnit, int needCondition)
{ {
TRIGGER_CHECK(calculator != NULL, return -1, "Invalid param"); PARAM_CHECK(calculator != NULL, return -1, "Invalid param");
int dataSize = dataUnit * dataNumber; int dataSize = dataUnit * dataNumber;
if (needCondition) { if (needCondition) {
dataSize += 5 * SUPPORT_DATA_BUFFER_MAX; dataSize += 5 * SUPPORT_DATA_BUFFER_MAX;
} }
calculator->data = (char *)malloc(dataSize); calculator->data = (char *)malloc(dataSize);
TRIGGER_CHECK(calculator->data != NULL, return -1, "Failed to malloc for calculator"); PARAM_CHECK(calculator->data != NULL, return -1, "Failed to malloc for calculator");
calculator->dataNumber = dataNumber; calculator->dataNumber = dataNumber;
calculator->endIndex = 0; calculator->endIndex = 0;
calculator->dataUnit = dataUnit; calculator->dataUnit = dataUnit;
...@@ -47,30 +48,30 @@ int CalculatorInit(LogicCalculator *calculator, int dataNumber, int dataUnit, in ...@@ -47,30 +48,30 @@ int CalculatorInit(LogicCalculator *calculator, int dataNumber, int dataUnit, in
void CalculatorFree(LogicCalculator *calculator) void CalculatorFree(LogicCalculator *calculator)
{ {
TRIGGER_CHECK(calculator != NULL, return, "Invalid param"); PARAM_CHECK(calculator != NULL, return, "Invalid param");
free(calculator->data); free(calculator->data);
calculator->data = NULL; calculator->data = NULL;
} }
static void CalculatorClear(LogicCalculator *calculator) static void CalculatorClear(LogicCalculator *calculator)
{ {
TRIGGER_CHECK(calculator != NULL, return, "Invalid param"); PARAM_CHECK(calculator != NULL, return, "Invalid param");
calculator->endIndex = 0; calculator->endIndex = 0;
} }
static int CalculatorPushChar(LogicCalculator *calculator, char data) static int CalculatorPushChar(LogicCalculator *calculator, char data)
{ {
TRIGGER_CHECK(calculator != NULL, return -1, "Invalid param"); PARAM_CHECK(calculator != NULL, return -1, "Invalid param");
TRIGGER_CHECK(calculator->endIndex < calculator->dataNumber, return -1, "More data for calculator support"); PARAM_CHECK(calculator->endIndex < calculator->dataNumber, return -1, "More data for calculator support");
TRIGGER_CHECK(sizeof(char) == calculator->dataUnit, return -1, "More data for calculator support"); PARAM_CHECK(sizeof(char) == calculator->dataUnit, return -1, "More data for calculator support");
calculator->data[calculator->endIndex++] = data; calculator->data[calculator->endIndex++] = data;
return 0; return 0;
} }
static int CalculatorPopChar(LogicCalculator *calculator, char *data) static int CalculatorPopChar(LogicCalculator *calculator, char *data)
{ {
TRIGGER_CHECK(calculator != NULL, return -1, "Invalid param"); PARAM_CHECK(calculator != NULL, return -1, "Invalid param");
TRIGGER_CHECK(calculator->endIndex < calculator->dataNumber, return -1, "More data for calculator support"); PARAM_CHECK(calculator->endIndex < calculator->dataNumber, return -1, "More data for calculator support");
if (calculator->endIndex == 0) { if (calculator->endIndex == 0) {
return -1; return -1;
} }
...@@ -80,32 +81,32 @@ static int CalculatorPopChar(LogicCalculator *calculator, char *data) ...@@ -80,32 +81,32 @@ static int CalculatorPopChar(LogicCalculator *calculator, char *data)
static int CalculatorPush(LogicCalculator *calculator, void *data) static int CalculatorPush(LogicCalculator *calculator, void *data)
{ {
TRIGGER_CHECK(calculator != NULL, return -1, "Invalid param"); PARAM_CHECK(calculator != NULL, return -1, "Invalid param");
TRIGGER_CHECK(calculator->endIndex < calculator->dataNumber, return -1, "More data for calculator support"); PARAM_CHECK(calculator->endIndex < calculator->dataNumber, return -1, "More data for calculator support");
char *tmpData = (calculator->data + calculator->dataUnit * calculator->endIndex); char *tmpData = (calculator->data + calculator->dataUnit * calculator->endIndex);
int ret = memcpy_s(tmpData, calculator->dataUnit, data, calculator->dataUnit); int ret = memcpy_s(tmpData, calculator->dataUnit, data, calculator->dataUnit);
TRIGGER_CHECK(ret == 0, return -1, "Failed to copy logic data"); PARAM_CHECK(ret == 0, return -1, "Failed to copy logic data");
calculator->endIndex++; calculator->endIndex++;
return 0; return 0;
} }
static int CalculatorPop(LogicCalculator *calculator, void *data) static int CalculatorPop(LogicCalculator *calculator, void *data)
{ {
TRIGGER_CHECK(calculator != NULL || data == NULL, return -1, "Invalid param"); PARAM_CHECK(calculator != NULL || data == NULL, return -1, "Invalid param");
TRIGGER_CHECK(calculator->endIndex < calculator->dataNumber, return -1, "More data for calculator support"); PARAM_CHECK(calculator->endIndex < calculator->dataNumber, return -1, "More data for calculator support");
if (calculator->endIndex == 0) { if (calculator->endIndex == 0) {
return -1; return -1;
} }
char *tmpData = calculator->data + calculator->dataUnit * (calculator->endIndex - 1); char *tmpData = calculator->data + calculator->dataUnit * (calculator->endIndex - 1);
int ret = memcpy_s(data, calculator->dataUnit, tmpData, calculator->dataUnit); int ret = memcpy_s(data, calculator->dataUnit, tmpData, calculator->dataUnit);
TRIGGER_CHECK(ret == 0, return -1, "Failed to copy logic data"); PARAM_CHECK(ret == 0, return -1, "Failed to copy logic data");
calculator->endIndex--; calculator->endIndex--;
return 0; return 0;
} }
static int CalculatorLength(const LogicCalculator *calculator) static int CalculatorLength(const LogicCalculator *calculator)
{ {
TRIGGER_CHECK(calculator != NULL, return 0, "Invalid param"); PARAM_CHECK(calculator != NULL, return 0, "Invalid param");
return calculator->endIndex; return calculator->endIndex;
} }
...@@ -134,7 +135,7 @@ static int HandleOperationOr(LogicCalculator *calculator, char *prefix, u_int32_ ...@@ -134,7 +135,7 @@ static int HandleOperationOr(LogicCalculator *calculator, char *prefix, u_int32_
CalculatorPushChar(calculator, e); CalculatorPushChar(calculator, e);
} else { } else {
ret = PrefixAdd(prefix, prefixIndex, prefixLen, e); ret = PrefixAdd(prefix, prefixIndex, prefixLen, e);
TRIGGER_CHECK(ret == 0, return -1, "Invalid prefix"); PARAM_CHECK(ret == 0, return -1, "Invalid prefix");
} }
} while (CalculatorLength(calculator) > 0 && e != '('); } while (CalculatorLength(calculator) > 0 && e != '(');
CalculatorPushChar(calculator, '|'); CalculatorPushChar(calculator, '|');
...@@ -150,13 +151,10 @@ static int ComputeSubCondition(LogicCalculator *calculator, LogicData *data, con ...@@ -150,13 +151,10 @@ static int ComputeSubCondition(LogicCalculator *calculator, LogicData *data, con
// 解析条件 // 解析条件
int ret = GetValueFromContent(condition + data->startIndex, int ret = GetValueFromContent(condition + data->startIndex,
data->endIndex - data->startIndex, 0, calculator->conditionName, SUPPORT_DATA_BUFFER_MAX); data->endIndex - data->startIndex, 0, calculator->conditionName, SUPPORT_DATA_BUFFER_MAX);
TRIGGER_CHECK(ret == 0, return -1, "Failed parse content name"); PARAM_CHECK(ret == 0, return -1, "Failed parse content name");
ret = GetValueFromContent(condition + data->startIndex, data->endIndex - data->startIndex, ret = GetValueFromContent(condition + data->startIndex, data->endIndex - data->startIndex,
strlen(calculator->conditionName) + 1, calculator->conditionContent, SUPPORT_DATA_BUFFER_MAX); strlen(calculator->conditionName) + 1, calculator->conditionContent, SUPPORT_DATA_BUFFER_MAX);
TRIGGER_CHECK(ret == 0, return -1, "Failed parse content value"); PARAM_CHECK(ret == 0, return -1, "Failed parse content value");
TRIGGER_LOGI("ComputeSubCondition subcondition \'%s\' \'%s\'",
calculator->conditionName, calculator->conditionContent);
// check name // check name
if (strcmp(calculator->conditionName, calculator->inputName) == 0) { if (strcmp(calculator->conditionName, calculator->inputName) == 0) {
if (strcmp(calculator->conditionContent, "*") == 0) { if (strcmp(calculator->conditionContent, "*") == 0) {
...@@ -165,13 +163,13 @@ static int ComputeSubCondition(LogicCalculator *calculator, LogicData *data, con ...@@ -165,13 +163,13 @@ static int ComputeSubCondition(LogicCalculator *calculator, LogicData *data, con
if (strcmp(calculator->conditionContent, calculator->inputContent) == 0) { if (strcmp(calculator->conditionContent, calculator->inputContent) == 0) {
return 1; return 1;
} }
} else { }/* else {
u_int32_t len = SUPPORT_DATA_BUFFER_MAX; u_int32_t len = SUPPORT_DATA_BUFFER_MAX;
ret = SystemReadParameter(calculator->conditionName, calculator->readContent, &len); ret = SystemReadParam(calculator->conditionName, calculator->readContent, &len);
if (ret == 0 && strcmp(calculator->conditionContent, calculator->readContent) == 0) { if (ret == 0 && strcmp(calculator->conditionContent, calculator->readContent) == 0) {
return 1; return 1;
} }
} }*/
return 0; return 0;
} }
...@@ -210,7 +208,7 @@ int ComputeCondition(LogicCalculator *calculator, const char *condition) ...@@ -210,7 +208,7 @@ int ComputeCondition(LogicCalculator *calculator, const char *condition)
noneOper = 0; noneOper = 0;
int ret = CalculatorPop(calculator, (void*)&data2); int ret = CalculatorPop(calculator, (void*)&data2);
ret |= CalculatorPop(calculator, (void*)&data1); ret |= CalculatorPop(calculator, (void*)&data1);
TRIGGER_CHECK(ret == 0, return -1, "Failed to pop data"); PARAM_CHECK(ret == 0, return -1, "Failed to pop data");
ret = ComputeSubCondition(calculator, &data1, condition); ret = ComputeSubCondition(calculator, &data1, condition);
data1.flags = 0; data1.flags = 0;
...@@ -222,7 +220,7 @@ int ComputeCondition(LogicCalculator *calculator, const char *condition) ...@@ -222,7 +220,7 @@ int ComputeCondition(LogicCalculator *calculator, const char *condition)
} }
} }
ret = CalculatorPush(calculator, (void*)&data1); ret = CalculatorPush(calculator, (void*)&data1);
TRIGGER_CHECK(ret == 0, return -1, "Failed to push data"); PARAM_CHECK(ret == 0, return -1, "Failed to push data");
start = currIndex + 1; // 跳过符号 start = currIndex + 1; // 跳过符号
} else if (isspace(condition[currIndex])) { } else if (isspace(condition[currIndex])) {
if (start == currIndex) { if (start == currIndex) {
...@@ -233,7 +231,7 @@ int ComputeCondition(LogicCalculator *calculator, const char *condition) ...@@ -233,7 +231,7 @@ int ComputeCondition(LogicCalculator *calculator, const char *condition)
data1.startIndex = start; data1.startIndex = start;
data1.endIndex = currIndex; data1.endIndex = currIndex;
int ret = CalculatorPush(calculator, (void*)&data1); int ret = CalculatorPush(calculator, (void*)&data1);
TRIGGER_CHECK(ret == 0, return -1, "Failed to push data"); PARAM_CHECK(ret == 0, return -1, "Failed to push data");
start = currIndex + 1; start = currIndex + 1;
} }
currIndex++; currIndex++;
...@@ -244,7 +242,7 @@ int ComputeCondition(LogicCalculator *calculator, const char *condition) ...@@ -244,7 +242,7 @@ int ComputeCondition(LogicCalculator *calculator, const char *condition)
data1.endIndex = strlen(condition); data1.endIndex = strlen(condition);
} else { } else {
int ret = CalculatorPop(calculator, &data1); int ret = CalculatorPop(calculator, &data1);
TRIGGER_CHECK(ret == 0, return -1, "Invalid calculator"); PARAM_CHECK(ret == 0, return -1, "Invalid calculator");
} }
return ComputeSubCondition(calculator, &data1, condition); return ComputeSubCondition(calculator, &data1, condition);
} }
...@@ -263,17 +261,17 @@ int ConvertInfixToPrefix(const char *condition, char *prefix, u_int32_t prefixLe ...@@ -263,17 +261,17 @@ int ConvertInfixToPrefix(const char *condition, char *prefix, u_int32_t prefixLe
CalculatorPopChar(&calculator, &e); CalculatorPopChar(&calculator, &e);
while (e != '(') { while (e != '(') {
ret = PrefixAdd(prefix, &prefixIndex, prefixLen, e); ret = PrefixAdd(prefix, &prefixIndex, prefixLen, e);
TRIGGER_CHECK(ret == 0, CalculatorFree(&calculator); return -1, "Invalid prefix"); PARAM_CHECK(ret == 0, CalculatorFree(&calculator); return -1, "Invalid prefix");
ret = CalculatorPopChar(&calculator, &e); ret = CalculatorPopChar(&calculator, &e);
TRIGGER_CHECK(ret == 0, CalculatorFree(&calculator); return -1, "Invalid calculator"); PARAM_CHECK(ret == 0, CalculatorFree(&calculator); return -1, "Invalid calculator");
} }
} else if (condition[curr] == '|') { } else if (condition[curr] == '|') {
TRIGGER_CHECK(condition[curr + 1] == '|', CalculatorFree(&calculator); return -1, "Invalid condition"); PARAM_CHECK(condition[curr + 1] == '|', CalculatorFree(&calculator); return -1, "Invalid condition");
ret = HandleOperationOr(&calculator, prefix, &prefixIndex, prefixLen); ret = HandleOperationOr(&calculator, prefix, &prefixIndex, prefixLen);
TRIGGER_CHECK(ret == 0, CalculatorFree(&calculator); return -1, "Invalid prefix"); PARAM_CHECK(ret == 0, CalculatorFree(&calculator); return -1, "Invalid prefix");
curr++; curr++;
} else if (condition[curr] == '&') { } else if (condition[curr] == '&') {
TRIGGER_CHECK(condition[curr + 1] == '&', CalculatorFree(&calculator); return -1, "Invalid condition"); PARAM_CHECK(condition[curr + 1] == '&', CalculatorFree(&calculator); return -1, "Invalid condition");
prefix[prefixIndex++] = ' '; prefix[prefixIndex++] = ' ';
CalculatorPushChar(&calculator, condition[curr]); CalculatorPushChar(&calculator, condition[curr]);
curr++; curr++;
...@@ -283,13 +281,13 @@ int ConvertInfixToPrefix(const char *condition, char *prefix, u_int32_t prefixLe ...@@ -283,13 +281,13 @@ int ConvertInfixToPrefix(const char *condition, char *prefix, u_int32_t prefixLe
prefix[prefixIndex++] = condition[curr]; prefix[prefixIndex++] = condition[curr];
} }
curr++; curr++;
TRIGGER_CHECK(prefixIndex < prefixLen, CalculatorFree(&calculator); return -1, "Invalid prefixIndex"); PARAM_CHECK(prefixIndex < prefixLen, CalculatorFree(&calculator); return -1, "Invalid prefixIndex");
} }
while (CalculatorLength(&calculator) > 0) { while (CalculatorLength(&calculator) > 0) {
CalculatorPopChar(&calculator, &e); CalculatorPopChar(&calculator, &e);
ret = PrefixAdd(prefix, &prefixIndex, prefixLen, e); ret = PrefixAdd(prefix, &prefixIndex, prefixLen, e);
TRIGGER_CHECK(ret == 0, CalculatorFree(&calculator); PARAM_CHECK(ret == 0, CalculatorFree(&calculator);
return -1, "Invalid prefix %u %u", prefixIndex, prefixLen); return -1, "Invalid prefix %u %u", prefixIndex, prefixLen);
} }
prefix[prefixIndex] = '\0'; prefix[prefixIndex] = '\0';
......
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
#include "init_utils.h" #include "init_utils.h"
#include "trigger_checker.h" #include "trigger_checker.h"
#define LABEL "Trigger"
#define TRIGGER_AREA_SPACE 1024*64 #define TRIGGER_AREA_SPACE 1024*64
#define TRIGGER_EXECUTE_QUEUE 64 #define TRIGGER_EXECUTE_QUEUE 64
#define BUFFER_SIZE 256 #define BUFFER_SIZE 256
...@@ -44,18 +45,18 @@ ...@@ -44,18 +45,18 @@
int InitTriggerWorkSpace(TriggerWorkSpace *workSpace) int InitTriggerWorkSpace(TriggerWorkSpace *workSpace)
{ {
TRIGGER_CHECK(workSpace != NULL, return -1, "Invalid parm"); PARAM_CHECK(workSpace != NULL, return -1, "Invalid parm");
if (workSpace->area != NULL) { if (workSpace->area != NULL) {
return 0; return 0;
} }
CheckAndCreateDir(TRIGGER_PATH); CheckAndCreateDir(TRIGGER_PATH);
int fd = open(TRIGGER_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, 0444); int fd = open(TRIGGER_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, 0444);
TRIGGER_CHECK(fd >= 0, return -1, "Open file fail error %s", strerror(errno)); PARAM_CHECK(fd >= 0, return -1, "Open file fail error %s", strerror(errno));
lseek(fd, TRIGGER_AREA_SPACE, SEEK_SET); lseek(fd, TRIGGER_AREA_SPACE, SEEK_SET);
write(fd, "", 1); write(fd, "", 1);
void *areaAddr = (void *)mmap(NULL, TRIGGER_AREA_SPACE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); void *areaAddr = (void *)mmap(NULL, TRIGGER_AREA_SPACE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
TRIGGER_CHECK(areaAddr != MAP_FAILED, close(fd); return -1, PARAM_CHECK(areaAddr != MAP_FAILED, close(fd); return -1,
"Failed to map memory error %s", strerror(errno)); "Failed to map memory error %s", strerror(errno));
close(fd); close(fd);
...@@ -84,30 +85,29 @@ static CommandNode *GetCmdByIndex(TriggerWorkSpace *workSpace, TriggerNode *trig ...@@ -84,30 +85,29 @@ static CommandNode *GetCmdByIndex(TriggerWorkSpace *workSpace, TriggerNode *trig
return NULL; return NULL;
} }
u_int32_t size = sizeof(CommandNode) + 2; u_int32_t size = sizeof(CommandNode) + 2;
TRIGGER_CHECK((index + size) < workSpace->area->dataSize, PARAM_CHECK((index + size) < workSpace->area->dataSize,
return NULL, "Invalid index for cmd %u", index); return NULL, "Invalid index for cmd %u", index);
return (CommandNode *)(workSpace->area->data + index); return (CommandNode *)(workSpace->area->data + index);
} }
static u_int32_t AddCommand(TriggerWorkSpace *workSpace, TriggerNode *trigger, const char *cmdName, const char *content) static u_int32_t AddCommand(TriggerWorkSpace *workSpace, TriggerNode *trigger, const char *cmdName, const char *content)
{ {
TRIGGER_CHECK(workSpace != NULL && trigger != NULL, return 0, "list is null"); PARAM_CHECK(workSpace != NULL && trigger != NULL, return 0, "list is null");
TRIGGER_CHECK(content != NULL, return 0, "command is null");
u_int32_t size = sizeof(CommandNode) + strlen(cmdName) + 1; u_int32_t size = sizeof(CommandNode) + strlen(cmdName) + 1;
size += (content == NULL) ? 1 : strlen(content) + 1; size += (content == NULL) ? 1 : strlen(content) + 1;
TRIGGER_CHECK((workSpace->area->currOffset + size) < workSpace->area->dataSize, PARAM_CHECK((workSpace->area->currOffset + size) < workSpace->area->dataSize,
return 0, "Not enough memory for cmd %u %u", size, workSpace->area->currOffset); return 0, "Not enough memory for cmd %u %u", size, workSpace->area->currOffset);
CommandNode *node = (CommandNode *)(workSpace->area->data + workSpace->area->currOffset); CommandNode *node = (CommandNode *)(workSpace->area->data + workSpace->area->currOffset);
TRIGGER_CHECK(node != NULL, return 0, "Failed to alloc memory for command"); PARAM_CHECK(node != NULL, return 0, "Failed to alloc memory for command");
int ret = memcpy_s(node->name, sizeof(node->name) - 1, cmdName, strlen(cmdName)); int ret = memcpy_s(node->name, sizeof(node->name) - 1, cmdName, strlen(cmdName));
TRIGGER_CHECK(ret == 0, return 0, "Failed to copy command"); PARAM_CHECK(ret == 0, return 0, "Failed to copy command");
node->name[strlen(cmdName)] = '\0'; node->name[strlen(cmdName)] = '\0';
if (content != NULL) { if (content != NULL) {
ret = memcpy_s(node->content, size, content, strlen(content)); ret = memcpy_s(node->content, size, content, strlen(content));
node->content[strlen(content)] = '\0'; node->content[strlen(content)] = '\0';
TRIGGER_CHECK(ret == 0, return 0, "Failed to copy command"); PARAM_CHECK(ret == 0, return 0, "Failed to copy command");
} else { } else {
node->content[0] = '\0'; node->content[0] = '\0';
} }
...@@ -135,36 +135,36 @@ static TriggerNode *GetTriggerByIndex(TriggerWorkSpace *workSpace, u_int32_t ind ...@@ -135,36 +135,36 @@ static TriggerNode *GetTriggerByIndex(TriggerWorkSpace *workSpace, u_int32_t ind
return NULL; return NULL;
} }
u_int32_t size = sizeof(TriggerNode) + 1; u_int32_t size = sizeof(TriggerNode) + 1;
TRIGGER_CHECK((index + size) < workSpace->area->dataSize, PARAM_CHECK((index + size) < workSpace->area->dataSize,
return NULL, "Invalid index for trigger %u", index); return NULL, "Invalid index for trigger %u", index);
return (TriggerNode *)(workSpace->area->data + index); return (TriggerNode *)(workSpace->area->data + index);
} }
static u_int32_t AddTrigger(TriggerWorkSpace *workSpace, int type, const char *name, const char *condition) static u_int32_t AddTrigger(TriggerWorkSpace *workSpace, int type, const char *name, const char *condition)
{ {
TRIGGER_CHECK(workSpace != NULL && name != NULL, return 0, "list is null"); PARAM_CHECK(workSpace != NULL && name != NULL, return 0, "list is null");
const char *tmpCond = condition; const char *tmpCond = condition;
if (type == TRIGGER_BOOT && condition == NULL) { if (type == TRIGGER_BOOT && condition == NULL) {
tmpCond = name; tmpCond = name;
} }
u_int32_t conditionSize = (tmpCond == NULL) ? 1 : strlen(tmpCond) + 1 + CONDITION_EXTEND_LEN; u_int32_t conditionSize = (tmpCond == NULL) ? 1 : strlen(tmpCond) + 1 + CONDITION_EXTEND_LEN;
TRIGGER_CHECK((workSpace->area->currOffset + sizeof(TriggerNode) + conditionSize) < workSpace->area->dataSize, PARAM_CHECK((workSpace->area->currOffset + sizeof(TriggerNode) + conditionSize) < workSpace->area->dataSize,
return -1, "Not enough memory for cmd"); return -1, "Not enough memory for cmd");
TriggerNode *node = (TriggerNode *)(workSpace->area->data + workSpace->area->currOffset); TriggerNode *node = (TriggerNode *)(workSpace->area->data + workSpace->area->currOffset);
TRIGGER_CHECK(node != NULL, return 0, "Failed to alloc memory for trigger"); PARAM_CHECK(node != NULL, return 0, "Failed to alloc memory for trigger");
node->type = type; node->type = type;
int ret = memcpy_s(node->name, sizeof(node->name) - 1, name, strlen(name)); int ret = memcpy_s(node->name, sizeof(node->name) - 1, name, strlen(name));
TRIGGER_CHECK(ret == 0, return 0, "Failed to memcpy_s for trigger"); PARAM_CHECK(ret == 0, return 0, "Failed to memcpy_s for trigger");
node->name[strlen(name)] = '\0'; node->name[strlen(name)] = '\0';
if (tmpCond != NULL) { if (tmpCond != NULL) {
if (type == TRIGGER_PROPERTY) { if (type == TRIGGER_PROPERTY) {
ret = ConvertInfixToPrefix(tmpCond, node->condition, conditionSize); ret = ConvertInfixToPrefix(tmpCond, node->condition, conditionSize);
TRIGGER_CHECK(ret == 0, return 0, "Failed to memcpy_s for trigger"); PARAM_CHECK(ret == 0, return 0, "Failed to memcpy_s for trigger");
} else { } else {
ret = memcpy_s(node->condition, strlen(tmpCond) + 1, tmpCond, strlen(tmpCond)); ret = memcpy_s(node->condition, strlen(tmpCond) + 1, tmpCond, strlen(tmpCond));
TRIGGER_CHECK(ret == 0, return 0, "Failed to memcpy_s for trigger"); PARAM_CHECK(ret == 0, return 0, "Failed to memcpy_s for trigger");
node->condition[strlen(tmpCond)] = '\0'; node->condition[strlen(tmpCond)] = '\0';
} }
} else { } else {
...@@ -194,22 +194,22 @@ static u_int32_t AddTrigger(TriggerWorkSpace *workSpace, int type, const char *n ...@@ -194,22 +194,22 @@ static u_int32_t AddTrigger(TriggerWorkSpace *workSpace, int type, const char *n
static int GetTriggerIndex(const char *type) static int GetTriggerIndex(const char *type)
{ {
if (strncmp("property", type, strlen("property")) == 0) { if (strncmp("param", type, strlen("param")) == 0) {
return TRIGGER_PROPERTY; return TRIGGER_PROPERTY;
} }
static const char *triggerType[] = { static const char *triggerType[] = {
"boot", "early-init", "init", "early-init", "late-init", "pre-init", "boot", "early-init", "init", "early-init", "late-init", "post-init",
"early-fs", "post-fs", "late-fs", "post-fs-data", "early-fs", "post-fs", "late-fs", "post-fs-data",
"nonencrypted", "nonencrypted",
"firmware_mounts_complete", "firmware_mounts_complete",
"load_persist_props_action" "load_persist_params_action"
}; };
for (size_t i = 0; i < sizeof(triggerType) / sizeof(char*); i++) { for (size_t i = 0; i < sizeof(triggerType) / sizeof(char*); i++) {
if (strncmp(triggerType[i], type, strlen(triggerType[i])) == 0) { if (strncmp(triggerType[i], type, strlen(triggerType[i])) == 0) {
return TRIGGER_BOOT; return TRIGGER_BOOT;
} }
} }
return TRIGGER_UNKNOW; return TRIGGER_BOOT;
} }
static int CheckBootTriggerMatch(TriggerNode *trigger, void *content, u_int32_t contentSize) static int CheckBootTriggerMatch(TriggerNode *trigger, void *content, u_int32_t contentSize)
...@@ -222,53 +222,61 @@ static int CheckBootTriggerMatch(TriggerNode *trigger, void *content, u_int32_t ...@@ -222,53 +222,61 @@ static int CheckBootTriggerMatch(TriggerNode *trigger, void *content, u_int32_t
int ParseTrigger(TriggerWorkSpace *workSpace, cJSON *triggerItem) int ParseTrigger(TriggerWorkSpace *workSpace, cJSON *triggerItem)
{ {
TRIGGER_CHECK(triggerItem != NULL, return -1, "Invalid file"); PARAM_CHECK(triggerItem != NULL, return -1, "Invalid file");
TRIGGER_CHECK(workSpace != NULL, return -1, "Failed to create trigger list"); PARAM_CHECK(workSpace != NULL, return -1, "Failed to create trigger list");
char *name = cJSON_GetStringValue(cJSON_GetObjectItem(triggerItem, "name")); char *name = cJSON_GetStringValue(cJSON_GetObjectItem(triggerItem, "name"));
TRIGGER_CHECK(name != NULL, return -1, "Can not get name from cfg"); PARAM_CHECK(name != NULL, return -1, "Can not get name from cfg");
char *condition = cJSON_GetStringValue(cJSON_GetObjectItem(triggerItem, "condition")); char *condition = cJSON_GetStringValue(cJSON_GetObjectItem(triggerItem, "condition"));
int index = GetTriggerIndex(name); int index = GetTriggerIndex(name);
TRIGGER_CHECK(CHECK_INDEX_VALID(workSpace, index), return -1, "Failed to get trigger index"); PARAM_CHECK(CHECK_INDEX_VALID(workSpace, index), return -1, "Failed to get trigger index");
u_int32_t offset = AddTrigger(workSpace, index, name, condition); u_int32_t offset = 0;
//TRIGGER_LOGE("AddTrigger %u %s %u", offset, name, workSpace->area->currOffset); TriggerNode *trigger = GetTriggerByName(workSpace, name, &offset);
TRIGGER_CHECK(offset > 0, return -1, "Failed to create trigger %s", name); if (trigger == NULL) {
TriggerNode *trigger = GetTriggerByIndex(workSpace, offset); offset = AddTrigger(workSpace, index, name, condition);
PARAM_CHECK(offset > 0, return -1, "Failed to create trigger %s", name);
trigger = GetTriggerByIndex(workSpace, offset);
} else {
if (condition != NULL) {
PARAM_LOGE("Warning parseTrigger %s %s", name, condition);
}
}
PARAM_LOGE("ParseTrigger %s %u", name, offset);
// 添加命令行 // 添加命令行
cJSON* cmdItems = cJSON_GetObjectItem(triggerItem, CMDS_ARR_NAME_IN_JSON); cJSON* cmdItems = cJSON_GetObjectItem(triggerItem, CMDS_ARR_NAME_IN_JSON);
TRIGGER_CHECK(cJSON_IsArray(cmdItems), return -1, "Command item must be array"); PARAM_CHECK(cJSON_IsArray(cmdItems), return -1, "Command item must be array");
int cmdLinesCnt = cJSON_GetArraySize(cmdItems); int cmdLinesCnt = cJSON_GetArraySize(cmdItems);
TRIGGER_CHECK(cmdLinesCnt > 0, return -1, "Command array size must positive"); PARAM_CHECK(cmdLinesCnt > 0, return -1, "Command array size must positive %s", name);
for (int i = 0; i < cmdLinesCnt; ++i) { for (int i = 0; i < cmdLinesCnt; ++i) {
char *cmdLineStr = cJSON_GetStringValue(cJSON_GetArrayItem(cmdItems, i)); char *cmdLineStr = cJSON_GetStringValue(cJSON_GetArrayItem(cmdItems, i));
TRIGGER_CHECK(cmdLinesCnt > 0, continue, "Command is null"); PARAM_CHECK(cmdLinesCnt > 0, continue, "Command is null");
size_t cmdLineLen = strlen(cmdLineStr); size_t cmdLineLen = strlen(cmdLineStr);
const char *matchCmd = GetMatchCmd(cmdLineStr); const char *matchCmd = GetMatchCmd(cmdLineStr);
if (matchCmd == NULL && strncmp(cmdLineStr, TRIGGER_CMD, strlen(TRIGGER_CMD)) == 0) { if (matchCmd == NULL && strncmp(cmdLineStr, TRIGGER_CMD, strlen(TRIGGER_CMD)) == 0) {
matchCmd = TRIGGER_CMD; matchCmd = TRIGGER_CMD;
} }
TRIGGER_CHECK(matchCmd != NULL, continue, "Command not support %s", cmdLineStr); PARAM_CHECK(matchCmd != NULL, continue, "Command not support %s", cmdLineStr);
size_t matchLen = strlen(matchCmd); size_t matchLen = strlen(matchCmd);
if (matchLen == cmdLineLen) { if (matchLen == cmdLineLen) {
offset = AddCommand(workSpace, trigger, matchCmd, NULL); offset = AddCommand(workSpace, trigger, matchCmd, NULL);
} else { } else {
offset = AddCommand(workSpace, trigger, matchCmd, cmdLineStr + matchLen); offset = AddCommand(workSpace, trigger, matchCmd, cmdLineStr + matchLen);
} }
//TRIGGER_LOGE("AddCommand %u %s %u", offset, cmdLineStr, workSpace->area->currOffset); //PARAM_LOGE("AddCommand %u %s %u", offset, cmdLineStr, workSpace->area->currOffset);
TRIGGER_CHECK(offset > 0, continue, "Failed to add command %s", cmdLineStr); PARAM_CHECK(offset > 0, continue, "Failed to add command %s", cmdLineStr);
} }
return 0; return 0;
} }
int ExecuteTrigger(TriggerWorkSpace *workSpace, TriggerNode *trigger, CMD_EXECUTE cmdExecuter) int ExecuteTrigger(TriggerWorkSpace *workSpace, TriggerNode *trigger, CMD_EXECUTE cmdExecuter)
{ {
TRIGGER_CHECK(workSpace != NULL && trigger != NULL && cmdExecuter != NULL, return -1, "Invalid param"); PARAM_CHECK(workSpace != NULL && trigger != NULL && cmdExecuter != NULL, return -1, "Invalid param");
TRIGGER_LOGI("ExecuteCmds trigger %s", trigger->name); PARAM_LOGI("ExecuteCmds trigger %s", trigger->name);
CommandNode *cmd = GetCmdByIndex(workSpace, trigger, trigger->firstCmd); CommandNode *cmd = GetCmdByIndex(workSpace, trigger, trigger->firstCmd);
while (cmd != NULL) { while (cmd != NULL) {
cmdExecuter(trigger, cmd->name, cmd->content); cmdExecuter(trigger, cmd->name, cmd->content);
...@@ -279,7 +287,7 @@ int ExecuteTrigger(TriggerWorkSpace *workSpace, TriggerNode *trigger, CMD_EXECUT ...@@ -279,7 +287,7 @@ int ExecuteTrigger(TriggerWorkSpace *workSpace, TriggerNode *trigger, CMD_EXECUT
int ExecuteQueuePush(TriggerWorkSpace *workSpace, TriggerNode *trigger, u_int32_t triggerIndex) int ExecuteQueuePush(TriggerWorkSpace *workSpace, TriggerNode *trigger, u_int32_t triggerIndex)
{ {
TRIGGER_CHECK(workSpace != NULL, return -1, "Invalid area"); PARAM_CHECK(workSpace != NULL, return -1, "Invalid area");
pthread_mutex_lock(&workSpace->executeQueue.mutex); pthread_mutex_lock(&workSpace->executeQueue.mutex);
u_int32_t index = workSpace->executeQueue.endIndex++ % workSpace->executeQueue.queueCount; u_int32_t index = workSpace->executeQueue.endIndex++ % workSpace->executeQueue.queueCount;
workSpace->executeQueue.executeQueue[index] = triggerIndex; workSpace->executeQueue.executeQueue[index] = triggerIndex;
...@@ -303,22 +311,22 @@ TriggerNode *ExecuteQueuePop(TriggerWorkSpace *workSpace) ...@@ -303,22 +311,22 @@ TriggerNode *ExecuteQueuePop(TriggerWorkSpace *workSpace)
int ExecuteQueueSize(TriggerWorkSpace *workSpace) int ExecuteQueueSize(TriggerWorkSpace *workSpace)
{ {
TRIGGER_CHECK(workSpace != NULL, return 0, "Invalid param"); PARAM_CHECK(workSpace != NULL, return 0, "Invalid param");
return workSpace->executeQueue.endIndex - workSpace->executeQueue.startIndex; return workSpace->executeQueue.endIndex - workSpace->executeQueue.startIndex;
} }
int CheckTrigger(TriggerWorkSpace *workSpace, int CheckTrigger(TriggerWorkSpace *workSpace,
int type, void *content, u_int32_t contentSize, TRIGGER_CHECK_DONE triggerExecuter) int type, void *content, u_int32_t contentSize, PARAM_CHECK_DONE triggerExecuter)
{ {
static TRIGGER_MATCH triggerCheckMatch[TRIGGER_MAX] = { static TRIGGER_MATCH triggerCheckMatch[TRIGGER_MAX] = {
CheckBootTriggerMatch, NULL, NULL CheckBootTriggerMatch, NULL, NULL
}; };
TRIGGER_LOGI("ExecuteTrigger check content %s", (char*)content); PARAM_LOGI("ExecuteTrigger check content %s", (char*)content);
TRIGGER_CHECK(workSpace != NULL, return -1, "Trigger not init"); PARAM_CHECK(workSpace != NULL, return -1, "Trigger not init");
TRIGGER_CHECK(CHECK_INDEX_VALID(workSpace, type), return -1, "Invalid type %d", type); PARAM_CHECK(CHECK_INDEX_VALID(workSpace, type), return -1, "Invalid type %d", type);
TRIGGER_CHECK((u_int32_t)type < sizeof(triggerCheckMatch) / sizeof(triggerCheckMatch[0]), PARAM_CHECK((u_int32_t)type < sizeof(triggerCheckMatch) / sizeof(triggerCheckMatch[0]),
return -1, "Failed to get check function"); return -1, "Failed to get check function");
TRIGGER_CHECK(triggerCheckMatch[type] != NULL, return 0, "Failed to get check function"); PARAM_CHECK(triggerCheckMatch[type] != NULL, return 0, "Failed to get check function");
u_int32_t index = workSpace->header[type].firstTrigger; u_int32_t index = workSpace->header[type].firstTrigger;
TriggerNode *trigger = GetTriggerByIndex(workSpace, workSpace->header[type].firstTrigger); TriggerNode *trigger = GetTriggerByIndex(workSpace, workSpace->header[type].firstTrigger);
while (trigger != NULL) { while (trigger != NULL) {
...@@ -331,26 +339,25 @@ int CheckTrigger(TriggerWorkSpace *workSpace, ...@@ -331,26 +339,25 @@ int CheckTrigger(TriggerWorkSpace *workSpace,
return 0; return 0;
} }
int CheckPropertyTrigger(TriggerWorkSpace *workSpace, int CheckParamTrigger(TriggerWorkSpace *workSpace,
const char *content, u_int32_t contentSize, TRIGGER_CHECK_DONE triggerExecuter) const char *content, u_int32_t contentSize, PARAM_CHECK_DONE triggerExecuter)
{ {
TRIGGER_CHECK(workSpace != NULL && content != NULL && triggerExecuter != NULL, PARAM_CHECK(workSpace != NULL && content != NULL && triggerExecuter != NULL,
return -1, "Failed arg for property trigger"); return -1, "Failed arg for param trigger");
LogicCalculator calculator; LogicCalculator calculator;
CalculatorInit(&calculator, 100, sizeof(LogicData), 1); CalculatorInit(&calculator, 100, sizeof(LogicData), 1);
// 先解析content // 先解析content
int ret = GetValueFromContent(content, contentSize, 0, calculator.inputName, SUPPORT_DATA_BUFFER_MAX); int ret = GetValueFromContent(content, contentSize, 0, calculator.inputName, SUPPORT_DATA_BUFFER_MAX);
TRIGGER_CHECK(ret == 0, CalculatorFree(&calculator); return -1, "Failed parse content name"); PARAM_CHECK(ret == 0, CalculatorFree(&calculator); return -1, "Failed parse content name");
ret = GetValueFromContent(content, contentSize, ret = GetValueFromContent(content, contentSize,
strlen(calculator.inputName) + 1, calculator.inputContent, SUPPORT_DATA_BUFFER_MAX); strlen(calculator.inputName) + 1, calculator.inputContent, SUPPORT_DATA_BUFFER_MAX);
TRIGGER_CHECK(ret == 0, CalculatorFree(&calculator); return -1, "Failed parse content value"); PARAM_CHECK(ret == 0, CalculatorFree(&calculator); return -1, "Failed parse content value");
TRIGGER_LOGI("CheckPropertyTrigger content %s ", content); PARAM_LOGI("CheckParamTrigger content %s ", content);
u_int32_t index = workSpace->header[TRIGGER_PROPERTY].firstTrigger; u_int32_t index = workSpace->header[TRIGGER_PROPERTY].firstTrigger;
TriggerNode *trigger = GetTriggerByIndex(workSpace, workSpace->header[TRIGGER_PROPERTY].firstTrigger); TriggerNode *trigger = GetTriggerByIndex(workSpace, workSpace->header[TRIGGER_PROPERTY].firstTrigger);
while (trigger != NULL) { while (trigger != NULL) {
TRIGGER_LOGI("CheckPropertyTrigger name:%s condition \'%s\' ", trigger->name, trigger->condition);
ret = ComputeCondition(&calculator, trigger->condition); ret = ComputeCondition(&calculator, trigger->condition);
if (ret == 1) { if (ret == 1) {
triggerExecuter(trigger, index); triggerExecuter(trigger, index);
...@@ -364,7 +371,7 @@ int CheckPropertyTrigger(TriggerWorkSpace *workSpace, ...@@ -364,7 +371,7 @@ int CheckPropertyTrigger(TriggerWorkSpace *workSpace,
TriggerNode *GetTriggerByName(TriggerWorkSpace *workSpace, const char *triggerName, u_int32_t *triggerIndex) TriggerNode *GetTriggerByName(TriggerWorkSpace *workSpace, const char *triggerName, u_int32_t *triggerIndex)
{ {
TRIGGER_CHECK(workSpace != NULL && triggerName != NULL, return NULL, "Invalid param"); PARAM_CHECK(workSpace != NULL && triggerName != NULL, return NULL, "Invalid param");
for (size_t i = 0; i < sizeof(workSpace->header) / sizeof(workSpace->header[0]); i++) { for (size_t i = 0; i < sizeof(workSpace->header) / sizeof(workSpace->header[0]); i++) {
u_int32_t index = workSpace->header[i].firstTrigger; u_int32_t index = workSpace->header[i].firstTrigger;
TriggerNode *trigger = GetTriggerByIndex(workSpace, workSpace->header[i].firstTrigger); TriggerNode *trigger = GetTriggerByIndex(workSpace, workSpace->header[i].firstTrigger);
......
...@@ -18,70 +18,59 @@ ...@@ -18,70 +18,59 @@
#include <unistd.h> #include <unistd.h>
#include "init_cmds.h" #include "init_cmds.h"
#include "property_manager.h" #include "param_manager.h"
#include "trigger_checker.h" #include "trigger_checker.h"
#include "uv.h" #include "uv.h"
#define LABEL "Trigger"
#define SYS_POWER_CTRL "sys.powerctrl." #define SYS_POWER_CTRL "sys.powerctrl."
static int g_triggerServiceStart = 0; static int g_triggerServiceStart = 0;
static TriggerWorkSpace g_triggerWorkSpace = {}; static TriggerWorkSpace g_triggerWorkSpace = {};
static int DoCmdExecute(TriggerNode *trigger, const char *cmdName, const char *command) static int DoCmdExecute(TriggerNode *trigger, const char *cmdName, const char *command)
{ {
TRIGGER_CHECK(trigger != NULL && cmdName != NULL && command != NULL, return -1, "Invalid param"); PARAM_CHECK(trigger != NULL && cmdName != NULL && command != NULL, return -1, "Invalid param");
if (strncmp(cmdName, TRIGGER_CMD, strlen(TRIGGER_CMD)) == 0) { if (strncmp(cmdName, TRIGGER_CMD, strlen(TRIGGER_CMD)) == 0) {
u_int32_t triggerIndex = 0; u_int32_t triggerIndex = 0;
TriggerNode *node = GetTriggerByName(&g_triggerWorkSpace, command, &triggerIndex); TriggerNode *node = GetTriggerByName(&g_triggerWorkSpace, command, &triggerIndex);
if (node != NULL && !TRIGGER_NODE_IN_QUEUE(node)) { // 不在队列中 if (node != NULL && !TRIGGER_NODE_IN_QUEUE(node)) { // 不在队列中
TRIGGER_LOGI("DoCmdExecute trigger %s", node->name); PARAM_LOGI("DoCmdExecute trigger %s", node->name);
TRIGGER_NODE_SET_QUEUE_FLAG(node); TRIGGER_NODE_SET_QUEUE_FLAG(node);
ExecuteQueuePush(&g_triggerWorkSpace, node, triggerIndex); ExecuteQueuePush(&g_triggerWorkSpace, node, triggerIndex);
} }
return 0; return 0;
} }
TRIGGER_LOGI("DoCmdExecute trigger %s cmd %s", trigger->name, cmdName); PARAM_LOGI("DoCmdExecute trigger %s cmd %s %s", trigger->name, cmdName, command);
DoCmdByName(cmdName, command); DoCmdByName(cmdName, command);
return 0; return 0;
} }
static int DoTiggerCheckResult(TriggerNode *trigger, u_int32_t triggerIndex) static int DoTiggerCheckResult(TriggerNode *trigger, u_int32_t triggerIndex)
{ {
// 直接执行,不需要添加队列
if (!g_triggerServiceStart) {
TRIGGER_LOGI("DoTiggerExecute trigger %s", trigger->name);
ExecuteTrigger(&g_triggerWorkSpace, trigger, DoCmdExecute);
TRIGGER_NODE_CLEAR_QUEUE_FLAG(trigger);
}
// 已经在队列中了,则不执行 TODO // 已经在队列中了,则不执行 TODO
if (TRIGGER_NODE_IN_QUEUE(trigger)) { if (TRIGGER_NODE_IN_QUEUE(trigger)) {
TRIGGER_LOGI("DoTiggerExecute trigger %s has been waiting execute", trigger->name); PARAM_LOGI("DoTiggerExecute trigger %s has been waiting execute", trigger->name);
return 0; return 0;
} }
TRIGGER_NODE_SET_QUEUE_FLAG(trigger);
if (trigger->type == TRIGGER_BOOT) { // 立刻执行 PARAM_LOGI("Waiting to exec trigger %s", trigger->name);
TRIGGER_LOGI("DoTiggerExecute trigger %s", trigger->name); ExecuteQueuePush(&g_triggerWorkSpace, trigger, triggerIndex);
ExecuteTrigger(&g_triggerWorkSpace, trigger, DoCmdExecute);
TRIGGER_NODE_CLEAR_QUEUE_FLAG(trigger);
} else {
TRIGGER_NODE_SET_QUEUE_FLAG(trigger);
TRIGGER_LOGI("DoTiggerExecute trigger %s", trigger->name);
ExecuteQueuePush(&g_triggerWorkSpace, trigger, triggerIndex);
}
return 0; return 0;
} }
void ExecuteQueueWork() void ExecuteQueueWork(u_int32_t maxCount)
{ {
int executeCount = 0; PARAM_LOGI("ExecuteQueueWork %d %d", getpid(), gettid());
u_int32_t executeCount = 0;
TriggerNode *trigger = ExecuteQueuePop(&g_triggerWorkSpace); TriggerNode *trigger = ExecuteQueuePop(&g_triggerWorkSpace);
while (trigger != NULL) { while (trigger != NULL) {
ExecuteTrigger(&g_triggerWorkSpace, trigger, DoCmdExecute); ExecuteTrigger(&g_triggerWorkSpace, trigger, DoCmdExecute);
TRIGGER_NODE_CLEAR_QUEUE_FLAG(trigger); TRIGGER_NODE_CLEAR_QUEUE_FLAG(trigger);
executeCount++; executeCount++;
if (executeCount > 5) { if (executeCount > maxCount) {
break; break;
} }
PARAM_LOGI("ExecuteQueueWork %u", executeCount);
trigger = ExecuteQueuePop(&g_triggerWorkSpace); trigger = ExecuteQueuePop(&g_triggerWorkSpace);
} }
} }
...@@ -90,7 +79,7 @@ static void CheckTriggers(int type, void *content, u_int32_t contentLen) ...@@ -90,7 +79,7 @@ static void CheckTriggers(int type, void *content, u_int32_t contentLen)
{ {
switch (type) { switch (type) {
case EVENT_PROPERTY: { case EVENT_PROPERTY: {
CheckPropertyTrigger(&g_triggerWorkSpace, content, contentLen, DoTiggerCheckResult); CheckParamTrigger(&g_triggerWorkSpace, content, contentLen, DoTiggerCheckResult);
break; break;
} }
case EVENT_BOOT: { case EVENT_BOOT: {
...@@ -98,7 +87,7 @@ static void CheckTriggers(int type, void *content, u_int32_t contentLen) ...@@ -98,7 +87,7 @@ static void CheckTriggers(int type, void *content, u_int32_t contentLen)
break; break;
} }
default: default:
TRIGGER_LOGI("CheckTriggers: %d", type); PARAM_LOGI("CheckTriggers: %d", type);
break; break;
} }
} }
...@@ -106,7 +95,7 @@ static void CheckTriggers(int type, void *content, u_int32_t contentLen) ...@@ -106,7 +95,7 @@ static void CheckTriggers(int type, void *content, u_int32_t contentLen)
static void ProcessAfterEvent(uv_work_t *req, int status) static void ProcessAfterEvent(uv_work_t *req, int status)
{ {
free(req); free(req);
ExecuteQueueWork(); ExecuteQueueWork(UINT32_MAX);
} }
static void ProcessEvent(uv_work_t *req) static void ProcessEvent(uv_work_t *req)
...@@ -119,12 +108,12 @@ static const char *GetCmdInfo(const char *content, u_int32_t contentSize, char * ...@@ -119,12 +108,12 @@ static const char *GetCmdInfo(const char *content, u_int32_t contentSize, char *
{ {
char cmd[MAX_CMD_NAME_LEN + 1] = { 0 }; char cmd[MAX_CMD_NAME_LEN + 1] = { 0 };
int ret = GetValueFromContent(content, contentSize, 0, cmd, sizeof(cmd)); int ret = GetValueFromContent(content, contentSize, 0, cmd, sizeof(cmd));
TRIGGER_CHECK(ret == 0, return NULL, "Failed parse cmd"); PARAM_CHECK(ret == 0, return NULL, "Failed parse cmd");
u_int32_t cmdLen = strlen(cmd); u_int32_t cmdLen = strlen(cmd);
TRIGGER_CHECK(cmdLen < MAX_CMD_NAME_LEN, return NULL, "Failed parse cmd"); PARAM_CHECK(cmdLen < MAX_CMD_NAME_LEN, return NULL, "Failed parse cmd");
cmd[cmdLen] = ' '; cmd[cmdLen] = ' ';
cmd[cmdLen + 1] = '\0'; cmd[cmdLen + 1] = '\0';
*cmdParam = content + cmdLen + 1; *cmdParam = (char *)content + cmdLen + 1;
return GetMatchCmd(cmd); return GetMatchCmd(cmd);
} }
...@@ -137,70 +126,68 @@ static void SendTriggerEvent(TriggerDataEvent *event) ...@@ -137,70 +126,68 @@ static void SendTriggerEvent(TriggerDataEvent *event)
if (matchCmd != NULL) { if (matchCmd != NULL) {
DoCmdByName(matchCmd, cmdParam); DoCmdByName(matchCmd, cmdParam);
} else { } else {
TRIGGER_LOGE("SendTriggerEvent cmd %s not found", event->content); PARAM_LOGE("SendTriggerEvent cmd %s not found", event->content);
} }
free(event);
return;
} }
if (event->type == EVENT_BOOT || g_triggerServiceStart == 0) { else if (event->type == EVENT_BOOT || g_triggerServiceStart == 0) {
CheckTriggers(EVENT_PROPERTY, event->content, event->contentSize); CheckTriggers(event->type, event->content, event->contentSize);
free(event); ExecuteQueueWork(UINT32_MAX); // 需要立刻执行
} else { } else {
uv_queue_work(uv_default_loop(), &event->request, ProcessEvent, ProcessAfterEvent); uv_queue_work(uv_default_loop(), &event->request, ProcessEvent, ProcessAfterEvent);
event = NULL;
}
if (event != NULL) {
free(event);
} }
} }
void PostPropertyTrigger(const char *name, const char *value) void PostParamTrigger(const char *name, const char *value)
{ {
TRIGGER_CHECK(name != NULL && value != NULL, return, "Invalid param"); PARAM_CHECK(name != NULL && value != NULL, return, "Invalid param");
TRIGGER_LOGI("PostPropertyTrigger %s ", name); PARAM_LOGI("PostParamTrigger %s ", name);
int contentLen = strlen(name) + strlen(value) + 2; int contentLen = strlen(name) + strlen(value) + 2;
TriggerDataEvent *event = (TriggerDataEvent *)malloc(sizeof(TriggerDataEvent) + contentLen); TriggerDataEvent *event = (TriggerDataEvent *)malloc(sizeof(TriggerDataEvent) + contentLen);
TRIGGER_CHECK(event != NULL, return, "Failed to alloc memory"); PARAM_CHECK(event != NULL, return, "Failed to alloc memory");
event->type = EVENT_PROPERTY; event->type = EVENT_PROPERTY;
event->request.data = (char*)event + sizeof(uv_work_t); event->request.data = (char*)event + sizeof(uv_work_t);
event->contentSize = BuildPropertyContent(event->content, contentLen, name, value); event->contentSize = BuildParamContent(event->content, contentLen, name, value);
TRIGGER_CHECK(event->contentSize > 0, return, "Failed to copy porperty"); PARAM_CHECK(event->contentSize > 0, return, "Failed to copy porperty");
SendTriggerEvent(event); SendTriggerEvent(event);
TRIGGER_LOGI("PostPropertyTrigger %s success", name); PARAM_LOGI("PostParamTrigger %s success", name);
} }
void PostTrigger(EventType type, void *content, u_int32_t contentLen) void PostTrigger(EventType type, void *content, u_int32_t contentLen)
{ {
TRIGGER_LOGI("PostTrigger %d", type); PARAM_LOGI("PostTrigger %d", type);
TRIGGER_CHECK(content != NULL && contentLen > 0, return, "Invalid param"); PARAM_CHECK(content != NULL && contentLen > 0, return, "Invalid param");
if (type == EVENT_BOOT || g_triggerServiceStart == 0) { TriggerDataEvent *event = (TriggerDataEvent *)malloc(sizeof(TriggerDataEvent) + contentLen + 1);
CheckTriggers(type, content, contentLen); PARAM_CHECK(event != NULL, return, "Failed to alloc memory");
} else { event->type = type;
TriggerDataEvent *event = (TriggerDataEvent *)malloc(sizeof(TriggerDataEvent) + contentLen + 1); event->request.data = (char*)event + sizeof(uv_work_t);
TRIGGER_CHECK(event != NULL, return, "Failed to alloc memory"); event->contentSize = contentLen;
event->type = type; memcpy_s(event->content, contentLen, content, contentLen);
event->request.data = (char*)event + sizeof(uv_work_t); event->content[contentLen] = '\0';
event->contentSize = contentLen; SendTriggerEvent(event);
memcpy_s(event->content, contentLen, content, contentLen); PARAM_LOGI("PostTrigger %d success", type);
event->content[contentLen] = '\0';
SendTriggerEvent(event);
}
TRIGGER_LOGI("PostTrigger %d success", type);
} }
void StartTriggerService() void StartTriggerService()
{ {
TRIGGER_LOGI("StartTriggerService "); PARAM_LOGI("StartTriggerService ");
g_triggerServiceStart = 1; g_triggerServiceStart = 1;
} }
int ParseTriggerConfig(cJSON *fileRoot) int ParseTriggerConfig(cJSON *fileRoot)
{ {
TRIGGER_CHECK(fileRoot != NULL, return -1, "Invalid file"); PARAM_CHECK(fileRoot != NULL, return -1, "Invalid file");
int ret = InitTriggerWorkSpace(&g_triggerWorkSpace); int ret = InitTriggerWorkSpace(&g_triggerWorkSpace);
TRIGGER_CHECK(ret == 0, return -1, "Failed to init trigger"); PARAM_CHECK(ret == 0, return -1, "Failed to init trigger");
cJSON *triggers = cJSON_GetObjectItemCaseSensitive(fileRoot, TRIGGER_ARR_NAME_IN_JSON); cJSON *triggers = cJSON_GetObjectItemCaseSensitive(fileRoot, TRIGGER_ARR_NAME_IN_JSON);
TRIGGER_CHECK(cJSON_IsArray(triggers), return -1, "Trigger item must array"); PARAM_CHECK(cJSON_IsArray(triggers), return -1, "Trigger item must array");
int size = cJSON_GetArraySize(triggers); int size = cJSON_GetArraySize(triggers);
TRIGGER_CHECK(size > 0, return -1, "Trigger array size must positive"); PARAM_CHECK(size > 0, return -1, "Trigger array size must positive");
for (int i = 0; i < size; ++i) { for (int i = 0; i < size; ++i) {
cJSON *item = cJSON_GetArrayItem(triggers, i); cJSON *item = cJSON_GetArrayItem(triggers, i);
...@@ -211,12 +198,15 @@ int ParseTriggerConfig(cJSON *fileRoot) ...@@ -211,12 +198,15 @@ int ParseTriggerConfig(cJSON *fileRoot)
void DoTriggerExec(const char *content) void DoTriggerExec(const char *content)
{ {
TRIGGER_CHECK(content != NULL, return, "Invalid trigger content"); PARAM_CHECK(content != NULL, return, "Invalid trigger content");
u_int32_t triggerIndex = 0; u_int32_t triggerIndex = 0;
TriggerNode *trigger = GetTriggerByName(&g_triggerWorkSpace, content, &triggerIndex); TriggerNode *trigger = GetTriggerByName(&g_triggerWorkSpace, content, &triggerIndex);
if (trigger != NULL) { if (trigger != NULL && !TRIGGER_NODE_IN_QUEUE(trigger)) { // 不在队列中
ExecuteTrigger(&g_triggerWorkSpace, trigger, DoCmdExecute); PARAM_LOGI("DoTriggerExec trigger %s", trigger->name);
TRIGGER_NODE_SET_QUEUE_FLAG(trigger);
ExecuteQueuePush(&g_triggerWorkSpace, trigger, triggerIndex);
} }
ExecuteQueueWork(UINT32_MAX); // 需要立刻执行
} }
TriggerWorkSpace *GetTriggerWorkSpace() TriggerWorkSpace *GetTriggerWorkSpace()
......
# Copyright (c) 2020 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
ohos_executable("reboot") {
sources = [
"init_cmd_reboot.c",
]
include_dirs = [
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/services/include/param/",
"//third_party/bounds_checking_function/include",
]
deps = [
"//base/startup/init_lite/interfaces/innerkits/reboot:libreboot",
]
install_enable = true
part_name = "init"
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "init_reboot_api.h"
int main(int argc, char* argv[])
{
if (argc > 2) {
printf("usage: reboot shutdown\n reboot updater\n reboot updater[:options]\n reboot\n");
return 0;
}
if (argc == 2 && strcmp(argv[1], "shutdown") != 0 &&
strcmp(argv[1], "updater") != 0 &&
strncmp(argv[1], "updater:", strlen("updater:")) != 0 ) {
printf("usage: reboot shutdown\n reboot updater\n reboot updater[:options]\n reboot\n");
return 0;
}
int ret = 0;
if (argc == 2) {
ret = DoRebootApi(argv[1]);
} else {
ret = DoRebootApi("NoArgument");
}
if (ret != 0) {
printf("[reboot command] DoRebootApi return error\n");
} else {
printf("[reboot command] DoRebootApi return ok\n");
}
while (1) {
pause();
}
return 0;
}
...@@ -19,6 +19,8 @@ ...@@ -19,6 +19,8 @@
#include <sys/mount.h> #include <sys/mount.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/sysmacros.h> #include <sys/sysmacros.h>
#include <unistd.h>
#include "init_log.h"
#define DEFAULT_RW_MODE 0666 #define DEFAULT_RW_MODE 0666
#define DEFAULT_NO_AUTHORITY_MODE 0600 #define DEFAULT_NO_AUTHORITY_MODE 0600
...@@ -30,17 +32,17 @@ ...@@ -30,17 +32,17 @@
void MountBasicFs() void MountBasicFs()
{ {
if (mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755") != 0) { if (mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755") != 0) {
printf("Mount tmpfs failed. %s\n", strerror(errno)); INIT_LOGE("Mount tmpfs failed. %s\n", strerror(errno));
} }
if (mount("proc", "/proc", "proc", 0, "hidepid=2") != 0) { if (mount("proc", "/proc", "proc", 0, "hidepid=2") != 0) {
printf("Mount procfs failed. %s\n", strerror(errno)); INIT_LOGE("Mount procfs failed. %s\n", strerror(errno));
} }
if (mount("sysfs", "/sys", "sysfs", 0, NULL) != 0) { if (mount("sysfs", "/sys", "sysfs", 0, NULL) != 0) {
printf("Mount sysfs failed. %s\n", strerror(errno)); INIT_LOGE("Mount sysfs failed. %s\n", strerror(errno));
} }
#ifndef __LITEOS__ #ifndef __LITEOS__
if (mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL) != 0) { if (mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL) != 0) {
printf("Mount selinuxfs failed. %s\n", strerror(errno)); INIT_LOGE("Mount selinuxfs failed. %s\n", strerror(errno));
} }
#endif #endif
} }
...@@ -48,17 +50,17 @@ void MountBasicFs() ...@@ -48,17 +50,17 @@ void MountBasicFs()
void CreateDeviceNode() void CreateDeviceNode()
{ {
if (mknod("/dev/kmsg", S_IFCHR | DEFAULT_NO_AUTHORITY_MODE, makedev(1, DEVICE_ID_ELEVNTH)) != 0) { if (mknod("/dev/kmsg", S_IFCHR | DEFAULT_NO_AUTHORITY_MODE, makedev(1, DEVICE_ID_ELEVNTH)) != 0) {
printf("Create /dev/kmsg device node failed. %s\n", strerror(errno)); INIT_LOGE("Create /dev/kmsg device node failed. %s\n", strerror(errno));
} }
if (mknod("/dev/null", S_IFCHR | DEFAULT_RW_MODE, makedev(1, DEVICE_ID_THIRD)) != 0) { if (mknod("/dev/null", S_IFCHR | DEFAULT_RW_MODE, makedev(1, DEVICE_ID_THIRD)) != 0) {
printf("Create /dev/null device node failed. %s\n", strerror(errno)); INIT_LOGE("Create /dev/null device node failed. %s\n", strerror(errno));
} }
if (mknod("/dev/random", S_IFCHR | DEFAULT_RW_MODE, makedev(1, DEVICE_ID_EIGHTH)) != 0) { if (mknod("/dev/random", S_IFCHR | DEFAULT_RW_MODE, makedev(1, DEVICE_ID_EIGHTH)) != 0) {
printf("Create /dev/random device node failed. %s\n", strerror(errno)); INIT_LOGE("Create /dev/random device node failed. %s\n", strerror(errno));
} }
if (mknod("/dev/urandom", S_IFCHR | DEFAULT_RW_MODE, makedev(1, DEVICE_ID_NINTH)) != 0) { if (mknod("/dev/urandom", S_IFCHR | DEFAULT_RW_MODE, makedev(1, DEVICE_ID_NINTH)) != 0) {
printf("Create /dev/urandom device node failed. %s\n", strerror(errno)); INIT_LOGE("Create /dev/urandom device node failed. %s\n", strerror(errno));
} }
} }
...@@ -66,12 +68,12 @@ int MakeSocketDir(const char *path, mode_t mode) ...@@ -66,12 +68,12 @@ int MakeSocketDir(const char *path, mode_t mode)
{ {
int rc = mkdir("/dev/unix/", mode); int rc = mkdir("/dev/unix/", mode);
if (rc < 0 && errno != EEXIST) { if (rc < 0 && errno != EEXIST) {
printf("Create %s failed. %d\n", path, errno); INIT_LOGE("Create %s failed. %d\n", path, errno);
return -1; return -1;
} }
rc = mkdir("/dev/unix/socket/", mode); rc = mkdir("/dev/unix/socket/", mode);
if (rc < 0 && errno != EEXIST) { if (rc < 0 && errno != EEXIST) {
printf("Create %s failed. %d\n", path, errno); INIT_LOGE("Create %s failed. %d\n", path, errno);
return -1; return -1;
} }
return rc; return rc;
......
...@@ -26,12 +26,13 @@ ...@@ -26,12 +26,13 @@
#ifdef __LINUX__ #ifdef __LINUX__
#include "init_signal_handler.h" #include "init_signal_handler.h"
#endif #endif
#include "init_log.h"
void RebootSystem() void RebootSystem()
{ {
int ret = reboot(RB_AUTOBOOT); int ret = reboot(RB_AUTOBOOT);
if (ret != 0) { if (ret != 0) {
printf("[Init] reboot failed! syscall ret %d, err %d.\n", ret, errno); INIT_LOGE("reboot failed! syscall ret %d, err %d.\n", ret, errno);
} }
} }
...@@ -39,7 +40,7 @@ int KeepCapability() ...@@ -39,7 +40,7 @@ int KeepCapability()
{ {
#if ((defined __LINUX__) || (!defined OHOS_LITE)) #if ((defined __LINUX__) || (!defined OHOS_LITE))
if (prctl(PR_SET_SECUREBITS, SECBIT_NO_SETUID_FIXUP | SECBIT_NO_SETUID_FIXUP_LOCKED)) { if (prctl(PR_SET_SECUREBITS, SECBIT_NO_SETUID_FIXUP | SECBIT_NO_SETUID_FIXUP_LOCKED)) {
printf("[Init] prctl PR_SET_SECUREBITS failed: %d\n", errno); INIT_LOGE("prctl PR_SET_SECUREBITS failed: %d\n", errno);
return -1; return -1;
} }
#endif #endif
...@@ -50,7 +51,7 @@ int SetAmbientCapability(int cap) ...@@ -50,7 +51,7 @@ int SetAmbientCapability(int cap)
{ {
#if ((defined __LINUX__) || (!defined OHOS_LITE)) #if ((defined __LINUX__) || (!defined OHOS_LITE))
if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, cap, 0, 0)) { if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, cap, 0, 0)) {
printf("[Init] prctl PR_CAP_AMBIENT failed: %d\n", errno); INIT_LOGE("prctl PR_CAP_AMBIENT failed: %d\n", errno);
return -1; return -1;
} }
#endif #endif
...@@ -62,15 +63,15 @@ void ExecuteRcs() ...@@ -62,15 +63,15 @@ void ExecuteRcs()
#if (defined __LINUX__) && (defined NEED_EXEC_RCS_LINUX) #if (defined __LINUX__) && (defined NEED_EXEC_RCS_LINUX)
pid_t retPid = fork(); pid_t retPid = fork();
if (retPid < 0) { if (retPid < 0) {
printf("[Init] ExecuteRcs, fork failed! err %d.\n", errno); INIT_LOGE("ExecuteRcs, fork failed! err %d.\n", errno);
return; return;
} }
// child process // child process
if (retPid == 0) { if (retPid == 0) {
printf("[Init] ExecuteRcs, child process id %d.\n", getpid()); INIT_LOGI("ExecuteRcs, child process id %d.\n", getpid());
if (execle("/bin/sh", "sh", "/etc/init.d/rcS", NULL, NULL) != 0) { if (execle("/bin/sh", "sh", "/etc/init.d/rcS", NULL, NULL) != 0) {
printf("[Init] ExecuteRcs, execle failed! err %d.\n", errno); INIT_LOGE("ExecuteRcs, execle failed! err %d.\n", errno);
} }
_exit(0x7f); // 0x7f: user specified _exit(0x7f); // 0x7f: user specified
} }
...@@ -78,14 +79,14 @@ void ExecuteRcs() ...@@ -78,14 +79,14 @@ void ExecuteRcs()
// init process // init process
sem_t sem; sem_t sem;
if (sem_init(&sem, 0, 0) != 0) { if (sem_init(&sem, 0, 0) != 0) {
printf("[Init] ExecuteRcs, sem_init failed, err %d.\n", errno); INIT_LOGE("ExecuteRcs, sem_init failed, err %d.\n", errno);
return; return;
} }
SignalRegWaitSem(retPid, &sem); SignalRegWaitSem(retPid, &sem);
// wait until rcs process exited // wait until rcs process exited
if (sem_wait(&sem) != 0) { if (sem_wait(&sem) != 0) {
printf("[Init] ExecuteRcs, sem_wait failed, err %d.\n", errno); INIT_LOGE("ExecuteRcs, sem_wait failed, err %d.\n", errno);
} }
#endif #endif
} }
......
...@@ -38,7 +38,7 @@ struct CapStrCapNum { ...@@ -38,7 +38,7 @@ struct CapStrCapNum {
int CapNum; int CapNum;
}; };
static struct CapStrCapNum g_capStrCapNum[] = { static const struct CapStrCapNum g_capStrCapNum[] = {
{"CHOWN", CAP_CHOWN}, {"CHOWN", CAP_CHOWN},
{"DAC_OVERRIDE", CAP_DAC_OVERRIDE}, {"DAC_OVERRIDE", CAP_DAC_OVERRIDE},
{"DAC_READ_SEARCH", CAP_DAC_READ_SEARCH}, {"DAC_READ_SEARCH", CAP_DAC_READ_SEARCH},
...@@ -85,7 +85,7 @@ static int GetServiceStringCaps(const cJSON* filedJ, Service* curServ) ...@@ -85,7 +85,7 @@ static int GetServiceStringCaps(const cJSON* filedJ, Service* curServ)
for (; i < curServ->servPerm.capsCnt; ++i) { for (; i < curServ->servPerm.capsCnt; ++i) {
if (cJSON_GetArrayItem(filedJ, i) == NULL || !cJSON_GetStringValue(cJSON_GetArrayItem(filedJ, i)) if (cJSON_GetArrayItem(filedJ, i) == NULL || !cJSON_GetStringValue(cJSON_GetArrayItem(filedJ, i))
|| strlen(cJSON_GetStringValue(cJSON_GetArrayItem(filedJ, i))) <= 0) { // check all errors || strlen(cJSON_GetStringValue(cJSON_GetArrayItem(filedJ, i))) <= 0) { // check all errors
INIT_LOGE("[Init] GetServiceStringCaps, parse item[%d] as string, error.\n", i); INIT_LOGE("GetServiceStringCaps, parse item[%d] as string, error.\n", i);
break; break;
} }
char* fieldStr = cJSON_GetStringValue(cJSON_GetArrayItem(filedJ, i)); char* fieldStr = cJSON_GetStringValue(cJSON_GetArrayItem(filedJ, i));
...@@ -99,12 +99,12 @@ static int GetServiceStringCaps(const cJSON* filedJ, Service* curServ) ...@@ -99,12 +99,12 @@ static int GetServiceStringCaps(const cJSON* filedJ, Service* curServ)
if (j < mapSize) { if (j < mapSize) {
curServ->servPerm.caps[i] = g_capStrCapNum[j].CapNum; curServ->servPerm.caps[i] = g_capStrCapNum[j].CapNum;
} else { } else {
INIT_LOGE("[Init] GetServiceStringCaps, fieldStr = %s, error.\n", fieldStr); INIT_LOGE("GetServiceStringCaps, fieldStr = %s, error.\n", fieldStr);
break; break;
} }
if (curServ->servPerm.caps[i] > CAP_LAST_CAP && curServ->servPerm.caps[i] != FULL_CAP) { if (curServ->servPerm.caps[i] > CAP_LAST_CAP && curServ->servPerm.caps[i] != FULL_CAP) {
// resources will be released by function: ReleaseServiceMem // resources will be released by function: ReleaseServiceMem
INIT_LOGE("[Init] GetServiceStringCaps, cap = %d, error.\n", curServ->servPerm.caps[i]); INIT_LOGE("GetServiceStringCaps, cap = %d, error.\n", curServ->servPerm.caps[i]);
return SERVICE_FAILURE; return SERVICE_FAILURE;
} }
} }
...@@ -118,11 +118,11 @@ int GetServiceCaps(const cJSON* curArrItem, Service* curServ) ...@@ -118,11 +118,11 @@ int GetServiceCaps(const cJSON* curArrItem, Service* curServ)
curServ->servPerm.caps = NULL; curServ->servPerm.caps = NULL;
cJSON* filedJ = cJSON_GetObjectItem(curArrItem, "caps"); cJSON* filedJ = cJSON_GetObjectItem(curArrItem, "caps");
if (filedJ == NULL) { if (filedJ == NULL) {
INIT_LOGE("[Init] GetServiceCaps, caps is not found. but maybe ok.\n"); INIT_LOGE("GetServiceCaps, caps is not found. but maybe ok.\n");
return SERVICE_SUCCESS; return SERVICE_SUCCESS;
} }
if (!cJSON_IsArray(filedJ)) { if (!cJSON_IsArray(filedJ)) {
INIT_LOGE("[Init] GetServiceCaps, caps is not a list, error.\n"); INIT_LOGE("GetServiceCaps, caps is not a list, error.\n");
return SERVICE_FAILURE; return SERVICE_FAILURE;
} }
// caps array does not exist, means do not need any capability // caps array does not exist, means do not need any capability
...@@ -131,13 +131,13 @@ int GetServiceCaps(const cJSON* curArrItem, Service* curServ) ...@@ -131,13 +131,13 @@ int GetServiceCaps(const cJSON* curArrItem, Service* curServ)
return SERVICE_SUCCESS; return SERVICE_SUCCESS;
} }
if (capsCnt > MAX_CAPS_CNT_FOR_ONE_SERVICE) { if (capsCnt > MAX_CAPS_CNT_FOR_ONE_SERVICE) {
INIT_LOGE("[Init] GetServiceCaps, too many caps[cnt %d] for one service, should not exceed %d.\n", INIT_LOGE("GetServiceCaps, too many caps[cnt %d] for one service, should not exceed %d.\n",
capsCnt, MAX_CAPS_CNT_FOR_ONE_SERVICE); capsCnt, MAX_CAPS_CNT_FOR_ONE_SERVICE);
return SERVICE_FAILURE; return SERVICE_FAILURE;
} }
curServ->servPerm.caps = (unsigned int*)malloc(sizeof(unsigned int) * capsCnt); curServ->servPerm.caps = (unsigned int*)malloc(sizeof(unsigned int) * capsCnt);
if (curServ->servPerm.caps == NULL) { if (curServ->servPerm.caps == NULL) {
INIT_LOGE("[Init] GetServiceCaps, malloc error.\n"); INIT_LOGE("GetServiceCaps, malloc error.\n");
return SERVICE_FAILURE; return SERVICE_FAILURE;
} }
curServ->servPerm.capsCnt = capsCnt; curServ->servPerm.capsCnt = capsCnt;
...@@ -146,13 +146,13 @@ int GetServiceCaps(const cJSON* curArrItem, Service* curServ) ...@@ -146,13 +146,13 @@ int GetServiceCaps(const cJSON* curArrItem, Service* curServ)
cJSON* capJ = cJSON_GetArrayItem(filedJ, i); cJSON* capJ = cJSON_GetArrayItem(filedJ, i);
if (!cJSON_IsNumber(capJ) || cJSON_GetNumberValue(capJ) < 0) { if (!cJSON_IsNumber(capJ) || cJSON_GetNumberValue(capJ) < 0) {
// resources will be released by function: ReleaseServiceMem // resources will be released by function: ReleaseServiceMem
INIT_LOGE("[Init] GetServiceCaps, capJ is not a number or capJ < 0, error.\n"); INIT_LOGE("GetServiceCaps, capJ is not a number or capJ < 0, error.\n");
break; break;
} }
curServ->servPerm.caps[i] = (unsigned int)cJSON_GetNumberValue(capJ); curServ->servPerm.caps[i] = (unsigned int)cJSON_GetNumberValue(capJ);
if (curServ->servPerm.caps[i] > CAP_LAST_CAP && curServ->servPerm.caps[i] != FULL_CAP) { // CAP_LAST_CAP = 37 if (curServ->servPerm.caps[i] > CAP_LAST_CAP && curServ->servPerm.caps[i] != FULL_CAP) { // CAP_LAST_CAP = 37
// resources will be released by function: ReleaseServiceMem // resources will be released by function: ReleaseServiceMem
INIT_LOGE("[Init] GetServiceCaps, caps = %d, error.\n", curServ->servPerm.caps[i]); INIT_LOGE("GetServiceCaps, caps = %d, error.\n", curServ->servPerm.caps[i]);
return SERVICE_FAILURE; return SERVICE_FAILURE;
} }
} }
......
此差异已折叠。
...@@ -15,7 +15,9 @@ ...@@ -15,7 +15,9 @@
#include "init_import.h" #include "init_import.h"
#include <stdio.h> #include <stdio.h>
#include <unistd.h>
#include "cJSON.h" #include "cJSON.h"
#include "init_log.h"
#include "init_read_cfg.h" #include "init_read_cfg.h"
#define IMPORT_ARR_NAME_IN_JSON "import" #define IMPORT_ARR_NAME_IN_JSON "import"
...@@ -25,7 +27,7 @@ void ParseAllImports(cJSON *root) ...@@ -25,7 +27,7 @@ void ParseAllImports(cJSON *root)
cJSON *importAttr = cJSON_GetObjectItemCaseSensitive(root, IMPORT_ARR_NAME_IN_JSON); cJSON *importAttr = cJSON_GetObjectItemCaseSensitive(root, IMPORT_ARR_NAME_IN_JSON);
if (!cJSON_IsArray(importAttr)) { if (!cJSON_IsArray(importAttr)) {
printf("[Init] ParseAllImports, import item is not array!\n"); INIT_LOGE("ParseAllImports, import item is not array!\n");
return; return;
} }
int importAttrSize = cJSON_GetArraySize(importAttr); int importAttrSize = cJSON_GetArraySize(importAttr);
...@@ -33,17 +35,17 @@ void ParseAllImports(cJSON *root) ...@@ -33,17 +35,17 @@ void ParseAllImports(cJSON *root)
for (int i = 0; i < importAttrSize; i++) { for (int i = 0; i < importAttrSize; i++) {
cJSON *importItem = cJSON_GetArrayItem(importAttr, i); cJSON *importItem = cJSON_GetArrayItem(importAttr, i);
if (!cJSON_IsString(importItem)) { if (!cJSON_IsString(importItem)) {
printf("[Init] Invalid type of import item. should be string\n"); INIT_LOGE("Invalid type of import item. should be string\n");
return; return;
} }
char *importFile = cJSON_GetStringValue(importItem); char *importFile = cJSON_GetStringValue(importItem);
if (importFile == NULL) { if (importFile == NULL) {
printf("[Init] cannot get import config file\n"); INIT_LOGE("cannot get import config file\n");
return; return;
} }
printf("[Init] [Debug], ready to import %s...\n", importFile); INIT_LOGD("ready to import %s...\n", importFile);
ParseInitCfg(importFile); ParseInitCfg(importFile);
} }
printf("[Init] [Debug], parse import file done\n"); INIT_LOGD("parse import file done\n");
return; return;
} }
\ No newline at end of file
此差异已折叠。
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
#include "init_utils.h" #include "init_utils.h"
#ifndef OHOS_LITE #ifndef OHOS_LITE
#include "trigger.h" #include "init_param.h"
#endif #endif
#include "securec.h" #include "securec.h"
#ifndef __LINUX__ #ifndef __LINUX__
...@@ -61,21 +61,17 @@ static void ParseInitCfgContents(cJSON *root) ...@@ -61,21 +61,17 @@ static void ParseInitCfgContents(cJSON *root)
void ParseInitCfg(const char *configFile) void ParseInitCfg(const char *configFile)
{ {
if (configFile == NULL || *configFile == '\0') { if (configFile == NULL || *configFile == '\0') {
printf("[Init] Invalid config file\n"); INIT_LOGE("Invalid config file\n");
return; return;
} }
char *fileBuf = ReadFileToBuf(configFile); char *fileBuf = ReadFileToBuf(configFile);
//printf("[Init] start dump config file: \n");
//printf("%s", fileBuf);
//printf("[Init] end dump config file: \n");
cJSON* fileRoot = cJSON_Parse(fileBuf); cJSON* fileRoot = cJSON_Parse(fileBuf);
free(fileBuf); free(fileBuf);
fileBuf = NULL; fileBuf = NULL;
if (fileRoot == NULL) { if (fileRoot == NULL) {
printf("[Init] InitReadCfg, parse failed! please check file %s format.\n", configFile); INIT_LOGE("InitReadCfg, parse failed! please check file %s format.\n", configFile);
return; return;
} }
ParseInitCfgContents(fileRoot); ParseInitCfgContents(fileRoot);
...@@ -88,14 +84,14 @@ static void ReadCfgs(const char *dirPath) ...@@ -88,14 +84,14 @@ static void ReadCfgs(const char *dirPath)
{ {
DIR *pDir = opendir(dirPath); DIR *pDir = opendir(dirPath);
if (pDir == NULL) { if (pDir == NULL) {
INIT_LOGE("[Init], ParseCfgs open cfg dir :%s failed.%d\n", dirPath, errno); INIT_LOGE("ParseCfgs open cfg dir :%s failed.%d\n", dirPath, errno);
return; return;
} }
struct dirent *dp; struct dirent *dp;
while ((dp = readdir(pDir)) != NULL) { while ((dp = readdir(pDir)) != NULL) {
char fileName[FILE_NAME_MAX_SIZE]; char fileName[FILE_NAME_MAX_SIZE];
if (snprintf_s(fileName, FILE_NAME_MAX_SIZE, FILE_NAME_MAX_SIZE - 1, "%s/%s", dirPath, dp->d_name) == -1) { if (snprintf_s(fileName, FILE_NAME_MAX_SIZE, FILE_NAME_MAX_SIZE - 1, "%s/%s", dirPath, dp->d_name) == -1) {
INIT_LOGE("[Init], ParseCfgs snprintf_s failed.\n"); INIT_LOGE("ParseCfgs snprintf_s failed.\n");
closedir(pDir); closedir(pDir);
return; return;
} }
...@@ -104,7 +100,7 @@ static void ReadCfgs(const char *dirPath) ...@@ -104,7 +100,7 @@ static void ReadCfgs(const char *dirPath)
if (strstr(dp->d_name, ".cfg") == NULL) { if (strstr(dp->d_name, ".cfg") == NULL) {
continue; continue;
} }
INIT_LOGE("[Init], fileName :%s.\n", fileName); INIT_LOGE("fileName :%s.\n", fileName);
ParseInitCfg(fileName); ParseInitCfg(fileName);
} }
} }
...@@ -120,9 +116,15 @@ static void ParseOtherCfgs() ...@@ -120,9 +116,15 @@ static void ParseOtherCfgs()
void InitReadCfg() void InitReadCfg()
{ {
#ifndef OHOS_LITE
InitParamService();
LoadDefaultParams("/system/etc/prop.default");
LoadDefaultParams("/system/build.prop");
LoadDefaultParams("/system/buildz.prop");
#endif
ParseInitCfg(INIT_CONFIGURATION_FILE); ParseInitCfg(INIT_CONFIGURATION_FILE);
ParseOtherCfgs(); ParseOtherCfgs();
printf("[init], Parse init config file done.\n"); INIT_LOGI("Parse init config file done.\n");
DumpAllServices(); DumpAllServices();
// DumpAllJobs(); // DumpAllJobs();
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
...@@ -69,7 +69,7 @@ struct CmdArgs* GetCmd(const char *cmdContent, const char *delim) ...@@ -69,7 +69,7 @@ struct CmdArgs* GetCmd(const char *cmdContent, const char *delim)
FreeCmd(&ctx); FreeCmd(&ctx);
return NULL); return NULL);
if (ctx->argc > MAX_CMD_NAME_LEN - 1) { if (ctx->argc > MAX_CMD_NAME_LEN - 1) {
INIT_LOGE("[Init] GetCmd failed, max cmd number is 10.\n"); INIT_LOGE("GetCmd failed, max cmd number is 10.\n");
FreeCmd(&ctx); FreeCmd(&ctx);
return NULL; return NULL;
} }
...@@ -92,7 +92,7 @@ void FreeCmd(struct CmdArgs **cmd) ...@@ -92,7 +92,7 @@ void FreeCmd(struct CmdArgs **cmd)
return; return;
} }
void Logger(StatupLogLevel level, const char *format, ...) void Logger(InitLogLevel level, const char *format, ...)
{ {
FILE* pFile = fopen(LOG_FILE_NAME, "a"); FILE* pFile = fopen(LOG_FILE_NAME, "a");
static char *logLeveInfo[] = { "VERBOSE", "INFO", "WARN", "ERROR", "FATAL" }; static char *logLeveInfo[] = { "VERBOSE", "INFO", "WARN", "ERROR", "FATAL" };
......
文件模式从 100755 更改为 100644
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册