1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "service_watcher.h"
16
17 #include <errno.h>
18 #include <stdio.h>
19 #include <string.h>
20
21 #include "beget_ext.h"
22 #include "init_utils.h"
23 #include "parameter.h"
24 #include "securec.h"
25 #include "service_control.h"
26 #include "sysparam_errno.h"
27
ServiceStateChange(const char * key,const char * value,void * context)28 static void ServiceStateChange(const char *key, const char *value, void *context)
29 {
30 ServiceStatusChangePtr callback = (ServiceStatusChangePtr)context;
31 uint32_t v = 0;
32 int ret = StringToUint(value, &v);
33 BEGET_ERROR_CHECK(ret == 0, return, "Failed to get value from %s", value);
34 ServiceStatus status = (ServiceStatus)v;
35 if (strlen(key) > strlen(STARTUP_SERVICE_CTL)) {
36 callback(key + strlen(STARTUP_SERVICE_CTL) + 1, status);
37 } else {
38 BEGET_LOGE("Invalid service name %s %s", key, value);
39 }
40 }
41
ServiceWatchForStatus(const char * serviceName,ServiceStatusChangePtr changeCallback)42 int ServiceWatchForStatus(const char *serviceName, ServiceStatusChangePtr changeCallback)
43 {
44 if (serviceName == NULL) {
45 BEGET_LOGE("Service wait failed, service is null.");
46 return -1;
47 }
48 char paramName[PARAM_NAME_LEN_MAX] = {0};
49 if (snprintf_s(paramName, PARAM_NAME_LEN_MAX, PARAM_NAME_LEN_MAX - 1,
50 "%s.%s", STARTUP_SERVICE_CTL, serviceName) == -1) {
51 BEGET_LOGE("Failed snprintf_s err=%d", errno);
52 return -1;
53 }
54 if (SystemWatchParameter(paramName, ServiceStateChange, (void *)changeCallback) != 0) {
55 BEGET_LOGE("Wait param for %s failed.", paramName);
56 return -1;
57 }
58 return 0;
59 }
60
WatchParameter(const char * keyprefix,ParameterChgPtr callback,void * context)61 int WatchParameter(const char *keyprefix, ParameterChgPtr callback, void *context)
62 {
63 if (keyprefix == NULL) {
64 return EC_INVALID;
65 }
66 #ifdef NO_PARAM_WATCHER
67 printf("ParameterWatcher is disabled.");
68 return EC_INVALID;
69 #else
70 return SystemWatchParameter(keyprefix, callback, context);
71 #endif
72 }