OmniSciDB  1dac507f6e
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
QueryState.cpp
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.cpp
19  * Author: matt.pulver@omnisci.com
20  *
21  */
22 
23 #include "QueryState.h"
24 #include "Catalog/Catalog.h"
25 #include "Catalog/SessionInfo.h"
26 
27 #include <algorithm>
28 #include <iomanip>
29 
30 namespace query_state {
31 
32 Event::Event(char const* name, Events::iterator parent)
33  : name(name)
34  , parent(parent)
35  , thread_id(std::this_thread::get_id())
36  , started(Clock::now().time_since_epoch())
37  , stopped(Clock::duration::zero()) {}
38 
39 void Event::stop() {
40  CHECK(stopped.exchange(Clock::now().time_since_epoch()) == Clock::duration::zero())
41  << "stop() called more than once.";
42 }
43 
45  std::shared_ptr<Catalog_Namespace::SessionInfo const> const& session_info)
46  : session_info(session_info)
47  , db_name(session_info->getCatalog().getCurrentDB().dbName)
48  , user_name(session_info->get_currentUser().userName)
49  , public_session_id(session_info->get_public_session_id()) {}
50 
51 std::atomic<query_state::Id> QueryState::s_next_id{0};
52 
54  std::shared_ptr<Catalog_Namespace::SessionInfo const> const& session_info,
55  std::string query_str)
56  : id_(s_next_id++)
57  , session_data_(session_info ? boost::make_optional<SessionData>(session_info)
58  : boost::none)
59  , query_str_(std::move(query_str))
60  , logged_(false) {}
61 
63  return createQueryStateProxy(events_.end());
64 }
65 
67  return QueryStateProxy(*this, parent);
68 }
69 
70 Timer QueryState::createTimer(char const* event_name, Events::iterator parent) {
71  std::lock_guard<std::mutex> lock(events_mutex_);
72  return Timer(shared_from_this(), events_.emplace(events_.end(), event_name, parent));
73 }
74 
75 std::shared_ptr<Catalog_Namespace::SessionInfo const> QueryState::getConstSessionInfo()
76  const {
77  if (!session_data_) {
78  throw std::runtime_error("session_info_ was not set for this QueryState.");
79  }
80  if (auto retval = session_data_->session_info.lock()) {
81  return retval;
82  } else {
83  // This can happen for a query on a database that is simultaneously dropped.
84  throw std::runtime_error("session_info requested but has expired.");
85  }
86 }
87 
88 // Assumes query_state_ is not null, and events_mutex_ is locked for this.
89 void QueryState::logCallStack(std::stringstream& ss,
90  unsigned const depth,
91  Events::iterator parent) {
92  auto it = parent == events_.end() ? events_.begin() : std::next(parent);
93  for (; it != events_.end(); ++it) {
94  if (it->parent == parent) {
95  auto duration = it->duration(); // std::optional, true if event completed
96  ss << '\n'
97  << std::setw(depth << 1) << ' ' << it->name << ' ' << it->thread_id
98  << " - total time " << (duration ? *duration : -1) << " ms";
99  logCallStack(ss, depth + 1, it);
100  // If events_ is expendable, then this can be put here to speed-up large lists.
101  // it = events_.erase(it); } else { ++it; } (and remove above ++it.)
102  }
103  }
104 }
105 
106 void QueryState::logCallStack(std::stringstream& ss) {
107  std::lock_guard<std::mutex> lock(events_mutex_);
108  logCallStack(ss, 1, events_.end());
109 }
110 
111 Timer QueryStateProxy::createTimer(char const* event_name) {
112  return query_state_.createTimer(event_name, parent_);
113 }
114 
115 Timer::Timer(std::shared_ptr<QueryState>&& query_state, Events::iterator event)
116  : query_state_(std::move(query_state)), event_(event) {}
117 
119  return query_state_->createQueryStateProxy(event_);
120 }
121 
123  event_->stop();
124 }
125 
126 std::atomic<int64_t> StdLogData::s_match{0};
127 
128 std::shared_ptr<Catalog_Namespace::SessionInfo const> StdLog::getConstSessionInfo()
129  const {
130  return session_info_;
131 }
132 
133 std::shared_ptr<Catalog_Namespace::SessionInfo> StdLog::getSessionInfo() const {
134  return session_info_;
135 }
136 
138  std::string const& str;
139 };
140 
141 std::ostream& operator<<(std::ostream& os, QuoteFormatter const& quote_formatter) {
142  if (quote_formatter.str.find_first_of(" \"") == std::string::npos) {
143  return os << quote_formatter.str;
144  } else {
145  return os << std::quoted(quote_formatter.str, '"', '"');
146  }
147 }
148 
149 std::ostream& operator<<(std::ostream& os, SessionData const& session_data) {
150  return os << QuoteFormatter{session_data.db_name} << ' '
151  << QuoteFormatter{session_data.user_name} << ' '
152  << session_data.public_session_id;
153 }
154 
157 };
158 
159 std::ostream& operator<<(std::ostream& os, SessionInfoFormatter const& formatter) {
160  return os << QuoteFormatter{formatter.session_info.getCatalog().getCurrentDB().dbName}
161  << ' ' << QuoteFormatter{formatter.session_info.get_currentUser().userName}
162  << ' ' << formatter.session_info.get_public_session_id();
163 }
164 
165 void StdLog::log(logger::Severity severity, char const* label) {
166  if (logger::fast_logging_check(severity)) {
167  std::stringstream ss;
168  ss << file_ << ':' << line_ << ' ' << label << ' ' << func_ << ' ' << match_ << ' '
169  << duration<std::chrono::milliseconds>() << ' ';
170  if (session_info_) {
171  ss << SessionInfoFormatter{*session_info_} << ' ';
172  } else if (query_state_ && query_state_->getSessionData()) {
173  ss << *query_state_->getSessionData() << ' ';
174  } else {
175  ss << " "; // 3 spaces for 3 empty strings
176  }
177  auto const& nv = name_value_pairs_;
178  if (nv.empty() && (!query_state_ || query_state_->emptyLog())) {
179  ss << ' '; // 1 space for final empty names/values arrays
180  } else {
181  // All values are logged after all names, so separate values stream is needed.
182  std::stringstream values;
183  unsigned nvalues = 0;
184  if (query_state_ && !query_state_->getQueryStr().empty()) {
185  ss << (nvalues ? ',' : '{') << std::quoted("query_str", '"', '"');
186  values << (nvalues++ ? ',' : '{')
187  << std::quoted(hide_sensitive_data_from_query(query_state_->getQueryStr()),
188  '"',
189  '"');
190  }
191  for (auto itr = nv.cbegin(); itr != nv.cend(); ++itr) {
192  ss << (nvalues ? ',' : '{') << std::quoted(*itr, '"', '"');
193  values << (nvalues++ ? ',' : '{') << std::quoted(*++itr, '"', '"');
194  }
195  ss << "} " << values.rdbuf() << '}';
196  }
197  BOOST_LOG_SEV(logger::gSeverityLogger::get(), severity) << ss.rdbuf();
198  }
199 }
200 
201 void StdLog::logCallStack(logger::Severity severity, char const* label) {
202  if (logger::fast_logging_check(severity) && query_state_) {
203  std::stringstream ss;
204  ss << file_ << ':' << line_ << ' ' << label << ' ' << func_ << ' ' << match_
205  << " total time " << duration<std::chrono::milliseconds>() << " ms";
206  query_state_->logCallStack(ss);
207  BOOST_LOG_SEV(logger::gSeverityLogger::get(), severity) << ss.rdbuf();
208  }
209 }
210 
212  log(logger::Severity::INFO, "stdlog");
213  logCallStack(logger::Severity::DEBUG1, "stacked_times");
214  if (query_state_) {
215  query_state_->setLogged(true);
216  }
217  if (session_info_) {
218  session_info_->update_last_used_time();
219  }
220 }
221 
222 void StdLog::setQueryState(std::shared_ptr<QueryState> query_state) {
223  query_state_ = std::move(query_state);
224 }
225 
227  std::shared_ptr<Catalog_Namespace::SessionInfo> session_info) {
228  session_info_ = std::move(session_info);
229 }
230 
231 } // namespace query_state
std::string const & str
Definition: QueryState.cpp:138
std::string hide_sensitive_data_from_query(std::string const &query_str)
unsigned const line_
Definition: QueryState.h:234
boost::optional< SessionData > session_data_
Definition: QueryState.h:127
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
std::string const & get_public_session_id() const
Definition: SessionInfo.h:105
Events::iterator const parent_
Definition: QueryState.h:166
void setSessionInfo(std::shared_ptr< Catalog_Namespace::SessionInfo >)
Definition: QueryState.cpp:226
Timer createTimer(char const *event_name)
Definition: QueryState.cpp:111
std::ostream & operator<<(std::ostream &os, QuoteFormatter const &quote_formatter)
Definition: QueryState.cpp:141
QueryState(std::shared_ptr< Catalog_Namespace::SessionInfo const > const &, std::string query_str)
Definition: QueryState.cpp:53
This file contains the class specification and related data structures for Catalog.
std::atomic< Clock::duration > stopped
Definition: QueryState.h:94
std::list< std::string > name_value_pairs_
Definition: QueryState.h:238
CHECK(cgen_state)
bool fast_logging_check(Channel)
Definition: Logger.h:171
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:176
void setQueryState(std::shared_ptr< QueryState >)
Definition: QueryState.cpp:222
void logCallStack(logger::Severity, char const *label)
Definition: QueryState.cpp:201
std::shared_ptr< Catalog_Namespace::SessionInfo > getSessionInfo() const
Definition: QueryState.cpp:133
Catalog_Namespace::SessionInfo const & session_info
Definition: QueryState.cpp:156
Timer(std::shared_ptr< QueryState > &&, Events::iterator event)
Definition: QueryState.cpp:115
QueryStateProxy createQueryStateProxy()
Definition: QueryState.cpp:118
std::shared_ptr< Catalog_Namespace::SessionInfo > session_info_
Definition: QueryState.h:253
Event(char const *const name, Events::iterator parent)
Definition: QueryState.cpp:32
static std::atomic< int64_t > s_match
Definition: QueryState.h:232
Catalog & getCatalog() const
Definition: SessionInfo.h:90
Severity
Definition: Logger.h:73
int64_t const match_
Definition: QueryState.h:237
std::shared_ptr< QueryState > query_state_
Definition: QueryState.h:254
bool g_enable_watchdog false
Definition: Execute.cpp:71
std::mutex events_mutex_
Definition: QueryState.h:130
char const *const func_
Definition: QueryState.h:235
Events::iterator event_
Definition: QueryState.h:206
std::string public_session_id
Definition: QueryState.h:116
void log(logger::Severity, char const *label)
Definition: QueryState.cpp:165
std::shared_ptr< Catalog_Namespace::SessionInfo const > getConstSessionInfo() const
Definition: QueryState.cpp:128
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
const UserMetadata & get_currentUser() const
Definition: SessionInfo.h:93
std::chrono::steady_clock Clock
Definition: QueryState.h:82
static std::atomic< Id > s_next_id
Definition: QueryState.h:125