Skip to content

Commit

Permalink
Merge pull request meshery#8663 from aabidsofi19/aabidsofi/k8s-switcher
Browse files Browse the repository at this point in the history
Aabidsofi/k8s switcher
  • Loading branch information
theBeginner86 authored Sep 7, 2023
2 parents 1acbf0e + 485c67f commit 3f36a0a
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 50 deletions.
34 changes: 20 additions & 14 deletions provider-ui/lib/data-fetch.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,40 @@
import fetch from 'isomorphic-unfetch'
import fetch from "isomorphic-unfetch";

// This can be migrated as a custom hook in React
const dataFetch = (url, options = {}, successFn, errorFn) => {
// const controller = new AbortController();
// const signal = controller.signal;
// options.signal = signal;
// setTimeout(() => controller.abort(), 10000); // nice to have but will mess with the load test
if (errorFn === undefined) {
errorFn = (err) => {
console.error(`Error fetching ${url} --DataFetch`, err);
};
}
fetch(url, options)
.then(res => {
.then((res) => {
if (res.status === 401 || res.redirected) {
if (window.location.host.endsWith('3000')) {
window.location = '/user/login' // for local dev thru node server
if (window.location.host.endsWith("3000")) {
window.location = "/user/login"; // for local dev thru node server
} else {
window.location.reload() // for use with Go server
window.location.reload(); // for use with Go server
}
}
let result
let result;
if (res.ok) {
// console.log(`res type: ${res.type}`);
try {
result = res.json()
result = res.json();
} catch (e) {
result = res.text()
result = res.text();
}
return result
return result;
} else {
res.text().then(errorFn)
res.text().then(errorFn);
}
}).then(successFn)
.catch(errorFn)
}
})
.then(successFn)
.catch(errorFn);
};

export default dataFetch
export default dataFetch;
13 changes: 10 additions & 3 deletions ui/components/ConnectionWizard/helpers/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,21 @@ export const closeButtonForSnackbarAction = (closeSnackbar) => (key) => (
</IconButton>
)



export const successHandlerGenerator = (notify, msg, cb) => (res) => {

if (res !== undefined) {
if (cb !== undefined) cb(res)
notify({ message : `${msg}: ${res}`, event_type : EVENT_TYPES.SUCCESS })
if (typeof res == "object") {
res = JSON.stringify(res)
}
notify({ message : `${msg}`, details : `${res}`, event_type : EVENT_TYPES.SUCCESS })
}
}

export const errorHandlerGenerator = (notify, msg, cb) => (err) => {
if (cb !== undefined) cb(err)
notify({ message : `${msg}: ${err}`, event_type : EVENT_TYPES.ERROR })
}
err = typeof err !== "string" ? err.toString() : err
notify({ message : `${msg}`, details : err, event_type : EVENT_TYPES.ERROR })
}
33 changes: 17 additions & 16 deletions ui/components/ConnectionWizard/helpers/kubernetesHelpers.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import dataFetch from "../../../lib/data-fetch";
import { updateProgress } from "../../../lib/store";
import { EVENT_TYPES } from "../../../lib/event-types";

/**
* Pings kuberenetes server endpoint
* @param {(res) => void} successHandler
* @param {(err) => void} errorHandler
*/
export const pingKubernetes = (successHandler,errorHandler, context) => {
export const pingKubernetes = (successHandler, errorHandler, connectionId) => {
dataFetch(
"/api/system/kubernetes/ping?connection_id=" + context,
"/api/system/kubernetes/ping?connection_id=" + connectionId,
{ credentials : "include" },
successHandler,
errorHandler
Expand All @@ -28,23 +27,23 @@ export const pingKubernetes = (successHandler,errorHandler, context) => {
*
* @return {true|false}
*/
export const isKubernetesConnected = (isClusterConfigured,kubernetesPingStatus) => {
export const isKubernetesConnected = (isClusterConfigured, kubernetesPingStatus) => {

if (isClusterConfigured){
if (isClusterConfigured) {
if (kubernetesPingStatus) return true
}

return false
}


export const deleteKubernetesConfig = (successCb,errorCb, id) =>
export const deleteKubernetesConfig = (successCb, errorCb, connectionId) =>
dataFetch(
"/api/system/kubernetes/contexts/" + id,
"/api/system/kubernetes/contexts/" + connectionId,
{
method : "DELETE",
credentials : "include", },
updateProgress({ showProgress : false }),
credentials : "include",
},
successCb,
errorCb
)
Expand Down Expand Up @@ -113,13 +112,15 @@ export const submitConfig = (notify, updateProgress, updateK8SConfig, contextNam
updateProgress({ showProgress : false });
if (typeof result !== "undefined") {
notify({ message : "Kubernetes config was validated!", event_type : EVENT_TYPES.SUCCESS });
updateK8SConfig({ k8sConfig : {
inClusterConfig : inClusterConfigForm,
k8sfile,
contextName : result.contextName,
clusterConfigured : true,
configuredServer : result.configuredServer,
}, });
updateK8SConfig({
k8sConfig : {
inClusterConfig : inClusterConfigForm,
k8sfile,
contextName : result.contextName,
clusterConfigured : true,
configuredServer : result.configuredServer,
},
});
}
},
(err) => alert(err)
Expand Down
31 changes: 15 additions & 16 deletions ui/components/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ import RemoteComponent from './RemoteComponent';
import { CapabilitiesRegistry } from "../utils/disabledComponents";
import ExtensionPointSchemaValidator from '../utils/ExtensionPointSchemaValidator';
import dataFetch from '../lib/data-fetch';
import { withNotify } from '../utils/hooks/useNotification';
import { useNotification } from '../utils/hooks/useNotification';
import { useNotification, withNotify } from '../utils/hooks/useNotification';

const lightColor = 'rgba(255, 255, 255, 0.7)';
const styles = (theme) => ({
Expand Down Expand Up @@ -270,8 +269,7 @@ function K8sContextMenu({
const [showFullContextMenu, setShowFullContextMenu] = React.useState(false);
const [transformProperty, setTransformProperty] = React.useState(100);
const deleteCtxtRef = React.createRef();
const { notify } = useNotification();

const { notify } = useNotification()
const styleSlider = {
position : "absolute",
left : "-5rem",
Expand Down Expand Up @@ -336,12 +334,13 @@ function K8sContextMenu({
return STATUS.NOT_CONNECTED;
}

const handleKubernetesClick = (id) => {
const handleKubernetesClick = (name, connectionID) => {

updateProgress({ showProgress : true })
pingKubernetes(
successHandlerGenerator (notify, "Kubernetes pinged", () => updateProgress({ showProgress : false })),
errorHandlerGenerator(notify, "Kubernetes not pinged", () => updateProgress({ showProgress : false })),
id
successHandlerGenerator(notify, `Kubernetes pinged: ${name}`, () => updateProgress({ showProgress : false }),),
errorHandlerGenerator(notify, `Not able to ping kubernetes: ${name}`, () => updateProgress({ showProgress : false })),
connectionID
)
}

Expand All @@ -359,8 +358,8 @@ function K8sContextMenu({
}
}
deleteKubernetesConfig(
successHandlerGenerator(notify, "Kubernetes config removed", successCallback),
errorHandlerGenerator(notify, "Not able to remove config"),
successHandlerGenerator(notify, `Kubernetes config removed for ${name}`, successCallback),
errorHandlerGenerator(notify, `Not able to remove config for ${name}`),
connectionID
)
}
Expand All @@ -377,7 +376,7 @@ function K8sContextMenu({
}, [])
return (
<>
<div style={ show ? cursorNotAllowed : {}}>
<div style={show ? cursorNotAllowed : {}}>
<IconButton
aria-label="contexts"
className="k8s-icon-button"
Expand All @@ -399,7 +398,7 @@ function K8sContextMenu({
? 'menu-list-grow'
: undefined}
aria-haspopup="true"
style={show? ctxStyle : { marginRight : "0.5rem" }}
style={show ? ctxStyle : { marginRight : "0.5rem" }}
>
<div className={classes.cbadgeContainer}>
<img className="k8s-image" src="/static/img/kubernetes.svg" width="24px" height="24px" style={{ zIndex : "2" }} />
Expand Down Expand Up @@ -430,7 +429,7 @@ function K8sContextMenu({
InputProps={{
endAdornment :
(
<Search className={classes.searchIcon} style={iconMedium} />
<Search className={classes.searchIcon} style={iconMedium} />
)
}}
/>
Expand Down Expand Up @@ -461,7 +460,7 @@ function K8sContextMenu({
</Button>
</Link>
}
{contexts?.contexts?.map((ctx,idx) => {
{contexts?.contexts?.map((ctx, idx) => {
const meshStatus = getMeshSyncStatus(ctx.id);
const brokerStatus = getBrokerStatus(ctx.id);
const operStatus = getOperatorStatus(ctx.id);
Expand All @@ -485,7 +484,7 @@ function K8sContextMenu({
<Chip
label={ctx?.name}
onDelete={handleKubernetesDelete(ctx.name, ctx.connection_id)}
onClick={() => handleKubernetesClick(ctx.connection_id)}
onClick={() => handleKubernetesClick(ctx.name, ctx.connection_id)}
avatar={
meshStatus ?
<BadgeAvatars>
Expand Down Expand Up @@ -675,4 +674,4 @@ const mapDispatchToProps = (dispatch) => ({
});


export default withStyles(styles)(connect(mapStateToProps, mapDispatchToProps)(withNotify(Header)));
export default withStyles(styles)(connect(mapStateToProps, mapDispatchToProps)(withNotify(Header)));
7 changes: 6 additions & 1 deletion ui/lib/data-fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ const dataFetch = (url, options = {}, successFn, errorFn) => {
// const signal = controller.signal;
// options.signal = signal;
// setTimeout(() => controller.abort(), 10000); // nice to have but will mess with the load test
if (errorFn === undefined) {
errorFn = (err) => {
console.error(`Error fetching ${url} --DataFetch`, err);
};
}
fetch(url, options)
.then(res => {
if (res.status === 401 || res.redirected) {
Expand Down Expand Up @@ -33,7 +38,7 @@ const dataFetch = (url, options = {}, successFn, errorFn) => {

}).then(successFn)
.catch((e) => {
if(e.then) {
if (e.then) {
e.then(text => errorFn(text))
return;
}
Expand Down

0 comments on commit 3f36a0a

Please sign in to comment.