comparison Framework/Orthanc/Core/SystemToolbox.cpp @ 15:da2cf3ace87a

sync
author Sebastien Jodogne <s.jodogne@gmail.com>
date Wed, 09 Nov 2016 17:20:44 +0100
parents
children
comparison
equal deleted inserted replaced
14:0b9034112fde 15:da2cf3ace87a
1 /**
2 * Orthanc - A Lightweight, RESTful DICOM Store
3 * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
4 * Department, University Hospital of Liege, Belgium
5 *
6 * This program is free software: you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation, either version 3 of the
9 * License, or (at your option) any later version.
10 *
11 * In addition, as a special exception, the copyright holders of this
12 * program give permission to link the code of its release with the
13 * OpenSSL project's "OpenSSL" library (or with modified versions of it
14 * that use the same license as the "OpenSSL" library), and distribute
15 * the linked executables. You must obey the GNU General Public License
16 * in all respects for all of the code used other than "OpenSSL". If you
17 * modify file(s) with this exception, you may extend this exception to
18 * your version of the file(s), but you are not obligated to do so. If
19 * you do not wish to do so, delete this exception statement from your
20 * version. If you delete this exception statement from all source files
21 * in the program, then also delete it here.
22 *
23 * This program is distributed in the hope that it will be useful, but
24 * WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
26 * General Public License for more details.
27 *
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30 **/
31
32
33 #include "PrecompiledHeaders.h"
34 #include "SystemToolbox.h"
35
36
37 #if BOOST_HAS_DATE_TIME == 1
38 #include <boost/date_time/posix_time/posix_time.hpp>
39 #endif
40
41
42 #if defined(_WIN32)
43 #include <windows.h>
44 #include <process.h> // For "_spawnvp()" and "_getpid()"
45 #else
46 #include <unistd.h> // For "execvp()"
47 #include <sys/wait.h> // For "waitpid()"
48 #endif
49
50 #if defined(__APPLE__) && defined(__MACH__)
51 #include <mach-o/dyld.h> /* _NSGetExecutablePath */
52 #include <limits.h> /* PATH_MAX */
53 #endif
54
55 #if defined(__linux__) || defined(__FreeBSD_kernel__) || defined(__FreeBSD__)
56 #include <limits.h> /* PATH_MAX */
57 #include <signal.h>
58 #include <unistd.h>
59 #endif
60
61
62 #include "Logging.h"
63 #include "OrthancException.h"
64 #include "Toolbox.h"
65
66 #include <boost/filesystem.hpp>
67 #include <boost/filesystem/fstream.hpp>
68
69
70 namespace Orthanc
71 {
72 static bool finish_;
73 static ServerBarrierEvent barrierEvent_;
74
75 #if defined(_WIN32)
76 static BOOL WINAPI ConsoleControlHandler(DWORD dwCtrlType)
77 {
78 // http://msdn.microsoft.com/en-us/library/ms683242(v=vs.85).aspx
79 finish_ = true;
80 return true;
81 }
82 #else
83 static void SignalHandler(int signal)
84 {
85 if (signal == SIGHUP)
86 {
87 barrierEvent_ = ServerBarrierEvent_Reload;
88 }
89
90 finish_ = true;
91 }
92 #endif
93
94
95 static ServerBarrierEvent ServerBarrierInternal(const bool* stopFlag)
96 {
97 #if defined(_WIN32)
98 SetConsoleCtrlHandler(ConsoleControlHandler, true);
99 #else
100 signal(SIGINT, SignalHandler);
101 signal(SIGQUIT, SignalHandler);
102 signal(SIGTERM, SignalHandler);
103 signal(SIGHUP, SignalHandler);
104 #endif
105
106 // Active loop that awakens every 100ms
107 finish_ = false;
108 barrierEvent_ = ServerBarrierEvent_Stop;
109 while (!(*stopFlag || finish_))
110 {
111 Toolbox::USleep(100 * 1000);
112 }
113
114 #if defined(_WIN32)
115 SetConsoleCtrlHandler(ConsoleControlHandler, false);
116 #else
117 signal(SIGINT, NULL);
118 signal(SIGQUIT, NULL);
119 signal(SIGTERM, NULL);
120 signal(SIGHUP, NULL);
121 #endif
122
123 return barrierEvent_;
124 }
125
126
127 ServerBarrierEvent SystemToolbox::ServerBarrier(const bool& stopFlag)
128 {
129 return ServerBarrierInternal(&stopFlag);
130 }
131
132
133 ServerBarrierEvent SystemToolbox::ServerBarrier()
134 {
135 const bool stopFlag = false;
136 return ServerBarrierInternal(&stopFlag);
137 }
138
139
140 static std::streamsize GetStreamSize(std::istream& f)
141 {
142 // http://www.cplusplus.com/reference/iostream/istream/tellg/
143 f.seekg(0, std::ios::end);
144 std::streamsize size = f.tellg();
145 f.seekg(0, std::ios::beg);
146
147 return size;
148 }
149
150
151 void SystemToolbox::ReadFile(std::string& content,
152 const std::string& path)
153 {
154 if (!IsRegularFile(path))
155 {
156 LOG(ERROR) << std::string("The path does not point to a regular file: ") << path;
157 throw OrthancException(ErrorCode_RegularFileExpected);
158 }
159
160 boost::filesystem::ifstream f;
161 f.open(path, std::ifstream::in | std::ifstream::binary);
162 if (!f.good())
163 {
164 throw OrthancException(ErrorCode_InexistentFile);
165 }
166
167 std::streamsize size = GetStreamSize(f);
168 content.resize(size);
169 if (size != 0)
170 {
171 f.read(reinterpret_cast<char*>(&content[0]), size);
172 }
173
174 f.close();
175 }
176
177
178 bool SystemToolbox::ReadHeader(std::string& header,
179 const std::string& path,
180 size_t headerSize)
181 {
182 if (!IsRegularFile(path))
183 {
184 LOG(ERROR) << std::string("The path does not point to a regular file: ") << path;
185 throw OrthancException(ErrorCode_RegularFileExpected);
186 }
187
188 boost::filesystem::ifstream f;
189 f.open(path, std::ifstream::in | std::ifstream::binary);
190 if (!f.good())
191 {
192 throw OrthancException(ErrorCode_InexistentFile);
193 }
194
195 bool full = true;
196
197 {
198 std::streamsize size = GetStreamSize(f);
199 if (size <= 0)
200 {
201 headerSize = 0;
202 full = false;
203 }
204 else if (static_cast<size_t>(size) < headerSize)
205 {
206 headerSize = size; // Truncate to the size of the file
207 full = false;
208 }
209 }
210
211 header.resize(headerSize);
212 if (headerSize != 0)
213 {
214 f.read(reinterpret_cast<char*>(&header[0]), headerSize);
215 }
216
217 f.close();
218
219 return full;
220 }
221
222
223 void SystemToolbox::WriteFile(const void* content,
224 size_t size,
225 const std::string& path)
226 {
227 boost::filesystem::ofstream f;
228 f.open(path, std::ofstream::out | std::ofstream::binary);
229 if (!f.good())
230 {
231 throw OrthancException(ErrorCode_CannotWriteFile);
232 }
233
234 if (size != 0)
235 {
236 f.write(reinterpret_cast<const char*>(content), size);
237
238 if (!f.good())
239 {
240 f.close();
241 throw OrthancException(ErrorCode_FileStorageCannotWrite);
242 }
243 }
244
245 f.close();
246 }
247
248
249 void SystemToolbox::WriteFile(const std::string& content,
250 const std::string& path)
251 {
252 WriteFile(content.size() > 0 ? content.c_str() : NULL,
253 content.size(), path);
254 }
255
256
257 void SystemToolbox::RemoveFile(const std::string& path)
258 {
259 if (boost::filesystem::exists(path))
260 {
261 if (IsRegularFile(path))
262 {
263 boost::filesystem::remove(path);
264 }
265 else
266 {
267 throw OrthancException(ErrorCode_RegularFileExpected);
268 }
269 }
270 }
271
272
273 uint64_t SystemToolbox::GetFileSize(const std::string& path)
274 {
275 try
276 {
277 return static_cast<uint64_t>(boost::filesystem::file_size(path));
278 }
279 catch (boost::filesystem::filesystem_error&)
280 {
281 throw OrthancException(ErrorCode_InexistentFile);
282 }
283 }
284
285
286 void SystemToolbox::MakeDirectory(const std::string& path)
287 {
288 if (boost::filesystem::exists(path))
289 {
290 if (!boost::filesystem::is_directory(path))
291 {
292 throw OrthancException(ErrorCode_DirectoryOverFile);
293 }
294 }
295 else
296 {
297 if (!boost::filesystem::create_directories(path))
298 {
299 throw OrthancException(ErrorCode_MakeDirectory);
300 }
301 }
302 }
303
304
305 bool SystemToolbox::IsExistingFile(const std::string& path)
306 {
307 return boost::filesystem::exists(path);
308 }
309
310
311 #if defined(_WIN32)
312 static std::string GetPathToExecutableInternal()
313 {
314 // Yes, this is ugly, but there is no simple way to get the
315 // required buffer size, so we use a big constant
316 std::vector<char> buffer(32768);
317 /*int bytes =*/ GetModuleFileNameA(NULL, &buffer[0], static_cast<DWORD>(buffer.size() - 1));
318 return std::string(&buffer[0]);
319 }
320
321 #elif defined(__linux__) || defined(__FreeBSD_kernel__) || defined(__FreeBSD__)
322 static std::string GetPathToExecutableInternal()
323 {
324 std::vector<char> buffer(PATH_MAX + 1);
325 ssize_t bytes = readlink("/proc/self/exe", &buffer[0], buffer.size() - 1);
326 if (bytes == 0)
327 {
328 throw OrthancException(ErrorCode_PathToExecutable);
329 }
330
331 return std::string(&buffer[0]);
332 }
333
334 #elif defined(__APPLE__) && defined(__MACH__)
335 static std::string GetPathToExecutableInternal()
336 {
337 char pathbuf[PATH_MAX + 1];
338 unsigned int bufsize = static_cast<int>(sizeof(pathbuf));
339
340 _NSGetExecutablePath( pathbuf, &bufsize);
341
342 return std::string(pathbuf);
343 }
344
345 #else
346 #error Support your platform here
347 #endif
348
349
350 std::string SystemToolbox::GetPathToExecutable()
351 {
352 boost::filesystem::path p(GetPathToExecutableInternal());
353 return boost::filesystem::absolute(p).string();
354 }
355
356
357 std::string SystemToolbox::GetDirectoryOfExecutable()
358 {
359 boost::filesystem::path p(GetPathToExecutableInternal());
360 return boost::filesystem::absolute(p.parent_path()).string();
361 }
362
363
364 void SystemToolbox::ExecuteSystemCommand(const std::string& command,
365 const std::vector<std::string>& arguments)
366 {
367 // Convert the arguments as a C array
368 std::vector<char*> args(arguments.size() + 2);
369
370 args.front() = const_cast<char*>(command.c_str());
371
372 for (size_t i = 0; i < arguments.size(); i++)
373 {
374 args[i + 1] = const_cast<char*>(arguments[i].c_str());
375 }
376
377 args.back() = NULL;
378
379 int status;
380
381 #if defined(_WIN32)
382 // http://msdn.microsoft.com/en-us/library/275khfab.aspx
383 status = static_cast<int>(_spawnvp(_P_OVERLAY, command.c_str(), &args[0]));
384
385 #else
386 int pid = fork();
387
388 if (pid == -1)
389 {
390 // Error in fork()
391 #if ORTHANC_ENABLE_LOGGING == 1
392 LOG(ERROR) << "Cannot fork a child process";
393 #endif
394
395 throw OrthancException(ErrorCode_SystemCommand);
396 }
397 else if (pid == 0)
398 {
399 // Execute the system command in the child process
400 execvp(command.c_str(), &args[0]);
401
402 // We should never get here
403 _exit(1);
404 }
405 else
406 {
407 // Wait for the system command to exit
408 waitpid(pid, &status, 0);
409 }
410 #endif
411
412 if (status != 0)
413 {
414 #if ORTHANC_ENABLE_LOGGING == 1
415 LOG(ERROR) << "System command failed with status code " << status;
416 #endif
417
418 throw OrthancException(ErrorCode_SystemCommand);
419 }
420 }
421
422
423 int SystemToolbox::GetProcessId()
424 {
425 #if defined(_WIN32)
426 return static_cast<int>(_getpid());
427 #else
428 return static_cast<int>(getpid());
429 #endif
430 }
431
432
433 bool SystemToolbox::IsRegularFile(const std::string& path)
434 {
435 namespace fs = boost::filesystem;
436
437 try
438 {
439 if (fs::exists(path))
440 {
441 fs::file_status status = fs::status(path);
442 return (status.type() == boost::filesystem::regular_file ||
443 status.type() == boost::filesystem::reparse_file); // Fix BitBucket issue #11
444 }
445 }
446 catch (fs::filesystem_error&)
447 {
448 }
449
450 return false;
451 }
452
453
454 FILE* SystemToolbox::OpenFile(const std::string& path,
455 FileMode mode)
456 {
457 #if defined(_WIN32)
458 // TODO Deal with special characters by converting to the current locale
459 #endif
460
461 const char* m;
462 switch (mode)
463 {
464 case FileMode_ReadBinary:
465 m = "rb";
466 break;
467
468 case FileMode_WriteBinary:
469 m = "wb";
470 break;
471
472 default:
473 throw OrthancException(ErrorCode_ParameterOutOfRange);
474 }
475
476 return fopen(path.c_str(), m);
477 }
478
479
480 #if BOOST_HAS_DATE_TIME == 1
481 std::string SystemToolbox::GetNowIsoString()
482 {
483 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
484 return boost::posix_time::to_iso_string(now);
485 }
486
487 void SystemToolbox::GetNowDicom(std::string& date,
488 std::string& time)
489 {
490 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
491 tm tm = boost::posix_time::to_tm(now);
492
493 char s[32];
494 sprintf(s, "%04d%02d%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
495 date.assign(s);
496
497 // TODO milliseconds
498 sprintf(s, "%02d%02d%02d.%06d", tm.tm_hour, tm.tm_min, tm.tm_sec, 0);
499 time.assign(s);
500 }
501 #endif
502 }