Debian Codegraph @

pkg/kdump/config-client-suse.js

raw
1 /*
2 * Copyright (C) 2022 SUSE LLC
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import { ConfigFile } from './config-client.js';
7
8 /* Parse an dotenv-style config file
9 * and monitor it for changes
10 */
11 export class ConfigFileSUSE extends ConfigFile {
12 /* parse lines of the config file
13 * if a line has a valid key=value format, use the key in _internal structure
14 * and also store original line, line index, value and optional line suffix / comment
15 * if value was quoted it will be stripped of quotes in `value` and `quoted` flag will
16 * be used when writing the file to keep original formatting
17 * e.g. for line 'someKey="foo" # comment'
18 * outputObject._internal["someKey"] = {
19 * index: 0,
20 * value: "foo",
21 * quoted: true,
22 * origLine: 'someKey="foo" # comment',
23 * suffix: "# comment"
24 * }
25 * skipNotify: Don't notify about changes, e.g.to avoid multiple updates when writing a file
26 */
27 _parseText(rawContent, skipNotify = false) {
28 this._dataAvailableResolve();
29
30 // clear settings if file is empty/missing
31 if (!rawContent) {
32 this._originalSettings = null;
33 this.settings = null;
34 if (!skipNotify)
35 this.dispatchEvent("kdumpConfigChanged", this.settings);
36 return;
37 }
38
39 // if nothing changed, don't bother parsing the content
40 if (rawContent == this._rawContent)
41 return;
42
43 this._rawContent = rawContent;
44
45 // this is the format expected by the UI
46 this.settings = {
47 _internal: {},
48 targets: {},
49 compression: { enabled: false, allowed: true },
50 nfs_supports_directory: false,
51 };
52
53 this._lines = rawContent.split(/\r?\n/);
54 this._lines.forEach((line, index) => {
55 const trimmed = line.trim();
56 // if the line is empty or only a comment, skip
57 if (trimmed.indexOf("#") === 0 || trimmed.length === 0)
58 return;
59
60 // parse KEY=value or KEY="value" line
61 let parts = trimmed.match(/^([A-Z_]+)\s*=\s*(.*)$/);
62 if (parts === null) {
63 console.warn("Malformed kdump config line:", trimmed, "in", this.filename);
64 return;
65 }
66 const key = parts[1];
67 let value = parts[2];
68
69 // value might be quoted
70 let quoted = false;
71 if (value.startsWith('"')) {
72 quoted = true;
73 parts = value.match(/^"([^"]*)"\s*(.*)$/);
74 // malformed line, no ending quote?
75 if (parts === null) {
76 console.warn("Incorrectly quoted value in kdump config line:", line, "in", this.filename);
77 return;
78 }
79 } else {
80 // not quoted should be simple value but grab everything and quote on write
81 parts = value.match(/^([^#]+?)\s*(#.*)?$/);
82 if (parts === null)
83 parts = ["", ""];
84 }
85 value = parts[1];
86 const suffix = (parts[2] || "").trim();
87
88 this.settings._internal[key] = {
89 index,
90 value,
91 origLine: line,
92 quoted,
93 suffix
94 };
95 });
96
97 // make sure we copy the original keys so we overwrite the correct lines when saving
98 this._originalSettings = { };
99 Object.keys(this.settings._internal).forEach((key) => {
100 this._originalSettings[key] = { ...this.settings._internal[key] };
101 });
102
103 this._extractSettings();
104
105 if (!skipNotify)
106 this.dispatchEvent("kdumpConfigChanged", this.settings);
107 }
108
109 /* extract settings managed by cockpit from _internal into platform independent model
110 */
111 _extractSettings() {
112 // generate target(s) from KDUMP_SAVEDIR
113 if ("KDUMP_SAVEDIR" in this.settings._internal && this.settings._internal.KDUMP_SAVEDIR.value) {
114 let savedir = this.settings._internal.KDUMP_SAVEDIR.value;
115 // handle legacy "file" without prefix
116 if (savedir.startsWith("/"))
117 savedir = "file://" + savedir;
118 // server includes "username:password@" and can be empty for file://
119 const parts = savedir.match(/^(.*):\/\/([^/]*)(\/.*)$/);
120 // malformed KDUMP_SAVEDIR
121 if (parts === null) {
122 console.warn("Malformed KDUMP_SAVEDIR entry:", savedir, "in", this.filename);
123 return;
124 }
125 const [, scheme, server, path] = parts;
126 if (scheme === "file") {
127 this.settings.targets.local = {
128 type: "local",
129 path,
130 };
131 } else if (scheme === "nfs") {
132 this.settings.targets.nfs = {
133 type: scheme,
134 // on read full path is used as export
135 export: path,
136 server,
137 };
138 } else {
139 this.settings.targets[scheme] = {
140 type: scheme,
141 path,
142 server,
143 };
144 // sshkey is used by ssh and sftp/scp
145 if ("KDUMP_SSH_IDENTITY" in this.settings._internal) {
146 this.settings.targets[scheme].sshkey =
147 this.settings._internal.KDUMP_SSH_IDENTITY.value;
148 }
149 }
150 }
151
152 // default to local if no target configured
153 if (Object.keys(this.settings.targets).length === 0)
154 this.settings.targets.local = { type: "local" };
155
156 this.settings.compression.enabled = (
157 !("KDUMP_DUMPFORMAT" in this.settings._internal) ||
158 // TODO: what about other compression formats (lzo, snappy)?
159 this.settings._internal.KDUMP_DUMPFORMAT.value === "compressed"
160 );
161 }
162
163 /* update single _internal setting to given value
164 * make sure setting exists if value is not empty
165 * don't delete existing settings
166 */
167 _updateSetting(settings, key, value) {
168 if (key in settings._internal) {
169 settings._internal[key].value = value;
170 } else {
171 if (value)
172 settings._internal[key] = { value };
173 }
174 }
175
176 /* transform settings from model back to _internal format
177 * this.settings = current state from file
178 * settings = in-memory state from UI
179 */
180 _persistSettings(settings) {
181 // target
182 if (Object.keys(settings.targets).length > 0) {
183 const target = Object.values(settings.targets)[0];
184
185 if ("sshkey" in target)
186 this._updateSetting(settings, "KDUMP_SSH_IDENTITY", target.sshkey);
187
188 let savedir;
189 // default for empty path (except nfs, see below)
190 let path = target.path || "/var/crash";
191 if (path && !path.startsWith("/"))
192 path = "/" + path;
193 if (target.type === "local") {
194 savedir = "file://" + path;
195 } else if (target.type === "nfs") {
196 // override empty path default as nfs path is merged into export on read
197 if (!target.path)
198 path = "";
199 let exprt = target.export;
200 if (!exprt.startsWith("/"))
201 exprt = "/" + exprt;
202 savedir = "nfs://" + target.server + exprt + path;
203 } else {
204 savedir = target.type + "://" + target.server + path;
205 }
206 this._updateSetting(settings, "KDUMP_SAVEDIR", savedir);
207 }
208 // compression
209 if (this.settings.compression.enabled != settings.compression.enabled) {
210 if (settings.compression.enabled) {
211 this._updateSetting(settings, "KDUMP_DUMPFORMAT", "compressed");
212 } else {
213 this._updateSetting(settings, "KDUMP_DUMPFORMAT", "ELF");
214 }
215 }
216 return settings;
217 }
218
219 /* generate the config file from raw text and settings
220 */
221 generateConfig(settings) {
222 settings = this._persistSettings(settings);
223
224 const lines = this._lines.slice(0);
225
226 // we take the lines from our last read operation and modify them with the new settings
227 Object.keys(settings._internal).forEach((key) => {
228 const entry = settings._internal[key];
229
230 let value = entry.value !== undefined ? entry.value : "";
231 // quote what was quoted before + empty values + multi-word values
232 if (entry.quoted || value === "" || value.includes(" "))
233 value = '"' + value + '"';
234 let line = key + "=" + value;
235 if (entry.suffix)
236 line = line + " " + entry.suffix;
237 // this might be a new entry
238 if (!(key in this._originalSettings)) {
239 lines.push(line);
240 return;
241 }
242 // otherwise edit the old line
243 const origEntry = this._originalSettings[key];
244 lines[origEntry.index] = line;
245 });
246
247 // make sure file ends with a newline
248 if (lines[lines.length - 1] !== "")
249 lines.push("");
250 return lines.join("\n");
251 }
252 }