YugabyteDB (2.13.1.0-b60, 21121d69985fbf76aa6958d8f04a9bfa936293b5)

Coverage Report

Created: 2022-03-22 16:43

/Users/deen/code/yugabyte-db/src/yb/util/pb_util.cc
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
//
18
// The following only applies to changes made to this file as part of YugaByte development.
19
//
20
// Portions Copyright (c) YugaByte, Inc.
21
//
22
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
23
// in compliance with the License.  You may obtain a copy of the License at
24
//
25
// http://www.apache.org/licenses/LICENSE-2.0
26
//
27
// Unless required by applicable law or agreed to in writing, software distributed under the License
28
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
29
// or implied.  See the License for the specific language governing permissions and limitations
30
// under the License.
31
//
32
// Some portions copyright (C) 2008, Google, inc.
33
//
34
// Utilities for working with protobufs.
35
// Some of this code is cribbed from the protobuf source,
36
// but modified to work with yb's 'faststring' instead of STL strings.
37
38
#include "yb/util/pb_util.h"
39
40
#include <memory>
41
#include <string>
42
#include <unordered_set>
43
#include <vector>
44
45
#include <glog/logging.h>
46
#include <google/protobuf/descriptor.pb.h>
47
#include <google/protobuf/descriptor_database.h>
48
#include <google/protobuf/dynamic_message.h>
49
#include <google/protobuf/io/coded_stream.h>
50
#include <google/protobuf/io/zero_copy_stream.h>
51
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
52
#include <google/protobuf/message.h>
53
#include <google/protobuf/util/message_differencer.h>
54
55
#include "yb/gutil/callback.h"
56
#include "yb/gutil/casts.h"
57
#include "yb/gutil/map-util.h"
58
#include "yb/gutil/strings/escaping.h"
59
#include "yb/gutil/strings/fastmem.h"
60
61
#include "yb/util/coding-inl.h"
62
#include "yb/util/coding.h"
63
#include "yb/util/crc.h"
64
#include "yb/util/debug/sanitizer_scopes.h"
65
#include "yb/util/debug/trace_event.h"
66
#include "yb/util/env.h"
67
#include "yb/util/env_util.h"
68
#include "yb/util/path_util.h"
69
#include "yb/util/pb_util-internal.h"
70
#include "yb/util/pb_util.pb.h"
71
#include "yb/util/result.h"
72
#include "yb/util/status.h"
73
#include "yb/util/status_log.h"
74
75
using google::protobuf::Descriptor;
76
using google::protobuf::DescriptorPool;
77
using google::protobuf::DynamicMessageFactory;
78
using google::protobuf::FieldDescriptor;
79
using google::protobuf::FileDescriptor;
80
using google::protobuf::FileDescriptorProto;
81
using google::protobuf::FileDescriptorSet;
82
using google::protobuf::io::ArrayInputStream;
83
using google::protobuf::io::CodedInputStream;
84
using google::protobuf::Message;
85
using google::protobuf::MessageLite;
86
using google::protobuf::Reflection;
87
using google::protobuf::SimpleDescriptorDatabase;
88
using yb::crc::Crc;
89
using yb::pb_util::internal::SequentialFileFileInputStream;
90
using yb::pb_util::internal::WritableFileOutputStream;
91
using std::deque;
92
using std::endl;
93
using std::shared_ptr;
94
using std::string;
95
using std::unordered_set;
96
using std::vector;
97
using strings::Substitute;
98
using strings::Utf8SafeCEscape;
99
100
static const char* const kTmpTemplateSuffix = ".tmp.XXXXXX";
101
102
// Protobuf container constants.
103
static const int kPBContainerVersion = 1;
104
static const char kPBContainerMagic[] = "yugacntr";
105
static const int kPBContainerMagicLen = 8;
106
static const int kPBContainerHeaderLen =
107
    // magic number + version
108
    kPBContainerMagicLen + sizeof(uint32_t);
109
static const int kPBContainerChecksumLen = sizeof(uint32_t);
110
111
COMPILE_ASSERT((arraysize(kPBContainerMagic) - 1) == kPBContainerMagicLen,
112
               kPBContainerMagic_does_not_match_expected_length);
113
114
namespace yb {
115
namespace pb_util {
116
117
namespace {
118
119
// When serializing, we first compute the byte size, then serialize the message.
120
// If serialization produces a different number of bytes than expected, we
121
// call this function, which crashes.  The problem could be due to a bug in the
122
// protobuf implementation but is more likely caused by concurrent modification
123
// of the message.  This function attempts to distinguish between the two and
124
// provide a useful error message.
125
void ByteSizeConsistencyError(size_t byte_size_before_serialization,
126
                              size_t byte_size_after_serialization,
127
0
                              size_t bytes_produced_by_serialization) {
128
0
  CHECK_EQ(byte_size_before_serialization, byte_size_after_serialization)
129
0
      << "Protocol message was modified concurrently during serialization.";
130
0
  CHECK_EQ(bytes_produced_by_serialization, byte_size_before_serialization)
131
0
      << "Byte size calculation and serialization were inconsistent.  This "
132
0
         "may indicate a bug in protocol buffers or it may be caused by "
133
0
         "concurrent modification of the message.";
134
0
  LOG(FATAL) << "This shouldn't be called if all the sizes are equal.";
135
0
}
136
137
string InitializationErrorMessage(const char* action,
138
0
                                  const MessageLite& message) {
139
  // Note:  We want to avoid depending on strutil in the lite library, otherwise
140
  //   we'd use:
141
  //
142
  // return strings::Substitute(
143
  //   "Can't $0 message of type \"$1\" because it is missing required "
144
  //   "fields: $2",
145
  //   action, message.GetTypeName(),
146
  //   message.InitializationErrorString());
147
148
0
  string result;
149
0
  result += "Can't ";
150
0
  result += action;
151
0
  result += " message of type \"";
152
0
  result += message.GetTypeName();
153
0
  result += "\" because it is missing required fields: ";
154
0
  result += message.InitializationErrorString();
155
0
  return result;
156
0
}
157
158
11
uint8_t* GetUInt8Ptr(const char* buffer) {
159
11
  return pointer_cast<uint8_t*>(const_cast<char*>(buffer));
160
11
}
161
162
25.7M
uint8_t* GetUInt8Ptr(uint8_t* buffer) {
163
25.7M
  return buffer;
164
25.7M
}
165
166
template <class Out>
167
25.7M
void DoAppendPartialToString(const MessageLite &msg, Out* output) {
168
25.7M
  auto old_size = output->size();
169
25.7M
  int byte_size = msg.ByteSize();
170
171
25.7M
  output->resize(old_size + byte_size);
172
173
25.7M
  uint8* start = GetUInt8Ptr(output->data()) + old_size;
174
25.7M
  uint8* end = msg.SerializeWithCachedSizesToArray(start);
175
25.7M
  if (end - start != byte_size) {
176
0
    ByteSizeConsistencyError(byte_size, msg.ByteSize(), end - start);
177
0
  }
178
25.7M
}
pb_util.cc:void yb::pb_util::(anonymous namespace)::DoAppendPartialToString<yb::faststring>(google::protobuf::MessageLite const&, yb::faststring*)
Line
Count
Source
167
25.7M
void DoAppendPartialToString(const MessageLite &msg, Out* output) {
168
25.7M
  auto old_size = output->size();
169
25.7M
  int byte_size = msg.ByteSize();
170
171
25.7M
  output->resize(old_size + byte_size);
172
173
25.7M
  uint8* start = GetUInt8Ptr(output->data()) + old_size;
174
25.7M
  uint8* end = msg.SerializeWithCachedSizesToArray(start);
175
25.7M
  if (end - start != byte_size) {
176
0
    ByteSizeConsistencyError(byte_size, msg.ByteSize(), end - start);
177
0
  }
178
25.7M
}
pb_util.cc:void yb::pb_util::(anonymous namespace)::DoAppendPartialToString<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(google::protobuf::MessageLite const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >*)
Line
Count
Source
167
11
void DoAppendPartialToString(const MessageLite &msg, Out* output) {
168
11
  auto old_size = output->size();
169
11
  int byte_size = msg.ByteSize();
170
171
11
  output->resize(old_size + byte_size);
172
173
11
  uint8* start = GetUInt8Ptr(output->data()) + old_size;
174
11
  uint8* end = msg.SerializeWithCachedSizesToArray(start);
175
11
  if (end - start != byte_size) {
176
0
    ByteSizeConsistencyError(byte_size, msg.ByteSize(), end - start);
177
0
  }
178
11
}
179
180
} // anonymous namespace
181
182
25.7M
void AppendToString(const MessageLite &msg, faststring *output) {
183
25.7M
  DCHECK
(msg.IsInitialized()) << InitializationErrorMessage("serialize", msg)5.29k
;
184
25.7M
  AppendPartialToString(msg, output);
185
25.7M
}
186
187
25.7M
void AppendPartialToString(const MessageLite &msg, faststring* output) {
188
25.7M
  DoAppendPartialToString(msg, output);
189
25.7M
}
190
191
11
void AppendPartialToString(const MessageLite &msg, std::string* output) {
192
11
  DoAppendPartialToString(msg, output);
193
11
}
194
195
415k
void SerializeToString(const MessageLite &msg, faststring *output) {
196
415k
  output->clear();
197
415k
  AppendToString(msg, output);
198
415k
}
199
200
3.34k
bool ParseFromSequentialFile(MessageLite *msg, SequentialFile *rfile) {
201
3.34k
  SequentialFileFileInputStream istream(rfile);
202
3.34k
  return msg->ParseFromZeroCopyStream(&istream);
203
3.34k
}
204
205
4.32M
Status ParseFromArray(MessageLite* msg, const uint8_t* data, size_t length) {
206
4.32M
  CodedInputStream in(data, narrow_cast<uint32_t>(length));
207
4.32M
  in.SetTotalBytesLimit(511 * 1024 * 1024, -1);
208
  // Parse data into protobuf message
209
4.32M
  if (!msg->ParseFromCodedStream(&in)) {
210
0
    return STATUS(Corruption, "Error parsing msg", InitializationErrorMessage("parse", *msg));
211
0
  }
212
4.32M
  return Status::OK();
213
4.32M
}
214
215
Status WritePBToPath(Env* env, const std::string& path,
216
                     const MessageLite& msg,
217
4.69k
                     SyncMode sync) {
218
4.69k
  const string tmp_template = path + kTmpTemplateSuffix;
219
4.69k
  string tmp_path;
220
221
4.69k
  std::unique_ptr<WritableFile> file;
222
4.69k
  RETURN_NOT_OK(env->NewTempWritableFile(WritableFileOptions(), tmp_template, &tmp_path, &file));
223
4.69k
  env_util::ScopedFileDeleter tmp_deleter(env, tmp_path);
224
225
4.69k
  WritableFileOutputStream ostream(file.get());
226
4.69k
  bool res = msg.SerializeToZeroCopyStream(&ostream);
227
4.69k
  if (!res || !ostream.Flush()) {
228
0
    return STATUS(IOError, "Unable to serialize PB to file");
229
0
  }
230
231
4.69k
  if (sync == pb_util::SYNC) {
232
0
    RETURN_NOT_OK_PREPEND(file->Sync(), "Failed to Sync() " + tmp_path);
233
0
  }
234
4.69k
  RETURN_NOT_OK_PREPEND(file->Close(), "Failed to Close() " + tmp_path);
235
4.69k
  RETURN_NOT_OK_PREPEND(env->RenameFile(tmp_path, path), "Failed to rename tmp file to " + path);
236
4.69k
  tmp_deleter.Cancel();
237
4.69k
  if (sync == pb_util::SYNC) {
238
0
    RETURN_NOT_OK_PREPEND(env->SyncDir(DirName(path)), "Failed to SyncDir() parent of " + path);
239
0
  }
240
4.69k
  return Status::OK();
241
4.69k
}
242
243
3.34k
Status ReadPBFromPath(Env* env, const std::string& path, MessageLite* msg) {
244
3.34k
  shared_ptr<SequentialFile> rfile;
245
3.34k
  RETURN_NOT_OK(env_util::OpenFileForSequential(env, path, &rfile));
246
3.34k
  if (!ParseFromSequentialFile(msg, rfile.get())) {
247
0
    return STATUS(IOError, "Unable to parse PB from path", path);
248
0
  }
249
3.34k
  return Status::OK();
250
3.34k
}
251
252
0
static void TruncateString(string* s, size_t max_len) {
253
0
  if (s->size() > max_len) {
254
0
    s->resize(max_len);
255
0
    s->append("<truncated>");
256
0
  }
257
0
}
258
259
0
void TruncateFields(Message* message, int max_len) {
260
0
  const Reflection* reflection = message->GetReflection();
261
0
  vector<const FieldDescriptor*> fields;
262
0
  reflection->ListFields(*message, &fields);
263
0
  for (const FieldDescriptor* field : fields) {
264
0
    if (field->is_repeated()) {
265
0
      for (int i = 0; i < reflection->FieldSize(*message, field); i++) {
266
0
        switch (field->cpp_type()) {
267
0
          case FieldDescriptor::CPPTYPE_STRING: {
268
0
            const string& s_const = reflection->GetRepeatedStringReference(*message, field, i,
269
0
                                                                           nullptr);
270
0
            TruncateString(const_cast<string*>(&s_const), max_len);
271
0
            break;
272
0
          }
273
0
          case FieldDescriptor::CPPTYPE_MESSAGE: {
274
0
            TruncateFields(reflection->MutableRepeatedMessage(message, field, i), max_len);
275
0
            break;
276
0
          }
277
0
          default:
278
0
            break;
279
0
        }
280
0
      }
281
0
    } else {
282
0
      switch (field->cpp_type()) {
283
0
        case FieldDescriptor::CPPTYPE_STRING: {
284
0
          const string& s_const = reflection->GetStringReference(*message, field, nullptr);
285
0
          TruncateString(const_cast<string*>(&s_const), max_len);
286
0
          break;
287
0
        }
288
0
        case FieldDescriptor::CPPTYPE_MESSAGE: {
289
0
          TruncateFields(reflection->MutableMessage(message, field), max_len);
290
0
          break;
291
0
        }
292
0
        default:
293
0
          break;
294
0
      }
295
0
    }
296
0
  }
297
0
}
298
299
WritablePBContainerFile::WritablePBContainerFile(std::unique_ptr<WritableFile> writer)
300
  : closed_(false),
301
2.10M
    writer_(std::move(writer)) {
302
2.10M
}
303
304
2.10M
WritablePBContainerFile::~WritablePBContainerFile() {
305
2.10M
  WARN_NOT_OK(Close(), "Could not Close() when destroying file");
306
2.10M
}
307
308
2.10M
Status WritablePBContainerFile::Init(const Message& msg) {
309
2.10M
  DCHECK(!closed_);
310
311
2.10M
  faststring buf;
312
2.10M
  buf.resize(kPBContainerHeaderLen);
313
314
  // Serialize the magic.
315
2.10M
  strings::memcpy_inlined(buf.data(), kPBContainerMagic, kPBContainerMagicLen);
316
2.10M
  size_t offset = kPBContainerMagicLen;
317
318
  // Serialize the version.
319
2.10M
  InlineEncodeFixed32(buf.data() + offset, kPBContainerVersion);
320
2.10M
  offset += sizeof(uint32_t);
321
2.10M
  DCHECK_EQ(kPBContainerHeaderLen, offset)
322
0
    << "Serialized unexpected number of total bytes";
323
324
  // Serialize the supplemental header.
325
2.10M
  ContainerSupHeaderPB sup_header;
326
2.10M
  PopulateDescriptorSet(msg.GetDescriptor()->file(),
327
2.10M
                        sup_header.mutable_protos());
328
2.10M
  sup_header.set_pb_type(msg.GetTypeName());
329
2.10M
  RETURN_NOT_OK_PREPEND(AppendMsgToBuffer(sup_header, &buf),
330
2.10M
                        "Failed to prepare supplemental header for writing");
331
332
  // Write the serialized buffer to the file.
333
2.10M
  RETURN_NOT_OK_PREPEND(writer_->Append(buf),
334
2.10M
                        "Failed to Append() header to file");
335
2.10M
  return Status::OK();
336
2.10M
}
337
338
2.10M
Status WritablePBContainerFile::Append(const Message& msg) {
339
2.10M
  DCHECK(!closed_);
340
341
2.10M
  faststring buf;
342
2.10M
  RETURN_NOT_OK_PREPEND(AppendMsgToBuffer(msg, &buf),
343
2.10M
                        "Failed to prepare buffer for writing");
344
2.10M
  RETURN_NOT_OK_PREPEND(writer_->Append(buf), "Failed to Append() data to file");
345
346
2.10M
  return Status::OK();
347
2.10M
}
348
349
0
Status WritablePBContainerFile::Flush() {
350
0
  DCHECK(!closed_);
351
352
  // TODO: Flush just the dirty bytes.
353
0
  RETURN_NOT_OK_PREPEND(writer_->Flush(WritableFile::FLUSH_ASYNC), "Failed to Flush() file");
354
355
0
  return Status::OK();
356
0
}
357
358
2.10M
Status WritablePBContainerFile::Sync() {
359
2.10M
  DCHECK(!closed_);
360
361
2.10M
  RETURN_NOT_OK_PREPEND(writer_->Sync(), "Failed to Sync() file");
362
363
2.10M
  return Status::OK();
364
2.10M
}
365
366
4.21M
Status WritablePBContainerFile::Close() {
367
4.21M
  if (!closed_) {
368
2.10M
    closed_ = true;
369
370
2.10M
    RETURN_NOT_OK_PREPEND(writer_->Close(), "Failed to Close() file");
371
2.10M
  }
372
373
4.21M
  return Status::OK();
374
4.21M
}
375
376
4.21M
Status WritablePBContainerFile::AppendMsgToBuffer(const Message& msg, faststring* buf) {
377
4.21M
  DCHECK
(msg.IsInitialized()) << InitializationErrorMessage("serialize", msg)552
;
378
4.21M
  int data_size = msg.ByteSize();
379
4.21M
  uint64_t bufsize = sizeof(uint32_t) + data_size + kPBContainerChecksumLen;
380
381
  // Grow the buffer to hold the new data.
382
4.21M
  size_t orig_size = buf->size();
383
4.21M
  buf->resize(orig_size + bufsize);
384
4.21M
  uint8_t* dst = buf->data() + orig_size;
385
386
  // Serialize the data size.
387
4.21M
  InlineEncodeFixed32(dst, static_cast<uint32_t>(data_size));
388
4.21M
  size_t offset = sizeof(uint32_t);
389
390
  // Serialize the data.
391
4.21M
  if (PREDICT_FALSE(!msg.SerializeWithCachedSizesToArray(dst + offset))) {
392
0
    return STATUS(IOError, "Failed to serialize PB to array");
393
0
  }
394
4.21M
  offset += data_size;
395
396
  // Calculate and serialize the checksum.
397
4.21M
  uint32_t checksum = crc::Crc32c(dst, offset);
398
4.21M
  InlineEncodeFixed32(dst + offset, checksum);
399
4.21M
  offset += kPBContainerChecksumLen;
400
401
4.21M
  DCHECK_EQ
(bufsize, offset) << "Serialized unexpected number of total bytes"0
;
402
4.21M
  return Status::OK();
403
4.21M
}
404
405
void WritablePBContainerFile::PopulateDescriptorSet(
406
2.10M
    const FileDescriptor* desc, FileDescriptorSet* output) {
407
  // Because we don't compile protobuf with TSAN enabled, copying the
408
  // static PB descriptors in this function ends up triggering a lot of
409
  // race reports. We suppress the reports, but TSAN still has to walk
410
  // the stack, etc, and this function becomes very slow. So, we ignore
411
  // TSAN here.
412
2.10M
  debug::ScopedTSANIgnoreReadsAndWrites ignore_tsan;
413
414
2.10M
  FileDescriptorSet all_descs;
415
416
  // Tracks all schemas that have been added to 'unemitted' at one point
417
  // or another. Is a superset of 'unemitted' and only ever grows.
418
2.10M
  unordered_set<const FileDescriptor*> processed;
419
420
  // Tracks all remaining unemitted schemas.
421
2.10M
  deque<const FileDescriptor*> unemitted;
422
423
2.10M
  InsertOrDie(&processed, desc);
424
2.10M
  unemitted.push_front(desc);
425
17.7M
  while (!unemitted.empty()) {
426
15.6M
    const FileDescriptor* proto = unemitted.front();
427
428
    // The current schema is emitted iff we've processed (i.e. emitted) all
429
    // of its dependencies.
430
15.6M
    bool emit = true;
431
38.5M
    for (int i = 0; i < proto->dependency_count(); 
i++22.9M
) {
432
22.9M
      const FileDescriptor* dep = proto->dependency(i);
433
22.9M
      if (InsertIfNotPresent(&processed, dep)) {
434
9.90M
        unemitted.push_front(dep);
435
9.90M
        emit = false;
436
9.90M
      }
437
22.9M
    }
438
15.6M
    if (emit) {
439
12.0M
      unemitted.pop_front();
440
12.0M
      proto->CopyTo(all_descs.mutable_file()->Add());
441
12.0M
    }
442
15.6M
  }
443
2.10M
  all_descs.Swap(output);
444
2.10M
}
445
446
ReadablePBContainerFile::ReadablePBContainerFile(std::unique_ptr<RandomAccessFile> reader)
447
  : offset_(0),
448
330k
    reader_(std::move(reader)) {
449
330k
}
450
451
330k
ReadablePBContainerFile::~ReadablePBContainerFile() {
452
330k
  WARN_NOT_OK(Close(), "Could not Close() when destroying file");
453
330k
}
454
455
330k
Status ReadablePBContainerFile::Init() {
456
  // Read header data.
457
330k
  Slice header;
458
330k
  std::unique_ptr<uint8_t[]> scratch;
459
330k
  RETURN_NOT_OK_PREPEND(ValidateAndRead(kPBContainerHeaderLen, EOF_NOT_OK, &header, &scratch),
460
330k
                        Substitute("Could not read header for proto container file $0",
461
330k
                                   reader_->filename()));
462
463
  // Validate magic number.
464
330k
  if (PREDICT_FALSE(!strings::memeq(kPBContainerMagic, header.data(), kPBContainerMagicLen))) {
465
1
    string file_magic(reinterpret_cast<const char*>(header.data()), kPBContainerMagicLen);
466
1
    return STATUS(Corruption, "Invalid magic number",
467
1
                              Substitute("Expected: $0, found: $1",
468
1
                                         Utf8SafeCEscape(kPBContainerMagic),
469
1
                                         Utf8SafeCEscape(file_magic)));
470
1
  }
471
472
  // Validate container file version.
473
330k
  uint32_t version = DecodeFixed32(header.data() + kPBContainerMagicLen);
474
330k
  if (PREDICT_FALSE(version != kPBContainerVersion)) {
475
    // We only support version 1.
476
1
    return STATUS(NotSupported,
477
1
        Substitute("Protobuf container has version $0, we only support version $1",
478
1
                   version, kPBContainerVersion));
479
1
  }
480
481
  // Read the supplemental header.
482
330k
  ContainerSupHeaderPB sup_header;
483
330k
  RETURN_NOT_OK_PREPEND(ReadNextPB(&sup_header), Substitute(
484
330k
      "Could not read supplemental header from proto container file $0",
485
330k
      reader_->filename()));
486
330k
  protos_.reset(sup_header.release_protos());
487
330k
  pb_type_ = sup_header.pb_type();
488
489
330k
  return Status::OK();
490
330k
}
491
492
661k
Status ReadablePBContainerFile::ReadNextPB(Message* msg) {
493
661k
  VLOG
(1) << "Reading PB from offset " << offset_370
;
494
495
  // Read the size from the file. EOF here is acceptable: it means we're
496
  // out of PB entries.
497
661k
  Slice size;
498
661k
  std::unique_ptr<uint8_t[]> size_scratch;
499
661k
  RETURN_NOT_OK_PREPEND(ValidateAndRead(sizeof(uint32_t), EOF_OK, &size, &size_scratch),
500
661k
                        Substitute("Could not read data size from proto container file $0",
501
661k
                                   reader_->filename()));
502
661k
  uint32_t data_size = DecodeFixed32(size.data());
503
504
  // Read body into buffer for checksum & parsing.
505
661k
  Slice body;
506
661k
  std::unique_ptr<uint8_t[]> body_scratch;
507
661k
  RETURN_NOT_OK_PREPEND(ValidateAndRead(data_size, EOF_NOT_OK, &body, &body_scratch),
508
661k
                        Substitute("Could not read body from proto container file $0",
509
661k
                                   reader_->filename()));
510
511
  // Read checksum.
512
661k
  uint32_t expected_checksum = 0;
513
661k
  {
514
661k
    Slice encoded_checksum;
515
661k
    std::unique_ptr<uint8_t[]> encoded_checksum_scratch;
516
661k
    RETURN_NOT_OK_PREPEND(ValidateAndRead(kPBContainerChecksumLen, EOF_NOT_OK,
517
661k
                                          &encoded_checksum, &encoded_checksum_scratch),
518
661k
                          Substitute("Could not read checksum from proto container file $0",
519
661k
                                     reader_->filename()));
520
661k
    expected_checksum = DecodeFixed32(encoded_checksum.data());
521
661k
  }
522
523
  // Validate CRC32C checksum.
524
0
  Crc* crc32c = crc::GetCrc32cInstance();
525
661k
  uint64_t actual_checksum = 0;
526
  // Compute a rolling checksum over the two byte arrays (size, body).
527
661k
  crc32c->Compute(size.data(), size.size(), &actual_checksum);
528
661k
  crc32c->Compute(body.data(), body.size(), &actual_checksum);
529
661k
  if (PREDICT_FALSE(actual_checksum != expected_checksum)) {
530
2
    return STATUS(Corruption, Substitute("Incorrect checksum of file $0: actually $1, expected $2",
531
2
                                         reader_->filename(), actual_checksum, expected_checksum));
532
2
  }
533
534
  // The checksum is correct. Time to decode the body.
535
  //
536
  // We could compare pb_type_ against msg.GetTypeName(), but:
537
  // 1. pb_type_ is not available when reading the supplemental header,
538
  // 2. ParseFromArray() should fail if the data cannot be parsed into the
539
  //    provided message type.
540
541
  // To permit parsing of very large PB messages, we must use parse through a
542
  // CodedInputStream and bump the byte limit. The SetTotalBytesLimit() docs
543
  // say that 512MB is the shortest theoretical message length that may produce
544
  // integer overflow warnings, so that's what we'll use.
545
661k
  ArrayInputStream ais(body.data(), narrow_cast<int>(body.size()));
546
661k
  CodedInputStream cis(&ais);
547
661k
  cis.SetTotalBytesLimit(512 * 1024 * 1024, -1);
548
661k
  if (PREDICT_FALSE(!msg->ParseFromCodedStream(&cis))) {
549
0
    return STATUS(IOError, "Unable to parse PB from path", reader_->filename());
550
0
  }
551
552
661k
  return Status::OK();
553
661k
}
554
555
2
Status ReadablePBContainerFile::Dump(ostream* os, bool oneline) {
556
  // Use the embedded protobuf information from the container file to
557
  // create the appropriate kind of protobuf Message.
558
  //
559
  // Loading the schemas into a DescriptorDatabase (and not directly into
560
  // a DescriptorPool) defers resolution until FindMessageTypeByName()
561
  // below, allowing for schemas to be loaded in any order.
562
2
  SimpleDescriptorDatabase db;
563
8
  for (int i = 0; i < protos()->file_size(); 
i++6
) {
564
6
    if (!db.Add(protos()->file(i))) {
565
0
      return STATUS(Corruption, "Descriptor not loaded", Substitute(
566
0
          "Could not load descriptor for PB type $0 referenced in container file",
567
0
          pb_type()));
568
0
    }
569
6
  }
570
2
  DescriptorPool pool(&db);
571
2
  const Descriptor* desc = pool.FindMessageTypeByName(pb_type());
572
2
  if (!desc) {
573
0
    return STATUS(NotFound, "Descriptor not found", Substitute(
574
0
        "Could not find descriptor for PB type $0 referenced in container file",
575
0
        pb_type()));
576
0
  }
577
2
  DynamicMessageFactory factory;
578
2
  const Message* prototype = factory.GetPrototype(desc);
579
2
  if (!prototype) {
580
0
    return STATUS(NotSupported, "Descriptor not supported", Substitute(
581
0
        "Descriptor $0 referenced in container file not supported",
582
0
        pb_type()));
583
0
  }
584
2
  std::unique_ptr<Message> msg(prototype->New());
585
586
  // Dump each message in the container file.
587
2
  int count = 0;
588
2
  Status s;
589
2
  for (s = ReadNextPB(msg.get());
590
6
      s.ok();
591
4
      s = ReadNextPB(msg.get())) {
592
4
    if (oneline) {
593
2
      *os << count++ << "\t" << msg->ShortDebugString() << endl;
594
2
    } else {
595
2
      *os << pb_type_ << " " << count << endl;
596
2
      *os << "-------" << endl;
597
2
      *os << msg->DebugString() << endl;
598
2
      count++;
599
2
    }
600
4
  }
601
2
  return s.IsEndOfFile() ? Status::OK() : 
s0
;
602
2
}
603
604
661k
Status ReadablePBContainerFile::Close() {
605
661k
  std::unique_ptr<RandomAccessFile> deleter;
606
661k
  deleter.swap(reader_);
607
661k
  return Status::OK();
608
661k
}
609
610
Status ReadablePBContainerFile::ValidateAndRead(size_t length, EofOK eofOK,
611
                                                Slice* result,
612
2.31M
                                                std::unique_ptr<uint8_t[]>* scratch) {
613
  // Validate the read length using the file size.
614
2.31M
  uint64_t file_size = VERIFY_RESULT(reader_->Size());
615
2.31M
  if (offset_ + length > file_size) {
616
7
    switch (eofOK) {
617
4
      case EOF_OK:
618
4
        return STATUS(EndOfFile, "Reached end of file");
619
3
      case EOF_NOT_OK:
620
3
        return STATUS(Corruption, "File size not large enough to be valid",
621
0
                                  Substitute("Proto container file $0: "
622
0
                                      "tried to read $0 bytes at offset "
623
0
                                      "$1 but file size is only $2",
624
0
                                      reader_->filename(), length,
625
0
                                      offset_, file_size));
626
0
      default:
627
0
        LOG(FATAL) << "Unknown value for eofOK: " << eofOK;
628
7
    }
629
7
  }
630
631
  // Perform the read.
632
2.31M
  Slice s;
633
2.31M
  std::unique_ptr<uint8_t[]> local_scratch(new uint8_t[length]);
634
2.31M
  RETURN_NOT_OK(reader_->Read(offset_, length, &s, local_scratch.get()));
635
636
  // Sanity check the result.
637
2.31M
  if (PREDICT_FALSE(s.size() < length)) {
638
0
    return STATUS(Corruption, "Unexpected short read", Substitute(
639
0
        "Proto container file $0: tried to read $1 bytes; got $2 bytes",
640
0
        reader_->filename(), length, s.size()));
641
0
  }
642
643
2.31M
  *result = s;
644
2.31M
  scratch->swap(local_scratch);
645
2.31M
  offset_ += s.size();
646
2.31M
  return Status::OK();
647
2.31M
}
648
649
namespace {
650
651
Status ReadPBContainer(
652
356k
    Env* env, const std::string& path, Message* msg, const std::string* pb_type_name = nullptr) {
653
356k
  std::unique_ptr<RandomAccessFile> file;
654
356k
  RETURN_NOT_OK(env->NewRandomAccessFile(path, &file));
655
656
330k
  ReadablePBContainerFile pb_file(std::move(file));
657
330k
  RETURN_NOT_OK(pb_file.Init());
658
659
330k
  if (pb_type_name && 
pb_file.pb_type() != *pb_type_name0
) {
660
0
    WARN_NOT_OK(pb_file.Close(), "Could not Close() PB container file");
661
0
    return STATUS(InvalidArgument,
662
0
                  Substitute("Wrong PB type: $0, expected $1", pb_file.pb_type(), *pb_type_name));
663
0
  }
664
665
330k
  RETURN_NOT_OK(pb_file.ReadNextPB(msg));
666
330k
  return pb_file.Close();
667
330k
}
668
669
} // namespace
670
671
356k
Status ReadPBContainerFromPath(Env* env, const std::string& path, Message* msg) {
672
356k
  return ReadPBContainer(env, path, msg);
673
356k
}
674
675
Status ReadPBContainerFromPath(
676
0
    Env* env, const std::string& path, const std::string& pb_type_name, Message* msg) {
677
0
  return ReadPBContainer(env, path, msg, &pb_type_name);
678
0
}
679
680
Status WritePBContainerToPath(Env* env, const std::string& path,
681
                              const Message& msg,
682
                              CreateMode create,
683
2.10M
                              SyncMode sync) {
684
2.10M
  TRACE_EVENT2("io", "WritePBContainerToPath",
685
2.10M
               "path", path,
686
2.10M
               "msg_type", msg.GetTypeName());
687
688
2.10M
  if (create == NO_OVERWRITE && 
env->FileExists(path)17.9k
) {
689
1
    return STATUS(AlreadyPresent, Substitute("File $0 already exists", path));
690
1
  }
691
692
2.10M
  const string tmp_template = path + kTmpTemplateSuffix;
693
2.10M
  string tmp_path;
694
695
2.10M
  std::unique_ptr<WritableFile> file;
696
2.10M
  RETURN_NOT_OK(env->NewTempWritableFile(WritableFileOptions(), tmp_template, &tmp_path, &file));
697
2.10M
  env_util::ScopedFileDeleter tmp_deleter(env, tmp_path);
698
699
2.10M
  WritablePBContainerFile pb_file(std::move(file));
700
2.10M
  RETURN_NOT_OK(pb_file.Init(msg));
701
2.10M
  RETURN_NOT_OK(pb_file.Append(msg));
702
2.10M
  
if (2.10M
sync == pb_util::SYNC2.10M
) {
703
2.10M
    RETURN_NOT_OK(pb_file.Sync());
704
2.10M
  }
705
2.10M
  RETURN_NOT_OK(pb_file.Close());
706
2.10M
  RETURN_NOT_OK_PREPEND(env->RenameFile(tmp_path, path),
707
2.10M
                        "Failed to rename tmp file to " + path);
708
2.10M
  tmp_deleter.Cancel();
709
2.10M
  if (
sync == pb_util::SYNC2.10M
) {
710
2.10M
    RETURN_NOT_OK_PREPEND(env->SyncDir(DirName(path)),
711
2.10M
                          "Failed to SyncDir() parent of " + path);
712
2.10M
  }
713
2.10M
  return Status::OK();
714
2.10M
}
715
716
bool ArePBsEqual(const google::protobuf::Message& prev_pb,
717
                 const google::protobuf::Message& new_pb,
718
692k
                 std::string* diff_str) {
719
692k
  google::protobuf::util::MessageDifferencer md;
720
692k
  if (diff_str) {
721
0
    md.ReportDifferencesToString(diff_str);
722
0
  }
723
692k
  return md.Compare(prev_pb, new_pb);
724
692k
}
725
726
} // namespace pb_util
727
} // namespace yb