OmniSciDB  fe05a0c208
 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::string 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&);
159  void setQuerySubmittedTime(const std::string& t);
160  const std::string getQuerySubmittedTime() const;
161  inline void setLogged(bool logged) { logged_.store(logged); }
162  friend class QueryStates;
163 };
164 
165 // Light-weight class used as intermediary between Timer objects spawning child Timers.
166 // Assumes lifetime is less than original QueryState.
169  Events::iterator const parent_;
170 
171  public:
172  QueryStateProxy(QueryState& query_state, Events::iterator parent)
173  : query_state_(query_state), parent_(parent) {}
174  Timer createTimer(char const* event_name);
176  const QueryState& getConstQueryState() const { return query_state_; }
177 };
178 
179 // At this point it is not clear how long we want to keep completed queries.
180 // The data structure and lifetime are not currently settled upon.
181 class QueryStates {
182  using CircleBuffer = boost::circular_buffer<std::shared_ptr<QueryState>>;
183  // constexpr size_t MAX_SIZE_BEFORE_OVERWRITE = 128; // C++17
185  std::mutex circle_mutex_;
186 
187  public:
188  template <typename... ARGS>
189  CircleBuffer::value_type create(ARGS&&... args) {
190  std::lock_guard<std::mutex> lock(circle_mutex_);
191  /* Logic for ensuring QueryState objects are logged before deleting them.
192  if (circle_buffer_.full() && !circle_buffer_.front()->isLogged()) {
193  constexpr size_t MAX_SIZE_BEFORE_OVERWRITE = 128;
194  if (circle_buffer_.size() < MAX_SIZE_BEFORE_OVERWRITE) {
195  circle_buffer_.set_capacity(2 * circle_buffer_.capacity());
196  } else {
197  LOG(ERROR) << "QueryStates is holding " << circle_buffer_.size()
198  << " queries but the oldest query_state has not completed
199  logging.";
200  }
201  }
202  */
203  circle_buffer_.push_back(QueryState::create(std::forward<ARGS>(args)...));
204  return circle_buffer_.back();
205  }
206 };
207 
208 class Timer {
209  std::shared_ptr<QueryState> query_state_;
210  Events::iterator event_; // = pointer into QueryState::events_
211 
212  public:
213  Timer(std::shared_ptr<QueryState>&&, Events::iterator event);
214  Timer(Timer const&) = delete;
215  Timer& operator=(Timer const&) = delete;
216  Timer(Timer&&) = default;
217  Timer& operator=(Timer&&) = default;
218  ~Timer();
220 };
221 
222 // Log Format:
223 // YYYY-MM-DDTHH:MM::SS.FFFFFF [S] [pid] [file]:[line] [label] [func] [match] [dur_ms]
224 // [dbname] [user] [pubsessid] {[names]} {[values]}
225 // Call at both beginning(label="stdlog_begin") and end(label="stdlog") of Thrift call,
226 // with dur_ms = current age of StdLog object in milliseconds.
227 // stdlog_begin is logged at DEBUG1 level, stdlog is logged at INFO level.
228 // All remaining optional parameters are name,value pairs that will be included in log.
229 #define STDLOG(...) \
230  BOOST_PP_IF(BOOST_PP_IS_EMPTY(__VA_ARGS__), \
231  query_state::StdLog(__FILE__, __LINE__, __func__), \
232  query_state::StdLog(__FILE__, __LINE__, __func__, __VA_ARGS__))
233 
234 class StdLogData {
235  protected:
236  static std::atomic<int64_t> s_match;
237  std::string const file_;
238  unsigned const line_;
239  char const* const func_;
240  Clock::time_point const start_;
241  int64_t const match_; // Unique to each begin/end pair to match them together.
242  std::list<std::string> name_value_pairs_;
243  template <typename... Pairs>
244  StdLogData(char const* file, unsigned line, char const* func, Pairs&&... pairs)
245  : file_(boost::filesystem::path(file).filename().string())
246  , line_(line)
247  , func_(func)
248  , start_(Clock::now())
249  , match_(s_match++)
250  , name_value_pairs_{to_string(std::forward<Pairs>(pairs))...} {
251  static_assert(sizeof...(Pairs) % 2 == 0,
252  "StdLogData() requires an even number of name/value parameters.");
253  }
254 };
255 
256 class StdLog : public StdLogData {
257  std::shared_ptr<Catalog_Namespace::SessionInfo> session_info_;
258  std::shared_ptr<QueryState> query_state_;
259  void log(logger::Severity, char const* label);
260  void logCallStack(logger::Severity, char const* label);
261  static logger::Severity stdlogBeginSeverity(char const* func);
262 
263  public:
264  template <typename... Pairs>
265  StdLog(char const* file,
266  unsigned line,
267  char const* func,
268  std::shared_ptr<Catalog_Namespace::SessionInfo> session_info,
269  Pairs&&... pairs)
270  : StdLogData(file, line, func, std::forward<Pairs>(pairs)...)
271  , session_info_(std::move(session_info)) {
272  log(stdlogBeginSeverity(func), "stdlog_begin");
273  }
274 
275  template <typename... Pairs>
276  StdLog(char const* file,
277  unsigned line,
278  char const* func,
279  std::shared_ptr<Catalog_Namespace::SessionInfo> session_info,
280  std::shared_ptr<QueryState> query_state,
281  Pairs&&... pairs)
282  : StdLogData(file, line, func, std::forward<Pairs>(pairs)...)
283  , session_info_(std::move(session_info))
284  , query_state_(std::move(query_state)) {
285  log(stdlogBeginSeverity(func), "stdlog_begin");
286  }
287 
288  template <typename... Pairs>
289  StdLog(char const* file,
290  unsigned line,
291  char const* func,
292  std::shared_ptr<QueryState> query_state,
293  Pairs&&... pairs)
294  : StdLogData(file, line, func, std::forward<Pairs>(pairs)...)
295  , query_state_(std::move(query_state)) {
296  log(stdlogBeginSeverity(func), "stdlog_begin");
297  }
298  template <typename... Pairs>
299  StdLog(char const* file, unsigned line, char const* func, Pairs&&... pairs)
300  : StdLogData(file, line, func, std::forward<Pairs>(pairs)...) {
301  log(stdlogBeginSeverity(func), "stdlog_begin");
302  }
303  StdLog(StdLog const&) = delete;
304  StdLog(StdLog&&) = default;
305  ~StdLog();
306  template <typename... Pairs>
307  void appendNameValuePairs(Pairs&&... pairs) {
308  static_assert(sizeof...(Pairs) % 2 == 0,
309  "appendNameValuePairs() requires an even number of parameters.");
310  name_value_pairs_.splice(name_value_pairs_.cend(),
311  {to_string(std::forward<Pairs>(pairs))...});
312  }
313  template <typename Units = std::chrono::milliseconds>
314  typename Units::rep duration() const {
315  return std::chrono::duration_cast<Units>(Clock::now() - start_).count();
316  }
317  std::shared_ptr<Catalog_Namespace::SessionInfo const> getConstSessionInfo() const;
318  std::shared_ptr<Catalog_Namespace::SessionInfo> getSessionInfo() const;
319  void setQueryState(std::shared_ptr<QueryState>);
320  void setSessionInfo(std::shared_ptr<Catalog_Namespace::SessionInfo>);
321 };
322 
323 } // namespace query_state
324 
325 #endif // OMNISCI_THRIFTHANDLER_QUERYSTATE_H
unsigned const line_
Definition: QueryState.h:238
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:209
std::string const file_
Definition: QueryState.h:237
void logCallStack(std::stringstream &, unsigned const depth, Events::iterator parent)
Definition: QueryState.cpp:102
QueryStateProxy createQueryStateProxy()
Definition: QueryState.cpp:66
boost::optional< SessionData > const & getSessionData() const
Definition: QueryState.h:156
const QueryState & getConstQueryState() const
Definition: QueryState.h:176
std::string const & getQueryStr() const
Definition: QueryState.h:153
Events::iterator const parent_
Definition: QueryState.h:169
Clock::duration const started
Definition: QueryState.h:92
static std::shared_ptr< QueryState > create(ARGS &&...args)
Definition: QueryState.h:141
void setQuerySubmittedTime(const std::string &t)
Definition: QueryState.cpp:92
Timer & operator=(Timer const &)=delete
CircleBuffer::value_type create(ARGS &&...args)
Definition: QueryState.h:189
Events::iterator const parent
Definition: QueryState.h:90
void setSessionInfo(std::shared_ptr< Catalog_Namespace::SessionInfo >)
Definition: QueryState.cpp:267
Timer createTimer(char const *event_name)
Definition: QueryState.cpp:124
std::string to_string(char const *&&v)
QueryState(std::shared_ptr< Catalog_Namespace::SessionInfo const > const &, std::string query_str)
Definition: QueryState.cpp:56
Units::rep duration() const
Definition: QueryState.h:314
std::atomic< Clock::duration > stopped
Definition: QueryState.h:94
std::list< std::string > name_value_pairs_
Definition: QueryState.h:242
std::string submitted_
Definition: QueryState.h:132
StdLogData(char const *file, unsigned line, char const *func, Pairs &&...pairs)
Definition: QueryState.h:244
void setLogged(bool logged)
Definition: QueryState.h:161
boost::circular_buffer< std::shared_ptr< QueryState >> CircleBuffer
Definition: QueryState.h:182
std::string const query_str_
Definition: QueryState.h:128
static logger::Severity stdlogBeginSeverity(char const *func)
Definition: QueryState.cpp:181
QueryState & getQueryState()
Definition: QueryState.h:175
void setQueryState(std::shared_ptr< QueryState >)
Definition: QueryState.cpp:263
int count
StdLog(char const *file, unsigned line, char const *func, std::shared_ptr< Catalog_Namespace::SessionInfo > session_info, Pairs &&...pairs)
Definition: QueryState.h:265
void logCallStack(logger::Severity, char const *label)
Definition: QueryState.cpp:242
std::shared_ptr< Catalog_Namespace::SessionInfo > getSessionInfo() const
Definition: QueryState.cpp:146
QueryStateProxy(QueryState &query_state, Events::iterator parent)
Definition: QueryState.h:172
std::thread::id const thread_id
Definition: QueryState.h:91
Timer(std::shared_ptr< QueryState > &&, Events::iterator event)
Definition: QueryState.cpp:128
StdLog(char const *file, unsigned line, char const *func, std::shared_ptr< QueryState > query_state, Pairs &&...pairs)
Definition: QueryState.h:289
QueryStateProxy createQueryStateProxy()
Definition: QueryState.cpp:131
std::shared_ptr< Catalog_Namespace::SessionInfo > session_info_
Definition: QueryState.h:257
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:35
void appendNameValuePairs(Pairs &&...pairs)
Definition: QueryState.h:307
static std::atomic< int64_t > s_match
Definition: QueryState.h:236
Severity
Definition: Logger.h:79
boost::optional< typename Units::rep > duration() const
Definition: QueryState.h:97
int64_t const match_
Definition: QueryState.h:241
std::shared_ptr< QueryState > query_state_
Definition: QueryState.h:258
Clock::time_point const start_
Definition: QueryState.h:240
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:276
char * t
std::mutex events_mutex_
Definition: QueryState.h:130
char const *const func_
Definition: QueryState.h:239
Events::iterator event_
Definition: QueryState.h:210
StdLog(char const *file, unsigned line, char const *func, Pairs &&...pairs)
Definition: QueryState.h:299
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:206
std::shared_ptr< Catalog_Namespace::SessionInfo const > getConstSessionInfo() const
Definition: QueryState.cpp:141
CircleBuffer circle_buffer_
Definition: QueryState.h:184
std::shared_ptr< Catalog_Namespace::SessionInfo const > getConstSessionInfo() const
Definition: QueryState.cpp:79
Timer createTimer(char const *event_name, Events::iterator parent)
Definition: QueryState.cpp:74
std::chrono::steady_clock Clock
Definition: QueryState.h:82
const std::string getQuerySubmittedTime() const
Definition: QueryState.cpp:96
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