Belle II Software development
Downloader.cc
1/**************************************************************************
2 * basf2 (Belle II Analysis Software Framework) *
3 * Author: The Belle II Collaboration *
4 * *
5 * See git log for contributors and copyright holders. *
6 * This file is licensed under LGPL-3.0, see LICENSE.md. *
7 **************************************************************************/
8
9#include <framework/database/Downloader.h>
10#include <framework/core/RandomNumbers.h>
11#include <framework/gearbox/Unit.h>
12#include <framework/logging/Logger.h>
13#include <framework/utilities/Utils.h>
14#include <framework/utilities/EnvironmentVariables.h>
15
16#include <curl/curl.h>
17#include <TMD5.h>
18
19#include <boost/algorithm/string.hpp>
20
21#include <chrono>
22#include <thread>
23
24namespace Belle2::Conditions {
26 struct CurlSession {
28 CURL* curl{nullptr};
30 curl_slist* headers{nullptr};
32 char errbuf[CURL_ERROR_SIZE];
34 double lasttime{0};
35 };
36
37 namespace {
48 size_t write_function(void* buffer, size_t size, size_t nmemb, void* userp)
49 {
50 // size in bytes is size*nmemb so copy the correct amount and return it to curl
51 try {
52 std::ostream& stream = *static_cast<std::ostream*>(userp);
53 stream.write(static_cast<const char*>(buffer), size * nmemb);
54 } catch (std::ios_base::failure& e) {
55 B2ERROR("Writing error while downloading: " << e.code().message() << '(' << e.code().value() << ')');
56 return 0;
57 }
58 return size * nmemb;
59 }
60
71 int progress_callback(void* clientp, curl_off_t dltotal, curl_off_t dlnow,
72 __attribute((unused)) curl_off_t ultotal, __attribute((unused)) curl_off_t ulnow)
73 {
74 // nothing to show ...
75 if (dlnow == 0) return 0;
76 // otherwise print number of transferred bytes
77 CurlSession& status = *static_cast<CurlSession*>(clientp);
78 double time = Utils::getClock();
79 // make sure we don't print the status too often
80 if (status.lasttime != 0 && (time - status.lasttime) / Unit::ms < 200) {
81 return 0;
82 }
83 status.lasttime = time;
84 if (dltotal > 0) {
85 B2DEBUG(39, "curl:= " << dlnow << " / " << dltotal << " bytes transferred");
86 } else {
87 B2DEBUG(39, "curl:= " << dlnow << " bytes transferred");
88 }
89 return 0;
90 }
91
102 int debug_callback([[maybe_unused]] CURL* handle, curl_infotype type, char* data, size_t size,
103 [[maybe_unused]] void* userptr)
104 {
105 std::string prefix = "curl:";
106 // Choose loglevel: if type is CURLINFO_TEXT the messages are general
107 // information about what curl is doing. The more detailed information
108 // about incoming/outgoing headers is a bit less important so give it a
109 // higher log level.
110 int level = 39;
111 if (type == CURLINFO_TEXT) { prefix += "*"; level = 38; }
112 else if (type == CURLINFO_HEADER_OUT) prefix += ">";
113 else if (type == CURLINFO_HEADER_IN) prefix += "<";
114 else return 0;
115 // Convert char* data to a string and strip whitespace ...
116 std::string message(data, size);
117 boost::trim(message);
118 // And log if there's something left
119 if (!message.empty()) B2DEBUG(level, prefix << " " << message);
120 return 0;
121 }
122
124 std::string getUserAgent()
125 {
126 return "BASF2/" + ::Belle2::EnvironmentVariables::get("BELLE2_RELEASE", "unknown");
127 }
128 }
129 /* We only want to initialize curl once */
130 bool Downloader::s_globalInit{false};
131
133 {
134 static Downloader instance;
135 return instance;
136 }
137
139
140 std::string Downloader::escapeString(const std::string& text)
141 {
142 //make sure we have an active curl session ...
143 auto session = ensureSession(); // cppcheck-suppress unreadVariable
144 char* escaped = curl_easy_escape(m_session->curl, text.c_str(), text.size());
145 if (!escaped) {
146 throw std::runtime_error("Could not escape string");
147 }
148 std::string escapedStr{escaped};
149 curl_free(escaped);
150 return escapedStr;
151 }
152
154 std::string Downloader::joinWithSlash(const std::string& base, const std::string& rest)
155 {
156 return boost::trim_right_copy_if(base, boost::is_any_of("/")) + "/" +
157 boost::trim_left_copy_if(rest, boost::is_any_of("/"));
158 }
159
161 {
162 // start a curl session but if there is already one return false
163 if (m_session) return false;
164 // make sure curl is initialized correctly
165 if (!s_globalInit) {
166 curl_global_init(CURL_GLOBAL_ALL);
167 s_globalInit = true;
168 }
169 // create the curl session
170 m_session = std::make_unique<CurlSession>();
171 m_session->curl = curl_easy_init();
172 if (!m_session->curl) {
173 B2FATAL("Cannot initialize libcurl");
174 }
175 m_session->headers = curl_slist_append(nullptr, "Accept: application/json");
176 curl_easy_setopt(m_session->curl, CURLOPT_HTTPHEADER, m_session->headers);
177 curl_easy_setopt(m_session->curl, CURLOPT_TCP_KEEPALIVE, 1L);
178 curl_easy_setopt(m_session->curl, CURLOPT_CONNECTTIMEOUT, m_connectionTimeout);
179 curl_easy_setopt(m_session->curl, CURLOPT_LOW_SPEED_LIMIT, 10 * 1024); //10 kB/s
180 curl_easy_setopt(m_session->curl, CURLOPT_LOW_SPEED_TIME, m_stalledTimeout);
181 curl_easy_setopt(m_session->curl, CURLOPT_WRITEFUNCTION, write_function);
182 curl_easy_setopt(m_session->curl, CURLOPT_VERBOSE, 1);
183 curl_easy_setopt(m_session->curl, CURLOPT_NOPROGRESS, 0);
184 curl_easy_setopt(m_session->curl, CURLOPT_DEBUGFUNCTION, debug_callback);
185 curl_easy_setopt(m_session->curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
186 curl_easy_setopt(m_session->curl, CURLOPT_XFERINFODATA, m_session.get());
187 curl_easy_setopt(m_session->curl, CURLOPT_FAILONERROR, true);
188 curl_easy_setopt(m_session->curl, CURLOPT_ERRORBUFFER, m_session->errbuf);
189 // enable transparent compression support
190 curl_easy_setopt(m_session->curl, CURLOPT_ACCEPT_ENCODING, "");
191 // Set proxy if defined
192 if (EnvironmentVariables::isSet("BELLE2_CONDB_PROXY")) {
193 const std::string proxy = EnvironmentVariables::get("BELLE2_CONDB_PROXY");
194 curl_easy_setopt(m_session->curl, CURLOPT_PROXY, proxy.c_str());
195 }
196 curl_easy_setopt(m_session->curl, CURLOPT_AUTOREFERER, 1L);
197 curl_easy_setopt(m_session->curl, CURLOPT_FOLLOWLOCATION, 1L);
198 curl_easy_setopt(m_session->curl, CURLOPT_MAXREDIRS, 10L);
199 curl_easy_setopt(m_session->curl, CURLOPT_TCP_FASTOPEN, 0L);
200 curl_easy_setopt(m_session->curl, CURLOPT_SSL_VERIFYPEER, 0L);
201 curl_easy_setopt(m_session->curl, CURLOPT_SSL_VERIFYHOST, 0L);
202 curl_easy_setopt(m_session->curl, CURLOPT_SSL_VERIFYSTATUS, 0L);
203 curl_easy_setopt(m_session->curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER);
204 // Don't cache DNS entries, ask the system every time we need to connect ...
205 curl_easy_setopt(m_session->curl, CURLOPT_DNS_CACHE_TIMEOUT, 0L);
206 // and shuffle the addresses so we try a different node, otherwise we might
207 // always get the same address due to system caching and RFC 3484
208 curl_easy_setopt(m_session->curl, CURLOPT_DNS_SHUFFLE_ADDRESSES, 1L);
209 auto version = getUserAgent();
210 curl_easy_setopt(m_session->curl, CURLOPT_USERAGENT, version.c_str());
211 return true;
212 }
213
215 {
216 // if there's a session clean it ...
217 if (m_session) {
218 curl_easy_cleanup(m_session->curl);
219 curl_slist_free_all(m_session->headers);
220 m_session.reset();
221 }
222 }
223
224 std::string Downloader::calculateChecksum(std::istream& input)
225 {
226 // rewind stream
227 input.clear();
228 input.seekg(0, std::ios::beg);
229 // and calculate md5 checksum by feeding it blockwise to the TMD5 update
230 TMD5 md5;
231 char buffer[4096];
232 while (input.good()) {
233 input.read(buffer, 4096);
234 if (input.gcount() == 0) break;
235 md5.Update((unsigned char*)buffer, input.gcount());
236 }
237 // finalize and return output
238 md5.Final();
239 return md5.AsString();
240 }
241
242 void Downloader::setConnectionTimeout(unsigned int timeout)
243 {
244 m_connectionTimeout = timeout;
245 if (m_session) {
246 curl_easy_setopt(m_session->curl, CURLOPT_CONNECTTIMEOUT, m_connectionTimeout);
247 }
248 }
249
250 void Downloader::setStalledTimeout(unsigned int timeout)
251 {
252 m_stalledTimeout = timeout;
253 if (m_session) {
254 curl_easy_setopt(m_session->curl, CURLOPT_LOW_SPEED_TIME, m_stalledTimeout);
255 }
256 }
257
258 bool Downloader::download(const std::string& url, std::ostream& buffer, bool silentOnMissing)
259 {
260 // make sure we have an active curl session ...
261 auto session = ensureSession();
262 // and initialize the internal random number generator
264 B2DEBUG(37, "Download started ..." << LogVar("url", url));
265 // we might need to try a few times in case of HTTP error >= 300
266 for (unsigned int retry{1};; ++retry) {
267 //rewind the stream to the beginning
268 buffer.clear();
269 buffer.seekp(0, std::ios::beg);
270 if (!buffer.good()) {
271 throw std::runtime_error("cannot write to stream");
272 }
273 // Set the exception flags to notify us of any problem during writing
274 auto oldExceptionMask = buffer.exceptions();
275 buffer.exceptions(std::ios::failbit | std::ios::badbit);
276 // build the request ...
277 CURLcode res{CURLE_FAILED_INIT};
278 // and set all the curl options
279 curl_easy_setopt(m_session->curl, CURLOPT_URL, url.c_str());
280 curl_easy_setopt(m_session->curl, CURLOPT_WRITEDATA, &buffer);
281 // perform the request ...
282 res = curl_easy_perform(m_session->curl);
283 // flush output
284 buffer.exceptions(oldExceptionMask);
285 buffer.flush();
286 // and check for errors which occurred during download ...
287 if (res != CURLE_OK) {
288 size_t len = strlen(m_session->errbuf);
289 const std::string error = len ? m_session->errbuf : curl_easy_strerror(res);
290 if (m_maxRetries > 0 && res == CURLE_HTTP_RETURNED_ERROR) {
291 if (retry <= m_maxRetries) {
292 // we treat everything below 300 as permanent error with the request,
293 // while if 300 or above we retry
294 // 404 corresponds to Not Found and we want to treat it differently
295 long responseCode{0};
296 curl_easy_getinfo(m_session->curl, CURLINFO_RESPONSE_CODE, &responseCode);
297 if (responseCode >= 300 and responseCode != 404) {
298 // use exponential backoff but don't restrict to exact slots like
299 // Ethernet, just use a random wait time between 1s and maxDelay =
300 // 2^(retry)-1 * backoffFactor
301 double maxDelay = (std::pow(2, retry) - 1) * m_backoffFactor;
302 // This is an exception in the whole basf2: instead of relying on gRandom for getting a random number,
303 // we rely on a different random number generator, and the reason is:
304 // since the request may fail because of several reasons independent from basf2 (bad connection,
305 // faulty squid cache, etc.), we might retry a new request altering the internal state of the gRandom
306 // instance, spoiling our capability to fully reproduce our results.
307 // In this way, relying on a different generator, we are safe.
308 m_rndDistribution->param(std::uniform_real_distribution<double>::param_type(1.0, maxDelay));
309 double seconds = (*m_rndDistribution)(*m_rnd);
310 B2WARNING("Could not download url, retrying ..."
311 << LogVar("url", url) << LogVar("error", error)
312 << LogVar("try", retry) << LogVar("waiting time", seconds));
313 std::this_thread::sleep_for(std::chrono::milliseconds((int)(seconds * 1e3)));
314 continue;
315 }
316 // special treatment for 404: if silentOnMissing is true we just return false silently
317 // this is useful when checking if a file exists on the server
318 if (responseCode == 404 and silentOnMissing) return false;
319 }
320 }
321 throw std::runtime_error(error);
322 }
323 break;
324 }
325 // all fine
326 B2DEBUG(37, "Download finished successfully." << LogVar("url", url));
327 return true;
328 }
329
331 {
332 if (not m_rndIsInitialized) {
333 // We need to provide a seed for m_rnd: let's take the basf2Seed and hash it
334 auto downloaderSeed = std::hash<std::string> {}(RandomNumbers::getSeed());
335 m_rnd->seed(downloaderSeed);
336 m_rndIsInitialized = true;
337 }
338 }
339} // namespace Belle2::Conditions
Simple class to encapsulate libcurl as used by the ConditionsDatabase.
Definition: Downloader.h:22
void finishSession()
Finish an existing curl session if any is active at the moment.
Definition: Downloader.cc:214
static bool s_globalInit
flag to indicate whether curl has been initialized already
Definition: Downloader.h:98
std::unique_ptr< std::uniform_real_distribution< double > > m_rndDistribution
A uniform real distribution for extracting random numbers.
Definition: Downloader.h:121
bool startSession()
Start a new curl session if none is active at the moment.
Definition: Downloader.cc:160
void initializeRandomGeneratorSeed()
Initialize the seed of the internal random number generator.
Definition: Downloader.cc:330
bool download(const std::string &url, std::ostream &stream, bool silentOnMissing=false)
get an url and save the content to stream This function raises exceptions when there are any problems
Definition: Downloader.cc:258
unsigned int m_maxRetries
Number of retries to perform when downloading fails with HTTP response code >=300.
Definition: Downloader.h:104
unsigned int m_connectionTimeout
Timeout to wait for connections in seconds.
Definition: Downloader.h:100
void setStalledTimeout(unsigned int timeout)
Set the timeout to wait for stalled connections (<10KB/s), 0 disables timeout.
Definition: Downloader.cc:250
std::unique_ptr< CurlSession > m_session
curl session handle
Definition: Downloader.h:96
unsigned int m_stalledTimeout
Timeout to wait for stalled connections (<10KB/s)
Definition: Downloader.h:102
bool m_rndIsInitialized
Flag for keeping track if the internal random generator is correctly initialized or not.
Definition: Downloader.h:123
std::unique_ptr< std::mt19937 > m_rnd
This is a special exception in basf2 where an instance of gRandom is NOT used: since this class inter...
Definition: Downloader.h:119
std::string joinWithSlash(const std::string &base, const std::string &second)
Join two strings and make sure that there is exactly one '/' between them.
Definition: Downloader.cc:154
static std::string calculateChecksum(std::istream &input)
calculate the digest/checksum on a given string.
Definition: Downloader.cc:224
void setConnectionTimeout(unsigned int timeout)
Set the timeout to wait for connections in seconds, 0 means built in curl default.
Definition: Downloader.cc:242
std::string escapeString(const std::string &text)
Escape a string to make it safe to be used in web requests.
Definition: Downloader.cc:140
ScopeGuard ensureSession()
Make sure there's an active session and return a ScopeGuard object that closes the session on destruc...
Definition: Downloader.h:43
unsigned int m_backoffFactor
Backoff factor for retries in seconds.
Definition: Downloader.h:106
static Downloader & getDefaultInstance()
Return the default instance.
Definition: Downloader.cc:132
static std::string getSeed()
Get the random number generator seed.
Definition: RandomNumbers.h:92
static const double ms
[millisecond]
Definition: Unit.h:96
Class to store variables with their name which were sent to the logging service.
static std::string get(const std::string &name, const std::string &fallback="")
Get the value of an environment variable or the given fallback value if the variable is not set.
static bool isSet(const std::string &name)
Check if a value is set in the database.
double getClock()
Return current value of the real-time clock.
Definition: Utils.cc:66
struct encapsulating all the state information needed by curl
Definition: Downloader.cc:26
CURL * curl
curl session information
Definition: Downloader.cc:28
double lasttime
last time we printed the status (in ns)
Definition: Downloader.cc:34
curl_slist * headers
headers to send with every request
Definition: Downloader.cc:30
char errbuf[CURL_ERROR_SIZE]
error buffer in case some error happens during downloading
Definition: Downloader.cc:32