F #5627: Add dockerhub tags to export form (#1646)

Co-authored-by: Tino Vázquez <cvazquez@opennebula.io>
(cherry picked from commit 39f89538b5)
This commit is contained in:
Sergio Betanzos authored and Tino Vazquez committed 2021-12-03 12:45:08 +01:00
1 parent 80056e5f2e
commit c9af404339
14 files changed
+410 -33

No files matched your search

@@ -24,12 +24,12 @@ const NAME_FIELD = {
label: T.Name,
tooltip: T.ExportAppNameConcept,
type: INPUT_TYPES.TEXT,
validation: lazy((_, { context }) => {
return string()
validation: lazy((_, { context }) =>
string()
.trim()
.required()
.default(() => context.app.NAME)
}),
),
}
/** @type {Field} Template name field */
@@ -38,20 +38,20 @@ const TEMPLATE_NAME_FIELD = {
label: T.VMTemplate,
tooltip: T.ExportTemplateNameConcept,
type: INPUT_TYPES.TEXT,
validation: lazy((_, { context }) => {
return string()
validation: lazy((_, { context }) =>
string()
.trim()
.required()
.default(() => context.app.NAME)
}),
),
}
/** @type {Field} Associate field */
const ASSOCIATED_FIELD = {
name: 'associated',
label: T.DontAssociateApp,
label: T.ExportAssociateApp,
type: INPUT_TYPES.SWITCH,
validation: boolean().yesOrNo(),
validation: boolean().default(() => true),
grid: { md: 12 },
}
@@ -0,0 +1,67 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, 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 { useFormContext } from 'react-hook-form'
import { DockerHubTagsTable } from 'client/components/Tables'
import { SCHEMA } from 'client/components/Forms/MarketplaceApp/ExportForm/Steps/DockerHubTagsTable/schema'
import { Step } from 'client/utils'
import { T } from 'client/constants'
export const STEP_ID = 'tag'
const Content = ({ data, app }) => {
const { name } = data?.[0] ?? {}
const { setValue } = useFormContext()
const handleSelectedRows = (rows) => {
const { original = {} } = rows?.[0] ?? {}
setValue(STEP_ID, original.id !== undefined ? [original] : [])
}
return (
<DockerHubTagsTable
app={app}
singleSelect
onlyGlobalSearch
onlyGlobalSelectedRows
initialState={{ selectedRowIds: { [name]: true } }}
onSelectedRowsChange={handleSelectedRows}
/>
)
}
/**
* Step to select the DockerHub tag.
*
* @param {object} app - Marketplace App resource
* @returns {Step} DockerHub tag step
*/
const DockerHubTagStep = (app) => ({
id: STEP_ID,
label: T.SelectDockerHubTag,
resolver: SCHEMA,
content: (props) => Content({ ...props, app }),
})
Content.propTypes = {
data: PropTypes.any,
setFormData: PropTypes.func,
app: PropTypes.object,
}
export default DockerHubTagStep
@@ -0,0 +1,19 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, 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, object, ArraySchema } from 'yup'
/** @type {ArraySchema} Datastore table schema */
export const SCHEMA = array(object()).max(1).ensure()
@@ -19,19 +19,38 @@ import BasicConfiguration, {
import DatastoresTable, {
STEP_ID as DATASTORE_ID,
} from 'client/components/Forms/MarketplaceApp/ExportForm/Steps/DatastoresTable'
import DockerHubTagsTable, {
STEP_ID as TAG_ID,
} from 'client/components/Forms/MarketplaceApp/ExportForm/Steps/DockerHubTagsTable'
import { createSteps } from 'client/utils'
const Steps = createSteps([BasicConfiguration, DatastoresTable], {
transformInitialValue: (app, schema) => schema.cast({}, { context: { app } }),
transformBeforeSubmit: (formData) => {
const { [BASIC_ID]: configuration, [DATASTORE_ID]: [datastore] = [] } =
formData
const Steps = createSteps(
(app) => {
const isDockerImage = String(app?.MARKETPLACE).toLowerCase() === 'dockerhub'
return {
datastore: datastore?.ID,
...configuration,
}
return [
BasicConfiguration,
DatastoresTable,
isDockerImage && DockerHubTagsTable,
].filter(Boolean)
},
})
{
transformInitialValue: (app, schema) =>
schema.cast({}, { context: { app } }),
transformBeforeSubmit: (formData) => {
const {
[BASIC_ID]: configuration,
[DATASTORE_ID]: [datastore] = [],
[TAG_ID]: [tag] = [],
} = formData
return {
datastore: datastore?.ID,
tag: tag?.name,
...configuration,
}
},
}
)
export default Steps
@@ -0,0 +1,92 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, 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 { useMemo, useEffect, useState, useCallback } from 'react'
import PropTypes from 'prop-types'
import { useFetch } from 'client/hooks'
import { useMarketplaceAppApi } from 'client/features/One'
import EnhancedTable from 'client/components/Tables/Enhanced'
import DockerHubTagsRow from 'client/components/Tables/DockerHubTags/row'
const getNextPageFromUrl = (url) => {
try {
const { searchParams } = new URL(url)
return searchParams.get('page')
} catch {
return undefined
}
}
const DockerHubTagsTable = ({ app, ...props } = {}) => {
const { getDockerHubTags } = useMarketplaceAppApi()
const [tags, setTags] = useState(() => [])
const {
data: { next, results = [] } = {},
fetchRequest,
loading,
status,
STATUS: { INIT, FETCHED },
} = useFetch(getDockerHubTags)
useEffect(() => {
const appId = app?.ID
const requests = app?.ID && {
[INIT]: () => fetchRequest({ id: appId }),
[FETCHED]: () => {
if (!next) return
const page = getNextPageFromUrl(next)
fetchRequest({ id: appId, page })
},
}
requests[status]?.()
}, [app?.ID, status])
useEffect(() => {
status === FETCHED && setTags((prev) => prev.concat(results))
}, [status])
const memoData = useMemo(() => tags, [tags?.length])
const memoColumns = useMemo(() => [{ accessor: 'name' }], [])
return (
<EnhancedTable
columns={memoColumns}
data={memoData}
isLoading={loading}
getRowId={useCallback((row) => String(row.name), [])}
RowComponent={DockerHubTagsRow}
{...props}
/>
)
}
DockerHubTagsTable.displayName = 'DockerHubTagsTable'
DockerHubTagsTable.propTypes = {
...EnhancedTable.propTypes,
app: PropTypes.shape({
ID: PropTypes.string,
}),
}
export default DockerHubTagsTable
@@ -0,0 +1,148 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, 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 { memo, useState } from 'react'
import PropTypes from 'prop-types'
import { Stack, Typography, Box } from '@mui/material'
import { rowStyles } from 'client/components/Tables/styles'
import {
isoDateToMilliseconds,
timeFromMilliseconds,
} from 'client/models/Helper'
import { prettyBytes } from 'client/utils'
const LIMIT_IMAGES_TO_SHOW = 3
const CHARS_DIGEST = 12
const TagImage = memo(({ image }) => {
const { digest = 'Unknown', os, architecture, size } = image
const fullOs = [os, architecture].filter(Boolean).join('/')
const prettySize = prettyBytes(size, 'B', 2)
const trimmedDigest = String(digest)
.replace('sha256:', '')
.substring(0, CHARS_DIGEST)
return (
<Stack
spacing={2}
direction="row"
flexWrap="nowrap"
alignItems="center"
justifyContent="space-between"
sx={{ '&:hover': { bgcolor: 'secondary.light' } }}
>
<Typography
title="digest"
variant="subtitle2"
flexGrow={1.25}
width={100}
>
{trimmedDigest}
</Typography>
<Typography
title="OS/Architecture"
variant="subtitle2"
flexGrow={1.25}
width={80}
textAlign="start"
>
{fullOs}
</Typography>
<Typography
title="Size"
variant="subtitle2"
textAlign="end"
flexGrow={1.25}
width={80}
>
{prettySize}
</Typography>
</Stack>
)
})
const Row = ({ original, value: _, ...props }) => {
const [showMore, setShowMore] = useState(() => false)
const classes = rowStyles()
const { name, tag_last_pushed: lastPushed, images } = original
const time = timeFromMilliseconds(isoDateToMilliseconds(lastPushed))
const timeAgo = lastPushed ? `Last pushed ${time.toRelative()}` : ''
const handleShowMore = (evt) => {
evt.stopPropagation()
setShowMore(true)
}
return (
<div {...props}>
<div className={classes.main}>
<div className={classes.title}>
<Typography component="span">{name}</Typography>
</div>
<div className={classes.caption}>
<span title={time.toFormat('ff')} className="full-width">
{timeAgo}
</span>
</div>
{images?.length > 0 && (
<Box flexBasis="100%" mt={1}>
{showMore ? (
images?.map((image) => (
<TagImage key={image.digest} image={image} />
))
) : (
<>
{images.slice(0, LIMIT_IMAGES_TO_SHOW)?.map((image) => (
<TagImage key={image.digest} image={image} />
))}
{images.length - LIMIT_IMAGES_TO_SHOW > 0 && (
<Typography color="secondary.dark" onClick={handleShowMore}>
{`+${images.length - LIMIT_IMAGES_TO_SHOW} more...`}
</Typography>
)}
</>
)}
</Box>
)}
</div>
</div>
)
}
TagImage.displayName = 'TagImage'
TagImage.propTypes = {
image: PropTypes.shape({
digest: PropTypes.string,
os: PropTypes.string,
architecture: PropTypes.string,
size: PropTypes.number,
}),
}
Row.propTypes = {
original: PropTypes.object,
value: PropTypes.object,
isSelected: PropTypes.bool,
handleClick: PropTypes.func,
}
export default Row
@@ -90,6 +90,7 @@ const GlobalFilter = ({ useTableProps, className }) => {
</div>
<InputBase
value={value ?? ''}
type="search"
onChange={(event) => {
setValue(event.target.value)
handleChange(event.target.value)
@@ -45,6 +45,7 @@ const EnhancedTable = ({
canFetchMore,
columns,
globalActions,
globalFilter,
data,
fetchMore,
getRowId,
@@ -86,6 +87,7 @@ const EnhancedTable = ({
columns,
data,
defaultColumn,
globalFilter,
sortTypes,
getRowId,
// When table has update, disable all of the auto resetting
@@ -158,14 +160,12 @@ const EnhancedTable = ({
{/* PAGINATION */}
<div className={styles.pagination}>
{page?.length > 0 && (
<Pagination
handleChangePage={handleChangePage}
useTableProps={useTableProps}
count={rows.length}
showPageCount={showPageCount}
/>
)}
<Pagination
handleChangePage={handleChangePage}
useTableProps={useTableProps}
count={rows.length}
showPageCount={showPageCount}
/>
</div>
</div>
@@ -234,6 +234,7 @@ export const EnhancedTableProps = {
globalActions: PropTypes.arrayOf(ActionPropTypes),
columns: PropTypes.array,
data: PropTypes.array,
globalFilter: PropTypes.func,
fetchMore: PropTypes.func,
getRowId: PropTypes.func,
initialState: PropTypes.object,
@@ -48,17 +48,17 @@ const VmsTable = (props) => {
const { status, data, fetchRequest, loading, reloading, error, STATUS } =
useFetch(getVms)
const { INIT, PENDING } = STATUS
const { INIT, PENDING, FETCHED } = STATUS
useEffect(() => {
const requests = {
INIT: () =>
[INIT]: () =>
fetchRequest({
start: INITIAL_ELEMENT,
end: -INTERVAL_ON_FIRST_RENDER,
state: -1, // Any state, except DONE
}),
FETCHED: () => {
[FETCHED]: () => {
const canFetchMore =
!error && data?.vms?.length === INTERVAL_ON_FIRST_RENDER
@@ -15,6 +15,7 @@
* ------------------------------------------------------------------------- */
import ClustersTable from 'client/components/Tables/Clusters'
import DatastoresTable from 'client/components/Tables/Datastores'
import DockerHubTagsTable from 'client/components/Tables/DockerHubTags'
import EnhancedTable, {
EnhancedTableProps,
} from 'client/components/Tables/Enhanced'
@@ -40,6 +41,7 @@ export {
VirtualizedTable,
ClustersTable,
DatastoresTable,
DockerHubTagsTable,
GroupsTable,
HostsTable,
ImagesTable,
@@ -100,13 +100,14 @@ module.exports = {
SaveAsTemplate: 'Save as Template',
Search: 'Search',
Select: 'Select',
SelectDatastore: 'Select a Datastore to store the resource',
SelectDockerHubTag: 'Select DockerHub image tag (default latest)',
SelectGroup: 'Select a group',
SelectHost: 'Select a host',
SelectMarketplace: 'Select Marketplace',
SelectNetwork: 'Select a network',
SelectRequest: 'Select request',
SelectVmTemplate: 'Select a VM Template',
SelectDatastore: 'Select a Datastore to store the resource',
SelectMarketplace: 'Select Marketplace',
Share: 'Share',
Show: 'Show',
ShowAll: 'Show all',
@@ -598,7 +599,7 @@ module.exports = {
'Name that the resource will get for description purposes',
ExportTemplateNameConcept:
'The following template will be created in OpenNebula and the previous images will be referenced in the disks',
DontAssociateApp: 'Do not import/export associated VM templates/images',
ExportAssociateApp: 'Export associated VM templates/images',
ImportAssociateApp: 'Import associated VM templates/images',
/* User inputs */
@@ -31,6 +31,11 @@ export const getMarketplaceApps = createAction(
(response) => ({ [RESOURCES.app]: response })
)
export const getDockerHubTags = createAction(
`${APP}/dockerhub-tags`,
marketplaceAppService.getDockerHubTags
)
export const exportApp = createAction(
`${APP}/export`,
marketplaceAppService.export
@@ -36,6 +36,8 @@ export const useMarketplaceAppApi = () => {
getMarketplaceApp: (id) =>
unwrapDispatch(actions.getMarketplaceApp({ id })),
getMarketplaceApps: () => unwrapDispatch(actions.getMarketplaceApps()),
getDockerHubTags: (options) =>
unwrapDispatch(actions.getDockerHubTags(options)),
exportApp: (id, data) => unwrapDispatch(actions.exportApp({ id, ...data })),
create: (id, template) => unwrapDispatch(actions.create({ id, template })),
importVm: (id, data) =>
@@ -61,6 +61,26 @@ export const marketplaceAppService = {
return [res?.data?.MARKETPLACEAPP_POOL?.MARKETPLACEAPP ?? []].flat()
},
/**
* Retrieves DockerHub tags information for marketplace app.
*
* @param {object} params - Request parameters
* @param {string|number} params.id - App id
* @param {string|number} [params.page] - Number of page
* @returns {object[]} List of DockerHub tags
* @throws Fails when response isn't code 200
*/
getDockerHubTags: async ({ id, page }) => {
const res = await RestClient.request({
url: `/api/marketapp/dockertags/${id}`,
params: { page },
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res?.data
return res?.data
},
/**
* Exports the marketplace app to the OpenNebula cloud.
*
@@ -71,7 +91,7 @@ export const marketplaceAppService = {
* @param {string|number} params.file - File datastore id or name
* @param {string} params.tag - DockerHub image tag (default latest)
* @param {string|number} params.template - Associate with VM template
* @param {boolean} params.associated - If `true`, don't export associated VM templates/images
* @param {boolean} params.associated - If `false`, Do not export associated VM templates/images
* @param {string} params.vmname - The name for the new VM Template, if the App contains one
* @returns {number} Template and image ids
* @throws Fails when response isn't code 200