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