blob: af92ae6d9ea18829fc9b956aea29696c84bc868e [file] [log] [blame]
Vizerai12d1fc62016-09-09 14:22:19 -07001/*
2 *
Jan Tattermusch7897ae92017-06-07 22:57:36 +02003 * Copyright 2016 gRPC authors.
Vizerai12d1fc62016-09-09 14:22:19 -07004 *
Jan Tattermusch7897ae92017-06-07 22:57:36 +02005 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
Vizerai12d1fc62016-09-09 14:22:19 -07008 *
Jan Tattermusch7897ae92017-06-07 22:57:36 +02009 * http://www.apache.org/licenses/LICENSE-2.0
Vizerai12d1fc62016-09-09 14:22:19 -070010 *
Jan Tattermusch7897ae92017-06-07 22:57:36 +020011 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
Vizerai12d1fc62016-09-09 14:22:19 -070016 *
17 */
18
19#include "src/core/ext/census/trace_context.h"
20
21#include <grpc/census.h>
22#include <grpc/support/log.h>
23#include <stdbool.h>
24
25#include "third_party/nanopb/pb_decode.h"
26#include "third_party/nanopb/pb_encode.h"
27
28// This function assumes the TraceContext is valid.
29size_t encode_trace_context(google_trace_TraceContext *ctxt, uint8_t *buffer,
30 const size_t buf_size) {
31 // Create a stream that will write to our buffer.
32 pb_ostream_t stream = pb_ostream_from_buffer(buffer, buf_size);
33
34 // encode message
35 bool status = pb_encode(&stream, google_trace_TraceContext_fields, ctxt);
36
37 if (!status) {
38 gpr_log(GPR_DEBUG, "TraceContext encoding failed: %s",
39 PB_GET_ERROR(&stream));
40 return 0;
41 }
42
43 return stream.bytes_written;
44}
45
46bool decode_trace_context(google_trace_TraceContext *ctxt, uint8_t *buffer,
47 const size_t nbytes) {
48 // Create a stream that reads nbytes from the buffer.
49 pb_istream_t stream = pb_istream_from_buffer(buffer, nbytes);
50
51 // decode message
52 bool status = pb_decode(&stream, google_trace_TraceContext_fields, ctxt);
53
54 if (!status) {
55 gpr_log(GPR_DEBUG, "TraceContext decoding failed: %s",
56 PB_GET_ERROR(&stream));
Vizeraicb849ef2016-09-09 14:39:31 -070057 return false;
Vizerai12d1fc62016-09-09 14:22:19 -070058 }
59
60 // check fields
Vizerai864db532017-01-20 18:30:44 -080061 if (!ctxt->has_trace_id_hi || !ctxt->has_trace_id_lo) {
Vizerai12d1fc62016-09-09 14:22:19 -070062 gpr_log(GPR_DEBUG, "Invalid TraceContext: missing trace_id");
63 return false;
64 }
65 if (!ctxt->has_span_id) {
66 gpr_log(GPR_DEBUG, "Invalid TraceContext: missing span_id");
67 return false;
68 }
69
70 return true;
71}