function_scheduler.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. #include "function_scheduler.hpp"
  2. #include "db_gateway.hpp"
  3. #include "function_jobs.hpp"
  4. #include "function_record.hpp"
  5. #include "function_registry.hpp"
  6. #include "functions/cron.hpp"
  7. #include "functions/timezone.hpp"
  8. #include <spdlog/spdlog.h>
  9. #include <chrono>
  10. #include <optional>
  11. #include <utility>
  12. #include <vector>
  13. namespace svapi {
  14. namespace {
  15. /// The key under which a function's last fired minute is remembered. '\x1f'
  16. /// (unit separator) cannot appear in a project name - the project charset is
  17. /// restricted because /fn/{project}/* is unauthenticated - so two different
  18. /// (project, function) pairs cannot collide on one key.
  19. std::string lastFiredKey(const std::string& project, const std::string& functionId) {
  20. return project + '\x1f' + functionId;
  21. }
  22. } // namespace
  23. FunctionScheduler::FunctionScheduler(DbGateway& db, FunctionRegistry& registry,
  24. FunctionJobQueue& jobs, FunctionSchedulerOptions opts)
  25. : db_(db), registry_(registry), jobs_(jobs), opts_(opts) {
  26. // A tick interval of a minute or more silently drops schedules, so refuse to
  27. // carry a configured value that cannot work. Clamping loudly beats firing
  28. // "most" minutes and leaving an operator to wonder which ones.
  29. if (opts_.tickIntervalSec == 0 || opts_.tickIntervalSec >= 60) {
  30. spdlog::warn("function scheduler tick interval {}s cannot see every cron minute; "
  31. "using 20s", opts_.tickIntervalSec);
  32. opts_.tickIntervalSec = 20;
  33. }
  34. }
  35. FunctionScheduler::~FunctionScheduler() { stop(); }
  36. void FunctionScheduler::start() {
  37. {
  38. std::lock_guard<std::mutex> lk(m_);
  39. if (started_) return;
  40. started_ = true;
  41. stop_ = false;
  42. }
  43. th_ = std::thread([this] { loop(); });
  44. spdlog::info("function scheduler started (tick {}s, reclaim {}s, claim timeout {}s)",
  45. opts_.tickIntervalSec, opts_.reclaimIntervalSec, opts_.claimTimeoutSec);
  46. }
  47. void FunctionScheduler::stop() {
  48. {
  49. std::lock_guard<std::mutex> lk(m_);
  50. if (!started_) return;
  51. stop_ = true;
  52. }
  53. cv_.notify_all();
  54. if (th_.joinable()) th_.join();
  55. std::lock_guard<std::mutex> lk(m_);
  56. started_ = false;
  57. }
  58. bool FunctionScheduler::running() const {
  59. std::lock_guard<std::mutex> lk(m_);
  60. return started_ && !stop_;
  61. }
  62. uint32_t FunctionScheduler::reclaimOnce() {
  63. std::lock_guard<std::mutex> pass(passM_);
  64. try {
  65. const uint32_t n = jobs_.reclaimStale(opts_.claimTimeoutSec, opts_.maxAttempts);
  66. // Worth an info line: a non-zero count means a runner died holding work,
  67. // which is the kind of thing an operator wants to see in the journal
  68. // rather than infer from a job that ran twice.
  69. if (n > 0) spdlog::info("reclaimed {} stale function job(s)", n);
  70. return n;
  71. } catch (const std::exception& e) {
  72. spdlog::warn("function job reclaim failed: {}", e.what());
  73. return 0;
  74. }
  75. }
  76. uint32_t FunctionScheduler::tickOnce(std::time_t now) {
  77. std::lock_guard<std::mutex> pass(passM_);
  78. const std::time_t minute = minuteFloor(now);
  79. uint32_t enqueued = 0;
  80. std::unordered_map<std::string, std::time_t> stillPresent;
  81. std::vector<std::string> projects;
  82. try {
  83. projects = db_.listProjects();
  84. } catch (const std::exception& e) {
  85. // No project list means no pass. Deliberately not fatal and deliberately
  86. // not remembered: the next tick tries again, and because nothing was
  87. // recorded in lastFired_, a minute lost to a database blip can still
  88. // fire on a later tick within the same minute.
  89. spdlog::warn("function scheduler could not list projects: {}", e.what());
  90. return 0;
  91. }
  92. for (const std::string& project : projects) {
  93. std::vector<FunctionRecord> rows;
  94. try {
  95. rows = registry_.list(project);
  96. } catch (const std::exception& e) {
  97. spdlog::warn("function scheduler could not read registry for '{}': {}",
  98. project, e.what());
  99. // Keep this project's lastFired_ entries: dropping them on a
  100. // transient read failure would re-fire the current minute once the
  101. // read recovers.
  102. for (const auto& [key, when] : lastFired_)
  103. if (key.rfind(project + '\x1f', 0) == 0) stillPresent[key] = when;
  104. continue;
  105. }
  106. for (const FunctionRecord& row : rows) {
  107. // A disabled or invalid function does not run. Its lastFired_ entry
  108. // is dropped with it, so re-enabling starts from "has not fired",
  109. // which is the same thing a restart does.
  110. if (!row.enabled || !row.valid) continue;
  111. const functions::ParseResult parsed = functions::parseDescriptor(row.descriptor);
  112. if (!parsed.ok || parsed.descriptor.type != functions::TriggerType::Cron) continue;
  113. std::string cronError;
  114. const std::optional<functions::CronExpr> expr =
  115. functions::CronExpr::parse(parsed.descriptor.schedule, &cronError);
  116. if (!expr) {
  117. // The write path validates the schedule with this same parser,
  118. // so reaching here means a row was written by an older or
  119. // broken path. Say so once per tick rather than silently never
  120. // firing, which is indistinguishable from a broken scheduler.
  121. spdlog::warn("cron function {}/{} has an unusable schedule '{}': {}",
  122. project, row.functionId, parsed.descriptor.schedule, cronError);
  123. continue;
  124. }
  125. const std::string key = lastFiredKey(project, row.functionId);
  126. const auto it = lastFired_.find(key);
  127. const std::time_t last = it == lastFired_.end() ? 0 : it->second;
  128. stillPresent[key] = last;
  129. // The descriptor's `tz`, empty for a schedule that did not declare
  130. // one. It has to reach the matcher: evaluated in UTC instead, an
  131. // 08:00 Budapest schedule fires at 09:00 local in winter and 10:00
  132. // in summer, and a schedule that drifts by an hour twice a year is
  133. // not something anybody notices quickly.
  134. const std::string& zone = parsed.descriptor.timezone;
  135. if (!zone.empty() && !functions::timezoneKnown(zone)) {
  136. // The write path validates `tz` against the same host tz
  137. // database, so reaching here means the row predates that check
  138. // or tzdata went away under us. Never firing is the safe
  139. // answer - a silent UTC fallback would move the author's 08:00
  140. // report - but it must be said out loud, because "never fires"
  141. // and "broken scheduler" look identical from outside.
  142. spdlog::warn("cron function {}/{} declares time zone '{}', which this host "
  143. "does not know; it will not fire until tzdata provides it",
  144. project, row.functionId, zone);
  145. continue;
  146. }
  147. const functions::CronExpr e = *expr;
  148. if (!cronDue([&e, &zone](std::time_t t) { return e.matchesIn(t, zone); }, now, last))
  149. continue;
  150. bool active = false;
  151. try {
  152. active = jobs_.hasActive(project, row.functionId);
  153. } catch (const std::exception& ex) {
  154. // Unknown whether a job is active. Treat it as active: skipping
  155. // a tick loses one run, queueing a second copy of a job that is
  156. // already running breaks the guarantee the author asked for.
  157. spdlog::warn("single-flight check failed for {}/{}, skipping this tick: {}",
  158. project, row.functionId, ex.what());
  159. active = true;
  160. }
  161. if (skipForSingleFlight(parsed.descriptor.singleFlight, active)) {
  162. spdlog::info("cron tick skipped for {}/{}: previous job still pending or "
  163. "claimed (single flight)", project, row.functionId);
  164. // The minute is consumed even though nothing was queued, so the
  165. // next two ticks inside this minute do not re-log the same skip.
  166. stillPresent[key] = minute;
  167. continue;
  168. }
  169. FunctionJob job;
  170. // jobId is left empty: the queue assigns it and enqueue() returns it.
  171. job.project = project;
  172. job.functionId = row.functionId;
  173. job.trigger = "cron";
  174. job.payload = nlohmann::json{{"schedule", parsed.descriptor.schedule},
  175. {"scheduled_at", static_cast<int64_t>(minute)}};
  176. // A cron run starts a trigger chain rather than continuing one, so it
  177. // is always depth 0. If it writes to a watched table, the event
  178. // watcher is what counts from here.
  179. job.depth = 0;
  180. job.runAfter = static_cast<uint64_t>(minute);
  181. job.createdAt = static_cast<uint64_t>(now);
  182. std::string jobId;
  183. try {
  184. jobId = jobs_.enqueue(job);
  185. } catch (const std::exception& ex) {
  186. spdlog::warn("could not enqueue cron job for {}/{}: {}",
  187. project, row.functionId, ex.what());
  188. }
  189. if (jobId.empty()) {
  190. // Not recorded as fired, so a later tick in the same minute can
  191. // still get this run out. Losing a run to a database blip when a
  192. // retry was available would be our bug, not the database's.
  193. spdlog::warn("cron job for {}/{} was not enqueued; will retry this minute",
  194. project, row.functionId);
  195. continue;
  196. }
  197. stillPresent[key] = minute;
  198. ++enqueued;
  199. spdlog::debug("enqueued cron job {} for {}/{}", jobId, project, row.functionId);
  200. }
  201. }
  202. // Prune: a function that no longer exists, or is no longer an enabled valid
  203. // cron function, must not keep an entry forever. The map is rebuilt from
  204. // what this pass actually saw.
  205. lastFired_ = std::move(stillPresent);
  206. return enqueued;
  207. }
  208. void FunctionScheduler::loop() {
  209. std::time_t lastReclaim = 0;
  210. for (;;) {
  211. const std::time_t now = std::time(nullptr);
  212. try {
  213. tickOnce(now);
  214. } catch (const std::exception& e) {
  215. // The loop must outlive any single bad pass: a scheduler that dies
  216. // on one exception stops every schedule on the host, and nothing
  217. // restarts it short of a service restart.
  218. spdlog::warn("function scheduler tick failed: {}", e.what());
  219. }
  220. if (lastReclaim == 0 ||
  221. now - lastReclaim >= static_cast<std::time_t>(opts_.reclaimIntervalSec)) {
  222. reclaimOnce();
  223. lastReclaim = now;
  224. }
  225. std::unique_lock<std::mutex> lk(m_);
  226. cv_.wait_for(lk, std::chrono::seconds(opts_.tickIntervalSec), [this] { return stop_; });
  227. if (stop_) return;
  228. }
  229. }
  230. } // namespace svapi