1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
#[cfg(feature = "management")]
use crate::skywalking_proto::v3::management_service_client::ManagementServiceClient;
use crate::{
reporter::{CollectItem, Report},
skywalking_proto::v3::{
log_report_service_client::LogReportServiceClient,
meter_report_service_client::MeterReportServiceClient,
trace_segment_report_service_client::TraceSegmentReportServiceClient, LogData, MeterData,
SegmentObject,
},
};
use futures_util::stream;
use std::{
collections::LinkedList,
error::Error,
future::{pending, Future},
mem::take,
pin::Pin,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
task::{Context, Poll},
};
use tokio::{
select,
sync::{mpsc, Mutex},
task::JoinHandle,
try_join,
};
use tonic::{
async_trait,
metadata::{Ascii, MetadataValue},
service::{interceptor::InterceptedService, Interceptor},
transport::{self, Channel, Endpoint},
Request, Status,
};
pub trait CollectItemProduce: Send + Sync + 'static {
fn produce(&self, item: CollectItem) -> Result<(), Box<dyn Error>>;
}
impl CollectItemProduce for () {
fn produce(&self, _item: CollectItem) -> Result<(), Box<dyn Error>> {
Ok(())
}
}
impl CollectItemProduce for mpsc::UnboundedSender<CollectItem> {
fn produce(&self, item: CollectItem) -> Result<(), Box<dyn Error>> {
Ok(self.send(item)?)
}
}
#[async_trait]
pub trait CollectItemConsume: Send + Sync + 'static {
async fn consume(&mut self) -> Result<Option<CollectItem>, Box<dyn Error + Send>>;
async fn try_consume(&mut self) -> Result<Option<CollectItem>, Box<dyn Error + Send>>;
}
#[async_trait]
impl CollectItemConsume for () {
async fn consume(&mut self) -> Result<Option<CollectItem>, Box<dyn Error + Send>> {
Ok(None)
}
async fn try_consume(&mut self) -> Result<Option<CollectItem>, Box<dyn Error + Send>> {
Ok(None)
}
}
#[async_trait]
impl CollectItemConsume for mpsc::UnboundedReceiver<CollectItem> {
async fn consume(&mut self) -> Result<Option<CollectItem>, Box<dyn Error + Send>> {
Ok(self.recv().await)
}
async fn try_consume(&mut self) -> Result<Option<CollectItem>, Box<dyn Error + Send>> {
use mpsc::error::TryRecvError;
match self.try_recv() {
Ok(item) => Ok(Some(item)),
Err(e) => match e {
TryRecvError::Empty => Ok(None),
TryRecvError::Disconnected => Err(Box::new(e)),
},
}
}
}
type DynInterceptHandler = dyn Fn(Request<()>) -> Result<Request<()>, Status> + Send + Sync;
#[derive(Default, Clone)]
struct CustomInterceptor {
authentication: Option<Arc<String>>,
custom_intercept: Option<Arc<DynInterceptHandler>>,
}
impl Interceptor for CustomInterceptor {
fn call(&mut self, mut request: tonic::Request<()>) -> Result<tonic::Request<()>, Status> {
if let Some(authentication) = &self.authentication {
if let Ok(authentication) = authentication.parse::<MetadataValue<Ascii>>() {
request
.metadata_mut()
.insert("authentication", authentication);
}
}
if let Some(custom_intercept) = &self.custom_intercept {
request = custom_intercept(request)?;
}
Ok(request)
}
}
struct Inner<P, C> {
producer: P,
consumer: Mutex<Option<C>>,
is_reporting: AtomicBool,
is_closed: AtomicBool,
}
pub type DynErrHandle = dyn Fn(Box<dyn Error>) + Send + Sync + 'static;
pub struct GrpcReporter<P, C> {
inner: Arc<Inner<P, C>>,
err_handle: Arc<Option<Box<DynErrHandle>>>,
channel: Channel,
interceptor: CustomInterceptor,
}
impl GrpcReporter<mpsc::UnboundedSender<CollectItem>, mpsc::UnboundedReceiver<CollectItem>> {
pub fn new(channel: Channel) -> Self {
let (p, c) = mpsc::unbounded_channel();
Self::new_with_pc(channel, p, c)
}
pub async fn connect(
address: impl TryInto<Endpoint, Error = transport::Error>,
) -> crate::Result<Self> {
let endpoint = address.try_into()?;
let channel = endpoint.connect().await?;
Ok(Self::new(channel))
}
}
impl<P: CollectItemProduce, C: CollectItemConsume> GrpcReporter<P, C> {
pub fn new_with_pc(channel: Channel, producer: P, consumer: C) -> Self {
Self {
inner: Arc::new(Inner {
producer,
consumer: Mutex::new(Some(consumer)),
is_reporting: Default::default(),
is_closed: Default::default(),
}),
err_handle: Default::default(),
channel,
interceptor: Default::default(),
}
}
pub fn with_err_handle(
mut self,
handle: impl Fn(Box<dyn Error>) + Send + Sync + 'static,
) -> Self {
self.err_handle = Arc::new(Some(Box::new(handle)));
self
}
pub fn with_authentication(mut self, authentication: impl Into<String>) -> Self {
self.interceptor.authentication = Some(Arc::new(authentication.into()));
self
}
pub fn with_custom_intercept(
mut self,
custom_intercept: impl Fn(Request<()>) -> Result<Request<()>, Status> + Send + Sync + 'static,
) -> Self {
self.interceptor.custom_intercept = Some(Arc::new(custom_intercept));
self
}
pub async fn reporting(&self) -> Reporting<P, C> {
if self.inner.is_reporting.swap(true, Ordering::Relaxed) {
panic!("reporting already called");
}
Reporting {
rb: ReporterAndBuffer {
inner: Arc::clone(&self.inner),
status_handle: None,
trace_buffer: Default::default(),
log_buffer: Default::default(),
meter_buffer: Default::default(),
trace_client: TraceSegmentReportServiceClient::with_interceptor(
self.channel.clone(),
self.interceptor.clone(),
),
log_client: LogReportServiceClient::with_interceptor(
self.channel.clone(),
self.interceptor.clone(),
),
meter_client: MeterReportServiceClient::with_interceptor(
self.channel.clone(),
self.interceptor.clone(),
),
#[cfg(feature = "management")]
management_client: ManagementServiceClient::with_interceptor(
self.channel.clone(),
self.interceptor.clone(),
),
},
shutdown_signal: Box::pin(pending()),
consumer: self.inner.consumer.lock().await.take().unwrap(),
}
}
}
impl<P, C> Clone for GrpcReporter<P, C> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
err_handle: self.err_handle.clone(),
channel: self.channel.clone(),
interceptor: self.interceptor.clone(),
}
}
}
impl<P: CollectItemProduce, C: CollectItemConsume> Report for GrpcReporter<P, C> {
fn report(&self, item: CollectItem) {
if !self.inner.is_closed.load(Ordering::Relaxed) {
if let Err(e) = self.inner.producer.produce(item) {
if let Some(handle) = self.err_handle.as_deref() {
handle(e);
}
}
}
}
}
struct ReporterAndBuffer<P, C> {
inner: Arc<Inner<P, C>>,
status_handle: Option<Box<dyn Fn(tonic::Status) + Send + 'static>>,
trace_buffer: LinkedList<SegmentObject>,
log_buffer: LinkedList<LogData>,
meter_buffer: LinkedList<MeterData>,
trace_client: TraceSegmentReportServiceClient<InterceptedService<Channel, CustomInterceptor>>,
log_client: LogReportServiceClient<InterceptedService<Channel, CustomInterceptor>>,
meter_client: MeterReportServiceClient<InterceptedService<Channel, CustomInterceptor>>,
#[cfg(feature = "management")]
#[cfg_attr(docsrs, doc(cfg(feature = "management")))]
management_client: ManagementServiceClient<InterceptedService<Channel, CustomInterceptor>>,
}
impl<P: CollectItemProduce, C: CollectItemConsume> ReporterAndBuffer<P, C> {
async fn report(&mut self, item: CollectItem) {
match item {
CollectItem::Trace(item) => {
self.trace_buffer.push_back(*item);
}
CollectItem::Log(item) => {
self.log_buffer.push_back(*item);
}
CollectItem::Meter(item) => {
self.meter_buffer.push_back(*item);
}
#[cfg(feature = "management")]
CollectItem::Instance(item) => {
if let Err(e) = self
.management_client
.report_instance_properties(*item)
.await
{
if let Some(status_handle) = &self.status_handle {
status_handle(e);
}
}
}
#[cfg(feature = "management")]
CollectItem::Ping(item) => {
if let Err(e) = self.management_client.keep_alive(*item).await {
if let Some(status_handle) = &self.status_handle {
status_handle(e);
}
}
}
}
if !self.trace_buffer.is_empty() {
let buffer = take(&mut self.trace_buffer);
if let Err(e) = self.trace_client.collect(stream::iter(buffer)).await {
if let Some(status_handle) = &self.status_handle {
status_handle(e);
}
}
}
if !self.log_buffer.is_empty() {
let buffer = take(&mut self.log_buffer);
if let Err(e) = self.log_client.collect(stream::iter(buffer)).await {
if let Some(status_handle) = &self.status_handle {
status_handle(e);
}
}
}
if !self.meter_buffer.is_empty() {
let buffer = take(&mut self.meter_buffer);
if let Err(e) = self.meter_client.collect(stream::iter(buffer)).await {
if let Some(status_handle) = &self.status_handle {
status_handle(e);
}
}
}
}
}
pub struct Reporting<P, C> {
rb: ReporterAndBuffer<P, C>,
consumer: C,
shutdown_signal: Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>>,
}
impl<P: CollectItemProduce, C: CollectItemConsume> Reporting<P, C> {
pub fn with_graceful_shutdown(
mut self,
shutdown_signal: impl Future<Output = ()> + Send + Sync + 'static,
) -> Self {
self.shutdown_signal = Box::pin(shutdown_signal);
self
}
pub fn with_status_handle(mut self, handle: impl Fn(tonic::Status) + Send + 'static) -> Self {
self.rb.status_handle = Some(Box::new(handle));
self
}
pub fn spawn(self) -> ReportingJoinHandle {
ReportingJoinHandle {
handle: tokio::spawn(self.start()),
}
}
pub async fn start(self) -> crate::Result<()> {
let (shutdown_tx, mut shutdown_rx) = mpsc::unbounded_channel();
let Reporting {
mut rb,
mut consumer,
shutdown_signal,
} = self;
let work_fut = async move {
loop {
select! {
item = consumer.consume() => {
match item {
Ok(Some(item)) => {
rb.report(item).await;
}
Ok(None) => break,
Err(err) => return Err(crate::Error::Other(err)),
}
}
_ = shutdown_rx.recv() => break,
}
}
rb.inner.is_closed.store(true, Ordering::Relaxed);
loop {
match consumer.try_consume().await {
Ok(Some(item)) => {
rb.report(item).await;
}
Ok(None) => break,
Err(err) => return Err(err.into()),
}
}
Ok::<_, crate::Error>(())
};
let shutdown_fut = async move {
shutdown_signal.await;
shutdown_tx
.send(())
.map_err(|e| crate::Error::Other(Box::new(e)))?;
Ok(())
};
try_join!(work_fut, shutdown_fut)?;
Ok(())
}
}
pub struct ReportingJoinHandle {
handle: JoinHandle<crate::Result<()>>,
}
impl Future for ReportingJoinHandle {
type Output = crate::Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.handle).poll(cx).map(|r| r?)
}
}