meta_srv/utils/
etcd.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 common_meta::kv_backend::etcd::create_etcd_tls_options;
16use etcd_client::{Client, ConnectOptions};
17use servers::tls::{TlsMode, TlsOption};
18use snafu::ResultExt;
19
20use crate::error::{self, BuildTlsOptionsSnafu, Result};
21
22/// Creates an etcd client with TLS configuration.
23pub async fn create_etcd_client_with_tls(
24    store_addrs: &[String],
25    tls_config: Option<&TlsOption>,
26) -> Result<Client> {
27    let etcd_endpoints = store_addrs
28        .iter()
29        .map(|x| x.trim())
30        .filter(|x| !x.is_empty())
31        .collect::<Vec<_>>();
32
33    let connect_options = tls_config
34        .map(|c| create_etcd_tls_options(&convert_tls_option(c)))
35        .transpose()
36        .context(BuildTlsOptionsSnafu)?
37        .flatten()
38        .map(|tls_options| ConnectOptions::new().with_tls(tls_options));
39
40    Client::connect(&etcd_endpoints, connect_options)
41        .await
42        .context(error::ConnectEtcdSnafu)
43}
44
45fn convert_tls_option(tls_option: &TlsOption) -> common_meta::kv_backend::etcd::TlsOption {
46    let mode = match tls_option.mode {
47        TlsMode::Disable => common_meta::kv_backend::etcd::TlsMode::Disable,
48        _ => common_meta::kv_backend::etcd::TlsMode::Require,
49    };
50    common_meta::kv_backend::etcd::TlsOption {
51        mode,
52        cert_path: tls_option.cert_path.clone(),
53        key_path: tls_option.key_path.clone(),
54        ca_cert_path: tls_option.ca_cert_path.clone(),
55    }
56}