diff --git a/install.sh b/install.sh index 2473d3d472..88fa19a8df 100755 --- a/install.sh +++ b/install.sh @@ -2271,7 +2271,9 @@ FIREEDGE_SUNSTONE_ETC_VIEW_ADMIN="src/fireedge/etc/sunstone/views/admin/vm-tab.y src/fireedge/etc/sunstone/views/admin/cluster-tab.yaml \ src/fireedge/etc/sunstone/views/admin/support-tab.yaml \ src/fireedge/etc/sunstone/views/admin/zone-tab.yaml \ - src/fireedge/etc/sunstone/views/admin/marketplace-tab.yaml" + src/fireedge/etc/sunstone/views/admin/marketplace-tab.yaml \ + src/fireedge/etc/sunstone/views/admin/driver-tab.yaml \ + src/fireedge/etc/sunstone/views/admin/provider-tab.yaml" FIREEDGE_SUNSTONE_ETC_VIEW_USER="src/fireedge/etc/sunstone/views/user/vm-tab.yaml \ src/fireedge/etc/sunstone/views/user/vm-template-tab.yaml \ diff --git a/share/providers/aws/ansible/templates/ssh_cluster.j2 b/share/providers/aws/ansible/templates/ssh_cluster.j2 index b8be286e92..7e8062108e 100644 --- a/share/providers/aws/ansible/templates/ssh_cluster.j2 +++ b/share/providers/aws/ansible/templates/ssh_cluster.j2 @@ -8,6 +8,7 @@ user_inputs: description: Number of public IPs to allocate type: number default: 0 + mandatory: false match: type: number values: diff --git a/share/providers/aws/driver.conf b/share/providers/aws/driver.conf index f78519e133..14a5a392b6 100644 --- a/share/providers/aws/driver.conf +++ b/share/providers/aws/driver.conf @@ -9,3 +9,17 @@ version: '1.0.0' # FireEdge configuration (logos, metadata, etc) fireedge: logo: '/fireedge/client/assets/images/providers/aws.png' + color: "FD6F8E" + operations: + add-host: amount # aws, scaleway, equinix + del-host: ids + add-ip: amount + layout: + provider: + - oneform_hosts + - instance_type + - instance_os_name + - instance_disk_size + network: + - cidr_block + - oneform_public_ips \ No newline at end of file diff --git a/share/providers/dummy/ansible/templates/dummy_cluster.j2 b/share/providers/dummy/ansible/templates/dummy_cluster.j2 index c90b03610a..e364033c38 100644 --- a/share/providers/dummy/ansible/templates/dummy_cluster.j2 +++ b/share/providers/dummy/ansible/templates/dummy_cluster.j2 @@ -8,6 +8,7 @@ user_inputs: description: Physical device name for the network type: string default: "eth0" + mandatory: false match: type: list values: @@ -17,6 +18,7 @@ user_inputs: description: Number of public IPs to allocate type: number default: 0 + mandatory: false match: type: number values: diff --git a/share/providers/dummy/driver.conf b/share/providers/dummy/driver.conf index bc5e28b51f..d34f67e813 100644 --- a/share/providers/dummy/driver.conf +++ b/share/providers/dummy/driver.conf @@ -9,3 +9,16 @@ version: '1.0.0' # FireEdge configuration (logos, metadata, etc) fireedge: logo: '/fireedge/client/assets/images/providers/dummy.png' + color: "23CE6B" + operations: + add-host: amount # aws, scaleway, equinix + del-host: ids + add-ip: amount + layout: + provider: + - oneform_hosts + - instance_type + - instance_os_name + network: + - phydev_name + - oneform_public_ips \ No newline at end of file diff --git a/share/providers/equinix/ansible/templates/ssh_cluster.j2 b/share/providers/equinix/ansible/templates/ssh_cluster.j2 index f7f9d45fda..340899bc54 100644 --- a/share/providers/equinix/ansible/templates/ssh_cluster.j2 +++ b/share/providers/equinix/ansible/templates/ssh_cluster.j2 @@ -8,6 +8,7 @@ user_inputs: description: Number of public IPs to allocate type: number default: 0 + mandatory: false match: type: number values: diff --git a/share/providers/equinix/driver.conf b/share/providers/equinix/driver.conf index 0577178087..a6dfa9b2b6 100644 --- a/share/providers/equinix/driver.conf +++ b/share/providers/equinix/driver.conf @@ -9,8 +9,20 @@ version: '1.0.0' # FireEdge configuration (logos, metadata, etc) fireedge: logo: '/fireedge/client/assets/images/providers/equinix.png' + color: "2EBFA5" literals: ny: 'New York' am: 'Amsterdam' sv: 'Silicon Valley' ty: 'Tokyo' + operations: + add-host: amount # aws, scaleway, equinix + del-host: ids + add-ip: amount + layout: + provider: + - oneform_hosts + - instance_type + - instance_os_name + network: + - oneform_public_ips \ No newline at end of file diff --git a/share/providers/equinix/terraform/provider.tf b/share/providers/equinix/terraform/provider.tf index 490194572d..e7bb9b075f 100644 --- a/share/providers/equinix/terraform/provider.tf +++ b/share/providers/equinix/terraform/provider.tf @@ -21,6 +21,7 @@ variable "project_id" { variable "region" { type = string description = "Equinix Region" + default = "am" } provider "equinix" { diff --git a/share/providers/i3dnet/driver.conf b/share/providers/i3dnet/driver.conf index 75c0076f2c..38a203740c 100644 --- a/share/providers/i3dnet/driver.conf +++ b/share/providers/i3dnet/driver.conf @@ -9,3 +9,13 @@ version: '1.0.0' # FireEdge configuration (logos, metadata, etc) fireedge: logo: '/fireedge/client/assets/images/providers/i3dnet.png' + color: "000f00" + operations: + add-host: amount # aws, scaleway, equinix + del-host: ids + add-ip: amount + layout: + provider: + - oneform_hosts + - instance_type + - instance_os_name \ No newline at end of file diff --git a/share/providers/onprem/driver.conf b/share/providers/onprem/driver.conf index cfe7d24cad..164c9df9b6 100644 --- a/share/providers/onprem/driver.conf +++ b/share/providers/onprem/driver.conf @@ -9,6 +9,15 @@ version: '1.0.0' # FireEdge configuration (logos, metadata, etc) fireedge: logo: '/fireedge/client/assets/images/providers/onprem.png' + color: "6172F3" + operations: + add-host: ips + del-host: ids + layout: + provider: + - oneform_onprem_hosts + network: + - phydev_name connection: {} user_inputs: [] diff --git a/share/providers/scaleway/ansible/templates/ssh_cluster.j2 b/share/providers/scaleway/ansible/templates/ssh_cluster.j2 index 400ca33d81..f146b57c30 100644 --- a/share/providers/scaleway/ansible/templates/ssh_cluster.j2 +++ b/share/providers/scaleway/ansible/templates/ssh_cluster.j2 @@ -8,6 +8,7 @@ user_inputs: description: Number of public IPs to allocate type: number default: 0 + mandatory: false match: type: number values: diff --git a/share/providers/scaleway/driver.conf b/share/providers/scaleway/driver.conf index 0794bb21e4..7a02cc2603 100644 --- a/share/providers/scaleway/driver.conf +++ b/share/providers/scaleway/driver.conf @@ -9,3 +9,15 @@ version: '1.0.0' # FireEdge configuration (logos, metadata, etc) fireedge: logo: '/fireedge/client/assets/images/providers/scaleway.png' + color: "948DD7" + operations: + add-host: amount # aws, scaleway, equinix + del-host: ids + add-ip: amount + layout: + provider: + - oneform_hosts + - instance_type + - instance_os_name + network: + - cidr_block \ No newline at end of file diff --git a/src/cli/oneprovision b/src/cli/oneprovision index 98526dd07e..76dc5aaa9b 100755 --- a/src/cli/oneprovision +++ b/src/cli/oneprovision @@ -83,7 +83,7 @@ CommandParser::CmdParser.new(ARGV) do :large => '--ids ids', :short => '-i ids', :description => 'Hosts IDs to remove from the provision', - :format => Integer + :format => Array } AMOUNT = { @@ -107,7 +107,7 @@ CommandParser::CmdParser.new(ARGV) do :short => '-i ips', :large => '--ips ips', :description => 'IP addresses to add as hosts. Only valid for on-prem providers', - :format => Integer + :format => Array } PROVIDER_ID = { @@ -391,8 +391,7 @@ CommandParser::CmdParser.new(ARGV) do if amount.nil? && host_ips.nil? amount = 1 end - - nodes = amount || [host_ips] + nodes = amount || host_ips response = client.scale_provision(provision_id, 'up', nodes) return [response[:err_code], response[:message]] \ @@ -442,7 +441,7 @@ CommandParser::CmdParser.new(ARGV) do amount = 1 end - nodes = amount || [host_ids] + nodes = amount || host_ids response = client.scale_provision(provision_id, 'down', nodes, :force => force) return [response[:err_code], response[:message]] \ diff --git a/src/fireedge/etc/fireedge-server.conf b/src/fireedge/etc/fireedge-server.conf index 2069b443d1..a5a916e341 100644 --- a/src/fireedge/etc/fireedge-server.conf +++ b/src/fireedge/etc/fireedge-server.conf @@ -21,7 +21,7 @@ one_xmlrpc: 'http://localhost:2633/RPC2' oneflow_server: 'http://localhost:2474' # Form Server: use it if you have form-server and fireedge on different servers -oneform_server: 'http://localhost:13013' +oneform_server: 'http://localhost:13013/api/v1' # JWT expiration time (minutes) session_expiration: 180 diff --git a/src/fireedge/etc/sunstone/tab-manifest.yaml b/src/fireedge/etc/sunstone/tab-manifest.yaml index 6e1cc922b7..a24b06f952 100644 --- a/src/fireedge/etc/sunstone/tab-manifest.yaml +++ b/src/fireedge/etc/sunstone/tab-manifest.yaml @@ -198,9 +198,17 @@ routes: - title: Drivers path: /driver + sidebar: false + icon: DataTransferUp + Component: Drivers + - title: Providers + path: /provider sidebar: true - icon: HardDrive - Component: Drivers + icon: SettingsProfiles + Component: Providers + - title: Create Provider + path: /provider/create + Component: CreateProvider - title: Clusters path: /cluster sidebar: true @@ -209,6 +217,12 @@ - title: Create Cluster path: /cluster/create Component: CreateCluster + - title: Create Cluster Cloud + path: /cluster/create_cloud + Component: CreateClusterCloud + - title: Cluster Logs + path: /cluster/create_cloud_logs/:id + Component: CreateClusterCloudLogs - title: Cluster path: /cluster/:id Component: ClusterDetail diff --git a/src/fireedge/etc/sunstone/views/admin/cluster-tab.yaml b/src/fireedge/etc/sunstone/views/admin/cluster-tab.yaml index 38d8f40a85..72e348c267 100644 --- a/src/fireedge/etc/sunstone/views/admin/cluster-tab.yaml +++ b/src/fireedge/etc/sunstone/views/admin/cluster-tab.yaml @@ -9,7 +9,11 @@ resource_name: "CLUSTER" actions: create_dialog: true + create_cloud_dialog: true + create_cloud_dialog_logs: true update_dialog: true + deprovision: true + retry: true delete: true # Filters - List of criteria to filter the resources @@ -40,9 +44,21 @@ info-tabs: host: enabled: true + provision: + actions: + add: true + delete: true vnet: enabled: true + provision: + actions: + add: true + delete: true + delete_ar: true + datastore: enabled: true drs: enabled: true + logs: + enabled: true diff --git a/src/fireedge/etc/sunstone/views/admin/driver-tab.yaml b/src/fireedge/etc/sunstone/views/admin/driver-tab.yaml index 7b2f6fe745..e8e53d60b3 100644 --- a/src/fireedge/etc/sunstone/views/admin/driver-tab.yaml +++ b/src/fireedge/etc/sunstone/views/admin/driver-tab.yaml @@ -20,8 +20,8 @@ info-tabs: information_panel: enabled: true connection: - enabled: true + enabled: false deployment_confs: - enabled: true + enabled: false user_inputs: - enabled: true \ No newline at end of file + enabled: false \ No newline at end of file diff --git a/src/fireedge/etc/sunstone/views/admin/provider-tab.yaml b/src/fireedge/etc/sunstone/views/admin/provider-tab.yaml new file mode 100644 index 0000000000..460e89c68d --- /dev/null +++ b/src/fireedge/etc/sunstone/views/admin/provider-tab.yaml @@ -0,0 +1,48 @@ +--- +# This file describes the information and actions available in the PROVIDER tab + +# Resource + +resource_name: "PROVIDER" + +# Actions - Which buttons are visible to operate over the resources + +actions: + create_dialog: true + update_dialog: true + delete: true + chown: true + chgrp: true + +# Filters - List of criteria to filter the resources + +filters: + owner: true + group: true + +# Info Tabs - Which info tabs are used to show extended information + +info-tabs: + info: + enabled: true + information_panel: + enabled: true + actions: + rename: true + permissions_panel: + enabled: true + actions: + chmod: true + ownership_panel: + enabled: true + actions: + chown: true + chgrp: true + + template: + enabled: true + +# Dialogs + +dialogs: + create_dialog: \ No newline at end of file diff --git a/src/fireedge/package-lock.json b/src/fireedge/package-lock.json index eaeb40fd2e..408a023eab 100644 --- a/src/fireedge/package-lock.json +++ b/src/fireedge/package-lock.json @@ -3498,7 +3498,6 @@ "resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz", "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==", "dev": true, - "license": "MIT", "peer": true }, "node_modules/@socket.io/component-emitter": { @@ -4407,7 +4406,6 @@ "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.6.tgz", "integrity": "sha512-F/TKATkzseUExPlfvmwQKGITM3DGTK+vkAsCZoDc5daVygbJBnjEUCbgkAvVFsgfXfX4YIqZ/27G3k3tdXrTxQ==", "dev": true, - "license": "MIT", "peer": true, "dependencies": { "call-bind": "^1.0.8", @@ -7544,7 +7542,6 @@ "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.32.0.tgz", "integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==", "dev": true, - "license": "MIT", "peer": true, "dependencies": { "@rtsao/scc": "^1.1.0", @@ -7579,7 +7576,6 @@ "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", "dev": true, - "license": "MIT", "peer": true, "dependencies": { "ms": "^2.1.1" @@ -7590,7 +7586,6 @@ "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", "dev": true, - "license": "Apache-2.0", "peer": true, "dependencies": { "esutils": "^2.0.2" @@ -11519,7 +11514,6 @@ "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz", "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==", "dev": true, - "license": "MIT", "peer": true, "dependencies": { "call-bind": "^1.0.7", diff --git a/src/fireedge/src/modules/components/Buttons/AddressRangeActions.js b/src/fireedge/src/modules/components/Buttons/AddressRangeActions.js index 3075ec72ff..6a251d7449 100644 --- a/src/fireedge/src/modules/components/Buttons/AddressRangeActions.js +++ b/src/fireedge/src/modules/components/Buttons/AddressRangeActions.js @@ -133,7 +133,7 @@ const UpdateAddressRangeAction = memo( ) const DeleteAddressRangeAction = memo( - ({ vnetId, ar, onSubmit, oneConfig, adminGroup }) => { + ({ vnetId, ar, onSubmit, oneConfig, adminGroup, submit }) => { const [removeAR] = VnAPI.useRemoveRangeFromVNetMutation() const { AR_ID } = ar @@ -142,7 +142,10 @@ const DeleteAddressRangeAction = memo( return await onSubmit(AR_ID) } - await removeAR({ id: vnetId, address: AR_ID }) + // When deleting AR in a provision, use the oneform API + submit + ? await submit({ arId: AR_ID }) + : await removeAR({ id: vnetId, address: AR_ID }) } // Disable action if the disk has a restricted attribute on the template @@ -181,6 +184,7 @@ const ActionPropTypes = { onSubmit: PropTypes.func, oneConfig: PropTypes.object, adminGroup: PropTypes.bool, + submit: PropTypes.object, } AddAddressRangeAction.propTypes = ActionPropTypes diff --git a/src/fireedge/src/modules/components/Cards/DriverCard.js b/src/fireedge/src/modules/components/Cards/DriverCard.js index e597953011..3d0b57d207 100644 --- a/src/fireedge/src/modules/components/Cards/DriverCard.js +++ b/src/fireedge/src/modules/components/Cards/DriverCard.js @@ -44,6 +44,8 @@ const DriverCard = memo( // Get logo for the driver const logoSource = useMemo(() => { if (!fireedge?.logo) return `${LOGO_DRIVERS_IMAGES_URL}/default.png` + if (fireedge?.logo.includes(LOGO_DRIVERS_IMAGES_URL)) + return `${fireedge.logo}` return `${LOGO_DRIVERS_IMAGES_URL}/${fireedge?.logo}` }, [fireedge]) diff --git a/src/fireedge/src/modules/components/Cards/ProviderCard.js b/src/fireedge/src/modules/components/Cards/ProviderCard.js new file mode 100644 index 0000000000..68ace09bc6 --- /dev/null +++ b/src/fireedge/src/modules/components/Cards/ProviderCard.js @@ -0,0 +1,121 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { Typography, useTheme } from '@mui/material' +import PropTypes from 'prop-types' +import { ReactElement, memo, useMemo } from 'react' +import { rowStyles } from '@modules/components/Tables/styles' +import Image from '@modules/components/Image' +import Timer from '@modules/components/Timer' +import { Tr } from '@modules/components/HOC' +import { LOGO_DRIVERS_IMAGES_URL, T } from '@ConstantsModule' +import { timeFromMilliseconds } from '@ModelsModule' +import { Package } from 'iconoir-react' + +const ProviderCard = memo( + /** + * @param {object} props - Props + * @param {object} props.rootProps - Props to root component + * @param {ReactElement} [props.actions] - Actions + * @param {object} props.provider - Driver data + * @returns {ReactElement} - Card + */ + ({ provider, rootProps, actions }) => { + const theme = useTheme() + const classes = useMemo(() => rowStyles(theme), [theme]) + + // Get data from provider + const { + ID, + NAME, + TEMPLATE: { + PROVIDER_BODY: { + registration_time: regTime, + provision_ids: provisionIds, + fireedge = {}, + } = {}, + }, + } = provider + + const numberOfProvisions = useMemo( + () => provisionIds.length, + [provisionIds] + ) + + const time = useMemo(() => timeFromMilliseconds(+regTime), [regTime]) + + // Get logo for the provider + const logoSource = useMemo(() => { + if (!fireedge?.logo) return `${LOGO_DRIVERS_IMAGES_URL}/default.png` + if (fireedge?.logo.includes(LOGO_DRIVERS_IMAGES_URL)) + return `${fireedge.logo}` + + return `${LOGO_DRIVERS_IMAGES_URL}/${fireedge?.logo}` + }, [fireedge]) + + return ( +
+
+ logo +
+
+
+ + {NAME} + +
+
+ {`#${ID}`} + + + + + + {numberOfProvisions} + +
+
+ {actions &&
{actions}
} +
+ ) + } +) + +ProviderCard.propTypes = { + provider: PropTypes.object, + rootProps: PropTypes.shape({ + className: PropTypes.string, + }), + onDeleteLabel: PropTypes.func, + actions: PropTypes.any, +} + +ProviderCard.displayName = 'ProviderCard' + +export default ProviderCard diff --git a/src/fireedge/src/modules/components/Cards/index.js b/src/fireedge/src/modules/components/Cards/index.js index 6dc5e0576b..05761f8e9f 100644 --- a/src/fireedge/src/modules/components/Cards/index.js +++ b/src/fireedge/src/modules/components/Cards/index.js @@ -40,6 +40,7 @@ import NetworkCard from '@modules/components/Cards/NetworkCard' import NicCard from '@modules/components/Cards/NicCard' import PciCard from '@modules/components/Cards/PciCard' import PolicyCard from '@modules/components/Cards/PolicyCard' +import ProviderCard from '@modules/components/Cards/ProviderCard' import ScheduleActionCard from '@modules/components/Cards/ScheduleActionCard' import SecurityGroupCard from '@modules/components/Cards/SecurityGroupCard' import SelectCard from '@modules/components/Cards/SelectCard' @@ -84,6 +85,7 @@ export { NicCard, PciCard, PolicyCard, + ProviderCard, ScheduleActionCard, SecurityGroupCard, SelectCard, diff --git a/src/fireedge/src/modules/components/Dialogs/DialogConfirmation.js b/src/fireedge/src/modules/components/Dialogs/DialogConfirmation.js index 7a1f94d3e2..934149eb7f 100644 --- a/src/fireedge/src/modules/components/Dialogs/DialogConfirmation.js +++ b/src/fireedge/src/modules/components/Dialogs/DialogConfirmation.js @@ -13,23 +13,23 @@ * See the License for the specific language governing permissions and * * limitations under the License. * * ------------------------------------------------------------------------- */ -import { memo, JSXElementConstructor } from 'react' import PropTypes from 'prop-types' +import { JSXElementConstructor, memo } from 'react' +import { STYLE_BUTTONS, T } from '@ConstantsModule' +import { Action } from '@modules/components/Cards/SelectCard' +import SubmitButton from '@modules/components/FormControl/SubmitButton' +import { Tr } from '@modules/components/HOC' import { - useMediaQuery, Dialog, - DialogTitle, - DialogContent, DialogActions, + DialogContent, + DialogTitle, Typography, + useMediaQuery, } from '@mui/material' import { Box } from '@mui/system' import { Cancel as CancelIcon } from 'iconoir-react' -import SubmitButton from '@modules/components/FormControl/SubmitButton' -import { Action } from '@modules/components/Cards/SelectCard' -import { Tr } from '@modules/components/HOC' -import { T, STYLE_BUTTONS } from '@ConstantsModule' /** * @typedef {object} DialogProps @@ -51,8 +51,8 @@ import { T, STYLE_BUTTONS } from '@ConstantsModule' * @param {DialogProps} props - Dialog properties * @returns {JSXElementConstructor} - Dialog with confirmation basic buttons */ -const DialogConfirmation = memo( - ({ +const DialogConfirmation = memo((props) => { + const { open = true, title = '', subheader, @@ -66,108 +66,107 @@ const DialogConfirmation = memo( fixedHeight, children, dataCy, - }) => { - const isMobile = useMediaQuery((theme) => theme.breakpoints.only('xs')) + } = props + const isMobile = useMediaQuery((theme) => theme.breakpoints.only('xs')) - return ( - + - - - {title && ( - - {typeof title === 'string' ? Tr(title) : title} - - )} - {subheader && ( - - {typeof subheader === 'string' ? Tr(subheader) : subheader} - - )} - - {handleCancel && ( - } - /> + + {title && ( + + {typeof title === 'string' ? Tr(title) : title} + )} - - {children && ( - - {children} - + {subheader && ( + + {typeof subheader === 'string' ? Tr(subheader) : subheader} + + )} + + {handleCancel && ( + } + /> )} - {handleAccept && ( - - - - )} - - ) - } -) + + {children && ( + + {typeof children === 'function' ? children(props) : children} + + )} + {handleAccept && ( + + + + )} + + ) +}) export const DialogPropTypes = { open: PropTypes.bool, diff --git a/src/fireedge/src/modules/components/Forms/Cluster/AddHostForm/index.js b/src/fireedge/src/modules/components/Forms/Cluster/AddHostForm/index.js new file mode 100644 index 0000000000..bd23ec7a02 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/AddHostForm/index.js @@ -0,0 +1,28 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { createForm } from '@UtilsModule' +import { + FIELDS, + SCHEMA, +} from '@modules/components/Forms/Cluster/AddHostForm/schema' + +const AddHostForm = createForm(SCHEMA, FIELDS, { + transformInitialValue: (hosts, schema) => ({ + ...schema.cast({ hosts }, { stripUnknown: true }), + }), +}) + +export default AddHostForm diff --git a/src/fireedge/src/modules/components/Forms/Cluster/AddHostForm/schema.js b/src/fireedge/src/modules/components/Forms/Cluster/AddHostForm/schema.js new file mode 100644 index 0000000000..4f590c893c --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/AddHostForm/schema.js @@ -0,0 +1,61 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { array, lazy, object, ObjectSchema, string } from 'yup' + +import { INPUT_TYPES, T } from '@ConstantsModule' +import { Field, getValidationFromFields } from '@UtilsModule' + +/** @type {Field} Host field */ +const HOSTS = ({ formType = '', filter }) => { + if (formType === 'amount') { + return { + name: 'hosts', + label: T.NumberOfHostsToAdd, + type: INPUT_TYPES.TEXT, + htmlType: 'number', + fieldProps: { min: 1 }, + grid: { md: 12 }, + validation: string() + .trim() + .required() + .default(() => 1), + } + } else { + return { + name: 'hosts', + label: T.SelectNewHostsToAdd, + type: INPUT_TYPES.AUTOCOMPLETE, + tooltip: [T.PressKeysToAddAValue, ['ENTER']], + multiple: true, + fieldProps: { + freeSolo: true, + }, + grid: { md: 12 }, + validation: lazy(() => + array(string().trim()) + .required() + .default(() => undefined) + ), + } + } +} + +/** @type {Field[]} List of fields */ +export const FIELDS = (params) => [HOSTS(params)] + +/** @type {ObjectSchema} Schema */ +export const SCHEMA = (params) => + object(getValidationFromFields(FIELDS(params))) diff --git a/src/fireedge/src/modules/components/Forms/Cluster/AddVnetsForm/index.js b/src/fireedge/src/modules/components/Forms/Cluster/AddVnetsForm/index.js new file mode 100644 index 0000000000..654e93cb5a --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/AddVnetsForm/index.js @@ -0,0 +1,28 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { createForm } from '@UtilsModule' +import { + FIELDS, + SCHEMA, +} from '@modules/components/Forms/Cluster/AddVnetsForm/schema' + +const AddVnetsForm = createForm(SCHEMA, FIELDS, { + transformInitialValue: (vnets, schema) => ({ + ...schema.cast({ vnets }, { stripUnknown: true }), + }), +}) + +export default AddVnetsForm diff --git a/src/fireedge/src/modules/components/Forms/Cluster/AddVnetsForm/schema.js b/src/fireedge/src/modules/components/Forms/Cluster/AddVnetsForm/schema.js new file mode 100644 index 0000000000..d238f30f5a --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/AddVnetsForm/schema.js @@ -0,0 +1,40 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { object, ObjectSchema, number } from 'yup' + +import { INPUT_TYPES, T } from '@ConstantsModule' +import { Field, getValidationFromFields } from '@UtilsModule' + +/** @type {Field} Host field */ +const AMOUNT = () => ({ + name: 'amount', + label: T.NumberOfIPsToAdd, + type: INPUT_TYPES.TEXT, + htmlType: 'number', + fieldProps: { min: 1 }, + grid: { md: 12 }, + validation: number() + .integer() + .positive() + .required() + .default(() => 1), +}) + +/** @type {Field[]} List of fields */ +export const FIELDS = () => [AMOUNT()] + +/** @type {ObjectSchema} Schema */ +export const SCHEMA = () => object(getValidationFromFields(FIELDS())) diff --git a/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/Deployments/index.js b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/Deployments/index.js new file mode 100644 index 0000000000..331ff91906 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/Deployments/index.js @@ -0,0 +1,49 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { T } from '@ConstantsModule' +import PropTypes from 'prop-types' +import FormWithSchema from '@modules/components/Forms/FormWithSchema' +import { SCHEMA, FIELDS } from './schema' + +export const STEP_ID = 'deployments' + +const Content = (providers, groupedDrivers, deploymentSteps) => ( + +) + +/** + * @param {Array} providers - Array of providers + * @param {Array} groupedDrivers - Array of drivers with deployment configurations fields + * @param {Array} deploymentSteps - Array of deployment steps + * @returns {object} Deployment configurations with associated next steps + */ +const Deployments = (providers, groupedDrivers, deploymentSteps) => ({ + id: STEP_ID, + label: T.DeploymentTypes, + resolver: SCHEMA(providers), + optionsValidate: { abortEarly: false }, + content: () => Content(providers, groupedDrivers, deploymentSteps), +}) + +Deployments.propTypes = { + providers: PropTypes.object, +} + +export default Deployments diff --git a/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/Deployments/schema.js b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/Deployments/schema.js new file mode 100644 index 0000000000..fed14a23a1 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/Deployments/schema.js @@ -0,0 +1,84 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { INPUT_TYPES, T } from '@ConstantsModule' +import { Field, getObjectSchemaFromFields, arrayToOptions } from '@UtilsModule' +import { ObjectSchema, string } from 'yup' +import { findIndex } from 'lodash' + +/** @type {Field} Name field */ +const DEPLOYMENT_CONF = (providers, groupedDrivers, deploymentSteps) => { + const stepControl = [] + + deploymentSteps?.forEach((deploymentStep, index) => { + const deploymentConf = { + condition: (deployment) => + findIndex(deploymentSteps, { name: deployment }) !== index, + steps: [deploymentSteps[index].name], + } + stepControl.push(deploymentConf) + }) + + return { + name: 'DEPLOYMENT_CONF', + label: T['cluster.deployment_conf'], + type: INPUT_TYPES.AUTOCOMPLETE, + optionsOnly: true, + dependOf: '$provider.PROVIDER', + dependencies: '$provider.PROVIDER', + clearInvalid: true, + values: (providerId = []) => { + const selectedProvider = providers.find((p) => p.ID === providerId) + const selectedDriver = selectedProvider + ? groupedDrivers.find( + (driver) => + driver.name === selectedProvider.TEMPLATE.PROVIDER_BODY.driver + ) + : {} + + return arrayToOptions(selectedDriver?.deploymentConfs, { + addEmpty: true, + getText: ({ deploymentName }) => deploymentName, + getValue: ({ deploymentAlias }) => deploymentAlias, + }) + }, + validation: string() + .trim() + .required() + .default(() => undefined), + grid: { md: 12 }, + stepControl: stepControl, + } +} + +/** + * @param {Array} providers - Array of Providers + * @param {Array} groupedDrivers - Array of drivers with deployment configurations fields + * @param {Array} deploymentSteps - Array of deployment steps + * @returns {Field[]} Fields + */ +const FIELDS = (providers, groupedDrivers, deploymentSteps) => [ + DEPLOYMENT_CONF(providers, groupedDrivers, deploymentSteps), +] + +/** + * @param {Array} providers - Array of Providers + * @param {Array} groupedDrivers - Array of drivers with deployment configurations fields + * @returns {ObjectSchema} Schema + */ +const SCHEMA = (providers, groupedDrivers) => + getObjectSchemaFromFields(FIELDS(providers, groupedDrivers)) + +export { SCHEMA, FIELDS } diff --git a/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/General/index.js b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/General/index.js new file mode 100644 index 0000000000..a74c962f31 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/General/index.js @@ -0,0 +1,45 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 PropTypes from 'prop-types' +import FormWithSchema from '@modules/components/Forms/FormWithSchema' +import { T } from '@ConstantsModule' +import { SCHEMA, FIELDS } from './schema' + +export const STEP_ID = 'general' + +const Content = () => ( + +) + +/** + * General OneForm Cluster configuration. + * + * @returns {object} General configuration step + */ +const General = () => ({ + id: STEP_ID, + label: T.General, + resolver: SCHEMA, + optionsValidate: { abortEarly: false }, + content: () => Content(), +}) + +General.propTypes = { + data: PropTypes.object, + setFormData: PropTypes.func, +} + +export default General diff --git a/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/General/schema.js b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/General/schema.js new file mode 100644 index 0000000000..28b565870d --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/General/schema.js @@ -0,0 +1,47 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { INPUT_TYPES, T } from '@ConstantsModule' +import { Field, getObjectSchemaFromFields } from '@UtilsModule' +import { string } from 'yup' + +/** @type {Field} Name field */ +const NAME = { + name: 'NAME', + label: T['cluster.create.name'], + type: INPUT_TYPES.TEXT, + validation: string() + .trim() + .required() + .default(() => undefined), + grid: { md: 12 }, +} + +/** @type {Field} Description field */ +const DESCRIPTION = { + name: 'DESCRIPTION', + label: T['cluster.create.description'], + type: INPUT_TYPES.TEXT, + validation: string() + .trim() + .default(() => undefined), + grid: { md: 12 }, +} + +const FIELDS = [NAME, DESCRIPTION] + +const SCHEMA = getObjectSchemaFromFields(FIELDS) + +export { SCHEMA, FIELDS } diff --git a/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/OneformTags.js b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/OneformTags.js new file mode 100644 index 0000000000..65c88b94ad --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/OneformTags.js @@ -0,0 +1,92 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { useCallback, useMemo } from 'react' +import PropTypes from 'prop-types' +import { T } from '@ConstantsModule' +import { cleanEmpty, cloneObject, set } from '@UtilsModule' +import { object } from 'yup' +import { useFormContext, useWatch } from 'react-hook-form' +import { useTheme, Box, Alert } from '@mui/material' +import { css } from '@emotion/css' +import { AttributePanel } from '@modules/components/Tabs/Common' +import { Tr } from '@modules/components/HOC' + +export const STEP_ID = 'oneform-tags' + +const Content = () => { + const theme = useTheme() + const { setValue } = useFormContext() + const oneformTags = useWatch({ name: STEP_ID }) + + const handleChangeAttribute = useCallback( + (path, newValue) => { + const newOneformTags = cloneObject(oneformTags) + + set(newOneformTags, path, newValue) + setValue(STEP_ID, cleanEmpty(newOneformTags)) + }, + [oneformTags] + ) + + // Style for info message + const useStyles = ({ palette }) => ({ + groupInfo: css({ + '&': { + gridColumn: '1 / -1', + marginTop: '1em', + backgroundColor: palette.background.paper, + }, + }), + }) + + const classes = useMemo(() => useStyles(theme), [theme]) + + return ( + + + {Tr(T['oneformtags.info'])} + + + + ) +} + +Content.propTypes = { + isUpdate: PropTypes.bool, +} + +/** + * OneForm Tags for Provision. + * + * @returns {object} Oneform Tags step + */ +// IDEA: check the src/modules/components/Forms/VmTemplate/CreateForm/Steps/CustomVariables.js for inspiration +const OneformTags = () => ({ + id: STEP_ID, + label: T.OneformTags, + resolver: object(), + optionsValidate: { abortEarly: false }, + content: () => Content(), +}) + +export default OneformTags diff --git a/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/ProvidersTable/index.js b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/ProvidersTable/index.js new file mode 100644 index 0000000000..19305dc329 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/ProvidersTable/index.js @@ -0,0 +1,54 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 PropTypes from 'prop-types' +import { T } from '@ConstantsModule' +import { SCHEMA, FIELDS } from './schema' +import FormWithSchema from '@modules/components/Forms/FormWithSchema' + +export const STEP_ID = 'provider' + +const Content = (providersSteps) => ( + +) + +/** + * Providers table selector. + * + * @param {object} steps - Next steps associated for providers + * @param {boolean} onpremiseProvider - Use onpremise provider + * @returns {object} Drivers table selector step + */ +const ProvidersStep = (steps, onpremiseProvider) => ({ + id: STEP_ID, + label: T.SelectProvider, + resolver: SCHEMA(steps), + optionsValidate: { abortEarly: false }, + content: () => Content(steps), + defaultDisabled: { + condition: () => onpremiseProvider, + }, +}) + +ProvidersStep.propTypes = { + data: PropTypes.object, + setFormData: PropTypes.func, +} + +export default ProvidersStep diff --git a/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/ProvidersTable/schema.js b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/ProvidersTable/schema.js new file mode 100644 index 0000000000..21607a5a69 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/ProvidersTable/schema.js @@ -0,0 +1,53 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { ProvidersTable } from '@modules/components/Tables' +import { INPUT_TYPES, T } from '@ConstantsModule' +import { Field, getObjectSchemaFromFields } from '@UtilsModule' +import { string, ArraySchema } from 'yup' + +const PROVIDER = (providersSteps) => { + const stepControl = [] + + return { + name: 'PROVIDER', + label: T.Providers, + type: INPUT_TYPES.TABLE, + Table: () => ProvidersTable.Table, + getRowId: (row) => String(row.ID), + singleSelect: true, + validation: string() + .trim() + .required() + .default(() => undefined), + grid: { md: 12 }, + stepControl: stepControl || undefined, + fieldProps: { + preserveState: true, + }, + } +} + +/** + * @param {object} providersSteps - Associated steps for each driver + * @returns {Field[]} Fields + */ +const FIELDS = (providersSteps) => [PROVIDER(providersSteps)] + +/** @type {ArraySchema} Drivers table schema */ +const SCHEMA = (providersSteps) => + getObjectSchemaFromFields(FIELDS(providersSteps)) + +export { SCHEMA, FIELDS } diff --git a/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/UserInputs/index.js b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/UserInputs/index.js new file mode 100644 index 0000000000..5c09fed369 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/UserInputs/index.js @@ -0,0 +1,67 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 PropTypes from 'prop-types' +import { T } from '@ConstantsModule' +import FormWithSchema from '@modules/components/Forms/FormWithSchema' +import { generateTabs } from '@modules/components/Forms/UserInputs' + +import { + FIELDS, + SCHEMA, +} from '@modules/components/Forms/Cluster/CreateCloudForm/Steps/UserInputs/schema' + +const Content = (stepName, userInputs, userInputsLayout) => { + if (userInputsLayout && userInputsLayout.length > 0) { + return generateTabs(userInputsLayout, stepName, FIELDS) + } else { + return ( + + ) + } +} + +/** + * User Inputs configuration. + * + * @param {string} stepName - Name of the step + * @param {object} userInputs - user inputs fields + * @param {object} userInputsLayout - The user inputs layout + * @returns {object} User Inputs configuration step + */ +const UserInputs = (stepName, userInputs, userInputsLayout) => ({ + id: stepName, + label: T.UserInputs, + resolver: SCHEMA(userInputs), + optionsValidate: { abortEarly: false }, + content: () => Content(stepName, userInputs, userInputsLayout), + defaultDisabled: { + condition: () => true, + }, +}) + +UserInputs.propTypes = { + data: PropTypes.object, + setFormData: PropTypes.func, +} + +Content.propTypes = { isUpdate: PropTypes.bool } + +export default UserInputs diff --git a/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/UserInputs/schema.js b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/UserInputs/schema.js new file mode 100644 index 0000000000..956a2732d3 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/UserInputs/schema.js @@ -0,0 +1,34 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { ObjectSchema } from 'yup' + +import { getObjectSchemaFromFields } from '@UtilsModule' +import { Field, UserInputObject } from '@ConstantsModule' + +/** + * @param {UserInputObject[]} userInputs - User inputs + * @returns {Field[]} User inputs in Field format + */ +const FIELDS = (userInputs = []) => userInputs + +/** + * @param {UserInputObject[]} userInputs - User inputs + * @returns {ObjectSchema} User inputs schema + */ +const SCHEMA = (userInputs = []) => + getObjectSchemaFromFields(FIELDS(userInputs)) + +export { FIELDS, SCHEMA } diff --git a/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/index.js b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/index.js new file mode 100644 index 0000000000..3f68a2ce75 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/Steps/index.js @@ -0,0 +1,183 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 General, { + STEP_ID as GENERAL_ID, +} from '@modules/components/Forms/Cluster/CreateCloudForm/Steps/General' +import ProvidersStep, { + STEP_ID as PROVIDER_ID, +} from '@modules/components/Forms/Cluster/CreateCloudForm/Steps/ProvidersTable' + +import Deployments, { + STEP_ID as DEPLOYMENT_ID, +} from '@modules/components/Forms/Cluster/CreateCloudForm/Steps/Deployments' + +import UserInputs from '@modules/components/Forms/Cluster/CreateCloudForm/Steps/UserInputs' + +import OneformTags, { + STEP_ID as TAGS_ID, +} from '@modules/components/Forms/Cluster/CreateCloudForm/Steps/OneformTags' + +import { createFieldsFromDeploymentConfs } from '@modules/components/Forms/Oneform' + +import { createSteps, groupUserInputs } from '@UtilsModule' + +/** + * Create steps for Cluster using OneForm: + * 1. General: Name of the cluster + */ +const Steps = createSteps( + ({ providers = [], drivers = [], onpremiseProvider = false }) => { + /** + * 1. GENERAL STEP + */ + + const steps = [() => General()] + + // Group drivers to generate provider step + const groupedDrivers = createFieldsFromDeploymentConfs(drivers) + const providerSteps = providers.map((provider) => { + const selectedDriver = drivers.find( + (driver) => driver.name === provider.TEMPLATE.PROVIDER_BODY.driver + ) + + return { + id: provider.ID, + name: provider.NAME, + hasSteps: selectedDriver?.deployment_confs?.length > 0, + } + }) + + /** + * 2. PROVIDER STEP + */ + + // Add provider step if is not the onpremise case + steps.push(() => ProvidersStep(providerSteps, onpremiseProvider)) + + /** + * 3. DEPLOYMENT CONF STEP + */ + + // Get deployment configurations available + const deploymentSteps = [] + groupedDrivers.forEach((driverWithDeployments) => { + const deploymentConfs = driverWithDeployments.deploymentConfs + deploymentConfs.forEach((deploymentConf) => { + const componentName = deploymentConf.deploymentAlias + const step = { + name: componentName, + } + deploymentSteps.push(step) + }) + }) + + // Add deployment conf step + steps.push(() => Deployments(providers, groupedDrivers, deploymentSteps)) + + /** + * 4. USER INPUTS STEP: This step is only displayed after select the deployment conf of the step 3 + */ + + // Generate user inputs step for each provider and deployment conf + groupedDrivers.forEach((driverWithDeployments) => { + const deploymentConfs = driverWithDeployments.deploymentConfs + const fireedge = driverWithDeployments.fireedge + const name = driverWithDeployments.name + deploymentConfs.forEach((deploymentConf) => { + // Get the user inputs to display + const userInputs = deploymentConf.deploymentUserInputs + + // Group user inputs + const userInputsLayout = fireedge?.layout + ? groupUserInputs(userInputs, fireedge, name) + : undefined + + // Get the component name + const componentName = deploymentConf.deploymentAlias + steps.push(() => + UserInputs(componentName, userInputs, userInputsLayout) + ) + }) + }) + + /** + * 5. TAGS STEP + */ + steps.push(() => OneformTags()) + + // Delete empty steps + return steps.filter(Boolean) + }, + { + transformInitialValue: (initialValues, schema) => { + // Add onpremise provider if the user selects onpremise provider option + if ( + initialValues?.onpremiseProvider && + initialValues?.onpremProviders && + initialValues?.onpremProviders?.length > 0 + ) { + schema.default() + + const knownTemplate = schema.cast( + { + [PROVIDER_ID]: { PROVIDER: initialValues?.onpremProviders[0].ID }, + }, + { + stripUnknown: true, + } + ) + + return knownTemplate + } else { + return schema.default() + } + }, + transformBeforeSubmit: (formData) => { + const { + [GENERAL_ID]: generalData, + [PROVIDER_ID]: providerData, + [DEPLOYMENT_ID]: deploymentData, + [TAGS_ID]: tagsData, + } = formData + + const providerId = providerData.PROVIDER + const userInputsData = formData[deploymentData.DEPLOYMENT_CONF] + const [driver, deploymentType] = deploymentData.DEPLOYMENT_CONF.split('-') + + if (tagsData) { + userInputsData.oneform_tags = tagsData ?? {} + } + + const template = { + name: generalData.NAME, + driver: driver, + deployment_type: deploymentType, + provider_id: providerId, + user_inputs_values: userInputsData, + } + + const description = generalData.DESCRIPTION + + if (description) { + return { ...template, description: description } + } + + return template + }, + } +) + +export default Steps diff --git a/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/index.js b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/index.js new file mode 100644 index 0000000000..9f6e685a90 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/CreateCloudForm/index.js @@ -0,0 +1,16 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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. * + * ------------------------------------------------------------------------- */ +export { default } from '@modules/components/Forms/Cluster/CreateCloudForm/Steps' diff --git a/src/fireedge/src/modules/components/Forms/Cluster/DeleteHostForm/index.js b/src/fireedge/src/modules/components/Forms/Cluster/DeleteHostForm/index.js new file mode 100644 index 0000000000..058b78952d --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/DeleteHostForm/index.js @@ -0,0 +1,28 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { createForm } from '@UtilsModule' +import { + FIELDS, + SCHEMA, +} from '@modules/components/Forms/Cluster/DeleteHostForm/schema' + +const DeleteHostForm = createForm(SCHEMA, FIELDS, { + transformInitialValue: (clusterId, schema) => ({ + ...schema.cast({ cluster: clusterId }, { stripUnknown: true }), + }), +}) + +export default DeleteHostForm diff --git a/src/fireedge/src/modules/components/Forms/Cluster/DeleteHostForm/schema.js b/src/fireedge/src/modules/components/Forms/Cluster/DeleteHostForm/schema.js new file mode 100644 index 0000000000..511d2ffae9 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/DeleteHostForm/schema.js @@ -0,0 +1,63 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { array, lazy, object, ObjectSchema, string } from 'yup' + +import { INPUT_TYPES, T } from '@ConstantsModule' +import { HostsTable } from '@modules/components/Tables' +import { Field, getValidationFromFields } from '@UtilsModule' + +/** @type {Field} Host field */ +const HOSTS = ({ formType = '', filter }) => { + if (formType === 'amount') { + return { + name: 'hosts', + label: T.NumberOfHostsToAdd, + type: INPUT_TYPES.TEXT, + htmlType: 'number', + fieldProps: { min: 1 }, + grid: { md: 12 }, + validation: string() + .trim() + .required() + .default(() => 1), + } + } + + return { + name: 'hosts', + label: T.SelectNewHostsToDelete, + type: INPUT_TYPES.TABLE, + Table: () => HostsTable.Table, + fieldProps: { + filter, + preserveState: true, + }, + singleSelect: false, + grid: { md: 12 }, + validation: lazy(() => + array(string().trim()) + .required() + .default(() => undefined) + ), + } +} + +/** @type {Field[]} List of fields */ +export const FIELDS = (params) => [HOSTS(params)] + +/** @type {ObjectSchema} Schema */ +export const SCHEMA = (params) => + object(getValidationFromFields(FIELDS(params))) diff --git a/src/fireedge/src/modules/components/Forms/Cluster/DeleteVnetsForm/index.js b/src/fireedge/src/modules/components/Forms/Cluster/DeleteVnetsForm/index.js new file mode 100644 index 0000000000..aed33049ca --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/DeleteVnetsForm/index.js @@ -0,0 +1,28 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { createForm } from '@UtilsModule' +import { + FIELDS, + SCHEMA, +} from '@modules/components/Forms/Cluster/DeleteVnetsForm/schema' + +const DeleteVnetsForm = createForm(SCHEMA, FIELDS, { + transformInitialValue: (vnets, schema) => ({ + ...schema.cast({ vnets }, { stripUnknown: true }), + }), +}) + +export default DeleteVnetsForm diff --git a/src/fireedge/src/modules/components/Forms/Cluster/DeleteVnetsForm/schema.js b/src/fireedge/src/modules/components/Forms/Cluster/DeleteVnetsForm/schema.js new file mode 100644 index 0000000000..514b379227 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Cluster/DeleteVnetsForm/schema.js @@ -0,0 +1,63 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { array, lazy, object, ObjectSchema, string } from 'yup' + +import { INPUT_TYPES, T } from '@ConstantsModule' +import { VnsTable } from '@modules/components/Tables' +import { Field, getValidationFromFields } from '@UtilsModule' + +/** @type {Field} Host field */ +const VNETS = ({ formType = '', filter }) => { + if (formType === 'amount') { + return { + name: 'vnets', + label: T.NumberOfVnetsToAdd, + type: INPUT_TYPES.TEXT, + htmlType: 'number', + fieldProps: { min: 1 }, + grid: { md: 12 }, + validation: string() + .trim() + .required() + .default(() => 1), + } + } + + return { + name: 'vnets', + label: T.SelectNewVnetsToAdd, + type: INPUT_TYPES.TABLE, + Table: () => VnsTable.Table, + fieldProps: { + filter, + preserveState: true, + }, + singleSelect: false, + grid: { md: 12 }, + validation: lazy(() => + array(string().trim()) + .required() + .default(() => undefined) + ), + } +} + +/** @type {Field[]} List of fields */ +export const FIELDS = (params) => [VNETS(params)] + +/** @type {ObjectSchema} Schema */ +export const SCHEMA = (params) => + object(getValidationFromFields(FIELDS(params))) diff --git a/src/fireedge/src/modules/components/Forms/Cluster/index.js b/src/fireedge/src/modules/components/Forms/Cluster/index.js index 6ffce791fb..4f8358eb91 100644 --- a/src/fireedge/src/modules/components/Forms/Cluster/index.js +++ b/src/fireedge/src/modules/components/Forms/Cluster/index.js @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * * limitations under the License. * * ------------------------------------------------------------------------- */ -import { ReactElement } from 'react' import { AsyncLoadForm, ConfigurationProps } from '@modules/components/HOC' import { CreateFormCallback } from '@UtilsModule' +import { ReactElement } from 'react' /** * @param {ConfigurationProps} configProps - Configuration @@ -41,4 +41,48 @@ const ChangeClusterForm = (configProps) => const CreateForm = (configProps) => AsyncLoadForm({ formPath: 'Cluster/CreateForm' }, configProps) -export { ChangeClusterForm, CreateForm, UpdatePlanConfigurationForm } +/** + * @param {ConfigurationProps} configProps - Configuration + * @returns {ReactElement|CreateFormCallback} Asynchronous loaded form + */ +const CreateCloudForm = (configProps) => + AsyncLoadForm({ formPath: 'Cluster/CreateCloudForm' }, configProps) + +/** + * @param {ConfigurationProps} configProps - Configuration + * @returns {ReactElement|CreateFormCallback} Asynchronous loaded form + */ +const AddHostForm = (configProps) => + AsyncLoadForm({ formPath: 'Cluster/AddHostForm' }, configProps) + +/** + * @param {ConfigurationProps} configProps - Configuration + * @returns {ReactElement|CreateFormCallback} Asynchronous loaded form + */ +const AddVnetsForm = (configProps) => + AsyncLoadForm({ formPath: 'Cluster/AddVnetsForm' }, configProps) + +/** + * @param {ConfigurationProps} configProps - Configuration + * @returns {ReactElement|CreateFormCallback} Asynchronous loaded form + */ +const DeleteVnetsForm = (configProps) => + AsyncLoadForm({ formPath: 'Cluster/DeleteVnetsForm' }, configProps) + +/** + * @param {ConfigurationProps} configProps - Configuration + * @returns {ReactElement|CreateFormCallback} Asynchronous loaded form + */ +const DeleteHostForm = (configProps) => + AsyncLoadForm({ formPath: 'Cluster/DeleteHostForm' }, configProps) + +export { + AddHostForm, + AddVnetsForm, + ChangeClusterForm, + CreateCloudForm, + CreateForm, + DeleteHostForm, + DeleteVnetsForm, + UpdatePlanConfigurationForm, +} diff --git a/src/fireedge/src/modules/components/Forms/Oneform.js b/src/fireedge/src/modules/components/Forms/Oneform.js new file mode 100755 index 0000000000..45afa32ab3 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Oneform.js @@ -0,0 +1,98 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { schemaOdsUserInputField } from '@UtilsModule' + +/** + * Create a list of fields to use in the schema and in forms from the list of ODS User Inputs. + * + * @param {Array} drivers - List of drivers. + * @returns {Array} - List of fields. + */ +const createFieldsFromDriversOdsUserInputs = (drivers = []) => { + const driverNames = drivers.map((driver) => driver.name) + const groupedConnectionValues = drivers.map((driver, index) => ({ + name: driverNames[index], + connection: driver.connection, + })) + + const groupedFields = groupedConnectionValues.map( + ({ name: driverName, connection }) => ({ + name: driverName, + driverFields: connection.map((connectionValue) => + schemaOdsUserInputField(connectionValue) + ), + }) + ) + + return groupedFields +} + +/** + * Create an object with the fields for each available deployment configuration + * for a specific provider with its associated driver. + * + * @param {Array} drivers - Array of available drivers + * @returns {Array} An array of objects where each object contains the driver name + * and an array with the deployment configurations and fields + */ +const createFieldsFromDeploymentConfs = (drivers = []) => { + const driverNames = drivers.map((driver) => driver.name) + const groupedDeploymentConfs = drivers.map((driver, index) => ({ + name: driverNames[index], + userInputs: driver.user_inputs, + deploymentConfs: driver.deployment_confs, + fireedge: driver?.fireedge, + })) + + const groupedFields = groupedDeploymentConfs.map( + ({ name: driverName, userInputs, deploymentConfs, fireedge }) => { + const deploymentUserInputsFields = deploymentConfs.map( + (deploymentConf) => { + const deploymentConfUserInputs = deploymentConf.user_inputs ?? [] + // this is a special case, since oneform_tags user inputs + // are going to be treated in the OneformTags step + const filteredUserInputs = userInputs.filter( + (ui) => ui.name !== 'oneform_tags' + ) + const deploymentUserInputs = filteredUserInputs.concat( + deploymentConfUserInputs + ) + const resultUserInputs = deploymentUserInputs.map((ui) => + schemaOdsUserInputField(ui) + ) + + return { + deploymentName: deploymentConf.name, + deploymentAlias: `${driverName}-${deploymentConf.inventory}`, + deploymentInventory: deploymentConf.inventory, + deploymentDescription: deploymentConf.description, + deploymentUserInputs: resultUserInputs, + } + } + ) + + return { + name: driverName, + deploymentConfs: deploymentUserInputsFields, + fireedge: fireedge, + } + } + ) + + return groupedFields +} + +export { createFieldsFromDriversOdsUserInputs, createFieldsFromDeploymentConfs } diff --git a/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/ConnectionValues/index.js b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/ConnectionValues/index.js new file mode 100644 index 0000000000..948504df23 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/ConnectionValues/index.js @@ -0,0 +1,62 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 PropTypes from 'prop-types' +import FormWithSchema from '@modules/components/Forms/FormWithSchema' +import { getObjectSchemaFromFields } from '@UtilsModule' +import { T } from '@ConstantsModule' + +const STEP_ID = 'connection_values' + +const Content = (driverName, fields) => ( + +) + +/** + * Connection Values configuration. + * + * @param {object} driver - Driver data + * @param {boolean} create - Determine if this step is shown. True as default + * @returns {object} Connection values configuration step + */ +const ConnectionValues = (driver, create = true) => { + const driverName = driver?.name + const driverFields = driver?.driverFields + + return { + id: driverName, + label: T.ConnectionValues, + resolver: getObjectSchemaFromFields(driverFields), + optionsValidate: { abortEarly: false }, + content: () => Content(driverName, driverFields), + defaultDisabled: { + condition: () => create, + }, + } +} + +ConnectionValues.propTypes = { + data: PropTypes.object, + setFormData: PropTypes.func, +} + +Content.propTypes = { isUpdate: PropTypes.bool } + +export default ConnectionValues diff --git a/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/DriversTable/index.js b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/DriversTable/index.js new file mode 100644 index 0000000000..c3a6d69946 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/DriversTable/index.js @@ -0,0 +1,54 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 PropTypes from 'prop-types' +import { T } from '@ConstantsModule' +import { SCHEMA, FIELDS } from './schema' +import FormWithSchema from '@modules/components/Forms/FormWithSchema' + +export const STEP_ID = 'driver' + +const Content = (driversSteps) => ( + +) + +/** + * Drivers table selector. + * + * @param {object} steps - Next steps associated for drivers + * @param {boolean} update - Determine if this step is shown. False as default + * @returns {object} Drivers table selector step + */ +const DriversStep = (steps, update = false) => ({ + id: STEP_ID, + label: T.SelectDriver, + resolver: SCHEMA(steps), + optionsValidate: { abortEarly: false }, + content: () => Content(steps), + defaultDisabled: { + condition: () => update, + }, +}) + +DriversStep.propTypes = { + data: PropTypes.object, + setFormData: PropTypes.func, +} + +export default DriversStep diff --git a/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/DriversTable/schema.js b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/DriversTable/schema.js new file mode 100644 index 0000000000..cc0cd226f3 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/DriversTable/schema.js @@ -0,0 +1,68 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { DriversTable } from '@modules/components/Tables' +import { INPUT_TYPES, T } from '@ConstantsModule' +import { Field, getObjectSchemaFromFields } from '@UtilsModule' +import { string, ArraySchema } from 'yup' +import { findIndex } from 'lodash' + +const DRIVER = (driversSteps) => { + const stepControl = [] + + driversSteps?.forEach((driver, indexDriver) => { + if (driver?.hasSteps) { + const stepControlDriver = { + condition: (value) => + findIndex(driversSteps, { name: value }) !== indexDriver, + steps: [driversSteps[indexDriver]?.name], + } + + stepControl.push(stepControlDriver) + } + }) + + return { + name: 'DRIVER', + label: T.Drivers, + type: INPUT_TYPES.TABLE, + Table: () => DriversTable.Table, + getRowId: (row) => String(row.name), + validation: string() + .trim() + .required() + .default(() => undefined), + grid: { md: 12 }, + fieldProps: { + filterData: (drivers) => + drivers.filter( + (driver) => + driver.name.toLowerCase() !== 'onprem' && driver.state === 'ENABLED' + ), + }, + stepControl: stepControl || undefined, + } +} + +/** + * @param {object} driversSteps - Associated steps for each driver + * @returns {Field[]} Fields + */ +const FIELDS = (driversSteps) => [DRIVER(driversSteps)] + +/** @type {ArraySchema} Drivers table schema */ +const SCHEMA = (driversSteps) => getObjectSchemaFromFields(FIELDS(driversSteps)) + +export { SCHEMA, FIELDS } diff --git a/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/General/index.js b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/General/index.js new file mode 100644 index 0000000000..f4b33cbed8 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/General/index.js @@ -0,0 +1,51 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 PropTypes from 'prop-types' +import FormWithSchema from '@modules/components/Forms/FormWithSchema' +import { T } from '@ConstantsModule' +import { SCHEMA, NAME_FIELD, DESCRIPTION_FIELD } from './schema' + +export const STEP_ID = 'general' + +const Content = () => ( + +) + +/** + * General Provider configuration. + * + * @returns {object} General configuration step + */ +const General = () => ({ + id: STEP_ID, + label: T.General, + resolver: SCHEMA, + optionsValidate: { abortEarly: false }, + content: () => Content(), +}) + +General.propTypes = { + data: PropTypes.object, + setFormData: PropTypes.func, +} + +Content.propTypes = { isUpdate: PropTypes.bool } + +export default General diff --git a/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/General/schema.js b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/General/schema.js new file mode 100644 index 0000000000..ebd0a817c2 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/General/schema.js @@ -0,0 +1,51 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { INPUT_TYPES, T } from '@ConstantsModule' +import { Field, getObjectSchemaFromFields } from '@UtilsModule' +import { string } from 'yup' + +/** @type {Field} Name field */ +const NAME_FIELD = { + name: 'name', + label: T.Name, + type: INPUT_TYPES.TEXT, + validation: string() + .trim() + .min(3) + .required() + .default(() => undefined), + grid: { md: 12 }, +} + +/** @type {Field} Description field */ +const DESCRIPTION_FIELD = { + name: 'description', + label: T.Description, + type: INPUT_TYPES.TEXT, + validation: string() + .trim() + .test( + 'is-not-numeric', + 'Description should not be a numeric value', + (value) => isNaN(value) || value.trim() === '' + ) + .default(() => ''), + grid: { md: 12 }, +} + +const SCHEMA = getObjectSchemaFromFields([NAME_FIELD, DESCRIPTION_FIELD]) + +export { SCHEMA, NAME_FIELD, DESCRIPTION_FIELD } diff --git a/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/index.js b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/index.js new file mode 100644 index 0000000000..b8752ba94c --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/Steps/index.js @@ -0,0 +1,114 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 General, { + STEP_ID as GENERAL_ID, +} from '@modules/components/Forms/Provider/CreateForm/Steps/General' + +import DriversStep, { + STEP_ID as DRIVER_ID, +} from '@modules/components/Forms/Provider/CreateForm/Steps/DriversTable' + +import ConnectionValues from '@modules/components/Forms/Provider/CreateForm/Steps/ConnectionValues' + +import { createFieldsFromDriversOdsUserInputs } from '@modules/components/Forms/Oneform' + +import { createSteps } from '@UtilsModule' +import { isEmpty } from 'lodash' + +const Steps = createSteps( + ({ dataTemplate = {}, drivers = [] }) => { + const steps = [] + let driversSteps, groupedDrivers + // if dataTemplateExtended is populated, render DriverStep but disabled + if (!isEmpty(dataTemplate)) { + const selectedProvider = dataTemplate.TEMPLATE.PROVIDER_BODY ?? {} + const providerDriver = drivers.find( + (driver) => driver.name === selectedProvider?.driver + ) + groupedDrivers = createFieldsFromDriversOdsUserInputs([providerDriver]) + const connectionValuesFields = groupedDrivers[0] + const driverFields = groupedDrivers[0].driverFields + driversSteps = [ + { + name: selectedProvider.name, + }, + ] + steps.push(() => DriversStep(driversSteps, true)) + steps.push(() => General()) + if (driverFields && driverFields.length > 0) { + steps.push(() => ConnectionValues(connectionValuesFields, false)) + } + } else { + // Group drivers with their connection values to get if step is available or not + groupedDrivers = createFieldsFromDriversOdsUserInputs(drivers) + driversSteps = groupedDrivers?.map((driver) => ({ + name: driver?.name, + hasSteps: driver?.driverFields?.length > 0, + })) + steps.push(() => DriversStep(driversSteps)) + steps.push(() => General()) + // If available connection values, it will be as part of the Form Stepper + groupedDrivers.forEach((driver) => { + steps.push(() => ConnectionValues(driver)) + }) + } + + return steps.filter(Boolean) + }, + { + saveState: true, + transformInitialValue: (Provider, schema) => { + const { NAME: name } = Provider + + const template = Provider?.TEMPLATE?.PROVIDER_BODY ?? {} + + const { description, driver, connection: connectionValues } = template + + const objectSchema = { + [GENERAL_ID]: { name, description }, + [DRIVER_ID]: { DRIVER: driver }, + [driver]: connectionValues, + } + + const knownTemplate = schema.cast(objectSchema, { stripUnknown: true }) + + return knownTemplate + }, + + transformBeforeSubmit: (formData) => { + const { [GENERAL_ID]: generalData, [DRIVER_ID]: driverData } = formData + + const connectionValuesData = formData[driverData.DRIVER] + + const template = { + name: generalData.name, + driver: driverData.DRIVER, + connection_values: connectionValuesData || {}, // create + connection: connectionValuesData || {}, // update + } + + const description = generalData.description + + if (description) { + return { ...template, description: description } + } + + return template + }, + } +) + +export default Steps diff --git a/src/fireedge/src/modules/components/Forms/Provider/CreateForm/index.js b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/index.js new file mode 100644 index 0000000000..df7df91707 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Provider/CreateForm/index.js @@ -0,0 +1,16 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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. * + * ------------------------------------------------------------------------- */ +export { default } from '@modules/components/Forms/Provider/CreateForm/Steps' diff --git a/src/fireedge/src/modules/components/Forms/Provider/index.js b/src/fireedge/src/modules/components/Forms/Provider/index.js new file mode 100644 index 0000000000..7dcf40b228 --- /dev/null +++ b/src/fireedge/src/modules/components/Forms/Provider/index.js @@ -0,0 +1,27 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { ReactElement } from 'react' +import { AsyncLoadForm, ConfigurationProps } from '@modules/components/HOC' +import { CreateStepsCallback } from '@UtilsModule' + +/** + * @param {ConfigurationProps} configProps - Configuration + * @returns {ReactElement|CreateStepsCallback} Asynchronous loaded form + */ +const CreateForm = (configProps) => + AsyncLoadForm({ formPath: 'Provider/CreateForm' }, configProps) + +export { CreateForm } diff --git a/src/fireedge/src/modules/components/Forms/index.js b/src/fireedge/src/modules/components/Forms/index.js index e9c9aa5509..799b30518f 100644 --- a/src/fireedge/src/modules/components/Forms/index.js +++ b/src/fireedge/src/modules/components/Forms/index.js @@ -30,6 +30,7 @@ import * as Image from '@modules/components/Forms/Image' import * as Labels from '@modules/components/Forms/Labels' import * as Marketplace from '@modules/components/Forms/Marketplace' import * as MarketplaceApp from '@modules/components/Forms/MarketplaceApp' +import * as Provider from '@modules/components/Forms/Provider' import * as SecurityGroup from '@modules/components/Forms/SecurityGroups' import * as Service from '@modules/components/Forms/Service' import * as ServiceTemplate from '@modules/components/Forms/ServiceTemplate' @@ -66,6 +67,7 @@ export const Form = { Labels, Marketplace, MarketplaceApp, + Provider, SecurityGroup, Service, ServiceTemplate, diff --git a/src/fireedge/src/modules/components/Icons/OpenNebulaIcon.js b/src/fireedge/src/modules/components/Icons/OpenNebulaIcon.js index d1e8c244b4..874a167302 100644 --- a/src/fireedge/src/modules/components/Icons/OpenNebulaIcon.js +++ b/src/fireedge/src/modules/components/Icons/OpenNebulaIcon.js @@ -26,6 +26,7 @@ const OpenNebulaLogo = memo( withText, viewBox = withText ? '600 400 750 300' : '600 400 250 270', disabledBetaText, + customColor, ...props }) => { const [displaySkeleton, setDisplaySkeleton] = useState(true) @@ -127,27 +128,51 @@ const OpenNebulaLogo = memo( {/* Log image */} @@ -240,6 +265,7 @@ OpenNebulaLogo.propTypes = { spinner: bool, withText: bool, disabledBetaText: bool, + customColor: string, } OpenNebulaLogo.defaultProps = { diff --git a/src/fireedge/src/modules/components/LogsViewer/index.js b/src/fireedge/src/modules/components/LogsViewer/index.js index ebbedaee53..b78a92c913 100644 --- a/src/fireedge/src/modules/components/LogsViewer/index.js +++ b/src/fireedge/src/modules/components/LogsViewer/index.js @@ -36,8 +36,10 @@ import { SortDown, SortUp, RefreshDouble, + RedoCircle, } from 'iconoir-react' import { T, STYLE_BUTTONS } from '@ConstantsModule' +import { ProvisionAPI } from '@FeaturesModule' import { Tr, Translate, SubmitButton } from '@modules/components' import { styles } from '@modules/components/LogsViewer/styles' import HeaderPopover from '@modules/components/Header/Popover' @@ -61,9 +63,16 @@ const cache = new CellMeasurerCache({ * @param {object} props.getLogs - Function to refresh logs * @param {boolean} props.isFetching - If the request to get logs to the API is in progress * @param {object} props.options - Component options + * @param {number} props.provisionId - Provision ID * @returns {object} - The Log Viewer component */ -const LogsViewer = ({ logs, getLogs, isFetching, options = {} }) => { +const LogsViewer = ({ + logs, + getLogs, + isFetching, + provisionId, + options = {}, +}) => { // Get options const { followLogs = false } = options @@ -83,6 +92,8 @@ const LogsViewer = ({ logs, getLogs, isFetching, options = {} }) => { const [filterValue, setFilterValue] = useState('') const [filteredLogs, setFilteredLogs] = useState(logs?.lines || []) + const [retry] = ProvisionAPI.useRetryProvisionMutation() + // Follow logs useEffect(() => { if (followLogs && listRef.current && filteredLogs.length > 0) { @@ -159,7 +170,6 @@ const LogsViewer = ({ logs, getLogs, isFetching, options = {} }) => { ) ) } - const Row = ({ index, key, style, parent }) => { const log = filteredLogs[index] const regexDate = /^(.+?\[\w\])\s*(.*)/ @@ -313,6 +323,13 @@ const LogsViewer = ({ logs, getLogs, isFetching, options = {} }) => { isSubmitting={isFetching} onClick={() => getLogs()} /> + } + tooltip={Tr(T.Retry)} + isSubmitting={isFetching} + onClick={() => retry({ id: provisionId })} + /> @@ -346,6 +363,7 @@ LogsViewer.propTypes = { getLogs: PropTypes.object, isFetching: PropTypes.bool, options: PropTypes.object, + provisionId: PropTypes.string, } export default LogsViewer diff --git a/src/fireedge/src/modules/components/Tables/Clusters/CreateAction/index.js b/src/fireedge/src/modules/components/Tables/Clusters/CreateAction/index.js new file mode 100644 index 0000000000..49a1270881 --- /dev/null +++ b/src/fireedge/src/modules/components/Tables/Clusters/CreateAction/index.js @@ -0,0 +1,183 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { ReactElement, useMemo } from 'react' +import { useHistory } from 'react-router-dom' +import styles from '@modules/components/Tables/Clusters/CreateAction/styles' +import { Typography, useTheme, Stack, Box } from '@mui/material' +import { Tr } from '@modules/components/HOC' +import { T } from '@ConstantsModule' +import { OpenNebulaLogo } from '@modules/components/Icons' +import { PATH } from '@modules/components/path' +import { Cloud, City, OpenNewWindow } from 'iconoir-react' +import { generateDocLink } from '@UtilsModule' +import { SystemAPI } from '@FeaturesModule' + +const CLUSTER_TYPES = { + OPENNEBULA: 'OPENNEBULA', + ONEFORM: 'ONEFORM', + ONEFORM_ONPREMISE: 'ONEFORM_ONPREMISE', +} + +/** + * Create Cluster Action. + * + * @returns {ReactElement} - Create Cluster Action component + */ +const CreateAction = () => { + const { data: version } = SystemAPI.useGetOneVersionQuery() + + // Get classes + const theme = useTheme() + const classes = useMemo(() => styles(theme), [theme]) + + // Get history to redirect to forms + const history = useHistory() + + const onClick = (type) => { + switch (type) { + case CLUSTER_TYPES.OPENNEBULA: + history.push(PATH.INFRASTRUCTURE.CLUSTERS.CREATE) + break + case CLUSTER_TYPES.ONEFORM: + history.push(PATH.INFRASTRUCTURE.CLUSTERS.CREATE_CLOUD) + break + case CLUSTER_TYPES.ONEFORM_ONPREMISE: + history.push(PATH.INFRASTRUCTURE.CLUSTERS.CREATE_CLOUD, { + onpremiseProvider: true, + }) + break + } + } + + return ( + + + + {Tr(T['cluster.create.selection.title'])} + + + {Tr(T['cluster.create.selection.subtitle'])} + + + + onClick(CLUSTER_TYPES.OPENNEBULA)} + > + + + + + + {Tr(T['cluster.create.opennebula.title'])} + + + {Tr(T['cluster.create.opennebula.subtitle'])} + + + e.stopPropagation()} + className={classes.linkContent} + > + {Tr(T.LearnMore)} + + + + + + + onClick(CLUSTER_TYPES.ONEFORM_ONPREMISE)} + > + + + + + + {Tr(T['cluster.create.onpremise.title'])} + + + {Tr(T['cluster.create.onpremise.subtitle'])} + + + e.stopPropagation()} + className={classes.linkContent} + > + {Tr(T.LearnMore)} + + + + + + + onClick(CLUSTER_TYPES.ONEFORM)} + > + + + + + + {Tr(T['cluster.create.provider.title'])} + + + {Tr(T['cluster.create.provider.subtitle'])} + + + e.stopPropagation()} + className={classes.linkContent} + > + {Tr(T.LearnMore)} + + + + + + + + ) +} + +export { CreateAction } diff --git a/src/fireedge/src/modules/components/Tables/Clusters/CreateAction/styles.js b/src/fireedge/src/modules/components/Tables/Clusters/CreateAction/styles.js new file mode 100644 index 0000000000..55c950e442 --- /dev/null +++ b/src/fireedge/src/modules/components/Tables/Clusters/CreateAction/styles.js @@ -0,0 +1,103 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { css } from '@emotion/css' + +/** + * Create styles for the breadcrumb. + * + * @param {object} theme - Theme + * @param {object} theme.palette - Palette + * @returns {object} CSS styles with the palette + */ +const styles = ({ palette }) => ({ + container: css({ + justifyContent: 'center', + alignItems: 'stretch', + marginLeft: '50px', + marginRight: '50px', + paddingBottom: '50px', + }), + cardContainer: css({ + display: 'grid', + gridTemplateRows: 'repeat(3, 1fr)', + gridTemplateColumns: '1fr', + gap: '20px', + alignItems: 'stretch', + }), + card: css({ + alignItems: 'flex-start', + padding: '12px 16px', + borderRadius: '8px', + border: `1px solid ${palette.cluster.createCluster.cardBorder}`, + cursor: 'pointer', + display: 'flex', + flexDirection: 'row', + justifyContent: 'flex-start', + width: '100%', + }), + cardIcon: css({ + padding: '2px', + margin: '0px 2px 0px 0px', + }), + icon: css({ + width: '24px', + height: '24px', + color: palette.cluster.createCluster.icon, + }), + cardContent: css({ + width: '100%', + }), + headerContainer: css({ + marginBottom: '25px', + }), + title: css({ + color: palette.cluster.createCluster.title, + fontSize: '20px', + fontStyle: 'normal', + fontWeight: 700, + lineHeight: '32px', + }), + subtitle: css({ + color: palette.cluster.createCluster.subtitle, + fontSize: '13px', + fontStyle: 'normal', + fontWeight: 400, + lineHeight: '16px', + }), + linkContainer: css({ + color: 'red', + fontSize: '13px', + fontStyle: 'normal', + fontWeight: 400, + lineHeight: '16px', + alignSelf: 'flex-end', + marginTop: '5px', + display: 'flex', + alignItems: 'center', + gap: '5px', + }), + linkContent: css({ + color: palette.cluster.createCluster.link, + textDecoration: 'none', + }), + linkIcon: css({ + width: '10px', + height: '10px', + color: palette.cluster.createCluster.link, + }), +}) + +export default styles diff --git a/src/fireedge/src/modules/components/Tables/Clusters/actions.js b/src/fireedge/src/modules/components/Tables/Clusters/actions.js index bd3ea88bd6..6aa2ef139c 100644 --- a/src/fireedge/src/modules/components/Tables/Clusters/actions.js +++ b/src/fireedge/src/modules/components/Tables/Clusters/actions.js @@ -18,7 +18,7 @@ import { Plus, Trash } from 'iconoir-react' import { useMemo } from 'react' import { useHistory } from 'react-router-dom' -import { ClusterAPI, useGeneralApi, useViews } from '@FeaturesModule' +import { ClusterAPI, ProvisionAPI, useViews } from '@FeaturesModule' import { createActions, @@ -27,12 +27,14 @@ import { import { CLUSTER_ACTIONS, + PROVISION_ACTIONS, RESOURCE_NAMES, STYLE_BUTTONS, T, } from '@ConstantsModule' import { Translate } from '@modules/components/HOC' import { PATH } from '@modules/components/path' +import { CreateAction } from '@modules/components/Tables/Clusters/CreateAction' const ListClusterNames = ({ rows = [] }) => rows?.map?.(({ id, original }) => { @@ -72,7 +74,9 @@ const Actions = (props = {}) => { const history = useHistory() const { view, getResourceView } = useViews() const [remove] = ClusterAPI.useRemoveClusterMutation() - const { setSecondTitle } = useGeneralApi() + const [removeProvision] = ProvisionAPI.useRemoveProvisionMutation() + const [deprovision] = ProvisionAPI.useUndeployProvisionMutation() + const [retry] = ProvisionAPI.useRetryProvisionMutation() return useMemo( () => @@ -87,10 +91,18 @@ const Actions = (props = {}) => { importance: STYLE_BUTTONS.IMPORTANCE.MAIN, size: STYLE_BUTTONS.SIZE.MEDIUM, type: STYLE_BUTTONS.TYPE.FILLED, - action: () => { - setSecondTitle({}) - history.push(PATH.INFRASTRUCTURE.CLUSTERS.CREATE) - }, + options: [ + { + isConfirmDialog: true, + dialogProps: { + title: T['cluster.create.selection.head'], + children: () => , + fixedWidth: false, + fixedHeight: false, + handleAccept: undefined, + }, + }, + ], }, { accessor: CLUSTER_ACTIONS.UPDATE_DIALOG, @@ -100,6 +112,8 @@ const Actions = (props = {}) => { importance: STYLE_BUTTONS.IMPORTANCE.SECONDARY, size: STYLE_BUTTONS.SIZE.MEDIUM, type: STYLE_BUTTONS.TYPE.OUTLINED, + disabled: (rows) => + rows.some(({ original }) => original?.TEMPLATE?.ONEFORM), action: (rows) => { const cluster = rows?.[0]?.original ?? {} const path = PATH.INFRASTRUCTURE.CLUSTERS.CREATE @@ -107,6 +121,62 @@ const Actions = (props = {}) => { history.push(path, cluster) }, }, + { + accessor: PROVISION_ACTIONS.DEPROVISION, + label: T.Deprovision, + tooltip: T.Deprovision, + importance: STYLE_BUTTONS.IMPORTANCE.SECONDARY, + size: STYLE_BUTTONS.SIZE.MEDIUM, + type: STYLE_BUTTONS.TYPE.OUTLINED, + selected: { min: 1 }, + dataCy: `cluster_${PROVISION_ACTIONS.DEPROVISION}`, + disabled: (rows) => + rows.some(({ original }) => !original?.TEMPLATE?.ONEFORM), + options: [ + { + isConfirmDialog: true, + dialogProps: { + title: T.DEPROVISION, + dataCy: `modal-${PROVISION_ACTIONS.DEPROVISION}`, + children: MessageToConfirmAction, + }, + onSubmit: (rows) => async () => { + const ids = rows?.map?.( + ({ original }) => original?.TEMPLATE?.ONEFORM?.PROVISION_ID + ) + await Promise.all(ids.map((id) => deprovision({ id }))) + setSelectedRows && setSelectedRows([]) + }, + }, + ], + }, + { + accessor: PROVISION_ACTIONS.RETRY, + tooltip: T.Retry, + label: T.Retry, + importance: STYLE_BUTTONS.IMPORTANCE.SECONDARY, + size: STYLE_BUTTONS.SIZE.MEDIUM, + type: STYLE_BUTTONS.TYPE.OUTLINED, + selected: { min: 1 }, + dataCy: `cluster_${PROVISION_ACTIONS.RETRY}`, + disabled: (rows) => + rows.some(({ original }) => !original?.TEMPLATE?.ONEFORM), + options: [ + { + isConfirmDialog: true, + dialogProps: { + title: T.Retry, + dataCy: `modal-${PROVISION_ACTIONS.RETRY}`, + children: MessageToConfirmAction, + }, + onSubmit: (rows) => async () => { + const ids = rows?.map?.(({ original }) => original?.ID) + await Promise.all(ids.map((id) => retry({ id }))) + setSelectedRows && setSelectedRows([]) + }, + }, + ], + }, { accessor: CLUSTER_ACTIONS.DELETE, tooltip: T.Delete, @@ -125,8 +195,23 @@ const Actions = (props = {}) => { children: MessageToConfirmAction, }, onSubmit: (rows) => async () => { - const ids = rows?.map?.(({ original }) => original?.ID) - await Promise.all(ids.map((id) => remove({ id }))) + const idsWithType = rows?.map?.(({ original }) => ({ + id: original?.ID, + type: original?.TEMPLATE?.ONEFORM?.PROVISION_ID + ? 'removeProvision' + : 'remove', + provisionId: + original?.TEMPLATE?.ONEFORM?.PROVISION_ID ?? -1, + })) + await Promise.all( + idsWithType.map(({ id, type, provisionId }) => { + if (type === 'removeProvision') { + return removeProvision({ id: provisionId, force: true }) + } + + return remove({ id }) + }) + ) setSelectedRows && setSelectedRows([]) }, }, diff --git a/src/fireedge/src/modules/components/Tables/Clusters/columns.js b/src/fireedge/src/modules/components/Tables/Clusters/columns.js index 59d96d003d..c5b3ceb5c2 100644 --- a/src/fireedge/src/modules/components/Tables/Clusters/columns.js +++ b/src/fireedge/src/modules/components/Tables/Clusters/columns.js @@ -38,4 +38,9 @@ export default [ accessor: (row) => getTotalOfResources(row?.VNETS), sortType: 'number', }, + { + Header: 'Type', + id: 'TEMPLATE', + accessor: 'TEMPLATE', + }, ] diff --git a/src/fireedge/src/modules/components/Tables/Clusters/row.js b/src/fireedge/src/modules/components/Tables/Clusters/row.js index e9f87b8522..950aff32d9 100644 --- a/src/fireedge/src/modules/components/Tables/Clusters/row.js +++ b/src/fireedge/src/modules/components/Tables/Clusters/row.js @@ -16,14 +16,32 @@ /* eslint-disable jsdoc/require-jsdoc */ import PropTypes from 'prop-types' -import { Typography, useTheme } from '@mui/material' -import { Cloud, Folder, HardDrive, NetworkAlt } from 'iconoir-react' +import { alpha, Box, styled, Typography, useTheme } from '@mui/material' +import { Folder, HardDrive, NetworkAlt } from 'iconoir-react' -import { useMemo } from 'react' import { rowStyles } from '@modules/components/Tables/styles' +import { useMemo } from 'react' -import { Tr } from '@modules/components/HOC' import { T } from '@ConstantsModule' +import { Tr } from '@modules/components/HOC' + +const TagType = styled(Typography, { + shouldForwardProp: (prop) => !['provision'].includes(prop), +})(({ theme, provision }) => { + const color = provision?.color + ? `#${provision.color}` + : theme.palette.primary.main + + return { + color: alpha(color, 1), + border: `1px solid ${alpha(color, 1)}`, + fontSize: theme.typography.button.fontSize, + textTransform: 'capitalize', + padding: `${theme.typography.pxToRem(1)} ${theme.typography.pxToRem(8)}`, + backgroundColor: alpha(color, 0.1), + userSelect: 'none', + } +}) const Row = ({ original, @@ -36,7 +54,7 @@ const Row = ({ }) => { const theme = useTheme() const classes = useMemo(() => rowStyles(theme), [theme]) - const { ID, NAME, HOSTS, DATASTORES, VNETS, PROVIDER_NAME } = value + const { ID, NAME, HOSTS, DATASTORES, VNETS, TEMPLATE } = value return (
@@ -45,6 +63,21 @@ const Row = ({ {NAME} + + {TEMPLATE?.ONEFORM && TEMPLATE?.ONEFORM?.PROVIDER && ( + + + {TEMPLATE?.ONEFORM?.PROVIDER} + + + )} +
{`#${ID}`} @@ -69,12 +102,6 @@ const Row = ({ {`${DATASTORES}`} - {PROVIDER_NAME && ( - - - {` ${PROVIDER_NAME}`} - - )}
diff --git a/src/fireedge/src/modules/components/Tables/Clusters/table.js b/src/fireedge/src/modules/components/Tables/Clusters/table.js index 2dfe5c56e8..95ba9e17bc 100644 --- a/src/fireedge/src/modules/components/Tables/Clusters/table.js +++ b/src/fireedge/src/modules/components/Tables/Clusters/table.js @@ -15,14 +15,14 @@ * ------------------------------------------------------------------------- */ import { ReactElement, useMemo } from 'react' +import { RESOURCE_NAMES, T } from '@ConstantsModule' +import { ClusterAPI, useViews } from '@FeaturesModule' import ClusterColumns from '@modules/components/Tables/Clusters/columns' import ClusterRow from '@modules/components/Tables/Clusters/row' import EnhancedTable, { createColumns, } from '@modules/components/Tables/Enhanced' import WrapperRow from '@modules/components/Tables/Enhanced/WrapperRow' -import { RESOURCE_NAMES, T } from '@ConstantsModule' -import { useViews, ClusterAPI } from '@FeaturesModule' const DEFAULT_DATA_CY = 'clusters' @@ -94,6 +94,11 @@ const ClustersTable = (props) => { accessor: ({ DATASTORES }) => Array.isArray(DATASTORES.ID) ? DATASTORES.ID.length : 1, }, + { + header: T.Type, + id: 'provision', + accessor: 'TEMPLATE.ONEFORM.PROVIDER', + }, ] const { component, header } = WrapperRow(ClusterRow) @@ -101,7 +106,7 @@ const ClustersTable = (props) => { return ( data, [data])} + data={data} rootProps={rootProps} searchProps={searchProps} refetch={refetch} diff --git a/src/fireedge/src/modules/components/Tables/Drivers/actions.js b/src/fireedge/src/modules/components/Tables/Drivers/actions.js index 3f0bd14bf2..cf2c993883 100644 --- a/src/fireedge/src/modules/components/Tables/Drivers/actions.js +++ b/src/fireedge/src/modules/components/Tables/Drivers/actions.js @@ -113,6 +113,7 @@ const Actions = () => { size: STYLE_BUTTONS.SIZE.MEDIUM, type: STYLE_BUTTONS.TYPE.FILLED, selected: false, + disabled: (rows) => rows.length > 0, options: [ { isConfirmDialog: true, diff --git a/src/fireedge/src/modules/components/Tables/Drivers/table.js b/src/fireedge/src/modules/components/Tables/Drivers/table.js index 5ca13ac141..52116164fa 100644 --- a/src/fireedge/src/modules/components/Tables/Drivers/table.js +++ b/src/fireedge/src/modules/components/Tables/Drivers/table.js @@ -14,8 +14,8 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ import { ReactElement, useEffect, useMemo } from 'react' -import { Alert } from '@mui/material' -import { Translate } from '@modules/components/HOC' +import { Alert, Typography } from '@mui/material' +import { Translate, Tr } from '@modules/components/HOC' import EnhancedTable, { createColumns, } from '@modules/components/Tables/Enhanced' @@ -23,7 +23,8 @@ import WrapperRow from '@modules/components/Tables/Enhanced/WrapperRow' import DriverColumns from '@modules/components/Tables/Drivers/columns' import DriverRow from '@modules/components/Tables/Drivers/row' import { RESOURCE_NAMES, T } from '@ConstantsModule' -import { useViews, DriverAPI } from '@FeaturesModule' +import { useViews, DriverAPI, SystemAPI } from '@FeaturesModule' +import { generateDocLink } from '@UtilsModule' const DEFAULT_DATA_CY = 'drivers' @@ -43,12 +44,18 @@ const DriversTable = (props) => { const { view, getResourceView } = useViews() const { - data = [], + data: drivers = [], isFetching, refetch, error, } = DriverAPI.useGetDriversQuery() + // Filter data if there is filter function + const data = + props?.filterData && typeof props?.filterData === 'function' + ? props?.filterData(drivers) + : drivers + useEffect(() => { if (handleRefetch && refetch) { handleRefetch(refetch) @@ -72,6 +79,9 @@ const DriversTable = (props) => { const { component, header } = WrapperRow(DriverRow) + // Get version to show links to documentation + const { data: version } = SystemAPI.useGetOneVersionQuery() + return ( { error?.status === 500 && ( + + {Tr(T['oneform.info.more'])} + + {Tr(T['oneform.info.more.link'])} + + ) } diff --git a/src/fireedge/src/modules/components/Tables/Hosts/table.js b/src/fireedge/src/modules/components/Tables/Hosts/table.js index c25ab69856..c28e55247f 100644 --- a/src/fireedge/src/modules/components/Tables/Hosts/table.js +++ b/src/fireedge/src/modules/components/Tables/Hosts/table.js @@ -38,8 +38,8 @@ import { import WrapperRow from '@modules/components/Tables/Enhanced/WrapperRow' import HostColumns from '@modules/components/Tables/Hosts/columns' import HostRow from '@modules/components/Tables/Hosts/row' -import { useFormContext } from 'react-hook-form' import { getResourceLabels } from '@UtilsModule' +import { useFormContext } from 'react-hook-form' const DEFAULT_DATA_CY = 'hosts' diff --git a/src/fireedge/src/modules/components/Tables/Providers/actions.js b/src/fireedge/src/modules/components/Tables/Providers/actions.js new file mode 100644 index 0000000000..f1bd7ec713 --- /dev/null +++ b/src/fireedge/src/modules/components/Tables/Providers/actions.js @@ -0,0 +1,196 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { Box, Typography } from '@mui/material' +import { useMemo } from 'react' +import { useHistory } from 'react-router-dom' +import { PATH } from '@modules/components/path' + +import { + PROVIDER_ACTIONS, + RESOURCE_NAMES, + STYLE_BUTTONS, + T, +} from '@ConstantsModule' +import { ProviderAPI, useGeneralApi, useViews } from '@FeaturesModule' +import { Translate } from '@modules/components/HOC' +import { ChangeGroupForm, ChangeUserForm } from '@modules/components/Forms/Vm' +import { + createActions, + GlobalAction, +} from '@modules/components/Tables/Enhanced/Utils' +import { Group, Plus, Trash } from 'iconoir-react' + +/** + * List all the provider names. + * + * @param {object} param - Properties + * @param {Array} param.rows - List of drivers + * @returns {Array} - List of drivers + */ +const ListProviderNames = ({ rows = [] }) => + rows.map(({ id, original }) => { + const { ID, NAME } = original + + return ( + + {`#${ID} ${NAME}`} + + ) + }) + +const SubHeader = (rows) => + +const MessageToConfirmAction = (rows, description) => ( + + + {description && } + + +) + +MessageToConfirmAction.displayName = 'MessageToConfirmAction' + +/** + * Generates the actions to operate resources on Host table. + * + * @param {object} props - datatable props + * @param {Function} props.setSelectedRows - set selected rows + * @returns {GlobalAction} - Actions + */ +const Actions = (props = {}) => { + const { setSelectedRows } = props + const history = useHistory() + const { view, getResourceView } = useViews() + const { setSecondTitle } = useGeneralApi() + + const [remove] = ProviderAPI.useRemoveProviderMutation() + const [changeOwnership] = ProviderAPI.useChangeProviderOwnershipMutation() + + const providerActions = useMemo( + () => + createActions({ + filters: getResourceView(RESOURCE_NAMES.PROVIDER)?.actions, + actions: [ + { + accessor: PROVIDER_ACTIONS.CREATE_DIALOG, + tooltip: T.Create, + label: T.Create, + icon: Plus, + importance: STYLE_BUTTONS.IMPORTANCE.MAIN, + size: STYLE_BUTTONS.SIZE.MEDIUM, + type: STYLE_BUTTONS.TYPE.FILLED, + action: () => { + setSecondTitle({}) + history.push(PATH.INFRASTRUCTURE.PROVIDERS.CREATE) + }, + }, + { + accessor: PROVIDER_ACTIONS.UPDATE_DIALOG, + label: T.Update, + tooltip: T.Update, + selected: { max: 1 }, + importance: STYLE_BUTTONS.IMPORTANCE.SECONDARY, + size: STYLE_BUTTONS.SIZE.MEDIUM, + type: STYLE_BUTTONS.TYPE.OUTLINED, + action: (rows) => { + const provider = rows?.[0]?.original ?? {} + const path = PATH.INFRASTRUCTURE.PROVIDERS.CREATE + + history.push(path, provider) + }, + }, + { + tooltip: T.Ownership, + icon: Group, + selected: true, + importance: STYLE_BUTTONS.IMPORTANCE.SECONDARY, + size: STYLE_BUTTONS.SIZE.MEDIUM, + type: STYLE_BUTTONS.TYPE.OUTLINED, + dataCy: 'template-ownership', + options: [ + { + accessor: PROVIDER_ACTIONS.CHANGE_OWNER, + name: T.ChangeOwner, + dialogProps: { + title: T.ChangeOwner, + subheader: SubHeader, + dataCy: `modal-${PROVIDER_ACTIONS.CHANGE_OWNER}`, + validateOn: 'onSubmit', + }, + form: ChangeUserForm, + onSubmit: (rows) => (newOwnership) => { + rows?.map?.(({ original }) => + changeOwnership({ id: original?.ID, ...newOwnership }) + ) + }, + }, + { + accessor: PROVIDER_ACTIONS.CHANGE_GROUP, + name: T.ChangeGroup, + dialogProps: { + title: T.ChangeGroup, + subheader: SubHeader, + dataCy: `modal-${PROVIDER_ACTIONS.CHANGE_GROUP}`, + validateOn: 'onSubmit', + }, + form: ChangeGroupForm, + onSubmit: (rows) => async (newOwnership) => { + const ids = rows?.map?.(({ original }) => original?.ID) + await Promise.all( + ids.map((id) => changeOwnership({ id, ...newOwnership })) + ) + }, + }, + ], + }, + { + accessor: PROVIDER_ACTIONS.DELETE, + tooltip: T.Delete, + icon: Trash, + selected: { min: 1 }, + importance: STYLE_BUTTONS.IMPORTANCE.DANGER, + size: STYLE_BUTTONS.SIZE.MEDIUM, + type: STYLE_BUTTONS.TYPE.OUTLINED, + options: [ + { + isConfirmDialog: true, + dialogProps: { + title: T.Delete, + dataCy: `modal-${PROVIDER_ACTIONS.DELETE}`, + children: MessageToConfirmAction, + }, + onSubmit: (rows) => async () => { + const ids = rows?.map?.(({ original }) => original?.ID) + await Promise.all(ids.map((id) => remove({ id }))) + setSelectedRows && setSelectedRows([]) + }, + }, + ], + }, + ], + }), + [view] + ) + + return providerActions +} + +export default Actions diff --git a/src/fireedge/src/modules/components/Tables/Providers/columns.js b/src/fireedge/src/modules/components/Tables/Providers/columns.js new file mode 100644 index 0000000000..4c54687d64 --- /dev/null +++ b/src/fireedge/src/modules/components/Tables/Providers/columns.js @@ -0,0 +1,35 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { Column } from 'opennebula-react-table' + +import { T } from '@ConstantsModule' + +/** @type {Column[]} Provider columns */ +const COLUMNS = [ + { Header: T.ID, id: 'id', accessor: 'ID', sortType: 'number' }, + { Header: T.Name, id: 'name', accessor: 'NAME' }, + { + Header: T.RegistrationTime, + id: 'time', + accessor: 'TEMPLATE.PROVIDER_BODY.registration_time', + }, + { Header: T.Owner, id: 'owner', accessor: 'UNAME' }, + { Header: T.Group, id: 'group', accessor: 'GNAME' }, +] + +COLUMNS.noFilterIds = ['id', 'name', 'time'] + +export default COLUMNS diff --git a/src/fireedge/src/modules/components/Tables/Providers/index.js b/src/fireedge/src/modules/components/Tables/Providers/index.js new file mode 100644 index 0000000000..3d5767e7e9 --- /dev/null +++ b/src/fireedge/src/modules/components/Tables/Providers/index.js @@ -0,0 +1,28 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 table from '@modules/components/Tables/Providers/table' +import columns from '@modules/components/Tables/Providers/columns' +import row from '@modules/components/Tables/Providers/row' +import actions from '@modules/components/Tables/Providers/actions' + +const ProvidersTable = { + Table: table, + Columns: columns, + Row: row, + Actions: actions, +} + +export default ProvidersTable diff --git a/src/fireedge/src/modules/components/Tables/Providers/row.js b/src/fireedge/src/modules/components/Tables/Providers/row.js new file mode 100644 index 0000000000..9bf9a89005 --- /dev/null +++ b/src/fireedge/src/modules/components/Tables/Providers/row.js @@ -0,0 +1,60 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { ProviderCard } from '@modules/components/Cards' +import PropTypes from 'prop-types' +import { memo, useMemo } from 'react' +import { oneApi } from '@FeaturesModule' + +const Row = memo( + ({ + original, + value, + onClickLabel, + zone, + headerList, + rowDataCy, + isSelected, + toggleRowSelected, + ...props + }) => { + const state = oneApi.endpoints.getProviders.useQueryState(undefined, { + selectFromResult: ({ data = [] }) => + data.find((provider) => +provider.ID === +original.ID), + }) + + const memoTemplate = useMemo(() => state ?? original, [state, original]) + + return + }, + (prev, next) => prev.className === next.className +) + +Row.propTypes = { + original: PropTypes.object, + value: PropTypes.object, + isSelected: PropTypes.bool, + className: PropTypes.string, + handleClick: PropTypes.func, + onClickLabel: PropTypes.func, + zone: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), + headerList: PropTypes.oneOfType([PropTypes.array, PropTypes.bool]), + rowDataCy: PropTypes.string, + toggleRowSelected: PropTypes.func, +} + +Row.displayName = 'ProviderRow' + +export default Row diff --git a/src/fireedge/src/modules/components/Tables/Providers/table.js b/src/fireedge/src/modules/components/Tables/Providers/table.js new file mode 100644 index 0000000000..117836b422 --- /dev/null +++ b/src/fireedge/src/modules/components/Tables/Providers/table.js @@ -0,0 +1,133 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { ReactElement, useEffect, useMemo } from 'react' +import { Alert, Typography } from '@mui/material' +import { Translate, Tr } from '@modules/components/HOC' +import EnhancedTable, { + createColumns, +} from '@modules/components/Tables/Enhanced' +import WrapperRow from '@modules/components/Tables/Enhanced/WrapperRow' +import ProviderColumns from '@modules/components/Tables/Providers/columns' +import ProviderRow from '@modules/components/Tables/Providers/row' +import { RESOURCE_NAMES, T } from '@ConstantsModule' +import { timeFromMilliseconds } from '@ModelsModule' +import { useViews, ProviderAPI, SystemAPI } from '@FeaturesModule' +import { generateDocLink } from '@UtilsModule' +import Timer from '@modules/components/Timer' + +const DEFAULT_DATA_CY = 'providers' + +/** + * @param {object} props - Props + * @returns {ReactElement} Providers table + */ +const ProvidersTable = (props) => { + const { + rootProps = {}, + searchProps = {}, + handleRefetch, + ...rest + } = props ?? {} + rootProps['data-cy'] ??= DEFAULT_DATA_CY + searchProps['data-cy'] ??= `search-${DEFAULT_DATA_CY}` + + const { view, getResourceView } = useViews() + const { + data = [], + isFetching, + refetch, + error, + } = ProviderAPI.useGetProvidersQuery() + + // Get version to show links to documentation + const { data: version } = SystemAPI.useGetOneVersionQuery() + + useEffect(() => { + if (handleRefetch && refetch) { + handleRefetch(refetch) + } + }, [handleRefetch, refetch]) + + const columns = useMemo( + () => + createColumns({ + filters: getResourceView(RESOURCE_NAMES.PROVIDER)?.filters, + columns: ProviderColumns, + }), + [view] + ) + + const listHeader = [ + { header: T.ID, id: 'id', accessor: 'ID' }, + { header: T.Owner, id: 'owner', accessor: 'UNAME' }, + { header: T.Group, id: 'group', accessor: 'GNAME' }, + { header: T.Name, id: 'name', accessor: 'NAME' }, + { + header: T.StartTime, + id: 'start-time', + accessor: ({ + TEMPLATE: { PROVIDER_BODY: { registration_time: regTime } = {} }, + }) => { + const time = useMemo(() => timeFromMilliseconds(+regTime), [regTime]) + + return + }, + }, + ] + + const { component, header } = WrapperRow(ProviderRow) + + return ( + String(row.ID)} + noDataMessage={ + error?.status === 500 && ( + + + + {Tr(T['oneform.info.more'])} + + {Tr(T['oneform.info.more.link'])} + + + + ) + } + RowComponent={component} + headerList={header && listHeader} + resourceType={RESOURCE_NAMES.PROVIDER} + {...rest} + /> + ) +} + +ProvidersTable.propTypes = { ...EnhancedTable.propTypes } +ProvidersTable.displayName = 'ProvidersTable' + +export default ProvidersTable diff --git a/src/fireedge/src/modules/components/Tables/VmGroups/table.js b/src/fireedge/src/modules/components/Tables/VmGroups/table.js index 0c880affc2..e7f545b0ec 100644 --- a/src/fireedge/src/modules/components/Tables/VmGroups/table.js +++ b/src/fireedge/src/modules/components/Tables/VmGroups/table.js @@ -13,16 +13,16 @@ * See the License for the specific language governing permissions and * * limitations under the License. * * ------------------------------------------------------------------------- */ -import { ReactElement, useEffect, useMemo } from 'react' -import WrapperRow from '@modules/components/Tables/Enhanced/WrapperRow' import { useViews, VmGroupAPI } from '@FeaturesModule' +import WrapperRow from '@modules/components/Tables/Enhanced/WrapperRow' +import { ReactElement, useEffect, useMemo } from 'react' +import { RESOURCE_NAMES, T } from '@ConstantsModule' import EnhancedTable, { createColumns, } from '@modules/components/Tables/Enhanced' import VmGroupColumns from '@modules/components/Tables/VmGroups/columns' import VmGroupRow from '@modules/components/Tables/VmGroups/row' -import { RESOURCE_NAMES, T } from '@ConstantsModule' const DEFAULT_DATA_CY = 'vmgroups' diff --git a/src/fireedge/src/modules/components/Tables/index.js b/src/fireedge/src/modules/components/Tables/index.js index ffb31057df..4ab7b7a7d8 100644 --- a/src/fireedge/src/modules/components/Tables/index.js +++ b/src/fireedge/src/modules/components/Tables/index.js @@ -29,6 +29,7 @@ import IncrementsTable from '@modules/components/Tables/Increments' import MarketplaceAppsTable from '@modules/components/Tables/MarketplaceApps' import MarketplacesTable from '@modules/components/Tables/Marketplaces' import PcisTable from '@modules/components/Tables/Pcis' +import ProvidersTable from '@modules/components/Tables/Providers' import SecurityGroupsTable from '@modules/components/Tables/SecurityGroups' import ServiceTemplatesTable from '@modules/components/Tables/ServiceTemplates' import ServicesTable from '@modules/components/Tables/Services' @@ -66,6 +67,7 @@ export { MarketplaceAppsTable, MarketplacesTable, PcisTable, + ProvidersTable, SecurityGroupsTable, ServiceTemplatesTable, ServicesTable, diff --git a/src/fireedge/src/modules/components/Tabs/Cluster/Hosts/Action.js b/src/fireedge/src/modules/components/Tabs/Cluster/Hosts/Action.js new file mode 100644 index 0000000000..7113eead10 --- /dev/null +++ b/src/fireedge/src/modules/components/Tabs/Cluster/Hosts/Action.js @@ -0,0 +1,122 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 PropTypes from 'prop-types' +import { memo } from 'react' + +import { STYLE_BUTTONS, T } from '@ConstantsModule' +import ButtonToTriggerForm from '@modules/components/Forms/ButtonToTriggerForm' +import { AddHostForm, DeleteHostForm } from '@modules/components/Forms/Cluster' + +const AddHost = memo(({ formType, submit, filter }) => { + // Handle submit form + const handleSubmit = (formData) => { + submit(formData.hosts) + } + + return ( + { + const params = { + stepProps: { + formType, + }, + } + formType !== 'amount' && + filter && + (params.stepProps.filter = filter) + + return AddHostForm(params) + }, + onSubmit: handleSubmit, + }, + ]} + /> + ) +}) + +const DeleteHost = memo(({ formType, submit, filter }) => { + const handleSubmit = (formData) => { + submit(formData.hosts) + } + + return ( + { + const params = { + stepProps: { + formType, + }, + } + formType !== 'amount' && + filter && + (params.stepProps.filter = filter) + + return DeleteHostForm(params) + }, + onSubmit: handleSubmit, + }, + ]} + /> + ) +}) + +AddHost.propTypes = { + formType: PropTypes.string, + filter: PropTypes.func, + submit: PropTypes.func, +} +AddHost.displayName = 'AddHostAction' + +DeleteHost.propTypes = { + formType: PropTypes.string, + filter: PropTypes.func, + submit: PropTypes.func, +} +DeleteHost.displayName = 'DeleteHostAction' + +export { AddHost, DeleteHost } diff --git a/src/fireedge/src/modules/components/Tabs/Cluster/Hosts/index.js b/src/fireedge/src/modules/components/Tabs/Cluster/Hosts/index.js index fa2b43cad5..3228b0e226 100644 --- a/src/fireedge/src/modules/components/Tabs/Cluster/Hosts/index.js +++ b/src/fireedge/src/modules/components/Tabs/Cluster/Hosts/index.js @@ -13,14 +13,22 @@ * See the License for the specific language governing permissions and * * limitations under the License. * * ------------------------------------------------------------------------- */ -import { ReactElement } from 'react' -import PropTypes from 'prop-types' -import { Box } from '@mui/material' -import { HostsTable } from '@modules/components/Tables' -import { ClusterAPI, HostAPI } from '@FeaturesModule' -import { useHistory, generatePath } from 'react-router-dom' +import { T } from '@ConstantsModule' +import { + ClusterAPI, + HostAPI, + ProvisionAPI, + useGeneralApi, +} from '@FeaturesModule' +import { getActionsAvailable } from '@ModelsModule' import { PATH } from '@modules/components/path' +import { HostsTable } from '@modules/components/Tables' import { ProfileSelector } from '@modules/components/Tabs/Common/PCI' +import { Box, Stack } from '@mui/material' +import PropTypes from 'prop-types' +import { ReactElement, useMemo } from 'react' +import { generatePath, useHistory } from 'react-router-dom' +import { AddHost, DeleteHost } from './Action' const _ = require('lodash') /** @@ -28,13 +36,50 @@ const _ = require('lodash') * * @param {object} props - Props * @param {string} props.id - Cluster id + * @param {object} props.tabProps - Tab props + * @param {object} props.tabProps.provision - Provision panel info * @returns {ReactElement} Hosts tab */ -const Hosts = ({ id }) => { +const Hosts = ({ tabProps: { provision: provisionPanel } = {}, id }) => { const [update] = ClusterAPI.useUpdateClusterMutation() + const { enqueueSuccess } = useGeneralApi() + const actionsAvailable = getActionsAvailable(provisionPanel?.actions) + // Get info about the cluster - const { data: cluster } = ClusterAPI.useGetClusterQuery({ id }) + const { data: cluster, refetch: refetchCluster } = + ClusterAPI.useGetClusterQuery({ id }) const { data: hosts = [] } = HostAPI.useGetHostsQuery() + const provisionID = cluster?.TEMPLATE?.ONEFORM?.PROVISION_ID + const { data: dataProvision = {}, refetch: refetchProvision } = provisionID + ? ProvisionAPI.useGetProvisionQuery({ id: provisionID, extended: true }) + : { data: {}, refetch: () => undefined } + const [scaleProvisionHosts] = ProvisionAPI.useScaleProvisionHostsMutation() + + const refetchAll = () => { + refetchProvision() && refetchCluster() + } + + const operations = useMemo( + () => dataProvision?.TEMPLATE?.PROVISION_BODY?.fireedge?.operations ?? {}, + [cluster, dataProvision] + ) + + const ars = useMemo( + () => + dataProvision?.TEMPLATE?.PROVISION_BODY?.one_objects?.networks + ?.filter((n) => n?.template?.netrole !== 'public') + ?.flatMap((n) => n?.template?.ar ?? []) + ?.map( + (ar) => + Object.fromEntries( + Object.entries(ar).map(([key, value]) => [ + key.toUpperCase(), + value, + ]) + ) ?? [] + ), + [cluster, dataProvision] + ) // Define function to get details of a host const history = useHistory() @@ -55,6 +100,31 @@ const Hosts = ({ id }) => { .concat(hosts) ?.filter(({ ID }) => hostIds?.includes(ID)) + const filterHostsIncluded = (dataToFilter) => + dataToFilter.filter((host) => _.includes(hostIds, host.ID)) + + const handleAddHost = async (data) => { + if (!data) return + await scaleProvisionHosts({ id: provisionID, nodes: data, direction: 'up' }) + refetchAll() + + // Success message + enqueueSuccess(T.AddHostProvisionSuccess) + } + + const handleDeleteHost = async (data) => { + if (!data) return + await scaleProvisionHosts({ + id: provisionID, + nodes: data, + direction: 'down', + }) + refetchAll() + + // Success message + enqueueSuccess(T.DeleteHostProvisionSuccess) + } + return ( { resource={cluster} /> - - dataToFilter.filter((host) => _.includes(hostIds, host.ID)) - } - onRowClick={(row) => handleRowClick(row.ID)} - /> + + + {actionsAvailable?.includes?.('add') && operations?.['add-host'] && ( + + )} + {actionsAvailable?.includes?.('delete') && + operations?.['del-host'] && ( + + )} + + handleRowClick(row.ID)} + /> + ) } Hosts.propTypes = { id: PropTypes.string, + tabProps: PropTypes.object, } Hosts.displayName = 'Hosts' diff --git a/src/fireedge/src/modules/components/Tabs/Cluster/Info/information.js b/src/fireedge/src/modules/components/Tabs/Cluster/Info/information.js index 318cabaf11..df3382f9c2 100644 --- a/src/fireedge/src/modules/components/Tabs/Cluster/Info/information.js +++ b/src/fireedge/src/modules/components/Tabs/Cluster/Info/information.js @@ -15,10 +15,12 @@ * ------------------------------------------------------------------------- */ import { ReactElement } from 'react' import PropTypes from 'prop-types' -import { ClusterAPI } from '@FeaturesModule' +import { ClusterAPI, ProvisionAPI } from '@FeaturesModule' import { List } from '@modules/components/Tabs/Common' +import { StatusChip, StatusCircle } from '@modules/components/Status' import { T, Cluster, CLUSTER_ACTIONS } from '@ConstantsModule' -import { jsonToXml } from '@ModelsModule' +import { getProvisionColorState, jsonToXml } from '@ModelsModule' +import { Stack } from '@mui/material' /** * Renders mainly information tab. @@ -50,6 +52,28 @@ const InformationPanel = ({ cluster = {}, actions }) => { }, ] + // Show only Provision status if the cluster was created by OneForm + if (cluster?.TEMPLATE?.ONEFORM) { + const { data: provision } = ProvisionAPI.useGetProvisionQuery({ + id: cluster?.TEMPLATE?.ONEFORM?.PROVISION_ID, + }) + const provisionState = provision?.TEMPLATE?.PROVISION_BODY?.state + const stateColor = getProvisionColorState(provisionState) + info.push({ + name: T.State, + value: ( + + + + + ), + }) + } + /** * Update reserved CPU on the template cluster. * diff --git a/src/fireedge/src/modules/components/Tabs/Cluster/Logs/index.js b/src/fireedge/src/modules/components/Tabs/Cluster/Logs/index.js new file mode 100644 index 0000000000..2eb0a1f0e3 --- /dev/null +++ b/src/fireedge/src/modules/components/Tabs/Cluster/Logs/index.js @@ -0,0 +1,63 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 LogsViewer from '@modules/components/LogsViewer' +import { Stack } from '@mui/material' +import PropTypes from 'prop-types' +import { ReactElement } from 'react' + +import { ClusterAPI, ProvisionAPI } from '@FeaturesModule' +import { OpenNebulaLogo } from '@modules/components/Icons' + +/** + * Render log viewer tab showing the logs of the cluster (only for OneForm clusters). + * + * @param {object} props - Props + * @param {string} props.id - Cluster id + * @returns {ReactElement} Logs tab + */ +const Logs = ({ id }) => { + const { data: cluster } = ClusterAPI.useGetClusterQuery({ id }) + + // Get logs + const { + data: logsData, + refetch, + isFetching, + } = ProvisionAPI.useGetProvisionLogsQuery({ + id: cluster?.TEMPLATE?.ONEFORM?.PROVISION_ID, + all: true, + }) + + return logsData ? ( + + ) : ( + + + + ) +} + +Logs.propTypes = { + id: PropTypes.string, +} + +Logs.displayName = 'Logs' +Logs.label = 'Logs' + +export default Logs diff --git a/src/fireedge/src/modules/components/Tabs/Cluster/Vnets/Actions.js b/src/fireedge/src/modules/components/Tabs/Cluster/Vnets/Actions.js new file mode 100644 index 0000000000..f6538d1831 --- /dev/null +++ b/src/fireedge/src/modules/components/Tabs/Cluster/Vnets/Actions.js @@ -0,0 +1,156 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 PropTypes from 'prop-types' +import { memo } from 'react' +import { Stack } from '@mui/material' +import { STYLE_BUTTONS, T, VN_ACTIONS } from '@ConstantsModule' +import ButtonToTriggerForm from '@modules/components/Forms/ButtonToTriggerForm' +import { AddVnetsForm } from '@modules/components/Forms/Cluster' +import AddressRangeCard from '@modules/components/Cards/AddressRangeCard' +import SubmitButton from '@modules/components/FormControl/SubmitButton' + +import { useDialog } from '@HooksModule' + +import { DialogConfirmation } from '@modules/components/Dialogs' + +import { DeleteAddressRangeAction } from '@modules/components/Buttons' + +const { DELETE_AR } = VN_ACTIONS + +const AddIps = memo(({ formType, submit }) => { + // Handle submit form + const handleSubmit = (formData) => { + submit(formData.amount) + } + + return ( + { + const params = { + stepProps: { + formType, + }, + } + + return AddVnetsForm(params) + }, + onSubmit: handleSubmit, + }, + ]} + /> + ) +}) + +AddIps.propTypes = { + formType: PropTypes.string, + filter: PropTypes.func, + submit: PropTypes.func, +} +AddIps.displayName = 'AddIps' + +/** + * Action to edit administrators of a group. + * + * @param {object} props - Properties + * @param {object} props.vnet - Virtual network + * @param {object} props.oneConfig - OpenNebula config + * @param {boolean} props.adminGroup - If the user is admin + * @param {object} props.actions - List of actions + * @param {object} props.submit - Submit function + * @returns {object} - React component + */ +const DeleteIps = ({ vnet, oneConfig, adminGroup, actions = [], submit }) => { + const { display, show, hide } = useDialog() + + const addressRanges = [vnet?.AR_POOL?.AR ?? []].flat() + + return ( + <> + { + show() + }} + /> + + {display && ( + hide()} + title={T['cluster.vnet.del.ip']} + dataCy={'modal-del-ip'} + fixedWidth + > + + {addressRanges.map((ar) => ( + + {actions[DELETE_AR] === true && ( + + )} + + } + /> + ))} + + + )} + + ) +} + +DeleteIps.propTypes = { + vnet: PropTypes.object, + oneConfig: PropTypes.object, + adminGroup: PropTypes.bool, + actions: PropTypes.array, + submit: PropTypes.object, +} +DeleteIps.displayName = 'DeleteIps' + +export { AddIps, DeleteIps } diff --git a/src/fireedge/src/modules/components/Tabs/Cluster/Vnets/index.js b/src/fireedge/src/modules/components/Tabs/Cluster/Vnets/index.js index 811d0ce6f2..bc82c23d98 100644 --- a/src/fireedge/src/modules/components/Tabs/Cluster/Vnets/index.js +++ b/src/fireedge/src/modules/components/Tabs/Cluster/Vnets/index.js @@ -13,25 +13,84 @@ * See the License for the specific language governing permissions and * * limitations under the License. * * ------------------------------------------------------------------------- */ -import { ReactElement } from 'react' +import { T } from '@ConstantsModule' +import { ClusterAPI, ProvisionAPI, useGeneralApi, VnAPI } from '@FeaturesModule' +import { getActionsAvailable } from '@ModelsModule' +import { ReactElement, useMemo } from 'react' import PropTypes from 'prop-types' import { Stack } from '@mui/material' import { VnsTable } from '@modules/components/Tables' -import { ClusterAPI } from '@FeaturesModule' import { useHistory, generatePath } from 'react-router-dom' import { PATH } from '@modules/components/path' -const _ = require('lodash') +import { + AddIps, + DeleteIps, +} from '@modules/components/Tabs/Cluster/Vnets/Actions' +import { isEmpty, find } from 'lodash' /** * Renders vnets tab showing the vnets of the cluster. * * @param {object} props - Props * @param {string} props.id - Cluster id + * @param {object} props.tabProps - Tab props + * @param {object} props.tabProps.provision - Provision panel info + * @param {object} props.oneConfig - OpenNebula config + * @param {boolean} props.adminGroup - If the user is admin * @returns {ReactElement} Vnets tab */ -const Vnets = ({ id }) => { +const Vnets = ({ + tabProps: { provision: provisionPanel } = {}, + id, + oneConfig, + adminGroup, +}) => { + const actionsAvailable = getActionsAvailable(provisionPanel?.actions) + const { enqueueSuccess } = useGeneralApi() + // Get info about the cluster - const { data: cluster } = ClusterAPI.useGetClusterQuery({ id }) + const { data: cluster, refetch: refetchCluster } = + ClusterAPI.useGetClusterQuery({ id }) + + // Get info about the provision + const provisionID = cluster?.TEMPLATE?.ONEFORM?.PROVISION_ID + const { data: dataProvision = {}, refetch: refetchProvision } = provisionID + ? ProvisionAPI.useGetProvisionQuery({ + id: provisionID, + extended: true, + }) + : { data: {}, refetch: () => undefined } + + // Get vnets of the cluster + const provisionVnets = + dataProvision?.TEMPLATE?.PROVISION_BODY?.one_objects?.networks + const vnets = isEmpty(provisionVnets) + ? [] + : Array.isArray(provisionVnets) + ? provisionVnets + : [provisionVnets] + + // Get public vnet (the one that has vn_mad equal to elastic) + const publicVnet = find(vnets, (v) => v.template?.vn_mad === 'elastic') + const { data: dataPublicVnet, refetch: refetchVnet } = + VnAPI.useGetVNetworkQuery({ id: publicVnet?.id }, { skip: !publicVnet }) + + // Refresh + const refetchAll = () => { + refetchProvision() + refetchCluster() + refetchVnet() + } + + // API actions + const [addIpsProvision] = ProvisionAPI.useAddIpsProvisionMutation() + const [deleteIpsProvision] = ProvisionAPI.useDeleteIpsProvisionMutation() + + // Geta avaliable operations + const operations = useMemo( + () => dataProvision?.TEMPLATE?.PROVISION_BODY?.fireedge?.operations ?? {}, + [cluster, dataProvision] + ) // Define function to get details of a vnet const history = useHistory() @@ -39,35 +98,71 @@ const Vnets = ({ id }) => { history.push(generatePath(PATH.NETWORK.VNETS.DETAIL, { id: String(rowId) })) } - // Get vnets of the cluster - const vnets = _.isEmpty(cluster?.VNETS) - ? [] - : Array.isArray(cluster?.VNETS?.ID) - ? cluster?.VNETS?.ID - : [cluster?.VNETS?.ID] + // Add ips to the cluster + const handleAddIp = async (ipsAmount) => { + // Exit if there is not ips amount + if (!ipsAmount) return + + // Request to add ips + await addIpsProvision({ id: provisionID, amount: ipsAmount }) + + // Refresh + refetchAll() + + // Success message + enqueueSuccess(T.AddIpsProvisionSuccess) + } + + // Delete ip from the cluster + const handleDeleteIp = async ({ arId }) => { + // Exit if there is not address range id + if (!arId) return + + // Request to add ips + await deleteIpsProvision({ id: provisionID, ar_id: arId }) + + // Refresh + refetchAll() + + // Success message + enqueueSuccess(T.DeleteIpsProvisionSuccess) + } return ( -
- - - dataToFilter.filter((vnet) => _.includes(vnets, vnet.ID)) - } - onRowClick={(row) => handleRowClick(row.ID)} - /> + + + {actionsAvailable?.includes?.('add') && operations?.['add-ip'] && ( + + )} + {actionsAvailable?.includes?.('delete') && operations?.['del-ip'] && ( + + )} -
+ + + dataToFilter.filter((vnet) => + vnets.some((net) => String(net.id) === vnet.ID) + ) + } + onRowClick={(row) => handleRowClick(row.ID)} + /> + ) } Vnets.propTypes = { id: PropTypes.string, + tabProps: PropTypes.object, + oneConfig: PropTypes.object, + adminGroup: PropTypes.bool, } Vnets.displayName = 'Vnets' diff --git a/src/fireedge/src/modules/components/Tabs/Cluster/index.js b/src/fireedge/src/modules/components/Tabs/Cluster/index.js index 95e0d68b7a..b33a6bbe71 100644 --- a/src/fireedge/src/modules/components/Tabs/Cluster/index.js +++ b/src/fireedge/src/modules/components/Tabs/Cluster/index.js @@ -27,6 +27,7 @@ import Datastores from '@modules/components/Tabs/Cluster/Datastores' import PlanOptimization from '@modules/components/Tabs/Cluster/Drs' import Hosts from '@modules/components/Tabs/Cluster/Hosts' import Info from '@modules/components/Tabs/Cluster/Info' +import Logs from '@modules/components/Tabs/Cluster/Logs' import Vnets from '@modules/components/Tabs/Cluster/Vnets' import SingleDetailActions from '@modules/components/Tabs/SingleDetailActions' @@ -37,6 +38,7 @@ const getTabComponent = (tabName) => vnet: Vnets, datastore: Datastores, drs: PlanOptimization, + logs: Logs, }[tabName]) const ClusterTabs = memo(({ id, singleActions }) => { diff --git a/src/fireedge/src/modules/components/Tabs/Provider/Info/index.js b/src/fireedge/src/modules/components/Tabs/Provider/Info/index.js new file mode 100644 index 0000000000..189c661728 --- /dev/null +++ b/src/fireedge/src/modules/components/Tabs/Provider/Info/index.js @@ -0,0 +1,115 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { ReactElement } from 'react' +import PropTypes from 'prop-types' +import { Stack } from '@mui/material' + +import { ProviderAPI } from '@FeaturesModule' +import { Permissions, Ownership } from '@modules/components/Tabs/Common' +import Information from '@modules/components/Tabs/Provider/Info/information' +import { getActionsAvailable, permissionsToOctal } from '@ModelsModule' +import { toSnakeCase } from '@UtilsModule' + +/** + * Renders mainly information tab. + * + * @param {object} props - Props + * @param {object} props.tabProps - Tab information + * @param {string} props.id - Template id + * @returns {ReactElement} Information tab + */ +const ProviderInfoTab = ({ tabProps = {}, id }) => { + const { + information_panel: informationPanel, + permissions_panel: permissionsPanel, + ownership_panel: ownershipPanel, + } = tabProps + + const [changePermissions] = ProviderAPI.useChangeProviderPermissionsMutation() + const [changeOwnership] = ProviderAPI.useChangeProviderOwnershipMutation() + const { data: provider = {} } = ProviderAPI.useGetProviderQuery({ id }) + const { UNAME, UID, GNAME, GID, PERMISSIONS = {} } = provider + + const handleChangeOwnership = async (newOwnership) => { + await changeOwnership({ id, ...newOwnership }) + } + + const handleChangePermission = async (newPermission) => { + const [key, value] = Object.entries(newPermission)[0] + + // transform key to snake case concatenated by the first letter of permission type + // example: 'OWNER_ADMIN' -> 'OWNER_A' + const [member, permission] = toSnakeCase(key).toUpperCase().split('_') + const fullPermissionName = `${member}_${permission[0]}` + + const newPermissions = { ...PERMISSIONS, [fullPermissionName]: value } + const octet = permissionsToOctal(newPermissions) + + await changePermissions({ id, octet }) + } + + const getActions = (actions) => getActionsAvailable(actions) + + return ( + + {informationPanel?.enabled && ( + + )} + {permissionsPanel?.enabled && ( + + )} + {ownershipPanel?.enabled && ( + + )} + + ) +} + +ProviderInfoTab.propTypes = { + tabProps: PropTypes.object, + id: PropTypes.string, +} + +ProviderInfoTab.displayName = 'ProviderInfoTab' + +export default ProviderInfoTab diff --git a/src/fireedge/src/modules/components/Tabs/Provider/Info/information.js b/src/fireedge/src/modules/components/Tabs/Provider/Info/information.js new file mode 100644 index 0000000000..f6ebab765b --- /dev/null +++ b/src/fireedge/src/modules/components/Tabs/Provider/Info/information.js @@ -0,0 +1,85 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { ReactElement } from 'react' +import PropTypes from 'prop-types' + +import { List } from '@modules/components/Tabs/Common' +import { ProviderAPI } from '@FeaturesModule' + +import { timeToString } from '@ModelsModule' +import { T, Provider, PROVIDER_ACTIONS } from '@ConstantsModule' + +/** + * Renders mainly information tab. + * + * @param {object} props - Props + * @param {Provider} props.provider - Provider + * @param {string[]} props.actions - Available actions to information tab + * @returns {ReactElement} Information tab + */ +const InformationPanel = ({ provider = {}, actions }) => { + const [renameTemplate] = ProviderAPI.useRenameProviderMutation() + + const { + ID, + NAME, + TEMPLATE: { + PROVIDER_BODY: { description, registration_time: regTime } = {}, + }, + } = provider || {} + + const handleRename = async (_, newName) => { + await renameTemplate({ id: ID, template: { name: newName } }) + } + + const info = [ + { name: T.ID, value: ID, dataCy: 'id' }, + { + name: T.Name, + value: NAME, + canEdit: actions?.includes?.(PROVIDER_ACTIONS.RENAME), + handleEdit: handleRename, + dataCy: 'name', + }, + { + name: T.Description, + value: description, + dataCy: 'description', + }, + { + name: T.StartTime, + value: timeToString(regTime), + dataCy: 'time', + }, + ].filter(Boolean) + + return ( + + ) +} + +InformationPanel.displayName = 'InformationPanel' + +InformationPanel.propTypes = { + actions: PropTypes.arrayOf(PropTypes.string), + provider: PropTypes.object, +} + +export default InformationPanel diff --git a/src/fireedge/src/modules/components/Tabs/Provider/Template.js b/src/fireedge/src/modules/components/Tabs/Provider/Template.js new file mode 100644 index 0000000000..96187263be --- /dev/null +++ b/src/fireedge/src/modules/components/Tabs/Provider/Template.js @@ -0,0 +1,54 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { ReactElement } from 'react' +import PropTypes from 'prop-types' +import { Box, Accordion, AccordionDetails } from '@mui/material' + +import { ProviderAPI } from '@FeaturesModule' +/** + * Renders template tab. + * + * @param {object} props - Props + * @param {string} props.id - Template id + * @returns {ReactElement} Template tab + */ +const TemplateTab = ({ id }) => { + const { data: provider = {} } = ProviderAPI.useGetProviderQuery({ id }) + + return ( + + + + + {JSON.stringify(provider?.TEMPLATE ?? {}, null, 2)} + + + + + ) +} + +TemplateTab.propTypes = { + tabProps: PropTypes.object, + id: PropTypes.string, +} + +TemplateTab.displayName = 'TemplateTab' + +export default TemplateTab diff --git a/src/fireedge/src/modules/components/Tabs/Provider/index.js b/src/fireedge/src/modules/components/Tabs/Provider/index.js new file mode 100644 index 0000000000..2462fec486 --- /dev/null +++ b/src/fireedge/src/modules/components/Tabs/Provider/index.js @@ -0,0 +1,86 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { OpenNebulaLogo } from '@modules/components/Icons' +import { Alert, Stack } from '@mui/material' +import PropTypes from 'prop-types' +import { memo, useMemo } from 'react' + +import { RESOURCE_NAMES } from '@ConstantsModule' +import { ProviderAPI, useViews } from '@FeaturesModule' +import { getAvailableInfoTabs } from '@ModelsModule' + +import { BaseTab as Tabs } from '@modules/components/Tabs' +import Info from '@modules/components/Tabs/Provider/Info' +import Template from '@modules/components/Tabs/Provider/Template' +import SingleDetailActions from '@modules/components/Tabs/SingleDetailActions' + +const getTabComponent = (tabName) => + ({ + info: Info, + template: Template, + }[tabName]) + +const ProviderTabs = memo(({ id, singleActions }) => { + const { view, getResourceView } = useViews() + const { isError, error, data } = ProviderAPI.useGetProviderQuery({ + id, + }) + + const tabsAvailable = useMemo(() => { + const resource = RESOURCE_NAMES.PROVIDER + const infoTabs = getResourceView(resource)?.['info-tabs'] ?? {} + + return getAvailableInfoTabs(infoTabs, getTabComponent, id) + }, [view, id]) + + if (isError) { + return ( + + {error.data} + + ) + } + + if (id === data?.ID) { + return ( + <> + + + + ) + } + + return ( + + + + ) +}) + +ProviderTabs.propTypes = { + id: PropTypes.string.isRequired, + singleActions: PropTypes.func, +} + +ProviderTabs.displayName = 'ProviderTabs' + +export default ProviderTabs diff --git a/src/fireedge/src/modules/components/Tabs/User/Group/index.js b/src/fireedge/src/modules/components/Tabs/User/Group/index.js index 6f2387c301..c8f3b09606 100644 --- a/src/fireedge/src/modules/components/Tabs/User/Group/index.js +++ b/src/fireedge/src/modules/components/Tabs/User/Group/index.js @@ -85,12 +85,16 @@ const GroupsInfoTab = ({ tabProps: { actions } = {}, id: userId }) => { ) /* Filter groups showing only the ones the user is linked into and it's not its primary group */ - const filterGroupsLinked = (data) => - data.filter( + const filterGroupsLinked = (data) => { + const x = data.filter( (group) => USER_GROUPS.some((userGroup) => userGroup === group.ID) && group.ID !== primaryGroupId ) + console.log('revi', x) + + return x + } /* Filter groups showing only the ones the user has not as primary group */ const filterByNotPrimaryGroup = (data) => diff --git a/src/fireedge/src/modules/components/Tabs/index.js b/src/fireedge/src/modules/components/Tabs/index.js index d83df24212..9f71bc0fac 100644 --- a/src/fireedge/src/modules/components/Tabs/index.js +++ b/src/fireedge/src/modules/components/Tabs/index.js @@ -24,6 +24,7 @@ export { default as ImageTabs } from '@modules/components/Tabs/Image' export { default as MarketplaceAppsTabs } from '@modules/components/Tabs/MarketplaceApp' export { default as MarketplaceTabs } from '@modules/components/Tabs/Marketplace' export { default as QuotaTabs } from '@modules/components/Tabs/Quota' +export { default as ProviderTabs } from '@modules/components/Tabs/Provider' export { default as SecurityGroupTabs } from '@modules/components/Tabs/SecurityGroup' export { default as ServiceTabs } from '@modules/components/Tabs/Service' export { default as ServiceTemplateTabs } from '@modules/components/Tabs/ServiceTemplate' diff --git a/src/fireedge/src/modules/components/index.js b/src/fireedge/src/modules/components/index.js index 86eee35985..7ca18fbc88 100644 --- a/src/fireedge/src/modules/components/index.js +++ b/src/fireedge/src/modules/components/index.js @@ -35,6 +35,7 @@ export { default as Image } from '@modules/components/Image' export * from '@modules/components/List' export { default as LoadingScreen } from '@modules/components/LoadingScreen' export * from '@modules/components/LoadingState' +export * from '@modules/components/LogsViewer' export { default as MultipleTags } from '@modules/components/MultipleTags' export { default as Notifier, diff --git a/src/fireedge/src/modules/components/path.js b/src/fireedge/src/modules/components/path.js index bb0a221fa9..5de08eb49f 100644 --- a/src/fireedge/src/modules/components/path.js +++ b/src/fireedge/src/modules/components/path.js @@ -122,6 +122,8 @@ export const PATH = { LIST: `/${RESOURCE_NAMES.CLUSTER}`, DETAIL: `/${RESOURCE_NAMES.CLUSTER}/:id`, CREATE: `/${RESOURCE_NAMES.CLUSTER}/create`, + CREATE_CLOUD: `/${RESOURCE_NAMES.CLUSTER}/create_cloud`, + CREATE_CLOUD_LOGS: `/${RESOURCE_NAMES.CLUSTER}/create_cloud_logs/:id`, }, HOSTS: { LIST: `/${RESOURCE_NAMES.HOST}`, @@ -132,6 +134,11 @@ export const PATH = { LIST: `/${RESOURCE_NAMES.ZONE}`, DETAIL: `/${RESOURCE_NAMES.ZONE}/:id`, }, + PROVIDERS: { + LIST: `/${RESOURCE_NAMES.PROVIDER}`, + DETAIL: `/${RESOURCE_NAMES.PROVIDER}/:id`, + CREATE: `/${RESOURCE_NAMES.PROVIDER}/create`, + }, }, SYSTEM: { USERS: { diff --git a/src/fireedge/src/modules/constants/cluster.js b/src/fireedge/src/modules/constants/cluster.js index dea74a7c5e..93f884afaf 100644 --- a/src/fireedge/src/modules/constants/cluster.js +++ b/src/fireedge/src/modules/constants/cluster.js @@ -97,3 +97,78 @@ export const PLAN_STATE = { color: COLOR.warning.main, }, } + +export const PROVISION_STATES = { + PENDING: { + name: 'PENDING', + color: COLOR.info.light, + }, + INIT: { + name: 'INIT', + color: COLOR.info.light, + }, + INIT_FAILURE: { + name: 'INIT_FAILURE', + color: COLOR.error.dark, + }, + PLANNING: { + name: 'PLANNING', + color: COLOR.info.light, + }, + PLANNING_FAILURE: { + name: 'PLANNING_FAILURE', + color: COLOR.error.dark, + }, + APPLYING: { + name: 'APPLYING', + color: COLOR.info.light, + }, + APPLYING_FAILURE: { + name: 'APPLYING_FAILURE', + color: COLOR.error.dark, + }, + CONFIGURING_ONE: { + name: 'CONFIGURING_ONE', + color: COLOR.info.light, + }, + CONFIGURING_ONE_FAILURE: { + name: 'CONFIGURING_ONE_FAILURE', + color: COLOR.error.dark, + }, + CONFIGURING_PROVISION: { + name: 'CONFIGURING_PROVISION', + color: COLOR.info.light, + }, + CONFIGURING_PROVISION_FAILURE: { + name: 'CONFIGURING_PROVISION_FAILURE', + color: COLOR.error.dark, + }, + RUNNING: { + name: 'RUNNING', + color: COLOR.success.light, + }, + SCALING: { + name: 'SCALING', + color: COLOR.info.light, + }, + SCALING_FAILURE: { + name: 'SCALING_FAILURE', + color: COLOR.error.dark, + }, + DEPROVISIONING_ONE: { + name: 'DEPROVISIONING_ONE', + color: COLOR.info.light, + }, + DEPROVISIONING_ONE_FAILURE: { + name: 'DEPROVISIONING_ONE_FAILURE', + color: COLOR.error.dark, + }, + DEPROVISIONING: { + name: 'DEPROVISIONING', + color: COLOR.info.light, + }, + DONE: { + name: 'DONE', + color: COLOR.success.light, + }, +} diff --git a/src/fireedge/src/modules/constants/index.js b/src/fireedge/src/modules/constants/index.js index 725225a081..de40b35bba 100644 --- a/src/fireedge/src/modules/constants/index.js +++ b/src/fireedge/src/modules/constants/index.js @@ -186,6 +186,8 @@ export const RESOURCE_NAMES = { FILE: 'file', LOGO: 'logo', MARKETPLACE: 'marketplace', + PROVIDER: 'provider', + PROVISION: 'provision', SEC_GROUP: 'security-group', USER: 'user', VDC: 'virtual-data-center', @@ -230,6 +232,9 @@ export * from '@modules/constants/scheduler' export * from '@modules/constants/securityGroup' export * from '@modules/constants/serviceTemplate' export * as STATES from '@modules/constants/states' +export * from '@modules/constants/ods' +export * from '@modules/constants/provider' +export * from '@modules/constants/provision' export * from '@modules/constants/styles' export * from '@modules/constants/support' export * from '@modules/constants/system' diff --git a/src/fireedge/src/modules/constants/ods.js b/src/fireedge/src/modules/constants/ods.js new file mode 100644 index 0000000000..82ce61254c --- /dev/null +++ b/src/fireedge/src/modules/constants/ods.js @@ -0,0 +1,59 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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. * + * ------------------------------------------------------------------------- */ + +/** + * This class models the OpenNebula Document Server (ODS) user inputs that + * will be used in Sinatra servers like OneForm (connection values and user inputs) + * and OneK8S + */ + +/** + * @typedef {( + * 'string' | + * 'number' | + * 'bool' | + * 'list' | + * 'listString' | + * 'map' + * )} ODSUserInputType + * - Terraform types for ODS User Input + */ + +/** + * @typedef MatchValueType + * @property {ODSUserInputType} type - Type of ODS User Input + * @property {string} grouped_by - Grouping criteria for ODS User Input + * @property {string[]|object[]} values - List of possible values for the ODS User Input + */ + +/** + * @typedef ODSUserInput + * @property {string} name - Name of ODS User Input + * @property {string} description - Description of ODS User Input + * @property {string|boolean|number|Array|object} default - Default value for ODS User Input + * @property {ODSUserInputType} type - Type of ODS User Input + * @property {MatchValueType} match - Validation rule for ODS User Input + */ + +/** @enum {ODSUserInputType} Connection Value types */ +export const ODS_USER_INPUT_TYPES = { + string: 'string', + number: 'number', + bool: 'bool', + list: 'list', + listString: 'list(string)', + map: 'map', +} diff --git a/src/fireedge/src/modules/constants/provider.js b/src/fireedge/src/modules/constants/provider.js new file mode 100644 index 0000000000..40fca8ca35 --- /dev/null +++ b/src/fireedge/src/modules/constants/provider.js @@ -0,0 +1,38 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 * as ACTIONS from '@modules/constants/actions' + +/** + * @typedef Provider + * @property {string|number} ID - Id + * @property {string} NAME - Name + * @property {string|number} UID - User id + * @property {string|number} GID - Group id + * @property {string} UNAME - User name + * @property {string} GNAME - Group name + * @property {Permissions} PERMISSIONS - Permissions + * @property {object} TEMPLATE - Template information + * @property {string} [TEMPLATE.PROVIDER_BODY] - Provider body + */ + +export const PROVIDER_ACTIONS = { + CREATE_DIALOG: 'create_dialog', + UPDATE_DIALOG: 'update_dialog', + DELETE: 'delete', + RENAME: ACTIONS.RENAME, + CHANGE_OWNER: ACTIONS.CHANGE_OWNER, + CHANGE_GROUP: ACTIONS.CHANGE_GROUP, +} diff --git a/src/fireedge/src/modules/constants/provision.js b/src/fireedge/src/modules/constants/provision.js new file mode 100644 index 0000000000..5d87c6fab4 --- /dev/null +++ b/src/fireedge/src/modules/constants/provision.js @@ -0,0 +1,32 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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. * + * ------------------------------------------------------------------------- */ +/** + * @typedef Provision + * @property {string|number} ID - Id + * @property {string} NAME - Name + * @property {string|number} UID - User id + * @property {string|number} GID - Group id + * @property {string} UNAME - User name + * @property {string} GNAME - Group name + * @property {Permissions} PERMISSIONS - Permissions + * @property {object} TEMPLATE - Template information + * @property {string} [TEMPLATE.PROVISION_BODY] - Provision body + */ +export const PROVISION_ACTIONS = { + CREATE_CLOUD_DIALOG: 'create_cloud_dialog', + DEPROVISION: 'deprovision', + RETRY: 'retry', +} diff --git a/src/fireedge/src/modules/constants/translates.js b/src/fireedge/src/modules/constants/translates.js index 95fb1b0a32..34157528d0 100644 --- a/src/fireedge/src/modules/constants/translates.js +++ b/src/fireedge/src/modules/constants/translates.js @@ -106,6 +106,7 @@ module.exports = { CreateMarketplace: 'Create Marketplace', CreateMarketApp: 'Create App', CreateApp: 'Create App', + CreateProvider: 'Create Provider', CreateSecurityGroup: 'Create Security Group', CreateServiceTemplate: 'Create Service Template', CreateVirtualRouterTemplate: 'Create Virtual Router Template', @@ -139,6 +140,8 @@ module.exports = { DeleteOtherSnapshots: 'This will delete all the other image snapshots', Deploy: 'Deploy', DeployServiceTemplate: 'Deploy Service Template', + DeploymentTypes: 'Deployment Types', + Deprovision: 'Deprovision', Detach: 'Detach', DetachRestricted: 'You cannot delete this resource because it has restricted attributes on this template. Please, contact with your administrator.', @@ -218,6 +221,7 @@ module.exports = { SelectDatastoreImage: 'Select a Datastore', SelectDatastores: 'Select datastores', SelectDisk: 'Select disk', + SelectDriver: 'Select Provider driver', SelectDockerHubTag: 'Select DockerHub image tag (default latest)', SelectGroup: 'Select a group', SelectHost: 'Select Host', @@ -227,6 +231,7 @@ module.exports = { SelectVirtualNetworks: 'Select virtual networks', SelectNewCluster: 'Select a new Cluster', SelectNewSecGroup: 'Select security group', + SelectProvider: 'Select Provider', SelectRequest: 'Select request', SelectTheNewDatastore: 'Select the new datastore', SelectTheNewGroup: 'Select the new group', @@ -421,7 +426,8 @@ module.exports = { WrongUsernamePassword: 'Wrong username or password', SomethingWrong: 'Something go wrong', CannotConnectOneFlow: 'Cannot connect to OneFlow server', - CannotConnectOneForm: 'Cannot connect to OneForm server', + CannotConnectOneForm: + 'Cannot connect to OneForm server, please verify that service is running.', ContactYourAdmin: 'Please contact your system administrator', NotFound: 'Not found', Timeout: 'Timeout', @@ -690,6 +696,27 @@ module.exports = { Zones: 'Zones', Vnet: 'Vnet', Vnets: 'Vnets', + OneformTags: 'Oneform Tags', + Providers: 'Providers', + Provisions: 'Provisions', + NumberProvisions: 'Number of associated provisions', + 'cluster.create.selection.head': 'Creating New Cluster', + 'cluster.create.selection.title': 'Choose Your Deployment Type', + 'cluster.create.selection.subtitle': + 'Select how you want to create the cluster.', + 'cluster.create.opennebula.title': 'OpenNebula Cluster', + 'cluster.create.opennebula.subtitle': + 'Manually create new infrastructure on-premise.', + 'cluster.create.opennebula.help': 'More info in OpenNebula Documentation.', + 'cluster.create.provider.title': 'Cloud Provider', + 'cluster.create.provider.subtitle': + 'Automatically provision new infrastructure on cloud provider', + 'cluster.create.provider.help': 'More info in OpenNebula Documentation.', + 'cluster.create.onpremise.title': 'On-premise Cluster', + 'cluster.create.onpremise.subtitle': + 'Automatically provision new infrastructure on-premise', + 'cluster.create.onpremise.help': 'More info in OpenNebula Documentation.', + 'cluster.deployment_conf': 'Deployment configurations', 'cluster.form.create.general.help.title': 'Cluster', 'cluster.form.create.general.help.paragraph.1.1': 'Clusters group together hosts, datastores and virtual networks that are configured to work together. A cluster is used to:', @@ -722,6 +749,13 @@ module.exports = { 'FQDN or IP that OpenNebula can use to reach the hypervisor host', 'host.form.create.general.name.tooltip': "Please make sure the OpenNebula front-end can ssh passwrodlessly to the host using the 'oneadmin' user", + 'cluster.create.provisioning.description': + 'OneForm is automatically provisioning your cloud infrastructure. This typically takes 5-10 minutes.', + 'oneformtags.info': + 'Optional key-value pairs that will be propagated in the OpenNebula and Cloud resources', + 'oneform.info.more': 'See OpenNebula documentation to get more details ', + 'oneform.info.more.link': 'about OneForm service configuration.', + 'cluster.vnet.del.ip': 'Delete IP range', /* sections - network */ Network: 'Network', @@ -1922,6 +1956,18 @@ module.exports = { NumberOfAddresses: 'Number of addresses', AddToNewVirtualNetwork: 'Add to a new Virtual Network', AddToExistingReservation: 'Add to an existing Reservation', + AddHostProvision: 'Add Host to Provision', + AddHostProvisionSuccess: 'Host(s) added to provision successfully', + DeleteHostProvisionSuccess: 'Host(s) deleted from provision successfully', + DeleteVnetProvisionSuccess: 'Vnet(s) deleted from provision successfully', + AddIpsProvision: 'Add public IPs', + AddIpsProvisionSuccess: 'Public IPs added to the provision', + DeleteIpsProvisionSuccess: 'IP deleted', + DeleteHostProvision: 'Delete Provision Hosts', + NumberOfHostsToAdd: 'Number of Hosts to Add', + NumberOfIPsToAdd: 'Number of IPs to add', + SelectNewHostsToAdd: 'Select New Hosts to Add', + SelectNewVnetsToAdd: 'Select New Vnets to Add', FirstAddress: 'First address', IpOrMac: 'IP or MAC', MessageQos: @@ -1980,6 +2026,7 @@ module.exports = { /* Cluster schema */ CreateCluster: 'Create Cluster', 'cluster.create.name': 'Name', + 'cluster.create.description': 'Description', 'cluster.create.general.info': 'Cluster info', /* Cluster schema - capacity */ @@ -2206,6 +2253,7 @@ module.exports = { Max: 'Max', DefaultValue: 'Default value', Mandatory: 'Mandatory', + PressKeysToAddAHost: 'Add a hostname or IP address and press %s', PressKeysToAddAValue: 'Press any of the following keys to add a value: %s', MandatoryUserInputs: 'Show only mandatory inputs', Suggestion: 'Suggestion', @@ -2558,6 +2606,7 @@ module.exports = { SuccessVNetTemplateUpdated: 'Virtual Network Template updated - #%s %s', /* Error messages */ + ErrorCommaSeparatedValues: 'Must match a comma separated values list', ErrorExportingData: 'Error exporting data to %s : %s', ErrorVmTemplateFetching: 'Error fetching VM templates data: %s', ErrorHostFetching: 'Error fetching host data: %s', @@ -2574,6 +2623,7 @@ module.exports = { ErrorClusterOperation: 'Error performing operation on cluster', ErrorGroupCreated: 'Error creating group', ErrorMarketplaceCreated: 'Error creating marketplace', + ErrorProviderCreated: 'Error creating provider', ErrorProviderTemplateSelected: 'The template selected has a bad format. Ask your cloud administrator', ErrorShowbackCalculated: 'Error calculating showback: %s', @@ -2594,6 +2644,28 @@ module.exports = { Synchronize: 'Synchronize', Source: 'Source', + /* Connection Values */ + ConnectionValues: 'Connection Values', + access_key: 'Access Key', + auth_token: 'Auth Token', + i3dnet_api_key: 'i3D.net API Key', + project_id: 'Project ID', + region: 'Region', + secret_key: 'Secret Key', + zone: 'Zone', + + /* Provision User Inputs */ + cidr_block: 'CIDR Block', + instance_disk_size: 'Disk instance size', + instance_os_name: 'Instance OS name', + instance_type: 'Instance Type', + oneform_hosts: 'Number of Hosts', + oneform_public_ips: 'Number of Public IPs', + oneform_onprem_hosts: 'Onprem Hosts', + phydev_name: 'Physical interface', + /* Log viewer */ 'logs.level': 'Level', + + LearnMore: 'Learn more', } diff --git a/src/fireedge/src/modules/containers/Clusters/CreateCloud.js b/src/fireedge/src/modules/containers/Clusters/CreateCloud.js new file mode 100644 index 0000000000..e6c91ba536 --- /dev/null +++ b/src/fireedge/src/modules/containers/Clusters/CreateCloud.js @@ -0,0 +1,100 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { + DefaultFormStepper, + Form, + SkeletonStepsForm, + TranslateProvider, +} from '@ComponentsModule' +import { ReactElement } from 'react' +// import { generatePath, useHistory } from 'react-router-dom' +import { generatePath, useHistory, useLocation } from 'react-router' + +import { T } from '@ConstantsModule' +import { + ProvisionAPI, + DriverAPI, + ProviderAPI, + useGeneralApi, +} from '@FeaturesModule' +import { PATH } from '@modules/components/path' +import { get, filter } from 'lodash' +const { Cluster } = Form + +/** + * Displays the creation form for a cluster. + * + * @returns {ReactElement} - The cluster form component + */ +export function CreateClusterCloud() { + // Get history to redirect to forms + const history = useHistory() + const { enqueueError, enqueueSuccess } = useGeneralApi() + + // Check if using onpremise provider + const { state: { onpremiseProvider = false } = {} } = useLocation() + + const { data: providers } = ProviderAPI.useGetProvidersQuery() + const { data: drivers } = DriverAPI.useGetDriversQuery() + + // Use _.filter to get all items with driver="onprem" so when the user choose onprem, use the default onprem provider + const onpremProviders = filter( + providers, + (item) => get(item, 'TEMPLATE.PROVIDER_BODY.driver') === 'onprem' + ) + + // Create cluster request + const [allocateOneFormCluster] = ProvisionAPI.useCreateProvisionMutation() + + // In this current version only Provision creation is supported + const onSubmit = async (jsonTemplate) => { + try { + const { + DOCUMENT: { ID: newProvisionId }, + } = await allocateOneFormCluster({ + template: jsonTemplate, + }).unwrap() + history.push( + generatePath(PATH.INFRASTRUCTURE.CLUSTERS.CREATE_CLOUD_LOGS, { + id: newProvisionId, + }) + ) + enqueueSuccess(T.SuccessProviderCreated, [newProvisionId]) + } catch { + enqueueError(T.ErrorProviderCreated) + } + } + + return ( + + {!providers || !drivers ? ( + + ) : ( + } + > + {(config) => } + + )} + + ) +} diff --git a/src/fireedge/src/modules/containers/Clusters/CreateCloudLogs.js b/src/fireedge/src/modules/containers/Clusters/CreateCloudLogs.js new file mode 100644 index 0000000000..e634421364 --- /dev/null +++ b/src/fireedge/src/modules/containers/Clusters/CreateCloudLogs.js @@ -0,0 +1,146 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { ReactElement, useEffect, useState, useMemo } from 'react' +import { Redirect, useParams } from 'react-router-dom' +import { SkeletonStepsForm, TranslateProvider } from '@ComponentsModule' +import { Box, Stack, Typography, useTheme, LinearProgress } from '@mui/material' +import { ProvisionAPI } from '@FeaturesModule' +import LogsViewer from '@modules/components/LogsViewer' +import { Tr } from '@modules/components/HOC' +import { T } from '@ConstantsModule' +import { StatusChip } from '@modules/components/Status' +import { styles } from '@modules/containers/Clusters/styles' +import { last, filter } from 'lodash' +import { getProvisionColorState, getProvisionProgress } from '@ModelsModule' + +/** + * Displays the creation form for a cluster. + * + * @returns {ReactElement} - The cluster form component + */ +export function CreateClusterCloudLogs() { + // Get styles + const theme = useTheme() + const classes = useMemo(() => styles(theme), [theme]) + + const { id } = useParams() + + if (Number.isNaN(+id)) { + return + } + + // Get provision + const { data: provision } = ProvisionAPI.useGetProvisionQuery( + { id: id }, + { + pollingInterval: 3000, + skipPollingIfUnfocused: true, + } + ) + + // Handle progress in the progress bar + const [progress, setProgress] = useState(0) + useEffect(() => { + const nextProgress = getProvisionProgress( + provision?.TEMPLATE?.PROVISION_BODY?.state + ) + + // Only update if it's a valid number + if (typeof nextProgress === 'number') { + setProgress(nextProgress) + } + // if undefined → do nothing → bar stays where it is + }, [provision]) + + // Get logs + const { data: logsData } = ProvisionAPI.useGetProvisionLogsQuery( + { id: id, all: true }, + { + pollingInterval: 3000, + skipPollingIfUnfocused: true, + } + ) + + // Get last info from logs to display to the user + const lastInfo = useMemo( + () => (logs) => { + // Get message + const log = last(filter(logs?.lines, { level: 'info' })) + + // Delete date and level + const regexDate = /^(.+?\[\w\])\s*(.*)/ + const matchDate = log?.text.match(regexDate) + const message = matchDate ? matchDate[2] : log.text + + return message + }, + [logsData] + ) + + return logsData ? ( + + + + {Tr(T['cluster.create.provisioning.description'])} + + + + {provision?.NAME} + + + + + + + {progress < 100 && ( + + {lastInfo(logsData)} + + )} + = 100 ? classes.solidBar : classes.animatedBar, + }} + /> + + + + + ) : ( + + ) +} diff --git a/src/fireedge/src/modules/containers/Clusters/index.js b/src/fireedge/src/modules/containers/Clusters/index.js index d33b0725a3..f2b9fd66ca 100644 --- a/src/fireedge/src/modules/containers/Clusters/index.js +++ b/src/fireedge/src/modules/containers/Clusters/index.js @@ -15,4 +15,6 @@ * ------------------------------------------------------------------------- */ export * from '@modules/containers/Clusters/Clusters' export * from '@modules/containers/Clusters/Create' +export * from '@modules/containers/Clusters/CreateCloud' +export * from '@modules/containers/Clusters/CreateCloudLogs' export * from '@modules/containers/Clusters/Detail' diff --git a/src/fireedge/src/modules/containers/Clusters/styles.js b/src/fireedge/src/modules/containers/Clusters/styles.js new file mode 100644 index 0000000000..4362fc5123 --- /dev/null +++ b/src/fireedge/src/modules/containers/Clusters/styles.js @@ -0,0 +1,56 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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. * + * ------------------------------------------------------------------------- */ +/* eslint-disable jsdoc/require-jsdoc */ +import { css, keyframes } from '@emotion/css' + +const flow = keyframes` + 0% { background-position: 0% 50%; } + 100% { background-position: 300% 50%; } +` + +export const styles = ({ palette }) => ({ + root: css({ + height: '12px', + borderRadius: '96px', + backgroundColor: palette.progressBar.pending.color, + }), + animatedBar: css({ + backgroundImage: `linear-gradient( + 90deg, + ${palette.progressBar.completed.color}, + ${palette.progressBar.completed.auxColor}, + ${palette.progressBar.completed.color} + )`, + backgroundSize: '200% 100%', + animation: `${flow} 4s linear infinite`, + }), + solidBar: css({ + backgroundColor: palette.progressBar.completed.color, + }), + infoText: css({ + color: palette.primary.main, + fontSize: '14px', + fontStyle: 'normal', + fontWeight: 500, + lineHeight: '16px', + }), + titleText: css({ + fontSize: '14px', + fontStyle: 'normal', + fontWeight: 600, + lineHeight: '16px', + }), +}) diff --git a/src/fireedge/src/modules/containers/Providers/Create.js b/src/fireedge/src/modules/containers/Providers/Create.js new file mode 100644 index 0000000000..eab1628507 --- /dev/null +++ b/src/fireedge/src/modules/containers/Providers/Create.js @@ -0,0 +1,98 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { ReactElement } from 'react' +import { useHistory, useLocation } from 'react-router' + +import { useGeneralApi, ProviderAPI, DriverAPI } from '@FeaturesModule' + +import { + DefaultFormStepper, + SkeletonStepsForm, + PATH, + Form, + TranslateProvider, +} from '@ComponentsModule' +import { T } from '@ConstantsModule' + +const _ = require('lodash') +const { Provider } = Form + +/** + * Displays the creation or modification form to a Provider. + * + * @returns {ReactElement} Provider form + */ +export function CreateProvider() { + const history = useHistory() + const { state: { ID: providerId, NAME } = {} } = useLocation() + + const { enqueueSuccess, enqueueError } = useGeneralApi() + const [update] = ProviderAPI.useUpdateProviderMutation() + const [allocate] = ProviderAPI.useCreateProviderMutation() + + const { data: apiTemplateData } = ProviderAPI.useGetProviderQuery({ + id: providerId, + }) + + const { data: drivers } = DriverAPI.useGetDriversQuery() + + const dataTemplate = _.cloneDeep(apiTemplateData) + + const onSubmit = async (jsonTemplate) => { + try { + if (!providerId) { + const { + DOCUMENT: { ID: newProviderId, NAME: providerName }, + } = await allocate({ + template: jsonTemplate, + }).unwrap() + + history.push(PATH.INFRASTRUCTURE.PROVIDERS.LIST) + enqueueSuccess(T.SuccessProviderCreated, [newProviderId, providerName]) + } else { + await update({ + id: providerId, + template: jsonTemplate, + merge: false, + }).unwrap() + history.push(PATH.INFRASTRUCTURE.PROVIDERS.LIST) + enqueueSuccess(T.SuccessProviderUpdated, [providerId, NAME]) + } + } catch { + enqueueError(T.ErrorProviderCreated) + } + } + + return ( + + {!drivers || (providerId && !dataTemplate) ? ( + + ) : ( + } + > + {(config) => } + + )} + + ) +} diff --git a/src/fireedge/src/modules/containers/Providers/Detail.js b/src/fireedge/src/modules/containers/Providers/Detail.js new file mode 100644 index 0000000000..30a70971a7 --- /dev/null +++ b/src/fireedge/src/modules/containers/Providers/Detail.js @@ -0,0 +1,39 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { ProvidersTable } from '@modules/components/Tables' +import { ReactElement } from 'react' +import { Redirect, useParams } from 'react-router-dom' + +import { ProviderTabs, TranslateProvider } from '@ComponentsModule' + +/** + * Displays the detail information about a Provider. + * + * @returns {ReactElement} Provider detail component. + */ +export function ProviderDetail() { + const { id } = useParams() + + if (Number.isNaN(+id)) { + return + } + + return ( + + + + ) +} diff --git a/src/fireedge/src/modules/containers/Providers/Providers.js b/src/fireedge/src/modules/containers/Providers/Providers.js new file mode 100644 index 0000000000..4cad94d8b7 --- /dev/null +++ b/src/fireedge/src/modules/containers/Providers/Providers.js @@ -0,0 +1,231 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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. * + * ------------------------------------------------------------------------- */ +/* eslint-disable react/prop-types */ +import { Chip, Stack } from '@mui/material' +import { + Cancel, + Collapse, + Expand, + NavArrowLeft, + RefreshDouble, +} from 'iconoir-react' +import { Row } from 'opennebula-react-table' +import PropTypes from 'prop-types' +import { memo, ReactElement, useEffect, useState } from 'react' + +import { + GlobalLabel, + MultipleTags, + ResourcesBackButton, + ProvidersTable, + ProviderTabs, + SubmitButton, + Tr, + TranslateProvider, +} from '@ComponentsModule' +import { RESOURCE_NAMES, SERVER_CONFIG, T } from '@ConstantsModule' +import { + ProviderAPI, + useAuth, + useGeneral, + useGeneralApi, +} from '@FeaturesModule' + +/** + * Displays a list of Providers with a split pane between + * the list and selected row(s). + * + * @returns {ReactElement} Providers list and selected row(s) + */ +export function Providers() { + const [selectedRows, setSelectedRows] = useState(() => []) + const actions = ProvidersTable.Actions({ + selectedRows, + setSelectedRows, + }) + const { zone } = useGeneral() + + return ( + + ( + + )} + simpleGroupsTags={(props) => ( + + )} + info={(props) => { + const propsInfo = { + template: props?.selectedRows?.[0]?.original, + selectedRows: props?.selectedRows, + } + props?.gotoPage && (propsInfo.gotoPage = props.gotoPage) + props?.unselect && (propsInfo.unselect = props.unselect) + + return + }} + /> + + ) +} + +/** + * Displays details of a Provider. + * + * @param {object} template - Provider to display + * @param {Function} [gotoPage] - Function to navigate to a page of a Provider + * @param {Function} [unselect] - Function to unselect a Provider + * @param {object[]} [selectedRows] - Selected rows (for Labels) + * @returns {ReactElement} Provider details + */ +const InfoTabs = memo(({ template, gotoPage, unselect, selectedRows }) => { + const [get, { data: lazyData, isFetching }] = + ProviderAPI.useLazyGetProviderQuery() + const id = template?.ID ?? lazyData?.ID + + const { settings: { FIREEDGE: fireedge = {} } = {} } = useAuth() + const { FULL_SCREEN_INFO } = fireedge + const { fullViewMode } = SERVER_CONFIG + const fullModeDefault = + FULL_SCREEN_INFO === 'true' || fullViewMode === 'true' || false + const { isFullMode } = useGeneral() + const { setFullMode } = useGeneralApi() + + useEffect(() => { + !isFullMode && gotoPage() + }, []) + + return ( + + + + {fullModeDefault && ( + } + tooltip={Tr(T.Back)} + isSubmitting={isFetching} + onClick={() => unselect()} + /> + )} + + + + {fullModeDefault && ( + + )} + {!fullModeDefault && ( + : } + tooltip={Tr(T.FullScreen)} + isSubmitting={isFetching} + onClick={() => { + setFullMode(!isFullMode) + }} + /> + )} + } + tooltip={Tr(T.Refresh)} + isSubmitting={isFetching} + onClick={() => get({ id })} + /> + {typeof unselect === 'function' && ( + } + tooltip={Tr(T.Close)} + onClick={() => unselect()} + /> + )} + + + + + ) +}) + +InfoTabs.propTypes = { + template: PropTypes.object, + gotoPage: PropTypes.func, + unselect: PropTypes.func, +} + +InfoTabs.displayName = 'InfoTabs' + +/** + * Displays a list of tags that represent the selected rows. + * + * @param {Row[]} tags - Row(s) to display as tags + * @returns {ReactElement} List of tags + */ +const GroupedTags = ({ + tags = [], + handleElement = true, + onDelete = () => undefined, +}) => ( + + { + const { original, id, toggleRowSelected, gotoPage } = props + const clickElement = handleElement + ? { + onClick: gotoPage, + onDelete: () => onDelete(id) || toggleRowSelected(false), + } + : {} + + return + })} + /> + +) + +GroupedTags.propTypes = { + tags: PropTypes.array, + handleElement: PropTypes.bool, + onDelete: PropTypes.func, +} +GroupedTags.displayName = 'GroupedTags' diff --git a/src/fireedge/src/modules/containers/Providers/index.js b/src/fireedge/src/modules/containers/Providers/index.js new file mode 100644 index 0000000000..e581f2c24f --- /dev/null +++ b/src/fireedge/src/modules/containers/Providers/index.js @@ -0,0 +1,18 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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. * + * ------------------------------------------------------------------------- */ +export * from '@modules/containers/Providers/Create' +export * from '@modules/containers/Providers/Detail' +export * from '@modules/containers/Providers/Providers' diff --git a/src/fireedge/src/modules/containers/index.js b/src/fireedge/src/modules/containers/index.js index fd88cb7f15..39f6602b79 100644 --- a/src/fireedge/src/modules/containers/index.js +++ b/src/fireedge/src/modules/containers/index.js @@ -28,6 +28,7 @@ export * from '@modules/containers/Images' export * from '@modules/containers/Login' export * from '@modules/containers/MarketplaceApps' export * from '@modules/containers/Marketplaces' +export * from '@modules/containers/Providers' export * from '@modules/containers/SecurityGroups' export * from '@modules/containers/Services' export * from '@modules/containers/ServiceTemplates' diff --git a/src/fireedge/src/modules/features/Logs/hooks.js b/src/fireedge/src/modules/features/Logs/hooks.js new file mode 100644 index 0000000000..e68623f446 --- /dev/null +++ b/src/fireedge/src/modules/features/Logs/hooks.js @@ -0,0 +1,32 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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. * + * ------------------------------------------------------------------------- */ +/* eslint-disable jsdoc/require-jsdoc */ +import { useDispatch, useSelector, shallowEqual } from 'react-redux' +import { setLogs, setSearchText, LogsSlice } from '@modules/features/Logs/slice' + +const { name: logsSlice } = LogsSlice + +export const useLogs = () => + useSelector((state) => state[logsSlice], shallowEqual) + +export const useLogsApi = () => { + const dispatch = useDispatch() + + return { + setLogs: (logs) => dispatch(setLogs(logs)), + setSearchText: (filter) => dispatch(setSearchText(filter)), + } +} diff --git a/src/fireedge/src/modules/features/Logs/index.js b/src/fireedge/src/modules/features/Logs/index.js new file mode 100644 index 0000000000..57df06ad94 --- /dev/null +++ b/src/fireedge/src/modules/features/Logs/index.js @@ -0,0 +1,17 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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. * + * ------------------------------------------------------------------------- */ +export * from '@modules/features/Logs/hooks' +export * from '@modules/features/Logs/slice' diff --git a/src/fireedge/src/modules/features/Logs/slice.js b/src/fireedge/src/modules/features/Logs/slice.js new file mode 100644 index 0000000000..10eac74286 --- /dev/null +++ b/src/fireedge/src/modules/features/Logs/slice.js @@ -0,0 +1,87 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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. * + * ------------------------------------------------------------------------- */ +// src/features/logs/logsSlice.js +import { createSlice, createAsyncThunk } from '@reduxjs/toolkit' +import axios from 'axios' + +// Async thunk to fetch all logs +export const fetchLogs = createAsyncThunk('logs/fetchLogs', async () => { + const response = await axios.get('/api/logs') // Adjust endpoint + + return response.data.data.lines // Assuming your API response structure +}) + +const logsSlice = createSlice({ + name: 'logs', + initialState: { + allLogs: [], + filteredLogs: [], + status: 'idle', + error: null, + levelFilter: 'all', + searchText: '', + }, + reducers: { + setLogs(state, { payload }) { + state.allLogs = payload + }, + setLevelFilter(state, action) { + state.levelFilter = action.payload + state.filteredLogs = filterLogs( + state.allLogs, + state.levelFilter, + state.searchText + ) + }, + setSearchText(state, action) { + state.searchText = action.payload + state.filteredLogs = filterLogs( + state.allLogs, + state.levelFilter, + state.searchText + ) + }, + }, + extraReducers: (builder) => { + builder + .addCase(fetchLogs.pending, (state) => { + state.status = 'loading' + }) + .addCase(fetchLogs.fulfilled, (state, action) => { + state.status = 'succeeded' + state.allLogs = action.payload + state.filteredLogs = filterLogs( + action.payload, + state.levelFilter, + state.searchText + ) + }) + .addCase(fetchLogs.rejected, (state, action) => { + state.status = 'failed' + state.error = action.error.message + }) + }, +}) + +function filterLogs(logs, level, searchText) { + return logs.filter((log) => + log?.text?.toLowerCase().includes(searchText?.toLowerCase()) + ) +} + +export const { setLevelFilter, setSearchText, setLogs } = logsSlice.actions + +export { logsSlice as LogsSlice } diff --git a/src/fireedge/src/modules/features/OneApi/driver.js b/src/fireedge/src/modules/features/OneApi/driver.js index 1152beb90e..b96ee68b30 100644 --- a/src/fireedge/src/modules/features/OneApi/driver.js +++ b/src/fireedge/src/modules/features/OneApi/driver.js @@ -37,6 +37,11 @@ const driverApi = oneApi.injectEndpoints({ return { command } }, + transformResponse: (data) => + data.map((driver) => ({ + ...driver, + name: driver.name.toLowerCase(), + })), providesTags: (drivers) => drivers ? [ @@ -64,7 +69,10 @@ const driverApi = oneApi.injectEndpoints({ return { params, command } }, - providesTags: (_, __, { name }) => [{ type: DRIVER, id: name }], + transformResponse: (data) => ({ ...data, name: data.name.toLowerCase() }), + providesTags: (_, __, { name }) => [ + { type: DRIVER, id: name.toLowerCase() }, + ], }), enableDriver: builder.mutation({ diff --git a/src/fireedge/src/modules/features/OneApi/index.js b/src/fireedge/src/modules/features/OneApi/index.js index 1df018adc4..b02e8f5161 100644 --- a/src/fireedge/src/modules/features/OneApi/index.js +++ b/src/fireedge/src/modules/features/OneApi/index.js @@ -26,6 +26,10 @@ import ImageAPI from '@modules/features/OneApi/image' import LogoAPI from '@modules/features/OneApi/logo' import MarketplaceAPI from '@modules/features/OneApi/marketplace' import MarketplaceAppAPI from '@modules/features/OneApi/marketplaceApp' +import ProviderAPI from '@modules/features/OneApi/provider' +import ProvisionAPI, { + provisionEndpoints, +} from '@modules/features/OneApi/provision' import VnAPI from '@modules/features/OneApi/network' import VnTemplateAPI from '@modules/features/OneApi/networkTemplate' import { oneApi } from '@modules/features/OneApi/oneApi' @@ -69,6 +73,9 @@ export { ONE_RESOURCES, ONE_RESOURCES_POOL, oneApi, + ProviderAPI, + ProvisionAPI, + provisionEndpoints, SecurityGroupAPI, ServiceAPI, ServiceTemplateAPI, diff --git a/src/fireedge/src/modules/features/OneApi/provider.js b/src/fireedge/src/modules/features/OneApi/provider.js new file mode 100644 index 0000000000..607593f018 --- /dev/null +++ b/src/fireedge/src/modules/features/OneApi/provider.js @@ -0,0 +1,328 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { Actions, Commands } from 'server/routes/api/oneform/provider/routes' +import { oneApi } from '@modules/features/OneApi/oneApi' +import { FORM, FORM_POOL } from '@modules/features/OneApi/resources' +import { + updateResourceOnPool, + updateNameOnResource, + updateOwnershipOnResource, +} from '@modules/features/OneApi/common' +import { Provider } from '@ConstantsModule' + +const { PROVIDER } = FORM +const { PROVIDER_POOL } = FORM_POOL + +const basicEndpoints = (builder) => ({ + getProviders: builder.query({ + /** + * Retrieves information for all providers. + * + * @returns {Provider[]} List of providers + * @throws Fails when response isn't code 200 + */ + query: () => { + const name = Actions.LIST + const command = { name, ...Commands[name] } + + return { command } + }, + transformResponse: (data) => + data.map((provider) => provider.DOCUMENT ?? {}), + providesTags: (providers) => + providers + ? [ + ...providers.map(({ ID }) => ({ + type: PROVIDER_POOL, + id: `${ID}`, + })), + PROVIDER_POOL, + ] + : [PROVIDER_POOL], + }), + + getProvider: builder.query({ + /** + * Retrieves information of a single provider. + * + * @param {object} params - Request params + * @param {string} params.id - Provider name + * @returns {Provider} Provider object + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const name = Actions.SHOW + const command = { name, ...Commands[name] } + + return { params, command } + }, + transformResponse: (data) => data?.DOCUMENT ?? {}, + providesTags: (_, __, { id }) => [{ type: PROVIDER, id }], + }), + + createProvider: builder.mutation({ + /** + * Create a new provider. + * + * @param {object} params - Request params + * @param {object} params.template - Provider template data in JSON syntax + * @returns {number} Service template id + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const name = Actions.CREATE + const command = { name, ...Commands[name] } + + return { params, command } + }, + invalidatesTags: [PROVIDER_POOL], + }), + updateProvider: builder.mutation({ + /** + * Updates the provider contents. + * + * @param {object} params - Request params + * @param {string} params.id - Provider id + * @param {object} params.template - The new template contents + * @param {boolean} [params.merge] + * - ``true``: Merge new template with the existing one. + * - ``false``: Replace the whole template. + * + * By default, ``true``. + * @returns {number} Provider id + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const name = Actions.UPDATE + const command = { name, ...Commands[name] } + + return { params, command } + }, + invalidatesTags: (_, __, { id }) => [{ type: PROVIDER, id }], + async onQueryStarted(params, { dispatch, queryFulfilled }) { + try { + const patchProvider = dispatch( + providerApi.util.updateQueryData( + 'getProvider', + { id: params.id }, + updateNameOnResource(params) + ) + ) + + const patchProviders = dispatch( + providerApi.util.updateQueryData( + 'getProviders', + undefined, + updateNameOnResource(params) + ) + ) + + queryFulfilled.catch(() => { + patchProvider.undo() + patchProviders.undo() + }) + } catch {} + }, + }), + renameProvider: builder.mutation({ + /** + * Renames a Provider. + * + * @param {object} params - Request parameters + * @param {string|number} params.id - Provider id + * @param {string} params.name - The new name + * @returns {number} Provider id + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const cName = Actions.UPDATE + const command = { name: cName, ...Commands[cName] } + + return { params, command } + }, + invalidatesTags: (_, __, { id }) => [{ type: PROVIDER, id }], + async onQueryStarted(params, { dispatch, queryFulfilled }) { + try { + const patchProvider = dispatch( + providerApi.util.updateQueryData( + 'getProvider', + { id: params.id }, + updateNameOnResource(params) + ) + ) + + const patchProviders = dispatch( + providerApi.util.updateQueryData( + 'getProviders', + undefined, + updateNameOnResource({ id: params.id, name: params.template.name }) + ) + ) + + queryFulfilled.catch(() => { + patchProvider.undo() + patchProviders.undo() + }) + } catch {} + }, + }), + removeProvider: builder.mutation({ + /** + * Deletes a provider. + * + * @param {object} params - Request params + * @param {string} params.id - Provider id + * @returns {number} Provider id + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const name = Actions.DELETE + const command = { name, ...Commands[name] } + + return { params, command } + }, + invalidatesTags: [PROVIDER_POOL], + }), + changeProviderPermissions: builder.mutation({ + /** + * Changes the permission bits of a Provider. + * If set to `-1`, it's not changed. + * + * @param {object} params - Request parameters + * @param {string} params.id - Provider id + * @param {string} params.octet - Permissions in octal format + * @returns {number} Provider id + * @throws Fails when response isn't code 200 + */ + query: ({ octet, ...params }) => { + params.octet = octet + const name = Actions.CHMOD + const command = { name, ...Commands[name] } + + return { params, command } + }, + invalidatesTags: (_, __, { id }) => [{ type: PROVIDER, id }], + async onQueryStarted(params, { dispatch, queryFulfilled }) { + try { + const patchProvider = dispatch( + providerApi.util.updateQueryData( + 'getProvider', + { id: params.id }, + updateResourceOnPool(params) + ) + ) + + const patchProviders = dispatch( + providerApi.util.updateQueryData( + 'getProviders', + undefined, + updateResourceOnPool(params) + ) + ) + + queryFulfilled.catch(() => { + patchProvider.undo() + patchProviders.undo() + }) + } catch {} + }, + }), + changeProviderOwnership: builder.mutation({ + /** + * Changes the ownership bits of a provider. + * If set to `-1`, the user or group is not changed. + * + * @param {object} params - Request parameters + * @param {string} params.id - Provider id + * @param {number} params.user - New user id + * @param {number} params.group - New group id + * @returns {number} Provider id + * @throws Fails when response isn't code 200 + */ + query: ({ user = '-1', group = '-1', ...params }) => { + params.owner_id = user + params.group_id = group + + const name = Actions.CHOWN + const command = { name, ...Commands[name] } + + return { params, command } + }, + invalidatesTags: (_, __, { id }) => [{ type: PROVIDER, id }], + async onQueryStarted(params, { getState, dispatch, queryFulfilled }) { + try { + const patchProvider = dispatch( + providerApi.util.updateQueryData( + 'getProvider', + { id: params.id }, + updateOwnershipOnResource(getState(), params) + ) + ) + + const patchProviders = dispatch( + providerApi.util.updateQueryData( + 'getProviders', + undefined, + updateOwnershipOnResource(getState(), params) + ) + ) + + queryFulfilled.catch(() => { + patchProvider.undo() + patchProviders.undo() + }) + } catch {} + }, + }), +}) + +const providerApi = oneApi.injectEndpoints({ + endpoints: (builder) => ({ + ...basicEndpoints(builder), + }), +}) + +export const providerQueries = (({ + // Queries + useGetProvidersQuery, + useLazyGetProvidersQuery, + useGetProviderQuery, + useLazyGetProviderQuery, + + // Mutations + useCreateProviderMutation, + useUpdateProviderMutation, + useRenameProviderMutation, + useRemoveProviderMutation, + useChangeProviderPermissionsMutation, + useChangeProviderOwnershipMutation, +}) => ({ + // Queries + useGetProvidersQuery, + useLazyGetProvidersQuery, + useGetProviderQuery, + useLazyGetProviderQuery, + + // Mutations + useCreateProviderMutation, + useUpdateProviderMutation, + useRenameProviderMutation, + useRemoveProviderMutation, + useChangeProviderPermissionsMutation, + useChangeProviderOwnershipMutation, +}))(providerApi) + +export default providerQueries diff --git a/src/fireedge/src/modules/features/OneApi/provision.js b/src/fireedge/src/modules/features/OneApi/provision.js new file mode 100644 index 0000000000..eee74b06a7 --- /dev/null +++ b/src/fireedge/src/modules/features/OneApi/provision.js @@ -0,0 +1,295 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { Actions, Commands } from 'server/routes/api/oneform/provision/routes' + +import { oneApi } from '@modules/features/OneApi/oneApi' +import { FORM, FORM_POOL } from '@modules/features/OneApi/resources' +const { PROVISION_POOL } = FORM_POOL +const { PROVISION } = FORM + +const provisionApi = oneApi.injectEndpoints({ + endpoints: (builder) => ({ + getProvisions: builder.query({ + /** + * Retrieves information for all the provisions. + * + * @param {object} params - Request params + * @param {boolean} params.extended - Whether to retrieve extended information + * @returns {object[]} List of provisions + * @throws Fails when response isn't code 200 + */ + query: ({ extended = false, ...params }) => { + const name = Actions.LIST + const command = { name, ...Commands[name] } + + return { + params: { ...params, ...(extended ? { extended } : {}) }, + command, + } + }, + transformResponse: (data) => { + if (!Array.isArray(data)) return [] + + return data.map((item) => item.DOCUMENT) + }, + }), + + getProvision: builder.query({ + /** + * Retrieves information for one the provisions. + * + * @param {object} params - Request params + * @param {boolean} params.extended - Whether to retrieve extended information + * @returns {object} show provisions + * @throws Fails when response isn't code 200 + */ + query: ({ extended = false, ...params }) => { + const name = Actions.SHOW + const command = { name, ...Commands[name] } + + return { + params: { ...params, ...(extended ? { extended } : {}) }, + command, + } + }, + transformResponse: (data) => { + if (!data?.DOCUMENT) return {} + + return data.DOCUMENT + }, + providesTags: [], + }), + + getProvisionLogs: builder.query({ + /** + * Retrieves log for a provider. + * + * @param {object} params - Request params + * @param {number} params.id - Provision id + * @returns {object} Provider logs + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const name = Actions.LOGS + const command = { name, ...Commands[name] } + + return { params, command } + }, + keepUnusedDataFor: 0, + providesTags: [], + }), + + scaleProvisionHosts: builder.mutation({ + /** + * Add hosts to a provision. + * + * @param {object} params - Request parameters + * @param {string|number} params.id - User id + * @param {string|number} params.hosts - New host ids to add + * @returns {number} User id + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const name = Actions.ADD_HOST + Array.isArray(params?.hosts) + ? (params.ips = params.hosts.join(',')) + : (params.amount = params.hosts) + delete params.hosts + const command = { name, ...Commands[name] } + + return { params, command } + }, + }), + + deleteHostProvision: builder.mutation({ + /** + * Add hosts to a provision. + * + * @param {object} params - Request parameters + * @param {string|number} params.id - provision id + * @param {string} params.direction - Scale direction (up|down) + * @param {number} params.nodes - Number of nodes to scale + * @returns {number} User id + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const name = Actions.SCALE + Array.isArray(params?.hosts) + ? (params.ips = params.hosts.join(',')) + : (params.amount = params.hosts) + delete params.hosts + const command = { name, ...Commands[name] } + + return { params, command } + }, + }), + + addIpsProvision: builder.mutation({ + /** + * Add IPs to a provision. + * + * @param {object} params - Request parameters + * @param {string|number} params.id - provision id + * @param {string|number} params.amount - Number of IPs to add + * @returns {number} provision id + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const name = Actions.ADD_IP + const command = { name, ...Commands[name] } + + return { params, command } + }, + }), + + deleteIpsProvision: builder.mutation({ + /** + * Delete IPs for a provision. + * + * @param {object} params - Request parameters + * @param {string|number} params.id - provision id + * @param {string|number} params.ar_id - Address range to delete + * @returns {number} provision id + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const name = Actions.REMOVE_IP + const command = { name, ...Commands[name] } + + return { params, command } + }, + }), + + createProvision: builder.mutation({ + /** + * Create a new provision. + * + * @param {object} params - Request params + * @param {object} params.template - Provision template data in JSON syntax + * @returns {number} provision id + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const name = Actions.CREATE + const command = { name, ...Commands[name] } + + return { params, command } + }, + invalidatesTags: [PROVISION_POOL], + }), + retryProvision: builder.mutation({ + /** + * Retry a provision. + * + * @param {object} params - Request parameters + * @param {string|number} params.id - provision id + * @returns {string} OK + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const name = Actions.RETRY + const command = { name, ...Commands[name] } + + return { params, command } + }, + invalidatesTags: (result, error, { id }) => [ + { type: PROVISION, id }, + { type: PROVISION_POOL }, + ], + }), + undeployProvision: builder.mutation({ + /** + * Undeploy a provision. + * + * @param {object} params - Request parameters + * @param {string|number} params.id - provision id + * @param {boolean} params.force - Force undeploy + * @returns {number} provision id + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const name = Actions.UNDEPLOY + const command = { name, ...Commands[name] } + + return { params, command } + }, + invalidatesTags: (result, error, { id }) => [ + { type: PROVISION, id }, + { type: PROVISION_POOL }, + ], + }), + removeProvision: builder.mutation({ + /** + * Remove a provision. + * + * @param {object} params - Request parameters + * @param {string|number} params.id - provision id + * @param {boolean} params.force - Force removal + * @returns {number} provision id + * @throws Fails when response isn't code 200 + */ + query: (params) => { + const name = Actions.DELETE + const command = { name, ...Commands[name] } + + return { params, command } + }, + invalidatesTags: (result, error, { id }) => [ + { type: PROVISION, id }, + { type: PROVISION_POOL }, + ], + }), + }), +}) + +export const provisionQueries = (({ + // Queries + useGetProvisionQuery, + useGetProvisionLogsQuery, + useGetProvisionsQuery, + useLazyGetProvisionsQuery, + + // Mutations + useCreateProvisionMutation, + useScaleProvisionHostsMutation, + useRetryProvisionMutation, + useUndeployProvisionMutation, + useRemoveProvisionMutation, + useAddHostProvisionMutation, + useDeleteHostProvisionMutation, + useAddIpsProvisionMutation, + useDeleteIpsProvisionMutation, +}) => ({ + // Queries + useGetProvisionQuery, + useGetProvisionLogsQuery, + useGetProvisionsQuery, + useLazyGetProvisionsQuery, + + // Mutations + useCreateProvisionMutation, + useScaleProvisionHostsMutation, + useRetryProvisionMutation, + useUndeployProvisionMutation, + useRemoveProvisionMutation, + useAddHostProvisionMutation, + useDeleteHostProvisionMutation, + useAddIpsProvisionMutation, + useDeleteIpsProvisionMutation, +}))(provisionApi) + +export { provisionApi as provisionEndpoints } +export default provisionQueries diff --git a/src/fireedge/src/modules/models/Cluster.js b/src/fireedge/src/modules/models/Cluster.js new file mode 100644 index 0000000000..1c214d4d3b --- /dev/null +++ b/src/fireedge/src/modules/models/Cluster.js @@ -0,0 +1,59 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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 { COLOR } from '@modules/constants/color' +import { PROVISION_STATES } from '@modules/constants/cluster' + +/** + * Get the color for a provision state. + * + * @param {string} state - Provision state + * @returns {string} Color for the state + */ +export const getProvisionColorState = (state) => { + if (state) return PROVISION_STATES[state]?.color + + // Other cases, return info color + return COLOR.info.light +} + +/** + * Get the progress for a provision. + * + * @param {string} state - Provision state + * @returns {number} Number between 0 and 100 + */ +export const getProvisionProgress = (state) => { + if (!state) return undefined + + switch (state) { + case PROVISION_STATES.PENDING.name: + return 0 + case PROVISION_STATES.INIT.name: + return 10 + case PROVISION_STATES.PLANNING.name: + return 20 + case PROVISION_STATES.APPLYING.name: + return 40 + case PROVISION_STATES.CONFIGURING_ONE.name: + return 60 + case PROVISION_STATES.CONFIGURING_PROVISION.name: + return 80 + case PROVISION_STATES.RUNNING.name: + return 100 + default: + return undefined + } +} diff --git a/src/fireedge/src/modules/models/index.js b/src/fireedge/src/modules/models/index.js index 60d67d5030..9d557f6584 100644 --- a/src/fireedge/src/modules/models/index.js +++ b/src/fireedge/src/modules/models/index.js @@ -15,6 +15,7 @@ * ------------------------------------------------------------------------- */ export * from '@modules/models/ACL' +export * from '@modules/models/Cluster' export * from '@modules/models/Datastore' export * from '@modules/models/Group' export * from '@modules/models/Guacamole' diff --git a/src/fireedge/src/modules/providers/theme/palettes/dark.js b/src/fireedge/src/modules/providers/theme/palettes/dark.js index 867b52418d..0375729cd6 100644 --- a/src/fireedge/src/modules/providers/theme/palettes/dark.js +++ b/src/fireedge/src/modules/providers/theme/palettes/dark.js @@ -505,6 +505,28 @@ export const darkPalette = { }, }, + // Cluster + cluster: { + createCluster: { + title: '#F5F7F9', + subtitle: '#C4CDD5', + cardBorder: '#40435C', + icon: '#58D2FF', + link: sunstoneColors.blue[400], + }, + }, + + // Progress bar + progressBar: { + completed: { + color: '#58D2FF', + auxColor: '#58FFFF', + }, + pending: { + color: '#34384C', + }, + }, + sunstoneColors: sunstoneColors, error: { diff --git a/src/fireedge/src/modules/providers/theme/palettes/light.js b/src/fireedge/src/modules/providers/theme/palettes/light.js index 42b44a32c9..6bfbc979e1 100644 --- a/src/fireedge/src/modules/providers/theme/palettes/light.js +++ b/src/fireedge/src/modules/providers/theme/palettes/light.js @@ -514,6 +514,28 @@ export const lightPalette = { }, }, + // Cluster + cluster: { + createCluster: { + title: sunstoneColors.darkBlue[200], + subtitle: sunstoneColors.darkGrey[200], + cardBorder: sunstoneColors.grey[400], + icon: '#58D2FF', + link: sunstoneColors.blue[400], + }, + }, + + // Progress bar + progressBar: { + completed: { + color: primaryColor, + auxColor: sunstoneColors.blue[400], + }, + pending: { + color: '#E0E4E7', + }, + }, + sunstoneColors: sunstoneColors, error: { diff --git a/src/fireedge/src/modules/utils/index.js b/src/fireedge/src/modules/utils/index.js index c7b81de9bc..200c67085d 100644 --- a/src/fireedge/src/modules/utils/index.js +++ b/src/fireedge/src/modules/utils/index.js @@ -29,3 +29,4 @@ export * from '@modules/utils/restrictedAttributes' export * from '@modules/utils/tabManifest' export * from '@modules/utils/secgroups' export * from '@modules/utils/labels' +export * from '@modules/utils/ods' diff --git a/src/fireedge/src/modules/utils/ods.js b/src/fireedge/src/modules/utils/ods.js new file mode 100644 index 0000000000..9de664faa2 --- /dev/null +++ b/src/fireedge/src/modules/utils/ods.js @@ -0,0 +1,402 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2025, 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. * + * ------------------------------------------------------------------------- */ + +/** + * + * Utils file for common function to use with ODS (OpenNebula Document Server) that is the Framework to build services like oneflow, oneform or oneks. + * + */ + +import { upperFirst, find, findKey, includes, isPlainObject } from 'lodash' +import { useFormContext } from 'react-hook-form' +import { boolean, number, string, object, array } from 'yup' + +import { + T, + INPUT_TYPES, + ODS_USER_INPUT_TYPES, + ODSUserInput, +} from '@ConstantsModule' +import { Field, arrayToOptions } from '@modules/utils/schema' + +/** + * Groups the user inputs in a tab using the fireedge configuration from the driver configuration. + * The return value will be an array (instead of an object) to preseve order of the user inputs. + * + * @param {Array} userInputs - List of user inputs + * @param {Array} odsFireedgeGroups - List of groups for the user inputs + * @param {string} providerName - Name of the provider + * @returns {Array} List of user inputs group by app and group. + */ +export const groupUserInputs = ( + userInputs, + odsFireedgeGroups, + providerName +) => { + // Groups using the data from the driver conf + const groups = Object.entries(odsFireedgeGroups?.layout).map(([key]) => ({ + name: upperFirst(key), + userInputs: [], + })) + + // Array to store the user inputs that don't match the convention ONEAPP___ + const others = [] + + // Iterate over each user input + userInputs.forEach((userInput) => { + // Get the parent key in odsFireedgeGroups + const parentKey = findKey(odsFireedgeGroups?.layout, (values) => + includes(values, userInput.name) + ) + + // Check if the key matches the name of an user input + if (parentKey) { + // Add to corresponding group + const group = find(groups, { name: upperFirst(parentKey) }) + group.userInputs.push(userInput) + } else { + // Assign value to others + others.push(userInput) + } + }) + + // Add others in last position if there is any attribute in others + if (others && others?.length > 0) { + groups.push({ + name: 'Others', + userInputs: others, + }) + } + + // Return array to have the same structure that user inputs in vm templates + return [ + { + name: upperFirst(providerName), + groups: groups, + }, + ] +} + +// Functions or constants to use in schemaODSUserInputField + +const requiredSchema = (mandatory, schema) => + mandatory ? schema.required() : schema.notRequired() + +/** + * Determine the type of the ODS User Input itself. + * + * @param {ODSUserInput} odsUserInput - ODS User Input + * @returns {string} ODS User Input type + */ +const odsUserInputType = (odsUserInput) => { + if (odsUserInput.match && odsUserInput.match.grouped_by) { + return odsUserInput.type + } else if (odsUserInput.match) { + return odsUserInput.match.type + } else { + return odsUserInput.type + } +} + +/** + * Builder to get the proper yup validator according to the field. + * + * @param {string} type - inferred ODS User Input type + * @param {ODSUserInput} odsUserInput - ODS User Input + * @returns {object} yup validator for ODS User Input and type of INPUT_VALUE + */ +const odsUserInputValidation = (type, odsUserInput) => { + /** + * Different types of objects (match property determines which kind of object it's dealt) + * Strings + * Numbers + * Booleans + * Lists + * Depending Lists ==> match + * Ranges ==> match + * Map aka Objects + */ + const { mandatory } = odsUserInput + + const { + string: tstring, + number: tnumber, + bool: tbool, + list: tlist, + listString: tListString, + map: tmap, + } = ODS_USER_INPUT_TYPES + + let yupType, yupValidator, inputTypeValue + + switch (type) { + case tstring: { + yupType = string() + inputTypeValue = INPUT_TYPES.TEXT + break + } + case tnumber: { + yupType = number() + inputTypeValue = INPUT_TYPES.TEXT + break + } + case tbool: { + yupType = boolean() + inputTypeValue = INPUT_TYPES.SWITCH + break + } + case tlist: { + yupType = string() + inputTypeValue = INPUT_TYPES.AUTOCOMPLETE + break + } + case tListString: { + yupType = array(string()) + inputTypeValue = INPUT_TYPES.AUTOCOMPLETE + break + } + case tmap: { + // On first stage, map would be treated as INPUT_TYPES.AUTOCOMPLETE + yupType = object() + inputTypeValue = INPUT_TYPES.AUTOCOMPLETE + break + } + default: { + yupType = string() + inputTypeValue = INPUT_TYPES.TEXT + break + } + } + + yupValidator = requiredSchema(mandatory, yupType) + + if (odsUserInput.match && Array.isArray(odsUserInput.match.values)) { + inputTypeValue = INPUT_TYPES.AUTOCOMPLETE + } else if (odsUserInput.match && odsUserInput.match.grouped_by) { + inputTypeValue = INPUT_TYPES.AUTOCOMPLETE + } else if ( + odsUserInput.match && + odsUserInput.match.values && + 'min' in odsUserInput.match.values && + 'max' in odsUserInput.match.values + ) { + const min = odsUserInput.match.values.min + const max = odsUserInput.match.values.max + yupValidator = yupValidator.min(min).max(max) + inputTypeValue = INPUT_TYPES.SLIDER + } + + let defaultValue + + if ( + type === tListString && + Array.isArray(odsUserInput.default) && + odsUserInput.default.length === 0 + ) { + yupValidator = yupValidator.default(() => '') + defaultValue = '' + } else if ( + odsUserInput.default && + inputTypeValue === INPUT_TYPES.AUTOCOMPLETE + ) { + const option = odsUserInput.default + yupValidator = yupValidator.default(() => option) + defaultValue = odsUserInput.default + } else if (odsUserInput.default) { + yupValidator = yupValidator.default(() => odsUserInput.default) + defaultValue = odsUserInput.default + } + + return { + validation: yupValidator, + inputType: inputTypeValue, + defaultValue: defaultValue, + } +} + +/** + * @param {ODSUserInput} odsUserInput - ODS User Input + * @returns {Field} Field Properties + */ +export const schemaOdsUserInputField = (odsUserInput = {}) => { + // Get base input type for ODS User Input + const type = odsUserInputType(odsUserInput) + + // Get yup validator, input type and default value for ODS User Input + const { validation, inputType, defaultValue } = odsUserInputValidation( + type, + odsUserInput + ) + + // Base Field config for odsUserInput + const odsUserInputLabel = T[odsUserInput.name] ?? odsUserInput.name + const config = { + name: odsUserInput.name, + label: odsUserInputLabel, + tooltip: odsUserInput.description, + grid: { md: 6 }, + } + + const { + string: tstring, + number: tnumber, + bool: tbool, + list: tlist, + listString: tListString, + map: tmap, + } = ODS_USER_INPUT_TYPES + + let values + + switch (type) { + case tstring: { + config.type = inputType + + config.validation = validation + + if (odsUserInput.match && Array.isArray(odsUserInput.match.values)) { + const match = odsUserInput.match + values = match.values.map((option) => ({ + text: option, + value: option, + })) + config.values = values + + config.optionsOnly = true + } else if ( + odsUserInput.match && + isPlainObject(odsUserInput.match.values) && + odsUserInput.match.grouped_by + ) { + const dependentValues = (dependencies = []) => { + const [dependencyValue] = dependencies + const matchValues = odsUserInput.match.values[dependencyValue] || [] + if (!matchValues.length) { + const { setValue } = useFormContext() + setValue(odsUserInput.name, '') + } + + return arrayToOptions(matchValues, { addEmpty: true }) + } + const dependency = odsUserInput.match.grouped_by + config.values = dependentValues + config.optionsOnly = true + config.clearInvalid = true + config.dependOf = [dependency] + } + + break + } + + case tnumber: { + config.type = inputType + config.validation = validation + + if ( + odsUserInput.match && + isPlainObject(odsUserInput.match.values) && + 'min' in odsUserInput.match.values && + 'max' in odsUserInput.match.values + ) { + config.grid = { xs: 12, md: 6 } + config.fieldProps = { + min: odsUserInput.match.values.min, + max: odsUserInput.match.values.max, + step: 1, + } + } + + break + } + case tbool: { + config.type = inputType + config.validation = validation.yesOrNo() + config.grid = { md: 12 } + + break + } + + // At first stage, we treat maps and list as the same + case tlist: { + // Get list values + values = odsUserInput.match.values.map((option) => ({ + text: option, + value: option, + })) + + config.type = inputType + + config.validation = validation + + if (odsUserInput.match && odsUserInput.grouped_by) { + const match = odsUserInput.match + values = match.values.map((option) => ({ + text: option, + value: option, + })) + config.values = values + config.dependencies = odsUserInput.grouped_by + config.optionsOnly = true + } else if (odsUserInput.match) { + const match = odsUserInput.match + values = match.values.map((option) => ({ + text: option, + value: option, + })) + config.values = values + + config.optionsOnly = true + } else { + // values: List of values to show to the user + config.values = values + // optionsOnly: Restrict to the values of the list so the user cannot type a different value + config.optionsOnly = true + } + + break + } + + // oneform_onprem_hosts is the only value that is a list(string), + // so, it has is own custom tooltip + case tListString: { + config.type = inputType + config.tooltip = [T.PressKeysToAddAHost, ['ENTER']] + config.validation = validation + config.multiple = true + break + } + + case tmap: { + config.type = inputType + config.validation = validation + + break + } + + default: { + config.type = inputType + config.validation = validation + + break + } + } + + if (defaultValue) { + config.default = defaultValue + } + + return config +} diff --git a/src/fireedge/src/server/routes/api/oneform/driver/functions.js b/src/fireedge/src/server/routes/api/oneform/driver/functions.js index a505257437..39ff1d67bf 100644 --- a/src/fireedge/src/server/routes/api/oneform/driver/functions.js +++ b/src/fireedge/src/server/routes/api/oneform/driver/functions.js @@ -109,10 +109,10 @@ const driver = ( const config = { method: command.httpMethod, - path: command.path, + path: 'drivers/{0}', user, password, - request: { name: params.name }, + request: params.name, } oneFormConnection( @@ -194,10 +194,10 @@ const driverEnable = ( const config = { method: command.httpMethod, - path: command.path, + path: 'drivers/{0}/enable', user, password, - ...(params.name && { request: { name: params.name } }), + request: params.name, } oneFormConnection( @@ -237,10 +237,10 @@ const driverDisable = ( const config = { method: command.httpMethod, - path: command.path, + path: 'drivers/{0}/disable', user, password, - ...(params.name && { request: { name: params.name } }), + request: params.name, } oneFormConnection( diff --git a/src/fireedge/src/server/routes/api/oneform/index.js b/src/fireedge/src/server/routes/api/oneform/index.js index cb90680305..95926c6cdc 100644 --- a/src/fireedge/src/server/routes/api/oneform/index.js +++ b/src/fireedge/src/server/routes/api/oneform/index.js @@ -63,7 +63,9 @@ const { provisionRetry, provisionScaleHost, provisionAddIp, + provisionAddHost, provisionRemoveIp, + provisionRemoveHost, provisionChmod, provisionChown, provisionChgrp, @@ -173,10 +175,18 @@ const provisionEndpoints = [ action: provisionAddIp, ...CommandsProvision[ActionsProvision.ADD_IP], }, + { + action: provisionAddHost, + ...CommandsProvision[ActionsProvision.ADD_HOST], + }, { action: provisionRemoveIp, ...CommandsProvision[ActionsProvision.REMOVE_IP], }, + { + action: provisionRemoveHost, + ...CommandsProvision[ActionsProvision.REMOVE_HOST], + }, { action: provisionChmod, ...CommandsProvision[ActionsProvision.CHMOD], diff --git a/src/fireedge/src/server/routes/api/oneform/provider/functions.js b/src/fireedge/src/server/routes/api/oneform/provider/functions.js index 62e9491fe1..399aea8b17 100644 --- a/src/fireedge/src/server/routes/api/oneform/provider/functions.js +++ b/src/fireedge/src/server/routes/api/oneform/provider/functions.js @@ -118,10 +118,10 @@ const provider = ( const config = { method: command.httpMethod, - path: command.path, + path: 'providers/{0}', user, password, - request: { id: params.id }, + request: params.id, } oneFormConnection( @@ -276,10 +276,10 @@ const providerUpdate = ( const template = parsePostData(params.template) const config = { method: command.httpMethod, - path: command.path, + path: 'providers/{0}', user, password, - request: { id: params.id }, + request: params.id, post: template, } @@ -327,10 +327,10 @@ const providerDelete = ( const config = { method: command.httpMethod, - path: command.path, + path: '/providers/{0}', user, password, - request: { id: params.id }, + request: params.id, } oneFormConnection( @@ -376,10 +376,10 @@ const providerChmod = ( const config = { method: command.httpMethod, - path: command.path, + path: '/providers/{0}/chmod', user, password, - request: { id: params.id }, + request: params.id, post: { octet: params.octet }, } @@ -418,20 +418,13 @@ const providerChown = ( return next() } - if ( - params.owner_id == null || - isNaN(Number(params.owner_id)) || - Number(params.owner_id) < 0 - ) { + if (params.owner_id == null || isNaN(Number(params.owner_id))) { res.locals.httpCode = httpResponse(methodNotAllowed, '', 'invalid owner ID') return next() } - if ( - params.group_id !== null && - (isNaN(Number(params.group_id)) || Number(params.group_id) < 0) - ) { + if (params.group_id !== null && isNaN(Number(params.group_id))) { res.locals.httpCode = httpResponse(methodNotAllowed, '', 'invalid group ID') return next() @@ -439,10 +432,10 @@ const providerChown = ( const config = { method: command.httpMethod, - path: command.path, + path: '/providers/{0}/chown', user, password, - request: { id: params.id }, + request: params.id, post: { owner_id: params.owner_id, ...(params.group_id && { group_id: params.group_id }), @@ -484,11 +477,7 @@ const providerChgrp = ( return next() } - if ( - params.group_id == null || - isNaN(Number(params.group_id)) || - Number(params.group_id) < 0 - ) { + if (params.group_id == null || isNaN(Number(params.group_id))) { res.locals.httpCode = httpResponse(methodNotAllowed, '', 'invalid group ID') return next() @@ -496,10 +485,10 @@ const providerChgrp = ( const config = { method: command.httpMethod, - path: command.path, + path: '/providers/{0}/chgrp', user, password, - request: { id: params.id }, + request: params.id, post: { group_id: params.group_id }, } diff --git a/src/fireedge/src/server/routes/api/oneform/provision/functions.js b/src/fireedge/src/server/routes/api/oneform/provision/functions.js index 33adb23cbe..46f21023ff 100644 --- a/src/fireedge/src/server/routes/api/oneform/provision/functions.js +++ b/src/fireedge/src/server/routes/api/oneform/provision/functions.js @@ -118,10 +118,10 @@ const provision = ( const config = { method: command.httpMethod, - path: command.path, + path: '/provisions/{0}', user, password, - request: { id: params.id }, + request: params.id, } oneFormConnection( @@ -147,6 +147,7 @@ const provisions = ( userData = {} ) => { const { user, password } = userData + const { extended: includedProvider } = params const command = Commands[Actions.LIST] if (!user || !password) { @@ -166,6 +167,10 @@ const provisions = ( password, } + if (includedProvider) { + config.query = { include_provider: includedProvider } + } + oneFormConnection( config, (data) => success(next, res, data), @@ -213,10 +218,10 @@ const provisionLogs = ( const config = { method: command.httpMethod, - path: command.path, + path: '/provisions/{0}/logs' + (params?.all && '?all={1}'), user, password, - request: { id: params.id }, + request: [params.id, params?.all], } oneFormConnection( @@ -329,10 +334,10 @@ const provisionUpdate = ( const template = parsePostData(params.template) const config = { method: command.httpMethod, - path: command.path, + path: '/provisions/{0}', user, password, - request: { id: params.id }, + request: params.id, post: template, } @@ -380,11 +385,11 @@ const provisionDelete = ( const config = { method: command.httpMethod, - path: command.path, + path: '/provisions/{0}', user, password, - request: { id: params.id }, - post: { + request: params.id, + query: { ...(params.force !== undefined && { force: params.force }), }, } @@ -426,10 +431,10 @@ const provisionUndeploy = ( const config = { method: command.httpMethod, - path: command.path, + path: '/provisions/{0}/undeploy', user, password, - request: { id: params.id }, + request: params.id, post: { ...(params.force !== undefined && { force: params.force }), }, @@ -472,10 +477,10 @@ const provisionRetry = ( const config = { method: command.httpMethod, - path: command.path, + path: '/provisions/{0}/retry', user, password, - request: { id: params.id }, + request: params.id, post: { ...(params.force !== undefined && { force: params.force }), }, @@ -507,6 +512,7 @@ const provisionScaleHost = ( ) => { const { user, password } = userData const command = Commands[Actions.SCALE] + const nodes = params.nodes if (!user || !password || !params.id) { res.locals.httpCode = httpResponse( @@ -518,8 +524,21 @@ const provisionScaleHost = ( return next() } - if (params.nodes == null || isNaN(params.nodes) || Number(params.nodes) < 0) { - res.locals.httpCode = httpResponse(methodNotAllowed, '', 'invalid nodes') + const isNull = nodes == null + const isPositiveNumber = + (typeof nodes === 'number' || + (typeof nodes === 'string' && String(Number(nodes)) !== 'NaN')) && + Number(nodes) > 0 && + Number.isInteger(Number(nodes)) + const isArrayOfStrings = + Array.isArray(nodes) && nodes.every((v) => typeof v === 'string') + + if (isNull || (!isPositiveNumber && !isArrayOfStrings)) { + res.locals.httpCode = httpResponse( + methodNotAllowed, + '', + `invalid nodes ${nodes}` + ) return next() } @@ -536,10 +555,10 @@ const provisionScaleHost = ( const config = { method: command.httpMethod, - path: command.path, + path: '/provisions/{0}/scale', user, password, - request: { id: params.id }, + request: params.id, post: { direction: params.direction, nodes: params.nodes, @@ -589,10 +608,10 @@ const provisionAddIp = ( const config = { method: command.httpMethod, - path: command.path, + path: '/provisions/{0}/add-ip', user, password, - request: { id: params.id }, + request: params.id, post: { amount: params.amount, }, @@ -605,6 +624,100 @@ const provisionAddIp = ( ) } +/** + * Add IP to a provision. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params + * @param {object} userData - user data + * @returns {void} + */ +const provisionAddHost = ( + res = {}, + next = defaultEmptyFunction, + params = {}, + userData = {} +) => { + const { user, password } = userData + const command = Commands[Actions.ADD_HOST] + + if (!user || !password || !params.id) { + res.locals.httpCode = httpResponse( + methodNotAllowed, + '', + 'invalid provision ID' + ) + + return next() + } + + const config = { + method: command.httpMethod, + path: '/provisions/{0}/add-host', + user, + password, + request: params.id, + post: {}, + } + + params?.ips && (config.post.ips = params.ips) + params?.amount && (config.post.amount = params.amount) + + oneFormConnection( + config, + (data) => success(next, res, data), + (data) => error(next, res, data) + ) +} + +/** + * Remove HOST from a provision. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params + * @param {object} userData - user data + * @returns {void} + */ +const provisionRemoveHost = ( + res = {}, + next = defaultEmptyFunction, + params = {}, + userData = {} +) => { + const { user, password } = userData + const command = Commands[Actions.REMOVE_HOST] + + if (!user || !password || !params.id) { + res.locals.httpCode = httpResponse( + methodNotAllowed, + '', + 'invalid provision ID' + ) + + return next() + } + + const config = { + method: command.httpMethod, + path: '/provisions/{0}/remove-host', + user, + password, + request: params.id, + post: {}, + } + + params?.ids && (config.post.ids = params.ids) + params?.amount && (config.post.amount = params.amount) + + oneFormConnection( + config, + (data) => success(next, res, data), + (data) => error(next, res, data) + ) +} + /** * Remove IP from a provision. * @@ -645,10 +758,10 @@ const provisionRemoveIp = ( const config = { method: command.httpMethod, - path: command.path, + path: '/provisions/{0}/remove-ip', user, password, - request: { id: params.id }, + request: params.id, post: { ar_id: params.ar_id, }, @@ -697,10 +810,10 @@ const provisionChmod = ( const config = { method: command.httpMethod, - path: command.path, + path: '/provisions/{0}/chmod', user, password, - request: { id: params.id }, + request: params.id, post: { octet: params.octet }, } @@ -739,20 +852,13 @@ const provisionChown = ( return next() } - if ( - params.owner_id == null || - isNaN(Number(params.owner_id)) || - Number(params.owner_id) < 0 - ) { + if (params.owner_id == null || isNaN(Number(params.owner_id))) { res.locals.httpCode = httpResponse(methodNotAllowed, '', 'invalid owner ID') return next() } - if ( - params.group_id !== null && - (isNaN(Number(params.group_id)) || Number(params.group_id) < 0) - ) { + if (params.group_id !== null && isNaN(Number(params.group_id))) { res.locals.httpCode = httpResponse(methodNotAllowed, '', 'invalid group ID') return next() @@ -760,10 +866,10 @@ const provisionChown = ( const config = { method: command.httpMethod, - path: command.path, + path: '/provisions/{0}/chown', user, password, - request: { id: params.id }, + request: params.id, post: { owner_id: params.owner_id, ...(params.group_id && { group_id: params.group_id }), @@ -805,11 +911,7 @@ const provisionChgrp = ( return next() } - if ( - params.group_id == null || - isNaN(Number(params.group_id)) || - Number(params.group_id) < 0 - ) { + if (params.group_id == null || isNaN(Number(params.group_id))) { res.locals.httpCode = httpResponse(methodNotAllowed, '', 'invalid group ID') return next() @@ -817,10 +919,10 @@ const provisionChgrp = ( const config = { method: command.httpMethod, - path: command.path, + path: '/provisions/{0}/chgrp', user, password, - request: { id: params.id }, + request: params.id, post: { group_id: params.group_id }, } @@ -842,7 +944,9 @@ const provisionApi = { provisionRetry, provisionScaleHost, provisionAddIp, + provisionAddHost, provisionRemoveIp, + provisionRemoveHost, provisionChmod, provisionChown, provisionChgrp, diff --git a/src/fireedge/src/server/routes/api/oneform/provision/routes.js b/src/fireedge/src/server/routes/api/oneform/provision/routes.js index 8ccc8ccfe3..53c0506274 100644 --- a/src/fireedge/src/server/routes/api/oneform/provision/routes.js +++ b/src/fireedge/src/server/routes/api/oneform/provision/routes.js @@ -20,7 +20,7 @@ const { } = require('../../../../utils/constants/defaults') const basepath = '/provisions' -const { resource, postBody } = fromData +const { resource, postBody, query } = fromData const { GET, POST, DELETE, PATCH } = httpMethod const Actions = { @@ -46,8 +46,8 @@ const Commands = { httpMethod: GET, auth: true, params: { - all: { - from: fromData.query, + extended: { + from: query, default: 'false', }, }, @@ -58,6 +58,10 @@ const Commands = { auth: true, params: { id: { from: resource }, + extended: { + from: query, + default: 'false', + }, }, }, [Actions.LOGS]: { @@ -66,6 +70,10 @@ const Commands = { auth: true, params: { id: { from: resource }, + all: { + from: query, + default: 'true', + }, }, }, [Actions.CREATE]: { @@ -99,6 +107,10 @@ const Commands = { id: { from: resource, }, + force: { + from: query, + default: false, + }, }, }, [Actions.UNDEPLOY]: { diff --git a/src/fireedge/src/server/routes/api/oneform/utils.js b/src/fireedge/src/server/routes/api/oneform/utils.js index 9671cb0ffc..d13452549b 100644 --- a/src/fireedge/src/server/routes/api/oneform/utils.js +++ b/src/fireedge/src/server/routes/api/oneform/utils.js @@ -23,7 +23,6 @@ const { addPrintf } = require('server/utils/general') const { GET, DELETE } = httpMethod const appConfig = getFireedgeConfig() -const apiVersion = '/api/v1' /** * Return schema error. @@ -57,7 +56,7 @@ const oneFormConnection = ( success = () => undefined, error = () => undefined ) => { - const { method, path, user, password, request, post } = requestData + const { method, path, user, password, request, post, query } = requestData const optionMethod = method || GET const optionPath = path || '/' @@ -68,9 +67,7 @@ const oneFormConnection = ( const options = { method: optionMethod, - baseURL: `${ - appConfig.oneform_server || defaultOneFormServer - }/${apiVersion}`, + baseURL: `${appConfig.oneform_server || defaultOneFormServer}`, url: request ? addPrintf(optionPath, request) : optionPath, headers: { Authorization: `Basic ${optionAuth}`, @@ -80,6 +77,7 @@ const oneFormConnection = ( } if (post) options.data = post + if (query) options.params = query axios(options) .then((response) => { diff --git a/src/form/app/controllers/provision_controller.rb b/src/form/app/controllers/provision_controller.rb index 60770a68e8..329613f6e0 100644 --- a/src/form/app/controllers/provision_controller.rb +++ b/src/form/app/controllers/provision_controller.rb @@ -47,7 +47,8 @@ module OneFormServer # 200 OK - Array of provisions (JSON) # 500 Internal Server Error - If OpenNebula or retrieval error app.get '/provisions' do - show_all = params['all'] == 'true' + show_all = params['all'] == 'true' + include_provider = params['include_provider'] == 'true' pool = OneForm::ProvisionDocumentPool.new(@client) rc = pool.info @@ -67,6 +68,8 @@ module OneFormServer next if provision.state == OneForm::Provision::STATE['DONE'] && !show_all + provision.include_provider if include_provider + provisions << provision end @@ -87,7 +90,8 @@ module OneFormServer # 404 Not Found - If provision does not exist # 500 Internal Server Error - If OpenNebula error app.get '/provisions/:id' do - decode = params['decode'] == 'true' + decode = params['decode'] == 'true' + include_provider = params['include_provider'] == 'true' provision = OneForm::Provision.new_from_id(@client, params[:id]) @@ -96,6 +100,7 @@ module OneFormServer ) if OpenNebula.is_error?(provision) provision.decode_tfstate if decode + provision.include_provider if include_provider status 200 body process_response(provision) diff --git a/src/form/app/models/driver.rb b/src/form/app/models/driver.rb index 5b6e3971d6..ccb7ff79e1 100644 --- a/src/form/app/models/driver.rb +++ b/src/form/app/models/driver.rb @@ -531,6 +531,7 @@ module OneForm :description => normalized_values['description'] || nil, :type => normalized_values['type'].to_s.downcase, :default => normalized_values['default'], + :mandatory => normalized_values['default'].nil?, :match => match.empty? ? nil : match }.compact end diff --git a/src/form/app/models/provider.rb b/src/form/app/models/provider.rb index bb898f3888..bddd251245 100644 --- a/src/form/app/models/provider.rb +++ b/src/form/app/models/provider.rb @@ -21,7 +21,7 @@ module OneForm params do required(:name).filled(:string) - required(:description).filled(:string) + optional(:description).filled(:string) required(:driver).filled(:string) required(:fireedge).hash do diff --git a/src/form/app/models/provision.rb b/src/form/app/models/provision.rb index 4c573b9ec2..56d912e421 100644 --- a/src/form/app/models/provision.rb +++ b/src/form/app/models/provision.rb @@ -21,7 +21,7 @@ module OneForm params do required(:name).filled(:string) - required(:description).filled(:string) + optional(:description).filled(:string) required(:deployment_file).filled(:string) optional(:onedeploy_tags).filled(:string) required(:provider_id).filled(:integer) @@ -767,6 +767,17 @@ module OneForm @body['tfstate'] = JSON.parse(decoded_state) end + def include_provider + provider_id = @body['provider_id'] + return unless provider_id + + provider = OneForm::Provider.new_from_id(@client, provider_id) + raise provider if OpenNebula.is_error?(provider) + + @body['provider'] = provider.body + @body.delete('provider_id') + end + # ------------------------------------------------------ # OpenNebula Objects # ------------------------------------------------------