Debian Codegraph @

pkg/systemd/overview-cards/tuned-dialog.jsx

raw
1 /*
2 * Copyright (C) 2021 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from "cockpit";
7 import React, { useState, useEffect, useRef } from 'react';
8
9 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
10 import {
11 Modal, ModalBody, ModalFooter, ModalHeader
12 } from '@patternfly/react-core/dist/esm/components/Modal/index.js';
13 import { Popover } from "@patternfly/react-core/dist/esm/components/Popover/index.js";
14 import { Tooltip } from "@patternfly/react-core/dist/esm/components/Tooltip/index.js";
15 import { ExternalLinkSquareAltIcon, HelpIcon } from '@patternfly/react-icons';
16
17 import * as service from "service";
18 import { EmptyStatePanel } from 'cockpit-components-empty-state.jsx';
19 import { ModalError } from 'cockpit-components-inline-notification.jsx';
20 import { ProfilesMenuDialogBody } from './profiles-menu-dialog-body';
21 import { superuser } from 'superuser';
22 import { useEvent, useInit } from "hooks";
23 import { useDialogs } from "dialogs.jsx";
24
25 const _ = cockpit.gettext;
26
27 function poll_tuned_state(tuned, tunedService) {
28 return Promise.all([
29 tuned.call('/Tuned', 'com.redhat.tuned.control', 'is_running', []),
30 tuned.call('/Tuned', 'com.redhat.tuned.control', 'active_profile', []),
31 tuned.call('/Tuned', 'com.redhat.tuned.control', 'recommend_profile', [])
32 ])
33 .then(([[is_running], [active_result], [recommended]]) => {
34 const active = is_running ? active_result : "none";
35 return ({ state: "running", active, recommended });
36 })
37 .catch((ex) => {
38 if (!tunedService.exists)
39 return ({ state: "not-installed" });
40 else if (tunedService.state != "running")
41 return ({ state: "not-running" });
42 else
43 return Promise.reject(ex);
44 });
45 }
46
47 export const TunedPerformanceProfile = () => {
48 const Dialogs = useDialogs();
49 const [btnText, setBtnText] = useState();
50 const [state, setState] = useState();
51 const [status, setStatus] = useState();
52 const oldServiceState = useRef(null);
53
54 const tunedService = useInit(() => service.proxy("tuned.service"));
55
56 async function update() {
57 const tuned = cockpit.dbus("com.redhat.tuned", { superuser: "try" });
58 try {
59 const { state, active, recommended } = await poll_tuned_state(tuned, tunedService);
60 let status;
61
62 if (state == "not-installed")
63 status = _("Tuned is not available");
64 else if (state == "not-running")
65 status = _("Tuned is not running");
66 else if (active == "none")
67 status = _("Tuned is off");
68 else if (active == recommended)
69 status = _("This system is using the recommended profile");
70 else
71 status = _("This system is using a custom profile");
72 setBtnText(state == "running" ? active : _("none"));
73 setState(state);
74 setStatus(status);
75 } catch (ex) {
76 console.warn("failed to poll tuned", ex);
77
78 setBtnText("error");
79 setStatus(_("Communication with tuned has failed"));
80 }
81 tuned.close();
82 }
83
84 useEvent(superuser, "reconnect", update);
85 useEvent(tunedService, "changed", () => {
86 // We get a flood of "changed" events sometimes without the
87 // state actually changing. So let's protect against that.
88 if (oldServiceState.current !== tunedService.state) {
89 oldServiceState.current = tunedService.state;
90 update();
91 }
92 });
93
94 const showDialog = async () => {
95 await Dialogs.run(TunedDialog, { tunedService });
96 // Tuned does not send any change notifications...
97 await update();
98 };
99
100 return (
101 <Tooltip id="tuned-status-tooltip" content={status}>
102 <Button id="tuned-status-button"
103 isAriaDisabled={btnText == "error" || state == "not-installed" || !superuser.allowed}
104 isInline
105 onClick={showDialog}
106 variant='link'>
107 {btnText}
108 </Button>
109 </Tooltip>
110 );
111 };
112
113 const TunedDialog = ({
114 tunedService,
115 dialogResult,
116 }) => {
117 const [tunedDbus, setTunedDbus] = useState(null);
118 const [activeProfile, setActiveProfile] = useState();
119 const [loading, setLoading] = useState(true);
120 const [error, setError] = useState();
121 const [profiles, setProfiles] = useState([]);
122 const [selected, setSelected] = useState();
123
124 /* Tuned doesn't implement the DBus.Properties interface, so
125 * we occasionally poll for what we need.
126 *
127 * Tuned doesn't auto-activate on the bus, so we have to start
128 * it explicitly when opening the dialog.
129 */
130
131 const setProfile = () => {
132 const setService = () => {
133 /* When the profile is none we disable tuned */
134 const enable = (selected != "none");
135 const action = enable ? "start" : "stop";
136 return tunedDbus.call('/Tuned', 'com.redhat.tuned.control', action, [])
137 .then(results => {
138 /* Yup this is how tuned returns failures */
139 if (!results[0]) {
140 console.warn("Failed to " + action + " tuned:", results);
141 if (results[1])
142 return Promise.reject(results[1]);
143 else if (enable)
144 return Promise.reject(cockpit.format(_("Failed to enable tuned")));
145 else
146 return Promise.reject(cockpit.format(_("Failed to disable tuned")));
147 }
148
149 /* Now tell systemd about this change */
150 if (enable && !tunedService.enabled)
151 return tunedService.enable();
152 else if (!enable && tunedService.enabled)
153 return tunedService.disable();
154 else
155 return null;
156 });
157 };
158
159 let promise;
160
161 if (selected == "none") {
162 promise = tunedDbus.call("/Tuned", 'com.redhat.tuned.control', 'disable', [])
163 .then(results => {
164 /* Yup this is how tuned returns failures */
165 if (!results[0]) {
166 console.warn("Failed to disable tuned profile:", results);
167 return Promise.reject(_("Failed to disable tuned profile"));
168 }
169 });
170 } else {
171 promise = tunedDbus.call('/Tuned', 'com.redhat.tuned.control', 'switch_profile', [selected])
172 .then(results => {
173 /* Yup this is how tuned returns failures */
174 if (!results[0][0]) {
175 console.warn("Failed to switch profile:", results);
176 return Promise.reject(results[0][1] || _("Failed to switch profile"));
177 }
178 });
179 }
180
181 return promise
182 .then(setService)
183 .then(() => dialogResult.resolve())
184 .catch(setError);
185 };
186
187 useEffect(() => {
188 const withInfo = (active, recommended, profiles) => {
189 const model = [];
190 profiles.forEach(p => {
191 let name;
192 let desc;
193 if (typeof p === "string") {
194 name = p;
195 desc = "";
196 } else {
197 name = p[0];
198 desc = p[1];
199 }
200 if (name != "none") {
201 model.push({
202 name,
203 title: name,
204 description: desc,
205 active: name == active,
206 recommended: name == recommended,
207 });
208 }
209 });
210
211 model.unshift({
212 name: "none",
213 title: _("None"),
214 description: _("Disable tuned"),
215 active: active == "none",
216 recommended: recommended == "none",
217 });
218
219 setProfiles(model);
220 setActiveProfile(active);
221 setSelected(active);
222 };
223
224 const withTuned = (tunedDbus) => {
225 const tunedProfiles = () => {
226 return tunedDbus.call('/Tuned', 'com.redhat.tuned.control', 'profiles2', [])
227 .then((result) => result[0])
228 .catch(ex => {
229 return tunedDbus.call('/Tuned', 'com.redhat.tuned.control', 'profiles', [])
230 .then((result) => result[0]);
231 });
232 };
233
234 return poll_tuned_state(tunedDbus, tunedService)
235 .then(res => {
236 const { state, active, recommended } = res;
237 if (state != "running") {
238 setError(_("Tuned has failed to start"));
239 return;
240 }
241 return tunedProfiles()
242 .then(profiles => {
243 return withInfo(active, recommended, profiles);
244 })
245 .catch(setError);
246 })
247 .catch(setError);
248 };
249
250 let tuned = null;
251
252 tunedService.start()
253 .then(() => {
254 tuned = cockpit.dbus("com.redhat.tuned", { superuser: "try" });
255 setTunedDbus(tuned);
256 })
257 .then(() => withTuned(tuned))
258 .catch(setError)
259 .finally(() => setLoading(false));
260
261 return () => {
262 if (tuned)
263 tuned.close();
264 };
265 }, [tunedService]);
266
267 const help = (
268 <Popover
269 id="tuned-help"
270 bodyContent={
271 <div>
272 {_("Tuned is a service that monitors your system and optimizes the performance under certain workloads. The core of Tuned are profiles, which tune your system for different use cases.")}
273 </div>
274 }
275 footerContent={
276 <Button component='a'
277 rel="noopener noreferrer" target="_blank"
278 variant='link'
279 isInline
280 icon={<ExternalLinkSquareAltIcon />} iconPosition="right"
281 href="https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/9/html/monitoring_and_managing_system_status_and_performance/index">
282 {_("Learn more")}
283 </Button>
284 }
285 >
286 <Button icon={<HelpIcon />} variant="plain" aria-label={_("Help")} />
287 </Popover>
288 );
289
290 return (
291 <Modal position="top" variant="medium"
292 className="ct-m-stretch-body"
293 isOpen
294 onClose={() => dialogResult.resolve()}
295 >
296 <ModalHeader title={_("Change performance profile")}
297 help={help}
298 />
299 <ModalBody>
300 {error && <ModalError dialogError={typeof error == 'string' ? error : error.message} />}
301 {loading && <EmptyStatePanel loading />}
302 {activeProfile && <ProfilesMenuDialogBody active_profile={activeProfile}
303 change_selected={setSelected}
304 profiles={profiles} />}
305 </ModalBody>
306 <ModalFooter>
307 <Button variant='primary' isDisabled={!selected} onClick={setProfile}>
308 {_("Change profile")}
309 </Button>
310 <Button variant='link' onClick={() => dialogResult.resolve()}>
311 {_("Cancel")}
312 </Button>
313 </ModalFooter>
314 </Modal>
315 );
316 };