forked from npshub/mantid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UsageService.cpp
345 lines (290 loc) · 10.3 KB
/
UsageService.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source,
// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
// SPDX - License - Identifier: GPL - 3.0 +
#include "MantidKernel/UsageService.h"
#include "MantidKernel/ChecksumHelper.h"
#include "MantidKernel/ConfigService.h"
#include "MantidKernel/DateAndTime.h"
#include "MantidKernel/Exception.h"
#include "MantidKernel/InternetHelper.h"
#include "MantidKernel/Logger.h"
#include "MantidKernel/MantidVersion.h"
#include <Poco/ActiveResult.h>
#include <Poco/String.h>
#include <algorithm>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <json/json.h>
namespace {
constexpr auto SEPARATOR = "->";
}
namespace Mantid {
namespace Kernel {
/// static logger
Kernel::Logger g_log("UsageServiceImpl");
//----------------------------------------------------------------------------------------------
/** FeatureUsage
*/
FeatureUsage::FeatureUsage(const FeatureType &type, std::string name, const bool internal, std::string application)
: type(type), name(std::move(name)), internal(internal), application(std::move(application)) {}
// Better brute force.
bool FeatureUsage::operator<(const FeatureUsage &r) const {
if (type < r.type)
return true;
if (type > r.type)
return false;
// Otherwise type are equal
if (name < r.name)
return true;
if (name > r.name)
return false;
// Otherwise name are equal
if (static_cast<int>(internal) < static_cast<int>(r.internal))
return true;
if (static_cast<int>(internal) > static_cast<int>(r.internal))
return false;
// Otherwise all are equal
return false;
}
/// Convert the stored feature type enum to a string
std::string FeatureUsage::featureTypeToString() const {
switch (type) {
case FeatureType::Algorithm:
return "Algorithm";
case FeatureType::Feature:
return "Feature";
case FeatureType::Interface:
return "Interface";
case FeatureType::Function:
return "Function";
}
return "Unknown";
}
::Json::Value FeatureUsage::asJson() const {
::Json::Value retVal;
retVal["type"] = featureTypeToString();
retVal["name"] = name;
retVal["internal"] = internal;
retVal["application"] = application;
return retVal;
}
//----------------------------------------------------------------------------------------------
/** Constructor for UsageServiceImpl
*/
UsageServiceImpl::UsageServiceImpl()
: m_timer(), m_timerTicks(0), m_timerTicksTarget(0), m_FeatureQueue(), m_FeatureQueueSizeThreshold(50),
m_isEnabled(false), m_mutex(), m_application("python"), m_startTime(Types::Core::DateAndTime::getCurrentTime()),
m_startupActiveMethod(this, &UsageServiceImpl::sendStartupAsyncImpl),
m_featureActiveMethod(this, &UsageServiceImpl::sendFeatureAsyncImpl) {
setInterval(60);
auto url = Mantid::Kernel::ConfigService::Instance().getValue<std::string>("usagereports.rooturl");
if (!url.is_initialized()) {
g_log.debug() << "Failed to load usage report url\n";
} else {
m_url = url.get();
g_log.debug() << "Root usage reporting url is " << m_url << "\n";
};
}
void UsageServiceImpl::setApplicationName(const std::string &name) { m_application = name; }
std::string UsageServiceImpl::getApplicationName() const { return m_application; }
void UsageServiceImpl::setInterval(const uint32_t seconds) {
// set the ticks target to by 24 hours / interval
m_timerTicksTarget = 24 * 60 * 60 / seconds;
m_timer.setStartInterval((seconds * 1000));
m_timer.setPeriodicInterval((seconds * 1000));
}
void UsageServiceImpl::registerStartup() {
if (isEnabled()) {
sendStartupReport();
}
}
/** registerFeatureUsage
*/
void UsageServiceImpl::registerFeatureUsage(const FeatureType &type, const std::vector<std::string> &name,
const bool internal) {
if (isEnabled()) {
std::lock_guard<std::mutex> _lock(m_mutex);
using boost::algorithm::join;
m_FeatureQueue.push(FeatureUsage(type, join(name, SEPARATOR), internal, getApplicationName()));
}
}
void UsageServiceImpl::registerFeatureUsage(const FeatureType &type, const std::string &name, const bool internal) {
if (isEnabled()) {
std::lock_guard<std::mutex> _lock(m_mutex);
m_FeatureQueue.push(FeatureUsage(type, name, internal, getApplicationName()));
}
}
void UsageServiceImpl::registerFeatureUsage(const FeatureType &type, std::initializer_list<std::string> name,
const bool internal) {
registerFeatureUsage(type, std::vector<std::string>(name), internal);
}
bool UsageServiceImpl::isEnabled() const { return m_isEnabled; }
void UsageServiceImpl::setEnabled(const bool enabled) {
if (m_isEnabled != enabled) {
if (enabled) {
m_timer.start(Poco::TimerCallback<UsageServiceImpl>(*this, &UsageServiceImpl::timerCallback));
} else {
m_timer.stop();
}
}
m_isEnabled = enabled;
}
void UsageServiceImpl::clear() {
std::queue<FeatureUsage> empty;
std::swap(m_FeatureQueue, empty);
}
void UsageServiceImpl::flush() {
if (isEnabled()) {
sendFeatureUsageReport(true);
}
}
/** getUpTime returns the time for which the mantid instance has been running
@return time_duration The time for which mantid has been running.
*/
Types::Core::time_duration UsageServiceImpl::getUpTime() {
return Types::Core::DateAndTime::getCurrentTime() - m_startTime;
}
void UsageServiceImpl::shutdown() {
try {
// stop the timer
setEnabled(false);
// send any remaining feature usage records
sendFeatureUsageReport(true);
} catch (std::exception &ex) {
g_log.error() << "Error during the shutdown of the UsageService. " << ex.what();
}
}
void UsageServiceImpl::sendStartupReport() {
try {
std::string message = this->generateStartupMessage();
// send the report
Poco::ActiveResult<int> result = m_startupActiveMethod(message);
} catch (std::exception &ex) {
g_log.debug() << "Send startup usage failure. " << ex.what() << '\n';
}
}
void UsageServiceImpl::sendFeatureUsageReport(const bool synchronous = false) {
try {
std::string message = this->generateFeatureUsageMessage();
if (!message.empty()) {
if (synchronous) {
sendFeatureAsyncImpl(message);
} else {
Poco::ActiveResult<int> result = m_featureActiveMethod(message);
}
}
} catch (std::exception &ex) {
g_log.debug() << "sendFeatureUsageReport failure. " << ex.what() << '\n';
}
}
void UsageServiceImpl::timerCallback(Poco::Timer & /*unused*/) {
m_timerTicks++;
if (m_timerTicks > m_timerTicksTarget) {
// send startup report
sendStartupReport();
m_timerTicks = 0;
}
// Check bufferlength
if (m_FeatureQueue.size() > m_FeatureQueueSizeThreshold) {
sendFeatureUsageReport();
}
}
/**
* This puts together the system information for the json document.
*/
::Json::Value UsageServiceImpl::generateFeatureHeader() {
::Json::Value header;
// mantid version and sha1
header["mantidVersion"] = MantidVersion::versionShort();
return header;
}
/**
* This puts together the system information for the json document.
*/
std::string UsageServiceImpl::generateStartupMessage() {
::Json::Value message;
// username
message["uid"] = Kernel::ChecksumHelper::md5FromString(ConfigService::Instance().getUsername());
// hostname
message["host"] = Kernel::ChecksumHelper::md5FromString(ConfigService::Instance().getComputerName());
// os name, version, and architecture
message["osName"] = ConfigService::Instance().getOSName();
message["osArch"] = ConfigService::Instance().getOSArchitecture();
message["osVersion"] = ConfigService::Instance().getOSVersion();
message["osReadable"] = ConfigService::Instance().getOSVersionReadable();
// legacy interface requires paraview version DON'T REMOVE
message["ParaView"] = 0;
// mantid version and sha1
message["mantidVersion"] = MantidVersion::version();
message["mantidSha1"] = MantidVersion::revisionFull();
// mantid version and sha1
message["dateTime"] = m_startTime.toISO8601String();
message["application"] = m_application;
::Json::FastWriter writer;
return writer.write(message);
}
std::string UsageServiceImpl::generateFeatureUsageMessage() {
std::map<FeatureUsage, int> featureCountMap;
if (!m_FeatureQueue.empty()) {
// lock around emptying of the Q so any further threads have to wait
std::lock_guard<std::mutex> _lock(m_mutex);
// generate a map containing the counts of identical feature usage records
while (!m_FeatureQueue.empty()) {
auto featureUsage = m_FeatureQueue.front();
m_FeatureQueue.pop();
if (featureCountMap.find(featureUsage) == featureCountMap.end()) {
featureCountMap[featureUsage] = 1;
} else {
featureCountMap[featureUsage]++;
}
}
}
if (!featureCountMap.empty()) {
::Json::FastWriter writer;
::Json::Value features;
auto message = this->generateFeatureHeader();
for (auto const &featureItem : featureCountMap) {
::Json::Value thisFeature = featureItem.first.asJson();
thisFeature["count"] = featureItem.second;
features.append(thisFeature);
}
if (!features.empty()) {
message["features"] = features;
return writer.write(message);
}
}
return "";
}
//--------------------------------------------------------------------------------------------
/**
* Asynchronous execution
*/
/**Async method for sending startup messages
*/
int UsageServiceImpl::sendStartupAsyncImpl(const std::string &message) {
return this->sendReport(message, m_url + "/api/usage");
}
/**Async method for sending feature messages
*/
int UsageServiceImpl::sendFeatureAsyncImpl(const std::string &message) {
return this->sendReport(message, m_url + "/api/feature");
}
int UsageServiceImpl::sendReport(const std::string &message, const std::string &url) {
int status = -1;
try {
Kernel::InternetHelper helper;
std::stringstream responseStream;
helper.setTimeout(20);
helper.setBody(message);
status = helper.sendRequest(url, responseStream);
} catch (Mantid::Kernel::Exception::InternetError &e) {
status = e.errorCode();
g_log.information() << "Call to \"" << url << "\" responded with " << status << "\n" << e.what() << "\n";
}
return status;
}
} // namespace Kernel
} // namespace Mantid