watcher_manager.cpp 17.7 KB
Newer Older
S
sun_fan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * 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 "watcher_manager.h"
X
add ut  
xionglei6 已提交
16
#include <fcntl.h>
S
sun_fan 已提交
17 18 19 20 21 22
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <thread>

M
Mupceet 已提交
23 24
#include "param_message.h"
#include "init_param.h"
S
sun_fan 已提交
25
#include "system_ability_definition.h"
C
cheng_jinsong 已提交
26
#include "string_ex.h"
S
sun_fan 已提交
27 28 29 30 31 32 33
#include "watcher_utils.h"

namespace OHOS {
namespace init_param {
REGISTER_SYSTEM_ABILITY_BY_ID(WatcherManager, PARAM_WATCHER_DISTRIBUTED_SERVICE_ID, true)

const static int32_t INVALID_SOCKET = -1;
X
add ut  
xionglei6 已提交
34 35 36 37 38 39 40
WatcherManager::~WatcherManager()
{
    watchers_.clear();
    watcherGroups_.clear();
    groupMap_.clear();
}

S
sun_fan 已提交
41 42
uint32_t WatcherManager::AddWatcher(const std::string &keyPrefix, const sptr<IWatcher> &watcher)
{
X
add ut  
xionglei6 已提交
43 44 45 46 47 48 49
    WATCHER_CHECK(watcher != nullptr && deathRecipient_ != nullptr,
        return 0, "Invalid remove watcher for %s", keyPrefix.c_str());
    sptr<IRemoteObject> object = watcher->AsObject();
    if ((object != nullptr) && (object->IsProxyObject())) {
        WATCHER_CHECK(object->AddDeathRecipient(deathRecipient_),
            return 0, "Failed to add death recipient %s", keyPrefix.c_str());
    }
50

X
add ut  
xionglei6 已提交
51 52 53 54 55
    // check watcher id
    uint32_t watcherId = 0;
    int ret = GetWatcherId(watcherId);
    WATCHER_CHECK(ret == 0, return 0, "Failed to get watcher id for %s", keyPrefix.c_str());

X
xionglei6 已提交
56
    WATCHER_LOGV("AddWatcher prefix %s watcherId %u", keyPrefix.c_str(), watcherId);
X
add ut  
xionglei6 已提交
57
    bool newGroup = false;
S
sun_fan 已提交
58 59
    WatcherGroupPtr group = GetWatcherGroup(keyPrefix);
    if (group == nullptr) {
X
add ut  
xionglei6 已提交
60 61 62 63 64 65 66
        newGroup = true;
        uint32_t groupId = 0;
        ret = GetGroupId(groupId);
        WATCHER_CHECK(ret == 0, return 0, "Failed to get group id for %s", keyPrefix.c_str());
        group = std::make_shared<WatcherGroup>(groupId, keyPrefix);
        WATCHER_CHECK(group != nullptr, return 0, "Failed to create group for %s", keyPrefix.c_str());
    } else {
C
cheng_jinsong 已提交
67
        newGroup = group->Empty();
S
sun_fan 已提交
68
    }
C
cheng_jinsong 已提交
69 70 71
    ParamWatcherPtr paramWatcher = std::make_shared<ParamWatcher>(watcherId, watcher, group);
    WATCHER_CHECK(paramWatcher != nullptr, return 0, "Failed to create watcher for %s", keyPrefix.c_str());
    AddParamWatcher(keyPrefix, group, paramWatcher);
X
add ut  
xionglei6 已提交
72
    if (newGroup) {
S
sun_fan 已提交
73 74 75
        StartLoop();
        SendMessage(group, MSG_ADD_WATCHER);
    }
C
cheng_jinsong 已提交
76 77
    SendLocalChange(keyPrefix, paramWatcher);
    WATCHER_LOGI("AddWatcher %s watcherId: %u groupId %u success", keyPrefix.c_str(), watcherId, group->GetGroupId());
X
add ut  
xionglei6 已提交
78
    return watcherId;
S
sun_fan 已提交
79 80 81 82 83
}

int32_t WatcherManager::DelWatcher(const std::string &keyPrefix, uint32_t watcherId)
{
    auto group = GetWatcherGroup(keyPrefix);
X
add ut  
xionglei6 已提交
84 85
    WATCHER_CHECK(group != nullptr, return 0, "Can not find group %s", keyPrefix.c_str());
    auto paramWatcher = GetWatcher(watcherId);
C
cheng_jinsong 已提交
86
    WATCHER_CHECK(paramWatcher != nullptr, return 0, "Can not find watcher %s %d", keyPrefix.c_str(), watcherId);
X
xionglei6 已提交
87
    WATCHER_LOGV("DelWatcher prefix %s watcherId %u", keyPrefix.c_str(), watcherId);
X
add ut  
xionglei6 已提交
88 89
    return DelWatcher(group, paramWatcher);
}
S
sun_fan 已提交
90

X
add ut  
xionglei6 已提交
91 92 93 94 95 96 97 98 99
int32_t WatcherManager::DelWatcher(WatcherGroupPtr group, ParamWatcherPtr watcher)
{
    WATCHER_CHECK(watcher != nullptr && group != nullptr, return 0, "Invalid watcher");
    sptr<IRemoteObject> object = watcher->GetRemoteWatcher()->AsObject();
    if (object != nullptr) {
        object->RemoveDeathRecipient(deathRecipient_);
    }
    WATCHER_LOGI("DelWatcher watcherId %u prefix %s", watcher->GetWatcherId(), group->GetKeyPrefix().c_str());
    DelParamWatcher(watcher);
C
cheng_jinsong 已提交
100
    if (group->Empty()) {
S
sun_fan 已提交
101 102 103 104 105 106 107 108 109 110
        SendMessage(group, MSG_DEL_WATCHER);
        DelWatcherGroup(group);
    }
    return 0;
}

int WatcherManager::SendMessage(WatcherGroupPtr group, int type)
{
    ParamMessage *request = nullptr;
    request = (ParamMessage *)CreateParamMessage(type, group->GetKeyPrefix().c_str(), sizeof(ParamMessage));
X
add ut  
xionglei6 已提交
111
    WATCHER_CHECK(request != NULL, return PARAM_CODE_ERROR, "Failed to malloc for watch");
S
sun_fan 已提交
112 113
    request->id.watcherId = group->GetGroupId();
    request->msgSize = sizeof(ParamMessage);
114

C
cheng_jinsong 已提交
115
    WATCHER_LOGV("SendMessage %s groupId %d type %d", group->GetKeyPrefix().c_str(), group->GetGroupId(), type);
S
sun_fan 已提交
116
    int ret = PARAM_CODE_ERROR;
117 118 119
    int fd = GetServerFd(false);
    if (fd != INVALID_SOCKET) {
        ssize_t sendLen = send(serverFd_, (char *)request, request->msgSize, 0);
S
sun_fan 已提交
120
        ret = (sendLen > 0) ? 0 : PARAM_CODE_ERROR;
121
    }
S
sun_fan 已提交
122
    free(request);
X
add ut  
xionglei6 已提交
123
    WATCHER_CHECK(ret == 0, return ret, "SendMessage key: %s %d fail", group->GetKeyPrefix().c_str(), type);
S
sun_fan 已提交
124 125 126
    return 0;
}

4
411148299@qq.com 已提交
127
void WatcherManager::ProcessWatcherMessage(const std::vector<char> &buffer, uint32_t dataSize)
S
sun_fan 已提交
128
{
4
411148299@qq.com 已提交
129
    ParamMessage *msg = (ParamMessage *)buffer.data();
X
add ut  
xionglei6 已提交
130
    WATCHER_CHECK(msg != NULL, return, "Invalid msg");
X
xionglei6 已提交
131
    WATCHER_LOGV("ProcessWatcherMessage %d", msg->type);
S
sun_fan 已提交
132 133 134 135
    uint32_t offset = 0;
    if (msg->type != MSG_NOTIFY_PARAM) {
        return;
    }
X
add ut  
xionglei6 已提交
136
    WATCHER_CHECK(msg->msgSize <= dataSize, return, "Invalid msg size %d", msg->msgSize);
S
sun_fan 已提交
137
    ParamMsgContent *valueContent = GetNextContent((const ParamMessage *)msg, &offset);
X
add ut  
xionglei6 已提交
138
    WATCHER_CHECK(valueContent != NULL, return, "Invalid msg ");
X
xionglei6 已提交
139
    WATCHER_LOGV("ProcessWatcherMessage name %s watcherId %u ", msg->key, msg->id.watcherId);
S
sun_fan 已提交
140 141
    WatcherGroupPtr group = GetWatcherGroup(msg->id.watcherId);
    if (group != nullptr) {
X
add ut  
xionglei6 已提交
142
        std::lock_guard<std::mutex> lock(watcherMutex_);
S
sun_fan 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
        group->ProcessParameterChange(msg->key, valueContent->content);
    }
}

WatcherManager::WatcherGroupPtr WatcherManager::GetWatcherGroup(uint32_t groupId)
{
    std::lock_guard<std::mutex> lock(watcherMutex_);
    if (watcherGroups_.find(groupId) != watcherGroups_.end()) {
        return watcherGroups_[groupId];
    }
    return nullptr;
}

WatcherManager::WatcherGroupPtr WatcherManager::GetWatcherGroup(const std::string &keyPrefix)
{
158
    std::lock_guard<std::mutex> lock(watcherMutex_);
S
sun_fan 已提交
159 160 161
    if (groupMap_.find(keyPrefix) == groupMap_.end()) {
        return nullptr;
    }
162 163 164 165 166
    uint32_t groupId = groupMap_[keyPrefix];
    if (watcherGroups_.find(groupId) != watcherGroups_.end()) {
        return watcherGroups_[groupId];
    }
    return nullptr;
S
sun_fan 已提交
167 168
}

X
add ut  
xionglei6 已提交
169
void WatcherManager::AddParamWatcher(const std::string &keyPrefix, WatcherGroupPtr group, ParamWatcherPtr watcher)
S
sun_fan 已提交
170
{
X
xionglei6 已提交
171
    WATCHER_LOGV("AddParamWatcher prefix %s watcherId %u", keyPrefix.c_str(), watcher->GetWatcherId());
S
sun_fan 已提交
172 173
    uint32_t groupId = group->GetGroupId();
    std::lock_guard<std::mutex> lock(watcherMutex_);
174
    groupMap_[keyPrefix] = groupId;
X
add ut  
xionglei6 已提交
175
    watchers_[watcher->GetWatcherId()] = watcher;
176
    OH_ListAddTail(group->GetWatchers(), watcher->GetGroupNode());
X
add ut  
xionglei6 已提交
177

S
sun_fan 已提交
178 179 180 181 182 183
    if (watcherGroups_.find(groupId) != watcherGroups_.end()) {
        return;
    }
    watcherGroups_[groupId] = group;
}

X
add ut  
xionglei6 已提交
184
void WatcherManager::DelParamWatcher(ParamWatcherPtr watcher)
S
sun_fan 已提交
185 186
{
    std::lock_guard<std::mutex> lock(watcherMutex_);
187 188
    OH_ListRemove(watcher->GetGroupNode());
    OH_ListInit(watcher->GetGroupNode());
X
add ut  
xionglei6 已提交
189
    watchers_.erase(watcher->GetWatcherId());
X
xionglei6 已提交
190
    WATCHER_LOGV("DelParamWatcher watcherId %u", watcher->GetWatcherId());
S
sun_fan 已提交
191 192
}

X
add ut  
xionglei6 已提交
193
void WatcherManager::DelWatcherGroup(WatcherGroupPtr group)
S
sun_fan 已提交
194
{
X
add ut  
xionglei6 已提交
195 196 197
    std::lock_guard<std::mutex> lock(watcherMutex_);
    groupMap_.erase(group->GetKeyPrefix());
    watcherGroups_.erase(group->GetGroupId());
S
sun_fan 已提交
198 199 200 201 202
}

void WatcherManager::WatcherGroup::ProcessParameterChange(const std::string &name, const std::string &value)
{
    // walk watcher
X
add ut  
xionglei6 已提交
203 204
    ListNode *node = nullptr;
    ForEachListEntry(&watchers_, node) {
C
codex  
chengjinsong 已提交
205 206 207 208
        if (node != nullptr) {
            ParamWatcher *watcher = (ParamWatcher *)node;
            watcher->ProcessParameterChange(name, value);
        }
S
sun_fan 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    }
}

static int FilterParam(const char *name, const std::string &keyPrefix)
{
    if (keyPrefix.rfind("*") == keyPrefix.length() - 1) {
        return strncmp(name, keyPrefix.c_str(), keyPrefix.length() - 1) == 0;
    }
    return strcmp(name, keyPrefix.c_str()) == 0;
}

void WatcherManager::SendLocalChange(const std::string &keyPrefix, ParamWatcherPtr watcher)
{
    struct Context {
        char *buffer;
        ParamWatcherPtr watcher;
        std::string keyPrefix;
    };
X
xionglei6 已提交
227
    WATCHER_LOGV("SendLocalChange key %s  ", keyPrefix.c_str());
S
sun_fan 已提交
228 229 230
    std::vector<char> buffer(PARAM_NAME_LEN_MAX + PARAM_CONST_VALUE_LEN_MAX);
    struct Context context = {buffer.data(), watcher, keyPrefix};
    // walk watcher
X
xionglei6 已提交
231
    SystemTraversalParameter("", [](ParamHandle handle, void *cookie) {
S
sun_fan 已提交
232 233 234 235 236 237 238
            struct Context *context = (struct Context *)(cookie);
            SystemGetParameterName(handle, context->buffer, PARAM_NAME_LEN_MAX);
            if (!FilterParam(context->buffer, context->keyPrefix)) {
                return;
            }
            uint32_t size = PARAM_CONST_VALUE_LEN_MAX;
            SystemGetParameterValue(handle, context->buffer + PARAM_NAME_LEN_MAX, &size);
X
xionglei6 已提交
239
            WATCHER_LOGV("SendLocalChange key %s value: %s ", context->buffer, context->buffer + PARAM_NAME_LEN_MAX);
S
sun_fan 已提交
240
            context->watcher->ProcessParameterChange(context->buffer, context->buffer + PARAM_NAME_LEN_MAX);
C
codex  
chengjinsong 已提交
241
        }, reinterpret_cast<void *>(&context));
S
sun_fan 已提交
242 243 244 245
}

void WatcherManager::RunLoop()
{
X
xionglei6@huawei.com 已提交
246
    const int32_t RECV_BUFFER_MAX = 5 * 1024;
4
411148299@qq.com 已提交
247
    std::vector<char> buffer(RECV_BUFFER_MAX, 0);
X
add ut  
xionglei6 已提交
248
    bool retry = false;
X
xionglei6 已提交
249
    ssize_t recvLen = 0;
250
    while (!stop_) {
X
add ut  
xionglei6 已提交
251
        int fd = GetServerFd(retry);
X
xionglei6 已提交
252
        if (fd >= 0) {
X
xionglei6 已提交
253
            recvLen = recv(fd, buffer.data(), RECV_BUFFER_MAX, 0);
X
xionglei6 已提交
254
        }
X
add ut  
xionglei6 已提交
255 256 257
        if (stop_) {
            break;
        }
S
sun_fan 已提交
258
        if (recvLen <= 0) {
X
add ut  
xionglei6 已提交
259
            if (errno == EAGAIN) { // timeout
S
sun_fan 已提交
260 261
                continue;
            }
S
sun_fan 已提交
262
            PARAM_LOGE("Failed to recv msg from server errno %d", errno);
X
add ut  
xionglei6 已提交
263 264
            retry = true;  // re connect
        } else if (recvLen >= (ssize_t)sizeof(ParamMessage)) {
S
sun_fan 已提交
265 266 267
            ProcessWatcherMessage(buffer, recvLen);
        }
    }
X
add ut  
xionglei6 已提交
268 269 270 271
    if (serverFd_ > 0) {
        close(serverFd_);
        serverFd_ = INVALID_SOCKET;
    }
X
xionglei6 已提交
272
    WATCHER_LOGV("Exit runLoop");
S
sun_fan 已提交
273 274 275 276 277 278 279 280 281 282 283 284
}

void WatcherManager::StartLoop()
{
    if (pRecvThread_ == nullptr) {
        pRecvThread_ = new (std::nothrow)std::thread(&WatcherManager::RunLoop, this);
        WATCHER_CHECK(pRecvThread_ != nullptr, return, "Failed to create thread");
    }
}

int WatcherManager::GetServerFd(bool retry)
{
X
add ut  
xionglei6 已提交
285
    const int32_t sleepTime = 200;
286
    const int32_t maxRetry = 10;
S
sun_fan 已提交
287 288 289 290 291 292 293 294
    std::lock_guard<std::mutex> lock(mutex_);
    if (retry && serverFd_ != INVALID_SOCKET) {
        close(serverFd_);
        serverFd_ = INVALID_SOCKET;
    }
    if (serverFd_ != INVALID_SOCKET) {
        return serverFd_;
    }
295
    int32_t retryCount = 0;
S
sun_fan 已提交
296
    do {
X
add ut  
xionglei6 已提交
297 298
        serverFd_ = socket(PF_UNIX, SOCK_STREAM, 0);
        int flags = fcntl(serverFd_, F_GETFL, 0);
X
xionglei6 已提交
299
        (void)fcntl(serverFd_, F_SETFL, flags & ~O_NONBLOCK);
C
codex  
chengjinsong 已提交
300
        if (ConnectServer(serverFd_, CLIENT_PIPE_NAME) == 0) {
S
sun_fan 已提交
301 302
            break;
        }
X
add ut  
xionglei6 已提交
303 304 305
        close(serverFd_);
        serverFd_ = INVALID_SOCKET;
        usleep(sleepTime);
306 307
        retryCount++;
    } while (retryCount < maxRetry);
X
xionglei6 已提交
308
    WATCHER_LOGV("GetServerFd serverFd_ %d retryCount %d ", serverFd_, retryCount);
S
sun_fan 已提交
309 310 311 312 313
    return serverFd_;
}

void WatcherManager::OnStart()
{
X
add ut  
xionglei6 已提交
314
    WATCHER_LOGI("WatcherManager OnStart");
S
sun_fan 已提交
315 316
    bool res = Publish(this);
    if (!res) {
X
add ut  
xionglei6 已提交
317 318
        WATCHER_LOGE("WatcherManager Publish failed");
    }
319
    SystemSetParameter("bootevent.param_watcher.started", "true");
X
add ut  
xionglei6 已提交
320 321
    if (deathRecipient_ == nullptr) {
        deathRecipient_ = new DeathRecipient(this);
S
sun_fan 已提交
322 323 324 325
    }
    return;
}

326
void WatcherManager::StopLoop()
S
sun_fan 已提交
327
{
X
xionglei6 已提交
328
    WATCHER_LOGV("WatcherManager StopLoop serverFd_ %d", serverFd_);
329
    stop_ = true;
X
add ut  
xionglei6 已提交
330 331
    if (serverFd_ > 0) {
        shutdown(serverFd_, SHUT_RDWR);
S
sun_fan 已提交
332 333 334 335 336 337 338 339 340
        close(serverFd_);
        serverFd_ = INVALID_SOCKET;
    }
    if (pRecvThread_ != nullptr) {
        pRecvThread_->join();
        delete pRecvThread_;
        pRecvThread_ = nullptr;
    }
}
341 342 343

void WatcherManager::OnStop()
{
X
add ut  
xionglei6 已提交
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    {
        std::lock_guard<std::mutex> lock(watcherMutex_);
        for (auto iter = watchers_.begin(); iter != watchers_.end(); ++iter) {
            if (iter->second == nullptr) {
                continue;
            }
            sptr<IRemoteObject> object = iter->second->GetRemoteWatcher()->AsObject();
            if (object != nullptr) {
                object->RemoveDeathRecipient(deathRecipient_);
            }
        }
    }
    watchers_.clear();
    watcherGroups_.clear();
    groupMap_.clear();
359 360
    StopLoop();
}
X
add ut  
xionglei6 已提交
361 362 363 364 365 366

void WatcherManager::DeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
{
    WATCHER_CHECK(remote != nullptr, return, "Invalid remote obj");
    auto paramWatcher = manager_->GetWatcher(remote);
    WATCHER_CHECK(paramWatcher != nullptr, return, "Failed to get remote watcher info ");
X
xionglei6 已提交
367
    WATCHER_LOGV("OnRemoteDied watcherId %u", paramWatcher->GetWatcherId());
X
add ut  
xionglei6 已提交
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
    manager_->DelWatcher(paramWatcher->GetWatcherGroup(), paramWatcher);
}

WatcherManager::ParamWatcherPtr WatcherManager::GetWatcher(uint32_t watcherId)
{
    std::lock_guard<std::mutex> lock(watcherMutex_);
    auto iter = watchers_.find(watcherId);
    if (iter != watchers_.end()) {
        return iter->second;
    }
    return nullptr;
}

WatcherManager::ParamWatcherPtr WatcherManager::GetWatcher(const wptr<IRemoteObject> &remote)
{
    std::lock_guard<std::mutex> lock(watcherMutex_);
    for (auto iter = watchers_.begin(); iter != watchers_.end(); ++iter) {
        if (iter->second == nullptr) {
            continue;
        }
        if (remote == iter->second->GetRemoteWatcher()->AsObject()) {
            return iter->second;
        }
    }
    return nullptr;
}

int WatcherManager::GetWatcherId(uint32_t &watcherId)
{
    std::lock_guard<std::mutex> lock(watcherMutex_);
    watcherId = watcherId_;
    do {
        watcherId_++;
        if (watcherId_ == 0) {
            watcherId_++;
        }
        if (watchers_.find(watcherId_) == watchers_.end()) {
            break;
        }
        WATCHER_CHECK(watcherId_ != watcherId, return -1, "No enough watcherId %u", watcherId);
    } while (1);
    watcherId = watcherId_;
    return 0;
}

int WatcherManager::GetGroupId(uint32_t &groupId)
{
    std::lock_guard<std::mutex> lock(watcherMutex_);
    groupId = groupId_;
    do {
        groupId_++;
        if (watcherGroups_.find(groupId_) == watcherGroups_.end()) {
            break;
        }
        WATCHER_CHECK(groupId_ == groupId, return -1, "No enough groupId %u", groupId);
    } while (1);
    groupId = groupId_;
    return 0;
}
C
cheng_jinsong 已提交
427 428 429 430 431 432 433 434 435 436 437

int32_t WatcherManager::RefreshWatcher(const std::string &keyPrefix, uint32_t watcherId)
{
    WATCHER_LOGV("RefreshWatcher %s watcherId: %u", keyPrefix.c_str(), watcherId);
    auto group = GetWatcherGroup(keyPrefix);
    WATCHER_CHECK(group != nullptr, return 0, "Can not find group %s", keyPrefix.c_str());
    auto paramWatcher = GetWatcher(watcherId);
    WATCHER_CHECK(paramWatcher != nullptr, return 0, "Can not find watcher %s %d", keyPrefix.c_str(), watcherId);
    SendLocalChange(keyPrefix, paramWatcher);
    return 0;
}
C
cheng_jinsong 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511

WatcherManager::ParamWatcher *WatcherManager::WatcherGroup::GetNextWatcher(WatcherManager::ParamWatcher *watcher)
{
    if (watcher == nullptr) {
        if (ListEmpty(watchers_)) {
            return nullptr;
        }
        return reinterpret_cast<WatcherManager::ParamWatcher *>(GetWatchers()->next);
    }
    if (watcher->GetGroupNode() == nullptr) {
        return nullptr;
    }
    if (watcher->GetGroupNode()->next != GetWatchers()) {
        return reinterpret_cast<WatcherManager::ParamWatcher *>(watcher->GetGroupNode()->next);
    }
    return nullptr;
}

void WatcherManager::DumpWatcherGroup(int fd, const WatcherManager::WatcherGroupPtr &watchGroup)
{
    dprintf(fd, "Watch prefix   : %s \n", watchGroup->GetKeyPrefix().c_str());
    dprintf(fd, "Watch group id : %d \n", watchGroup->GetGroupId());

    // watcher id
    WatcherManager::ParamWatcher *watcher = watchGroup->GetNextWatcher(nullptr);
    if (watcher != nullptr) {
        dprintf(fd, "Watch id list  : %d", watcher->GetWatcherId());
    } else {
        return;
    }
    watcher = watchGroup->GetNextWatcher(watcher);
    while (watcher != nullptr) {
        dprintf(fd, ", %d", watcher->GetWatcherId());
        watcher = watchGroup->GetNextWatcher(watcher);
    }
    dprintf(fd, "\n");
}

int WatcherManager::Dump(int fd, const std::vector<std::u16string>& args)
{
    WATCHER_CHECK(fd >= 0, return -1, "Invalid fd for dump %d", fd);
    std::vector<std::string> params;
    for (auto& arg : args) {
        params.emplace_back(Str16ToStr8(arg));
    }
    if (params.size() >= 1 && params[0] == "-h") {
        std::string dumpInfo = {};
        dumpInfo.append("Usage:\n")
            .append(" -h                    ")
            .append("|help text for the tool\n")
            .append(" -k                    ")
            .append("|dump watcher infomation for key prefix\n");
        dprintf(fd, "%s\n", dumpInfo.c_str());
        return 0;
    }
    if (params.size() > 1 && params[0] == "-k") {
        auto group = GetWatcherGroup(params[1]);
        if (group == NULL) {
            dprintf(fd, "Prefix %s not found in watcher list\n", params[1].c_str());
            return 0;
        }
        DumpWatcherGroup(fd, group);
        return 0;
    }
    // all output
    std::lock_guard<std::mutex> lock(watcherMutex_);
    // dump all watcher
    for (auto it = groupMap_.begin(); it != groupMap_.end(); it++) {
        if (watcherGroups_.find(it->second) != watcherGroups_.end()) {
            DumpWatcherGroup(fd, watcherGroups_[it->second]);
        }
    }
    return 0;
}
S
sun_fan 已提交
512 513
} // namespace init_param
} // namespace OHOS