OmniSciDB  21ac014ffc
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups 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 #include "Shared/nvtx_helpers.h"
27 #include "Shared/toString.h"
28 
29 #include <algorithm>
30 #include <iomanip>
31 #include <string_view>
32 #include <unordered_map>
33 
34 namespace query_state {
35 
36 Event::Event(char const* name, Events::iterator parent)
37  : name(name)
38  , parent(parent)
39  , thread_id(std::this_thread::get_id())
40  , started(Clock::now().time_since_epoch())
41  , stopped(Clock::duration::zero()) {}
42 
43 void Event::stop() {
44  CHECK(stopped.exchange(Clock::now().time_since_epoch()) == Clock::duration::zero())
45  << "stop() called more than once.";
46 }
47 
49  std::shared_ptr<Catalog_Namespace::SessionInfo const> const& session_info)
50  : session_info(session_info)
51  , db_name(session_info->getCatalog().getCurrentDB().dbName)
52  , user_name(session_info->get_currentUser().userLoggable())
53  , public_session_id(session_info->get_public_session_id()) {}
54 
55 std::atomic<query_state::Id> QueryState::s_next_id{0};
56 
58  std::shared_ptr<Catalog_Namespace::SessionInfo const> const& session_info,
59  std::string query_str)
60  : id_(s_next_id++)
61  , session_data_(session_info ? boost::make_optional<SessionData>(session_info)
62  : boost::none)
63  , query_str_(std::move(query_str))
64  , logged_(false)
65  , submitted_(::toString(std::chrono::system_clock::now())) {}
66 
68  return createQueryStateProxy(events_.end());
69 }
70 
72  return QueryStateProxy(*this, parent);
73 }
74 
75 Timer QueryState::createTimer(char const* event_name, Events::iterator parent) {
76  std::lock_guard<std::mutex> lock(events_mutex_);
77  return Timer(shared_from_this(), events_.emplace(events_.end(), event_name, parent));
78 }
79 
80 std::shared_ptr<Catalog_Namespace::SessionInfo const> QueryState::getConstSessionInfo()
81  const {
82  if (!session_data_) {
83  throw std::runtime_error("session_info_ was not set for this QueryState.");
84  }
85  if (auto retval = session_data_->session_info.lock()) {
86  return retval;
87  } else {
88  // This can happen for a query on a database that is simultaneously dropped.
89  throw std::runtime_error("session_info requested but has expired.");
90  }
91 }
92 
93 void QueryState::setQuerySubmittedTime(const std::string& t) {
94  std::lock_guard<std::mutex> lock(events_mutex_);
95  submitted_ = t;
96 }
97 const std::string QueryState::getQuerySubmittedTime() const {
98  std::lock_guard<std::mutex> lock(events_mutex_);
99  return submitted_;
100 }
101 
102 // Assumes query_state_ is not null, and events_mutex_ is locked for this.
103 void QueryState::logCallStack(std::stringstream& ss,
104  unsigned const depth,
105  Events::iterator parent) {
106  auto it = parent == events_.end() ? events_.begin() : std::next(parent);
107  for (; it != events_.end(); ++it) {
108  if (it->parent == parent) {
109  auto duration = it->duration(); // std::optional, true if event completed
110  ss << '\n'
111  << std::setw(depth << 1) << ' ' << it->name << ' ' << it->thread_id
112  << " - total time " << (duration ? *duration : -1) << " ms";
113  logCallStack(ss, depth + 1, it);
114  // If events_ is expendable, then this can be put here to speed-up large lists.
115  // it = events_.erase(it); } else { ++it; } (and remove above ++it.)
116  }
117  }
118 }
119 
120 void QueryState::logCallStack(std::stringstream& ss) {
121  std::lock_guard<std::mutex> lock(events_mutex_);
122  logCallStack(ss, 1, events_.end());
123 }
124 
125 Timer QueryStateProxy::createTimer(char const* event_name) {
126  return query_state_.createTimer(event_name, parent_);
127 }
128 
129 Timer::Timer(std::shared_ptr<QueryState>&& query_state, Events::iterator event)
130  : query_state_(std::move(query_state)), event_(event) {
133 }
134 
136  return query_state_->createQueryStateProxy(event_);
137 }
138 
140  event_->stop();
142 }
143 
144 std::atomic<int64_t> StdLogData::s_match{0};
145 
146 std::shared_ptr<Catalog_Namespace::SessionInfo const> StdLog::getConstSessionInfo()
147  const {
148  return session_info_;
149 }
150 
151 std::shared_ptr<Catalog_Namespace::SessionInfo> StdLog::getSessionInfo() const {
152  return session_info_;
153 }
154 
156  std::string const& str;
157 };
158 
159 std::ostream& operator<<(std::ostream& os, QuoteFormatter const& quote_formatter) {
160  if (quote_formatter.str.find_first_of(" \"") == std::string::npos) {
161  return os << quote_formatter.str;
162  } else {
163  return os << std::quoted(quote_formatter.str, '"', '"');
164  }
165 }
166 
167 std::ostream& operator<<(std::ostream& os, SessionData const& session_data) {
168  return os << QuoteFormatter{session_data.db_name} << ' '
169  << QuoteFormatter{session_data.user_name} << ' '
170  << session_data.public_session_id;
171 }
172 
175 };
176 
177 std::ostream& operator<<(std::ostream& os, SessionInfoFormatter const& formatter) {
178  return os << QuoteFormatter{formatter.session_info.getCatalog().getCurrentDB().dbName}
179  << ' '
181  << ' ' << formatter.session_info.get_public_session_id();
182 }
183 
184 // Default severity for logging stdlog_begin lines is DEBUG1.
185 // Some functions, such as sql_execute, log them at INFO level.
187  logger::Severity const defaultSeverity = logger::Severity::DEBUG1;
188  static std::unordered_map<std::string_view, logger::Severity> const map{
189  {"connect", logger::Severity::INFO},
190  {"disconnect", logger::Severity::INFO},
191  {"switch_database", logger::Severity::INFO},
192  {"clone_session", logger::Severity::INFO},
193  {"get_tables_meta", logger::Severity::INFO},
194  {"get_table_details", logger::Severity::INFO},
195  {"sql_execute", logger::Severity::INFO},
196  {"sql_execute_df", logger::Severity::INFO},
197  {"sql_execute_gdf", logger::Severity::INFO},
198  {"sql_validate", logger::Severity::INFO},
199  {"render_vega", logger::Severity::INFO},
200  {"get_result_row_for_pixel", logger::Severity::INFO},
201  {"check_table_consistency", logger::Severity::INFO},
202  {"start_query", logger::Severity::INFO},
203  {"execute_query_step", logger::Severity::INFO},
204  {"broadcast_serialized_rows", logger::Severity::INFO},
205  {"start_render_query", logger::Severity::INFO},
206  {"execute_next_render_step", logger::Severity::INFO}};
207  auto const itr = map.find(func);
208  return itr == map.cend() ? defaultSeverity : itr->second;
209 }
210 
211 void StdLog::log(logger::Severity severity, char const* label) {
212  if (logger::fast_logging_check(severity)) {
213  std::stringstream ss;
214  ss << logger::thread_id() << ' ' << file_ << ':' << line_ << ' ' << label << ' '
215  << func_ << ' ' << match_ << ' ' << duration<std::chrono::milliseconds>() << ' ';
216  if (session_info_) {
217  ss << SessionInfoFormatter{*session_info_} << ' ';
218  } else if (query_state_ && query_state_->getSessionData()) {
219  ss << *query_state_->getSessionData() << ' ';
220  } else {
221  ss << " "; // 3 spaces for 3 empty strings
222  }
223  auto const& nv = name_value_pairs_;
224  if (nv.empty() && (!query_state_ || query_state_->emptyLog())) {
225  ss << ' '; // 1 space for final empty names/values arrays
226  } else {
227  // All values are logged after all names, so separate values stream is needed.
228  std::stringstream values;
229  unsigned nvalues = 0;
230  if (query_state_ && !query_state_->getQueryStr().empty()) {
231  ss << (nvalues ? ',' : '{') << std::quoted("query_str", '"', '"');
232  values << (nvalues++ ? ',' : '{')
233  << std::quoted(hide_sensitive_data_from_query(query_state_->getQueryStr()),
234  '"',
235  '"');
236  }
237  for (auto itr = nv.cbegin(); itr != nv.cend(); ++itr) {
238  ss << (nvalues ? ',' : '{') << std::quoted(*itr, '"', '"');
239  values << (nvalues++ ? ',' : '{') << std::quoted(*++itr, '"', '"');
240  }
241  ss << "} " << values.rdbuf() << '}';
242  }
243  BOOST_LOG_SEV(logger::gSeverityLogger::get(), severity) << ss.rdbuf();
244  }
245 }
246 
247 void StdLog::logCallStack(logger::Severity severity, char const* label) {
248  if (logger::fast_logging_check(severity) && query_state_) {
249  std::stringstream ss;
250  ss << file_ << ':' << line_ << ' ' << label << ' ' << func_ << ' ' << match_
251  << " total time " << duration<std::chrono::milliseconds>() << " ms";
252  query_state_->logCallStack(ss);
253  BOOST_LOG_SEV(logger::gSeverityLogger::get(), severity) << ss.rdbuf();
254  }
255 }
256 
258  log(logger::Severity::INFO, "stdlog");
259  logCallStack(logger::Severity::DEBUG1, "stacked_times");
260  if (query_state_) {
261  query_state_->setLogged(true);
262  }
263  if (session_info_) {
264  session_info_->update_last_used_time();
265  }
266 }
267 
268 void StdLog::setQueryState(std::shared_ptr<QueryState> query_state) {
269  query_state_ = std::move(query_state);
270 }
271 
273  std::shared_ptr<Catalog_Namespace::SessionInfo> session_info) {
274  session_info_ = std::move(session_info);
275 }
276 
277 } // namespace query_state
std::string const & str
Definition: QueryState.cpp:156
std::string hide_sensitive_data_from_query(std::string const &query_str)
unsigned const line_
Definition: QueryState.h:238
boost::optional< SessionData > session_data_
Definition: QueryState.h:127
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:103
QueryStateProxy createQueryStateProxy()
Definition: QueryState.cpp:67
std::string toString(const ExtArgumentType &sig_type)
std::string const & get_public_session_id() const
Definition: SessionInfo.h:85
Events::iterator const parent_
Definition: QueryState.h:169
void omnisci_range_pop()
string name
Definition: setup.in.py:72
void setQuerySubmittedTime(const std::string &t)
Definition: QueryState.cpp:93
void setSessionInfo(std::shared_ptr< Catalog_Namespace::SessionInfo >)
Definition: QueryState.cpp:272
Timer createTimer(char const *event_name)
Definition: QueryState.cpp:125
std::ostream & operator<<(std::ostream &os, QuoteFormatter const &quote_formatter)
Definition: QueryState.cpp:159
QueryState(std::shared_ptr< Catalog_Namespace::SessionInfo const > const &, std::string query_str)
Definition: QueryState.cpp:57
void omnisci_range_push(Category c, const char *name, const char *file)
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:242
std::string submitted_
Definition: QueryState.h:132
bool fast_logging_check(Channel)
Definition: Logger.h:180
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:222
static logger::Severity stdlogBeginSeverity(char const *func)
Definition: QueryState.cpp:186
void setQueryState(std::shared_ptr< QueryState >)
Definition: QueryState.cpp:268
void logCallStack(logger::Severity, char const *label)
Definition: QueryState.cpp:247
std::shared_ptr< Catalog_Namespace::SessionInfo > getSessionInfo() const
Definition: QueryState.cpp:151
Catalog_Namespace::SessionInfo const & session_info
Definition: QueryState.cpp:174
Timer(std::shared_ptr< QueryState > &&, Events::iterator event)
Definition: QueryState.cpp:129
QueryStateProxy createQueryStateProxy()
Definition: QueryState.cpp:135
std::shared_ptr< Catalog_Namespace::SessionInfo > session_info_
Definition: QueryState.h:257
Event(char const *const name, Events::iterator parent)
Definition: QueryState.cpp:36
static std::atomic< int64_t > s_match
Definition: QueryState.h:236
Catalog & getCatalog() const
Definition: SessionInfo.h:67
Severity
Definition: Logger.h:79
int64_t const match_
Definition: QueryState.h:241
std::shared_ptr< QueryState > query_state_
Definition: QueryState.h:258
ThreadId thread_id()
Definition: Logger.cpp:741
bool g_enable_watchdog false
Definition: Execute.cpp:75
#define CHECK(condition)
Definition: Logger.h:206
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
std::string public_session_id
Definition: QueryState.h:116
void log(logger::Severity, char const *label)
Definition: QueryState.cpp:211
std::shared_ptr< Catalog_Namespace::SessionInfo const > getConstSessionInfo() const
Definition: QueryState.cpp:146
std::string userLoggable() const
Definition: SysCatalog.cpp:124
std::shared_ptr< Catalog_Namespace::SessionInfo const > getConstSessionInfo() const
Definition: QueryState.cpp:80
Timer createTimer(char const *event_name, Events::iterator parent)
Definition: QueryState.cpp:75
const UserMetadata & get_currentUser() const
Definition: SessionInfo.h:73
std::chrono::steady_clock Clock
Definition: QueryState.h:82
const std::string getQuerySubmittedTime() const
Definition: QueryState.cpp:97
static std::atomic< Id > s_next_id
Definition: QueryState.h:125