Belle II Software  release-08-01-10
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/logging/Logger.h>
11 #include <framework/gearbox/Unit.h>
12 #include <framework/utilities/Utils.h>
13 #include <framework/utilities/EnvironmentVariables.h>
14 
15 #include <curl/curl.h>
16 #include <TMD5.h>
17 #include <TRandom.h>
18 
19 #include <boost/algorithm/string.hpp>
20 
21 #include <chrono>
22 #include <memory>
23 #include <thread>
24 
25 namespace Belle2::Conditions {
27  struct CurlSession {
29  CURL* curl{nullptr};
31  curl_slist* headers{nullptr};
33  char errbuf[CURL_ERROR_SIZE];
35  double lasttime{0};
36  };
37 
38  namespace {
49  size_t write_function(void* buffer, size_t size, size_t nmemb, void* userp)
50  {
51  // size in bytes is size*nmemb so copy the correct amount and return it to curl
52  try {
53  std::ostream& stream = *static_cast<std::ostream*>(userp);
54  stream.write(static_cast<const char*>(buffer), size * nmemb);
55  } catch (std::ios_base::failure& e) {
56  B2ERROR("Writing error while downloading: " << e.code().message() << '(' << e.code().value() << ')');
57  return 0;
58  }
59  return size * nmemb;
60  }
61 
72  int progress_callback(void* clientp, curl_off_t dltotal, curl_off_t dlnow,
73  __attribute((unused)) curl_off_t ultotal, __attribute((unused)) curl_off_t ulnow)
74  {
75  // nothing to show ...
76  if (dlnow == 0) return 0;
77  // otherwise print number of transferred bytes
78  CurlSession& status = *static_cast<CurlSession*>(clientp);
79  double time = Utils::getClock();
80  // make sure we don't print the status too often
81  if (status.lasttime != 0 && (time - status.lasttime) / Unit::ms < 200) {
82  return 0;
83  }
84  status.lasttime = time;
85  if (dltotal > 0) {
86  B2DEBUG(39, "curl:= " << dlnow << " / " << dltotal << " bytes transferred");
87  } else {
88  B2DEBUG(39, "curl:= " << dlnow << " bytes transferred");
89  }
90  return 0;
91  }
92 
103  int debug_callback([[maybe_unused]] CURL* handle, curl_infotype type, char* data, size_t size,
104  [[maybe_unused]] void* userptr)
105  {
106  std::string prefix = "curl:";
107  // Choose loglevel: if type is CURLINFO_TEXT the messages are general
108  // informations about what curl is doing. The more detailed information
109  // about incoming/outgoing headers is a bit less important so give it a
110  // higher log level.
111  int level = 39;
112  if (type == CURLINFO_TEXT) { prefix += "*"; level = 38; }
113  else if (type == CURLINFO_HEADER_OUT) prefix += ">";
114  else if (type == CURLINFO_HEADER_IN) prefix += "<";
115  else return 0;
116  // Convert char* data to a string and strip whitespace ...
117  std::string message(data, size);
118  boost::trim(message);
119  // And log if there's something left
120  if (!message.empty()) B2DEBUG(level, prefix << " " << message);
121  return 0;
122  }
123 
125  std::string getUserAgent()
126  {
127  return "BASF2/" + ::Belle2::EnvironmentVariables::get("BELLE2_RELEASE", "unknown");
128  }
129  }
130  /* We only want to initialize curl once */
131  bool Downloader::s_globalInit{false};
132 
134  {
135  static Downloader instance;
136  return instance;
137  }
138 
140 
141  std::string Downloader::escapeString(const std::string& text)
142  {
143  //make sure we have an active curl session ...
144  auto session = ensureSession(); // cppcheck-suppress unreadVariable
145  char* escaped = curl_easy_escape(m_session->curl, text.c_str(), text.size());
146  if (!escaped) {
147  throw std::runtime_error("Could not escape string");
148  }
149  std::string escapedStr{escaped};
150  curl_free(escaped);
151  return escapedStr;
152  }
153 
155  std::string Downloader::joinWithSlash(const std::string& base, const std::string& rest)
156  {
157  return boost::trim_right_copy_if(base, boost::is_any_of("/")) + "/" +
158  boost::trim_left_copy_if(rest, boost::is_any_of("/"));
159  }
160 
162  {
163  // start a curl session but if there is already one return false
164  if (m_session) return false;
165  // make sure curl is initialized correctly
166  if (!s_globalInit) {
167  curl_global_init(CURL_GLOBAL_ALL);
168  s_globalInit = true;
169  }
170  // create the curl session
171  m_session = std::make_unique<CurlSession>();
172  m_session->curl = curl_easy_init();
173  if (!m_session->curl) {
174  B2FATAL("Cannot initialize libcurl");
175  }
176  m_session->headers = curl_slist_append(nullptr, "Accept: application/json");
177  curl_easy_setopt(m_session->curl, CURLOPT_HTTPHEADER, m_session->headers);
178  curl_easy_setopt(m_session->curl, CURLOPT_TCP_KEEPALIVE, 1L);
179  curl_easy_setopt(m_session->curl, CURLOPT_CONNECTTIMEOUT, m_connectionTimeout);
180  curl_easy_setopt(m_session->curl, CURLOPT_LOW_SPEED_LIMIT, 10 * 1024); //10 kB/s
181  curl_easy_setopt(m_session->curl, CURLOPT_LOW_SPEED_TIME, m_stalledTimeout);
182  curl_easy_setopt(m_session->curl, CURLOPT_WRITEFUNCTION, write_function);
183  curl_easy_setopt(m_session->curl, CURLOPT_VERBOSE, 1);
184  curl_easy_setopt(m_session->curl, CURLOPT_NOPROGRESS, 0);
185  curl_easy_setopt(m_session->curl, CURLOPT_DEBUGFUNCTION, debug_callback);
186  curl_easy_setopt(m_session->curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
187  curl_easy_setopt(m_session->curl, CURLOPT_XFERINFODATA, m_session.get());
188  curl_easy_setopt(m_session->curl, CURLOPT_FAILONERROR, true);
189  curl_easy_setopt(m_session->curl, CURLOPT_ERRORBUFFER, m_session->errbuf);
190  // enable transparent compression support
191  curl_easy_setopt(m_session->curl, CURLOPT_ACCEPT_ENCODING, "");
192  // Set proxy if defined
193  if (EnvironmentVariables::isSet("BELLE2_CONDB_PROXY")) {
194  const std::string proxy = EnvironmentVariables::get("BELLE2_CONDB_PROXY");
195  curl_easy_setopt(m_session->curl, CURLOPT_PROXY, proxy.c_str());
196  }
197  curl_easy_setopt(m_session->curl, CURLOPT_AUTOREFERER, 1L);
198  curl_easy_setopt(m_session->curl, CURLOPT_FOLLOWLOCATION, 1L);
199  curl_easy_setopt(m_session->curl, CURLOPT_MAXREDIRS, 10L);
200  curl_easy_setopt(m_session->curl, CURLOPT_TCP_FASTOPEN, 0L);
201  curl_easy_setopt(m_session->curl, CURLOPT_SSL_VERIFYPEER, 0L);
202  curl_easy_setopt(m_session->curl, CURLOPT_SSL_VERIFYHOST, 0L);
203  curl_easy_setopt(m_session->curl, CURLOPT_SSL_VERIFYSTATUS, 0L);
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  B2DEBUG(37, "Download started ..." << LogVar("url", url));
263  // we might need to try a few times in case of HTTP>=500
264  for (unsigned int retry{1};; ++retry) {
265  //rewind the stream to the beginning
266  buffer.clear();
267  buffer.seekp(0, std::ios::beg);
268  if (!buffer.good()) {
269  throw std::runtime_error("cannot write to stream");
270  }
271  // Set the exception flags to notify us of any problem during writing
272  auto oldExceptionMask = buffer.exceptions();
273  buffer.exceptions(std::ios::failbit | std::ios::badbit);
274  // build the request ...
275  CURLcode res{CURLE_FAILED_INIT};
276  // and set all the curl options
277  curl_easy_setopt(m_session->curl, CURLOPT_URL, url.c_str());
278  curl_easy_setopt(m_session->curl, CURLOPT_WRITEDATA, &buffer);
279  // perform the request ...
280  res = curl_easy_perform(m_session->curl);
281  // flush output
282  buffer.exceptions(oldExceptionMask);
283  buffer.flush();
284  // and check for errors which occurred during download ...
285  if (res != CURLE_OK) {
286  size_t len = strlen(m_session->errbuf);
287  const std::string error = len ? m_session->errbuf : curl_easy_strerror(res);
288  if (m_maxRetries > 0 && res == CURLE_HTTP_RETURNED_ERROR) {
289  if (retry <= m_maxRetries) {
290  // we treat everything below 500 as permanent error with the request,
291  // only retry on 500.
292  long responseCode{0};
293  curl_easy_getinfo(m_session->curl, CURLINFO_RESPONSE_CODE, &responseCode);
294  if (responseCode >= 500) {
295  // use exponential backoff but don't restrict to exact slots like
296  // Ethernet, just use a random wait time between 1s and maxDelay =
297  // 2^(retry)-1 * backoffFactor
298  double maxDelay = (std::pow(2, retry) - 1) * m_backoffFactor;
299  double seconds = gRandom->Uniform(1., maxDelay);
300  B2WARNING("Could not download url, retrying ..."
301  << LogVar("url", url) << LogVar("error", error)
302  << LogVar("try", retry) << LogVar("waiting time", seconds));
303  std::this_thread::sleep_for(std::chrono::milliseconds((int)(seconds * 1e3)));
304  continue;
305  }
306  if (responseCode == 404 and silentOnMissing) return false;
307  }
308  }
309  throw std::runtime_error(error);
310  }
311  break;
312  }
313  // all fine
314  B2DEBUG(37, "Download finished successfully." << LogVar("url", url));
315  return true;
316  }
317 } // namespace Belle2::Conditions
Simple class to encapsulate libcurl as used by the ConditionsDatabase.
Definition: Downloader.h:21
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
bool startSession()
Start a new curl session if none is active at the moment.
Definition: Downloader.cc:161
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 >=500.
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
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:155
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:141
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:133
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:27
CURL * curl
curl session information
Definition: Downloader.cc:29
double lasttime
last time we printed the status (in ns)
Definition: Downloader.cc:35
curl_slist * headers
headers to send with every request
Definition: Downloader.cc:31
char errbuf[CURL_ERROR_SIZE]
error buffer in case some error happens during downloading
Definition: Downloader.cc:33