LDMX Software
URLStreamer.cxx
1#include "Conditions/URLStreamer.h"
2
3#include <string.h>
4#include <sys/wait.h>
5#include <unistd.h>
6
7#include <fstream>
8#include <iostream>
9#include <sstream>
10#include <string>
11
12#include "Framework/Exception/Exception.h"
13
14namespace conditions {
15
16static unsigned int http_requests_ = 0;
17static unsigned int http_failures_ = 0;
18
19void urlstatistics(unsigned int& http_requests, unsigned int& http_failures) {
20 http_requests = http_requests_;
21 http_failures = http_failures_;
22}
23
24std::unique_ptr<std::istream> urlstream(const std::string& url) {
25 if (url.find("file://") == 0 || (url.length() > 0 && url[0] == '/')) {
26 std::string fname = url;
27 if (fname.find("file://") == 0)
28 fname = url.substr(url.find("file://") + strlen("file://"));
29 std::ifstream* fs = new std::ifstream(fname);
30 if (!fs->good()) {
31 delete fs;
32 EXCEPTION_RAISE("ConditionsException",
33 "Unable to open CSV file '" + fname + "'");
34 }
35 return std::unique_ptr<std::istream>(fs);
36 }
37 if ((url.find("http://") != std::string::npos) ||
38 (url.find("https://") != std::string::npos)) {
39 http_requests_++;
40 // this implementation uses wget to handle the SSL processes
41 static int istream = 0;
42 char fname[250];
43 snprintf(fname, 250, "/tmp/httpstream_%d_%d.csv ", getpid(), istream++);
44 pid_t apid = fork();
45 if (apid == 0) { // child
46 execl("/usr/bin/wget", "wget", "-q", "--no-check-certificate", "-O",
47 fname, "-o", "/tmp/wget.log", url.c_str(), (char*)0);
48 } else {
49 int wstatus;
50 waitpid(apid, &wstatus, 0);
51 // std::cout << "EXITED: " << WIFEXITED(wstatus) << " STATUS: " <<
52 // WEXITSTATUS(wstatus) << std::endl;
53 if (WIFEXITED(wstatus) != 1 || WEXITSTATUS(wstatus) != 0) {
54 http_failures_++;
55 EXCEPTION_RAISE("ConditionsException",
56 "Wget error " + std::to_string(WEXITSTATUS(wstatus)) +
57 " retreiving URL '" + url + "'");
58 }
59 }
60 std::ifstream ib(fname);
61 if (ib.bad()) {
62 http_failures_++;
63 EXCEPTION_RAISE("ConditionsException",
64 "Bad/empty file retreiving URL '" + url + "'");
65 }
66 std::stringstream* ss = new std::stringstream();
67 (*ss) << ib.rdbuf();
68 // std::cout << "CONTENTS: \n" << ss->str();
69 ib.close(); // needed for some implementations
70 std::remove(fname);
71 return std::unique_ptr<std::istream>(ss);
72 }
73 EXCEPTION_RAISE("ConditionsException", "Unable to handle URL '" + url + "'");
74 return std::unique_ptr<std::istream>(nullptr);
75}
76
77} // namespace conditions