Skip to main content

cmd/datanode/
builder.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::sync::Arc;
16
17use cache::build_datanode_cache_registry;
18use catalog::kvbackend::new_read_only_meta_kv_backend;
19use common_base::Plugins;
20use common_meta::cache::LayeredCacheRegistryBuilder;
21use common_telemetry::info;
22use common_version::{short_version, verbose_version};
23use datanode::datanode::DatanodeBuilder;
24use datanode::service::DatanodeServiceBuilder;
25use meta_client::MetaClientType;
26use snafu::{OptionExt, ResultExt};
27use tracing_appender::non_blocking::WorkerGuard;
28
29use crate::datanode::{APP_NAME, DatanodeOptions, Instance};
30use crate::error::{MetaClientInitSnafu, MissingConfigSnafu, Result, StartDatanodeSnafu};
31use crate::{create_resource_limit_metrics, log_versions, maybe_activate_heap_profile};
32
33/// Builder for Datanode instance.
34pub struct InstanceBuilder {
35    guard: Vec<WorkerGuard>,
36    opts: DatanodeOptions,
37    datanode_builder: DatanodeBuilder,
38}
39
40impl InstanceBuilder {
41    /// Try to create a new [InstanceBuilder], and do some initialization work like allocating
42    /// runtime resources, setting up global logging and plugins, etc.
43    pub async fn try_new_with_init(
44        mut opts: DatanodeOptions,
45        mut plugins: Plugins,
46    ) -> Result<Self> {
47        let guard = Self::init(&mut opts, &mut plugins).await?;
48
49        let mut datanode_builder = Self::datanode_builder(&opts, &plugins).await?;
50
51        plugins::setup_datanode_plugins_post_build(&mut plugins, &opts.plugins, &datanode_builder)
52            .await
53            .context(StartDatanodeSnafu)?;
54        datanode_builder.set_plugins(plugins);
55
56        Ok(Self {
57            guard,
58            opts,
59            datanode_builder,
60        })
61    }
62
63    async fn init(opts: &mut DatanodeOptions, plugins: &mut Plugins) -> Result<Vec<WorkerGuard>> {
64        common_runtime::init_global_runtimes(&opts.runtime);
65
66        let dn_opts = &mut opts.component;
67        let guard = common_telemetry::init_global_logging(
68            APP_NAME,
69            &dn_opts.logging,
70            &dn_opts.tracing,
71            dn_opts.node_id.map(|x| x.to_string()),
72            None,
73        );
74
75        log_versions(verbose_version(), short_version(), APP_NAME);
76        maybe_activate_heap_profile(&dn_opts.memory);
77        create_resource_limit_metrics(APP_NAME);
78
79        plugins::setup_datanode_plugins_pre_build(plugins, &opts.plugins, dn_opts)
80            .await
81            .context(StartDatanodeSnafu)?;
82
83        dn_opts.grpc.detect_server_addr();
84
85        info!("Initialized Datanode instance with {:#?}", opts);
86        Ok(guard)
87    }
88
89    async fn datanode_builder(
90        opts: &DatanodeOptions,
91        plugins: &Plugins,
92    ) -> Result<DatanodeBuilder> {
93        let dn_opts = &opts.component;
94
95        let member_id = dn_opts
96            .node_id
97            .context(MissingConfigSnafu { msg: "'node_id'" })?;
98        let meta_client_options = dn_opts.meta_client.as_ref().context(MissingConfigSnafu {
99            msg: "meta client options",
100        })?;
101        let client = meta_client::create_meta_client(
102            MetaClientType::Datanode { member_id },
103            meta_client_options,
104            Some(plugins),
105            None,
106        )
107        .await
108        .context(MetaClientInitSnafu)?;
109
110        let backend = new_read_only_meta_kv_backend(client.clone());
111        let mut builder = DatanodeBuilder::new(dn_opts.clone(), plugins.clone(), backend.clone());
112
113        let registry = Arc::new(
114            LayeredCacheRegistryBuilder::default()
115                .add_cache_registry(build_datanode_cache_registry(backend))
116                .build(),
117        );
118        builder
119            .with_cache_registry(registry)
120            .with_meta_client(client.clone());
121        Ok(builder)
122    }
123
124    /// Get the mutable builder for Datanode, in case you want to change some fields before the
125    /// final construction.
126    pub fn mut_datanode_builder(&mut self) -> &mut DatanodeBuilder {
127        &mut self.datanode_builder
128    }
129
130    /// Try to build the Datanode instance.
131    pub async fn build(self) -> Result<Instance> {
132        let mut datanode = self
133            .datanode_builder
134            .build()
135            .await
136            .context(StartDatanodeSnafu)?;
137
138        let services = DatanodeServiceBuilder::new(&self.opts.component)
139            .with_default_grpc_server(&datanode.region_server())
140            .enable_http_service()
141            .build()
142            .context(StartDatanodeSnafu)?;
143        datanode.setup_services(services);
144
145        Ok(Instance::new(datanode, self.guard))
146    }
147}