GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage/nodes/benchmark/out/../src/tracing/node_trace_writer.cc Lines: 127 134 94.8 %
Date: 2019-01-07 12:15:22 Branches: 32 58 55.2 %

Line Branch Exec Source
1
#include "tracing/node_trace_writer.h"
2
3
#include <string.h>
4
#include <fcntl.h>
5
6
#include "util-inl.h"
7
8
namespace node {
9
namespace tracing {
10
11
65
NodeTraceWriter::NodeTraceWriter(const std::string& log_file_pattern)
12
65
    : log_file_pattern_(log_file_pattern) {}
13
14
65
void NodeTraceWriter::InitializeOnThread(uv_loop_t* loop) {
15
65
  CHECK_NULL(tracing_loop_);
16
65
  tracing_loop_ = loop;
17
18
65
  flush_signal_.data = this;
19
  int err = uv_async_init(tracing_loop_, &flush_signal_,
20
475
                          [](uv_async_t* signal) {
21
    NodeTraceWriter* trace_writer =
22
205
        ContainerOf(&NodeTraceWriter::flush_signal_, signal);
23
205
    trace_writer->FlushPrivate();
24
540
  });
25
65
  CHECK_EQ(err, 0);
26
27
65
  exit_signal_.data = this;
28
65
  err = uv_async_init(tracing_loop_, &exit_signal_, ExitSignalCb);
29
65
  CHECK_EQ(err, 0);
30
65
}
31
32
65
void NodeTraceWriter::WriteSuffix() {
33
  // If our final log file has traces, then end the file appropriately.
34
  // This means that if no trace events are recorded, then no trace file is
35
  // produced.
36
65
  bool should_flush = false;
37
  {
38
65
    Mutex::ScopedLock scoped_lock(stream_mutex_);
39
65
    if (total_traces_ > 0) {
40
65
      total_traces_ = kTracesPerFile;  // Act as if we reached the file limit.
41
65
      should_flush = true;
42
65
    }
43
  }
44
65
  if (should_flush) {
45
65
    Flush(true);
46
  }
47
65
}
48
49
195
NodeTraceWriter::~NodeTraceWriter() {
50
65
  WriteSuffix();
51
  uv_fs_t req;
52
65
  if (fd_ != -1) {
53
65
    CHECK_EQ(0, uv_fs_close(nullptr, &req, fd_, nullptr));
54
65
    uv_fs_req_cleanup(&req);
55
  }
56
65
  uv_async_send(&exit_signal_);
57
65
  Mutex::ScopedLock scoped_lock(request_mutex_);
58
179
  while (!exited_) {
59
49
    exit_cond_.Wait(scoped_lock);
60
65
  }
61
130
}
62
63
130
void replace_substring(std::string* target,
64
                       const std::string& search,
65
                       const std::string& insert) {
66
130
  size_t pos = target->find(search);
67
198
  for (; pos != std::string::npos; pos = target->find(search, pos)) {
68
68
    target->replace(pos, search.size(), insert);
69
68
    pos += insert.size();
70
  }
71
130
}
72
73
65
void NodeTraceWriter::OpenNewFileForStreaming() {
74
65
  ++file_num_;
75
  uv_fs_t req;
76
77
  // Evaluate a JS-style template string, it accepts the values ${pid} and
78
  // ${rotation}
79
65
  std::string filepath(log_file_pattern_);
80
65
  replace_substring(&filepath, "${pid}", std::to_string(uv_os_getpid()));
81
65
  replace_substring(&filepath, "${rotation}", std::to_string(file_num_));
82
83
65
  if (fd_ != -1) {
84
    CHECK_EQ(uv_fs_close(nullptr, &req, fd_, nullptr), 0);
85
    uv_fs_req_cleanup(&req);
86
  }
87
88
  fd_ = uv_fs_open(nullptr, &req, filepath.c_str(),
89
65
      O_CREAT | O_WRONLY | O_TRUNC, 0644, nullptr);
90
65
  uv_fs_req_cleanup(&req);
91
65
  if (fd_ < 0) {
92
    fprintf(stderr, "Could not open trace file %s: %s\n",
93
                    filepath.c_str(),
94
                    uv_strerror(fd_));
95
    fd_ = -1;
96
65
  }
97
65
}
98
99
3406
void NodeTraceWriter::AppendTraceEvent(TraceObject* trace_event) {
100
3406
  Mutex::ScopedLock scoped_lock(stream_mutex_);
101
  // If this is the first trace event, open a new file for streaming.
102
3406
  if (total_traces_ == 0) {
103
65
    OpenNewFileForStreaming();
104
    // Constructing a new JSONTraceWriter object appends "{\"traceEvents\":["
105
    // to stream_.
106
    // In other words, the constructor initializes the serialization stream
107
    // to a state where we can start writing trace events to it.
108
    // Repeatedly constructing and destroying json_trace_writer_ allows
109
    // us to use V8's JSON writer instead of implementing our own.
110
65
    json_trace_writer_.reset(TraceWriter::CreateJSONTraceWriter(stream_));
111
  }
112
3406
  ++total_traces_;
113
3406
  json_trace_writer_->AppendTraceEvent(trace_event);
114
3406
}
115
116
205
void NodeTraceWriter::FlushPrivate() {
117
205
  std::string str;
118
  int highest_request_id;
119
  {
120
205
    Mutex::ScopedLock stream_scoped_lock(stream_mutex_);
121
205
    if (total_traces_ >= kTracesPerFile) {
122
65
      total_traces_ = 0;
123
      // Destroying the member JSONTraceWriter object appends "]}" to
124
      // stream_ - in other words, ending a JSON file.
125
65
      json_trace_writer_.reset();
126
    }
127
    // str() makes a copy of the contents of the stream.
128
205
    str = stream_.str();
129
205
    stream_.str("");
130
205
    stream_.clear();
131
  }
132
  {
133
205
    Mutex::ScopedLock request_scoped_lock(request_mutex_);
134
205
    highest_request_id = num_write_requests_;
135
  }
136
205
  WriteToFile(std::move(str), highest_request_id);
137
205
}
138
139
205
void NodeTraceWriter::Flush(bool blocking) {
140
205
  Mutex::ScopedLock scoped_lock(request_mutex_);
141
205
  if (!json_trace_writer_) {
142
205
    return;
143
  }
144
205
  int request_id = ++num_write_requests_;
145
205
  int err = uv_async_send(&flush_signal_);
146
205
  CHECK_EQ(err, 0);
147
205
  if (blocking) {
148
    // Wait until data associated with this request id has been written to disk.
149
    // This guarantees that data from all earlier requests have also been
150
    // written.
151

615
    while (request_id > highest_request_id_completed_) {
152
205
      request_cond_.Wait(scoped_lock);
153
    }
154
205
  }
155
}
156
157
205
void NodeTraceWriter::WriteToFile(std::string&& str, int highest_request_id) {
158
410
  if (fd_ == -1) return;
159
160
205
  uv_buf_t buf = uv_buf_init(nullptr, 0);
161
  {
162
205
    Mutex::ScopedLock lock(request_mutex_);
163
    write_req_queue_.emplace(WriteRequest {
164
205
      std::move(str), highest_request_id
165
205
    });
166
205
    if (write_req_queue_.size() == 1) {
167
      buf = uv_buf_init(
168
205
          const_cast<char*>(write_req_queue_.front().str.c_str()),
169
410
          write_req_queue_.front().str.length());
170
205
    }
171
  }
172
  // Only one write request for the same file descriptor should be active at
173
  // a time.
174

205
  if (buf.base != nullptr && fd_ != -1) {
175
205
    StartWrite(buf);
176
  }
177
}
178
179
205
void NodeTraceWriter::StartWrite(uv_buf_t buf) {
180
  int err = uv_fs_write(
181
      tracing_loop_, &write_req_, fd_, &buf, 1, -1,
182
615
      [](uv_fs_t* req) {
183
        NodeTraceWriter* writer =
184
205
            ContainerOf(&NodeTraceWriter::write_req_, req);
185
205
        writer->AfterWrite();
186
820
      });
187
205
  CHECK_EQ(err, 0);
188
205
}
189
190
205
void NodeTraceWriter::AfterWrite() {
191
205
  CHECK_GE(write_req_.result, 0);
192
205
  uv_fs_req_cleanup(&write_req_);
193
194
205
  uv_buf_t buf = uv_buf_init(nullptr, 0);
195
  {
196
205
    Mutex::ScopedLock scoped_lock(request_mutex_);
197
205
    int highest_request_id = write_req_queue_.front().highest_request_id;
198
205
    write_req_queue_.pop();
199
205
    highest_request_id_completed_ = highest_request_id;
200
205
    request_cond_.Broadcast(scoped_lock);
201
205
    if (!write_req_queue_.empty()) {
202
      buf = uv_buf_init(
203
          const_cast<char*>(write_req_queue_.front().str.c_str()),
204
          write_req_queue_.front().str.length());
205
205
    }
206
  }
207

205
  if (buf.base != nullptr && fd_ != -1) {
208
    StartWrite(buf);
209
  }
210
205
}
211
212
// static
213
65
void NodeTraceWriter::ExitSignalCb(uv_async_t* signal) {
214
  NodeTraceWriter* trace_writer =
215
65
      ContainerOf(&NodeTraceWriter::exit_signal_, signal);
216
  uv_close(reinterpret_cast<uv_handle_t*>(&trace_writer->flush_signal_),
217
65
           nullptr);
218
  uv_close(reinterpret_cast<uv_handle_t*>(&trace_writer->exit_signal_),
219
195
           [](uv_handle_t* signal) {
220
      NodeTraceWriter* trace_writer =
221
          ContainerOf(&NodeTraceWriter::exit_signal_,
222
65
                      reinterpret_cast<uv_async_t*>(signal));
223
65
      Mutex::ScopedLock scoped_lock(trace_writer->request_mutex_);
224
65
      trace_writer->exited_ = true;
225
65
      trace_writer->exit_cond_.Signal(scoped_lock);
226
260
  });
227
65
}
228
229
}  // namespace tracing
230
}  // namespace node