Debian Codegraph @

pkg/systemd/timer-dialog-helpers.js

raw
1 /*
2 * Copyright (C) 2013 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from "cockpit";
7 import s_bus from "./busnames.js";
8 import { systemd_client, clock_realtime_now } from "./services.jsx";
9 import { CockpitManagedMarker } from "./service-details.jsx";
10
11 export function from_boot_usec(value) {
12 const result = { delay: "system-boot" };
13 const seconds = Math.floor(value / 1e6); // Convert from microseconds
14
15 if (seconds % 604800 === 0) {
16 result.delayNumber = seconds / 604800;
17 result.delayUnit = "weeks";
18 } else if (seconds % 3600 === 0) {
19 result.delayNumber = seconds / 3600;
20 result.delayUnit = "hours";
21 } else if (seconds % 60 === 0) {
22 result.delayNumber = seconds / 60;
23 result.delayUnit = "minutes";
24 } else {
25 result.delayNumber = seconds;
26 result.delayUnit = "seconds";
27 }
28
29 return result;
30 }
31
32 export function from_on_calendar(patterns) {
33 const joined = patterns.join('\n').trim();
34 let result = null;
35
36 const minutely = /^\*-\*-\* \*:\*:(\d{1,2}(?:,\d{1,2})*)$/;
37 const hourly = /^\*-\*-\* \*:(\d{1,2}(?:,\d{1,2})*)(?::00)?$/;
38 const daily = /^\*-\*-\* (\d{2}:\d{2})(?::00)?$/;
39 const weekly = /^([A-Za-z]{3}) \*-\*-\* (\d{2}:\d{2})(?::00)?$/;
40 const monthly = /^\*-\*-(\d{1,2}) (\d{2}:\d{2})(?::00)?$/;
41 const yearly = /^\*-(\d{2}-\d{2}) (\d{2}:\d{2})(?::00)?$/;
42 const specific = /^\d{4}-\d{2}-\d{2} (\d{2}:\d{2})(?::00)?$/;
43
44 if (minutely.test(joined)) {
45 const match = joined.match(minutely);
46 const seconds = match[1];
47 result = {
48 repeat: "minutely",
49 repeatPatterns: seconds.split(",").map(second => ({ second }))
50 };
51 }
52
53 if (hourly.test(joined)) {
54 const match = joined.match(hourly);
55 const minutes = match[1];
56 result = {
57 repeat: "hourly",
58 repeatPatterns: minutes.split(",").map(minute => ({ minute }))
59 };
60 }
61
62 if (patterns.every(line => daily.test(line))) {
63 result = {
64 repeat: "daily",
65 repeatPatterns: patterns.map(line => {
66 const match = line.match(daily);
67 const time = match[1];
68 return { time };
69 })
70 };
71 }
72
73 if (patterns.every(line => weekly.test(line))) {
74 result = {
75 repeat: "weekly",
76 repeatPatterns: patterns.map(line => {
77 const match = line.match(weekly);
78 const weekDay = match[1].toLowerCase();
79 const time = match[2];
80 return { day: weekDay, time };
81 })
82 };
83 }
84
85 if (patterns.every(line => monthly.test(line))) {
86 result = {
87 repeat: "monthly",
88 repeatPatterns: patterns.map(line => {
89 const match = line.match(monthly);
90 const day = Number(match[1]);
91 const time = match[2];
92 return { day, time };
93 })
94 };
95 }
96
97 if (patterns.every(line => yearly.test(line))) {
98 result = {
99 repeat: "yearly",
100 repeatPatterns: patterns.map((line) => {
101 const match = line.match(yearly);
102 const monthAndDay = match[1];
103 const time = match[2];
104 return { date: `${(new Date(clock_realtime_now)).getFullYear()}-${monthAndDay}`, time }; // specific year isn't important
105 })
106 };
107 }
108
109 if (specific.test(joined)) {
110 result = {
111 repeat: "no",
112 repeatPatterns: [],
113 specificTime: joined.match(specific)[1]
114 };
115 }
116
117 if (result) {
118 result.delay = "specific-time";
119 result.repeatPatterns = result.repeatPatterns.map((item, index) => {
120 return { key: index, ...item };
121 });
122
123 return result;
124 } else {
125 return null;
126 }
127 }
128
129 /* Escape STR so that it is parsed as a single argument in a
130 ExecStart= line. We need to escape spaces, newlines, quotes, and
131 backslashes by prepending a backslash. We also need to escape
132 specifiers by prepending a "%" character.
133 */
134
135 function escape_systemd_exec_arg(str) {
136 return str
137 .replaceAll("\\", "\\\\")
138 .replaceAll(" ", "\\s")
139 .replaceAll("\t", "\\t")
140 .replaceAll("\n", "\\n")
141 .replaceAll("\"", "\\\"")
142 .replaceAll("'", "\\'")
143 .replaceAll("%", "%%");
144 }
145
146 export function create_timer({ name, description, command, delay, delayUnit, delayNumber, repeat, repeatPatterns, specificTime, owner }) {
147 const timer_unit = {};
148 const repeat_array = repeatPatterns;
149 timer_unit.name = name.replace(/\s/g, '');
150 timer_unit.Description = description;
151 timer_unit.Command = "/bin/sh -c " + escape_systemd_exec_arg(command);
152 timer_unit.boot_time = delayNumber;
153 timer_unit.boot_time_unit = delayUnit;
154
155 function month_day_str(d) {
156 const month_str = (d.getMonth() + 1).toString();
157 const day_str = (d.getDate()).toString();
158 return `${month_str.padStart(2, '0')}-${day_str.padStart(2, '0')}`;
159 }
160
161 if (delay == "specific-time" && repeat == "no") {
162 const today = new Date(clock_realtime_now);
163 timer_unit.OnCalendar = `OnCalendar=${today.getFullYear()}-${month_day_str(today)} ${specificTime}:00`;
164 } else if (repeat == "minutely") {
165 timer_unit.repeat_second = repeat_array.map(item => Number(item.second));
166 timer_unit.OnCalendar = "OnCalendar=*-*-* *:*:" + timer_unit.repeat_second.join(",");
167 } else if (repeat == "hourly") {
168 timer_unit.repeat_minute = repeat_array.map(item => Number(item.minute));
169 timer_unit.OnCalendar = "OnCalendar=*-*-* *:" + timer_unit.repeat_minute.join(",");
170 } else if (repeat == "daily") {
171 timer_unit.OnCalendar = repeat_array.map(item => `OnCalendar=*-*-* ${item.time}:00`);
172 } else if (repeat == "weekly") {
173 timer_unit.OnCalendar = repeat_array.map(item => `OnCalendar=${item.day} *-*-* ${item.time}:00`);
174 } else if (repeat == "monthly") {
175 timer_unit.OnCalendar = repeat_array.map(item => `OnCalendar=*-*-${item.day} ${item.time}:00`);
176 } else if (repeat == "yearly") {
177 timer_unit.OnCalendar = repeat_array.map(item => `OnCalendar=*-${month_day_str(new Date(item.date))} ${item.time}:00`);
178 }
179 if (repeat != "hourly" && repeat != "minutely" && delay == "specific-time")
180 timer_unit.OnCalendar = timer_unit.OnCalendar.toString().replaceAll(",", "\n");
181 return create_timer_file({ timer_unit, delay, owner });
182 }
183
184 function create_timer_file({ timer_unit, delay, owner }) {
185 const unit = "[Unit]\nDescription=";
186 const service = "\n[Service]\nExecStart=";
187 const timer = "\n[Timer]\n";
188 const install = "[Install]\nWantedBy=timers.target\n";
189 const service_file = CockpitManagedMarker + unit + timer_unit.Description + service + timer_unit.Command + "\n";
190 let timer_file = CockpitManagedMarker;
191 if (delay == "system-boot") {
192 const boottimer = timer + "OnBootSec=" + timer_unit.boot_time + timer_unit.boot_time_unit + "\n";
193 timer_file += unit + timer_unit.Description + boottimer;
194 } else if (timer_unit.OnCalendar) {
195 const calendartimer = timer + timer_unit.OnCalendar + "\n";
196 timer_file += unit + timer_unit.Description + calendartimer;
197 }
198 timer_file += install;
199 // writing to file
200 const service_path = "/etc/systemd/system/" + timer_unit.name + ".service";
201 const timer_path = "/etc/systemd/system/" + timer_unit.name + ".timer";
202 return cockpit.file(service_path, { superuser: 'try' }).replace(service_file)
203 .then(() => cockpit.file(timer_path, { superuser: 'try' }).replace(timer_file))
204 .then(tag => systemd_client[owner].call(s_bus.O_MANAGER, s_bus.I_MANAGER, "EnableUnitFiles", [[timer_unit.name + ".timer"], false, false]))
205 /* Executing daemon reload after file operations is necessary -
206 * see https://github.com/systemd/systemd/blob/main/src/systemctl/systemctl.c [enable_unit function] */
207 .then(() => systemd_client[owner].call(s_bus.O_MANAGER, s_bus.I_MANAGER, "Reload", null))
208 .then(() => {
209 // start calendar timers
210 if (timer_unit.OnCalendar)
211 return systemd_client[owner].call(s_bus.O_MANAGER, s_bus.I_MANAGER, "StartUnit", [timer_unit.name + ".timer", "replace"]);
212 });
213 }