meta_srv/service/admin/
node_lease.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16
17use serde::{Deserialize, Serialize};
18use snafu::ResultExt;
19use tonic::codegen::http;
20
21use crate::cluster::MetaPeerClientRef;
22use crate::error::{self, Result};
23use crate::key::{DatanodeLeaseKey, LeaseValue};
24use crate::lease;
25use crate::service::admin::HttpHandler;
26
27pub struct NodeLeaseHandler {
28    pub meta_peer_client: MetaPeerClientRef,
29}
30
31#[async_trait::async_trait]
32impl HttpHandler for NodeLeaseHandler {
33    async fn handle(
34        &self,
35        _: &str,
36        _: http::Method,
37        _: &HashMap<String, String>,
38    ) -> Result<http::Response<String>> {
39        let leases = lease::alive_datanodes(&self.meta_peer_client, u64::MAX).await?;
40        let leases = leases
41            .into_iter()
42            .map(|(k, v)| HumanLease {
43                name: k,
44                human_time: common_time::Timestamp::new_millisecond(v.timestamp_millis)
45                    .to_local_string(),
46                lease: v,
47            })
48            .collect::<Vec<_>>();
49        let result = LeaseValues { leases }.try_into()?;
50
51        http::Response::builder()
52            .status(http::StatusCode::OK)
53            .body(result)
54            .context(error::InvalidHttpBodySnafu)
55    }
56}
57
58#[derive(Debug, Serialize, Deserialize)]
59pub struct HumanLease {
60    pub name: DatanodeLeaseKey,
61    pub human_time: String,
62    pub lease: LeaseValue,
63}
64
65#[derive(Debug, Serialize, Deserialize)]
66#[serde(transparent)]
67pub struct LeaseValues {
68    pub leases: Vec<HumanLease>,
69}
70
71impl TryFrom<LeaseValues> for String {
72    type Error = error::Error;
73
74    fn try_from(vals: LeaseValues) -> Result<Self> {
75        serde_json::to_string(&vals).context(error::SerializeToJsonSnafu {
76            input: format!("{vals:?}"),
77        })
78    }
79}