F #3951: Add policies in application form (#335)

* Add application card component
* Fix submit button component
* Fix list cards component
* Add policies in application form
* Fix linting
This commit is contained in:
Sergio Betanzos authored and GitHub committed 2020-10-20 17:15:42 +02:00
1 parent ded79ab856
commit 998c2a9cd2
36 files changed
+1013 -201

No files matched your search

+7 -7
View File
@@ -18,21 +18,21 @@ import PropTypes from 'prop-types'
import { StaticRouter, BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import root from 'window-or-global';
import { defaultWebpackMode } from 'server/utils/constants/defaults';
import root from 'window-or-global'
import MuiProvider from 'client/providers/muiProvider'
import NotistackProvider from 'client/providers/notistackProvider'
import { TranslateProvider } from 'client/components/HOC'
import Router from 'client/router'
if(process?.env?.NODE_ENV === 'development'){
const webpackHotMiddlewareClient = require("webpack-hot-middleware/client");
if (process?.env?.NODE_ENV === 'development') {
const webpackHotMiddlewareClient = require('webpack-hot-middleware/client')
webpackHotMiddlewareClient.subscribeAll(function (message) {
if(message?.action === 'built' && root?.location?.reload){
root.location.reload();
if (message?.action === 'built' && root?.location?.reload) {
root.location.reload()
}
});
})
}
const App = ({ location, context, store }) => (
@@ -0,0 +1,146 @@
import React, { memo } from 'react'
import PropTypes from 'prop-types'
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'
},
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 ApplicationCard = memo(
({ value, handleShow, handleRemove }) => {
const classes = useStyles()
const { NAME, TEMPLATE } = value
const { description, networks = [], roles = [] } = TEMPLATE.BODY
const numberOfTiers = roles?.length ?? 0
const numberOfNetworks = Object.keys(networks)?.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>
{handleShow && (
<Button variant="contained" size="small" onClick={handleShow}>
{Tr('Info')}
</Button>
)}
{handleRemove && (
<Button size="small" onClick={handleRemove}>
{Tr('Remove')}
</Button>
)}
</CardActions>
</Card>
</Fade>
)
}
)
ApplicationCard.propTypes = {
value: PropTypes.shape({
ID: PropTypes.string.isRequired,
NAME: PropTypes.string.isRequired,
TEMPLATE: PropTypes.shape({
BODY: PropTypes.shape({
description: PropTypes.string,
networks: PropTypes.object,
roles: PropTypes.arrayOf(PropTypes.object)
}).isRequired
}).isRequired
}),
handleShow: PropTypes.func,
handleRemove: PropTypes.func
}
ApplicationCard.defaultProps = {
value: {},
handleShow: undefined,
handleRemove: undefined
}
ApplicationCard.displayName = 'Application TemplateCard'
export default ApplicationCard
@@ -103,22 +103,22 @@ const ApplicationTemplateCard = memo(
</CardContent>
<CardActions>
{handleEdit && (
<Button variant="contained" size="small" onClick={handleEdit}>
<Button variant="contained" size="small" onClick={handleEdit} disableElevation>
{Tr('Edit')}
</Button>
)}
{handleDeploy && (
<Button variant="contained" size="small" onClick={handleDeploy}>
<Button variant="contained" size="small" onClick={handleDeploy} disableElevation>
{Tr('Deploy')}
</Button>
)}
{handleShow && (
<Button variant="contained" size="small" onClick={handleShow}>
<Button variant="contained" size="small" onClick={handleShow} disableElevation>
{Tr('Info')}
</Button>
)}
{handleRemove && (
<Button size="small" onClick={handleRemove}>
<Button size="small" onClick={handleRemove} disableElevation>
{Tr('Remove')}
</Button>
)}
@@ -131,7 +131,7 @@ const ApplicationTemplateCard = memo(
ApplicationTemplateCard.propTypes = {
value: PropTypes.shape({
ID: PropTypes.string,
ID: PropTypes.string.isRequired,
NAME: PropTypes.string.isRequired,
TEMPLATE: PropTypes.shape({
BODY: PropTypes.shape({
@@ -64,17 +64,17 @@ const NetworkCard = React.memo(
/>
<CardActions>
{handleEdit && (
<Button variant="contained" size="small" onClick={handleEdit}>
<Button variant="contained" size="small" onClick={handleEdit} disableElevation>
{Tr('Edit')}
</Button>
)}
{handleClone && (
<Button variant="contained" size="small" onClick={handleClone}>
<Button variant="contained" size="small" onClick={handleClone} disableElevation>
{Tr('Clone')}
</Button>
)}
{handleRemove && (
<Button size="small" onClick={handleRemove}>
<Button size="small" onClick={handleRemove} disableElevation>
{Tr('Remove')}
</Button>
)}
@@ -0,0 +1,64 @@
import React, { memo } from 'react'
import PropTypes from 'prop-types'
import { makeStyles, Card, CardContent, Button, CardActions } from '@material-ui/core'
import FormWithSchema from 'client/components/Forms/FormWithSchema'
import { Tr } from 'client/components/HOC'
const useStyles = makeStyles(() => ({
root: {
height: '100%',
minHeight: 140,
display: 'flex',
flexDirection: 'column'
},
content: {
minHeight: 260
}
}))
const PolicyCard = memo(
({ id, cy, fields, handleRemove, cardProps }) => {
const classes = useStyles()
return (
<Card variant="outlined" className={classes.root} {...cardProps}>
<CardContent className={classes.content}>
<FormWithSchema id={id} cy={cy} fields={fields} />
</CardContent>
<CardActions>
{handleRemove && (
<Button variant="contained" size="small" onClick={handleRemove} disableElevation>
{Tr('Remove')}
</Button>
)}
</CardActions>
</Card>
)
}
)
PolicyCard.propTypes = {
id: PropTypes.string,
cy: PropTypes.string,
fields: PropTypes.arrayOf(PropTypes.object),
handleEdit: PropTypes.func,
handleClone: PropTypes.func,
handleRemove: PropTypes.func,
cardProps: PropTypes.object
}
PolicyCard.defaultProps = {
id: undefined,
cy: undefined,
fields: undefined,
handleEdit: undefined,
handleClone: undefined,
handleRemove: undefined,
cardProps: undefined
}
PolicyCard.displayName = 'PolicyCard'
export default PolicyCard
@@ -67,17 +67,17 @@ const TierCard = memo(
/>
<CardActions>
{handleEdit && (
<Button variant="contained" size="small" onClick={handleEdit}>
<Button variant="contained" size="small" onClick={handleEdit} disableElevation>
{Tr('Edit')}
</Button>
)}
{handleClone && (
<Button variant="contained" size="small" onClick={handleClone}>
<Button variant="contained" size="small" onClick={handleClone} disableElevation>
{Tr('Clone')}
</Button>
)}
{handleRemove && (
<Button size="small" onClick={handleRemove}>
<Button size="small" onClick={handleRemove} disableElevation>
{Tr('Remove')}
</Button>
)}
@@ -4,6 +4,8 @@ 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'
import ApplicationCard from 'client/components/Cards/ApplicationCard'
import PolicyCard from 'client/components/Cards/PolicyCard'
export {
ClusterCard,
@@ -11,5 +13,7 @@ export {
TierCard,
EmptyCard,
SelectCard,
ApplicationTemplateCard
ApplicationTemplateCard,
ApplicationCard,
PolicyCard
}
@@ -12,13 +12,23 @@ import {
import { useForm, FormProvider } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers'
import ButtonSubmit from 'client/components/FormControl/SubmitButton'
import { Tr } from 'client/components/HOC'
const DialogForm = memo(
({ open, title, values, resolver, onSubmit, onCancel, children }) => {
({
open,
title,
values,
resolver,
onSubmit,
onCancel,
submitButtonProps,
children
}) => {
const isMobile = useMediaQuery(theme => theme.breakpoints.only('xs'))
const { handleSubmit, ...methods } = useForm({
const { handleSubmit, formState, ...methods } = useForm({
mode: 'onChange',
reValidateMode: 'onSubmit',
defaultValues: values,
@@ -34,12 +44,11 @@ const DialogForm = memo(
PaperProps={{
style: {
height: isMobile ? '100%' : '80%',
minHeight: '80%',
minWidth: '80%'
width: isMobile ? '100%' : '80%'
}
}}
>
<DialogTitle>{title}</DialogTitle>
<DialogTitle>{Tr(title)}</DialogTitle>
<DialogContent dividers>
<FormProvider {...methods}>{children}</FormProvider>
</DialogContent>
@@ -51,14 +60,13 @@ const DialogForm = memo(
</Button>
)}
{onSubmit && (
<Button
type="submit"
variant="contained"
color="primary"
<ButtonSubmit
data-cy="dg-form-submit-button"
isSubmitting={formState.isSubmitting}
onClick={handleSubmit(onSubmit)}
>
{Tr('Save')}
</Button>
label={Tr('Save')}
{...submitButtonProps}
/>
)}
</DialogActions>
)}
@@ -77,6 +85,7 @@ DialogForm.propTypes = {
resolver: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired,
onSubmit: PropTypes.func,
onCancel: PropTypes.func,
submitButtonProps: PropTypes.objectOf(PropTypes.any),
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
@@ -90,6 +99,7 @@ DialogForm.defaultProps = {
resolver: {},
onSubmit: undefined,
onCancel: undefined,
submitButtonProps: undefined,
children: null
}
@@ -1,4 +1,4 @@
import React from 'react'
import React, { memo } from 'react'
import { string } from 'prop-types'
import { Box, makeStyles, Typography } from '@material-ui/core'
@@ -21,7 +21,7 @@ const useStyles = makeStyles(theme => ({
}
}))
const ErrorHelper = ({ label, ...rest }) => {
const ErrorHelper = memo(({ label, ...rest }) => {
const classes = useStyles()
return (
@@ -36,7 +36,7 @@ const ErrorHelper = ({ label, ...rest }) => {
</Typography>
</Box>
)
}
})
ErrorHelper.propTypes = {
label: string
@@ -46,4 +46,6 @@ ErrorHelper.defaultProps = {
label: 'Error'
}
ErrorHelper.displayName = 'ErrorHelper'
export default ErrorHelper
@@ -6,10 +6,9 @@ import { makeStyles, CircularProgress, Button } from '@material-ui/core'
import { Submit } from 'client/constants/translates'
import { Tr } from 'client/components/HOC'
const useStyles = makeStyles(theme => ({
const useStyles = makeStyles(() => ({
button: {
transition: 'disabled 0.5s ease',
margin: theme.spacing(3, 0, 2)
transition: 'disabled 0.5s ease'
}
}))
@@ -10,22 +10,25 @@ import ErrorHelper from 'client/components/FormControl/ErrorHelper'
const TextController = memo(
({ control, cy, type, name, label, error }) => (
<Controller
as={
render={({ value, ...props }) =>
<TextField
fullWidth
value={value ?? ''}
type={type}
label={Tr(label)}
{...(label && { label: Tr(label) })}
inputProps={{ 'data-cy': cy }}
error={Boolean(error)}
helperText={Boolean(error) && <ErrorHelper label={error?.message} />}
FormHelperTextProps={{ 'data-cy': `${cy}-error` }}
{...props}
/>
}
name={name}
control={control}
/>
),
(prevProps, nextProps) => prevProps.error === nextProps.error
(prevProps, nextProps) =>
prevProps.error === nextProps.error && prevProps.type === nextProps.type
)
TextController.propTypes = {
@@ -1,7 +1,7 @@
import React from 'react'
import PropTypes from 'prop-types'
import { Grid } from '@material-ui/core'
import { Box, Grid } from '@material-ui/core'
import { useFormContext, useWatch } from 'react-hook-form'
import { TYPE_INPUT } from 'client/constants'
@@ -9,6 +9,7 @@ import TextController from 'client/components/FormControl/TextController'
import SelectController from 'client/components/FormControl/SelectController'
import CheckboxController from 'client/components/FormControl/CheckboxController'
import AutocompleteController from 'client/components/FormControl/AutocompleteController'
import { get } from 'client/utils/helpers'
const InputController = {
[TYPE_INPUT.TEXT]: TextController,
@@ -16,6 +17,8 @@ const InputController = {
[TYPE_INPUT.CHECKBOX]: CheckboxController,
[TYPE_INPUT.AUTOCOMPLETE]: AutocompleteController
}
const HiddenInput = ({ isHidden, children }) =>
isHidden ? <Box display="none">{children}</Box> : children
const FormWithSchema = ({ id, cy, fields }) => {
const { control, errors } = useFormContext()
@@ -26,26 +29,37 @@ const FormWithSchema = ({ id, cy, fields }) => {
({ 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 inputError = get(errors, inputName) ?? false
const dependValue = dependOf
? useWatch({ control, name: id ? `${id}.${dependOf}` : dependOf })
: null
const htmlTypeValue = typeof htmlType === 'function' && dependOf
? htmlType(dependValue)
: htmlType
const isHidden = htmlTypeValue === TYPE_INPUT.HIDDEN
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>
<HiddenInput key={`${cy}-${name}`} isHidden={isHidden}>
<Grid item xs={12} md={6} {...grid}>
{React.createElement(InputController[type], {
control,
cy: dataCy,
type: htmlTypeValue,
name: inputName,
label,
tooltip,
values: typeof values === 'function' && dependOf
? values(dependValue)
: values,
error: inputError
})}
</Grid>
</HiddenInput>
)
)
}
@@ -54,6 +68,11 @@ const FormWithSchema = ({ id, cy, fields }) => {
)
}
HiddenInput.propTypes = {
isHidden: PropTypes.bool,
children: PropTypes.object
}
FormWithSchema.propTypes = {
id: PropTypes.string,
cy: PropTypes.string,
@@ -1,4 +1,4 @@
import React, { useMemo } from 'react'
import React, { memo, useMemo } from 'react'
import PropTypes from 'prop-types'
import {
@@ -10,6 +10,8 @@ import {
} from '@material-ui/core'
import AddIcon from '@material-ui/icons/Add'
const gridValues = [false, 'auto', true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
const useStyles = makeStyles(() => ({
cardPlus: {
height: '100%',
@@ -19,7 +21,14 @@ const useStyles = makeStyles(() => ({
}
}))
function ListCards ({ handleCreate, list, CardComponent, cardsProps }) {
const ListCards = memo(({
list,
breakpoints,
handleCreate,
ButtonCreateComponent,
CardComponent,
cardsProps
}) => {
const classes = useStyles()
return (
@@ -27,32 +36,50 @@ function ListCards ({ handleCreate, list, CardComponent, cardsProps }) {
{handleCreate &&
useMemo(
() => (
<Grid item xs={12} sm={4} md={3} lg={2}>
<Card className={classes.cardPlus} raised>
<CardActionArea onClick={handleCreate}>
<CardContent>
<AddIcon />
</CardContent>
</CardActionArea>
</Card>
<Grid item {...breakpoints}>
{ButtonCreateComponent ? (
<ButtonCreateComponent onClick={handleCreate} />
) : (
<Card className={classes.cardPlus} raised>
<CardActionArea onClick={handleCreate}>
<CardContent>
<AddIcon />
</CardContent>
</CardActionArea>
</Card>
)}
</Grid>
),
[handleCreate, classes]
)}
{Array.isArray(list) &&
list?.map((value, index) => (
<Grid key={`card-${index}`} item xs={12} sm={4} md={3} lg={2}>
<Grid key={`card-${index}`} item {...breakpoints}>
<CardComponent value={value} {...cardsProps({ index, value })} />
</Grid>
))}
</Grid>
)
}
})
ListCards.propTypes = {
list: PropTypes.arrayOf(PropTypes.any).isRequired,
breakpoints: PropTypes.shape({
xs: PropTypes.oneOf(gridValues),
sm: PropTypes.oneOf(gridValues),
md: PropTypes.oneOf(gridValues),
lg: PropTypes.oneOf(gridValues),
xl: PropTypes.oneOf(gridValues)
}),
handleCreate: PropTypes.func,
ButtonCreateComponent: PropTypes.oneOfType([
PropTypes.func,
PropTypes.node,
PropTypes.object,
PropTypes.element
]),
CardComponent: PropTypes.oneOfType([
PropTypes.func,
PropTypes.node,
PropTypes.object,
PropTypes.element
@@ -62,9 +89,13 @@ ListCards.propTypes = {
ListCards.defaultProps = {
list: [],
breakpoints: { xs: 12, sm: 4, md: 3, lg: 2 },
handleCreate: undefined,
ButtonCreateComponent: undefined,
CardComponent: null,
cardsProps: () => undefined
}
ListCards.displayName = 'ListCards'
export default ListCards
@@ -32,8 +32,10 @@ module.exports = {
},
TYPE_INPUT: {
TEXT: 'text',
HIDDEN: 'hidden',
SELECT: 'select',
CHECKBOX: 'checkbox',
SLIDER: 'slider',
AUTOCOMPLETE: 'autocomplete'
}
}
@@ -1,25 +1,47 @@
import React, { useEffect } from 'react'
import { Box, LinearProgress } 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 { ClusterCard } from 'client/components/Cards'
import { ApplicationCard } from 'client/components/Cards'
import { Tr } from 'client/components/HOC'
const ApplicationsDeployed = () => {
const { applications, getApplications } = useApplication()
const { fetchRequest, loading, error } = useFetch(getApplications)
useEffect(() => {
getApplications()
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 <LinearProgress />
}
return (
<ListCards
list={applications}
CardComponent={ClusterCard}
cardsProps={({ value }) => {
console.log(value)
}}
/>
<Box p={3}>
<ListCards
list={applications}
CardComponent={ApplicationCard}
cardsProps={({ value: { ID, ...rest } }) => {
console.log(ID, rest)
}}
/>
</Box>
)
}
@@ -12,9 +12,17 @@ const SELECT = {
const TYPES_NETWORKS = [
{ text: 'Create', value: 'template_id', select: SELECT.template },
{ text: 'Reserve', value: 'reserve_from', select: SELECT.network },
{ text: 'Existing', value: 'id', select: SELECT.network }
{ text: 'Existing', value: 'id', select: SELECT.network, extra: false }
]
const needExtraValue = type => TYPES_NETWORKS.some(
({ value, extra }) => value === type && extra === false
)
const isNetworkSelector = type => TYPES_NETWORKS.some(
({ value, select }) => value === type && select === SELECT.network
)
const ID = {
name: 'id',
label: 'ID',
@@ -24,8 +32,7 @@ const ID = {
.string()
.uuid()
.required()
.default(uuidv4),
grid: { style: { display: 'none' } }
.default(uuidv4)
}
const MANDATORY = {
@@ -81,10 +88,8 @@ const ID_VNET = {
dependOf: TYPE.name,
values: dependValue => {
const { vNetworks, vNetworksTemplates } = useOpennebula()
const type = TYPES_NETWORKS.find(({ value }) => value === dependValue)
const values =
type?.select === SELECT.network ? vNetworks : vNetworksTemplates
const values = isNetworkSelector(dependValue) ? vNetworks : vNetworksTemplates
return values
.map(({ ID: value, NAME: text }) => ({ text, value }))
@@ -94,9 +99,7 @@ const ID_VNET = {
.string()
.trim()
.when(TYPE.name, (type, schema) =>
TYPES_NETWORKS.some(
({ value, select }) => type === value && select === SELECT.network
)
isNetworkSelector(type)
? schema.required('Network field is required')
: schema.required('Network template field is required')
)
@@ -108,9 +111,12 @@ const EXTRA = {
label: 'Extra',
multiline: true,
type: TYPE_INPUT.TEXT,
dependOf: TYPE.name,
htmlType: dependValue => needExtraValue(dependValue) ? TYPE_INPUT.HIDDEN : TYPE_INPUT.TEXT,
validation: yup
.string()
.trim()
.when(TYPE.name, (type, schema) => needExtraValue(type) ? schema.strip() : schema)
.default('')
}
@@ -8,39 +8,46 @@ const SHUTDOWN_ACTIONS = [
{ text: 'Shutdown hard', value: 'shutdown-hard' }
]
const NAME = {
name: 'name',
label: 'Name',
type: TYPE_INPUT.TEXT,
validation: yup
.string()
.trim()
.matches(/^[\w+\s*]+$/g, { message: 'Invalid characters' })
.required('Name field is required')
.default('')
}
const CARDINALITY = {
name: 'cardinality',
label: 'Cardinality',
type: TYPE_INPUT.TEXT,
htmlType: 'number',
validation: yup
.number()
.min(1, 'Cardinality field is required')
.required('Cardinality field is required')
.default(1)
}
const SHUTDOWN_ACTION = {
name: 'shutdown_action',
label: 'Select a VM shutdown action',
type: TYPE_INPUT.SELECT,
values: SHUTDOWN_ACTIONS,
validation: yup
.string()
.notRequired()
.oneOf(SHUTDOWN_ACTIONS.map(({ value }) => value))
.default(SHUTDOWN_ACTIONS[0].value)
}
export const FORM_FIELDS = [
{
name: 'name',
label: 'Name',
type: TYPE_INPUT.TEXT,
validation: yup
.string()
.trim()
.matches(/^[\w+\s*]+$/g, { message: 'Invalid characters' })
.required('Name field is required')
.default('')
},
{
name: 'cardinality',
label: 'Cardinality',
type: TYPE_INPUT.TEXT,
htmlType: 'number',
validation: yup
.number()
.min(1, 'Cardinality field is required')
.required('Cardinality field is 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[0].value)
}
NAME,
CARDINALITY,
SHUTDOWN_ACTION
]
export const STEP_FORM_SCHEMA = yup.object(
@@ -32,7 +32,7 @@ const Networks = () => ({
return {
title: name,
isSelected,
handleClick: () => isSelected ? handleSelect(id) : handleUnselect(id)
handleClick: () => isSelected ? handleUnselect(id) : handleSelect(id)
}
}}
/>
@@ -1,19 +1,130 @@
import React, { useCallback } from 'react'
import React, { useCallback, useEffect, useState } from 'react'
import { useFormContext } from 'react-hook-form'
import { Box, Tab, Tabs, Fab, AppBar } from '@material-ui/core'
import AddIcon from '@material-ui/icons/Add'
import FormWithSchema from 'client/components/Forms/FormWithSchema'
import { PolicyCard } from 'client/components/Cards'
import ListCards from 'client/components/List/ListCards'
import useListForm from 'client/hooks/useListForm'
import { set } from 'client/utils/helpers'
import { FORM_FIELDS, STEP_FORM_SCHEMA } from './schema'
import {
TAB_ID as ELASTICITY_ID,
ELASTICITY_FORM_SCHEMA,
ELASTICITY_FORM_FIELDS
} from './schemas/elasticity'
import {
TAB_ID as SCHEDULED_ID,
SCHEDULED_FORM_FIELDS,
SCHEDULED_FORM_SCHEMA
} from './schemas/scheduled'
import { POLICIES_FORM_FIELDS, POLICIES_SCHEMA } from './schemas'
export const STEP_ID = 'policies'
const TABS = {
elasticity: {
name: ELASTICITY_ID,
fields: ELASTICITY_FORM_FIELDS,
schema: ELASTICITY_FORM_SCHEMA
},
scheduled: {
name: SCHEDULED_ID,
fields: SCHEDULED_FORM_FIELDS,
schema: SCHEDULED_FORM_SCHEMA
}
}
const Policies = () => ({
id: STEP_ID,
label: 'Policies',
resolver: STEP_FORM_SCHEMA,
resolver: POLICIES_SCHEMA,
content: useCallback(
() => (
<FormWithSchema cy="form-policies" fields={FORM_FIELDS} id={STEP_ID} />
),
({ setFormData }) => {
const [tab, setTab] = useState(TABS.elasticity.name)
const { handleSetList } = useListForm({
key: STEP_ID,
setList: setFormData
})
const { watch } = useFormContext()
const policies = watch('policies')
useEffect(() => () => {
handleSetList(policies)
}, [])
const handleRemove = id => {
const newDataTab = policies?.[tab]?.filter(item => item.id !== id)
const newPolicies = set(policies, tab, newDataTab)
handleSetList(newPolicies)
}
const handleCreate = () => {
const defaultValues = TABS[tab]?.schema.default()
const newDataTab = [...policies?.[tab] ?? []].concat(defaultValues)
const newPolicies = set(policies, tab, newDataTab)
handleSetList(newPolicies)
}
return (
<>
<Box p={1}>
<FormWithSchema
id={STEP_ID}
cy="form-policy"
fields={POLICIES_FORM_FIELDS}
/>
</Box>
{React.useMemo(() => (
<AppBar position="static">
<Tabs value={tab} onChange={(_, tab) => setTab(tab)}>
{Object.keys(TABS).map(key =>
<Tab
key={`tab-${key}`}
id={`tab-${key}`}
value={key}
label={String(key).toUpperCase()}
/>
)}
</Tabs>
</AppBar>
), [tab])}
<Box overflow="hidden" height={1} position="relative">
<Fab
color="primary"
onClick={handleCreate}
style={{ position: 'absolute', zIndex: 1, bottom: 12, right: 28 }}
>
<AddIcon />
</Fab>
{React.useMemo(() => (
Object.keys(TABS).map(key => (
<Box key={`tab-${key}`} hidden={tab !== key} overflow="auto" height={1} p={2}>
<ListCards
list={policies[key]}
breakpoints={{ xs: 12, sm: 6 }}
CardComponent={PolicyCard}
cardsProps={({ index, value: { id } }) => ({
id: `${STEP_ID}.${key}[${index}]`,
cy: `form-policy-${key}[${index}]`,
fields: TABS[key].fields,
handleRemove: () => handleRemove(id)
})}
/>
</Box>
))
), [handleRemove])}
</Box>
</>
)
},
[]
)
})
@@ -1,28 +0,0 @@
import * as yup from 'yup'
import { TYPE_INPUT } from 'client/constants'
import { getValidationFromFields } from 'client/utils/helpers'
export const FORM_FIELDS = [
{
name: 'elasticityPolicies',
label: 'Elasticity',
type: TYPE_INPUT.TEXT,
validation: yup
.string()
.trim()
.default('')
},
{
name: 'scheduledPolicies',
label: 'Scheduled',
type: TYPE_INPUT.TEXT,
validation: yup
.string()
.trim()
.default('')
}
]
export const STEP_FORM_SCHEMA = yup.object(
getValidationFromFields(FORM_FIELDS)
)
@@ -0,0 +1,37 @@
import * as yup from 'yup'
import { getValidationFromFields } from 'client/utils/helpers'
import {
ID,
TYPE,
ADJUST,
MIN_ADJUST_STEP,
EXPRESSION,
PERIOD_NUMBER,
PERIOD,
COOLDOWN
} from './fields'
export const TAB_ID = 'elasticity'
export const ELASTICITY_FORM_FIELDS = [
// Auto-scaling Types
ID,
TYPE,
ADJUST,
MIN_ADJUST_STEP,
// Auto-scaling Based on Metrics
EXPRESSION,
PERIOD_NUMBER,
PERIOD,
COOLDOWN
]
export const ELASTICITY_FORM_SCHEMA = yup
.object(getValidationFromFields(ELASTICITY_FORM_FIELDS))
export const ELASTICITY_TAB_SCHEMA = yup
.array(ELASTICITY_FORM_SCHEMA)
.ensure()
.default([])
@@ -0,0 +1,180 @@
import * as yup from 'yup'
import { v4 as uuidv4 } from 'uuid'
import { TYPE_INPUT } from 'client/constants'
import { TYPES_POLICY, TIME_FORMATS, hasMinValue, isDateFormat } from './types'
const CRON_REG = /(@(annually|yearly|monthly|weekly|daily|hourly|reboot))|(@every (\d+(ns|us|µs|ms|s|m|h))+)|((((\d+,)+\d+|(\d+(\/|-)\d+)|\d+|\*) ?){5,7})/g
export const ID = {
name: 'id',
label: 'ID',
type: TYPE_INPUT.TEXT,
htmlType: 'hidden',
validation: yup
.string()
.trim()
.uuid()
.required()
.default(uuidv4)
}
// --------------------------------------------
// Auto-scaling Types
// --------------------------------------------
export const TYPE = {
name: 'type',
label: 'Type of adjustment',
type: TYPE_INPUT.SELECT,
values: TYPES_POLICY,
tooltip: `
CHANGE: Add/subtract the given number of VMs
CARDINALITY: Set the cardinality to the given number
PERCENTAGE_CHANGE: Add/subtract the given percentage to the current cardinality`,
validation: yup
.string()
.trim()
.oneOf(TYPES_POLICY.map(({ value }) => value))
.required('Type field is required')
.default(TYPES_POLICY[0].value)
}
export const ADJUST = {
name: 'adjust',
label: 'Adjust value',
type: TYPE_INPUT.TEXT,
htmlType: 'number',
tooltip: `
CHANGE: -2, will subtract 2 VMs from the tier
CARDINALITY: 9, will set cardinality to 8
PERCENTAGE_CHANGE: 20, will increment cardinality by 20%`,
validation: yup
.number()
.typeError('Adjust value must be a number')
.required('Adjust field is required')
.default(undefined)
}
export const MIN_ADJUST_STEP = {
name: 'min_adjust_step',
label: 'Min adjust step',
type: TYPE_INPUT.TEXT,
dependOf: TYPE.name,
tooltip: `
If present, the policy will change the cardinality by
at least the number of VMs set in this attribute`,
htmlType: dependValue => hasMinValue(dependValue) ? TYPE_INPUT.HIDDEN : 'number',
validation: yup
.number()
.typeError('Min. adjust step must be a number')
.min(1, 'Min. adjust step minimum is 1')
.when(TYPE.name, (type, schema) =>
hasMinValue(type) ? schema.strip() : schema
)
.notRequired()
.default(undefined)
}
// --------------------------------------------
// Auto-scaling Based on Metrics
// --------------------------------------------
export const EXPRESSION = {
name: 'expression',
label: 'Expression',
type: TYPE_INPUT.TEXT,
validation: yup
.string()
.trim()
.required('Expression field is required')
.default(undefined)
}
export const PERIOD_NUMBER = {
name: 'period_number',
label: 'Period number',
type: TYPE_INPUT.TEXT,
htmlType: 'number',
tooltip:
'Number of periods that the expression must be true before the elasticity is triggered',
validation: yup
.number()
.typeError('Period must be a number')
.min(0, 'Period number minimum is 0')
.notRequired()
.default(undefined)
}
export const PERIOD = {
name: 'period',
label: 'Period',
type: TYPE_INPUT.TEXT,
htmlType: 'number',
tooltip: 'Duration, in seconds, of each period in period_number',
validation: yup
.number()
.typeError('Period must be a number')
.min(0, 'Period minimum is 0')
.when(PERIOD_NUMBER.name, (value, schema) =>
value ? schema.strip() : schema
)
.notRequired()
.default(undefined)
}
export const COOLDOWN = {
name: 'cooldown',
label: 'Cooldown',
type: TYPE_INPUT.TEXT,
htmlType: 'number',
tooltip: `
Cooldown period duration after a scale operation, in seconds.
If it is not set, the one set for the Tier will be used
`,
validation: yup
.number()
.typeError('Cooldown must be a number')
.notRequired()
.default(undefined)
}
// --------------------------------------------
// Auto-scaling Based on a Schedule
// --------------------------------------------
export const TIME_FORMAT = {
name: 'time_format',
label: 'Time format',
type: TYPE_INPUT.SELECT,
values: TIME_FORMATS,
tooltip: `
START TIME: Exact time for the adjustment
RECURRENCE: Time for recurring adjustments.
Time is specified with the Unix cron syntax`,
validation: yup
.string()
.trim()
.notRequired()
.oneOf(TIME_FORMATS.map(({ value }) => value))
.default(TIME_FORMATS[0].value)
}
export const TIME_EXPRESSION = {
name: 'time_expression',
label: 'Time expression',
type: TYPE_INPUT.TEXT,
dependOf: TIME_FORMAT.name,
htmlType: dependValue => isDateFormat(dependValue)
? 'datetime-local' : TYPE_INPUT.TEXT,
validation: yup
.string()
.trim()
.notRequired()
.when(TIME_FORMAT.name, (value, schema) =>
isDateFormat(value)
? schema
: schema.matches(CRON_REG, { message: 'Invalid chars' })
)
.default(undefined)
}
@@ -0,0 +1,62 @@
import * as yup from 'yup'
import { TYPE_INPUT } from 'client/constants'
import { getValidationFromFields } from 'client/utils/helpers'
import { TAB_ID as ELASTICITY_ID, ELASTICITY_TAB_SCHEMA } from './elasticity'
import { TAB_ID as SCHEDULED_ID, SCHEDULED_TAB_SCHEMA } from './scheduled'
import { COOLDOWN } from './fields'
const MIN_VMS = {
name: 'min_vms',
label: 'Min. vms',
type: TYPE_INPUT.TEXT,
htmlType: 'number',
tooltip: 'Minimum number of VMs for elasticity adjustments',
validation: yup
.number()
.when(ELASTICITY_ID, (value, schema) => value?.length > 0
? schema.required('Minimum field is required')
: schema.notRequired().nullable()
)
.transform(value => !isNaN(value) ? value : null)
.default(undefined),
grid: { sm: 4, md: 4 }
}
const MAX_VMS = {
name: 'max_vms',
label: 'Max. vms',
type: TYPE_INPUT.TEXT,
htmlType: 'number',
tooltip: 'Maximum number of VMs for elasticity adjustments',
validation: yup
.number()
.moreThan(yup.ref(MIN_VMS.name), 'Max. vms field must be greater than min vms')
.when(ELASTICITY_ID, (value, schema) => value?.length > 0
? schema.required('Maximum field is required')
: schema.notRequired().nullable()
)
.transform(value => !isNaN(value) ? value : null)
.default(undefined),
grid: { sm: 4, md: 4 }
}
export const POLICIES_FORM_FIELDS = [
MIN_VMS,
MAX_VMS,
{
...COOLDOWN,
tooltip: `
Cooldown period duration after a scale operation, in seconds.
If it is not set, the default set in oneflow-server.conf will be used
`,
grid: { sm: 4, md: 4 }
}
]
export const POLICIES_SCHEMA = yup.object({
...getValidationFromFields(POLICIES_FORM_FIELDS),
[ELASTICITY_ID]: ELASTICITY_TAB_SCHEMA,
[SCHEDULED_ID]: SCHEDULED_TAB_SCHEMA
})
@@ -0,0 +1,32 @@
import * as yup from 'yup'
import { getValidationFromFields } from 'client/utils/helpers'
import {
ID,
TYPE,
ADJUST,
MIN_ADJUST_STEP,
TIME_FORMAT,
TIME_EXPRESSION
} from './fields'
export const TAB_ID = 'scheduled'
export const SCHEDULED_FORM_FIELDS = [
// Auto-scaling Types
ID,
TYPE,
ADJUST,
MIN_ADJUST_STEP,
// Auto-scaling Based on Schedule
TIME_FORMAT,
TIME_EXPRESSION
]
export const SCHEDULED_FORM_SCHEMA = yup
.object(getValidationFromFields(SCHEDULED_FORM_FIELDS))
export const SCHEDULED_TAB_SCHEMA = yup
.array(SCHEDULED_FORM_SCHEMA)
.ensure()
.default([])
@@ -0,0 +1,18 @@
export const TYPES_POLICY = [
{ text: 'Change', value: 'CHANGE', min: false },
{ text: 'Cardinality', value: 'CARDINALITY', min: false },
{ text: 'Percentege change', value: 'PERCENTAGE_CHANGE' }
]
export const TIME_FORMATS = [
{ text: 'Recurrence', value: 'recurrence' },
{ text: 'Start time', value: 'start_time', date: true }
]
export const hasMinValue = type => TYPES_POLICY.some(
({ value, min }) => value === type && min === false
)
export const isDateFormat = format => TIME_FORMATS.some(
({ value, date }) => value === format && date === true
)
@@ -48,17 +48,7 @@ function ApplicationCreate () {
}
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 && fetchRequest({ id })
}, [id])
useEffect(() => {
@@ -75,7 +65,7 @@ function ApplicationCreate () {
disableGutters
style={{ height: '100%', display: 'flex', flexDirection: 'column' }}
>
{loading ? (
{(id && !data) || loading ? (
<div>is loading...</div>
) : (
<FormProvider {...methods}>
@@ -56,6 +56,7 @@ const Form2fa = ({ onBack, onSubmit, error }) => {
data-cy="login-2fa-button"
isSubmitting={false}
label={Tr(Next)}
className={classes.submit}
/>
</Box>
</Box>
@@ -26,6 +26,7 @@ function FormGroup ({ onBack, onSubmit }) {
data-cy="login-group-button"
isSubmitting={false}
label={Tr(Next)}
className={classes.submit}
/>
</Box>
)
@@ -86,6 +86,7 @@ function FormUser ({ onSubmit, error }) {
data-cy="login-button"
isSubmitting={false}
label={Tr(SignIn)}
className={classes.submit}
/>
</Box>
)
@@ -38,6 +38,9 @@ export default makeStyles(theme =>
},
helper: {
animation: '1s ease-out 0s 1'
},
submit: {
margin: theme.spacing(3, 0, 2)
}
})
)
+21 -31
View File
@@ -1,4 +1,5 @@
import { useCallback, useState } from 'react'
import { set } from 'client/utils/helpers'
const NEXT_INDEX = index => index + 1
const EXISTS_INDEX = index => index !== -1
@@ -6,9 +7,14 @@ const EXISTS_INDEX = index => index !== -1
const getIndexById = (list, id) =>
list.findIndex(({ id: itemId }) => itemId === id)
const useListSelect = ({ multiple, key, list, setList, defaultValue }) => {
const useListForm = ({ multiple, key, list, setList, defaultValue }) => {
const [editingData, setEditingData] = useState({})
const handleSetList = useCallback(
newList => setList(data => ({ ...set(data, key, newList) })),
[key, setList, list]
)
const handleSelect = useCallback(
id =>
setList(prevList => ({
@@ -41,46 +47,30 @@ const useListSelect = ({ multiple, key, list, setList, defaultValue }) => {
const ZERO_DELETE_COUNT = 0
cloneList.splice(NEXT_INDEX(itemIndex), ZERO_DELETE_COUNT, cloneItem)
setList(prevList => ({ ...prevList, [key]: cloneList }))
handleSetList(cloneList)
},
[list, setList]
[list]
)
const handleRemove = useCallback(
id => {
// TODO confirmation??
setList(prevList => ({
...prevList,
[key]: prevList[key]?.filter(item => item.id !== id)
}))
},
[key, setList]
)
(id) => {
const newList = list?.filter(item => item.id !== id)
const handleSetList = useCallback(
newList => {
setList(prevList => ({ ...prevList, [key]: newList }))
handleSetList(newList)
},
[key, setList]
[key, list]
)
const handleSave = useCallback(
(values, id = editingData.id) => {
setList(prevList => {
const itemIndex = getIndexById(prevList[key], id)
const index = EXISTS_INDEX(itemIndex)
? itemIndex
: prevList[key].length
(values, id = editingData?.id) => {
const itemIndex = getIndexById(list, id)
const index = EXISTS_INDEX(itemIndex) ? itemIndex : list.length
return {
...prevList,
[key]: Object.assign(prevList[key], {
[index]: { ...editingData, ...values }
})
}
})
const newList = set(list, index, { ...editingData, ...values })
handleSetList(newList)
},
[key, setList, editingData]
[key, list, editingData]
)
const handleEdit = useCallback(
@@ -106,4 +96,4 @@ const useListSelect = ({ multiple, key, list, setList, defaultValue }) => {
}
}
export default useListSelect
export default useListForm
@@ -73,6 +73,16 @@ export default function useOpennebula () {
[dispatch, filter, templates]
)
const getTemplate = useCallback(
({ id }) => {
dispatch(startOneRequest())
return servicePool
.getTemplate({ filter, id })
.catch(err => dispatch(failureOneRequest({ error: err })))
},
[dispatch, filter]
)
const getMarketApps = useCallback(
({ end, start } = { end: -1, start: -1 }) => {
dispatch(startOneRequest())
@@ -105,6 +115,7 @@ export default function useOpennebula () {
getVNetworksTemplates,
templates,
getTemplates,
getTemplate,
apps,
getMarketApps,
clusters,
+14
View File
@@ -79,6 +79,20 @@ export const getTemplates = ({ filter, end, start }) => {
})
}
export const getTemplate = ({ filter, id }) => {
const name = Template.Actions.TEMPLATE_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Template.Commands[name] }
)
return requestData(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.VMTEMPLATE ?? {}
})
}
export const getMarketApps = ({ filter, end, start }) => {
const name = MarketApp.Actions.MARKETAPP_POOL_INFO
const { url, options } = requestParams(
+33
View File
@@ -25,3 +25,36 @@ export const filterBy = (arr, predicate) => {
.values()
]
}
export const get = (obj, path, defaultValue = undefined) => {
const travel = regexp =>
String.prototype.split
.call(path, regexp)
.filter(Boolean)
.reduce((res, key) => (res !== null && res !== undefined ? res[key] : res), obj)
const result = travel(/[,[\]]+?/) || travel(/[,[\].]+?/)
return result === undefined || result === obj ? defaultValue : result
}
export const set = (obj, path, value) => {
if (Object(obj) !== obj) return obj // When obj is not an object
// If not yet an array, get the keys from the string-path
if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || []
const result = path.slice(0, -1).reduce((res, key, idx) => {
if (Object(res[key]) === res[key]) return res[key]
// If the next key is array-index,
// then assign a new array object or new object
res[key] = Math.abs(path[idx + 1]) >> 0 === +path[idx + 1] ? [] : {}
return res[key]
}, obj)
// Assign the value to the last key
result[path[path.length - 1]] = value
return result
}
@@ -52,11 +52,14 @@ const parseTiers = (roles, networking) =>
name,
cardinality,
parents,
min_vms: minVms,
max_vms: maxVms,
cooldown,
shutdown_action: shutdownAction,
vm_template: vmTemplate,
vm_template_contents: content = '',
elasticity_policies: elasticityPolicies,
scheduled_policies: scheduledPolicies,
elasticity_policies: elasticityPolicies = [],
scheduled_policies: scheduledPolicies = [],
position = { x: 0, y: 0 }
} = data
@@ -70,6 +73,25 @@ const parseTiers = (roles, networking) =>
return network.id
}) ?? []
const elasticity = elasticityPolicies.map(({ id, ...policy }) =>
JSON.parse(JSON.stringify(policy))
)
const scheduled = scheduledPolicies.map(
({ id, recurrence, start_time: time, ...rest }) => {
return {
...JSON.parse(JSON.stringify(rest)),
...(recurrence && {
time_format: 'recurrence',
time_expression: recurrence
}),
...(time && {
time_format: 'start_time',
time_expression: time
})
}
})
return [
...res,
{
@@ -77,7 +99,13 @@ const parseTiers = (roles, networking) =>
template: { id: String(vmTemplate) },
networks,
parents,
policies: { elasticityPolicies, scheduledPolicies },
policies: {
min_vms: minVms,
max_vms: maxVms,
cooldown,
elasticity,
scheduled
},
position,
tier: { name, cardinality, shutdown_action: shutdownAction }
}
@@ -16,8 +16,9 @@ const mapNetworkToUserInput = network => {
const mapTiersToRoles = (tiers, networking, cluster) =>
tiers?.map(data => {
const { template, networks, parents, position, tier } = data
const { template, networks, parents, policies, position, tier } = data
const { shutdown_action: action, ...information } = tier
const { elasticity, scheduled, ...adjustments } = policies
const networksValue = networks
?.reduce((res, id, idx) => {
@@ -34,14 +35,26 @@ const mapTiersToRoles = (tiers, networking, cluster) =>
return [...res, parent?.tier?.name]
}, [])
const elasticityValues = elasticity.map(({ id, ...policy }) =>
JSON.parse(JSON.stringify(policy))
)
const scheduledValues = scheduled.map(
({ id, time_format: format, time_expression: expression, ...rest }) => ({
...JSON.parse(JSON.stringify(rest)),
...(expression && { [format]: expression })
})
)
return {
...information,
...adjustments,
...(action !== 'none' && { shutdown_action: action }),
parents: parentsValue,
vm_template: template?.id ?? template?.app,
vm_template_contents: networksValue,
elasticity_policies: [],
scheduled_policies: [],
elasticity_policies: elasticityValues,
scheduled_policies: scheduledValues,
position
}
})