OmniSciDB  94e8789169
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
QueryState.h
Go to the documentation of this file.
1 /*
2  * Copyright 2019 OmniSci, 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 
17 /*
18  * File: QueryState.h
19  * Author: matt.pulver@omnisci.com
20  *
21  */
22 
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  */
75 
76 namespace Catalog_Namespace {
77 class SessionInfo;
78 }
79 
80 namespace query_state {
81 
82 using Clock = std::chrono::steady_clock;
83 using Id = uint64_t;
84 
85 struct Event;
86 using Events = std::list<Event>;
87 
88 struct Event {
89  char const* const name;
90  Events::iterator const parent; // events_.end() = top level query_state
91  std::thread::id const thread_id;
92  Clock::duration const started;
93  // duration is used instead of time_point since it is trivially copyable for atomic.
94  std::atomic<Clock::duration> stopped;
95  Event(char const* const name, Events::iterator parent);
96  template <typename Units = std::chrono::milliseconds>
97  boost::optional<typename Units::rep> duration() const {
98  auto const stop_time = stopped.load();
99  return boost::make_optional(
100  stop_time != Clock::duration::zero(),
101  std::chrono::duration_cast<Units>(stop_time - started).count());
102  }
103  void stop();
104 };
105 
106 using EventFunction = std::function<void(Event const&)>;
107 
108 class QueryStateProxy;
109 class QueryStates;
110 
111 // SessionInfo can expire, so data is copied while available.
112 struct SessionData {
113  std::weak_ptr<Catalog_Namespace::SessionInfo const> session_info;
114  std::string db_name;
115  std::string user_name;
116  std::string public_session_id;
117 
118  SessionData() = default;
119  SessionData(std::shared_ptr<Catalog_Namespace::SessionInfo const> const&);
120 };
121 
122 class Timer;
123 
124 class QueryState : public std::enable_shared_from_this<QueryState> {
125  static std::atomic<Id> s_next_id;
126  Id const id_;
127  boost::optional<SessionData> session_data_;
128  std::string const query_str_;
130  mutable std::mutex events_mutex_;
131  std::atomic<bool> logged_;
132  std::chrono::time_point<std::chrono::system_clock> submitted_;
133  void logCallStack(std::stringstream&, unsigned const depth, Events::iterator parent);
134 
135  // Only shared_ptr instances are allowed due to call to shared_from_this().
136  QueryState(std::shared_ptr<Catalog_Namespace::SessionInfo const> const&,
137  std::string query_str);
138 
139  public:
140  template <typename... ARGS>
141  static std::shared_ptr<QueryState> create(ARGS&&... args) {
142  // Trick to call std::make_shared with private constructors.
143  struct EnableMakeShared : public QueryState {
144  EnableMakeShared(ARGS&&... args) : QueryState(std::forward<ARGS>(args)...) {}
145  };
146  return std::make_shared<EnableMakeShared>(std::forward<ARGS>(args)...);
147  }
149  QueryStateProxy createQueryStateProxy(Events::iterator parent);
150  Timer createTimer(char const* event_name, Events::iterator parent);
151  inline bool emptyLog() const { return events_.empty() && query_str_.empty(); }
152  inline Id getId() const { return id_; }
153  inline std::string const& getQueryStr() const { return query_str_; }
154  // Will throw exception if session_data_.session_info.expired().
155  std::shared_ptr<Catalog_Namespace::SessionInfo const> getConstSessionInfo() const;
156  boost::optional<SessionData> const& getSessionData() const { return session_data_; }
157  inline bool isLogged() const { return logged_.load(); }
158  void logCallStack(std::stringstream&);
160  const std::chrono::time_point<std::chrono::system_clock> t) {
161  submitted_ = t;
162  }
163  inline const std::chrono::time_point<std::chrono::system_clock> getQuerySubmittedTime()
164  const {
165  return submitted_;
166  }
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);
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:127
std::string filename(char const *path)
Definition: Logger.cpp:62
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:91
QueryStateProxy createQueryStateProxy()
Definition: QueryState.cpp:64
boost::optional< SessionData > const & getSessionData() const
Definition: QueryState.h:156
std::string const & getQueryStr() const
Definition: QueryState.h:153
Events::iterator const parent_
Definition: QueryState.h:175
Clock::duration const started
Definition: QueryState.h:92
static std::shared_ptr< QueryState > create(ARGS &&...args)
Definition: QueryState.h:141
Timer & operator=(Timer const &)=delete
CircleBuffer::value_type create(ARGS &&...args)
Definition: QueryState.h:194
Events::iterator const parent
Definition: QueryState.h:90
const std::chrono::time_point< std::chrono::system_clock > getQuerySubmittedTime() const
Definition: QueryState.h:163
void setSessionInfo(std::shared_ptr< Catalog_Namespace::SessionInfo >)
Definition: QueryState.cpp:256
Timer createTimer(char const *event_name)
Definition: QueryState.cpp:113
void setQuerySubmittedTime(const std::chrono::time_point< std::chrono::system_clock > t)
Definition: QueryState.h:159
std::string to_string(char const *&&v)
QueryState(std::shared_ptr< Catalog_Namespace::SessionInfo const > const &, std::string query_str)
Definition: QueryState.cpp:55
Units::rep duration() const
Definition: QueryState.h:319
std::atomic< Clock::duration > stopped
Definition: QueryState.h:94
std::list< std::string > name_value_pairs_
Definition: QueryState.h:247
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
std::string const query_str_
Definition: QueryState.h:128
static logger::Severity stdlogBeginSeverity(char const *func)
Definition: QueryState.cpp:170
QueryState & getQueryState()
Definition: QueryState.h:181
void setQueryState(std::shared_ptr< QueryState >)
Definition: QueryState.cpp:252
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:231
std::shared_ptr< Catalog_Namespace::SessionInfo > getSessionInfo() const
Definition: QueryState.cpp:135
QueryStateProxy(QueryState &query_state, Events::iterator parent)
Definition: QueryState.h:178
std::thread::id const thread_id
Definition: QueryState.h:91
Timer(std::shared_ptr< QueryState > &&, Events::iterator event)
Definition: QueryState.cpp:117
StdLog(char const *file, unsigned line, char const *func, std::shared_ptr< QueryState > query_state, Pairs &&...pairs)
Definition: QueryState.h:294
QueryStateProxy createQueryStateProxy()
Definition: QueryState.cpp:120
std::shared_ptr< Catalog_Namespace::SessionInfo > session_info_
Definition: QueryState.h:262
uint64_t Id
Definition: QueryState.h:83
std::weak_ptr< Catalog_Namespace::SessionInfo const > session_info
Definition: QueryState.h:113
std::list< Event > Events
Definition: QueryState.h:86
Event(char const *const name, Events::iterator parent)
Definition: QueryState.cpp:34
void appendNameValuePairs(Pairs &&...pairs)
Definition: QueryState.h:312
static std::atomic< int64_t > s_match
Definition: QueryState.h:241
Severity
Definition: Logger.h:73
boost::optional< typename Units::rep > duration() const
Definition: QueryState.h:97
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:106
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::chrono::time_point< std::chrono::system_clock > submitted_
Definition: QueryState.h:132
std::mutex events_mutex_
Definition: QueryState.h:130
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:116
bool emptyLog() const
Definition: QueryState.h:151
void log(logger::Severity, char const *label)
Definition: QueryState.cpp:195
std::shared_ptr< Catalog_Namespace::SessionInfo const > getConstSessionInfo() const
Definition: QueryState.cpp:130
CircleBuffer circle_buffer_
Definition: QueryState.h:189
std::shared_ptr< Catalog_Namespace::SessionInfo const > getConstSessionInfo() const
Definition: QueryState.cpp:77
Timer createTimer(char const *event_name, Events::iterator parent)
Definition: QueryState.cpp:72
std::chrono::steady_clock Clock
Definition: QueryState.h:82
std::atomic< bool > logged_
Definition: QueryState.h:131
char const *const name
Definition: QueryState.h:89
bool isLogged() const
Definition: QueryState.h:157
static std::atomic< Id > s_next_id
Definition: QueryState.h:125