blob: 1d420679b92f65232ad8a9735ea0ccbac34d1923 [file] [log] [blame]
Yoshie Muranakace9a3ef2020-05-06 14:33:22 -07001import { debounce } from 'lodash';
2
Yoshie Muranakadc04feb2019-12-04 08:41:22 -08003/**
4 * WebSocketPlugin will allow us to get new data from the server
5 * without having to poll for changes on the frontend.
6 *
Yoshie Muranaka1ace1d92020-02-06 13:47:28 -08007 * This plugin is subscribed to host state property and logging
8 * changes, indicated in the app header Health and Power status.
Yoshie Muranakadc04feb2019-12-04 08:41:22 -08009 *
10 * https://github.com/openbmc/docs/blob/b41aff0fabe137cdb0cfff584b5fe4a41c0c8e77/rest-api.md#event-subscription-protocol
11 */
12const WebSocketPlugin = store => {
13 let ws;
14 const data = {
Yoshie Muranaka1ace1d92020-02-06 13:47:28 -080015 paths: ['/xyz/openbmc_project/state/host0', '/xyz/openbmc_project/logging'],
16 interfaces: [
17 'xyz.openbmc_project.State.Host',
18 'xyz.openbmc_project.Logging.Entry'
19 ]
Yoshie Muranakadc04feb2019-12-04 08:41:22 -080020 };
21
22 const initWebSocket = () => {
Mateusz Gapski33a8c532020-07-24 08:52:53 +020023 const socketDisabled =
24 process.env.VUE_APP_SUBSCRIBE_SOCKET_DISABLED === 'true' ? true : false;
25 if (socketDisabled) return;
Yoshie Muranaka23f227d2020-05-01 14:19:43 -070026 const token = store.getters['authentication/token'];
27 ws = new WebSocket(`wss://${window.location.host}/subscribe`, [token]);
Yoshie Muranakadc04feb2019-12-04 08:41:22 -080028 ws.onopen = () => {
29 ws.send(JSON.stringify(data));
30 };
31 ws.onerror = event => {
32 console.error(event);
33 };
Yoshie Muranakace9a3ef2020-05-06 14:33:22 -070034 ws.onmessage = debounce(event => {
Yoshie Muranaka1ace1d92020-02-06 13:47:28 -080035 const data = JSON.parse(event.data);
36 const eventInterface = data.interface;
Yoshie Muranakace9a3ef2020-05-06 14:33:22 -070037 const path = data.path;
Yoshie Muranaka1ace1d92020-02-06 13:47:28 -080038
39 if (eventInterface === 'xyz.openbmc_project.State.Host') {
40 const { properties: { CurrentHostState } = {} } = data;
41 store.commit('global/setHostStatus', CurrentHostState);
Yoshie Muranakace9a3ef2020-05-06 14:33:22 -070042 } else if (path === '/xyz/openbmc_project/logging') {
43 store.dispatch('eventLog/getEventLogData');
Yoshie Muranaka1ace1d92020-02-06 13:47:28 -080044 }
Yoshie Muranakace9a3ef2020-05-06 14:33:22 -070045 // 2.5 sec debounce to avoid making multiple consecutive
46 // GET requests since log related server messages seem to
47 // come in clusters
48 }, 2500);
Yoshie Muranakadc04feb2019-12-04 08:41:22 -080049 };
50
51 store.subscribe(({ type }) => {
52 if (type === 'authentication/authSuccess') {
53 initWebSocket();
54 }
55 if (type === 'authentication/logout') {
56 if (ws) ws.close();
57 }
58 });
59
60 if (store.getters['authentication/isLoggedIn']) initWebSocket();
61};
62
63export default WebSocketPlugin;