cmd/
flownode.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::fmt::Debug;
16use std::path::Path;
17use std::sync::Arc;
18use std::time::Duration;
19
20use cache::{build_fundamental_cache_registry, with_default_composite_cache_registry};
21use catalog::information_extension::DistributedInformationExtension;
22use catalog::kvbackend::{CachedKvBackendBuilder, KvBackendCatalogManagerBuilder, MetaKvBackend};
23use clap::Parser;
24use client::client_manager::NodeClients;
25use common_base::Plugins;
26use common_config::{Configurable, DEFAULT_DATA_HOME};
27use common_grpc::channel_manager::ChannelConfig;
28use common_meta::cache::{CacheRegistryBuilder, LayeredCacheRegistryBuilder};
29use common_meta::heartbeat::handler::HandlerGroupExecutor;
30use common_meta::heartbeat::handler::invalidate_table_cache::InvalidateCacheHandler;
31use common_meta::heartbeat::handler::parse_mailbox_message::ParseMailboxMessageHandler;
32use common_meta::key::TableMetadataManager;
33use common_meta::key::flow::FlowMetadataManager;
34use common_stat::ResourceStatImpl;
35use common_telemetry::info;
36use common_telemetry::logging::{DEFAULT_LOGGING_DIR, TracingOptions};
37use common_version::{short_version, verbose_version};
38use flow::{
39    FlownodeBuilder, FlownodeInstance, FlownodeServiceBuilder, FrontendClient, FrontendInvoker,
40    get_flow_auth_options,
41};
42use meta_client::{MetaClientOptions, MetaClientType};
43use plugins::flownode::context::GrpcConfigureContext;
44use servers::configurator::GrpcBuilderConfiguratorRef;
45use snafu::{OptionExt, ResultExt, ensure};
46use tracing_appender::non_blocking::WorkerGuard;
47
48use crate::error::{
49    BuildCacheRegistrySnafu, InitMetadataSnafu, LoadLayeredConfigSnafu, MetaClientInitSnafu,
50    MissingConfigSnafu, OtherSnafu, Result, ShutdownFlownodeSnafu, StartFlownodeSnafu,
51};
52use crate::options::{GlobalOptions, GreptimeOptions};
53use crate::{App, create_resource_limit_metrics, log_versions, maybe_activate_heap_profile};
54
55pub const APP_NAME: &str = "greptime-flownode";
56
57type FlownodeOptions = GreptimeOptions<flow::FlownodeOptions>;
58
59pub struct Instance {
60    flownode: FlownodeInstance,
61    // Keep the logging guard to prevent the worker from being dropped.
62    _guard: Vec<WorkerGuard>,
63}
64
65impl Instance {
66    pub fn new(flownode: FlownodeInstance, guard: Vec<WorkerGuard>) -> Self {
67        Self {
68            flownode,
69            _guard: guard,
70        }
71    }
72
73    pub fn flownode(&self) -> &FlownodeInstance {
74        &self.flownode
75    }
76
77    /// allow customizing flownode for downstream projects
78    pub fn flownode_mut(&mut self) -> &mut FlownodeInstance {
79        &mut self.flownode
80    }
81}
82
83#[async_trait::async_trait]
84impl App for Instance {
85    fn name(&self) -> &str {
86        APP_NAME
87    }
88
89    async fn start(&mut self) -> Result<()> {
90        plugins::start_flownode_plugins(self.flownode.flow_engine().plugins().clone())
91            .await
92            .context(StartFlownodeSnafu)?;
93
94        self.flownode.start().await.context(StartFlownodeSnafu)
95    }
96
97    async fn stop(&mut self) -> Result<()> {
98        self.flownode
99            .shutdown()
100            .await
101            .context(ShutdownFlownodeSnafu)
102    }
103}
104
105#[derive(Parser)]
106pub struct Command {
107    #[clap(subcommand)]
108    subcmd: SubCommand,
109}
110
111impl Command {
112    pub async fn build(&self, opts: FlownodeOptions) -> Result<Instance> {
113        self.subcmd.build(opts).await
114    }
115
116    pub fn load_options(&self, global_options: &GlobalOptions) -> Result<FlownodeOptions> {
117        match &self.subcmd {
118            SubCommand::Start(cmd) => cmd.load_options(global_options),
119        }
120    }
121}
122
123#[derive(Parser)]
124enum SubCommand {
125    Start(StartCommand),
126}
127
128impl SubCommand {
129    async fn build(&self, opts: FlownodeOptions) -> Result<Instance> {
130        match self {
131            SubCommand::Start(cmd) => cmd.build(opts).await,
132        }
133    }
134}
135
136#[derive(Debug, Parser, Default)]
137struct StartCommand {
138    /// Flownode's id
139    #[clap(long)]
140    node_id: Option<u64>,
141    /// Bind address for the gRPC server.
142    #[clap(long, alias = "rpc-addr")]
143    rpc_bind_addr: Option<String>,
144    /// The address advertised to the metasrv, and used for connections from outside the host.
145    /// If left empty or unset, the server will automatically use the IP address of the first network interface
146    /// on the host, with the same port number as the one specified in `rpc_bind_addr`.
147    #[clap(long, alias = "rpc-hostname")]
148    rpc_server_addr: Option<String>,
149    /// Metasrv address list;
150    #[clap(long, value_delimiter = ',', num_args = 1..)]
151    metasrv_addrs: Option<Vec<String>>,
152    /// The configuration file for flownode
153    #[clap(short, long)]
154    config_file: Option<String>,
155    /// The prefix of environment variables, default is `GREPTIMEDB_FLOWNODE`;
156    #[clap(long, default_value = "GREPTIMEDB_FLOWNODE")]
157    env_prefix: String,
158    #[clap(long)]
159    http_addr: Option<String>,
160    /// HTTP request timeout in seconds.
161    #[clap(long)]
162    http_timeout: Option<u64>,
163    /// User Provider cfg, for auth, currently only support static user provider
164    #[clap(long)]
165    user_provider: Option<String>,
166}
167
168impl StartCommand {
169    fn load_options(&self, global_options: &GlobalOptions) -> Result<FlownodeOptions> {
170        let mut opts = FlownodeOptions::load_layered_options(
171            self.config_file.as_deref(),
172            self.env_prefix.as_ref(),
173        )
174        .context(LoadLayeredConfigSnafu)?;
175
176        self.merge_with_cli_options(global_options, &mut opts)?;
177
178        Ok(opts)
179    }
180
181    // The precedence order is: cli > config file > environment variables > default values.
182    fn merge_with_cli_options(
183        &self,
184        global_options: &GlobalOptions,
185        opts: &mut FlownodeOptions,
186    ) -> Result<()> {
187        let opts = &mut opts.component;
188
189        if let Some(dir) = &global_options.log_dir {
190            opts.logging.dir.clone_from(dir);
191        }
192
193        // If the logging dir is not set, use the default logs dir in the data home.
194        if opts.logging.dir.is_empty() {
195            opts.logging.dir = Path::new(DEFAULT_DATA_HOME)
196                .join(DEFAULT_LOGGING_DIR)
197                .to_string_lossy()
198                .to_string();
199        }
200
201        if global_options.log_level.is_some() {
202            opts.logging.level.clone_from(&global_options.log_level);
203        }
204
205        opts.tracing = TracingOptions {
206            #[cfg(feature = "tokio-console")]
207            tokio_console_addr: global_options.tokio_console_addr.clone(),
208        };
209
210        if let Some(addr) = &self.rpc_bind_addr {
211            opts.grpc.bind_addr.clone_from(addr);
212        }
213
214        if let Some(server_addr) = &self.rpc_server_addr {
215            opts.grpc.server_addr.clone_from(server_addr);
216        }
217
218        if let Some(node_id) = self.node_id {
219            opts.node_id = Some(node_id);
220        }
221
222        if let Some(metasrv_addrs) = &self.metasrv_addrs {
223            opts.meta_client
224                .get_or_insert_with(MetaClientOptions::default)
225                .metasrv_addrs
226                .clone_from(metasrv_addrs);
227        }
228
229        if let Some(http_addr) = &self.http_addr {
230            opts.http.addr.clone_from(http_addr);
231        }
232
233        if let Some(http_timeout) = self.http_timeout {
234            opts.http.timeout = Duration::from_secs(http_timeout);
235        }
236
237        if let Some(user_provider) = &self.user_provider {
238            opts.user_provider = Some(user_provider.clone());
239        }
240
241        ensure!(
242            opts.node_id.is_some(),
243            MissingConfigSnafu {
244                msg: "Missing node id option"
245            }
246        );
247
248        Ok(())
249    }
250
251    async fn build(&self, opts: FlownodeOptions) -> Result<Instance> {
252        common_runtime::init_global_runtimes(&opts.runtime);
253
254        let guard = common_telemetry::init_global_logging(
255            APP_NAME,
256            &opts.component.logging,
257            &opts.component.tracing,
258            opts.component.node_id.map(|x| x.to_string()),
259            None,
260        );
261
262        log_versions(verbose_version(), short_version(), APP_NAME);
263        maybe_activate_heap_profile(&opts.component.memory);
264        create_resource_limit_metrics(APP_NAME);
265
266        info!("Flownode start command: {:#?}", self);
267        info!("Flownode options: {:#?}", opts);
268
269        let plugin_opts = opts.plugins;
270        let mut opts = opts.component;
271        opts.grpc.detect_server_addr();
272
273        let mut plugins = Plugins::new();
274        plugins::setup_flownode_plugins(&mut plugins, &plugin_opts, &opts)
275            .await
276            .context(StartFlownodeSnafu)?;
277
278        let member_id = opts
279            .node_id
280            .context(MissingConfigSnafu { msg: "'node_id'" })?;
281
282        let meta_config = opts.meta_client.as_ref().context(MissingConfigSnafu {
283            msg: "'meta_client_options'",
284        })?;
285
286        let meta_client = meta_client::create_meta_client(
287            MetaClientType::Flownode { member_id },
288            meta_config,
289            None,
290            None,
291        )
292        .await
293        .context(MetaClientInitSnafu)?;
294
295        let cache_max_capacity = meta_config.metadata_cache_max_capacity;
296        let cache_ttl = meta_config.metadata_cache_ttl;
297        let cache_tti = meta_config.metadata_cache_tti;
298
299        // TODO(discord9): add helper function to ease the creation of cache registry&such
300        let cached_meta_backend =
301            CachedKvBackendBuilder::new(Arc::new(MetaKvBackend::new(meta_client.clone())))
302                .cache_max_capacity(cache_max_capacity)
303                .cache_ttl(cache_ttl)
304                .cache_tti(cache_tti)
305                .build();
306        let cached_meta_backend = Arc::new(cached_meta_backend);
307
308        // Builds cache registry
309        let layered_cache_builder = LayeredCacheRegistryBuilder::default().add_cache_registry(
310            CacheRegistryBuilder::default()
311                .add_cache(cached_meta_backend.clone())
312                .build(),
313        );
314        let fundamental_cache_registry =
315            build_fundamental_cache_registry(Arc::new(MetaKvBackend::new(meta_client.clone())));
316        let layered_cache_registry = Arc::new(
317            with_default_composite_cache_registry(
318                layered_cache_builder.add_cache_registry(fundamental_cache_registry),
319            )
320            .context(BuildCacheRegistrySnafu)?
321            .build(),
322        );
323
324        // flownode's frontend to datanode need not timeout.
325        // Some queries are expected to take long time.
326        let channel_config = ChannelConfig {
327            timeout: None,
328            ..Default::default()
329        };
330        let client = Arc::new(NodeClients::new(channel_config));
331
332        let information_extension = Arc::new(DistributedInformationExtension::new(
333            meta_client.clone(),
334            client.clone(),
335        ));
336        let catalog_manager = KvBackendCatalogManagerBuilder::new(
337            information_extension,
338            cached_meta_backend.clone(),
339            layered_cache_registry.clone(),
340        )
341        .build();
342
343        let table_metadata_manager =
344            Arc::new(TableMetadataManager::new(cached_meta_backend.clone()));
345        table_metadata_manager
346            .init()
347            .await
348            .context(InitMetadataSnafu)?;
349
350        let executor = HandlerGroupExecutor::new(vec![
351            Arc::new(ParseMailboxMessageHandler),
352            Arc::new(InvalidateCacheHandler::new(layered_cache_registry.clone())),
353        ]);
354
355        let mut resource_stat = ResourceStatImpl::default();
356        resource_stat.start_collect_cpu_usage();
357
358        let heartbeat_task = flow::heartbeat::HeartbeatTask::new(
359            &opts,
360            meta_client.clone(),
361            opts.heartbeat.clone(),
362            Arc::new(executor),
363            Arc::new(resource_stat),
364        );
365
366        let flow_metadata_manager = Arc::new(FlowMetadataManager::new(cached_meta_backend.clone()));
367        let flow_auth_header = get_flow_auth_options(&opts).context(StartFlownodeSnafu)?;
368        let frontend_client = FrontendClient::from_meta_client(
369            meta_client.clone(),
370            flow_auth_header,
371            opts.query.clone(),
372            opts.flow.batching_mode.clone(),
373        )
374        .context(StartFlownodeSnafu)?;
375        let frontend_client = Arc::new(frontend_client);
376        let flownode_builder = FlownodeBuilder::new(
377            opts.clone(),
378            plugins.clone(),
379            table_metadata_manager,
380            catalog_manager.clone(),
381            flow_metadata_manager,
382            frontend_client.clone(),
383        )
384        .with_heartbeat_task(heartbeat_task);
385
386        let mut flownode = flownode_builder.build().await.context(StartFlownodeSnafu)?;
387
388        let builder =
389            FlownodeServiceBuilder::grpc_server_builder(&opts, flownode.flownode_server());
390        let builder = if let Some(configurator) =
391            plugins.get::<GrpcBuilderConfiguratorRef<GrpcConfigureContext>>()
392        {
393            let context = GrpcConfigureContext {
394                kv_backend: cached_meta_backend.clone(),
395                fe_client: frontend_client.clone(),
396                flownode_id: member_id,
397                catalog_manager: catalog_manager.clone(),
398            };
399            configurator
400                .configure(builder, context)
401                .await
402                .context(OtherSnafu)?
403        } else {
404            builder
405        };
406        let grpc_server = builder.build();
407
408        let services = FlownodeServiceBuilder::new(&opts)
409            .with_grpc_server(grpc_server)
410            .enable_http_service()
411            .build()
412            .context(StartFlownodeSnafu)?;
413        flownode.setup_services(services);
414        let flownode = flownode;
415
416        let invoker = FrontendInvoker::build_from(
417            flownode.flow_engine().streaming_engine(),
418            catalog_manager.clone(),
419            cached_meta_backend.clone(),
420            layered_cache_registry.clone(),
421            meta_client.clone(),
422            client,
423        )
424        .await
425        .context(StartFlownodeSnafu)?;
426        flownode
427            .flow_engine()
428            .streaming_engine()
429            // TODO(discord9): refactor and avoid circular reference
430            .set_frontend_invoker(invoker)
431            .await;
432
433        Ok(Instance::new(flownode, guard))
434    }
435}