From e672fb856b737672947b87a514ff10626aaaba9f Mon Sep 17 00:00:00 2001 From: Sergio Betanzos Date: Fri, 2 Oct 2020 13:43:24 +0200 Subject: [PATCH] F #3951: Wizard create & update application (#281) --- src/fireedge/package.json | 1 - src/fireedge/src/public/actions/pool.js | 10 +- .../Cards/ApplicationTemplateCard.js | 137 ++++++++++++++++++ .../src/public/components/Cards/index.js | 10 +- .../components/FormControl/TextController.js | 5 +- .../public/components/FormStepper/index.js | 8 +- .../public/components/Forms/FormWithSchema.js | 50 ++++--- .../src/public/components/HOC/MainLayout.js | 3 +- .../src/public/components/HOC/Translate.js | 2 +- .../src/public/components/Sidebar/index.js | 34 +++-- .../Create/Steps/BasicConfiguration/schema.js | 20 +-- .../Create/Steps/Networking/schema.js | 19 ++- .../Tiers/Steps/BasicConfiguration/schema.js | 16 ++ .../Steps/Tiers/Steps/Policies/schema.js | 4 +- .../Steps/Tiers/Steps/Template/schema.js | 2 +- .../Application/Create/Steps/Tiers/index.js | 27 +--- .../containers/Application/Create/index.js | 66 +++++++-- .../Application/Deploy/Applications/index.js | 27 ++++ .../Application/Deploy/Templates/index.js | 56 +++++++ .../{Deploy.js => Deploy/index.js} | 81 +++++++---- .../containers/Infrastructure/Clusters.js | 70 --------- .../public/containers/Infrastructure/Hosts.js | 71 --------- .../public/containers/Infrastructure/Zones.js | 71 --------- .../containers/Infrastructure/host-columns.js | 86 ----------- .../public/containers/Infrastructure/index.js | 20 --- .../src/public/containers/Settings/index.js | 4 +- .../src/public/hooks/useApplication.js | 102 +++++++++++++ src/fireedge/src/public/hooks/useFetch.js | 35 +++++ src/fireedge/src/public/hooks/useListForm.js | 8 +- .../src/public/hooks/useOpennebula.js | 2 +- src/fireedge/src/public/reducers/general.js | 7 +- .../src/public/reducers/opennebula.js | 3 +- src/fireedge/src/public/router/endpoints.js | 31 +++- src/fireedge/src/public/router/index.js | 4 +- .../src/public/services/application.js | 74 ++++++++++ src/fireedge/src/public/utils/flow.js | 47 ------ .../public/utils/parser/templateToObject.js | 41 ++++++ .../public/utils/parser/toApplicationForm.js | 118 +++++++++++++++ .../utils/parser/toApplicationTemplate.js | 69 +++++++++ src/fireedge/src/public/utils/polyfills.js | 2 + 40 files changed, 925 insertions(+), 518 deletions(-) create mode 100644 src/fireedge/src/public/components/Cards/ApplicationTemplateCard.js create mode 100644 src/fireedge/src/public/containers/Application/Deploy/Applications/index.js create mode 100644 src/fireedge/src/public/containers/Application/Deploy/Templates/index.js rename src/fireedge/src/public/containers/Application/{Deploy.js => Deploy/index.js} (50%) delete mode 100644 src/fireedge/src/public/containers/Infrastructure/Clusters.js delete mode 100644 src/fireedge/src/public/containers/Infrastructure/Hosts.js delete mode 100644 src/fireedge/src/public/containers/Infrastructure/Zones.js delete mode 100644 src/fireedge/src/public/containers/Infrastructure/host-columns.js delete mode 100644 src/fireedge/src/public/containers/Infrastructure/index.js create mode 100644 src/fireedge/src/public/hooks/useApplication.js create mode 100644 src/fireedge/src/public/hooks/useFetch.js create mode 100644 src/fireedge/src/public/services/application.js delete mode 100644 src/fireedge/src/public/utils/flow.js create mode 100644 src/fireedge/src/public/utils/parser/templateToObject.js create mode 100644 src/fireedge/src/public/utils/parser/toApplicationForm.js create mode 100644 src/fireedge/src/public/utils/parser/toApplicationTemplate.js create mode 100644 src/fireedge/src/public/utils/polyfills.js diff --git a/src/fireedge/package.json b/src/fireedge/package.json index 1033da0479..b739fc5280 100644 --- a/src/fireedge/package.json +++ b/src/fireedge/package.json @@ -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", diff --git a/src/fireedge/src/public/actions/pool.js b/src/fireedge/src/public/actions/pool.js index ae3c7b23e8..12e46fbc8a 100644 --- a/src/fireedge/src/public/actions/pool.js +++ b/src/fireedge/src/public/actions/pool.js @@ -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 } }), diff --git a/src/fireedge/src/public/components/Cards/ApplicationTemplateCard.js b/src/fireedge/src/public/components/Cards/ApplicationTemplateCard.js new file mode 100644 index 0000000000..1d2ec4be84 --- /dev/null +++ b/src/fireedge/src/public/components/Cards/ApplicationTemplateCard.js @@ -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 ( + + + } + 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 + }} + /> + + + + + + + + + + + + {handleEdit && ( + + )} + {handleDeploy && ( + + )} + {handleRemove && ( + + )} + + + + ); + } +); + +export default ApplicationTemplateCard; diff --git a/src/fireedge/src/public/components/Cards/index.js b/src/fireedge/src/public/components/Cards/index.js index b6caee1ede..0f0f0322a2 100644 --- a/src/fireedge/src/public/components/Cards/index.js +++ b/src/fireedge/src/public/components/Cards/index.js @@ -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 +}; diff --git a/src/fireedge/src/public/components/FormControl/TextController.js b/src/fireedge/src/public/components/FormControl/TextController.js index 3721c31e50..e1a1a3ca79 100644 --- a/src/fireedge/src/public/components/FormControl/TextController.js +++ b/src/fireedge/src/public/components/FormControl/TextController.js @@ -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 }) => ( { +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() }; diff --git a/src/fireedge/src/public/components/Forms/FormWithSchema.js b/src/fireedge/src/public/components/Forms/FormWithSchema.js index 98f462f4c7..d73eca17ab 100644 --- a/src/fireedge/src/public/components/Forms/FormWithSchema.js +++ b/src/fireedge/src/public/components/Forms/FormWithSchema.js @@ -22,30 +22,34 @@ const FormWithSchema = ({ id, cy, fields }) => { return ( - {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 ( - - {InputController[type] && - React.createElement(InputController[type], { - control, - cy: dataCy, - name: inputName, - label, - tooltip, - values: dependOf ? values(dependValue) : values, - error: inputError - })} - - ); - })} + return ( + InputController[type] && ( + + {React.createElement(InputController[type], { + control, + cy: dataCy, + type: htmlType, + name: inputName, + label, + tooltip, + values: dependOf ? values(dependValue) : values, + error: inputError + })} + + ) + ); + } + )} ); }; diff --git a/src/fireedge/src/public/components/HOC/MainLayout.js b/src/fireedge/src/public/components/HOC/MainLayout.js index 80965952fd..fdcb7344cd 100644 --- a/src/fireedge/src/public/components/HOC/MainLayout.js +++ b/src/fireedge/src/public/components/HOC/MainLayout.js @@ -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)) { diff --git a/src/fireedge/src/public/components/HOC/Translate.js b/src/fireedge/src/public/components/HOC/Translate.js index b3bdb8773e..eefa954115 100644 --- a/src/fireedge/src/public/components/HOC/Translate.js +++ b/src/fireedge/src/public/components/HOC/Translate.js @@ -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(); diff --git a/src/fireedge/src/public/components/Sidebar/index.js b/src/fireedge/src/public/components/Sidebar/index.js index fc2a72336f..bedea77c87 100644 --- a/src/fireedge/src/public/components/Sidebar/index.js +++ b/src/fireedge/src/public/components/Sidebar/index.js @@ -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 ? ( - - ) : ( - - ) - ) -); - 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 ? ( + + ) : ( + + ) + ), + [endpoints] + ); + + return useMemo( () => ( { - + {SidebarEndpoints} diff --git a/src/fireedge/src/public/containers/Application/Create/Steps/BasicConfiguration/schema.js b/src/fireedge/src/public/containers/Application/Create/Steps/BasicConfiguration/schema.js index 06f6821c8c..32cfbcf403 100644 --- a/src/fireedge/src/public/containers/Application/Create/Steps/BasicConfiguration/schema.js +++ b/src/fireedge/src/public/containers/Application/Create/Steps/BasicConfiguration/schema.js @@ -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', diff --git a/src/fireedge/src/public/containers/Application/Create/Steps/Networking/schema.js b/src/fireedge/src/public/containers/Application/Create/Steps/Networking/schema.js index 76abf9c90d..a38dce241b 100644 --- a/src/fireedge/src/public/containers/Application/Create/Steps/Networking/schema.js +++ b/src/fireedge/src/public/containers/Application/Create/Steps/Networking/schema.js @@ -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) }; diff --git a/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/Steps/BasicConfiguration/schema.js b/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/Steps/BasicConfiguration/schema.js index 49ed289977..4e0389089b 100644 --- a/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/Steps/BasicConfiguration/schema.js +++ b/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/Steps/BasicConfiguration/schema.js @@ -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) } ]; diff --git a/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/Steps/Policies/schema.js b/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/Steps/Policies/schema.js index 153de56d0c..2e7171ed0f 100644 --- a/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/Steps/Policies/schema.js +++ b/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/Steps/Policies/schema.js @@ -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 diff --git a/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/Steps/Template/schema.js b/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/Steps/Template/schema.js index 0267802009..2a8f7e0503 100644 --- a/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/Steps/Template/schema.js +++ b/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/Steps/Template/schema.js @@ -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); diff --git a/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/index.js b/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/index.js index 84b88bfbf1..62ed54b214 100644 --- a/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/index.js +++ b/src/fireedge/src/public/containers/Application/Create/Steps/Tiers/index.js @@ -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 = () => { { handleSave(values); setShowDialog(false); diff --git a/src/fireedge/src/public/containers/Application/Create/index.js b/src/fireedge/src/public/containers/Application/Create/index.js index 63f1a90e60..9610d10d8b 100644 --- a/src/fireedge/src/public/containers/Application/Create/index.js +++ b/src/fireedge/src/public/containers/Application/Create/index.js @@ -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 ( - - - + {error &&
error!
} + {!error && loading ? ( +
is loading...
+ ) : ( + + + + )}
); } diff --git a/src/fireedge/src/public/containers/Application/Deploy/Applications/index.js b/src/fireedge/src/public/containers/Application/Deploy/Applications/index.js new file mode 100644 index 0000000000..5d4478ee68 --- /dev/null +++ b/src/fireedge/src/public/containers/Application/Deploy/Applications/index.js @@ -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 ( + { + console.log(value); + }} + /> + ); +}; + +export default ApplicationsList; diff --git a/src/fireedge/src/public/containers/Application/Deploy/Templates/index.js b/src/fireedge/src/public/containers/Application/Deploy/Templates/index.js new file mode 100644 index 0000000000..36015dbe75 --- /dev/null +++ b/src/fireedge/src/public/containers/Application/Deploy/Templates/index.js @@ -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 ( + + + {Tr('Cannot connect to OneFlow server')} + + + ); + } + + if (loading) { + return
loading
; + } + + return ( + + history.push(PATH.APPLICATION.CREATE)} + CardComponent={ApplicationTemplateCard} + cardsProps={({ value: { ID } }) => ({ + handleEdit: () => + history.push(PATH.APPLICATION.EDIT.replace(':id', ID)), + handleDeploy: undefined, + handleRemove: undefined + })} + /> + + ); +}; + +export default ApplicationsTemplatesList; diff --git a/src/fireedge/src/public/containers/Application/Deploy.js b/src/fireedge/src/public/containers/Application/Deploy/index.js similarity index 50% rename from src/fireedge/src/public/containers/Application/Deploy.js rename to src/fireedge/src/public/containers/Application/Deploy/index.js index 51c9d3bb96..8dbf1a9b0c 100644 --- a/src/fireedge/src/public/containers/Application/Deploy.js +++ b/src/fireedge/src/public/containers/Application/Deploy/index.js @@ -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 && } - Deploy - + + + + + + + + + + ); } diff --git a/src/fireedge/src/public/containers/Infrastructure/Clusters.js b/src/fireedge/src/public/containers/Infrastructure/Clusters.js deleted file mode 100644 index cda73f3d2e..0000000000 --- a/src/fireedge/src/public/containers/Infrastructure/Clusters.js +++ /dev/null @@ -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 ( -
- - - - } - 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: () => , - tooltip: 'Refresh Data', - isFreeAction: true, - onClick: () => tableRef?.current?.onQueryChange() - } - ]} - /> -
- ); -} - -Clusters.propTypes = { - name: PropTypes.string -}; - -Clusters.defaultProps = { - name: '' -}; - -export default Clusters; diff --git a/src/fireedge/src/public/containers/Infrastructure/Hosts.js b/src/fireedge/src/public/containers/Infrastructure/Hosts.js deleted file mode 100644 index be63f51b28..0000000000 --- a/src/fireedge/src/public/containers/Infrastructure/Hosts.js +++ /dev/null @@ -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 ( -
- - - - } - 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: () => , - tooltip: 'Refresh Data', - isFreeAction: true, - onClick: () => tableRef?.current?.onQueryChange() - } - ]} - /> -
- ); -} - -Hosts.propTypes = { - name: PropTypes.string -}; - -Hosts.defaultProps = { - name: '' -}; - -export default Hosts; diff --git a/src/fireedge/src/public/containers/Infrastructure/Zones.js b/src/fireedge/src/public/containers/Infrastructure/Zones.js deleted file mode 100644 index 85504da7c9..0000000000 --- a/src/fireedge/src/public/containers/Infrastructure/Zones.js +++ /dev/null @@ -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 ( -
- - - - } - 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: () => , - tooltip: 'Refresh Data', - isFreeAction: true, - onClick: () => tableRef?.current?.onQueryChange() - } - ]} - /> -
- ); -} - -Zones.propTypes = { - name: PropTypes.string -}; - -Zones.defaultProps = { - name: '' -}; - -export default Zones; diff --git a/src/fireedge/src/public/containers/Infrastructure/host-columns.js b/src/fireedge/src/public/containers/Infrastructure/host-columns.js deleted file mode 100644 index c6570a1060..0000000000 --- a/src/fireedge/src/public/containers/Infrastructure/host-columns.js +++ /dev/null @@ -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) => ( -
- {title} - -
-); - -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' } - ] -}; diff --git a/src/fireedge/src/public/containers/Infrastructure/index.js b/src/fireedge/src/public/containers/Infrastructure/index.js deleted file mode 100644 index 267818e7ff..0000000000 --- a/src/fireedge/src/public/containers/Infrastructure/index.js +++ /dev/null @@ -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 }; diff --git a/src/fireedge/src/public/containers/Settings/index.js b/src/fireedge/src/public/containers/Settings/index.js index 58aea430a6..e1448e8558 100644 --- a/src/fireedge/src/public/containers/Settings/index.js +++ b/src/fireedge/src/public/containers/Settings/index.js @@ -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 = () => ( diff --git a/src/fireedge/src/public/hooks/useApplication.js b/src/fireedge/src/public/hooks/useApplication.js new file mode 100644 index 0000000000..ac03f5b774 --- /dev/null +++ b/src/fireedge/src/public/hooks/useApplication.js @@ -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 + }; +} diff --git a/src/fireedge/src/public/hooks/useFetch.js b/src/fireedge/src/public/hooks/useFetch.js new file mode 100644 index 0000000000..efded66099 --- /dev/null +++ b/src/fireedge/src/public/hooks/useFetch.js @@ -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; diff --git a/src/fireedge/src/public/hooks/useListForm.js b/src/fireedge/src/public/hooks/useListForm.js index 98f03ea5a4..8e66f5759c 100644 --- a/src/fireedge/src/public/hooks/useListForm.js +++ b/src/fireedge/src/public/hooks/useListForm.js @@ -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; diff --git a/src/fireedge/src/public/hooks/useOpennebula.js b/src/fireedge/src/public/hooks/useOpennebula.js index b0b51df7b7..695b168963 100644 --- a/src/fireedge/src/public/hooks/useOpennebula.js +++ b/src/fireedge/src/public/hooks/useOpennebula.js @@ -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]); diff --git a/src/fireedge/src/public/reducers/general.js b/src/fireedge/src/public/reducers/general.js index d76f414521..cff73cc6b5 100644 --- a/src/fireedge/src/public/reducers/general.js +++ b/src/fireedge/src/public/reducers/general.js @@ -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: diff --git a/src/fireedge/src/public/reducers/opennebula.js b/src/fireedge/src/public/reducers/opennebula.js index 5b79471e92..f03109805a 100644 --- a/src/fireedge/src/public/reducers/opennebula.js +++ b/src/fireedge/src/public/reducers/opennebula.js @@ -19,7 +19,8 @@ const { Actions: UserActions } = require('../actions/user'); const initial = { vm: [], templates: [], - services: [], + applications: [], + applicationsTemplates: [], datastores: [], virtualRouters: [], vmGroups: [], diff --git a/src/fireedge/src/public/router/endpoints.js b/src/fireedge/src/public/router/endpoints.js index a9d4401808..b61c72ce68 100644 --- a/src/fireedge/src/public/router/endpoints.js +++ b/src/fireedge/src/public/router/endpoints.js @@ -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; diff --git a/src/fireedge/src/public/router/index.js b/src/fireedge/src/public/router/index.js index a17bb763bf..4d13f4d948 100644 --- a/src/fireedge/src/public/router/index.js +++ b/src/fireedge/src/public/router/index.js @@ -32,8 +32,8 @@ const renderRoute = ({ key={`key-${label.replace(' ', '-')}`} exact path={path} - component={props => ( - + component={() => ( + )} diff --git a/src/fireedge/src/public/services/application.js b/src/fireedge/src/public/services/application.js new file mode 100644 index 0000000000..2dbc656518 --- /dev/null +++ b/src/fireedge/src/public/services/application.js @@ -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 +}; diff --git a/src/fireedge/src/public/utils/flow.js b/src/fireedge/src/public/utils/flow.js deleted file mode 100644 index 8fc27a38e2..0000000000 --- a/src/fireedge/src/public/utils/flow.js +++ /dev/null @@ -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 }; diff --git a/src/fireedge/src/public/utils/parser/templateToObject.js b/src/fireedge/src/public/utils/parser/templateToObject.js new file mode 100644 index 0000000000..29e28469aa --- /dev/null +++ b/src/fireedge/src/public/utils/parser/templateToObject.js @@ -0,0 +1,41 @@ +const SINGLE_VARIABLE_REG = /^\s*(?[\w\d_-]+)\s*=\s*(?[^[\],]+?)(?:#.*)?$/gm; +const ARRAY_VARIABLE_REG = /\s*(?[\w\d_-]+)\s*=\s*\[(?.*?)\]/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; diff --git a/src/fireedge/src/public/utils/parser/toApplicationForm.js b/src/fireedge/src/public/utils/parser/toApplicationForm.js new file mode 100644 index 0000000000..9bbf666512 --- /dev/null +++ b/src/fireedge/src/public/utils/parser/toApplicationForm.js @@ -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; diff --git a/src/fireedge/src/public/utils/parser/toApplicationTemplate.js b/src/fireedge/src/public/utils/parser/toApplicationTemplate.js new file mode 100644 index 0000000000..dd073e17df --- /dev/null +++ b/src/fireedge/src/public/utils/parser/toApplicationTemplate.js @@ -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; diff --git a/src/fireedge/src/public/utils/polyfills.js b/src/fireedge/src/public/utils/polyfills.js new file mode 100644 index 0000000000..41bd39c87c --- /dev/null +++ b/src/fireedge/src/public/utils/polyfills.js @@ -0,0 +1,2 @@ +export const isInteger = value => + typeof value === 'number' && isFinite(value) && Math.floor(value) === value;