-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.R
executable file
·124 lines (81 loc) · 2.77 KB
/
init.R
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
suppressPackageStartupMessages({
library(callr, warn.conflicts = TRUE, quietly = TRUE)
library(logger, warn.conflicts = TRUE, quietly = TRUE)
library(plumber, warn.conflicts = TRUE, quietly = TRUE)
library(tictoc, warn.conflicts = TRUE, quietly = TRUE)
})
path <- Sys.getenv("API_PATH", "unset")
path <- switch(path, unset = NULL, path)
options(plumber.maxRequestSize = 1e8L, plumber.apiPath = path)
convert_empty <- function(x) switch(paste0(".", x), . = "-", x)
alert <- function(host, port, agent, branch, to, from, req, res) {
smtp <- emayili::server(host, port)
subject <- sprintf("Error report: %s on branch %s", agent, branch)
text <- sprintf(
"At [%s]: %s %s %s (Status: %s)",
format(Sys.time()),
req[["REQUEST_METHOD"]],
req[["PATH_INFO"]],
req[["QUERY_STRING"]],
res[["status"]]
)
message <- emayili::envelope(to, from, subject = subject, text = text)
smtp(message)
}
status_dir <- Sys.getenv("STATUS_DIR", "status")
log_dir <- Sys.getenv("LOG_DIR", "logs")
if (!dir.exists(status_dir)) {
stopifnot(
"Status dir creation failed" = dir.create(status_dir, recursive = TRUE)
)
}
if (!dir.exists(log_dir)) {
stopifnot(
"Log dir creation failed" = dir.create(log_dir, recursive = TRUE)
)
}
log_file <- tempfile("plumber_", log_dir, ".log")
log_appender(appender_tee(log_file))
p <- plumb("api.R")
p[["registerHooks"]](
list(
preroute = function() tic(),
postroute = function(req, res) {
end <- toc(quiet = TRUE)
f <- log_info
if (res[["status"]] >= 400L) {
f <- log_error
host <- Sys.getenv("SMTP_SERVER")
port <- Sys.getenv("SMTP_PORT")
to <- Sys.getenv("ERROR_EMAIL_TO")
from <- Sys.getenv("ERROR_EMAIL_FROM")
agent <- Sys.getenv("FINBIF_USER_AGENT")
branch <- Sys.getenv("BRANCH")
if (!any(c(host, port, to, from, agent, branch) == "")) {
r_bg(
alert,
list(host, port, agent, branch, to, from, req, res),
poll_connection = FALSE,
cleanup = FALSE
)
}
}
g <- function(...) {}
if (identical(sub( "/api", "", req[["PATH_INFO"]]), "/healthz")) f <- g
if (identical(req[["HTTP_USER_AGENT"]], "Zabbix")) f <- g
f(
paste(
"{convert_empty(req[[\"REMOTE_ADDR\"]])}",
"\"{convert_empty(req[[\"HTTP_USER_AGENT\"]])}\"",
"{convert_empty(req[[\"HTTP_HOST\"]])}",
"{convert_empty(req[[\"REQUEST_METHOD\"]])}",
"{convert_empty(req[[\"PATH_INFO\"]])}",
"{convert_empty(res[[\"status\"]])}",
"{round(end[[\"toc\"]] - end[[\"tic\"]],",
"digits = getOption(\"digits\", 5L))}"
)
)
}
)
)
p[["run"]](host = "0.0.0.0", port = 8000L, quiet = TRUE)