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
16 #include "stack_writer.h"
17 #include "logging.h"
18 #include "share_memory_allocator.h"
19
20 #include <algorithm>
21 #include <cinttypes>
22 #include <thread>
23 #include <unistd.h>
24
StackWriter(std::string name,uint32_t size,int smbFd,int eventFd)25 StackWriter::StackWriter(std::string name,
26 uint32_t size,
27 int smbFd,
28 int eventFd)
29 : pluginName_(name)
30 {
31 HILOG_INFO(LOG_CORE, "%s:%s %d [%d] [%d]", __func__, name.c_str(), size, smbFd, eventFd);
32 shareMemoryBlock_ = ShareMemoryAllocator::GetInstance().CreateMemoryBlockRemote(name, size, smbFd);
33 if (shareMemoryBlock_ == nullptr) {
34 HILOG_DEBUG(LOG_CORE, "%s:create shareMemoryBlock_ failed!", __func__);
35 }
36 eventNotifier_ = EventNotifier::CreateWithFd(eventFd);
37
38 lastFlushTime_ = std::chrono::steady_clock::now();
39 }
40
~StackWriter()41 StackWriter::~StackWriter()
42 {
43 HILOG_DEBUG(LOG_CORE, "%s:destroy eventfd = %d!", __func__, eventNotifier_ ? eventNotifier_->GetFd() : -1);
44 eventNotifier_ = nullptr;
45 ShareMemoryAllocator::GetInstance().ReleaseMemoryBlockRemote(pluginName_);
46 }
47
Report() const48 void StackWriter::Report() const
49 {
50 HILOG_DEBUG(LOG_CORE, "%s:stats B: %" PRIu64 ", P: %d, W:%" PRIu64 ", F: %d", __func__,
51 bytesCount_.load(), bytesPending_.load(), writeCount_.load(), flushCount_.load());
52 }
53
DoStats(long bytes)54 void StackWriter::DoStats(long bytes)
55 {
56 ++writeCount_;
57 bytesCount_ += bytes;
58 bytesPending_ += bytes;
59 }
60
Write(const void * data,size_t size)61 long StackWriter::Write(const void* data, size_t size)
62 {
63 if (shareMemoryBlock_ == nullptr || data == nullptr || size == 0) {
64 return false;
65 }
66 return shareMemoryBlock_->PutRaw(reinterpret_cast<const int8_t*>(data), size);
67 }
68
Flush()69 bool StackWriter::Flush()
70 {
71 ++flushCount_;
72 eventNotifier_->Post(flushCount_.load());
73 lastFlushTime_ = std::chrono::steady_clock::now();
74 bytesPending_ = 0;
75 return true;
76 }
77