source: icGREP/icgrep-devel/icgrep/toolchain/object_cache_util.hpp @ 6237

Last change on this file since 6237 was 6228, checked in by nmedfort, 7 months ago

redesign of PopCount? calculation + mem leak fix

File size: 2.3 KB
Line 
1#ifndef OBJECT_CACHE_SETTINGS_H
2#define OBJECT_CACHE_SETTINGS_H
3
4#include <boost/filesystem.hpp>
5#include <boost/lexical_cast.hpp>
6#include <chrono>
7#include <stdlib.h>
8#include <string>
9#include <sys/file.h>
10#include <sys/stat.h>
11#include <fcntl.h>
12#include <fstream>
13
14#define OBJECT_FILE_EXTENSION ".o"
15#define KERNEL_FILE_EXTENSION ".kernel"
16#define CACHE_JANITOR_FILE_NAME "cachejanitord"
17
18#define DAEMON_FILE "cachejanitor.pid"
19
20#define CACHE_ENTRY_MAX_HOURS (7 * 24)
21#define SECONDS_PER_HOUR (60 * 60)
22#define CACHE_ENTRY_EXPIRY_PERIOD (CACHE_ENTRY_MAX_HOURS * SECONDS_PER_HOUR)
23
24#ifdef BOOST_ATTRIBUTE_UNUSED
25#define UNUSED BOOST_ATTRIBUTE_UNUSED
26#else
27#define UNUSED
28#endif
29
30using namespace boost;
31using namespace std::chrono;
32namespace fs = boost::filesystem;
33using ios = std::ios;
34
35inline time_t currentTime() {
36    return system_clock::to_time_t(system_clock::now());
37}
38
39struct FileLock {
40
41    FileLock(const fs::path & cachePath, const bool allowFileCreation = true) noexcept
42    : mFd(open(fs::path{cachePath / DAEMON_FILE}.c_str(),
43               (allowFileCreation ? O_CREAT : O_TRUNC) | O_WRONLY | O_NONBLOCK,
44               S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH))
45    , mLocked(lock(mFd)) {
46
47    }
48
49    bool locked() const {
50        return mLocked;
51    }
52
53    void write_pid() const noexcept {
54        lseek(mFd, 0, SEEK_SET);
55        const auto pid = std::to_string(getpid());
56        UNUSED auto written = write(mFd, pid.c_str(), pid.length());
57        assert (written == static_cast<decltype(written)>(pid.length()));
58    }
59
60    ~FileLock() noexcept {
61        if (locked()) {
62            unlock(mFd);
63            close(mFd);
64        }
65    }
66
67private:
68
69    static bool lock(const int fd) noexcept {
70        if (fd == -1) return false;
71        struct flock lock = {};
72        lock.l_type = F_WRLCK;
73        #if SEEK_SET != 0
74        lock.l_whence = SEEK_SET;
75        #endif
76        return fcntl(fd, F_SETLK, &lock) == 0;
77    }
78
79    static bool unlock(const int fd) noexcept {
80        if (fd == -1) return false;
81        struct flock lock = {};
82        lock.l_type = F_UNLCK;
83        #if SEEK_SET != 0
84        lock.l_whence = SEEK_SET;
85        #endif
86        return fcntl(fd, F_SETLK, &lock) == 0;
87    }
88
89private:
90    const int mFd;
91    const bool mLocked;
92};
93
94#endif // OBJECT_CACHE_SETTINGS_H
Note: See TracBrowser for help on using the repository browser.