OmniSciDB  a5dc49c757
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
QueryState.h
Go to the documentation of this file.
1 /*
2  * Copyright 2022 HEAVY.AI, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
23 #ifndef OMNISCI_THRIFTHANDLER_QUERYSTATE_H
24 #define OMNISCI_THRIFTHANDLER_QUERYSTATE_H
25 
26 #include "Logger/Logger.h"
27 #include "Shared/StringTransform.h"
28 
29 #include <boost/circular_buffer.hpp>
30 #include <boost/filesystem.hpp>
31 #include <boost/noncopyable.hpp>
32 #include <boost/optional.hpp>
33 #include <boost/preprocessor.hpp>
34 
35 #include <atomic>
36 #include <chrono>
37 #include <list>
38 #include <memory>
39 #include <mutex>
40 #include <sstream>
41 #include <string>
42 #include <thread>
43 
44 /* See docs/QueryState.md for documentation.
45  *
46  * Outline:
47  * - Consolidate information about current and past queries.
48  * - DEPRECATION NOTICE:
49  * Timer and Event-related logic is replaced by logger::DebugTimer.
50  * For adding new timings, please see Logger.h instead.
51  * - Time and record code blocks, and save to stdlog.
52  *
53  * Classes:
54  * - StdLog - logs to DEBUG1 on construction, INFO on destruction.
55  * - QueryState - hold info on the evolution of a query.
56  * - QueryStateProxy - Light-weight QueryState wrapper to track Timer/Event nesting.
57  * - Timer - Created by QueryStateProxy to log function/block lifetime.
58  *
59  * Basic API Usage:
60  * - auto stdlog = STDLOG() // May include session_info, name/value pairs.
61  * - auto query_state = query_states_.create(get_session_ptr(session), query_str);
62  * - stdlog.setQueryState(query_state); // Log query_state when stdlog destructs.
63  * - auto query_state_proxy = query_state.createQueryStateProxy();
64  * - auto timer = query_state_proxy.createTimer(__func__);
65  */
66 
67 /* Notes:
68  * - QueryStates holds many QueryState instances.
69  * - QueryState holds many Event instances.
70  * - QueryState and QueryStateProxy can create Timers.
71  * - QueryState and Timer can create QueryStateProxies.
72  * - Timers and Events are one-to-one.
73  * - When StdLog destructs, it logs all of the associated QueryState's Events.
74  * - For each thrift request, there are a few possibilities wrt QueryState and RequestId:
75  * - A "normal" sql query has a QueryState and RequestId assigned to it.
76  * - Some thrift calls do not instantiate a QueryState but create log messages. A new
77  * RequestId is usually assigned for logging purposes.
78  * - Some thrift calls do not log, and thus no QueryState or RequestId is created or
79  * assigned.
80  * - Some requests require Calcite to invoke its own thrift calls.
81  * To uniformly accommodate the first two cases above, a new RequestId is assigned
82  * and an INFO log message is made to tie the RequestId of the originating request
83  * to the child.
84  */
85 
86 namespace Catalog_Namespace {
87 class SessionInfo;
88 }
89 
90 namespace query_state {
91 
92 using Clock = std::chrono::steady_clock;
93 
94 struct Event;
95 using Events = std::list<Event>;
96 
97 struct Event {
98  char const* const name;
99  Events::iterator const parent; // events_.end() = top level query_state
100  std::thread::id const thread_id;
101  Clock::duration const started;
102  // duration is used instead of time_point since it is trivially copyable for atomic.
103  std::atomic<Clock::duration> stopped;
104  Event(char const* const name, Events::iterator parent);
105  template <typename Units = std::chrono::milliseconds>
106  boost::optional<typename Units::rep> duration() const {
107  auto const stop_time = stopped.load();
108  return boost::make_optional(
109  stop_time != Clock::duration::zero(),
110  std::chrono::duration_cast<Units>(stop_time - started).count());
111  }
112  void stop();
113 };
114 
115 using EventFunction = std::function<void(Event const&)>;
116 
117 class QueryStateProxy;
118 class QueryStates;
119 
120 // SessionInfo can expire, so data is copied while available.
121 struct SessionData {
122  std::weak_ptr<Catalog_Namespace::SessionInfo const> session_info;
123  std::string db_name;
124  std::string user_name;
125  std::string public_session_id;
126 
127  SessionData() = default;
128  SessionData(std::shared_ptr<Catalog_Namespace::SessionInfo const> const&);
129 };
130 
131 class Timer;
132 
133 class QueryState : public std::enable_shared_from_this<QueryState> {
134  boost::optional<SessionData> session_data_;
135  std::string const query_str_;
137  mutable std::mutex events_mutex_;
138  std::atomic<bool> logged_;
139  std::string submitted_;
140  void logCallStack(std::stringstream&, unsigned const depth, Events::iterator parent);
141 
142  // Only shared_ptr instances are allowed due to call to shared_from_this().
143  QueryState(std::shared_ptr<Catalog_Namespace::SessionInfo const> const&,
144  std::string query_str);
145 
146  public:
147  template <typename... ARGS>
148  static std::shared_ptr<QueryState> create(ARGS&&... args) {
149  // Trick to call std::make_shared with private constructors.
150  struct EnableMakeShared : public QueryState {
151  EnableMakeShared(ARGS&&... args) : QueryState(std::forward<ARGS>(args)...) {}
152  };
153  return std::make_shared<EnableMakeShared>(std::forward<ARGS>(args)...);
154  }
156  QueryStateProxy createQueryStateProxy(Events::iterator parent);
157  Timer createTimer(char const* event_name, Events::iterator parent);
158  inline bool emptyLog() const { return events_.empty() && query_str_.empty(); }
159  inline std::string const& getQueryStr() const { return query_str_; }
160  // Will throw exception if session_data_.session_info.expired().
161  std::shared_ptr<Catalog_Namespace::SessionInfo const> getConstSessionInfo() const;
162  boost::optional<SessionData> const& getSessionData() const { return session_data_; }
163  inline bool isLogged() const { return logged_.load(); }
164  void logCallStack(std::stringstream&);
165  void setQuerySubmittedTime(const std::string& t);
166  const std::string getQuerySubmittedTime() const;
167  inline void setLogged(bool logged) { logged_.store(logged); }
168  friend class QueryStates;
169 };
170 
171 // Light-weight class used as intermediary between Timer objects spawning child Timers.
172 // Assumes lifetime is less than original QueryState.
175  Events::iterator const parent_;
176 
177  public:
178  QueryStateProxy(QueryState& query_state, Events::iterator parent)
179  : query_state_(query_state), parent_(parent) {}
180  Timer createTimer(char const* event_name);
181  QueryState* operator->() const { return &query_state_; }
182 };
183 
184 // At this point it is not clear how long we want to keep completed queries.
185 // The data structure and lifetime are not currently settled upon.
186 class QueryStates {
187  using CircleBuffer = boost::circular_buffer<std::shared_ptr<QueryState>>;
188  // constexpr size_t MAX_SIZE_BEFORE_OVERWRITE = 128; // C++17
190  std::mutex circle_mutex_;
191 
192  public:
193  template <typename... ARGS>
194  CircleBuffer::value_type create(ARGS&&... args) {
195  std::lock_guard<std::mutex> lock(circle_mutex_);
196  /* Logic for ensuring QueryState objects are logged before deleting them.
197  if (circle_buffer_.full() && !circle_buffer_.front()->isLogged()) {
198  constexpr size_t MAX_SIZE_BEFORE_OVERWRITE = 128;
199  if (circle_buffer_.size() < MAX_SIZE_BEFORE_OVERWRITE) {
200  circle_buffer_.set_capacity(2 * circle_buffer_.capacity());
201  } else {
202  LOG(ERROR) << "QueryStates is holding " << circle_buffer_.size()
203  << " queries but the oldest query_state has not completed
204  logging.";
205  }
206  }
207  */
208  circle_buffer_.push_back(QueryState::create(std::forward<ARGS>(args)...));
209  return circle_buffer_.back();
210  }
211 };
212 
213 class Timer {
214  std::shared_ptr<QueryState> query_state_;
215  Events::iterator event_; // = pointer into QueryState::events_
216 
217  public:
218  Timer(std::shared_ptr<QueryState>&&, Events::iterator event);
219  Timer(Timer const&) = delete;
220  Timer& operator=(Timer const&) = delete;
221  Timer(Timer&&) = default;
222  Timer& operator=(Timer&&) = default;
223  ~Timer();
225 };
226 
227 // Log Format:
228 // YYYY-MM-DDTHH:MM::SS.FFFFFF [S] [pid] [file]:[line] [label] [func] [match] [dur_ms]
229 // [dbname] [user] [pubsessid] {[names]} {[values]}
230 // Call at both beginning(label="stdlog_begin") and end(label="stdlog") of Thrift call,
231 // with dur_ms = current age of StdLog object in milliseconds.
232 // stdlog_begin is logged at DEBUG1 level, stdlog is logged at INFO level.
233 // All remaining optional parameters are name,value pairs that will be included in log.
234 #define STDLOG(...) \
235  BOOST_PP_IF(BOOST_PP_IS_EMPTY(__VA_ARGS__), \
236  query_state::StdLog(__FILE__, __LINE__, __func__), \
237  query_state::StdLog(__FILE__, __LINE__, __func__, __VA_ARGS__))
238 
239 class StdLogData {
240  protected:
241  static std::atomic<int64_t> s_match;
242  std::string const file_;
243  unsigned const line_;
244  char const* const func_;
245  Clock::time_point const start_;
246  int64_t const match_; // Unique to each begin/end pair to match them together.
247  std::list<std::string> name_value_pairs_;
248  template <typename... Pairs>
249  StdLogData(char const* file, unsigned line, char const* func, Pairs&&... pairs)
250  : file_(boost::filesystem::path(file).filename().string())
251  , line_(line)
252  , func_(func)
253  , start_(Clock::now())
254  , match_(s_match++)
255  , name_value_pairs_{to_string(std::forward<Pairs>(pairs))...} {
256  static_assert(sizeof...(Pairs) % 2 == 0,
257  "StdLogData() requires an even number of name/value parameters.");
258  }
259 };
260 
261 class StdLog : public StdLogData {
262  std::shared_ptr<Catalog_Namespace::SessionInfo> session_info_;
263  std::shared_ptr<QueryState> query_state_;
264  void log(logger::Severity, char const* label);
265  void logCallStack(logger::Severity, char const* label);
266  static logger::Severity stdlogBeginSeverity(char const* func);
267 
268  public:
269  template <typename... Pairs>
270  StdLog(char const* file,
271  unsigned line,
272  char const* func,
273  std::shared_ptr<Catalog_Namespace::SessionInfo> session_info,
274  Pairs&&... pairs)
275  : StdLogData(file, line, func, std::forward<Pairs>(pairs)...)
276  , session_info_(std::move(session_info)) {
277  log(stdlogBeginSeverity(func), "stdlog_begin");
278  }
279 
280  template <typename... Pairs>
281  StdLog(char const* file,
282  unsigned line,
283  char const* func,
284  std::shared_ptr<Catalog_Namespace::SessionInfo> session_info,
285  std::shared_ptr<QueryState> query_state,
286  Pairs&&... pairs)
287  : StdLogData(file, line, func, std::forward<Pairs>(pairs)...)
288  , session_info_(std::move(session_info))
289  , query_state_(std::move(query_state)) {
290  log(stdlogBeginSeverity(func), "stdlog_begin");
291  }
292 
293  template <typename... Pairs>
294  StdLog(char const* file,
295  unsigned line,
296  char const* func,
297  std::shared_ptr<QueryState> query_state,
298  Pairs&&... pairs)
299  : StdLogData(file, line, func, std::forward<Pairs>(pairs)...)
300  , query_state_(std::move(query_state)) {
301  log(stdlogBeginSeverity(func), "stdlog_begin");
302  }
303  template <typename... Pairs>
304  StdLog(char const* file, unsigned line, char const* func, Pairs&&... pairs)
305  : StdLogData(file, line, func, std::forward<Pairs>(pairs)...) {
306  log(stdlogBeginSeverity(func), "stdlog_begin");
307  }
308  StdLog(StdLog const&) = delete;
309  StdLog(StdLog&&) = default;
310  ~StdLog();
311  template <typename... Pairs>
312  void appendNameValuePairs(Pairs&&... pairs) {
313  static_assert(sizeof...(Pairs) % 2 == 0,
314  "appendNameValuePairs() requires an even number of parameters.");
315  name_value_pairs_.splice(name_value_pairs_.cend(),
316  {to_string(std::forward<Pairs>(pairs))...});
317  }
318  template <typename Units = std::chrono::milliseconds>
319  typename Units::rep duration() const {
320  return std::chrono::duration_cast<Units>(Clock::now() - start_).count();
321  }
322  std::shared_ptr<Catalog_Namespace::SessionInfo const> getConstSessionInfo() const;
323  std::shared_ptr<Catalog_Namespace::SessionInfo> getSessionInfo() const;
324  void setQueryState(std::shared_ptr<QueryState>);
325  void setSessionInfo(std::shared_ptr<Catalog_Namespace::SessionInfo>);
326 };
327 
328 } // namespace query_state
329 
330 #endif // OMNISCI_THRIFTHANDLER_QUERYSTATE_H
unsigned const line_
Definition: QueryState.h:243
boost::optional< SessionData > session_data_
Definition: QueryState.h:134
std::shared_ptr< QueryState > query_state_
Definition: QueryState.h:214
std::string const file_
Definition: QueryState.h:242
void logCallStack(std::stringstream &, unsigned const depth, Events::iterator parent)
Definition: QueryState.cpp:107
QueryStateProxy createQueryStateProxy()
Definition: QueryState.cpp:71
boost::optional< SessionData > const & getSessionData() const
Definition: QueryState.h:162
std::string const & getQueryStr() const
Definition: QueryState.h:159
Events::iterator const parent_
Definition: QueryState.h:175
Clock::duration const started
Definition: QueryState.h:101
static std::shared_ptr< QueryState > create(ARGS &&...args)
Definition: QueryState.h:148
void setQuerySubmittedTime(const std::string &t)
Definition: QueryState.cpp:97
Timer & operator=(Timer const &)=delete
CircleBuffer::value_type create(ARGS &&...args)
Definition: QueryState.h:194
Events::iterator const parent
Definition: QueryState.h:99
void setSessionInfo(std::shared_ptr< Catalog_Namespace::SessionInfo >)
Definition: QueryState.cpp:282
Timer createTimer(char const *event_name)
Definition: QueryState.cpp:129
std::string to_string(char const *&&v)
QueryState(std::shared_ptr< Catalog_Namespace::SessionInfo const > const &, std::string query_str)
Definition: QueryState.cpp:62
Units::rep duration() const
Definition: QueryState.h:319
std::atomic< Clock::duration > stopped
Definition: QueryState.h:103
std::list< std::string > name_value_pairs_
Definition: QueryState.h:247
std::string submitted_
Definition: QueryState.h:139
StdLogData(char const *file, unsigned line, char const *func, Pairs &&...pairs)
Definition: QueryState.h:249
void setLogged(bool logged)
Definition: QueryState.h:167
boost::circular_buffer< std::shared_ptr< QueryState >> CircleBuffer
Definition: QueryState.h:187
QueryStateProxy createQueryStateProxy()
Definition: QueryState.cpp:139
std::string const query_str_
Definition: QueryState.h:135
static logger::Severity stdlogBeginSeverity(char const *func)
Definition: QueryState.cpp:190
void setQueryState(std::shared_ptr< QueryState >)
Definition: QueryState.cpp:278
StdLog(char const *file, unsigned line, char const *func, std::shared_ptr< Catalog_Namespace::SessionInfo > session_info, Pairs &&...pairs)
Definition: QueryState.h:270
void logCallStack(logger::Severity, char const *label)
Definition: QueryState.cpp:255
std::shared_ptr< Catalog_Namespace::SessionInfo > getSessionInfo() const
Definition: QueryState.cpp:155
QueryStateProxy(QueryState &query_state, Events::iterator parent)
Definition: QueryState.h:178
std::thread::id const thread_id
Definition: QueryState.h:100
StdLog(char const *file, unsigned line, char const *func, std::shared_ptr< QueryState > query_state, Pairs &&...pairs)
Definition: QueryState.h:294
std::shared_ptr< Catalog_Namespace::SessionInfo > session_info_
Definition: QueryState.h:262
std::weak_ptr< Catalog_Namespace::SessionInfo const > session_info
Definition: QueryState.h:122
std::list< Event > Events
Definition: QueryState.h:95
Event(char const *const name, Events::iterator parent)
Definition: QueryState.cpp:43
Timer(std::shared_ptr< QueryState > &&, Events::iterator event)
Definition: QueryState.cpp:133
void appendNameValuePairs(Pairs &&...pairs)
Definition: QueryState.h:312
static std::atomic< int64_t > s_match
Definition: QueryState.h:241
tuple line
Definition: parse_ast.py:10
Severity
Definition: Logger.h:103
boost::optional< typename Units::rep > duration() const
Definition: QueryState.h:106
int64_t const match_
Definition: QueryState.h:246
std::shared_ptr< QueryState > query_state_
Definition: QueryState.h:263
Clock::time_point const start_
Definition: QueryState.h:245
std::function< void(Event const &)> EventFunction
Definition: QueryState.h:115
StdLog(char const *file, unsigned line, char const *func, std::shared_ptr< Catalog_Namespace::SessionInfo > session_info, std::shared_ptr< QueryState > query_state, Pairs &&...pairs)
Definition: QueryState.h:281
std::mutex events_mutex_
Definition: QueryState.h:137
char const *const func_
Definition: QueryState.h:244
Events::iterator event_
Definition: QueryState.h:215
StdLog(char const *file, unsigned line, char const *func, Pairs &&...pairs)
Definition: QueryState.h:304
std::string public_session_id
Definition: QueryState.h:125
QueryState * operator->() const
Definition: QueryState.h:181
bool emptyLog() const
Definition: QueryState.h:158
void log(logger::Severity, char const *label)
Definition: QueryState.cpp:217
std::shared_ptr< Catalog_Namespace::SessionInfo const > getConstSessionInfo() const
Definition: QueryState.cpp:150
CircleBuffer circle_buffer_
Definition: QueryState.h:189
std::shared_ptr< Catalog_Namespace::SessionInfo const > getConstSessionInfo() const
Definition: QueryState.cpp:84
Timer createTimer(char const *event_name, Events::iterator parent)
Definition: QueryState.cpp:79
std::chrono::steady_clock Clock
Definition: QueryState.h:92
const std::string getQuerySubmittedTime() const
Definition: QueryState.cpp:101
std::atomic< bool > logged_
Definition: QueryState.h:138
char const *const name
Definition: QueryState.h:98
bool isLogged() const
Definition: QueryState.h:163