summaryrefslogtreecommitdiff
path: root/src/timer_state.cc
blob: 8a0844ca32b137e5b14c9a21f8c998a4bc4d5b23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
#include "common.hh"

#include "io.hh"
#include "timer_state.hh"
#include "unique_fd.hh"

#include <errno.h>
#include <fcntl.h>
#include <functional>
#include <iostream>
#include <sdbus-c++/sdbus-c++.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <thread>

namespace {

const sdbus::ServiceName kServiceName{"org.the_jk.timer"};
const sdbus::ObjectPath kObjectPath{"/org/the_jk/timer/state"};
const sdbus::InterfaceName kInterfaceName{"org.the_jk.timer.State"};

class TimerStateImpl {
public:
  virtual ~TimerStateImpl() = default;

  virtual void start() = 0;
  virtual void stop() = 0;
  virtual void reset() = 0;

  virtual void enterLoop() {
    conn_->enterEventLoop();
  }

  virtual void leaveLoop() {
    conn_->leaveEventLoop();
  }

protected:
  TimerStateImpl(std::shared_ptr<sdbus::IConnection> conn,
                 TimerState::Delegate* delegate)
    : conn_(std::move(conn)), delegate_(delegate) {
  }

  std::shared_ptr<sdbus::IConnection> conn_;
  TimerState::Delegate* const delegate_;
};

class TimerStateClient : public TimerStateImpl {
public:
  TimerStateClient(std::shared_ptr<sdbus::IConnection> conn,
                   TimerState::Delegate* delegate)
    : TimerStateImpl(std::move(conn), delegate) {}

  void start() override {
    try {
      proxy_->callMethod("start").onInterface(kInterfaceName).dontExpectReply();
    } catch (sdbus::Error const& err) {
      std::cerr << "Failed to call start: " << err.what() << std::endl;
    }
  }

  void stop() override {
    try {
      proxy_->callMethod("stop").onInterface(kInterfaceName).dontExpectReply();
    } catch (sdbus::Error const& err) {
      std::cerr << "Failed to call stop: " << err.what() << std::endl;
    }
  }

  void reset() override {
    try {
      proxy_->callMethod("reset").onInterface(kInterfaceName).dontExpectReply();
    } catch (sdbus::Error const& err) {
      std::cerr << "Failed to call reset: " << err.what() << std::endl;
    }
  }

  bool init() {
    try {
      proxy_ = sdbus::createProxy(*conn_.get(), kServiceName, kObjectPath);
      proxy_->uponSignal("started").onInterface(kInterfaceName)
        .call([this](uint32_t total, int64_t epoch){
          signal_started(std::chrono::minutes(total),
                         std::chrono::system_clock::from_time_t(epoch));
        });
      proxy_->uponSignal("stopped").onInterface(kInterfaceName)
        .call([this](uint32_t total){
          signal_stopped(std::chrono::minutes(total));
        });
      proxy_->uponSignal("reset").onInterface(kInterfaceName)
        .call([this](){ signal_reset(); });

      dbus_proxy_ = sdbus::createProxy(*conn_.get(), sdbus::ServiceName{"org.freedesktop.DBus"},
                                       sdbus::ObjectPath{"/org/freedesktop/DBus"});
      dbus_proxy_->uponSignal("NameOwnerChanged")
        .onInterface("org.freedesktop.DBus")
        .call([this](const std::string& name,
                     const std::string& /* old_owner */,
                     const std::string& new_owner) {
          if (name == kServiceName && new_owner.empty()) {
            signal_restart();
          }
        });

      sync_state();
    } catch (sdbus::Error const& err) {
      std::cerr << "Failed to init client: " << err.what() << std::endl;
      return false;
    }

    return true;
  }

private:
  void signal_started(
      std::chrono::minutes total,
      std::chrono::time_point<std::chrono::system_clock> epoch) {
    delegate_->start(total, epoch);
  }

  void signal_stopped(std::chrono::minutes total) {
    delegate_->stop(total);
  }

  void signal_reset() {
    delegate_->reset();
  }

  void signal_restart() {
    delegate_->restart();
  }

  void sync_state() {
    auto method = proxy_->createMethodCall(kInterfaceName, sdbus::MethodName{"get_state"});
    auto reply = proxy_->callMethod(std::move(method));
    bool active;
    uint32_t total;
    int64_t epoch;
    reply >> active;
    reply >> total;
    reply >> epoch;
    if (active) {
      delegate_->start(std::chrono::minutes(total),
                       std::chrono::system_clock::from_time_t(epoch));
    } else {
      delegate_->stop(std::chrono::minutes(total));
    }
  }

  std::unique_ptr<sdbus::IProxy> proxy_;
  std::unique_ptr<sdbus::IProxy> dbus_proxy_;
};

class TimerStateServer : public TimerStateImpl {
public:
  TimerStateServer(std::shared_ptr<sdbus::IConnection> conn,
                   TimerState::Delegate* delegate)
    : TimerStateImpl(std::move(conn), delegate) {}

  void start() override {
    if (active_) return;
    active_ = true;
    start_ = std::chrono::system_clock::now();
    write_state();

    try {
      object_->emitSignal("started").onInterface(kInterfaceName).withArguments(
          static_cast<uint32_t>(total_.count()),
          static_cast<int64_t>(std::chrono::system_clock::to_time_t(start_)));
    } catch (sdbus::Error const& err) {
      std::cerr << "Failed to emit started: " << err.what() << std::endl;
    }
    delegate_->start(total_, start_);
  }

  void stop() override {
    if (!active_) return;
    active_ = false;
    total_ +=
      std::chrono::duration_cast<std::chrono::minutes>(
          std::chrono::system_clock::now() - start_);
    write_state();

    try {
      object_->emitSignal("stopped").onInterface(kInterfaceName).withArguments(
          static_cast<uint32_t>(total_.count()));
    } catch (sdbus::Error const& err) {
      std::cerr << "Failed to emit started: " << err.what() << std::endl;
    }
    delegate_->stop(total_);
  }

  void reset() override {
    if (active_) return;
    total_ = std::chrono::minutes::zero();
    write_state();

    try {
      object_->emitSignal("reset").onInterface(kInterfaceName);
    } catch (sdbus::Error const& err) {
      std::cerr << "Failed to emit reset: " << err.what() << std::endl;
    }
    delegate_->reset();
  }

  bool init(std::filesystem::path state_file) {
    if (!load_state(state_file))
      return false;

    try {
      auto object = sdbus::createObject(*conn_.get(), kObjectPath);
      auto start = [this]() { this->start(); };
      auto stop = [this]() { this->stop(); };
      auto reset = [this]() { this->reset(); };
      auto get_state = std::bind(&TimerStateServer::get_state, this, std::placeholders::_1);
      object->addVTable(
          sdbus::registerMethod("start").implementedAs(std::move(start)).withNoReply(),
          sdbus::registerMethod("stop").implementedAs(std::move(stop)).withNoReply(),
          sdbus::registerMethod("reset").implementedAs(std::move(reset)).withNoReply(),
          sdbus::MethodVTableItem{
            sdbus::MethodName{"get_state"}, sdbus::Signature{""}, {}, sdbus::Signature{"bux"}, {}, get_state, {}
          },
          sdbus::registerSignal("started").withParameters<uint32_t, int64_t>(),
          sdbus::registerSignal("stopped").withParameters<uint32_t>(),
          sdbus::registerSignal("reset")
      ).forInterface(kInterfaceName);

      object_ = std::move(object);
    } catch (sdbus::Error const& err) {
      std::cerr << "Failed to init server: " << err.what() << std::endl;
      return false;
    }

    if (active_) {
      delegate_->start(total_, start_);
    } else {
      delegate_->stop(total_);
    }

    return true;
  }

private:
  void get_state(sdbus::MethodCall call) {
    try {
      auto reply = call.createReply();
      reply << active_;
      reply << static_cast<uint32_t>(total_.count());
      if (active_) {
        reply << static_cast<int64_t>(
            std::chrono::system_clock::to_time_t(start_));
      } else {
        reply << static_cast<int64_t>(0);
      }
      reply.send();
    } catch (sdbus::Error const& err) {
      std::cerr << "Failed to reply to get_state: " << err.what() << std::endl;
    }
  }

  bool load_state(std::filesystem::path state_file) {
    fd_.reset(open(state_file.c_str(), O_RDWR | O_CREAT, S_IRWXU));
    if (!fd_) {
      std::cerr << "Unable to open or create " << state_file
                << " for reading and writing." << std::endl;
      return false;
    }
    if (flock(fd_.get(), LOCK_EX | LOCK_NB)) {
      std::cerr << "Unable to get exclusive lock on " << state_file
                << ": " << strerror(errno) << std::endl;
      return false;
    }
    std::string data;
    if (!io::read_all(fd_.get(), &data)) {
      std::cerr << "Error reading " << state_file
                << ": " << strerror(errno) << std::endl;
      return false;
    }
    if (data.empty()) {
      // Newly created file.
      active_ = false;
      total_ = std::chrono::minutes::zero();
    } else {
      if (!parse_state(std::move(data))) {
        std::cerr << "Invalid data in state " << state_file
                  << "." << std::endl;
        return false;
      }
    }
    return true;
  }

  bool parse_state(std::string data) {
    try {
      size_t end;
      auto active = std::stol(data, &end);
      if (end == data.size() || data[end] != '|')
        return false;
      data = data.substr(end + 1);
      auto total = std::stoul(data, &end);
      if (end == data.size() || data[end] != '|')
        return false;
      struct tm tm;
      auto* endp = strptime(
          data.substr(end + 1).c_str(), "%Y-%m-%d %H:%M:%S", &tm);
      if (!endp || (*endp != '\0' && *endp != '\n'))
        return false;

      active_ = active == 1;
      total_ = std::chrono::minutes(total);
      start_ = std::chrono::system_clock::from_time_t(timegm(&tm));

      return true;
    } catch (std::exception const& e) {
      return false;
    }
  }

  bool write_state() {
    std::string data =
      std::to_string(active_ ? 1L : -1L) + '|' + std::to_string(
          std::chrono::duration_cast<std::chrono::minutes>(total_).count())
      + '|';
    char tmp[50];
    auto time = std::chrono::system_clock::to_time_t(start_);
    auto len = strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", gmtime(&time));
    if (len == 0 || len == sizeof(tmp)) {
      std::cerr << "Failed to store state: invalid time." << std::endl;
      return false;
    }
    data.append(tmp, len);
    data.push_back('\n');
    if (lseek(fd_.get(), 0, SEEK_SET) ||
        !io::write_all(fd_.get(), data) ||
        ftruncate(fd_.get(), data.size())) {
      std::cerr << "Failed to store state: " << strerror(errno) << std::endl;
      return false;
    }
    return true;
  }

  bool active_{false};
  std::chrono::minutes total_{0};
  std::chrono::time_point<std::chrono::system_clock> start_;
  std::unique_ptr<sdbus::IObject> object_;
  unique_fd fd_;
};

class TimerStateWrapper : public TimerState {
public:
  explicit TimerStateWrapper(Delegate* delegate)
    : delegate_(delegate) {}

  ~TimerStateWrapper() override {
    if (impl_) impl_->leaveLoop();
    thread_.join();
  }

  bool init(std::filesystem::path state_file) {
    try {
      std::shared_ptr<sdbus::IConnection> conn(
          sdbus::createSessionBusConnection());

      try {
        conn->requestName(kServiceName);

        auto server = std::make_unique<TimerStateServer>(conn, delegate_);
        if (server->init(std::move(state_file))) {
          impl_ = std::move(server);
          return post_init();
        }
        // If server fails to init in any way, try client as backup.
      } catch (sdbus::Error const& e) {
        // This is here to catch requestName call, if requestName fails there
        // is a server running.
      }

      auto client = std::make_unique<TimerStateClient>(conn, delegate_);
      if (client->init()) {
        impl_ = std::move(client);
        return post_init();
      }
    } catch (sdbus::Error const& e) {
    }
    return false;
  }

  void start() override {
    impl_->start();
  }

  void stop() override {
    impl_->stop();
  }

  void reset() override {
    impl_->reset();
  }

private:
  bool post_init() {
    thread_ = std::thread(&TimerStateWrapper::run_impl, this);
    return true;
  }

  void run_impl() {
    impl_->enterLoop();
  }

  Delegate* const delegate_;
  std::unique_ptr<TimerStateImpl> impl_;
  std::thread thread_;
};

}  // namespace

std::unique_ptr<TimerState> TimerState::create(std::filesystem::path state_file,
                                               Delegate* delegate) {
  auto state = std::make_unique<TimerStateWrapper>(delegate);
  return state->init(std::move(state_file)) ? std::move(state) : nullptr;
}