Skip to main content

datanode/
error.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::any::Any;
16use std::sync::Arc;
17
18use common_error::define_into_tonic_status;
19use common_error::ext::{BoxedError, ErrorExt, RetryHint};
20use common_error::status_code::StatusCode;
21use common_macro::stack_trace_debug;
22use common_runtime::JoinError;
23use snafu::{Location, Snafu};
24use store_api::storage::RegionId;
25use table::error::Error as TableError;
26use tokio::time::error::Elapsed;
27
28/// Business error of datanode.
29#[derive(Snafu)]
30#[snafu(visibility(pub))]
31#[stack_trace_debug]
32pub enum Error {
33    #[snafu(display("Failed to execute async task"))]
34    AsyncTaskExecute {
35        #[snafu(implicit)]
36        location: Location,
37        source: Arc<Error>,
38    },
39
40    #[snafu(display("Failed to watch change"))]
41    WatchAsyncTaskChange {
42        #[snafu(implicit)]
43        location: Location,
44        #[snafu(source)]
45        error: tokio::sync::watch::error::RecvError,
46    },
47
48    #[snafu(display("Failed to handle heartbeat response"))]
49    HandleHeartbeatResponse {
50        #[snafu(implicit)]
51        location: Location,
52        source: common_meta::error::Error,
53    },
54
55    #[snafu(display("Failed to get info from meta server"))]
56    GetMetadata {
57        #[snafu(implicit)]
58        location: Location,
59        source: common_meta::error::Error,
60    },
61
62    #[snafu(display("Failed to execute logical plan"))]
63    ExecuteLogicalPlan {
64        #[snafu(implicit)]
65        location: Location,
66        source: query::error::Error,
67    },
68
69    #[snafu(display("Failed to join datanode runtime task, request_type: {}", request_type))]
70    RuntimeJoin {
71        request_type: &'static str,
72        #[snafu(source)]
73        error: JoinError,
74        #[snafu(implicit)]
75        location: Location,
76    },
77
78    #[snafu(display("Failed to create plan decoder"))]
79    NewPlanDecoder {
80        #[snafu(implicit)]
81        location: Location,
82        source: query::error::Error,
83    },
84
85    #[snafu(display("Failed to decode logical plan"))]
86    DecodeLogicalPlan {
87        #[snafu(implicit)]
88        location: Location,
89        source: common_query::error::Error,
90    },
91
92    #[snafu(display("Schema not found: {}", name))]
93    SchemaNotFound {
94        name: String,
95        #[snafu(implicit)]
96        location: Location,
97    },
98
99    #[snafu(display("Missing timestamp column in request"))]
100    MissingTimestampColumn {
101        #[snafu(implicit)]
102        location: Location,
103    },
104
105    #[snafu(display("Failed to delete value from table: {}", table_name))]
106    Delete {
107        table_name: String,
108        #[snafu(implicit)]
109        location: Location,
110        source: TableError,
111    },
112
113    #[snafu(display("Failed to start server"))]
114    StartServer {
115        #[snafu(implicit)]
116        location: Location,
117        source: servers::error::Error,
118    },
119
120    #[snafu(display("Failed to parse address {}", addr))]
121    ParseAddr {
122        addr: String,
123        #[snafu(source)]
124        error: std::net::AddrParseError,
125    },
126
127    #[snafu(display("Failed to create directory {}", dir))]
128    CreateDir {
129        dir: String,
130        #[snafu(source)]
131        error: std::io::Error,
132    },
133
134    #[snafu(display("Failed to remove directory {}", dir))]
135    RemoveDir {
136        dir: String,
137        #[snafu(source)]
138        error: std::io::Error,
139    },
140
141    #[snafu(display("Failed to open log store"))]
142    OpenLogStore {
143        #[snafu(implicit)]
144        location: Location,
145        source: Box<log_store::error::Error>,
146    },
147
148    #[snafu(display("Invalid SQL, error: {}", msg))]
149    InvalidSql { msg: String },
150
151    #[snafu(display("Illegal primary keys definition: {}", msg))]
152    IllegalPrimaryKeysDef {
153        msg: String,
154        #[snafu(implicit)]
155        location: Location,
156    },
157
158    #[snafu(display("Schema {} already exists", name))]
159    SchemaExists {
160        name: String,
161        #[snafu(implicit)]
162        location: Location,
163    },
164
165    #[snafu(display("Failed to initialize meta client"))]
166    MetaClientInit {
167        #[snafu(implicit)]
168        location: Location,
169        source: meta_client::error::Error,
170    },
171
172    #[snafu(display("Missing node id in Datanode config"))]
173    MissingNodeId {
174        #[snafu(implicit)]
175        location: Location,
176    },
177
178    #[snafu(display("Failed to build datanode"))]
179    BuildDatanode {
180        #[snafu(implicit)]
181        location: Location,
182        source: BoxedError,
183    },
184
185    #[snafu(display("Failed to build http client"))]
186    BuildHttpClient {
187        #[snafu(implicit)]
188        location: Location,
189        #[snafu(source)]
190        error: reqwest::Error,
191    },
192
193    #[snafu(display("Missing required field: {}", name))]
194    MissingRequiredField {
195        name: String,
196        #[snafu(implicit)]
197        location: Location,
198    },
199
200    #[snafu(display(
201        "No valid default value can be built automatically, column: {}",
202        column,
203    ))]
204    ColumnNoneDefaultValue {
205        column: String,
206        #[snafu(implicit)]
207        location: Location,
208    },
209
210    #[snafu(display("Failed to shutdown server"))]
211    ShutdownServer {
212        #[snafu(implicit)]
213        location: Location,
214        #[snafu(source)]
215        source: servers::error::Error,
216    },
217
218    #[snafu(display("Failed to shutdown instance"))]
219    ShutdownInstance {
220        #[snafu(implicit)]
221        location: Location,
222        #[snafu(source)]
223        source: BoxedError,
224    },
225
226    #[snafu(display("Payload not exist"))]
227    PayloadNotExist {
228        #[snafu(implicit)]
229        location: Location,
230    },
231
232    #[snafu(display("Unexpected, violated: {}", violated))]
233    Unexpected {
234        violated: String,
235        #[snafu(implicit)]
236        location: Location,
237    },
238
239    #[snafu(display("Failed to handle request for region {}", region_id))]
240    HandleRegionRequest {
241        region_id: RegionId,
242        #[snafu(implicit)]
243        location: Location,
244        source: BoxedError,
245    },
246
247    #[snafu(display("Failed to open batch regions"))]
248    HandleBatchOpenRequest {
249        #[snafu(implicit)]
250        location: Location,
251        source: BoxedError,
252    },
253
254    #[snafu(display("Failed to handle batch ddl request, ddl_type: {}", ddl_type))]
255    HandleBatchDdlRequest {
256        #[snafu(implicit)]
257        location: Location,
258        source: BoxedError,
259        ddl_type: String,
260    },
261
262    #[snafu(display("RegionId {} not found", region_id))]
263    RegionNotFound {
264        region_id: RegionId,
265        #[snafu(implicit)]
266        location: Location,
267    },
268
269    #[snafu(display("Region {} not ready", region_id))]
270    RegionNotReady {
271        region_id: RegionId,
272        #[snafu(implicit)]
273        location: Location,
274    },
275
276    #[snafu(display("Region {} is busy", region_id))]
277    RegionBusy {
278        region_id: RegionId,
279        #[snafu(implicit)]
280        location: Location,
281    },
282
283    #[snafu(display("Region engine {} is not registered", name))]
284    RegionEngineNotFound {
285        name: String,
286        #[snafu(implicit)]
287        location: Location,
288    },
289
290    #[snafu(display(
291        "GC configuration mismatch: metasrv.gc.enable={}, datanode.region_engine.mito.gc.enable={}",
292        metasrv_gc_enabled,
293        datanode_gc_enabled,
294    ))]
295    GcConfigMismatch {
296        metasrv_gc_enabled: bool,
297        datanode_gc_enabled: bool,
298        #[snafu(implicit)]
299        location: Location,
300    },
301
302    #[snafu(display("Unsupported output type, expected: {}", expected))]
303    UnsupportedOutput {
304        expected: String,
305        #[snafu(implicit)]
306        location: Location,
307    },
308
309    #[snafu(display("Failed to build region requests"))]
310    BuildRegionRequests {
311        #[snafu(implicit)]
312        location: Location,
313        source: store_api::metadata::MetadataError,
314    },
315
316    #[snafu(display("Failed to serialize WAL options for region {}", region_id))]
317    SerializeWalOptions {
318        region_id: RegionId,
319        #[snafu(source)]
320        error: serde_json::Error,
321        #[snafu(implicit)]
322        location: Location,
323    },
324
325    #[snafu(display("Failed to stop region engine {}", name))]
326    StopRegionEngine {
327        name: String,
328        #[snafu(implicit)]
329        location: Location,
330        source: BoxedError,
331    },
332
333    #[snafu(display(
334        "Failed to find logical regions in physical region {}",
335        physical_region_id
336    ))]
337    FindLogicalRegions {
338        physical_region_id: RegionId,
339        source: metric_engine::error::Error,
340        #[snafu(implicit)]
341        location: Location,
342    },
343
344    #[snafu(display("Failed to build mito engine"))]
345    BuildMitoEngine {
346        source: mito2::error::Error,
347        #[snafu(implicit)]
348        location: Location,
349    },
350
351    #[snafu(display("Failed to build metric engine"))]
352    BuildMetricEngine {
353        source: metric_engine::error::Error,
354        #[snafu(implicit)]
355        location: Location,
356    },
357
358    #[snafu(display("Failed to run gc for region {}", region_id))]
359    GcMitoEngine {
360        region_id: RegionId,
361        source: mito2::error::Error,
362        #[snafu(implicit)]
363        location: Location,
364    },
365
366    #[snafu(display("Failed to list SST entries from storage"))]
367    ListStorageSsts {
368        #[snafu(implicit)]
369        location: Location,
370        source: mito2::error::Error,
371    },
372
373    #[snafu(display("Failed to serialize options to TOML"))]
374    TomlFormat {
375        #[snafu(implicit)]
376        location: Location,
377        #[snafu(source(from(common_config::error::Error, Box::new)))]
378        source: Box<common_config::error::Error>,
379    },
380
381    #[snafu(display(
382        "Failed to get region metadata from engine {} for region_id {}",
383        engine,
384        region_id,
385    ))]
386    GetRegionMetadata {
387        engine: String,
388        region_id: RegionId,
389        #[snafu(implicit)]
390        location: Location,
391        source: BoxedError,
392    },
393
394    #[snafu(display("DataFusion"))]
395    DataFusion {
396        #[snafu(source)]
397        error: datafusion::error::DataFusionError,
398        #[snafu(implicit)]
399        location: Location,
400    },
401
402    #[snafu(display("Failed to acquire permit, source closed"))]
403    ConcurrentQueryLimiterClosed {
404        #[snafu(source)]
405        error: tokio::sync::AcquireError,
406        #[snafu(implicit)]
407        location: Location,
408    },
409
410    #[snafu(display("Failed to acquire permit under timeouts"))]
411    ConcurrentQueryLimiterTimeout {
412        #[snafu(source)]
413        error: Elapsed,
414        #[snafu(implicit)]
415        location: Location,
416    },
417
418    #[snafu(display("Cache not found in registry"))]
419    MissingCache {
420        #[snafu(implicit)]
421        location: Location,
422    },
423
424    #[snafu(display("Failed to serialize json"))]
425    SerializeJson {
426        #[snafu(source)]
427        error: serde_json::Error,
428        #[snafu(implicit)]
429        location: Location,
430    },
431
432    #[snafu(display("Failed object store operation"))]
433    ObjectStore {
434        source: object_store::error::Error,
435        #[snafu(implicit)]
436        location: Location,
437    },
438
439    #[snafu(display("Not yet implemented: {what}"))]
440    NotYetImplemented { what: String },
441}
442
443pub type Result<T> = std::result::Result<T, Error>;
444
445impl ErrorExt for Error {
446    fn status_code(&self) -> StatusCode {
447        use Error::*;
448        match self {
449            NewPlanDecoder { source, .. } | ExecuteLogicalPlan { source, .. } => {
450                source.status_code()
451            }
452
453            BuildRegionRequests { source, .. } => source.status_code(),
454            HandleHeartbeatResponse { source, .. } | GetMetadata { source, .. } => {
455                source.status_code()
456            }
457
458            DecodeLogicalPlan { source, .. } => source.status_code(),
459
460            Delete { source, .. } => source.status_code(),
461
462            InvalidSql { .. }
463            | IllegalPrimaryKeysDef { .. }
464            | MissingTimestampColumn { .. }
465            | SchemaNotFound { .. }
466            | SchemaExists { .. }
467            | MissingNodeId { .. }
468            | ColumnNoneDefaultValue { .. }
469            | MissingRequiredField { .. }
470            | RegionEngineNotFound { .. }
471            | GcConfigMismatch { .. }
472            | ParseAddr { .. }
473            | TomlFormat { .. }
474            | BuildDatanode { .. } => StatusCode::InvalidArguments,
475
476            PayloadNotExist { .. }
477            | Unexpected { .. }
478            | SerializeWalOptions { .. }
479            | WatchAsyncTaskChange { .. }
480            | BuildHttpClient { .. } => StatusCode::Unexpected,
481
482            AsyncTaskExecute { source, .. } => source.status_code(),
483
484            CreateDir { .. }
485            | RemoveDir { .. }
486            | ShutdownInstance { .. }
487            | DataFusion { .. }
488            | RuntimeJoin { .. } => StatusCode::Internal,
489
490            RegionNotFound { .. } => StatusCode::RegionNotFound,
491            RegionNotReady { .. } => StatusCode::RegionNotReady,
492            RegionBusy { .. } => StatusCode::RegionBusy,
493
494            StartServer { source, .. } | ShutdownServer { source, .. } => source.status_code(),
495
496            OpenLogStore { source, .. } => source.status_code(),
497            MetaClientInit { source, .. } => source.status_code(),
498            UnsupportedOutput { .. } | NotYetImplemented { .. } => StatusCode::Unsupported,
499            HandleRegionRequest { source, .. }
500            | GetRegionMetadata { source, .. }
501            | HandleBatchOpenRequest { source, .. }
502            | HandleBatchDdlRequest { source, .. } => source.status_code(),
503            StopRegionEngine { source, .. } => source.status_code(),
504
505            FindLogicalRegions { source, .. } => source.status_code(),
506            BuildMitoEngine { source, .. } | GcMitoEngine { source, .. } => source.status_code(),
507            BuildMetricEngine { source, .. } => source.status_code(),
508            ListStorageSsts { source, .. } => source.status_code(),
509            ConcurrentQueryLimiterClosed { .. } | ConcurrentQueryLimiterTimeout { .. } => {
510                StatusCode::RegionBusy
511            }
512            MissingCache { .. } => StatusCode::Internal,
513            SerializeJson { .. } => StatusCode::Internal,
514
515            ObjectStore { source, .. } => source.status_code(),
516        }
517    }
518
519    fn as_any(&self) -> &dyn Any {
520        self
521    }
522
523    fn retry_hint(&self) -> RetryHint {
524        use Error::*;
525
526        match self {
527            RegionBusy { .. }
528            | RegionNotReady { .. }
529            | ConcurrentQueryLimiterClosed { .. }
530            | ConcurrentQueryLimiterTimeout { .. } => RetryHint::Retryable,
531            NewPlanDecoder { source, .. } | ExecuteLogicalPlan { source, .. } => {
532                source.retry_hint()
533            }
534            HandleHeartbeatResponse { source, .. } | GetMetadata { source, .. } => {
535                source.retry_hint()
536            }
537            DecodeLogicalPlan { source, .. } => source.retry_hint(),
538            Delete { source, .. } => source.retry_hint(),
539            AsyncTaskExecute { source, .. } => source.retry_hint(),
540            StartServer { source, .. } | ShutdownServer { source, .. } => source.retry_hint(),
541            OpenLogStore { source, .. } => source.retry_hint(),
542            MetaClientInit { source, .. } => source.retry_hint(),
543            HandleRegionRequest { source, .. }
544            | GetRegionMetadata { source, .. }
545            | HandleBatchOpenRequest { source, .. }
546            | HandleBatchDdlRequest { source, .. }
547            | StopRegionEngine { source, .. } => source.retry_hint(),
548            FindLogicalRegions { source, .. } => source.retry_hint(),
549            BuildMitoEngine { source, .. } => source.retry_hint(),
550            GcMitoEngine { source, .. } => source.retry_hint(),
551            BuildMetricEngine { source, .. } => source.retry_hint(),
552            ListStorageSsts { source, .. } => source.retry_hint(),
553            ObjectStore { source, .. } => source.retry_hint(),
554            _ => RetryHint::NonRetryable,
555        }
556    }
557}
558
559define_into_tonic_status!(Error);
560
561#[cfg(test)]
562mod tests {
563    use common_error::ext::RetryHint;
564
565    use super::*;
566
567    #[test]
568    fn test_region_state_hints_are_retryable() {
569        let region_id = RegionId::new(1024, 1);
570
571        let err = RegionBusySnafu { region_id }.build();
572        assert_eq!(err.retry_hint(), RetryHint::Retryable);
573
574        let err = RegionNotReadySnafu { region_id }.build();
575        assert_eq!(err.retry_hint(), RetryHint::Retryable);
576    }
577
578    #[test]
579    fn test_default_hint_is_non_retryable() {
580        let err = UnexpectedSnafu {
581            violated: "mock error",
582        }
583        .build();
584
585        assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
586    }
587}