Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stop trying to guess the name of the libvirt service/socket (fedora-35 necessary changes) #387

Merged
merged 5 commits into from Sep 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 0 additions & 8 deletions src/actions/store-actions.js
Expand Up @@ -30,7 +30,6 @@ import {
UPDATE_ADD_NODE_DEVICE,
UPDATE_ADD_STORAGE_POOL,
UPDATE_ADD_VM,
UPDATE_LIBVIRT_STATE,
UPDATE_LIBVIRT_VERSION,
UPDATE_DOMAIN_SNAPSHOTS,
UPDATE_OS_INFO_LIST,
Expand Down Expand Up @@ -116,13 +115,6 @@ export function undefineVm({ connectionName, name, id, transientOnly }) {
};
}

export function updateLibvirtState(state) {
return {
type: UPDATE_LIBVIRT_STATE,
state,
};
}

export function updateLibvirtVersion({ libvirtVersion }) {
return {
type: UPDATE_LIBVIRT_VERSION,
Expand Down
85 changes: 46 additions & 39 deletions src/app.jsx
Expand Up @@ -16,7 +16,7 @@
* You should have received a copy of the GNU Lesser General Public License
* along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
*/
import React, { useState, useEffect, useRef } from 'react';
import React, { useState, useEffect } from 'react';
import { AlertGroup, Button } from '@patternfly/react-core';
import { ExclamationCircleIcon } from '@patternfly/react-icons';
import { superuser } from "superuser.js";
Expand All @@ -33,66 +33,73 @@ import { dummyVmsFilter, vmId } from "./helpers.js";
import { InlineNotification } from 'cockpit-components-inline-notification.jsx';
import {
getApiData,
getLibvirtVersion,
initState,
usageStartPolling,
usageStopPolling,
} from "./libvirtApi/common.js";
import { useObject, useEvent } from "hooks";
import * as service from 'service.js';
import { useEvent } from "hooks";
import store from './store.js';
import VMS_CONFIG from "./config.js";

import { updateLibvirtState } from './actions/store-actions.js';
const _ = cockpit.gettext;

superuser.reload_page_on_change();

export const App = ({ name }) => {
const libvirtService = useObject(() => service.proxy(name), null, []);
const prevLibvirtServiceRef = useRef();
function canLoggedUserConnectSession (connectionName, loggedUser) {
return connectionName !== 'session' || loggedUser.name !== 'root';
}

function unknownConnectionName() {
return cockpit.user()
.then(loggedUser => {
const connectionNames = (
Object.getOwnPropertyNames(VMS_CONFIG.Virsh.connections).filter(
// The 'root' user does not have its own qemu:///session just qemu:///system
// https://bugzilla.redhat.com/show_bug.cgi?id=1045069
connectionName => canLoggedUserConnectSession(connectionName, loggedUser))
);
return connectionNames;
});
}
export const App = () => {
const [loadingResources, setLoadingResources] = useState(false);
const [error, setError] = useState('');
const [systemSocketInactive, setSystemSocketInactive] = useState(false);

useEvent(libvirtService, "changed", () => {
store.dispatch(updateLibvirtState({
activeState: libvirtService.state,
}));
if (libvirtService.state == 'failed') {
console.warn("Libvirtd has failed");
setLoadingResources(false);
}
if (libvirtService.state == 'running' && prevLibvirtServiceRef.current !== 'running' && prevLibvirtServiceRef.current !== null) {
setLoadingResources(true);
// If promises rejected here show an toast alert in the main page
getApiData({ connectionName: 'system' })
.then(promises => {
const errorMsgs = [];
promises.forEach(promise => {
if (promise.status == 'rejected' && promise.reason)
errorMsgs.push(promise.reason.message);
});
setError(errorMsgs.join(', '));
})
.finally(() => setLoadingResources(false));
}
prevLibvirtServiceRef.current = libvirtService.state;
});
useEvent(superuser, "changed");
useEffect(() => {
initState();
prevLibvirtServiceRef.current = libvirtService.state;

setLoadingResources(true);
// Let's not show errors from resource fetching here as it can be related to permissions and in this case we should not spam users
getApiData({ connectionName: null })

return unknownConnectionName()
.then(connectionNames => {
return Promise.allSettled(connectionNames.map(conn => {
return getLibvirtVersion({ connectionName: conn })
.then(() => {
getApiData({ connectionName: conn })
.then(promises => {
const errorMsgs = [];
promises.forEach(promise => {
if (promise.status == 'rejected' && promise.reason)
errorMsgs.push(promise.reason.message);
});
setError(errorMsgs.join(', '));
});
}, () => {
/* If the API call failed on system connection and the user has superuser privileges then show the Empty state screen */
if (conn == "system")
setSystemSocketInactive(true);
});
}));
})
.finally(() => setLoadingResources(false));
}, []);

// Show libvirtSlate component if libvirtd is not running only to users that are allowed to start the service.
if (((!libvirtService.exists || libvirtService.state !== 'running') && superuser.allowed) ||
loadingResources) {
if ((superuser.allowed && systemSocketInactive) || loadingResources) {
return (
<LibvirtSlate libvirtService={libvirtService}
loadingResources={loadingResources} />
<LibvirtSlate loadingResources={loadingResources} />
);
} else return (
<AppActive error={error} />
Expand Down
68 changes: 7 additions & 61 deletions src/components/libvirtSlate.jsx
Expand Up @@ -16,88 +16,34 @@
* You should have received a copy of the GNU Lesser General Public License
* along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
*/
import React, { useState } from 'react';
import React from 'react';
import PropTypes from 'prop-types';

import cockpit from 'cockpit';
import {
startLibvirt,
enableLibvirt,
} from "../libvirtApi/common.js";

import { EmptyStatePanel } from "cockpit-components-empty-state.jsx";
import { Button, Checkbox } from "@patternfly/react-core";
import { Button } from "@patternfly/react-core";
import { ExclamationCircleIcon } from "@patternfly/react-icons";
import { InlineNotification } from 'cockpit-components-inline-notification.jsx';

const _ = cockpit.gettext;

const LibvirtSlate = ({ loadingResources, libvirtService }) => {
const [actionInProgress, setActionInProgress] = useState(false);
const [error, setError] = useState();
const [errorDetail, setErrorDetail] = useState();
const [libvirtEnabled, setLibvirtEnabled] = useState(true);

const startService = () => {
setActionInProgress(true);

enableLibvirt({
enable: libvirtEnabled,
serviceName: libvirtService.unit.Id
})
.then(() => {
startLibvirt({
serviceName: libvirtService.unit.Id
}).catch(ex => { setError(_("Failed to start virtualization service")); setErrorDetail(ex.message) });
}, ex => { setError(_("Failed to enable virtualization service")); setErrorDetail(ex.message) })
.finally(() => setActionInProgress(false));
};

const goToServicePage = () => {
const name = libvirtService.unit.Id ? libvirtService.unit.Id : 'libvirtd.service'; // fallback
cockpit.jump("/system/services#/" + name);
};

if (libvirtService.state === null)
return <EmptyStatePanel title={ _("Connecting to virtualization service") } loading />;

const name = libvirtService.unit.Id;

const LibvirtSlate = ({ loadingResources }) => {
if (loadingResources)
return <EmptyStatePanel title={ _("Loading resources") } loading />;

const detail = (
<Checkbox id="enable-libvirt"
isDisabled={!name}
isChecked={libvirtEnabled}
label={_("Automatically start libvirt on boot")}
onChange={setLibvirtEnabled} />
);

const troubleshoot_btn = (
<Button variant="link" onClick={ goToServicePage }>
<Button variant="link" onClick={() => cockpit.jump("/system/services")}>
{ _("Troubleshoot") }
</Button>);

return (
<>
{error
? <InlineNotification type='danger' text={error}
detail={errorDetail}
onDismiss={() => setError(undefined)} /> : null}
<EmptyStatePanel icon={ ExclamationCircleIcon }
title={ _("Virtualization service (libvirt) is not active") }
paragraph={ detail }
action={ name ? _("Start libvirt") : null }
isActionInProgress={actionInProgress}
onAction={ startService }
secondary={ troubleshoot_btn } />
</>
<EmptyStatePanel icon={ ExclamationCircleIcon }
title={ _("Virtualization service (libvirt) is not active") }
secondary={ troubleshoot_btn } />
);
};

LibvirtSlate.propTypes = {
libvirtService: PropTypes.object.isRequired,
loadingResources: PropTypes.bool.isRequired,
};

Expand Down
1 change: 0 additions & 1 deletion src/constants/store-action-types.js
Expand Up @@ -34,7 +34,6 @@ export const UPDATE_ADD_NETWORK = "UPDATE_ADD_NETWORK";
export const UPDATE_ADD_NODE_DEVICE = "UPDATE_ADD_NODE_DEVICE";
export const UPDATE_ADD_VM = "UPDATE_ADD_VM";
export const UPDATE_ADD_STORAGE_POOL = "UPDATE_ADD_STORAGE_POOL";
export const UPDATE_LIBVIRT_STATE = "UPDATE_LIBVIRT_STATE";
export const UPDATE_LIBVIRT_VERSION = "UPDATE_LIBVIRT_VERSION";
export const UPDATE_DOMAIN_SNAPSHOTS = "UPDATE_DOMAIN_SNAPSHOTS";
export const UPDATE_OS_INFO_LIST = "UPDATE_OS_INFO_LIST";
Expand Down
22 changes: 6 additions & 16 deletions src/index.js
Expand Up @@ -22,33 +22,23 @@ import 'polyfills'; // once per application
import React from 'react';
import ReactDOM from 'react-dom';

import cockpit from 'cockpit';
import store from './store.js';
import App from './app.jsx';
import { logDebug } from './helpers.js';
import getLibvirtServiceNameScript from 'raw-loader!./scripts/get_libvirt_service_name.sh';

function render(name) {
function render() {
ReactDOM.render(
<App name={name} />,
<App />,
document.getElementById('app')
);
}

function renderApp() {
return cockpit.script(getLibvirtServiceNameScript, null, { err: "message", environ: ['LC_ALL=C.UTF-8'] })
.then(serviceName => {
const match = serviceName.match(/([^\s]+)/);
const name = match ? match[0] : null;
if (name) {
// re-render app every time the state changes
store.subscribe(() => render(name));
// re-render app every time the state changes
store.subscribe(() => render());

// do initial render
render(name);
}
})
.catch(ex => console.error(`initialize failed: getting libvirt service name returned error: "${JSON.stringify(ex)}"`));
// do initial render
render();
}

/**
Expand Down
64 changes: 11 additions & 53 deletions src/libvirtApi/common.js
Expand Up @@ -24,7 +24,6 @@
import cockpit from "cockpit";
import store from "../store.js";
import * as python from "python.js";
import * as service from "service.js";

import getOSListScript from "raw-loader!../getOSList.py";

Expand All @@ -40,7 +39,6 @@ import {
} from "../actions/store-actions.js";

import {
getLibvirtServiceState,
getRefreshInterval,
usagePollingEnabled
} from "../selectors.js";
Expand Down Expand Up @@ -116,16 +114,8 @@ function calculateDiskStats(info) {
return disksStats;
}

export function canLoggedUserConnectSession (connectionName, loggedUser) {
return connectionName !== 'session' || loggedUser.name !== 'root';
}

function delayPollingHelper(action, timeout) {
window.setTimeout(() => {
const libvirtState = getLibvirtServiceState(store.getState());
if (libvirtState !== "running")
return delayPollingHelper(action, timeout);

logDebug('Executing delayed action');
action();
}, timeout);
Expand Down Expand Up @@ -238,7 +228,7 @@ function getLoggedInUser() {
});
}

function getLibvirtVersion({ connectionName }) {
export function getLibvirtVersion({ connectionName }) {
return call(connectionName, "/org/libvirt/QEMU", "org.freedesktop.DBus.Properties", "Get", ["org.libvirt.Connect", "LibVersion"], { timeout, type: "ss" })
.then(version => store.dispatch(updateLibvirtVersion({ libvirtVersion: version[0].v })));
}
Expand Down Expand Up @@ -479,44 +469,17 @@ function storagePoolUpdateOrDelete(connectionName, poolPath) {
.catch(ex => console.warn("storagePoolUpdateOrDelete action failed:", ex.toString()));
}

function unknownConnectionName() {
return cockpit.user()
.then(loggedUser => {
const connectionNames = (
Object.getOwnPropertyNames(VMS_CONFIG.Virsh.connections).filter(
// The 'root' user does not have its own qemu:///session just qemu:///system
// https://bugzilla.redhat.com/show_bug.cgi?id=1045069
connectionName => canLoggedUserConnectSession(connectionName, loggedUser))
);
return connectionNames;
});
}

export function enableLibvirt({ enable, serviceName }) {
logDebug(`ENABLE_LIBVIRT`);
const libvirtService = service.proxy(serviceName);
return enable ? libvirtService.enable() : libvirtService.disable();
}

export function getApiData({ connectionName }) {
if (connectionName) {
dbusClient(connectionName);
startEventMonitor({ connectionName });
return Promise.allSettled([
domainGetAll({ connectionName }),
storagePoolGetAll({ connectionName }),
interfaceGetAll({ connectionName }),
networkGetAll({ connectionName }),
nodeDeviceGetAll({ connectionName }),
getNodeMaxMemory({ connectionName }),
getLibvirtVersion({ connectionName }),
]);
} else {
return unknownConnectionName()
.then(connectionNames => {
return Promise.allSettled(connectionNames.map(conn => getApiData({ connectionName: conn })));
});
}
dbusClient(connectionName);
startEventMonitor({ connectionName });
return Promise.allSettled([
domainGetAll({ connectionName }),
storagePoolGetAll({ connectionName }),
interfaceGetAll({ connectionName }),
networkGetAll({ connectionName }),
nodeDeviceGetAll({ connectionName }),
getNodeMaxMemory({ connectionName }),
]);
}

export function initState() {
Expand All @@ -525,11 +488,6 @@ export function initState() {
getOsInfoList();
}

export function startLibvirt({ serviceName }) {
logDebug(`START_LIBVIRT`);
return service.proxy(serviceName).start();
}

export function usageStartPolling({
name,
connectionName,
Expand Down