B #-: Fix OneKS server, CLI, and Sunstone minor issues (#4724)

* Fix ODS shutdown with active HTTP requests
* Fix multiple ID support in OneKS CLI
* Wait for image readiness in OneKS fake
* Share and protect OneKS appliance resources
* Allow OneKS cluster creation without an explicit OpenNebula cluster ID
* Improve OneKS readiness checks and verify monitor API connectivity
* Skip OneKS cluster selection for non-admin users
* Show app installation progress and log command tooltip
* Use memory unit selectors in OneKS application forms
* Fix OneKS appliance placement without an explicit cluster
* Fix oneks app details and installation progress UI
* Lint code
* Fix schema
* Improve UX app progress status
* Fix dialog style
* Fix OneKS readiness probe routing and stream timeouts
This commit is contained in:
Victor Palma authored and GitHub committed 2026-11-26 09:02:45 +01:00
1 parent f1929b3d02
commit 19e0969dff
30 files changed
+1034 -378

No files matched your search

@@ -51,6 +51,7 @@ export const InformationUnitController = memo(
fieldProps = {},
readOnly = false,
onConditionChange,
defaultValue,
}) => {
const { translate } = useTranslation()
const watch = useWatch({
@@ -62,7 +63,7 @@ export const InformationUnitController = memo(
const {
field: { ref, value = '', onChange, ...inputProps },
fieldState: { error },
} = useController({ name, control })
} = useController({ name, control, defaultValue })
const safeFieldProps =
fieldProps && typeof fieldProps === 'object' ? fieldProps : {}
@@ -187,6 +188,7 @@ InformationUnitController.propTypes = {
fieldProps: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
readOnly: PropTypes.bool,
onConditionChange: PropTypes.func,
defaultValue: PropTypes.number,
}
InformationUnitController.displayName = 'InformationUnitController'
@@ -142,7 +142,7 @@ export const getStyles = ({ theme, variant }) => {
alignItems: 'flex-start',
bgcolor: 'transparent',
borderRadius: 0,
color: 'text.secondary',
color: 'text.body',
fontWeight: 400,
},
'& .item-content': {
@@ -42,6 +42,12 @@ module.exports = {
TargetNamespace: 'Target namespace',
CreateNamespace: 'Create namespace if it does not exist',
SuccessApplicationInstallStarted: 'Application installation started',
ApplicationComponentsReady: '%s of %s components ready',
ApplicationComponentsDeleted: '%s of %s components deleted',
ViewLogInstructions: 'View log instructions',
ApplicationLogInstructions: 'Application log instructions',
ApplicationInstallationLogsHint:
'Application installation logs for %s can be viewed using the cluster kubeconfig and the command below:',
ErrorApplicationInstallation: 'Error installing application: %s',
Back: 'Back',
Previous: 'Previous',
@@ -2938,6 +2944,7 @@ gpgkey=https://downloads.opennebula.io/repo/repo2.key...`,
ListMultiple: 'List multiple',
Boolean: 'Boolean',
Number: 'Number',
PositiveNumber: 'Enter a positive finite number.',
NumberFloat: 'Number float',
Text: 'Text',
Text64: 'Text64',
@@ -15,7 +15,7 @@
* ------------------------------------------------------------------------- */
import { ReactElement } from 'react'
import { generatePath, useHistory, useLocation } from 'react-router-dom'
import { OneKsAPI, useGeneralApi } from '@FeaturesModule'
import { OneKsAPI, useGeneralApi, useSystemData } from '@FeaturesModule'
import { DefaultFormStepper, SkeletonStepsForm } from '@ComponentsModule'
import { OneKs } from '@ResourcesModule'
@@ -31,7 +31,8 @@ import { T, ONEKS_OPERATIONS, PATH } from '@ConstantsModule'
export function CreateOneKsCluster() {
const history = useHistory()
const { state } = useLocation()
const clusterId = state?.ID
const { adminGroup } = useSystemData()
const clusterId = adminGroup ? state?.ID : undefined
const { enqueueSuccess, enqueueError } = useGeneralApi()
const [createOneKsCluster] = OneKsAPI.useCreateOneKsClusterMutation()
@@ -75,6 +76,7 @@ export function CreateOneKsCluster() {
stepProps={{
families: familiesUserInputs,
clusterId,
adminGroup,
}}
fallback={<SkeletonStepsForm />}
>
@@ -96,9 +96,9 @@ export const SingleView = ({
{ id: selectedId, expand: true },
{ skip: !isOpen || selectedId === undefined }
)
const { currentData: installedApplications } =
const { currentData: installedApplications, refetch: refetchApplications } =
OneKsAPI.useGetOneKsClusterApplicationsQuery(
{ id: selectedId, showNotification: false },
{ id: selectedId, all: true, showNotification: false },
{ skip: !isOpen || selectedId === undefined }
)
const { data: families = [], isLoading: isLoadingFamilies } =
@@ -137,7 +137,8 @@ export const SingleView = ({
isChangingPermissions ||
isChangingOwnership
const refreshCurrentData = async () => ID !== undefined && (await refetch())
const refreshCurrentData = async () =>
ID !== undefined && (await Promise.all([refetch(), refetchApplications()]))
const handleRename = async (newName) => {
await updateDocument({ id: ID, template: { name: newName } })
@@ -356,7 +357,10 @@ export const SingleView = ({
],
[
Array.isArray(installedApplications)
? String(installedApplications.length)
? String(
installedApplications.filter(({ parent }) => !parent)
.length
)
: '-',
T.InstalledApplications,
],
@@ -45,13 +45,13 @@ const AboutSection = ({ section, releaseName }) => {
return (
<Box sx={(theme) => getAboutStyles({ theme })}>
{title && <Typography variant="h6">{title}</Typography>}
{title && (
<Typography variant="h6" color="text.headings">
{title}
</Typography>
)}
{description && (
<Typography
variant="body2"
color="text.secondary"
whiteSpace="pre-line"
>
<Typography variant="body2" color="text.body" whiteSpace="pre-line">
{description}
</Typography>
)}
@@ -61,12 +61,14 @@ const AboutSection = ({ section, releaseName }) => {
items={steps.map((step, index) => (
<Box key={index} className="about-step">
{step.title && (
<Typography variant="subtitle2">{step.title}</Typography>
<Typography variant="subtitle2" color="text.headings">
{step.title}
</Typography>
)}
{step.description && (
<Typography
variant="body2"
color="text.secondary"
color="text.body"
whiteSpace="pre-line"
>
{step.description}
@@ -17,7 +17,13 @@
import PropTypes from 'prop-types'
import { ReactElement } from 'react'
import { useTheme } from '@mui/material'
import { Cancel, RefreshDouble, Trash } from 'iconoir-react'
import {
Cancel,
Check as CopiedIcon,
Copy as CopyIcon,
RefreshDouble,
Trash,
} from 'iconoir-react'
import {
DetailsDrawer as ResourceDetailsDrawer,
InfoSlot,
@@ -27,6 +33,8 @@ import {
ToggleGroup,
} from '@ComponentsModule'
import { T } from '@ConstantsModule'
import { useClipboard } from '@HooksModule'
import { sentenceCase } from '@UtilsModule'
import { getApplicationImage, getApplicationStateColor } from '@ModelsModule'
import { ApplicationImagePlaceholder } from '@modules/resources/OneKs/ApplicationImagePlaceholder'
import { ApplicationTabs } from '@modules/resources/OneKs/Details/Application/Tabs'
@@ -56,10 +64,11 @@ export const Application = ({
onClose,
}) => {
const { palette } = useTheme()
const { copy, isCopied } = useClipboard()
const releaseName = application?.release_name
const namespace = application?.target_namespace
const applicationName = application?.metadata?.name
const version = application?.version ?? '-'
const resourceVersion = application?.resource_version
const hasRelease = Boolean(application?.cluster_id && releaseName)
return (
@@ -141,15 +150,40 @@ export const Application = ({
<StatusTag
key="application-state"
statusColor={getApplicationStateColor(application.state)}
statusName={application.state}
statusName={sentenceCase(application.state)}
/>
) : (
'-'
),
T.State,
],
[
<Tag
key="application-release"
title={releaseName ?? '-'}
endIcon={
releaseName &&
(isCopied(releaseName) ? <CopiedIcon /> : <CopyIcon />)
}
onClick={releaseName ? () => copy(releaseName) : undefined}
type="button"
/>,
T.ReleaseName,
],
[
<Tag
key="application-namespace"
title={namespace ?? '-'}
endIcon={
namespace &&
(isCopied(namespace) ? <CopiedIcon /> : <CopyIcon />)
}
onClick={namespace ? () => copy(namespace) : undefined}
type="button"
/>,
T.TargetNamespace,
],
[<Tag key="application-version" title={version} />, T.Version],
[resourceVersion ?? '-', T.ResourceVersion],
],
},
],
@@ -14,6 +14,7 @@
* limitations under the License. *
* ------------------------------------------------------------------------- */
import PropTypes from 'prop-types'
import { object } from 'yup'
import { FormWithSchema } from '@ComponentsModule'
import { T } from '@ConstantsModule'
import { SCHEMA, FIELDS } from './schema'
@@ -27,18 +28,21 @@ const Content = () => (
/**
* Cluster configuration.
*
* @param {object} props - Form props
* @param {boolean} props.adminGroup - Whether the user belongs to the admin group
* @returns {object} Cluster configuration step
*/
const Cluster = () => ({
const Cluster = ({ adminGroup }) => ({
id: STEP_ID,
label: T.SelectCluster,
resolver: SCHEMA,
resolver: adminGroup ? SCHEMA : object().strip(),
optionsValidate: { abortEarly: false },
content: () => Content(),
defaultDisabled: { condition: () => !adminGroup },
})
Cluster.propTypes = {
families: PropTypes.array,
adminGroup: PropTypes.bool,
}
export default Cluster
@@ -47,7 +47,7 @@ const toId = (value) => {
const Steps = createSteps(
(formProps) => [
() => General(),
() => Cluster(),
() => Cluster(formProps),
() => Public(),
() => Private(),
() => KubernetesVersion(formProps),
@@ -56,16 +56,16 @@ const Steps = createSteps(
],
{
transformBeforeSubmit: (formData, _, stepProps) => {
const clusterId = formData?.cluster?.cluster ?? stepProps?.clusterId
const clusterId = stepProps?.adminGroup
? toId(formData?.cluster?.cluster ?? stepProps?.clusterId)
: undefined
return {
name: formData?.general?.NAME,
description: formData?.general?.DESCRIPTION,
kubernetes_version: formData?.kubernetes_version?.KUBERNETES_VERSION,
deployment: {
cluster: {
id: toId(clusterId),
},
...(clusterId !== undefined && { cluster: { id: clusterId } }),
networks: {
public: {
id: toId(formData?.public?.PUBLIC_NETWORK),
@@ -18,6 +18,8 @@ import {
schemaOdsUserInputField,
sentenceCase,
} from '@UtilsModule'
import { INPUT_TYPES, T } from '@ConstantsModule'
import { number } from 'yup'
/**
* @param {object} application - Selected application definition
@@ -26,6 +28,43 @@ import {
export const FIELDS = (application = {}) =>
(application?.user_inputs ?? []).map((userInput) => {
const field = schemaOdsUserInputField(userInput)
const regex = userInput.match?.values?.regex
const units = regex
?.match(/\(((?:[KMGTPE]i\|)*[KMGTPE]i)\)\\z$/)?.[1]
.split('|')
if (
userInput.type === 'string' &&
!userInput.sensitive &&
units?.includes('Mi')
) {
const match = new RegExp(regex.replace(/\\A/g, '^').replace(/\\z/g, '$'))
const defaultQuantity = userInput.default?.match(/^(\d+)([KMGTPE]i)$/)
const defaultValue = defaultQuantity
? Number(defaultQuantity[1]) *
1024 ** ('KMGTPE'.indexOf(defaultQuantity[2][0]) - 1)
: undefined
field.type = INPUT_TYPES.UNITS
field.defaultValue = defaultValue
field.validation = number()
.positive()
.integer()
.test(
'memory-quantity',
T.PositiveNumber,
(value) => value == null || match.test(`${value}Mi`)
)
.default(defaultValue)
if (userInput.mandatory) field.validation = field.validation.required()
field.fieldProps = {
...field.fieldProps,
min: 1,
step: 1,
isRequired: !!userInput.mandatory,
isOptional: !userInput.mandatory,
}
}
return {
...field,
@@ -37,6 +76,28 @@ export const FIELDS = (application = {}) =>
}
})
/**
* Serializes memory inputs stored by the unit controller in MB.
*
* @param {object} application - Selected application definition
* @param {object} values - Form input values
* @returns {object} Application input values ready for submission
*/
export const toUserInputValues = (application, values = {}) => {
const result = { ...values }
FIELDS(application).forEach(({ name, type }) => {
if (
type === INPUT_TYPES.UNITS &&
result[name] != null &&
result[name] !== ''
) {
result[name] = `${result[name]}Mi`
}
})
return result
}
/**
* @param {object} form - Form values
* @returns {object} Application input schema
@@ -16,6 +16,7 @@
import Application from '@modules/resources/OneKs/Forms/InstallApplicationForm/Steps/Application'
import Configuration from '@modules/resources/OneKs/Forms/InstallApplicationForm/Steps/Configuration'
import UserInputs from '@modules/resources/OneKs/Forms/InstallApplicationForm/Steps/UserInputs'
import { toUserInputValues } from '@modules/resources/OneKs/Forms/InstallApplicationForm/Steps/UserInputs/schema'
import { createSteps } from '@UtilsModule'
const Steps = createSteps([Application, Configuration, UserInputs], {
@@ -24,7 +25,10 @@ const Steps = createSteps([Application, Configuration, UserInputs], {
release_name: formData?.configuration?.RELEASE_NAME,
target_namespace: formData?.configuration?.TARGET_NAMESPACE,
create_namespace: formData?.configuration?.CREATE_NAMESPACE,
user_input_values: formData?.user_inputs ?? {},
user_input_values: toUserInputValues(
formData?.application?.DEFINITION,
formData?.user_inputs
),
}),
})
@@ -13,22 +13,33 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import { AlertNotification, Button, Image, TablePanel } from '@ComponentsModule'
import { Box, Typography } from '@mui/material'
import {
AlertDialog,
AlertNotification,
Button,
CodeSnippet,
Image,
ProgressBar,
StatusTag,
TablePanel,
} from '@ComponentsModule'
import { Box, Link, Stack, Typography } from '@mui/material'
import { ArrowTrSquare, Plus } from 'iconoir-react'
import PropTypes from 'prop-types'
import { Component } from 'react'
import { Component, useEffect, useMemo, useRef } from 'react'
import { generatePath, useHistory } from 'react-router-dom'
import { PATH, RESOURCE_NAMES, T } from '@ConstantsModule'
import { SystemAPI } from '@FeaturesModule'
import { SystemAPI, useModalsApi } from '@FeaturesModule'
import { useClipboard } from '@HooksModule'
import { useResourceSingleViewContext, useTranslation } from '@ProvidersModule'
import { generateDocLink } from '@UtilsModule'
import { generateDocLink, sentenceCase } from '@UtilsModule'
import { scale } from '@StylesModule'
import {
getApplicationDescription,
getApplicationImage,
getApplicationName,
getApplicationStateColor,
oneksApplicationTable,
} from '@ModelsModule'
import { ApplicationImagePlaceholder } from '@modules/resources/OneKs/ApplicationImagePlaceholder'
@@ -37,8 +48,146 @@ import { getStyles } from '@modules/resources/OneKs/Tabs/Applications/styles'
const MONITORING_DOC_PATH =
'platform_services/oneks/management/configuration/#monitor-configuration'
const columns = oneksApplicationTable.columns().map((column) =>
column.id === 'application'
/**
* @param {object} props - Dialog properties
* @param {string} props.releaseName - Application release name
* @param {Function} props.onClose - Close the dialog
* @returns {object} Application log instructions dialog
*/
const ApplicationLogInstructions = ({ releaseName, onClose }) => {
const { translate } = useTranslation()
const { copy, isCopied } = useClipboard()
const code = `kubectl -n kube-system logs -f --all-containers=true --tail=-1 -l helmcharts.helm.cattle.io/chart=${releaseName}`
return (
<AlertDialog
title={translate(T.ApplicationLogInstructions)}
dataCy="oneks-application-log-instructions"
onClose={onClose}
actionsProps={{
cancel: { label: translate(T.Close), onClick: onClose },
confirm: {
label: translate(isCopied(code) ? T.Copied : T.Copy),
onClick: () => copy(code),
},
}}
sx={{
width: '680px',
maxWidth: 'calc(100vw - 32px)',
actions: { justifyContent: 'flex-end' },
}}
>
<Stack
gap={2}
sx={{
'&& .topbar': { py: 0 },
'&& .code-container': {
pt: 0,
whiteSpace: 'pre-wrap',
wordBreak: 'normal',
overflowWrap: 'anywhere',
'& > code': { minWidth: 0 },
},
}}
>
<Typography variant="body2">
{translate(T.ApplicationInstallationLogsHint, [releaseName])}
</Typography>
<CodeSnippet code={code} />
</Stack>
</AlertDialog>
)
}
ApplicationLogInstructions.propTypes = {
releaseName: PropTypes.string.isRequired,
onClose: PropTypes.func.isRequired,
}
/**
* @param {object} props - Table cell properties
* @param {object} props.row - Application row
* @returns {object} Application state and component progress
*/
const ApplicationStateCell = ({ row }) => {
const { translate } = useTranslation()
const { showModal } = useModalsApi()
const application = row.original
const dependencies = application.dependencies ?? []
const components = [...dependencies, application]
const ready = components.filter(({ state }) => state === 'ready').length
const deleting = application.deleting
const total = application.componentsTotal ?? components.length
const completed = deleting ? Math.max(0, total - components.length) : ready
const progress = Math.round((completed / total) * 100)
return (
<Stack gap={1}>
<Stack direction="row" alignItems="center" gap={1}>
{application.state ? (
<StatusTag
statusColor={getApplicationStateColor(application.state)}
statusName={sentenceCase(application.state)}
/>
) : (
'-'
)}
</Stack>
{(deleting ||
application.state === 'installing' ||
dependencies.length > 0) &&
completed < total && (
<Stack gap={1}>
<ProgressBar
size="extraSmall"
value={progress}
label={translate(
deleting
? T.ApplicationComponentsDeleted
: T.ApplicationComponentsReady,
[completed, total]
)}
isLabelVisible
/>
<Link
component="button"
type="button"
variant="body2"
underline="hover"
sx={{
alignSelf: 'flex-start',
textAlign: 'left',
color: 'text.action',
}}
onClick={(event) => {
event.stopPropagation()
showModal({
isCustomDialog: true,
form: ApplicationLogInstructions,
customDialogProps: { releaseName: application.release_name },
})
}}
>
{translate(T.ViewLogInstructions)}
</Link>
</Stack>
)}
</Stack>
)
}
ApplicationStateCell.propTypes = { row: PropTypes.object }
const columns = oneksApplicationTable.columns().map((column) => {
if (column.id === 'state') {
return {
...column,
cell: ApplicationStateCell,
meta: { ...column.meta, disableCellTooltip: true },
}
}
return column.id === 'application'
? {
...column,
cell: ({ row }) => {
@@ -72,7 +221,7 @@ const columns = oneksApplicationTable.columns().map((column) =>
{name}
</Typography>
{description && (
<Typography variant="caption" color="text.secondary" noWrap>
<Typography variant="caption" color="text.body" noWrap>
{description}
</Typography>
)}
@@ -82,7 +231,7 @@ const columns = oneksApplicationTable.columns().map((column) =>
},
}
: column
)
})
/**
* Render applications tab.
@@ -111,13 +260,59 @@ const Applications = ({ data }) => {
: undefined
const id = data?.selected?.ID ?? data?.id
const {
data: applications = [],
data: allApplications = [],
isFetching,
isError,
} = oneksApplicationTable.useData(
{ id },
{ id, all: true, showNotification: false },
{ skip: !id || !isMonitoringEnabled }
)
const applicationProgress = useRef(new Map())
const applications = useMemo(
() =>
allApplications
.filter(({ parent }) => !parent)
.map((application) => {
const dependencies = allApplications.filter(
({ parent }) => parent === application.release_name
)
const previous = applicationProgress.current.get(
`${id}:${application.release_name}`
)
const componentsTotal = Math.max(
previous?.componentsTotal ?? 0,
dependencies.length + 1
)
const deleting =
application.state === 'deleting' ||
dependencies.some(({ state }) => state === 'deleting') ||
previous?.deleting === true ||
dependencies.length + 1 < componentsTotal
return {
...application,
state:
deleting && application.state !== 'error'
? 'deleting'
: application.state,
dependencies,
componentsTotal,
deleting,
}
}),
[allApplications, id]
)
useEffect(() => {
applicationProgress.current = new Map(
applications.map((application) => [
`${id}:${application.release_name}`,
{
componentsTotal: application.componentsTotal,
deleting: application.deleting,
},
])
)
}, [applications, id])
const openApplication = (application) => {
const releaseName = application?.release_name
if (!id || !releaseName) return
@@ -20,11 +20,11 @@ const oneKsDeploymentSchema = {
properties: {
cluster: {
type: 'object',
required: true,
required: false,
properties: {
id: {
type: 'integer',
required: true,
required: false,
},
},
},
+10 -2
View File
@@ -101,7 +101,12 @@ module OpenNebula
)
request.body = body.is_a?(String) ? body : body.to_json
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
Net::HTTP.start(
uri.host,
uri.port,
:use_ssl => uri.scheme == 'https',
:read_timeout => 60
) do |http|
http.request(request) do |response|
unless response.is_a?(Net::HTTPSuccess)
response_body = +''
@@ -229,10 +234,13 @@ module OpenNebula
end
def parse_event(raw_event)
lines = raw_event.lines
return [nil, nil] if lines.all? {|line| line.strip.empty? || line.start_with?(':') }
event = 'message'
data = +''
raw_event.each_line do |line|
lines.each do |line|
line = line.chomp
next if line.empty? || line.start_with?(':')
+1
View File
@@ -81,6 +81,7 @@ require 'lockfile'
require 'logger'
require 'parse-cron'
require 'puma'
require 'puma/events'
require 'rack'
require 'rackup'
require 'rexml'
+23 -1
View File
@@ -29,8 +29,11 @@ module OpenNebula
# @param name [String] Export name.
# @param app_id [String] Appliance import ID.
# @param datastore_id [Integer] Destination datastore ID.
# @param options [Hash] Settings for exported images and templates.
# @option options [String] :permissions Resource permissions.
# @option options [Integer] :lock_level Resource lock level.
# @return [OpenNebula::MarketPlaceApp, OpenNebula::Error] appliance or an API error.
def self.import(client, name, app_id, datastore_id)
def self.import(client, name, app_id, datastore_id, options = {})
return OpenNebula::Error.new(
'Marketplace appliance ID cannot be empty',
OpenNebula::Error::EACTION
@@ -61,6 +64,25 @@ module OpenNebula
tmplt_error = tmplt_ids.find {|tmplt_id| OpenNebula.is_error?(tmplt_id) }
return tmplt_error if tmplt_error
permissions = options[:permissions]
lock_level = options[:lock_level]
return app unless permissions || lock_level
resources = image_ids.map {|id| OpenNebula::Image.new_with_id(id, client) } +
tmplt_ids.map {|id| OpenNebula::Template.new_with_id(id, client) }
resources.each do |resource|
if permissions
rc = resource.chmod_octet(permissions)
return rc if OpenNebula.is_error?(rc)
end
next unless lock_level
rc = resource.lock(lock_level)
return rc if OpenNebula.is_error?(rc)
end
app
end
+70 -7
View File
@@ -119,6 +119,9 @@ module OpenNebula
@out = out
@event_name = event_name
@closed = false
@mutex = Mutex.new
@condition = ConditionVariable.new
@heartbeat_thread = nil
end
# Emit a Server-Sent Event to the stream
@@ -128,15 +131,25 @@ module OpenNebula
#
# @return [Boolean] true if written, false if the stream is closed
def emit(event, payload = {})
return false if @closed
write("event: #{event}\ndata: #{payload.to_json}\n\n")
end
@out << "event: #{event}\n"
@out << "data: #{payload.to_json}\n\n"
# Starts optional keepalive comments without emitting progress events.
#
# @param interval [Numeric] Seconds between heartbeat comments
# @return [Thread, nil] Managed heartbeat thread, or nil if already closed
def start_heartbeat(interval)
interval = Float(interval)
raise ArgumentError, 'Heartbeat interval must be positive and finite' \
unless interval.finite? && interval.positive?
true
rescue IOError, Errno::EPIPE, Puma::ConnectionError
@closed = true
false
@mutex.synchronize do
return if @closed
@heartbeat_thread ||= ThreadManager.instance.start(:sse_heartbeat) do
heartbeat_loop(interval)
end
end
end
# Emit a progress notification using the default event name
@@ -168,11 +181,57 @@ module OpenNebula
end
def close
thread = @mutex.synchronize do
@closed = true
@condition.broadcast
@heartbeat_thread
end
thread&.join
@out.close
rescue IOError
nil
end
private
# Serializes complete frames with heartbeats and stream closure.
def write(frame)
@mutex.synchronize do
return false if @closed
begin
@out << frame
true
rescue IOError, Errno::EPIPE, Puma::ConnectionError
@closed = true
@condition.broadcast
false
end
end
end
def heartbeat_loop(interval)
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + interval
loop do
return if ThreadManager.instance.stop?
@mutex.synchronize do
return if @closed
remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
@condition.wait(@mutex, [remaining, 1].min) if remaining.positive?
return if @closed
end
next if Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline
return unless write(": heartbeat\n\n")
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + interval
end
end
end
# Streams Server-Sent Events (SSE) to the HTTP client.
@@ -202,6 +261,7 @@ module OpenNebula
# @option opts [Hash] :headers ({}) extra response headers merged with
# the SSE defaults
# @option opts [Integer] :status_code (200) HTTP status code
# @option opts [Numeric, nil] :heartbeat_interval seconds between keepalive comments
# @yieldparam events [EventStream] object used to emit SSE events
# @return [Object] Sinatra streaming response
def stream_events(opts = {})
@@ -229,6 +289,9 @@ module OpenNebula
events = EventStream.new(out, :event_name => event_name)
begin
if opts[:heartbeat_interval]
events.start_heartbeat(opts[:heartbeat_interval])
end
yield events
rescue IOError, Errno::EPIPE, StreamClosed
nil
+10
View File
@@ -28,6 +28,16 @@ module OpenNebula
set key, value
end
options = respond_to?(:server_settings) ? server_settings.dup : {}
events = options[:events] ||= Puma::Events.new
# Stop ODS before Puma waits for requests that depend on its workers
events.register(:state) do |state|
ThreadManager.instance.stop! if [:stop, :halt, :restart].include?(state)
end
set :server_settings, options
# Configure custom logger
disable :logging
set :logger, Log.instance(SERVER_CONF[:log])
+148
View File
@@ -140,9 +140,134 @@ RSpec.describe ODS::ResponseHelper do
expect { stream.progress('x', 'y') }.to raise_error(ODS::ResponseHelper::StreamClosed)
expect(stream.progress('x', 'y', nil, :abort_on_close => false)).to be(false)
end
describe 'optional heartbeats' do
before { OdsSpecSupport.reset_thread_manager }
it 'writes SSE comments and stops the managed worker on close' do
output = StringIO.new
written = Queue.new
allow(output).to receive(:<<).and_wrap_original do |write, frame|
result = write.call(frame)
written << frame
result
end
stream = described_class.new(output)
worker = stream.start_heartbeat(0.01)
expect(Timeout.timeout(2) { written.pop }).to eq(": heartbeat\n\n")
expect(stream.start_heartbeat(0.01)).to equal(worker)
stream.close
expect(worker).not_to be_alive
expect(ODS::ThreadManager.instance.any_alive?).to be(false)
expect(stream.emit('after-close')).to be(false)
ensure
stream&.close
end
it 'wakes the worker immediately when closing a long heartbeat interval' do
stream = described_class.new(StringIO.new)
waiting = Queue.new
allow(stream.instance_variable_get(:@condition)).to receive(:wait)
.and_wrap_original do |wait, *args|
waiting << true
wait.call(*args)
end
worker = stream.start_heartbeat(15)
Timeout.timeout(2) { waiting.pop }
Timeout.timeout(1) { stream.close }
expect(worker).not_to be_alive
ensure
stream&.close
end
it 'rejects invalid intervals without starting a worker' do
stream = described_class.new(StringIO.new)
[0, -1, Float::INFINITY, Float::NAN].each do |interval|
expect { stream.start_heartbeat(interval) }.to raise_error(ArgumentError)
end
expect(ODS::ThreadManager.instance.any_alive?).to be(false)
ensure
stream&.close
end
it 'stops writing after a client disconnects' do
output = instance_double('Output', :close => nil)
expect(output).to receive(:<<).once.and_raise(Errno::EPIPE)
stream = described_class.new(output)
worker = stream.start_heartbeat(0.01)
Timeout.timeout(2) { worker.join }
expect(worker).not_to be_alive
expect { stream.progress('check', :success) }.to raise_error(
ODS::ResponseHelper::StreamClosed
)
ensure
stream&.close
end
it 'serializes concurrent progress frames and heartbeat comments' do
output = StringIO.new
written = Queue.new
allow(output).to receive(:<<).and_wrap_original do |write, frame|
frame.each_char do |char|
write.call(char)
Thread.pass
end
written << frame
frame
end
stream = described_class.new(output, :event_name => 'progress')
stream.start_heartbeat(0.001)
Timeout.timeout(2) { written.pop }
writers = 2.times.map do |id|
Thread.new do
10.times {|index| stream.progress('check', :started, [id, index]) }
end
end
Timeout.timeout(3) { writers.each(&:join) }
stream.close
frames = output.string.split("\n\n")
progress = frames.reject {|frame| frame == ': heartbeat' }
expect(progress.size).to eq(20)
progress.each do |frame|
expect(frame).to start_with("event: progress\ndata: ")
expect(JSON.parse(frame.split('data: ', 2).last)['name']).to eq('check')
end
ensure
writers&.each(&:join)
stream&.close
end
it 'honors managed server shutdown while waiting for the next heartbeat' do
stream = described_class.new(StringIO.new)
waiting = Queue.new
allow(stream.instance_variable_get(:@condition)).to receive(:wait)
.and_wrap_original do |wait, *args|
waiting << true
wait.call(*args)
end
worker = stream.start_heartbeat(15)
Timeout.timeout(2) { waiting.pop }
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 2
expect(ODS::ThreadManager.instance.stop!(:deadline => deadline)).to be(true)
expect(worker).not_to be_alive
ensure
stream&.close
end
end
end
it 'streams SSE success and close events with configured response metadata' do
expect(ODS::ThreadManager.instance).not_to receive(:start)
result = helper.stream_events(
:event_name => 'progress', :close_event => 'complete',
:close_payload => { :ok => true }, :status_code => 202,
@@ -162,6 +287,29 @@ RSpec.describe ODS::ResponseHelper do
)
end
it 'stops heartbeats on failure and still emits failure and close events' do
OdsSpecSupport.reset_thread_manager
output = Queue.new
worker = nil
helper.stream_events(:heartbeat_interval => 0.01, :close_event => 'complete') do |events|
worker = events.start_heartbeat(0.01)
allow(helper.stream_output).to receive(:<<).and_wrap_original do |write, frame|
result = write.call(frame)
output << frame
result
end
Timeout.timeout(2) { output.pop }
raise 'check failed'
end
expect(worker).not_to be_alive
expect(helper.stream_output).to be_closed
expect(helper.stream_output.string).to include(
': heartbeat', 'event: error', '"error":"check failed"', 'event: complete'
)
end
it 'emits default failures or delegates stream errors to a handler' do
helper.stream_events { raise 'stream failed' }
expect(helper.stream_output.string).to include(
@@ -156,7 +156,7 @@ module OneKS
rc = ClusterDeployment.validate(@client, deployment)
next rc if OpenNebula.is_error?(rc)
stream_events(:event_name => 'check_cluster') do |events|
stream_events(:event_name => 'check_cluster', :heartbeat_interval => 15) do |events|
OneKS::ClusterReadiness.run(@client, deployment, :stream => events)
end
end
+5 -1
View File
@@ -983,6 +983,8 @@ module OneKS
#------------------------------------------------------
def deployment_cluster
return {} if deployment_cluster_id.nil?
OneHelper::Cluster.body(@client, deployment_cluster_id)
end
@@ -1016,6 +1018,8 @@ module OneKS
end
def sched_requirements
return '' if deployment_cluster_id.nil?
"CLUSTER_ID = #{deployment_cluster_id}"
end
@@ -1027,7 +1031,7 @@ module OneKS
return target_networks if OpenNebula.is_error?(target_networks)
deployment.merge(
:cluster => target_cluster.deep_merge(deployment[:cluster]),
:cluster => target_cluster.deep_merge(deployment[:cluster] || {}),
:networks => target_networks,
:sched_requirements => sched_requirements
)
+13 -4
View File
@@ -78,13 +78,17 @@ module OneKS
return spec if OpenNebula.is_error?(spec)
extra_template = {
:SCHED_REQUIREMENTS => cluster.sched_requirements,
:ONEAPP_ONEKS_CLUSTER_NAME => cluster.uuid,
:ONEAPP_ONEKS_CLUSTER_SPEC => Base64.strict_encode64(spec),
:NIC => [{ :NETWORK_ID => cluster.public_network_id }]
:NIC => [{ :NETWORK_ID => cluster.public_network_id }],
:SCHED_REQUIREMENTS => OneHelper::Template.sched_requirements(
appliance[:template], cluster.sched_requirements
)
}
seed_id = appliance[:template].instantiate(vm_name, false, Hash.to_raw(extra_template))
seed_id = appliance[:template].instantiate(
vm_name, false, Hash.to_raw(extra_template.compact)
)
return OpenNebula::Error.new(
seed_id.message, OpenNebula::Error::EACTION
@@ -254,7 +258,12 @@ module OneKS
return rc if OpenNebula.is_error?(rc)
rc = OneHelper::Marketplace.import(
client, appliance_name, appliance_id, datastore_id
client,
appliance_name,
appliance_id,
datastore_id,
:permissions => '744',
:lock_level => 2
)
return rc if OpenNebula.is_error?(rc)
+69 -18
View File
@@ -20,8 +20,8 @@ module OneKS
class ClusterDeployment
SCHEMA = Dry::Schema.Params do
required(:cluster).hash do
required(:id).filled(:integer)
optional(:cluster).hash do
optional(:id).filled(:integer)
end
required(:networks).hash do
@@ -55,7 +55,7 @@ module OneKS
) unless deployment
cluster_id = deployment.dig(:cluster, :id)
cluster = OneHelper::Cluster.get(client, cluster_id)
cluster = OneHelper::Cluster.get(client, cluster_id) unless cluster_id.nil?
return OpenNebula::Error.new(
"OpenNebula cluster #{cluster_id} does not exist: #{cluster.message}",
@@ -68,7 +68,7 @@ module OneKS
rc = validate_datastores(client, cluster, deployment[:datastores])
return rc if OpenNebula.is_error?(rc)
rc = validate_appliances(client, cluster, family)
rc = validate_appliances(client, deployment, family)
return rc if OpenNebula.is_error?(rc)
true
@@ -79,23 +79,26 @@ module OneKS
)
end
# Resolves the appliance image and VM template in a datastore available to the
# target OpenNebula cluster
# Resolves the appliance in an image datastore compatible with the selected
# networks, explicit datastore and optional OpenNebula cluster.
# @param client [OpenNebula::Client] OpenNebula client
# @param deployment [Hash] Deployment placement section
# @param appliance_id [String] OneKS appliance ID
# @return [Hash, OpenNebula::Error] appliance image and template
def appliance(client, deployment, appliance_id)
cluster_id = deployment.dig(:cluster, :id)
cluster = OneHelper::Cluster.get(client, cluster_id)
cluster = OneHelper::Cluster.get(client, cluster_id) unless cluster_id.nil?
return cluster if OpenNebula.is_error?(cluster)
datastore_ids = appliance_datastores(client, deployment, cluster)
return datastore_ids if OpenNebula.is_error?(datastore_ids)
OneHelper::Template.find_by_appliance_id(
client, appliance_id, cluster.datastore_ids
client, appliance_id, datastore_ids
)
rescue StandardError => e
OpenNebula::Error.new(
"Error resolving deployment appliance: #{e.message}",
"Error resolving appliance: #{e.message}",
OpenNebula::Error::EACTION
)
end
@@ -133,6 +136,56 @@ module OneKS
private
# Reads membership from accessible resources, without requiring Cluster USE
def appliance_datastores(client, deployment, cluster)
networks = deployment[:networks]
return OpenNebula::Error.new(
'Missing deployment networks section', ODS::ResponseHelper::VALIDATION_EC
) if networks.nil? || networks.empty?
cluster_ids = [cluster.id.to_s] if cluster
networks.each_value do |net|
network = OneHelper::VirtualNetwork.get(client, net[:id])
return network if OpenNebula.is_error?(network)
ids = Array(network.retrieve_elements('CLUSTERS/ID'))
cluster_ids = cluster_ids.nil? ? ids : cluster_ids & ids
end
return OpenNebula::Error.new(
'Selected networks and OpenNebula cluster have no common placement',
ODS::ResponseHelper::VALIDATION_EC
) if cluster_ids.empty?
image_ds = deployment.dig(:datastores, :image, :id)
if image_ds
selected = OneHelper::Datastore.get(client, image_ds)
return selected if OpenNebula.is_error?(selected)
datastores = [selected]
else
datastores = OpenNebula::DatastorePool.new(client)
rc = datastores.info
return rc if OpenNebula.is_error?(rc)
end
ids = datastores.filter_map do |datastore|
next unless OneHelper::Datastore.image?(datastore)
next if (cluster_ids & Array(datastore.retrieve_elements('CLUSTERS/ID'))).empty?
datastore.id
end
return ids unless ids.empty?
OpenNebula::Error.new(
'No accessible image datastore is compatible with the selected networks ' \
'and deployment placement', ODS::ResponseHelper::VALIDATION_EC
)
end
# Checks that each deployment network exists and belongs to the
# selected OpenNebula cluster, when one is provided.
def validate_networks(client, cluster, networks)
@@ -150,7 +203,7 @@ module OneKS
ODS::ResponseHelper::VALIDATION_EC
) if OpenNebula.is_error?(network)
next if cluster.contains_vnet?(net_id)
next if cluster.nil? || cluster.contains_vnet?(net_id)
return OpenNebula::Error.new(
"Deployment #{role} network #{net_id} (#{network.name}) is not " \
@@ -176,7 +229,7 @@ module OneKS
ODS::ResponseHelper::VALIDATION_EC
) if OpenNebula.is_error?(datastore)
next if cluster.contains_datastore?(ds_id)
next if cluster.nil? || cluster.contains_datastore?(ds_id)
return OpenNebula::Error.new(
"Deployment #{role} datastore #{ds_id} " \
@@ -191,7 +244,7 @@ module OneKS
# Checks that every family appliance has a valid image and VM Template
# in a datastore available to the target OpenNebula cluster
def validate_appliances(client, cluster, family)
def validate_appliances(client, deployment, family)
family ||= ControlPlane.family_by_name(K8sGroup::DEFAULT_FAMILY)
return OpenNebula::Error.new(
@@ -203,17 +256,15 @@ module OneKS
return true if appliances.empty?
appliances.each do |appliance|
template = OneHelper::Template.find_by_appliance_id(
client, appliance[:id], cluster.datastore_ids
)
template = self.appliance(client, deployment, appliance[:id])
return template if OpenNebula.is_error?(template)
next if template
return OpenNebula::Error.new(
"Deployment appliance #{appliance[:name]} (#{appliance[:id]}) " \
'is not available in an image datastore associated with the ' \
"target OpenNebula cluster #{cluster.id} (#{cluster.name})",
"Appliance #{appliance[:name]} (#{appliance[:id]}) " \
'is not available in any image datastore accessible ' \
'with the selected configuration',
ODS::ResponseHelper::VALIDATION_EC
)
end
+116 -175
View File
@@ -47,11 +47,14 @@ module OneKS
'Creating probe VM' => proc { create_probe_vm },
'Waiting for probe VM RUNNING state' => proc { wait_probe_vm_running },
'Waiting for probe VM context' => proc { wait_probe_vm_context },
'Checking connectivity' => proc { check_internet_access },
'Checking OneGate access' => proc { check_onegate_access },
'Checking Internet connectivity' => proc { check_internet_access },
'Checking private network paths' => proc { check_network_access }
'Checking OpenNebula XML-RPC access' => proc { check_network_access }
}
checks['Checking OneKS monitor access'] = proc { check_oneks_access } \
if Features::Monitor.configured?
checks.each do |name, action|
progress(name, EVENTS::STARTED)
rc = action.call
@@ -120,18 +123,20 @@ module OneKS
OpenNebula::Error::EACTION
) if appliance.nil?
extra_template = {
:SCHED_REQUIREMENTS => OneHelper::Template.sched_requirements(
appliance[:template], @one_cluster.nil? ? nil : "CLUSTER_ID = #{@one_cluster}"
),
:NIC => [
{ :NETWORK_ID => @public_network },
{ :NETWORK_ID => @private_network }
]
}
vm_id = appliance[:template].instantiate(
"oneks-readiness-check-#{Time.now.to_i}",
false,
Hash.to_raw(
{
:NIC => [
{ :NETWORK_ID => @public_network },
{ :NETWORK_ID => @private_network }
],
:SCHED_REQUIREMENTS => "CLUSTER_ID = #{@one_cluster}"
}
)
Hash.to_raw(extra_template.compact)
)
return OpenNebula::Error.new(
@@ -260,20 +265,37 @@ module OneKS
#------------------------------------------------------
def check_onegate_access
rc = OneHelper::VirtualMachine.exec(
@client,
@id,
'/bin/sh -s',
:stdin => Base64.strict_encode64(onegate_access_script),
:timeout => TIMEOUT
output = probe_output(onegate_access_script, 'OneGate access failed')
return output if OpenNebula.is_error?(output)
response = JSON.parse(output)
return true if response.is_a?(Hash) && response['VM'].is_a?(Hash) &&
response['VM']['ID'].to_s == @id.to_s
OpenNebula::Error.new(
'OneGate did not return information for the probe VM', OpenNebula::Error::EACTION
)
rescue JSON::ParserError
OpenNebula::Error.new('OneGate returned invalid JSON', OpenNebula::Error::EACTION)
end
def check_oneks_access
endpoint = SERVER_CONF[:monitor][:endpoint].to_s.sub(%r{/+\z}, '') + '/'
status_format = '%{http_code}' # rubocop:disable Style/FormatStringToken
script = probe_script(
"http_request --output /dev/null --write-out '#{status_format}' " \
"#{Shellwords.escape(endpoint)}"
)
return OpenNebula::Error.new(
"OneKS cluster cannot reach OneGate endpoint: #{rc.message}",
OpenNebula::Error::EACTION
) if OpenNebula.is_error?(rc)
output = probe_output(script, 'OneKS API access failed')
return output if OpenNebula.is_error?(output)
return true if ['200', '401', '403'].include?(output.strip)
true
OpenNebula::Error.new(
"OneKS API returned unexpected HTTP status #{output.strip}",
OpenNebula::Error::EACTION
)
end
def check_internet_access
@@ -295,43 +317,44 @@ module OneKS
end
def check_network_access
targets = network_probe_targets
return OpenNebula::Error.new(
'OneKS cluster cannot reach the required private network ' \
"path: #{targets.message}",
OpenNebula::Error::EACTION
) if OpenNebula.is_error?(targets)
rc = OneHelper::VirtualMachine.exec(
@client,
@id,
'/bin/sh -s',
:stdin => Base64.strict_encode64(network_access_script(targets)),
:timeout => TIMEOUT
request = XMLRPC::Marshal.dump_call('one.system.version', '')
script = probe_script(
"http_request --fail --header 'Content-Type: text/xml' " \
"--data-binary #{Shellwords.escape(request)} " \
"#{Shellwords.escape(SERVER_CONF[:one_xmlrpc_tproxy].to_s)}"
)
output = probe_output(script, 'OpenNebula XML-RPC access failed')
return output if OpenNebula.is_error?(output)
return OpenNebula::Error.new(
'OneKS cluster cannot reach the required private network ' \
"path: #{rc.message}",
OpenNebula::Error::EACTION
) if OpenNebula.is_error?(rc)
begin
response = XMLRPC::Marshal.load_response(output)
rescue StandardError
return OpenNebula::Error.new(
'OpenNebula returned an invalid XML-RPC response', OpenNebula::Error::EACTION
)
end
true
return true if response.is_a?(Array) && response[0] == true &&
response[1].is_a?(String) && response[1].match?(/\A\d+\.\d+/)
return true if response.is_a?(Array) && response[0] == false &&
[OpenNebula::Error::EAUTHENTICATION,
OpenNebula::Error::EAUTHORIZATION].include?(response[2])
OpenNebula::Error.new(
'OpenNebula returned an unexpected XML-RPC response', OpenNebula::Error::EACTION
)
end
def onegate_access_script
<<~SCRIPT
set -eu
#{context_loader}
#{http_probe_helpers}
if [ -z "${ONEGATE_ENDPOINT:-}" ]; then
echo "ONEGATE_ENDPOINT not found in the cluster context" >&2
probe_script(<<~SCRIPT)
if [ -z "${ONEGATE_ENDPOINT:-}" ] || [ -z "${VMID:-}" ] ||
[ -z "${TOKENTXT:-}" ]; then
echo "OneGate endpoint, VM ID or token missing from the VM context" >&2
exit 1
fi
probe_url "$ONEGATE_ENDPOINT" "OneGate endpoint"
http_request --fail --header "X-ONEGATE-VMID: $VMID" \
--header "X-ONEGATE-TOKEN: $TOKENTXT" "${ONEGATE_ENDPOINT%/}/vm"
SCRIPT
end
@@ -341,7 +364,6 @@ module OneKS
<<~SCRIPT
set -eu
#{http_probe_helpers}
if command -v getent >/dev/null 2>&1; then
getent hosts #{Shellwords.escape(external_host)}
@@ -354,20 +376,40 @@ module OneKS
exit 127
fi
probe_url_strict #{Shellwords.escape(EXTERNAL_URL)} "Internet probe"
url=#{Shellwords.escape(EXTERNAL_URL)}
if command -v curl >/dev/null 2>&1; then
curl -fsSL --connect-timeout 5 --max-time 15 \
-o /dev/null "$url" && exit 0
elif command -v wget >/dev/null 2>&1; then
wget -q -T 15 -O /dev/null "$url" && exit 0
else
echo "Neither curl nor wget is available for the Internet probe" >&2
exit 127
fi
echo "Internet probe is not reachable through $url" >&2
exit 1
SCRIPT
end
def network_access_script(targets)
probes = targets.map do |target|
"probe_url #{Shellwords.escape(target[:url])} #{Shellwords.escape(target[:name])}"
end.join("\n")
# Loads the VM context and runs a probe command using the VM routing table
def probe_script(command)
<<~SCRIPT
set -eu
#{http_probe_helpers}
#{context_loader}
#{probes}
if ! command -v curl >/dev/null 2>&1; then
echo "curl is required for service checks" >&2
exit 127
fi
http_request() {
curl -sS --noproxy '*' \
--connect-timeout 5 --max-time 15 "$@"
}
#{command}
SCRIPT
end
@@ -379,130 +421,29 @@ module OneKS
/etc/one-context.d/one_env \
/mnt/context.sh \
/context.sh; do
[ -r "$context_file" ] && . "$context_file"
if [ -r "$context_file" ]; then
. "$context_file"
fi
done
SCRIPT
end
def http_probe_helpers
<<~SCRIPT
probe_url() {
url="$1"
label="$2"
if command -v curl >/dev/null 2>&1; then
http_code="$(curl -sS --connect-timeout 5 --max-time 15 \
-o /dev/null -w '%%{http_code}' "$url")" || {
echo "$label network is not reachable through $url" >&2
return 1
}
[ "$http_code" != "000" ] || {
echo "$label did not return an HTTP response through $url" >&2
return 1
}
return 0
fi
if command -v nc >/dev/null 2>&1 ||
{ command -v timeout >/dev/null 2>&1 &&
command -v bash >/dev/null 2>&1; }; then
probe_tcp_url "$url" "$label"
return $?
fi
if command -v wget >/dev/null 2>&1; then
wget -q -T 15 -O /dev/null "$url" && return 0
fi
echo "No HTTP or TCP probe tool is available to probe $label" >&2
return 127
}
probe_tcp_url() {
url="$1"
label="$2"
target="${url#*://}"
target="${target%%/*}"
host="${target%%:*}"
port="${target##*:}"
if [ "$host" = "$port" ]; then
case "$url" in
https://*) port=443 ;;
http://*) port=80 ;;
*)
echo "$label URL does not include a port: $url" >&2
return 1
;;
esac
fi
if command -v nc >/dev/null 2>&1; then
nc -z -w 5 "$host" "$port" && return 0
echo "$label TCP connection failed to $host:$port" >&2
return 1
fi
if command -v timeout >/dev/null 2>&1 &&
command -v bash >/dev/null 2>&1; then
timeout 5 bash -c ': > "/dev/tcp/$1/$2"' sh "$host" "$port" &&
return 0
echo "$label TCP connection failed to $host:$port" >&2
return 1
fi
return 1
}
probe_url_strict() {
url="$1"
label="$2"
if command -v curl >/dev/null 2>&1; then
curl -fsSL --connect-timeout 5 --max-time 15 \
-o /dev/null "$url" && return 0
elif command -v wget >/dev/null 2>&1; then
wget -q -T 15 -O /dev/null "$url" && return 0
else
echo "Neither curl nor wget is available to probe $label" >&2
return 127
fi
echo "$label is not reachable through $url" >&2
return 1
}
SCRIPT
end
def network_probe_targets
targets = []
xmlrpc_tproxy = SERVER_CONF[:one_xmlrpc_tproxy].to_s
unless xmlrpc_tproxy.strip.empty?
private_network = OneHelper::VirtualNetwork.name(
@client, @private_network
)
return private_network if OpenNebula.is_error?(private_network)
targets << {
:name => "OpenNebula XML-RPC TPROXY for #{private_network}",
:url => xmlrpc_tproxy
}
end
return OpenNebula::Error.new(
'No private network targets configured', OpenNebula::Error::EACTION
) if targets.empty?
targets
end
#------------------------------------------------------
# Helpers
#------------------------------------------------------
def probe_output(script, failure)
rc = OneHelper::VirtualMachine.exec(
@client, @id, '/bin/sh -s',
:stdin => Base64.strict_encode64(script), :timeout => TIMEOUT
)
return OpenNebula::Error.new(
"#{failure}: #{rc.message}", OpenNebula::Error::EACTION
) if OpenNebula.is_error?(rc)
rc[:stdout].to_s
end
def oneks_appliance
family = ControlPlane.family_by_name(@family)
return family if OpenNebula.is_error?(family)
@@ -17,6 +17,8 @@
require 'ods_helper'
require 'one_helper/oneks_helper'
require 'cloud/CloudClient'
require 'opennebula/cluster'
require 'opennebula/cluster_pool'
# OneKS cluster helper
class OneKSClusterHelper < ODSHelper
@@ -276,23 +278,29 @@ class OneKSClusterHelper < ODSHelper
client.update_cluster(cluster_id, { :name => name })
end
def chown(client, cluster_id, owner_id, group_id = nil)
rc = client.chown_cluster(cluster_id, owner_id, group_id)
return [rc[:err_code], rc[:message]] if CloudClient.is_error?(rc)
def chown(client, cluster_ids, owner_id, group_id = nil)
cluster_ids.each do |cluster_id|
rc = client.chown_cluster(cluster_id, owner_id, group_id)
return [rc[:err_code], rc[:message]] if CloudClient.is_error?(rc)
end
0
end
def chgrp(client, cluster_id, group_id)
rc = client.chgrp_cluster(cluster_id, group_id)
return [rc[:err_code], rc[:message]] if CloudClient.is_error?(rc)
def chgrp(client, cluster_ids, group_id)
cluster_ids.each do |cluster_id|
rc = client.chgrp_cluster(cluster_id, group_id)
return [rc[:err_code], rc[:message]] if CloudClient.is_error?(rc)
end
0
end
def chmod(client, cluster_id, octet)
rc = client.chmod_cluster(cluster_id, octet)
return [rc[:err_code], rc[:message]] if CloudClient.is_error?(rc)
def chmod(client, cluster_ids, octet)
cluster_ids.each do |cluster_id|
rc = client.chmod_cluster(cluster_id, octet)
return [rc[:err_code], rc[:message]] if CloudClient.is_error?(rc)
end
0
end
@@ -306,24 +314,26 @@ class OneKSClusterHelper < ODSHelper
0
end
def upgrade(client, cluster_id, options = {})
cluster = client.get_cluster(cluster_id, :expand => true)
return [cluster[:err_code], cluster[:message]] if CloudClient.is_error?(cluster)
def upgrade(client, cluster_ids, options = {})
cluster_ids.each do |cluster_id|
cluster = client.get_cluster(cluster_id, :expand => true)
return [cluster[:err_code], cluster[:message]] if CloudClient.is_error?(cluster)
family_name = cluster.dig(:TEMPLATE, :CLUSTER_BODY, :control_plane, :family)
return [-1, "Unable to determine control plane family for cluster #{cluster_id}"] \
if family_name.nil? || family_name.to_s.empty?
family_name = cluster.dig(:TEMPLATE, :CLUSTER_BODY, :control_plane, :family)
return [-1, "Unable to determine control plane family for cluster #{cluster_id}"] \
if family_name.nil? || family_name.to_s.empty?
family = client.get_cluster_family(family_name)
return [family[:err_code], family[:message]] if CloudClient.is_error?(family)
family = client.get_cluster_family(family_name)
return [family[:err_code], family[:message]] if CloudClient.is_error?(family)
current_version = cluster.dig(:TEMPLATE, self.class.template_tag, :kubernetes_version)
puts "Current Kubernetes version: #{current_version}"
current_version = cluster.dig(:TEMPLATE, self.class.template_tag, :kubernetes_version)
puts "Current Kubernetes version: #{current_version}"
version = resolve_k8s_version(family, options[:kubernetes_version])
rc = client.upgrade_cluster(cluster_id, version)
version = resolve_k8s_version(family, options[:kubernetes_version])
rc = client.upgrade_cluster(cluster_id, version)
return [rc[:err_code], rc[:message]] if CloudClient.is_error?(rc)
return [rc[:err_code], rc[:message]] if CloudClient.is_error?(rc)
end
0
end
@@ -383,6 +393,8 @@ class OneKSClusterHelper < ODSHelper
end
failed ? 1 : 0
rescue Timeout::Error, Errno::ETIMEDOUT
[-1, '[ERROR] Operation timeout reached']
rescue StandardError => e
[-1, e.message]
ensure
@@ -526,6 +538,7 @@ class OneKSClusterHelper < ODSHelper
end
def ask_cluster_body(client)
select_cluster = can_select_cluster?
str_h1 = '%-80s'
# Inputs processed in prompt order
@@ -534,17 +547,17 @@ class OneKSClusterHelper < ODSHelper
puts
CLIHelper.print_header(str_h1 % 'DEPLOYMENT PLACEMENT')
cluster_id = ask_required_integer('OpenNebula cluster ID')
cluster_id = ask_required_integer('OpenNebula cluster ID') if select_cluster
public_network = ask_required_integer('Public network ID')
private_network = ask_required_integer('Private network ID')
deployment = {
:cluster => { :id => cluster_id },
:cluster => cluster_id.nil? ? nil : { :id => cluster_id },
:networks => {
:public => { :id => public_network },
:private => { :id => private_network }
}
}
}.compact
rc = client.validate_cluster_deployment(deployment)
return [rc[:err_code], rc[:message]] if CloudClient.is_error?(rc)
@@ -595,12 +608,10 @@ class OneKSClusterHelper < ODSHelper
return [-1, "Missing #{self.class.template_tag} for cluster #{cluster_id}"] unless body
deployment = (body[:deployment] || {}).dup
deployment_id = deployment.dig(:cluster, :id)
public_network = deployment.dig(:networks, :public, :id)
private_network = deployment.dig(:networks, :private, :id)
missing = []
missing << 'deployment.cluster.id' if deployment_id.nil?
missing << 'deployment.networks.public.id' if public_network.nil?
missing << 'deployment.networks.private.id' if private_network.nil?
@@ -614,21 +625,38 @@ class OneKSClusterHelper < ODSHelper
end
def ask_cluster_check(body = {})
select_cluster = can_select_cluster?
cluster_id = body.dig(:cluster, :id)
public_network = body.dig(:networks, :public, :id)
private_network = body.dig(:networks, :private, :id)
cluster_id ||= ask_required_integer('OpenNebula cluster ID') if cluster_id.nil?
cluster_id = ask_required_integer('OpenNebula cluster ID') \
if select_cluster && cluster_id.nil?
public_network ||= ask_required_integer('Public network ID')
private_network ||= ask_required_integer('Private network ID')
{
:cluster => { :id => cluster_id },
:cluster => cluster_id.nil? ? nil : { :id => cluster_id },
:networks => {
:public => { :id => public_network },
:private => { :id => private_network }
}
}
}.compact
end
def can_select_cluster?
clusters = OpenNebula::ClusterPool.new(@client)
rc = clusters.info
if OpenNebula.is_error?(rc)
return false if rc.errno == OpenNebula::Error::EAUTHORIZATION
raise rc.message
end
clusters.any?
end
end
+14 -10
View File
@@ -196,12 +196,14 @@ class OneKSGroupHelper < ODSHelper
client.update_cluster_nodegroup(cluster_id, group_id, { :name => name })
end
def scale(client, group_id, target)
cluster_id = resolve_cluster_group(client, group_id)
return cluster_id if is_error?(cluster_id)
def scale(client, group_ids, target)
group_ids.each do |group_id|
cluster_id = resolve_cluster_group(client, group_id)
return cluster_id if is_error?(cluster_id)
rc = client.scale_cluster_nodegroup(cluster_id, group_id, { :target => target })
return [rc[:err_code], rc[:message]] if CloudClient.is_error?(rc)
rc = client.scale_cluster_nodegroup(cluster_id, group_id, { :target => target })
return [rc[:err_code], rc[:message]] if CloudClient.is_error?(rc)
end
0
end
@@ -218,12 +220,14 @@ class OneKSGroupHelper < ODSHelper
0
end
def recover(client, group_id, action = :retry)
cluster_id = resolve_cluster_group(client, group_id)
return cluster_id if is_error?(cluster_id)
def recover(client, group_ids, action = :retry)
group_ids.each do |group_id|
cluster_id = resolve_cluster_group(client, group_id)
return cluster_id if is_error?(cluster_id)
rc = client.recover_cluster_nodegroup(cluster_id, group_id, action)
return [rc[:err_code], rc[:message]] if CloudClient.is_error?(rc)
rc = client.recover_cluster_nodegroup(cluster_id, group_id, action)
return [rc[:err_code], rc[:message]] if CloudClient.is_error?(rc)
end
0
end
+88 -68
View File
@@ -262,8 +262,19 @@ CommandParser::CmdParser.new(ARGV) do
[0, arg]
end
set :format, :clusterid_list, OneKS::Client.list_to_id_desc('OneKS Clusters') do |arg|
OneKS::Client.list_to_id(arg, :clusters)
set :format, :resourceid_list, OneKS::Client.list_to_id_desc('OneKS resources') do |arg|
case args[0]
when 'cluster'
OneKS::Client.list_to_id(arg, :clusters)
when 'group'
OneKS::Client.list_to_id(arg, :groups)
else
[-1]
end
end
set :format, :release_name, 'Application release name' do |arg|
args[0] == 'app' ? [0, arg] : [-1]
end
########################################################################
@@ -542,6 +553,11 @@ CommandParser::CmdParser.new(ARGV) do
case resource
when 'cluster'
kscluster.set_client(
:user => options[:username] || ENV['ONEKS_USER'],
:password => options[:password] || ENV['ONEKS_PASSWORD']
) unless body
rc = kscluster.create(client, body, options)
return rc if kscluster.is_error?(rc)
when 'group'
@@ -664,15 +680,16 @@ CommandParser::CmdParser.new(ARGV) do
oneks chgrp cluster <cluster_id> <group_id>
EOT
command :chgrp, chgrp_desc, :resource, :resource_id, :groupid do
client = OneKSHelper.client(options)
resource = args[0]
resource_id = args[1]
group_id = args[2].to_i
command :chgrp, chgrp_desc, :resource, [:range, :resourceid_list], :groupid do
client = OneKSHelper.client(options)
resource = args[0]
resource_ids = args[1]
group_id = args[2].to_i
case resource
when 'cluster'
rc = kscluster.chgrp(client, resource_id, group_id)
rc = kscluster.chgrp(client, resource_ids, group_id)
return rc if kscluster.is_error?(rc)
when 'group', 'app'
STDERR.puts(
"chgrp operation is not supported for #{resource}. " \
@@ -701,16 +718,17 @@ CommandParser::CmdParser.new(ARGV) do
oneks chown cluster <cluster_id> <user_id> <group_id>
EOT
command :chown, chown_desc, :resource, :resource_id, :userid, [:groupid, nil] do
client = OneKSHelper.client(options)
resource = args[0]
resource_id = args[1]
owner_id = args[2].to_i
group_id = args[3] ? args[3].to_i : nil
command :chown, chown_desc, :resource, [:range, :resourceid_list], :userid, [:groupid, nil] do
client = OneKSHelper.client(options)
resource = args[0]
resource_ids = args[1]
owner_id = args[2].to_i
group_id = args[3] ? args[3].to_i : nil
case resource
when 'cluster'
rc = kscluster.chown(client, resource_id, owner_id, group_id)
rc = kscluster.chown(client, resource_ids, owner_id, group_id)
return rc if kscluster.is_error?(rc)
when 'group', 'app'
STDERR.puts(
"chown operation is not supported for #{resource}. " \
@@ -736,20 +754,21 @@ CommandParser::CmdParser.new(ARGV) do
oneks chmod cluster <cluster_id> 640
EOT
command :chmod, chmod_desc, :resource, :resource_id, :octet do
command :chmod, chmod_desc, :resource, [:range, :resourceid_list], :octet do
if !/\A\d+\z/.match(args[2])
STDERR.puts "Invalid '#{args[2]}' octed permissions"
exit(-1)
end
client = OneKSHelper.client(options)
resource = args[0]
resource_id = args[1]
octet = OpenNebulaHelper.to_octet(args[2])
client = OneKSHelper.client(options)
resource = args[0]
resource_ids = args[1]
octet = OpenNebulaHelper.to_octet(args[2])
case resource
when 'cluster'
rc = kscluster.chmod(client, resource_id, octet)
rc = kscluster.chmod(client, resource_ids, octet)
return rc if kscluster.is_error?(rc)
when 'group', 'app'
STDERR.puts(
"chmod operation is not supported for #{resource}. " \
@@ -790,13 +809,13 @@ CommandParser::CmdParser.new(ARGV) do
command :recover,
recover_desc,
:resource,
:resource_id,
[:range, :resourceid_list],
:options => [
RECOVER_RETRY, RECOVER_SUCCESS, RECOVER_FAILURE, RECOVER_DELETE_DB
] do
client = OneKSHelper.client(options)
resource = args[0]
resource_id = args[1]
client = OneKSHelper.client(options)
resource = args[0]
resource_ids = args[1]
actions = {
:retry => options[:retry],
@@ -820,9 +839,12 @@ CommandParser::CmdParser.new(ARGV) do
rc =
case resource
when 'cluster'
kscluster.recover(client, [resource_id], action)
kscluster.recover(client, resource_ids, action)
when 'group'
ksgroup.recover(client, resource_id, action)
result = ksgroup.recover(client, resource_ids, action)
return result if ksgroup.is_error?(result)
result
when 'app'
STDERR.puts('Recover is only supported for clusters and groups')
exit(-1)
@@ -836,21 +858,6 @@ CommandParser::CmdParser.new(ARGV) do
exit(1)
end
delete_desc = <<-EOT.unindent
Delete a specific OneKS resource.
Supported resources: #{all_resources_supported}.
Examples:
# Delete a cluster
oneks delete cluster <cluster_id>
# Delete a nodegroup
oneks delete group <group_id>
# Uninstall an Application by release name
oneks delete app <release_name> --cluster-id <cluster_id>
EOT
check_desc = <<-EOT.unindent
Run the OneKS readiness check service to validate public and private
network configurations before provisioning the Kubernetes cluster.
@@ -884,25 +891,21 @@ CommandParser::CmdParser.new(ARGV) do
if deployment_id || public_network || private_network
missing = []
missing << '--opennebula-cluster' if deployment_id.nil?
missing << '--public-network' if public_network.nil?
missing << '--private-network' if private_network.nil?
unless missing.empty?
STDERR.puts(
"#{missing.join(', ')} must be provided together."
)
STDERR.puts("#{missing.join(', ')} must be provided together.")
exit(-1)
end
body = {
:cluster => { :id => deployment_id },
:cluster => deployment_id.nil? ? nil : { :id => deployment_id },
:networks => {
:public => { :id => public_network },
:private => { :id => private_network }
}
}
}.compact
end
client = OneKSHelper.client(options)
@@ -931,25 +934,40 @@ CommandParser::CmdParser.new(ARGV) do
body = { :cluster_id => resource_id }
end
kscluster.set_client(
:user => options[:username] || ENV['ONEKS_USER'],
:password => options[:password] || ENV['ONEKS_PASSWORD']
) if body.empty?
kscluster.check(client, body)
rescue Interrupt
puts 'Aborting...'
exit(1)
end
delete_desc = <<-EOT.unindent
Delete a specific OneKS resource.
Supported resources: #{all_resources_supported}.
Examples:
# Delete a cluster
oneks delete cluster <cluster_id>
# Delete a nodegroup
oneks delete group <group_id>
# Uninstall an Application by release name
oneks delete app <release_name> --cluster-id <cluster_id>
EOT
command :delete,
delete_desc,
:resource,
:resource_id,
[:release_name, :range, :resourceid_list],
:options => [OpenNebulaHelper::FORCE, CLUSTER_ID] do
resource = args[0]
identifier = args[1]
if resource != 'app' && !identifier.to_s.match?(/^\d+$/)
STDERR.puts "Argument '#{identifier}' is not a valid ID"
exit(-1)
end
if options[:force] && resource != 'cluster'
STDERR.puts '--force is only supported for cluster deletion'
exit(-1)
@@ -965,9 +983,9 @@ CommandParser::CmdParser.new(ARGV) do
rc =
case resource
when 'cluster'
kscluster.delete(client, [identifier.to_i], options)
kscluster.delete(client, identifier, options)
when 'group'
ksgroup.delete(client, [identifier.to_i])
ksgroup.delete(client, identifier)
when 'app'
ksapp.delete(client, options[:cluster_id], identifier)
end
@@ -1029,15 +1047,16 @@ CommandParser::CmdParser.new(ARGV) do
command :upgrade,
upgrade_desc,
:resource,
:resource_id,
[:range, :resourceid_list],
:options => [KUBERNETES_VERSION] do
client = OneKSHelper.client(options)
resource = args[0]
resource_id = args[1]
client = OneKSHelper.client(options)
resource = args[0]
resource_ids = args[1]
case resource
when 'cluster'
rc = kscluster.upgrade(client, resource_id, options)
rc = kscluster.upgrade(client, resource_ids, options)
return rc if kscluster.is_error?(rc)
when 'group', 'app'
STDERR.puts(
"Upgrade operation is not supported for #{resource}. " \
@@ -1066,12 +1085,12 @@ CommandParser::CmdParser.new(ARGV) do
command :scale,
scale_desc,
:resource,
:resource_id,
[:range, :resourceid_list],
:options => [TARGET] do
client = OneKSHelper.client(options)
resource = args[0]
resource_id = args[1]
target = options[:target]
client = OneKSHelper.client(options)
resource = args[0]
resource_ids = args[1]
target = options[:target]
case resource
when 'cluster'
@@ -1082,7 +1101,8 @@ CommandParser::CmdParser.new(ARGV) do
)
exit(-1)
when 'group'
rc = ksgroup.scale(client, resource_id, target)
rc = ksgroup.scale(client, resource_ids, target)
return rc if ksgroup.is_error?(rc)
when 'app'
STDERR.puts('Scale is only supported for groups')
exit(-1)
+1
View File
@@ -33,6 +33,7 @@ require 'shellwords'
require 'set'
require 'uri'
require 'digest'
require 'xmlrpc/marshal'
# Helpers
require_relative File.join(APP_ROOT, 'lib', 'helpers', 'appliance_helper')
+28 -4
View File
@@ -297,11 +297,35 @@ module OneKS
image = OneHelper::Image.find(client, name)
return image if OpenNebula.is_error?(image)
next if image
content = Hash.to_raw(content) if content.is_a?(Hash)
rc = OneHelper::Image.create(client, append_name(content, name), datastore_id)
return rc if OpenNebula.is_error?(rc)
unless image
content = Hash.to_raw(content) if content.is_a?(Hash)
image = OneHelper::Image.create(
client, append_name(content, name), datastore_id
)
return image if OpenNebula.is_error?(image)
end
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + K8s::K8S_TIMEOUT
loop do
rc = image.info
return rc if OpenNebula.is_error?(rc)
state = image.state_str
break if ['READY', 'USED'].include?(state)
return OpenNebula::Error.new(
"Image '#{name}' entered ERROR", OpenNebula::Error::EACTION
) if state == 'ERROR'
return OpenNebula::Error.new(
"Image '#{name}' did not become ready within #{K8s::K8S_TIMEOUT} seconds",
OpenNebula::Error::EACTION
) if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
sleep 2
end
end
true
+22 -15
View File
@@ -27,27 +27,27 @@ module OneKS
# Finds appliance images in any of the provided datastores.
# Marketplace imports identified by their path take precedence
# over manually imported images marked with ONEKS_APPLIANCE_ID.
def find_all_by_appliance_id(client, appliance_id, datastore_ids)
def find_all_by_appliance_id(client, appliance_id, datastore_ids = nil)
return OpenNebula::Error.new(
'OneKS appliance ID cannot be empty', OpenNebula::Error::EACTION
) if appliance_id.to_s.empty?
datastore_ids = Array(datastore_ids).map(&:to_s)
unless datastore_ids.nil?
datastore_ids = Array(datastore_ids).map(&:to_s)
return OpenNebula::Error.new(
'Datastore IDs cannot be empty', OpenNebula::Error::EACTION
) if datastore_ids.empty?
return OpenNebula::Error.new(
'Datastore IDs cannot be empty', OpenNebula::Error::EACTION
) if datastore_ids.empty?
end
image_pool = OpenNebula::ImagePool.new(
client, OpenNebula::Pool::INFO_ALL
)
image_pool = OpenNebula::ImagePool.new(client, OpenNebula::Pool::INFO_ALL)
rc = image_pool.info
return rc if OpenNebula.is_error?(rc)
images = image_pool.sort_by {|image| image.id.to_i }.filter_map do |image|
# Skip if the datastore is not inclided in the target cluster datastores
next unless datastore_ids.include?(image['DATASTORE_ID'].to_s)
next if datastore_ids && !datastore_ids.include?(image['DATASTORE_ID'].to_s)
rc = image.info
return rc if OpenNebula.is_error?(rc)
@@ -71,17 +71,26 @@ module OneKS
# OneKS appliance VM Template discovery
module Template
# Adds placement restrictions while preserving the appliance requirements
def sched_requirements(template, requirements)
return if requirements.to_s.empty?
existing = template['TEMPLATE/SCHED_REQUIREMENTS'].to_s.strip
return requirements if existing.empty?
"(#{existing}) & (#{requirements})"
end
# Finds the image and VM Template for a Marketplace or
# manually imported OneKS appliance.
def find_by_appliance_id(client, appliance_id, datastore_ids)
def find_by_appliance_id(client, appliance_id, datastore_ids = nil)
images = ::OneHelper::Image.find_all_by_appliance_id(
client, appliance_id, datastore_ids
)
return images if OpenNebula.is_error?(images)
return OpenNebula::Error.new(
"Cannot find OneKS appliance image #{appliance_id} in datastores " \
"#{Array(datastore_ids).join(', ')}",
"Cannot find OneKS appliance image #{appliance_id}",
OpenNebula::Error::EACTION
) if images.empty?
@@ -94,9 +103,7 @@ module OneKS
Log.warn(
'ONE',
'Multiple appliance images found for appliance ID ' \
"#{appliance_id} in datastores " \
"#{Array(datastore_ids).join(', ')}. Using image " \
"#{image.id} with template #{template.id}."
"#{appliance_id}. Using image #{image.id} with template #{template.id}."
)
end