F #3951: Wizard create & update application (#281)

This commit is contained in:
Sergio Betanzos authored and GitHub committed 2020-10-02 13:43:24 +02:00
1 parent 5330483ce5
commit e672fb856b
40 files changed
+925 -518

No files matched your search

-1
View File
@@ -57,7 +57,6 @@
"luxon": "^1.25.0",
"morgan": "^1.10.0",
"node-pre-gyp": "^0.15.0",
"one-datatable": "sbbarragan/material-table#develop",
"prop-types": "^15.7.2",
"qrcode": "^1.4.2",
"react": "^16.8.6",
+7 -3
View File
@@ -18,9 +18,13 @@ module.exports = {
type: SUCCESS_ONE_REQUEST,
payload: { templates }
}),
setServices: services => ({
setApplications: applications => ({
type: SUCCESS_ONE_REQUEST,
payload: { services }
payload: { applications }
}),
setApplicationsTemplates: applicationsTemplates => ({
type: SUCCESS_ONE_REQUEST,
payload: { applicationsTemplates }
}),
setDatastores: datastores => ({
type: SUCCESS_ONE_REQUEST,
@@ -54,7 +58,7 @@ module.exports = {
type: SUCCESS_ONE_REQUEST,
payload: { vNetworks }
}),
setVNetworkTemplates: vNetworksTemplates => ({
setVNetworksTemplates: vNetworksTemplates => ({
type: SUCCESS_ONE_REQUEST,
payload: { vNetworksTemplates }
}),
@@ -0,0 +1,137 @@
import React from 'react';
import {
makeStyles,
Box,
Fade,
Badge,
Button,
Card,
CardHeader,
CardContent,
CardActions
} from '@material-ui/core';
import FileIcon from '@material-ui/icons/Description';
import VideogameAssetIcon from '@material-ui/icons/VideogameAsset';
import AccountTreeIcon from '@material-ui/icons/AccountTree';
import { Tr } from 'client/components/HOC';
const useStyles = makeStyles(theme => ({
root: {
height: '100%',
minHeight: 140,
display: 'flex',
flexDirection: 'column'
},
selected: {
color: theme.palette.primary.contrastText,
backgroundColor: theme.palette.primary.main,
'& $badge': {
color: theme.palette.primary.main,
backgroundColor: theme.palette.common.white
}
},
actionArea: {
height: '100%'
},
header: {
overflowX: 'hidden',
flexGrow: 1
},
subheader: {
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'initial',
display: '-webkit-box',
lineClamp: 2,
boxOrient: 'vertical'
},
badgesWrapper: {
display: 'flex',
gap: theme.typography.pxToRem(12)
},
badge: {},
icon: {}
}));
const ApplicationTemplateCard = React.memo(
({ value, handleEdit, handleDeploy, handleRemove }) => {
const classes = useStyles();
const { ID, NAME, TEMPLATE } = value;
const { description, networks, roles } = TEMPLATE.BODY;
const numberOfNetworks = Object.keys(networks)?.length ?? 0;
const numberOfTiers = Object.keys(roles)?.length ?? 0;
const badgePosition = { vertical: 'top', horizontal: 'right' };
return (
<Fade in unmountOnExit={false}>
<Card className={classes.root}>
<CardHeader
avatar={<FileIcon />}
className={classes.header}
classes={{ content: classes.headerContent }}
title={NAME}
titleTypographyProps={{
variant: 'body2',
noWrap: true,
title: NAME
}}
subheader={description}
subheaderTypographyProps={{
variant: 'body2',
noWrap: true,
className: classes.subheader,
title: description
}}
/>
<CardContent>
<Box className={classes.badgesWrapper}>
<Badge
showZero
title={Tr('Tiers')}
classes={{ badge: classes.badge }}
color="primary"
badgeContent={numberOfTiers}
anchorOrigin={badgePosition}
>
<VideogameAssetIcon />
</Badge>
<Badge
showZero
title={Tr('Networks')}
classes={{ badge: classes.badge }}
color="primary"
badgeContent={numberOfNetworks}
anchorOrigin={badgePosition}
>
<AccountTreeIcon />
</Badge>
</Box>
</CardContent>
<CardActions>
{handleEdit && (
<Button variant="contained" size="small" onClick={handleEdit}>
{Tr('Edit')}
</Button>
)}
{handleDeploy && (
<Button variant="contained" size="small" onClick={handleDeploy}>
{Tr('Clone')}
</Button>
)}
{handleRemove && (
<Button size="small" onClick={handleRemove}>
{Tr('Remove')}
</Button>
)}
</CardActions>
</Card>
</Fade>
);
}
);
export default ApplicationTemplateCard;
@@ -3,5 +3,13 @@ import NetworkCard from 'client/components/Cards/NetworkCard';
import TierCard from 'client/components/Cards/TierCard';
import EmptyCard from 'client/components/Cards/EmptyCard';
import SelectCard from 'client/components/Cards/SelectCard';
import ApplicationTemplateCard from 'client/components/Cards/ApplicationTemplateCard';
export { ClusterCard, NetworkCard, TierCard, EmptyCard, SelectCard };
export {
ClusterCard,
NetworkCard,
TierCard,
EmptyCard,
SelectCard,
ApplicationTemplateCard
};
@@ -7,11 +7,12 @@ import { Controller } from 'react-hook-form';
import ErrorHelper from 'client/components/FormControl/ErrorHelper';
const TextController = memo(
({ control, cy, name, label, error }) => (
({ control, cy, type, name, label, error }) => (
<Controller
as={
<TextField
fullWidth
type={type}
label={label}
inputProps={{ 'data-cy': cy }}
error={Boolean(error)}
@@ -29,6 +30,7 @@ const TextController = memo(
TextController.propTypes = {
control: PropTypes.object,
cy: PropTypes.string,
type: PropTypes.string,
name: PropTypes.string.isRequired,
label: PropTypes.string,
error: PropTypes.oneOfType([
@@ -40,6 +42,7 @@ TextController.propTypes = {
TextController.defaultProps = {
control: {},
cy: 'cy',
type: 'text',
name: '',
label: '',
error: false
@@ -10,12 +10,12 @@ import ErrorHelper from 'client/components/FormControl/ErrorHelper';
const FIRST_STEP = 0;
const FormStepper = ({ steps, initialValue, onSubmit }) => {
const FormStepper = ({ steps, onSubmit }) => {
const isMobile = useMediaQuery(theme => theme.breakpoints.only('xs'));
const { watch, trigger, reset, errors } = useFormContext();
const [formData, setFormData] = useState(() => watch());
const [activeStep, setActiveStep] = useState(FIRST_STEP);
const [formData, setFormData] = useState(initialValue);
const totalSteps = useMemo(() => steps?.length, [steps]);
const lastStep = useMemo(() => totalSteps - 1, [totalSteps]);
@@ -26,9 +26,9 @@ const FormStepper = ({ steps, initialValue, onSubmit }) => {
}, [formData]);
const handleNext = useCallback(() => {
const { id } = steps[activeStep];
const idSteps = steps.slice(0, activeStep + 1).map(({ id }) => id);
trigger(id).then(isValid => {
trigger(idSteps).then(isValid => {
if (!isValid) return;
const data = { ...formData, ...watch() };
@@ -22,30 +22,34 @@ const FormWithSchema = ({ id, cy, fields }) => {
return (
<Grid container spacing={1}>
{fields?.map(({ name, type, label, values, dependOf, tooltip }) => {
const dataCy = `${cy}-${name}`;
const inputName = id ? `${id}.${name}` : name;
const formError = id ? errors[id] : errors;
const inputError = formError ? formError[name] : false;
const dependValue = dependOf
? useWatch({ control, name: id ? `${id}.${dependOf}` : dependOf })
: null;
{fields?.map(
({ name, type, htmlType, label, values, dependOf, tooltip, grid }) => {
const dataCy = `${cy}-${name}`;
const inputName = id ? `${id}.${name}` : name;
const formError = id ? errors[id] : errors;
const inputError = formError ? formError[name] : false;
const dependValue = dependOf
? useWatch({ control, name: id ? `${id}.${dependOf}` : dependOf })
: null;
return (
<Grid key={`${cy}-${name}`} item xs={12} md={6}>
{InputController[type] &&
React.createElement(InputController[type], {
control,
cy: dataCy,
name: inputName,
label,
tooltip,
values: dependOf ? values(dependValue) : values,
error: inputError
})}
</Grid>
);
})}
return (
InputController[type] && (
<Grid key={`${cy}-${name}`} item xs={12} md={6} {...grid}>
{React.createElement(InputController[type], {
control,
cy: dataCy,
type: htmlType,
name: inputName,
label,
tooltip,
values: dependOf ? values(dependValue) : values,
error: inputError
})}
</Grid>
)
);
}
)}
</Grid>
);
};
@@ -41,7 +41,8 @@ const MainLayout = ({ children }) => {
}
}, [isLogged, isLoginInProcess]);
const { authenticated: authRoute } = findRouteByPathname(pathname);
const { authenticated } = findRouteByPathname(pathname);
const authRoute = Boolean(authenticated);
// PENDING TO AUTHENTICATING OR FIRST RENDERING
if (firstRender || (isLogged && authRoute && !authUser && !groups?.length)) {
@@ -18,7 +18,7 @@ import PropTypes from 'prop-types';
import { Select } from '@material-ui/core';
import { sprintf } from 'sprintf-js';
import root from 'window-or-global';
import { translations, defaultLang } from '../../../utils/constants/defaults';
import { translations, defaultLang } from 'server/utils/constants/defaults';
const langDefault = defaultLang;
const TranslateContext = new CreateContext();
@@ -13,7 +13,7 @@
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
import React from 'react';
import React, { useMemo } from 'react';
import clsx from 'clsx';
import {
List,
@@ -33,18 +33,6 @@ import SidebarLink from 'client/components/Sidebar/SidebarLink';
import SidebarCollapseItem from 'client/components/Sidebar/SidebarCollapseItem';
import Logo from 'client/icons/logo';
const Endpoints = React.memo(() =>
endpoints
?.filter(({ authenticated, header = false }) => authenticated && !header)
?.map((endpoint, index) =>
endpoint.routes ? (
<SidebarCollapseItem key={`item-${index}`} {...endpoint} />
) : (
<SidebarLink key={`item-${index}`} {...endpoint} />
)
)
);
const Sidebar = () => {
const classes = sidebarStyles();
const { isFixMenu, fixMenu } = useGeneral();
@@ -52,7 +40,23 @@ const Sidebar = () => {
const handleSwapMenu = () => fixMenu(!isFixMenu);
return React.useMemo(
const SidebarEndpoints = useMemo(
() =>
endpoints
?.filter(
({ authenticated, sidebar = false }) => authenticated && sidebar
)
?.map((endpoint, index) =>
endpoint.routes ? (
<SidebarCollapseItem key={`item-${index}`} {...endpoint} />
) : (
<SidebarLink key={`item-${index}`} {...endpoint} />
)
),
[endpoints]
);
return useMemo(
() => (
<Drawer
variant={'permanent'}
@@ -83,7 +87,7 @@ const Sidebar = () => {
<Divider />
<Box className={classes.menu}>
<List className={classes.list} disablePadding>
<Endpoints />
{SidebarEndpoints}
</List>
</Box>
</Drawer>
@@ -2,15 +2,15 @@ import * as yup from 'yup';
import { TYPE_INPUT } from 'client/constants';
import { getValidationFromFields } from 'client/utils/helpers';
export const STRATEGIES_DEPLOY = [
{ text: 'None', value: 'none' },
const STRATEGIES_DEPLOY = [
{ text: 'None', value: '""' },
{ text: 'Straight', value: 'straight' }
];
export const SHUTDOWN_ACTIONS = [
{ text: 'None', value: 'none' },
{ text: 'Terminate', value: 'shutdown' },
{ text: 'Terminate hard', value: 'shutdown-hard' }
const SHUTDOWN_ACTIONS = [
{ text: 'None', value: '""' },
{ text: 'Terminate', value: 'terminate' },
{ text: 'Terminate hard', value: 'terminate-hard' }
];
export const FORM_FIELDS = [
@@ -23,7 +23,7 @@ export const FORM_FIELDS = [
.min(5)
.trim()
.required('Name field is required')
.default('One_application')
.default('')
},
{
name: 'description',
@@ -33,7 +33,7 @@ export const FORM_FIELDS = [
validation: yup
.string()
.trim()
.default('OpenNebula is so cool!')
.default('')
},
{
name: 'deployment',
@@ -44,7 +44,7 @@ export const FORM_FIELDS = [
.string()
.required()
.oneOf(STRATEGIES_DEPLOY.map(({ value }) => value))
.default(STRATEGIES_DEPLOY[0].value)
.default(STRATEGIES_DEPLOY[1].value)
},
{
name: 'shutdown_action',
@@ -54,7 +54,7 @@ export const FORM_FIELDS = [
validation: yup
.string()
.oneOf(SHUTDOWN_ACTIONS.map(({ value }) => value))
.default(SHUTDOWN_ACTIONS[0].value)
.default(SHUTDOWN_ACTIONS[1].value)
},
{
name: 'ready_status_gate',
@@ -17,11 +17,15 @@ const TYPES_NETWORKS = [
const ID = {
name: 'id',
label: 'ID',
type: TYPE_INPUT.TEXT,
htmlType: 'hidden',
validation: yup
.string()
.uuid()
.required()
.default(uuidv4)
.default(uuidv4),
grid: { style: { display: 'none' } }
};
const MANDATORY = {
@@ -31,7 +35,8 @@ const MANDATORY = {
validation: yup
.boolean()
.required()
.default(false)
.default(false),
grid: { md: 12 }
};
const NAME = {
@@ -41,7 +46,7 @@ const NAME = {
validation: yup
.string()
.trim()
.required('Name is a required field')
.required('Name field is a required')
.default('')
};
@@ -64,12 +69,12 @@ const TYPE = {
validation: yup
.string()
.oneOf(TYPES_NETWORKS.map(({ value }) => value))
.required('Type is required field')
.required('Type field is required')
.default(TYPES_NETWORKS[0].value)
};
const ID_VNET = {
name: 'id_vnet',
name: 'idVnet',
label: `Select a network`,
type: TYPE_INPUT.AUTOCOMPLETE,
dependOf: TYPE.name,
@@ -91,8 +96,8 @@ const ID_VNET = {
TYPES_NETWORKS.some(
({ value, select }) => type === value && select === SELECT.network
)
? schema.required('Network is required field')
: schema.required('Network template is required field')
? schema.required('Network field is required')
: schema.required('Network template field is required')
)
.default(undefined)
};
@@ -2,6 +2,12 @@ import * as yup from 'yup';
import { TYPE_INPUT } from 'client/constants';
import { getValidationFromFields } from 'client/utils/helpers';
const SHUTDOWN_ACTIONS = [
{ text: 'None', value: '""' },
{ text: 'Shutdown', value: 'shutdown' },
{ text: 'Shutdown hard', value: 'shutdown-hard' }
];
export const FORM_FIELDS = [
{
name: 'name',
@@ -23,6 +29,16 @@ export const FORM_FIELDS = [
.min(1)
.required()
.default(1)
},
{
name: 'shutdown_action',
label: 'Select a VM shutdown action',
type: TYPE_INPUT.SELECT,
values: SHUTDOWN_ACTIONS,
validation: yup
.string()
.oneOf(SHUTDOWN_ACTIONS.map(({ value }) => value))
.default(SHUTDOWN_ACTIONS[1].value)
}
];
@@ -4,7 +4,7 @@ import { getValidationFromFields } from 'client/utils/helpers';
export const FORM_FIELDS = [
{
name: 'elasticity',
name: 'elasticityPolicies',
label: 'Elasticity',
type: TYPE_INPUT.TEXT,
validation: yup
@@ -13,7 +13,7 @@ export const FORM_FIELDS = [
.default('')
},
{
name: 'scheduled',
name: 'scheduledPolicies',
label: 'Scheduled',
type: TYPE_INPUT.TEXT,
validation: yup
@@ -18,5 +18,5 @@ export const FORM_FIELDS = [
export const STEP_FORM_SCHEMA = yup
.object(getValidationFromFields(FORM_FIELDS))
// .required('Template is required')
.required('Template is required')
.default(undefined);
@@ -21,30 +21,6 @@ export const STEP_ID = 'tiers';
const Tiers = () => {
const { steps, defaultValues, resolvers } = Steps();
const FRONTEND = {
...defaultValues(),
parents: [],
tier: { name: 'frontend', cardinality: 1 }
};
const MASTER = {
...defaultValues(),
parents: [FRONTEND.id],
tier: { name: 'master', cardinality: 1 }
};
const MINION = {
...defaultValues(),
parents: [FRONTEND.id],
tier: { name: 'minion', cardinality: 1 }
};
const WORKER = {
...defaultValues(),
parents: [MASTER.id, MINION.id],
tier: { name: 'worker', cardinality: 10 }
};
return {
id: STEP_ID,
label: 'Tier Definition',
@@ -53,7 +29,7 @@ const Tiers = () => {
.of(resolvers)
.min(1)
.required()
.default([FRONTEND, MASTER, MINION, WORKER]),
.default([]),
content: useCallback(({ data, setFormData }) => {
const [showDialog, setShowDialog] = useState(false);
const [nestedForm, setNestedForm] = useState({});
@@ -112,7 +88,6 @@ const Tiers = () => {
<Box display="flex" flexDirection="column" height={1}>
<FormStepper
steps={formSteps}
initialValue={editingData}
onSubmit={values => {
handleSave(values);
setShowDialog(false);
@@ -1,4 +1,5 @@
import React from 'react';
import React, { useEffect } from 'react';
import { useHistory, useParams } from 'react-router-dom';
import { Container } from '@material-ui/core';
import { useForm, FormProvider } from 'react-hook-form';
@@ -7,8 +8,24 @@ import { yupResolver } from '@hookform/resolvers';
import FormStepper from 'client/components/FormStepper';
import Steps from 'client/containers/Application/Create/Steps';
import { PATH } from 'client/router/endpoints';
import useFetch from 'client/hooks/useFetch';
import useApplication from 'client/hooks/useApplication';
import mapApplicationToForm from 'client/utils/parser/toApplicationForm';
import mapFormToApplication from 'client/utils/parser/toApplicationTemplate';
function ApplicationCreate() {
const history = useHistory();
const { id } = useParams();
const { steps, defaultValues, resolvers } = Steps();
const {
getApplicationTemplate,
createApplicationTemplate,
updateApplicationTemplate
} = useApplication();
const { data, fetchRequest, loading, error } = useFetch(
getApplicationTemplate
);
const methods = useForm({
mode: 'onSubmit',
@@ -16,20 +33,51 @@ function ApplicationCreate() {
resolver: yupResolver(resolvers)
});
const onSubmit = formData => console.log('submit', formData, methods.errors);
const onSubmit = formData => {
const application = mapFormToApplication(formData);
if (id)
updateApplicationTemplate({ id, data: application }).then(() =>
history.push(PATH.APPLICATION.DEPLOY)
);
else
createApplicationTemplate({ data: application }).then(() =>
history.push(PATH.APPLICATION.DEPLOY)
);
};
useEffect(() => {
try {
if (id) {
const idNumber = parseInt(id, 10);
if (idNumber < 0) throw new Error();
fetchRequest({ id: idNumber });
}
} catch {
// show error
history.push(PATH.DASHBOARD);
}
}, [id]);
useEffect(() => {
const formData = data ? mapApplicationToForm(data) : {};
methods.reset({ ...defaultValues, ...formData }, { errors: false });
}, [data]);
return (
<Container
disableGutters
style={{ height: '100%', display: 'flex', flexDirection: 'column' }}
>
<FormProvider {...methods}>
<FormStepper
steps={steps}
initialValue={defaultValues}
onSubmit={onSubmit}
/>
</FormProvider>
{error && <div>error!</div>}
{!error && loading ? (
<div>is loading...</div>
) : (
<FormProvider {...methods}>
<FormStepper steps={steps} onSubmit={onSubmit} />
</FormProvider>
)}
</Container>
);
}
@@ -0,0 +1,27 @@
import React, { useEffect } from 'react';
import useGeneral from 'client/hooks/useGeneral';
import useApplication from 'client/hooks/useApplication';
import ListCards from 'client/components/List/ListCards';
import { ClusterCard } from 'client/components/Cards';
const ApplicationsList = () => {
const { applications, getApplications } = useApplication();
useEffect(() => {
getApplications();
}, []);
return (
<ListCards
list={applications}
CardComponent={ClusterCard}
cardsProps={({ value }) => {
console.log(value);
}}
/>
);
};
export default ApplicationsList;
@@ -0,0 +1,56 @@
import React, { useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import { Box } from '@material-ui/core';
import { Alert } from '@material-ui/lab';
import useApplication from 'client/hooks/useApplication';
import useFetch from 'client/hooks/useFetch';
import ListCards from 'client/components/List/ListCards';
import { ApplicationTemplateCard } from 'client/components/Cards';
import { PATH } from 'client/router/endpoints';
import { Tr } from 'client/components/HOC';
const ApplicationsTemplatesList = () => {
const history = useHistory();
const { applicationsTemplates, getApplicationsTemplates } = useApplication();
const { fetchRequest, loading, error } = useFetch(getApplicationsTemplates);
useEffect(() => {
fetchRequest();
}, []);
if (error) {
return (
<Box pt={3} display="flex" justifyContent="center">
<Alert severity="error" icon={false} variant="filled">
{Tr('Cannot connect to OneFlow server')}
</Alert>
</Box>
);
}
if (loading) {
return <div>loading</div>;
}
return (
<Box p={3}>
<ListCards
list={applicationsTemplates}
handleCreate={() => history.push(PATH.APPLICATION.CREATE)}
CardComponent={ApplicationTemplateCard}
cardsProps={({ value: { ID } }) => ({
handleEdit: () =>
history.push(PATH.APPLICATION.EDIT.replace(':id', ID)),
handleDeploy: undefined,
handleRemove: undefined
})}
/>
</Box>
);
};
export default ApplicationsTemplatesList;
@@ -13,49 +13,66 @@
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
import React, { useEffect } from 'react';
import React, { useState } from 'react';
import {
makeStyles,
Card,
Chip,
CardContent,
Box,
Tab,
Tabs,
Paper,
Typography,
LinearProgress,
Box
Container
} from '@material-ui/core';
import useGeneral from 'client/hooks/useGeneral';
import useOpennebula from 'client/hooks/useOpennebula';
import ApplicationsTemplatesList from './Templates';
const useStyles = makeStyles({
card: {
minWidth: 275,
marginBottom: '2em'
},
title: {
fontSize: 14
}
});
const TABS = {
TEMPLATES: 'templates',
APPLICATIONS: 'applications'
};
function ApplicationDeploy() {
const classes = useStyles();
const { isLoading } = useGeneral();
const { groups, getUsers } = useOpennebula();
const [value, setValue] = useState(TABS.TEMPLATES);
useEffect(() => {
if (!isLoading) {
getUsers();
}
}, [getUsers]);
const getGroupById = findId => groups?.find(({ ID }) => ID === findId);
const handleChange = (_, newValue) => {
setValue(newValue);
};
return (
<>
{isLoading && <LinearProgress style={{ width: '100%' }} />}
Deploy
</>
<Container
disableGutters
style={{ height: '100%', display: 'flex', flexDirection: 'column' }}
>
<Paper>
<Tabs
value={value}
onChange={handleChange}
indicatorColor="primary"
textColor="primary"
>
<Tab
value={TABS.TEMPLATES}
label="Applications templates"
id={`tab-${TABS.TEMPLATES}`}
/>
<Tab
value={TABS.APPLICATIONS}
label="Applications deployed"
id={`tab-${TABS.APPLICATIONS}`}
/>
</Tabs>
</Paper>
<div hidden={value !== TABS.TEMPLATES}>
{value === TABS.TEMPLATES && <ApplicationsTemplatesList />}
</div>
<div hidden={value !== TABS.APPLICATIONS}>
{value === TABS.APPLICATIONS && (
<Box p={3}>
<Typography>{'Applications deployed'}</Typography>
</Box>
)}
</div>
</Container>
);
}
@@ -1,70 +0,0 @@
/* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
import React, { createRef } from 'react';
import PropTypes from 'prop-types';
import MaterialTable from 'one-datatable';
import { Refresh as RefreshIcon } from '@material-ui/icons';
import { Translate } from '../../components/HOC';
import { requestData } from '../../utils';
import HostColumns from './host-columns';
function Clusters({ name }) {
const tableRef = createRef();
return (
<div>
<MaterialTable
tableRef={tableRef}
title={
<h2>
<Translate word={name} />
</h2>
}
columns={HostColumns.columns}
data={query =>
new Promise(resolve => {
requestData('/api/hostpool/info').then(result => {
const values = Object.values(result?.data?.HOST_POOL);
resolve({
data: values,
page: query.page,
totalCount: values.length
});
});
})
}
actions={[
{
icon: () => <RefreshIcon />,
tooltip: 'Refresh Data',
isFreeAction: true,
onClick: () => tableRef?.current?.onQueryChange()
}
]}
/>
</div>
);
}
Clusters.propTypes = {
name: PropTypes.string
};
Clusters.defaultProps = {
name: ''
};
export default Clusters;
@@ -1,71 +0,0 @@
/* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
import React, { createRef } from 'react';
import PropTypes from 'prop-types';
import MaterialTable from 'one-datatable';
import { Refresh as RefreshIcon } from '@material-ui/icons';
import { Translate } from '../../components/HOC';
import { requestData } from '../../utils';
import HostColumns from './host-columns';
function Hosts({ name }) {
const tableRef = createRef();
return (
<div>
<MaterialTable
tableRef={tableRef}
title={
<h2>
<Translate word={name} />
</h2>
}
columns={HostColumns.columns}
data={query =>
new Promise(resolve => {
requestData('/api/hostpool/info').then(result => {
const values = Object.values(result?.data?.HOST_POOL);
resolve({
data: values,
page: query.page,
totalCount: values.length
});
});
})
}
actions={[
{
icon: () => <RefreshIcon />,
tooltip: 'Refresh Data',
isFreeAction: true,
onClick: () => tableRef?.current?.onQueryChange()
}
]}
/>
</div>
);
}
Hosts.propTypes = {
name: PropTypes.string
};
Hosts.defaultProps = {
name: ''
};
export default Hosts;
@@ -1,71 +0,0 @@
/* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
import React, { createRef } from 'react';
import PropTypes from 'prop-types';
import MaterialTable from 'one-datatable';
import { Refresh as RefreshIcon } from '@material-ui/icons';
import { Translate } from '../../components/HOC';
import { requestData } from '../../utils';
import HostColumns from './host-columns';
function Zones({ name }) {
const tableRef = createRef();
return (
<div>
<MaterialTable
tableRef={tableRef}
title={
<h2>
<Translate word={name} />
</h2>
}
columns={HostColumns.columns}
data={query =>
new Promise(resolve => {
requestData('/api/hostpool/info').then(result => {
const values = Object.values(result?.data?.HOST_POOL);
resolve({
data: values,
page: query.page,
totalCount: values.length
});
});
})
}
actions={[
{
icon: () => <RefreshIcon />,
tooltip: 'Refresh Data',
isFreeAction: true,
onClick: () => tableRef?.current?.onQueryChange()
}
]}
/>
</div>
);
}
Zones.propTypes = {
name: PropTypes.string
};
Zones.defaultProps = {
name: ''
};
export default Zones;
@@ -1,86 +0,0 @@
/* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
import React from 'react';
import { LinearProgress } from '@material-ui/core';
const statusBar = (title, ratio) => (
<div>
{title}
<LinearProgress variant="determinate" value={ratio} />
</div>
);
function format(size) {
if (typeof size !== 'number' || size === 0) {
return '0';
}
const baseLog = Math.floor(Math.log(size) / Math.log(1024));
console.log(baseLog);
return `${(size / 1024 ** baseLog).toFixed(2) * 1}${
['kB', 'MB', 'GB', 'TB'][baseLog]
}`;
}
export default {
columns: [
{ title: 'ID', field: 'ID' },
{ title: 'Name', field: 'NAME' },
{ title: 'Cluster', field: 'CLUSTER' },
{ title: 'RVMs', field: 'HOST_SHARE.RUNNING_VMS', type: 'numeric' },
{
title: 'Allocated CPU',
field: 'HOST_SHARE.MAX_CPU',
type: 'numeric',
render: row => {
const usage = parseInt(row?.HOST_SHARE?.CPU_USAGE, 10);
const max = parseInt(row?.HOST_SHARE?.MAX_CPU, 10);
const ratio = Math.round((usage / max) * 100);
const info = `${format(usage)} / ${format(max)} (${ratio}%)`;
return statusBar(info, ratio);
}
},
{
title: 'Allocated MEM',
field: 'HOST_SHARE.MAX_MEM',
type: 'numeric',
render: row => {
console.log(row);
const usage = parseInt(row?.HOST_SHARE?.MEM_USAGE, 10);
const max = parseInt(row?.HOST_SHARE?.MAX_MEM, 10);
const ratio = Math.round((usage / max) * 100);
const info = `${format(usage)} / ${format(max)} (${ratio}%)`;
return statusBar(info, ratio);
}
},
{
title: 'Status',
field: 'STATE',
lookup: {
'0': 'INIT',
'1': 'UPDATE',
'2': 'ON',
'3': 'ERROR',
'4': 'DISABLED',
'5': 'RETRY',
'6': 'INIT',
'7': 'DISABLED',
'8': 'OFF'
}
},
{ title: 'IM MAD', field: 'IM_MAD' },
{ title: 'VM MAD', field: 'VM_MAD' }
]
};
@@ -1,20 +0,0 @@
/* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
import Clusters from './Clusters';
import Hosts from './Hosts';
import Zones from './Zones';
export { Clusters, Hosts, Zones };
@@ -14,8 +14,8 @@
/* -------------------------------------------------------------------------- */
import React from 'react';
import { Translate } from '../../components/HOC';
import constants from '../../constants';
import { Translate } from 'client/components/HOC';
import constants from 'client/constants';
const { settings } = constants;
const Settings = () => (
@@ -0,0 +1,102 @@
import { useCallback } from 'react';
import { useSelector, useDispatch, shallowEqual } from 'react-redux';
import actions, {
startOneRequest,
failureOneRequest
} from 'client/actions/pool';
import * as serviceApplication from 'client/services/application';
import { filterBy } from 'client/utils/helpers';
export default function useOpennebula() {
const dispatch = useDispatch();
const {
applications,
applicationsTemplates,
filterPool: filter
} = useSelector(
state => ({
...state?.Opennebula,
filterPool: state?.Authenticated?.filterPool
}),
shallowEqual
);
const getApplications = useCallback(
({ end, start } = { end: -1, start: -1 }) => {
dispatch(startOneRequest());
return serviceApplication
.getApplications({ filter, end, start })
.then(data =>
dispatch(
actions.setApplications(filterBy(applications.concat(data), 'ID'))
)
)
.catch(err => {
dispatch(failureOneRequest({ error: err }));
});
},
[dispatch, filter, applications]
);
const getApplicationTemplate = useCallback(
({ id }) => {
dispatch(startOneRequest());
return serviceApplication.getTemplate({ id }).catch(err => {
dispatch(failureOneRequest({ error: err }));
});
},
[dispatch]
);
const getApplicationsTemplates = useCallback(
({ end, start } = { end: -1, start: -1 }) => {
dispatch(startOneRequest());
return serviceApplication
.getTemplates({ filter, end, start })
.then(data =>
dispatch(
actions.setApplicationsTemplates(
filterBy(applicationsTemplates.concat(data), 'ID')
)
)
)
.catch(err => {
dispatch(failureOneRequest({ error: err }));
});
},
[dispatch, filter, applicationsTemplates]
);
const createApplicationTemplate = useCallback(
({ data }) => {
dispatch(startOneRequest());
return serviceApplication.createTemplate({ data }).catch(err => {
dispatch(failureOneRequest({ error: err }));
});
},
[dispatch]
);
const updateApplicationTemplate = useCallback(
({ id, data }) => {
dispatch(startOneRequest());
return serviceApplication.updateTemplate({ id, data }).catch(err => {
dispatch(failureOneRequest({ error: err }));
});
},
[dispatch]
);
return {
applications,
getApplications,
applicationsTemplates,
getApplicationTemplate,
getApplicationsTemplates,
createApplicationTemplate,
updateApplicationTemplate
};
}
+35
View File
@@ -0,0 +1,35 @@
import { useState, useCallback } from 'react';
const useRequest = request => {
const [data, setData] = useState(undefined);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
const fetchRequest = useCallback(
payload => {
let ignore = false;
setLoading(true);
setError(false);
request(payload)
.then(response => {
if (response !== undefined && !ignore) {
setData(response);
} else {
setError(true);
}
})
.finally(() => {
setLoading(false);
});
return () => {
ignore = true;
};
},
[request]
);
return { data, fetchRequest, loading, error };
};
export default useRequest;
+4 -4
View File
@@ -30,12 +30,12 @@ const useListSelect = ({ multiple, key, list, setList, defaultValue }) => {
const handleClone = useCallback(
id => {
const itemIndex = getIndexById(list, id);
const { id: itemId, name, ...item } = list[itemIndex];
const { id: itemId, name = itemId, ...item } = list[itemIndex];
const cloneList = [...list];
const cloneItem = {
...item,
id: defaultValue.id,
name: `${name ?? itemId}_clone`
name: `${name}_clone`
};
const ZERO_DELETE_COUNT = 0;
@@ -65,9 +65,9 @@ const useListSelect = ({ multiple, key, list, setList, defaultValue }) => {
);
const handleSave = useCallback(
(values, id) => {
(values, id = editingData.id) => {
setList(prevList => {
const itemIndex = getIndexById(prevList[key], id ?? editingData.id);
const itemIndex = getIndexById(prevList[key], id);
const index = EXISTS_INDEX(itemIndex)
? itemIndex
: prevList[key].length;
@@ -56,7 +56,7 @@ export default function useOpennebula() {
dispatch(startOneRequest());
return servicePool
.getVNetworksTemplates({ filter })
.then(data => dispatch(actions.setVNetworkTemplates(data)))
.then(data => dispatch(actions.setVNetworksTemplates(data)))
.catch(err => dispatch(failureOneRequest({ error: err })));
}, [dispatch, filter]);
+6 -1
View File
@@ -19,6 +19,7 @@ const { Actions: GeneralActions } = require('../actions/general');
const initial = {
zone: 0,
errors: [],
isLoading: false,
isOpenMenu: false,
isFixMenu: false
@@ -31,7 +32,11 @@ const General = (state = initial, action) => {
case PoolActions.SUCCESS_ONE_REQUEST:
return { ...state, isLoading: false };
case PoolActions.FAILURE_ONE_REQUEST:
return { ...state, isLoading: false };
return {
...state,
errors: [...state.errors, action.payload.error],
isLoading: false
};
case GeneralActions.CHANGE_ZONE:
return { ...state, ...action.payload };
case GeneralActions.TOGGLE_MENU:
@@ -19,7 +19,8 @@ const { Actions: UserActions } = require('../actions/user');
const initial = {
vm: [],
templates: [],
services: [],
applications: [],
applicationsTemplates: [],
datastores: [],
virtualRouters: [],
vmGroups: [],
+26 -5
View File
@@ -21,6 +21,7 @@ import {
Reddit as RedditIcon,
Build as BuildIcon
} from '@material-ui/icons';
import { matchPath } from 'react-router-dom';
import Login from 'client/containers/Login';
import Dashboard from 'client/containers/Dashboard';
@@ -39,7 +40,8 @@ export const PATH = {
APPLICATION: {
CREATE: '/application/create',
MANAGE: '/application/manage',
DEPLOY: '/application/deploy'
DEPLOY: '/application/deploy',
EDIT: '/application/edit/:id'
},
SETTINGS: '/settings',
TEST_API: '/test-api'
@@ -56,6 +58,7 @@ const ENDPOINTS = [
label: 'Dashboard',
path: PATH.DASHBOARD,
authenticated: true,
sidebar: true,
icon: DashboardIcon,
component: Dashboard
},
@@ -72,6 +75,7 @@ const ENDPOINTS = [
path: PATH.TEST_API,
authenticated: true,
devMode: true,
sidebar: true,
icon: BallotIcon,
component: TestApi
},
@@ -80,6 +84,7 @@ const ENDPOINTS = [
path: '/webconsole',
authenticated: true,
devMode: true,
sidebar: true,
icon: BallotIcon,
component: Webconsole
},
@@ -90,10 +95,18 @@ const ENDPOINTS = [
icon: PaletteIcon,
component: ApplicationCreate
},
{
label: 'Edit Application',
path: PATH.APPLICATION.EDIT,
authenticated: true,
icon: PaletteIcon,
component: ApplicationCreate
},
{
label: 'Deploy Application',
path: PATH.APPLICATION.DEPLOY,
authenticated: true,
sidebar: true,
icon: RedditIcon,
component: ApplicationDeploy
},
@@ -101,14 +114,22 @@ const ENDPOINTS = [
label: 'Manage Application',
path: PATH.APPLICATION.MANAGE,
authenticated: true,
sidebar: true,
icon: BuildIcon,
component: ApplicationManage
}
];
export const findRouteByPathname = pathname =>
ENDPOINTS.flatMap(({ routes, ...item }) => routes ?? item)?.find(
({ path }) => path === pathname
) ?? {};
export const findRouteByPathname = pathname => {
const routes = ENDPOINTS.flatMap(
({ endpoints, ...item }) => endpoints ?? item
);
const route = routes?.find(({ path }) =>
matchPath(pathname, { path, exact: true })
);
return route ?? {};
};
export default ENDPOINTS;
+2 -2
View File
@@ -32,8 +32,8 @@ const renderRoute = ({
key={`key-${label.replace(' ', '-')}`}
exact
path={path}
component={props => (
<InternalLayout label={label} authRoute={authenticated} {...props}>
component={() => (
<InternalLayout label={label} authRoute={authenticated}>
<Component />
</InternalLayout>
)}
@@ -0,0 +1,74 @@
import { httpMethod } from 'server/utils/constants/defaults';
import {
SERVICE,
SERVICE_TEMPLATE
} from 'server/routes/api/routes/oneflow/string-routes';
import { jwtName } from 'client/constants';
import { requestData, removeStoreData } from 'client/utils';
import httpCodes from 'server/utils/constants/http-codes';
export const getApplication = ({}) => {
// request
};
export const getApplications = ({ filter }) =>
requestData(`/api/${SERVICE}`, {
data: { filter },
method: httpMethod.GET,
error: err => err?.message
}).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res;
return [res?.data?.DOCUMENT_POOL?.DOCUMENT ?? []].flat();
});
export const createApplication = ({}) => {
// request
};
export const getTemplate = ({ id }) =>
requestData(`/api/${SERVICE_TEMPLATE}/${id}`, {
method: httpMethod.GET,
error: err => err?.message
}).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res;
return res?.data?.DOCUMENT ?? {};
});
export const getTemplates = ({ filter }) =>
requestData(`/api/${SERVICE_TEMPLATE}`, {
data: { filter },
method: httpMethod.GET,
error: err => err?.message
}).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res;
return [res?.data?.DOCUMENT_POOL?.DOCUMENT ?? []].flat();
});
export const createTemplate = ({ data = {} }) =>
requestData(`/api/${SERVICE_TEMPLATE}`, {
data,
method: httpMethod.POST,
error: err => err?.message
}).then(console.log);
export const updateTemplate = ({ id, data = {} }) =>
requestData(`/api/${SERVICE_TEMPLATE}/${id}`, {
data,
method: httpMethod.PUT,
error: err => err?.message
}).then(console.log);
export default {
getApplication,
getApplications,
createApplication,
getTemplate,
getTemplates,
createTemplate,
updateTemplate
};
-47
View File
@@ -1,47 +0,0 @@
import dagre from 'dagre';
const generateFlow = (elements = []) => {
const NODE_WIDTH = 400;
const NODE_HEIGHT = 200;
const graph = new dagre.graphlib.Graph();
graph.setGraph({});
graph.setDefaultEdgeLabel(() => ({}));
elements.forEach(({ id, type, data, parents = [] }) => {
graph.setNode(id, {
data,
type: type ?? 'default',
width: NODE_WIDTH,
height: NODE_HEIGHT
});
parents.forEach(parent => {
graph.setEdge(parent, id);
});
});
dagre.layout(graph);
const nodes = graph.nodes().map(id => {
const node = graph.node(id);
return {
id,
type: node?.type,
data: node?.data,
position: {
x: node.x - node.width / 2,
y: node.y - node.height / 2
}
};
});
const edges = graph.edges().map(({ v: source, w: target }) => ({
id: `__${source}__${target}`,
source,
target,
animated: true
}));
return [...nodes, ...edges];
};
export { generateFlow };
@@ -0,0 +1,41 @@
const SINGLE_VARIABLE_REG = /^\s*(?<key>[\w\d_-]+)\s*=\s*(?<value>[^[\],]+?)(?:#.*)?$/gm;
const ARRAY_VARIABLE_REG = /\s*(?<masterKey>[\w\d_-]+)\s*=\s*\[(?<pieces>.*?)\]/gm;
const sanitizeKey = key => key?.trim().toLowerCase();
const sanitizeValue = value => value?.trim().replaceAll(/[\\"]/g, '');
const parseTemplateToObject = template => {
const stringWithoutNewLines = JSON.stringify(template).replaceAll(/\\n/g, '');
return {
...Array.from(template.matchAll(SINGLE_VARIABLE_REG)).reduce(
(result, match) => {
const key = sanitizeKey(match.groups.key);
const value = sanitizeValue(match.groups.value);
return { ...result, [key]: value };
},
{}
),
...Array.from(stringWithoutNewLines.matchAll(ARRAY_VARIABLE_REG)).reduce(
(result, match) => {
const masterKey = sanitizeKey(match.groups.masterKey);
const pieces = match.groups.pieces.split(',');
const vars = pieces.reduce((vrs, piece) => {
const [key, value] = piece.split('=');
return { ...vrs, [sanitizeKey(key)]: sanitizeValue(value) };
}, {});
return {
...result,
[masterKey]: [...(result[masterKey] ?? []), vars]
};
},
{}
)
};
};
export default parseTemplateToObject;
@@ -0,0 +1,118 @@
import { v4 as uuidv4 } from 'uuid';
import { STEP_ID as APPLICATION_ID } from 'client/containers/Application/Create/Steps/BasicConfiguration';
import { STEP_ID as CLUSTER_ID } from 'client/containers/Application/Create/Steps/Clusters';
import { STEP_ID as NETWORKING_ID } from 'client/containers/Application/Create/Steps/Networking';
import { STEP_ID as TIERS_ID } from 'client/containers/Application/Create/Steps/Tiers';
import parseTemplateToObject from './templateToObject';
const parseNetwork = input => {
const [name, values] = input;
const network = String(values).split('|');
// 0 mandatory; 1 network (user input type); 2 description; 3 empty; 4 info_network;
const mandatory = network[0] === 'M';
const description = network[2];
// 0 type; 1 id; 3 extra (optional)
const info = network[4].split(':');
const type = info[0];
const idVnet = info[1];
const extra = info[2] ?? '';
return {
id: uuidv4(),
name,
mandatory,
description,
type,
idVnet,
extra
};
};
const parseCluster = tiers => {
const NUM_REG = /(\d+)/g;
const clusters = tiers?.map(({ vm_template_contents: content = '' }) => {
const { sched_requirements: schedRequirements } = parseTemplateToObject(
content
);
return schedRequirements?.match(NUM_REG)?.join();
});
return clusters?.find(i => i !== undefined);
};
const parseTiers = (roles, networking) =>
roles
?.reduce((res, data) => {
const {
name,
cardinality,
parents,
shutdown_action: shutdownAction,
vm_template: vmTemplate,
vm_template_contents: content = '',
elasticity_policies: elasticityPolicies,
scheduled_policies: scheduledPolicies,
position = { x: 0, y: 0 }
} = data;
const hash = parseTemplateToObject(content);
const nics = hash.nic;
const networks =
nics?.map(({ network_id: networkId }) => {
const nicName = networkId?.replace('$', '');
const network = networking?.find(vnet => vnet.name === nicName);
return network.id;
}) ?? [];
return [
...res,
{
id: uuidv4(),
template: { template: String(vmTemplate) },
networks,
parents,
policies: { elasticityPolicies, scheduledPolicies },
position,
tier: { name, cardinality, shutdown_action: shutdownAction }
}
];
}, [])
.reduce((res, tier, _, src) => {
const parents = tier.parents?.map(name => {
const parent = src.find(item => item.tier.name === name);
return parent?.id;
});
return [...res, { ...tier, parents }];
}, []);
const mapApplicationToForm = data => {
const {
NAME,
TEMPLATE: {
BODY: { networks, roles, ...application }
}
} = data;
const networking = Object.entries(networks)?.map(parseNetwork) ?? [];
const tiers = parseTiers(roles, networking) ?? [];
const cluster = [...(parseCluster(roles) ?? '')];
return {
[APPLICATION_ID]: {
...application,
name: NAME
},
[NETWORKING_ID]: networking,
[CLUSTER_ID]: cluster,
[TIERS_ID]: tiers
};
};
export default mapApplicationToForm;
@@ -0,0 +1,69 @@
import { STEP_ID as APPLICATION_ID } from 'client/containers/Application/Create/Steps/BasicConfiguration';
import { STEP_ID as CLUSTER_ID } from 'client/containers/Application/Create/Steps/Clusters';
import { STEP_ID as NETWORKING_ID } from 'client/containers/Application/Create/Steps/Networking';
import { STEP_ID as TIERS_ID } from 'client/containers/Application/Create/Steps/Tiers';
const mapNetworkToUserInput = network => {
const { mandatory, description, type, idVnet, extra } = network;
const mandatoryValue = mandatory ? 'M' : 'O';
const descriptionValue = description ?? '';
const idVnetValue = idVnet ?? '';
const extraValue = `:${extra}` ?? '';
return `${mandatoryValue}|network|${descriptionValue}| |${type}:${idVnetValue}${extraValue}`;
};
const mapTiersToRoles = (tiers, networking, cluster) =>
tiers?.map(data => {
const { template, networks, parents, policies, position, tier } = data;
const networksValue = networks
?.reduce((res, id, idx) => {
const network = networking.find(net => net.id === id);
const networkString = `NIC = [\n NAME = "NIC${idx}",\n NETWORK_ID = "$${network.name}" ]\n`;
return [...res, networkString];
}, [])
?.join('')
?.concat(`SCHED_REQUIREMENTS = "ClUSTER_ID="${cluster}""`);
const parentsValue = parents?.reduce((res, id) => {
const parent = tiers.find(t => t.id === id);
return [...res, parent?.tier?.name];
}, []);
return {
...tier,
parents: parentsValue,
vm_template: template ? parseInt(template?.template, 10) : undefined,
vm_template_contents: networksValue,
elasticity_policies: [],
scheduled_policies: [],
position
};
});
const mapFormToApplication = data => {
const {
[APPLICATION_ID]: application,
[NETWORKING_ID]: networking,
[CLUSTER_ID]: cluster,
[TIERS_ID]: tiers
} = data;
return {
...application,
networks:
networking?.reduce(
(res, { name, ...network }) => ({
...res,
[name]: mapNetworkToUserInput(network)
}),
{}
) ?? {},
roles: mapTiersToRoles(tiers, networking, cluster)
};
};
export default mapFormToApplication;
@@ -0,0 +1,2 @@
export const isInteger = value =>
typeof value === 'number' && isFinite(value) && Math.floor(value) === value;