use std::sync::Arc;
use std::time::{Duration, Instant};
use futures::future::BoxFuture;
use serde_json::Value;
use crate::api::{Api, GraphQLResponse};
use crate::config::SkyWalkingConfig;
use crate::core::lifecycle::CloseGroup;
use crate::core::{Error, HealthStatus, HttpTransport, Result};
use crate::logging::{AttrValue, Attributes, BatchOptions, BatchingLogClient, LogClient};
use crate::logs::{SkyWalkingLogExporter, SkyWalkingLogQueryClient};
use crate::query::SkyWalkingQueryClient;
use crate::setup::init_tracing_with_config;
use crate::traces::SkyWalkingTraceQueryClient;
use crate::tracing::{TracingConfig, TracingHandle};
#[derive(Clone, Default)]
pub struct SkyWalkingLogClientOptions {
pub service_name: Option<String>,
pub service_instance: Option<String>,
pub batch: BatchOptions,
pub resource: Attributes,
}
impl std::fmt::Debug for SkyWalkingLogClientOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SkyWalkingLogClientOptions")
.field("service_name", &self.service_name)
.field("service_instance", &self.service_instance)
.field("batch", &self.batch)
.field("resource", &self.resource)
.finish()
}
}
impl SkyWalkingLogClientOptions {
pub fn service(name: impl Into<String>) -> Self {
SkyWalkingLogClientOptions {
service_name: Some(name.into()),
..Default::default()
}
}
pub fn instance(mut self, instance: impl Into<String>) -> Self {
self.service_instance = Some(instance.into());
self
}
pub fn batch(mut self, batch: BatchOptions) -> Self {
self.batch = batch;
self
}
pub fn resource_attribute(
mut self,
key: impl Into<String>,
value: impl Into<AttrValue>,
) -> Self {
self.resource.insert(key.into(), value.into());
self
}
fn build(self, exporter: SkyWalkingLogExporter) -> Result<BatchingLogClient> {
let mut resource = self.resource;
if let Some(name) = &self.service_name {
resource.insert("service.name".into(), name.clone().into());
}
if let Some(instance) = self.service_instance {
resource.insert("service.instance.id".into(), instance.into());
}
BatchingLogClient::builder(Arc::new(exporter))
.batch_options(self.batch)
.resource(resource)
.build()
}
}
pub fn create_log_client(
config: SkyWalkingConfig,
options: SkyWalkingLogClientOptions,
) -> Result<BatchingLogClient> {
let api = Arc::new(Api::new(config)?);
let exporter = SkyWalkingLogExporter::new(api, options.service_name.clone(), true);
options.build(exporter)
}
#[derive(Debug, Clone)]
pub struct SkyWalkingClient {
inner: Arc<Inner>,
}
#[derive(Debug)]
struct Inner {
api: Arc<Api>,
query: SkyWalkingQueryClient,
traces: SkyWalkingTraceQueryClient,
logs: SkyWalkingLogQueryClient,
on_close: CloseGroup,
}
impl SkyWalkingClient {
pub fn new(config: SkyWalkingConfig) -> Result<Self> {
config.validate()?;
let backend = config.trace_backend();
let api = Arc::new(Api::new(config)?);
let query = SkyWalkingQueryClient::new(Arc::clone(&api));
Ok(SkyWalkingClient {
inner: Arc::new(Inner {
traces: SkyWalkingTraceQueryClient::new(Arc::clone(&api), backend),
logs: SkyWalkingLogQueryClient::new(query.clone()),
query,
api,
on_close: CloseGroup::new(),
}),
})
}
pub fn from_env() -> Result<Self> {
Self::new(SkyWalkingConfig::from_env()?)
}
pub fn config(&self) -> &SkyWalkingConfig {
&self.inner.api.config
}
pub fn transport(&self) -> &HttpTransport {
&self.inner.api.transport
}
pub fn on_close<F>(&self, f: F)
where
F: FnOnce() -> BoxFuture<'static, ()> + Send + 'static,
{
self.inner.on_close.register(f);
}
pub fn query(&self) -> &SkyWalkingQueryClient {
&self.inner.query
}
pub fn traces(&self) -> &SkyWalkingTraceQueryClient {
&self.inner.traces
}
pub fn logs(&self) -> &SkyWalkingLogQueryClient {
&self.inner.logs
}
pub async fn health(&self) -> Result<HealthStatus> {
let resp = self
.transport()
.get("/healthcheck")
.operation("health")
.ok_status(404)
.ok_status(503)
.send()
.await;
let resp = match resp {
Ok(r) => r,
Err(e) => return HealthStatus::from_error(e),
};
match resp.status() {
503 => Ok(HealthStatus::unhealthy("unhealthy").with_detail("httpStatus", "503")),
404 => {
let check = match self
.inner
.api
.field(
"{checkHealth{score details}}",
Value::Null,
"checkHealth",
"health",
)
.await
{
Ok(v) => v,
Err(e) => return HealthStatus::from_error(e),
};
let score = check.get("score").and_then(Value::as_i64).unwrap_or(-1);
let details = check
.get("details")
.and_then(Value::as_str)
.unwrap_or_default();
if score == 0 {
return Ok(HealthStatus::healthy("ok"));
}
let status =
HealthStatus::unhealthy("unhealthy").with_detail("score", score.to_string());
Ok(if details.is_empty() {
status
} else {
status.with_detail("details", details)
})
}
_ => Ok(HealthStatus::healthy("ok")),
}
}
pub async fn ping(&self) -> Result<Duration> {
let started = Instant::now();
self.inner.api.time_info("ping").await?;
Ok(started.elapsed())
}
pub async fn server_version(&self) -> Result<String> {
let v = self
.inner
.api
.field("{version}", Value::Null, "version", "serverVersion")
.await?;
v.as_str()
.filter(|s| !s.is_empty())
.map(str::to_owned)
.ok_or_else(|| {
Error::unsupported("serverVersion: the service does not report a version")
})
}
pub async fn graphql(&self, query: &str, variables: Value) -> Result<GraphQLResponse> {
self.inner.query.graphql(query, variables).await
}
pub fn log_client(&self, options: SkyWalkingLogClientOptions) -> Result<BatchingLogClient> {
let exporter = SkyWalkingLogExporter::new(
Arc::clone(&self.inner.api),
options.service_name.clone(),
false,
);
let client = options.build(exporter)?;
let owned = client.clone();
self.on_close(move || {
Box::pin(async move {
let _ = owned.close().await;
})
});
Ok(client)
}
pub fn init_tracing(&self, config: TracingConfig) -> Result<TracingHandle> {
let handle = init_tracing_with_config(config, self.config())?;
let owned = handle.clone();
self.on_close(move || {
Box::pin(async move {
let _ = owned.shutdown().await;
})
});
Ok(handle)
}
pub async fn close(&self) {
self.inner.on_close.close().await;
self.inner.api.transport.close();
}
pub fn is_closed(&self) -> bool {
self.inner.api.transport.is_closed()
}
}