1 //  Copyright (c) 2018-present, Facebook, Inc.  All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 #pragma once
6 
7 #include "monitoring/instrumented_mutex.h"
8 #include "options/db_options.h"
9 #include "rocksdb/io_status.h"
10 #include "rocksdb/listener.h"
11 #include "rocksdb/status.h"
12 
13 namespace ROCKSDB_NAMESPACE {
14 
15 class DBImpl;
16 
17 class ErrorHandler {
18   public:
ErrorHandler(DBImpl * db,const ImmutableDBOptions & db_options,InstrumentedMutex * db_mutex)19    ErrorHandler(DBImpl* db, const ImmutableDBOptions& db_options,
20                 InstrumentedMutex* db_mutex)
21        : db_(db),
22          db_options_(db_options),
23          bg_error_(Status::OK()),
24          recovery_error_(Status::OK()),
25          db_mutex_(db_mutex),
26          auto_recovery_(false),
27          recovery_in_prog_(false) {}
~ErrorHandler()28    ~ErrorHandler() {}
29 
EnableAutoRecovery()30    void EnableAutoRecovery() { auto_recovery_ = true; }
31 
32    Status::Severity GetErrorSeverity(BackgroundErrorReason reason,
33                                      Status::Code code,
34                                      Status::SubCode subcode);
35 
36    Status SetBGError(const Status& bg_err, BackgroundErrorReason reason);
37 
38    Status SetBGError(const IOStatus& bg_io_err, BackgroundErrorReason reason);
39 
GetBGError()40    Status GetBGError() { return bg_error_; }
41 
GetRecoveryError()42    Status GetRecoveryError() { return recovery_error_; }
43 
44    Status ClearBGError();
45 
IsDBStopped()46    bool IsDBStopped() {
47      return !bg_error_.ok() &&
48             bg_error_.severity() >= Status::Severity::kHardError;
49     }
50 
IsBGWorkStopped()51     bool IsBGWorkStopped() {
52       return !bg_error_.ok() &&
53              (bg_error_.severity() >= Status::Severity::kHardError ||
54               !auto_recovery_);
55     }
56 
IsRecoveryInProgress()57     bool IsRecoveryInProgress() { return recovery_in_prog_; }
58 
59     Status RecoverFromBGError(bool is_manual = false);
60     void CancelErrorRecovery();
61 
62    private:
63     DBImpl* db_;
64     const ImmutableDBOptions& db_options_;
65     Status bg_error_;
66     // A separate Status variable used to record any errors during the
67     // recovery process from hard errors
68     Status recovery_error_;
69     InstrumentedMutex* db_mutex_;
70     // A flag indicating whether automatic recovery from errors is enabled
71     bool auto_recovery_;
72     bool recovery_in_prog_;
73 
74     Status OverrideNoSpaceError(Status bg_error, bool* auto_recovery);
75     void RecoverFromNoSpace();
76 };
77 
78 }  // namespace ROCKSDB_NAMESPACE
79