F #5422: Separate config files (#1545)

This commit is contained in:
Jorge Miguel Lobo Escalona authored and GitHub committed 2021-10-25 19:42:13 +02:00
1 parent 3945aa842a
commit 17244697fa
31 files changed
+1870 -12662

No files matched your search

+11 -1
View File
@@ -1,5 +1,15 @@
# Prepend for oneprovision command
vcenter_prepend_command: ''
# Prepend for sunstone commands
sunstone_prepend: ''
# Support
support_url: ''
support_token: ''
# this display button and clock icon in table of vm
:leases:
leases:
suspend:
time: "+1209600"
color: "#000000"
+1349 -12452
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -32,7 +32,7 @@
"devDependencies": {
"@pmmmwh/react-refresh-webpack-plugin": "0.5.1",
"cross-env": "7.0.2",
"eslint": "7.11.0",
"eslint": "7.32.0",
"eslint-config-prettier": "6.11.0",
"eslint-config-standard": "14.1.1",
"eslint-import-resolver-alias": "1.1.2",
@@ -107,6 +107,7 @@
"luxon": "1.28.0",
"marked": "2.0.0",
"morgan": "1.10.0",
"node-zendesk": "^2.1.0",
"notistack": "2.0.2",
"opennebula-guacamole": "1.0.0",
"path": "0.12.7",
+2 -2
View File
@@ -32,7 +32,7 @@ import {
import { websockets } from './routes/websockets'
import { guacamole } from './routes/websockets/guacamole'
import { vmrc } from './routes/websockets/vmrc'
import { getConfig, messageTerminal } from './utils'
import { getFireedgeConfig, messageTerminal } from './utils'
import {
defaultAppName, defaultApps,
defaultEvents, defaultHost,
@@ -62,7 +62,7 @@ const basename = defaultAppName ? `/${defaultAppName}` : ''
let frontPath = 'client'
// settings
const appConfig = getConfig()
const appConfig = getFireedgeConfig()
const host = appConfig.host || defaultHost
const port = appConfig.port || defaultPort
@@ -25,7 +25,7 @@ const {
default2FAOpennebulaTmpVar
} = require('server/utils/constants/defaults')
const { httpResponse } = require('server/utils/server')
const { getConfig } = require('server/utils/yml')
const { getFireedgeConfig } = require('server/utils/yml')
const { check2Fa } = require('server/utils/jwt')
const { Actions } = require('server/utils/constants/commands/user')
const {
@@ -35,7 +35,7 @@ const {
} = require('server/utils/opennebula')
// user config
const appConfig = getConfig()
const appConfig = getFireedgeConfig()
const twoFactorAuthIssuer =
appConfig.TWO_FACTOR_AUTH_ISSUER || default2FAIssuer
@@ -29,7 +29,7 @@ const {
defaultSessionLimitExpiration,
defaultRememberSessionExpiration
} = require('server/utils/constants/defaults')
const { getConfig } = require('server/utils/yml')
const { getFireedgeConfig } = require('server/utils/yml')
const {
ok,
unauthorized,
@@ -43,7 +43,7 @@ const {
getDefaultParamsOfOpennebulaCommand
} = require('server/utils/opennebula')
const appConfig = getConfig()
const appConfig = getFireedgeConfig()
const namespace = appConfig.namespace || defaultNamespace
@@ -24,6 +24,7 @@ defaultFilesRoutes.map(file => {
try {
// eslint-disable-next-line global-require
const fileInfo = require(`./${file}`)
if (fileInfo.private && fileInfo.private.length) {
filesDataPrivate.push(...fileInfo.private)
}
@@ -18,13 +18,13 @@ const { request: axios } = require('axios')
const btoa = require('btoa')
const { defaultOneFlowServer } = require('server/utils/constants/defaults')
const { getConfig } = require('server/utils/yml')
const { getFireedgeConfig } = require('server/utils/yml')
const { httpMethod } = require('server/utils/constants/defaults')
const { addPrintf } = require('server/utils/general')
const { GET, DELETE } = httpMethod
const appConfig = getConfig()
const appConfig = getFireedgeConfig()
/**
* Return schema error.
@@ -30,8 +30,7 @@ const {
renameSync,
moveSync
} = require('fs-extra')
const { getConfig } = require('server/utils/yml')
const { spawnSync, spawn } = require('child_process')
const { getFireedgeConfig, getProvisionConfig } = require('server/utils/yml')
const { messageTerminal } = require('server/utils/general')
const { defaultError } = require('server/utils/server')
@@ -228,119 +227,16 @@ const moveToFolder = (path = '', relative = '/../') => {
return rtn
}
/**
* Add prepend of command example: 'ssh xxxx:'".
*
* @param {string} command - cli command
* @param {string} resource - resource by command
* @returns {object} command and resource
*/
const addPrependCommand = (command = '', resource = '') => {
const appConfig = getConfig()
const prependCommand = appConfig.oneprovision_prepend_command || ''
const rsc = Array.isArray(resource) ? resource : [resource]
let newCommand = command
let newRsc = rsc
if (prependCommand) {
const splitPrepend = prependCommand.split(' ').filter(el => el !== '')
newCommand = splitPrepend[0]
// remove command
splitPrepend.shift()
// stringify the rest of the parameters
const stringifyRestCommand = [command, ...rsc].join(' ')
newRsc = [...splitPrepend, stringifyRestCommand]
}
return {
cmd: newCommand,
rsc: newRsc
}
}
/**
* Add command optional params from fireedge server config.
*
* @returns {Array} command optional params
*/
const addOptionalCreateCommand = () => {
const appConfig = getConfig()
const optionalCreateCommand = appConfig.oneprovision_optional_create_command || ''
const optionalCreateCommand = getSpecificConfig('oneprovision_optional_create_command')
return [optionalCreateCommand].filter(Boolean) // return array position valids, no undefined or nulls
}
/**
* Run Asynchronous commands for CLI.
*
* @param {string} command - command to execute
* @param {string} resource - params for the command to execute
* @param {object} callbacks - the functions in case the command emits by the stderr(err), stdout(out) and when it finishes(close)
*/
const executeCommandAsync = (
command = '',
resource = '',
callbacks = {
err: () => undefined,
out: () => undefined,
close: () => undefined
}
) => {
const err = callbacks && callbacks.err && typeof callbacks.err === 'function' ? callbacks.err : () => undefined
const out = callbacks && callbacks.out && typeof callbacks.out === 'function' ? callbacks.out : () => undefined
const close = callbacks && callbacks.close && typeof callbacks.close === 'function' ? callbacks.close : () => undefined
const { cmd, rsc } = addPrependCommand(command, resource)
const execute = spawn(cmd, rsc)
if (execute) {
execute.stderr.on('data', (data) => {
err(data)
})
execute.stdout.on('data', (data) => {
out(data)
})
execute.on('error', error => {
messageTerminal(defaultError(error && error.message, 'Error command: %s'))
})
execute.on('close', (code) => {
if (close) {
// code === 0 is success command
close(code === 0)
}
})
}
}
/**
* Run Synchronous commands for CLI.
*
* @param {string} command - command to execute
* @param {string} resource - params for the command to execute
* @param {object} options - optional params for the command
* @returns {object} CLI output
*/
const executeCommand = (command = '', resource = '', options = {}) => {
let rtn = { success: false, data: null }
const { cmd, rsc } = addPrependCommand(command, resource)
const execute = spawnSync(cmd, rsc, options)
if (execute) {
if (execute.stdout && execute.status === 0) {
rtn = { success: true, data: execute.stdout.toString() }
} else if (execute.stderr && execute.stderr.length > 0) {
rtn = { success: false, data: execute.stderr.toString() }
messageTerminal(defaultError(execute.stderr.toString(), 'Error command: %s'))
}
}
return rtn
}
/**
* Get recursive folder from a directory.
*
@@ -377,7 +273,7 @@ const findRecursiveFolder = (path = '', finder = '', rtn = false) => {
*/
const getEndpoint = () => {
let rtn = []
const appConfig = getConfig()
const appConfig = getFireedgeConfig()
if (appConfig && appConfig.one_xmlrpc) {
const parseUrl = parse(appConfig.one_xmlrpc)
const protocol = parseUrl.protocol || ''
@@ -387,20 +283,39 @@ const getEndpoint = () => {
return rtn
}
/**
* Get provision config. (this if for v6.2).
*
* @param {string} key - key get
* @returns {string} value of config item
*/
const getSpecificConfig = (key = '') => {
if (key) {
const appConfig = getFireedgeConfig()
const provisionConfig = getProvisionConfig()
if (Object.hasOwnProperty.call(provisionConfig, key)) {
return provisionConfig[key]
}
if (Object.hasOwnProperty.call(appConfig, key)) {
return appConfig[key]
}
}
return ''
}
const functionRoutes = {
getEndpoint,
createYMLContent,
executeCommand,
createTemporalFile,
createFolderWithFiles,
removeFile,
renameFolder,
moveToFolder,
executeCommandAsync,
findRecursiveFolder,
publish,
addOptionalCreateCommand,
subscriber
subscriber,
getSpecificConfig
}
module.exports = functionRoutes
@@ -38,7 +38,8 @@ const setPrivateRoutes = (routes = {}, path = '', action = () => undefined) => {
setFunctionRoute(route, path,
(req, res, next, connection, userId, user) => {
action(req, res, next, routes[route], user, connection)
})
}
)
)
})
}
@@ -33,14 +33,15 @@ const {
httpResponse,
parsePostData,
getFilesbyEXT,
existsFile
existsFile,
executeCommand
} = require('server/utils/server')
const {
executeCommand,
createTemporalFile,
createYMLContent,
removeFile,
getEndpoint
getEndpoint,
getSpecificConfig
} = require('./functions')
const httpInternalError = httpResponse(internalServerError, '', '')
@@ -53,7 +54,7 @@ const httpInternalError = httpResponse(internalServerError, '', '')
* @param {object} params - params of http request
* @param {object} userData - user of http request
*/
const getConfig = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => {
const getProviderConfig = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => {
const path = `${global.paths.PROVISION_PATH}${defaultProvidersConfigPath}`
const extFiles = 'yaml'
let response = internalServerError
@@ -126,7 +127,7 @@ const getConnectionProviders = (res = {}, next = defaultEmptyFunction, params =
const authCommand = ['--user', user, '--password', password]
if (params && params.id) {
const paramsCommand = ['show', `${params.id}`.toLowerCase(), ...authCommand, ...endpoint, '--json']
const executedCommand = executeCommand(defaultCommandProvider, paramsCommand)
const executedCommand = executeCommand(defaultCommandProvider, paramsCommand, getSpecificConfig('oneprovision_prepend_command'))
try {
const response = executedCommand.success ? ok : internalServerError
const data = JSON.parse(executedCommand.data)
@@ -168,7 +169,7 @@ const getListProviders = (res = {}, next = defaultEmptyFunction, params = {}, us
if (params && params.id) {
paramsCommand = ['show', `${params.id}`.toLowerCase(), ...authCommand, ...endpoint, '--json']
}
const executedCommand = executeCommand(defaultCommandProvider, paramsCommand)
const executedCommand = executeCommand(defaultCommandProvider, paramsCommand, getSpecificConfig('oneprovision_prepend_command'))
try {
const response = executedCommand.success ? ok : internalServerError
const data = JSON.parse(executedCommand.data)
@@ -312,7 +313,7 @@ const deleteProvider = (res = {}, next = defaultEmptyFunction, params = {}, user
const endpoint = getEndpoint()
const authCommand = ['--user', user, '--password', password]
const paramsCommand = ['delete', `${params.id}`.toLowerCase(), ...authCommand, ...endpoint]
const executedCommand = executeCommand(defaultCommandProvider, paramsCommand)
const executedCommand = executeCommand(defaultCommandProvider, paramsCommand, getSpecificConfig('oneprovision_prepend_command'))
const data = executedCommand.data || ''
try {
if (executedCommand && executedCommand.success) {
@@ -331,7 +332,7 @@ const deleteProvider = (res = {}, next = defaultEmptyFunction, params = {}, user
}
const providerFunctionsApi = {
getConfig,
getProviderConfig,
getConnectionProviders,
getListProviders,
createProviders,
@@ -21,7 +21,7 @@ const {
createProviders,
updateProviders,
deleteProvider,
getConfig
getProviderConfig
} = require('./provider-functions')
const { httpMethod } = require('server/utils/constants/defaults')
@@ -42,7 +42,7 @@ const routes = {
}
},
config: {
action: getConfig,
action: getProviderConfig,
params: {}
}
},
@@ -35,7 +35,9 @@ const {
existsFile,
createFile,
getDirectories,
getFilesbyEXT
getFilesbyEXT,
executeCommand,
executeCommandAsync
} = require('server/utils/server')
const { checkEmptyObject } = require('server/utils/general')
const {
@@ -45,8 +47,6 @@ const {
defaultErrorTemplate
} = require('server/utils/constants/defaults')
const {
executeCommand,
executeCommandAsync,
createTemporalFile,
createFolderWithFiles,
createYMLContent,
@@ -56,7 +56,8 @@ const {
findRecursiveFolder,
publish,
getEndpoint,
addOptionalCreateCommand
addOptionalCreateCommand,
getSpecificConfig
} = require('./functions')
const { provision } = require('./schemas')
@@ -150,6 +151,7 @@ const executeWithEmit = (command = [], actions = {}, dataForLog = {}) => {
executeCommandAsync(
defaultCommandProvision,
command,
getSpecificConfig('oneprovision_prepend_command'),
{
err: message => {
emit(message, err)
@@ -301,7 +303,12 @@ const getProvisionDefaults = (res = {}, next = defaultEmptyFunction, params = {}
if (content && filePath && path) {
const name = basename(filePath).replace(`.${extFiles}`, '')
const paramsCommand = ['validate', '--dump', filePath, ...authCommand, ...endpoint]
const executedCommand = executeCommand(defaultCommandProvision, paramsCommand, { cwd: path })
const executedCommand = executeCommand(
defaultCommandProvision,
paramsCommand,
getSpecificConfig('oneprovision_prepend_command'),
{ cwd: path }
)
if (executedCommand && executedCommand.success) {
if (!provisions[name]) {
provisions[name] = []
@@ -385,7 +392,12 @@ const getListResourceProvision = (res = {}, next = defaultEmptyFunction, params
if (params && params.resource && user && password) {
const endpoint = getEndpoint()
const authCommand = ['--user', user, '--password', password]
const executedCommand = executeCommand(defaultCommandProvision, [`${params.resource}`.toLowerCase(), 'list', ...authCommand, ...endpoint, '--json'])
const paramsCommand = [`${params.resource}`.toLowerCase(), 'list', ...authCommand, ...endpoint, '--json']
const executedCommand = executeCommand(
defaultCommandProvision,
paramsCommand,
getSpecificConfig('oneprovision_prepend_command')
)
try {
const response = executedCommand.success ? ok : internalServerError
res.locals.httpCode = httpResponse(response, JSON.parse(executedCommand.data))
@@ -417,7 +429,11 @@ const getListProvisions = (res = {}, next = defaultEmptyFunction, params = {}, u
if (params && params.id) {
paramsCommand = ['show', `${params.id}`.toLowerCase(), ...authCommand, ...endpoint, '--json']
}
const executedCommand = executeCommand(defaultCommandProvision, paramsCommand)
const executedCommand = executeCommand(
defaultCommandProvision,
paramsCommand,
getSpecificConfig('oneprovision_prepend_command')
)
try {
const response = executedCommand.success ? ok : internalServerError
const data = JSON.parse(executedCommand.data)
@@ -466,7 +482,11 @@ const deleteResource = (res = {}, next = defaultEmptyFunction, params = {}, user
const endpoint = getEndpoint()
const authCommand = ['--user', user, '--password', password]
const paramsCommand = [`${params.resource}`.toLowerCase(), 'delete', `${params.id}`.toLowerCase(), ...authCommand, ...endpoint]
const executedCommand = executeCommand(defaultCommandProvision, paramsCommand)
const executedCommand = executeCommand(
defaultCommandProvision,
paramsCommand,
getSpecificConfig('oneprovision_prepend_command')
)
try {
const response = executedCommand.success ? ok : internalServerError
rtn = httpResponse(response, executedCommand.data ? JSON.parse(executedCommand.data) : params.id)
@@ -597,7 +617,11 @@ const hostCommand = (res = {}, next = defaultEmptyFunction, params = {}, userDat
const endpoint = getEndpoint()
const authCommand = ['--user', user, '--password', password]
const paramsCommand = ['host', `${params.action}`.toLowerCase(), `${params.id}`.toLowerCase(), ...authCommand, ...endpoint]
const executedCommand = executeCommand(defaultCommandProvision, paramsCommand)
const executedCommand = executeCommand(
defaultCommandProvision,
paramsCommand,
getSpecificConfig('oneprovision_prepend_command')
)
try {
const response = executedCommand.success ? ok : internalServerError
res.locals.httpCode = httpResponse(response, executedCommand.data ? JSON.parse(executedCommand.data) : params.id)
@@ -626,7 +650,11 @@ const hostCommandSSH = (res = {}, next = defaultEmptyFunction, params = {}, user
const endpoint = getEndpoint()
const authCommand = ['--user', user, '--password', password]
const paramsCommand = ['host', `${params.action}`.toLowerCase(), `${params.id}`.toLowerCase(), `${params.command}`.toLowerCase(), ...authCommand, ...endpoint]
const executedCommand = executeCommand(defaultCommandProvision, paramsCommand)
const executedCommand = executeCommand(
defaultCommandProvision,
paramsCommand,
getSpecificConfig('oneprovision_prepend_command')
)
try {
const response = executedCommand.success ? ok : internalServerError
res.locals.httpCode = httpResponse(response, executedCommand.data ? JSON.parse(executedCommand.data) : params.id)
@@ -930,7 +958,11 @@ const validate = (res = {}, next = defaultEmptyFunction, params = {}, userData =
const file = createTemporalFile(`${global.paths.CPI}/${defaultFolderTmpProvision}`, 'yaml', content)
if (file && file.name && file.path) {
const paramsCommand = ['validate', '--dump', file.path, ...authCommand, ...endpoint]
const executedCommand = executeCommand(defaultCommandProvision, paramsCommand)
const executedCommand = executeCommand(
defaultCommandProvision,
paramsCommand,
getSpecificConfig('oneprovision_prepend_command')
)
let response = internalServerError
if (executedCommand && executedCommand.success) {
response = ok
@@ -15,14 +15,27 @@
* ------------------------------------------------------------------------- */
const { Validator } = require('jsonschema')
const { defaultFolderTmpProvision, defaultCommandProvisionTemplate } = require('server/utils/constants/defaults')
const {
defaultFolderTmpProvision,
defaultCommandProvisionTemplate
} = require('server/utils/constants/defaults')
const {
ok,
internalServerError
} = require('server/utils/constants/http-codes')
const { httpResponse, parsePostData } = require('server/utils/server')
const { executeCommand, createYMLContent, createTemporalFile, removeFile, getEndpoint } = require('./functions')
const {
httpResponse,
parsePostData,
executeCommand
} = require('server/utils/server')
const {
createYMLContent,
createTemporalFile,
removeFile,
getEndpoint,
getSpecificConfig
} = require('./functions')
const { provider } = require('./schemas')
const httpInternalError = httpResponse(internalServerError, '', '')
@@ -45,7 +58,7 @@ const getListProvisionTemplates = (res = {}, next = () => undefined, params = {}
if (params && params.id) {
paramsCommand = ['show', `${params.id}`.toLowerCase(), ...authCommand, ...endpoint, '--json']
}
const executedCommand = executeCommand(defaultCommandProvisionTemplate, paramsCommand)
const executedCommand = executeCommand(defaultCommandProvisionTemplate, paramsCommand, getSpecificConfig('oneprovision_prepend_command'))
try {
const response = executedCommand.success ? ok : internalServerError
res.locals.httpCode = httpResponse(response, JSON.parse(executedCommand.data))
@@ -82,7 +95,7 @@ const createProvisionTemplate = (res = {}, next = () => undefined, params = {},
const file = createTemporalFile(`${global.paths.CPI}/${defaultFolderTmpProvision}`, 'yaml', content)
if (file && file.name && file.path) {
const paramsCommand = ['create', file.path, ...authCommand, ...endpoint]
const executedCommand = executeCommand(defaultCommandProvisionTemplate, paramsCommand)
const executedCommand = executeCommand(defaultCommandProvisionTemplate, paramsCommand, getSpecificConfig('oneprovision_prepend_command'))
res.locals.httpCode = httpResponse(internalServerError)
if (executedCommand && executedCommand.success && executedCommand.data) {
res.locals.httpCode = httpResponse(ok, executedCommand.data)
@@ -121,7 +134,7 @@ const instantiateProvisionTemplate = (res = {}, next = () => undefined, params =
const authCommand = ['--user', user, '--password', password]
const endpoint = getEndpoint()
const paramsCommand = ['instantiate', `${params.id}`.toLowerCase(), ...authCommand, ...endpoint]
const executedCommand = executeCommand(defaultCommandProvisionTemplate, paramsCommand)
const executedCommand = executeCommand(defaultCommandProvisionTemplate, paramsCommand, getSpecificConfig('oneprovision_prepend_command'))
try {
const response = executedCommand.success ? ok : internalServerError
res.locals.httpCode = httpResponse(response, JSON.parse(executedCommand.data))
@@ -158,7 +171,7 @@ const updateProvisionTemplate = (res = {}, next = () => undefined, params = {},
const file = createTemporalFile(`${global.paths.CPI}/${defaultFolderTmpProvision}`, 'yaml', content)
if (file && file.name && file.path) {
const paramsCommand = ['update', params.id, file.path, ...authCommand, ...endpoint]
const executedCommand = executeCommand(defaultCommandProvisionTemplate, paramsCommand)
const executedCommand = executeCommand(defaultCommandProvisionTemplate, paramsCommand, getSpecificConfig('oneprovision_prepend_command'))
res.locals.httpCode = httpResponse(internalServerError)
if (executedCommand && executedCommand.success && executedCommand.data) {
res.locals.httpCode = httpResponse(ok, executedCommand.data)
@@ -197,7 +210,7 @@ const deleteProvisionTemplate = (res = {}, next = () => undefined, params = {},
const authCommand = ['--user', user, '--password', password]
const endpoint = getEndpoint()
const paramsCommand = ['delete', `${params.id}`.toLowerCase(), ...authCommand, ...endpoint]
const executedCommand = executeCommand(defaultCommandProvisionTemplate, paramsCommand)
const executedCommand = executeCommand(defaultCommandProvisionTemplate, paramsCommand, getSpecificConfig('oneprovision_prepend_command'))
try {
const response = executedCommand.success ? ok : internalServerError
res.locals.httpCode = httpResponse(response, JSON.parse(executedCommand.data))
@@ -15,8 +15,10 @@
* ------------------------------------------------------------------------- */
const { parse } = require('yaml')
const { getSunstoneConfig } = require('server/utils/yml')
const { defaultEmptyFunction } = require('server/utils/constants/defaults')
const { existsFile, httpResponse, getFiles } = require('server/utils/server')
const { sensitiveDataRemoverConfig } = require('server/utils/opennebula')
const { Actions: ActionsUser } = require('server/utils/constants/commands/user')
const { Actions: ActionsGroup } = require('server/utils/constants/commands/group')
@@ -26,6 +28,8 @@ const {
notFound
} = require('server/utils/constants/http-codes')
const sensitiveData = ['support_url', 'support_token']
const httpInternalError = httpResponse(internalServerError, '', '')
/**
@@ -141,25 +145,26 @@ const getViews = (res = {}, next = () => undefined, params = {}, userData = {},
* @param {object} params - params of http request
* @param {object} userData - user of http request
*/
const getConfig = (res = {}, next = () => undefined, params = {}, userData = {}) => {
if (global && global.paths && global.paths.SUNSTONE_CONFIG) {
existsFile(
global.paths.SUNSTONE_CONFIG,
filedata => {
const jsonFileData = parse(filedata) || {}
responseHttp(
res,
next,
httpResponse(ok, jsonFileData)
const getConfig = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => {
let error
const config = getSunstoneConfig(
err => {
error = err
}
)
responseHttp(
res,
next,
error
? httpResponse(notFound, error)
: httpResponse(
ok,
sensitiveDataRemoverConfig(
config,
sensitiveData
)
},
() => {
responseHttp(res, next, notFound)
}
)
} else {
responseHttp(res, next, httpInternalError)
}
)
)
}
const sunstoneApi = {
@@ -0,0 +1,32 @@
/* ------------------------------------------------------------------------- *
* 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. *
* ------------------------------------------------------------------------- */
const questions = {
datastores: [
],
templates: [
],
networks: [
],
images: [
]
}
module.exports = questions
@@ -20,7 +20,7 @@ const express = require('express')
const { resolve } = require('path')
const Worker = require('tiny-worker')
const { defaults, httpCodes, params } = require('server/utils/constants')
const { getConfig } = require('server/utils/yml')
const { getFireedgeConfig } = require('server/utils/yml')
const {
opennebulaConnect,
@@ -81,7 +81,7 @@ router.all(
res.locals.httpCode = httpResponse(internalServerError)
const { zone } = getQueriesState()
// get data zones by config file
const appConfig = getConfig()
const appConfig = getFireedgeConfig()
if (
appConfig.one_xmlrpc &&
Array.isArray(defaultOpennebulaZones) &&
@@ -108,11 +108,13 @@ router.all(
const { resource } = req.params
const routeFunction = checkIfIsARouteFunction(resource, httpMethod)
res.locals.httpCode = httpResponse(methodNotAllowed)
const dataSources = {
[fromData.resource]: getParamsState(),
[fromData.query]: getQueriesState(),
[fromData.query]: req.query,
[fromData.postBody]: req.body
}
if (routeFunction) {
/*********************************************************
* This execute functions (routes)
@@ -140,6 +142,7 @@ router.all(
* This execute a XMLRPC commands
*********************************************************/
dataSources[fromData.query] = getQueriesState()
const { method } = getParamsState()
const command = commandXMLRPC(
resource,
@@ -21,7 +21,7 @@ const { createStore, compose, applyMiddleware } = require('redux')
const thunk = require('redux-thunk').default
const { ServerStyleSheets } = require('@mui/styles')
const rootReducer = require('client/store/reducers')
const { getConfig } = require('server/utils/yml')
const { getFireedgeConfig } = require('server/utils/yml')
const {
availableLanguages, defaultWebpackMode, defaultApps
} = require('server/utils/constants/defaults')
@@ -29,7 +29,7 @@ const { APP_URL, STATIC_FILES_URL } = require('client/constants')
const { upperCaseFirst } = require('client/utils')
// settings
const appConfig = getConfig()
const appConfig = getFireedgeConfig()
const langs = appConfig.langs || availableLanguages
const scriptLanguages = []
const languages = Object.keys(langs)
@@ -162,7 +162,7 @@ const validateResourceAndSession = (req, res, next) => {
res.status(status.id).json(status)
}
/**
* MIDDLEWARE set optional parameters.
* MIDDLEWARE set optional parameters (params ins URL).
*
* @param {object} req - http request
* @param {object} res - http response
@@ -174,6 +174,7 @@ const setOptionalParameters = (req, res, next) => {
const keys = Object.keys(req.params)
keys.forEach(param => {
if (start) {
// The params[0] is the resource
start = false
return start
}
@@ -15,7 +15,7 @@
* ------------------------------------------------------------------------- */
const GuacamoleOpennebula = require('opennebula-guacamole')
const { getConfig } = require('server/utils/yml')
const { getFireedgeConfig } = require('server/utils/yml')
const { messageTerminal } = require('server/utils/general')
const { genFireedgeKey, genPathResources } = require('server/utils/server')
const { writeInLogger } = require('server/utils/logger')
@@ -66,7 +66,7 @@ const clientCallbacks = {
}
}
const appConfig = getConfig()
const appConfig = getFireedgeConfig()
const guacd = appConfig.guacd || {}
const guacdPort = guacd.port || 4822
const guacdHost = guacd.host || 'localhost'
@@ -18,7 +18,7 @@
const { parse } = require('url')
const { createProxyMiddleware } = require('http-proxy-middleware')
const { readFileSync } = require('fs-extra')
const { getConfig } = require('server/utils/yml')
const { getFireedgeConfig } = require('server/utils/yml')
const { messageTerminal } = require('server/utils/general')
const { genPathResources, validateServerIsSecure } = require('server/utils/server')
const { writeInLogger } = require('server/utils/logger')
@@ -26,7 +26,7 @@ const { endpointVmrc, defaultPort } = require('server/utils/constants/defaults')
genPathResources()
const appConfig = getConfig()
const appConfig = getFireedgeConfig()
const port = appConfig.port || defaultPort
const protocol = validateServerIsSecure() ? 'https' : 'http'
const url = `${protocol}://localhost:${port}`
@@ -191,7 +191,7 @@ module.exports = {
default: 0
},
decrypt: {
from: postBody,
from: query,
default: false
}
}
@@ -105,7 +105,7 @@ module.exports = {
default: 0
},
decrypt: {
from: postBody,
from: query,
default: false
}
}
@@ -681,7 +681,7 @@ module.exports = {
from: query,
default: -2
},
filterbykey: {
filterBykey: {
from: query,
default: ''
}
@@ -171,7 +171,7 @@ module.exports = {
default: 0
},
decrypt: {
from: postBody,
from: query,
default: false
}
}
@@ -22,12 +22,12 @@ const internalProvisionPath = `${appName}/${appNameProvision}`
const baseUrl = `${appName ? `/${appName}/` : '/'}`
const baseUrlWebsockets = 'websockets/'
const apps = {
sunstone: {
name: appNameSunstone,
[appNameSunstone]: {
theme: appNameSunstone,
name: appNameSunstone,
assets: true
},
provision: {
[appNameProvision]: {
name: appNameProvision,
theme: appNameProvision
}
@@ -110,6 +110,7 @@ const defaults = {
defaultCommandProvision: 'oneprovision',
defaultCommandProvisionTemplate: 'oneprovision-template',
defaultCommandProvider: 'oneprovider',
defaultCommandVcenter: 'onevcenter',
defaultFolderTmpProvision: 'tmp',
defaultHideCredentials: true,
defaultHideCredentialReplacer: '****',
@@ -118,6 +119,7 @@ const defaults = {
defaultSunstonePath: internalSunstonePath,
defaultSunstoneViews: `${appNameSunstone}-views.yaml`,
defaultSunstoneConfig: `${appNameSunstone}-server.conf`,
defaultProvisionConfig: `${appNameProvision}-server.conf`,
defaultProvisionPath: internalProvisionPath,
defaultProvidersConfigPath: 'providers.d',
defaultTypeLog: 'prod',
+2 -2
View File
@@ -19,7 +19,7 @@ const functionRoutes = require('../routes/api')
const { validateAuth } = require('./jwt')
const { httpResponse, getDataZone } = require('./server')
const { messageTerminal, addPrintf, checkEmptyObject } = require('./general')
const { getConfig } = require('./yml')
const { getFireedgeConfig } = require('./yml')
const {
responseOpennebula,
@@ -133,7 +133,7 @@ module.exports = {
checkOpennebulaCommand,
checkMethodRouteFunction,
responseOpennebula,
getConfig,
getFireedgeConfig,
httpResponse,
getDataZone,
checkEmptyObject,
+136 -3
View File
@@ -32,10 +32,31 @@ const {
defaultMessageProblemOpennebula
} = require('./constants/defaults')
const { getConfig } = require('./yml')
const { getFireedgeConfig } = require('./yml')
// regex for separate the commands .info
const regexInfoAction = /^(\w+).info$/
// regex for separate string by lines
const regexLine = /\n/
// regex for remove multiple blanks
const regexRemoveBlanks = /\s+/gi
// regex for remove ANSI Color
// eslint-disable-next-line no-control-regex
const regexANSIColor = /\u001b\[.*?m/gi
// regex string with CSV format
const csvFormat = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/
// regex sanitize string CSV formated
const csvSanitize = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g
// regex single quote
const singleQuote = /\\'/g
// regex double quote
const doubleQuote = /\\"/g
// regex handle special case of empty last value.
const lastValueRegexCsv = /,\s*$/g
// regex text string wrapped in square brackets
const stringWrappedBrakets = /^\[.*\]$/g
// regex first and last brakets
const brakets = /(^\[)|(\]$)/g
/**
* Parse xml to JSON.
@@ -103,7 +124,7 @@ const opennebulaConnect = (username = '', password = '', zoneURL = '') => {
rtn = (action = '', parameters = [], callback = () => undefined, fillHookResource = true) => {
if (action && parameters && Array.isArray(parameters) && callback) {
// user config
const appConfig = getConfig()
const appConfig = getFireedgeConfig()
const namespace = appConfig.namespace || defaultNamespace
const xmlParameters = [`${username}:${password}`, ...parameters]
xmlClient.methodCall(
@@ -436,6 +457,115 @@ const generateNewResourceTemplate = (
return sprintf(wrapper, positions)
}
/**
* Parse result console to string.
*
* @param {string} stringConsole - console string
* @param {Array} excludeRegexs - array regexs for exclude
* @returns {string} new console string
*/
const consoleParseToString = (stringConsole = '', excludeRegexs = []) => {
const rtn = []
if (stringConsole) {
console.log('all -->', JSON.stringify(stringConsole))
const lines = stringConsole.split(regexLine)
lines.forEach(line => {
let test = ''
for (const c of line) {
test += c.charCodeAt(0) + ' '
}
console.log('-->', test)
let pass = true
if (Array.isArray(excludeRegexs)) {
excludeRegexs.forEach(rex => {
if (rex.test(line)) {
pass = false
}
})
}
line = line.replace(regexRemoveBlanks, ' ').replace(regexANSIColor, '').trim()
if (line && pass) {
rtn.push(line)
}
})
}
return rtn
}
/**
* Parse array string to json.
*
* @param {Array} arrayConsole - result of consoleParseToString function
* @param {string} regexHeader - regex for find header
* @returns {string} new console string
*/
const consoleParseToJSON = (arrayConsole = [], regexHeader = '') => {
let rtn = []
if (regexHeader && Array.isArray(arrayConsole) && arrayConsole[0] && regexHeader.test(arrayConsole[0])) {
const header = arrayConsole[0].split(',')
arrayConsole.forEach((row = '', i = 0) => {
if (row && i > 0) {
const explodeRow = CSVtoArray(row)
rtn.push(
explodeRow.map((value, index) => {
return { [header[index]]: stringWrappedBrakets.test(value) ? CSVtoArray(value.replace(brakets, '')) : value }
})
)
}
})
} else {
rtn = arrayConsole
}
return rtn
}
/**
* Parse strinf csv to array.
*
* @param {string} text - csv string
* @returns {Array} csv array
*/
const CSVtoArray = (text = '') => {
const rtn = []
if (csvFormat.test(text)) { // if input string is not well formed CSV string.
text.replace(csvSanitize,
(m0, m1, m2, m3) => {
if (m1 !== undefined) {
rtn.push(m1.replace(singleQuote, "'"))
} else if (m2 !== undefined) {
rtn.push(m2.replace(doubleQuote, '"'))
} else if (m3 !== undefined) {
rtn.push(m3)
}
return ''
})
if (lastValueRegexCsv.test(text)) {
rtn.push('')
}
}
return rtn
}
/**
* Remove config sensitive data.
*
* @param {object} config - config data
* @param {Array} keys - key for remove
* @returns {object} config without sensitive data
*/
const sensitiveDataRemoverConfig = (config = {}, keys = []) => {
const rtn = config
if (Array.isArray(keys)) {
keys.forEach(key => {
if (Object.hasOwnProperty.call(config, key)) {
delete rtn[key]
}
})
}
return config
}
module.exports = {
opennebulaConnect,
responseOpennebula,
@@ -448,5 +578,8 @@ module.exports = {
getDefaultParamsOfOpennebulaCommand,
generateNewResourceTemplate,
fillResourceforHookConnection,
xml2json
xml2json,
consoleParseToString,
consoleParseToJSON,
sensitiveDataRemoverConfig
}
+117 -1
View File
@@ -25,6 +25,7 @@ const { internalServerError } = require('./constants/http-codes')
const { messageTerminal } = require('server/utils/general')
const { validateAuth } = require('server/utils/jwt')
const { writeInLogger } = require('server/utils/logger')
const { spawnSync, spawn } = require('child_process')
const {
from: fromData,
defaultAppName,
@@ -45,6 +46,7 @@ const {
defaultSunstoneViews,
defaultSunstoneConfig,
defaultProvisionPath,
defaultProvisionConfig,
defaultEmptyFunction
} = require('./constants/defaults')
@@ -499,6 +501,9 @@ const genPathResources = () => {
if (!global.paths.PROVISION_PATH) {
global.paths.PROVISION_PATH = `${ETC_LOCATION}/${defaultProvisionPath}/`
}
if (!global.paths.PROVISION_CONFIG) {
global.paths.PROVISION_CONFIG = `${ETC_LOCATION}/${defaultProvisionPath}/${defaultProvisionConfig}`
}
if (!global.paths.ETC_CPI) {
global.paths.ETC_CPI = `${ETC_LOCATION}/${defaultAppName}`
}
@@ -659,6 +664,115 @@ const parsePostData = (postData = {}) => {
})
return rtn
}
/**
* Add prepend of command example: 'ssh xxxx:'".
*
* @param {string} command - cli command
* @param {string} resource - resource by command
* @param {string} prepend - prepend for command
* @returns {object} command and resource
*/
const addPrependCommand = (command = '', resource = '', prepend = '') => {
const rsc = Array.isArray(resource) ? resource : [resource]
let newCommand = command
let newRsc = rsc
if (prepend) {
const splitPrepend = prepend.split(' ').filter(el => el !== '')
newCommand = splitPrepend[0]
// remove command
splitPrepend.shift()
// stringify the rest of the parameters
const stringifyRestCommand = [command, ...rsc].join(' ')
newRsc = [...splitPrepend, stringifyRestCommand]
}
return {
cmd: newCommand,
rsc: newRsc
}
}
/**
* Run Synchronous commands for CLI.
*
* @param {string} command - command to execute
* @param {string} resource - params for the command to execute
* @param {string} prependCommand - prepend for command
* @param {object} options - optional params for the command
* @returns {object} CLI output
*/
const executeCommand = (command = '', resource = '', prependCommand = '', options = {}) => {
let rtn = { success: false, data: null }
const { cmd, rsc } = addPrependCommand(command, resource, prependCommand)
const execute = spawnSync(cmd, rsc, options)
if (execute) {
if (execute.stdout && execute.status === 0) {
rtn = { success: true, data: execute.stdout.toString() }
} else if (execute.stderr && execute.stderr.length > 0) {
rtn = { success: false, data: execute.stderr.toString() }
messageTerminal(
defaultError(
execute.stderr.toString(),
'Error command: %s'
)
)
}
}
return rtn
}
/**
* Run Asynchronous commands for CLI.
*
* @param {string} command - command to execute
* @param {string} resource - params for the command to execute
* @param {string} prependCommand - prepend for command
* @param {object} callbacks - the functions in case the command emits by the stderr(err), stdout(out) and when it finishes(close)
*/
const executeCommandAsync = (
command = '',
resource = '',
prependCommand = '',
callbacks = {
err: defaultEmptyFunction,
out: defaultEmptyFunction,
close: defaultEmptyFunction
}
) => {
const err = callbacks && callbacks.err && typeof callbacks.err === 'function' ? callbacks.err : defaultEmptyFunction
const out = callbacks && callbacks.out && typeof callbacks.out === 'function' ? callbacks.out : defaultEmptyFunction
const close = callbacks && callbacks.close && typeof callbacks.close === 'function' ? callbacks.close : defaultEmptyFunction
const { cmd, rsc } = addPrependCommand(command, resource, prependCommand)
const execute = spawn(cmd, rsc)
if (execute) {
execute.stderr.on('data', (data) => {
err(data)
})
execute.stdout.on('data', (data) => {
out(data)
})
execute.on('error', error => {
messageTerminal(defaultError(error && error.message, 'Error command: %s'))
})
execute.on('close', (code) => {
if (close) {
// code === 0 is success command
close(code === 0)
}
})
}
}
module.exports = {
setFunctionRoute,
addFunctionAsRoute,
@@ -684,5 +798,7 @@ module.exports = {
defaultError,
getDirectories,
getFiles,
getFilesbyEXT
getFilesbyEXT,
executeCommand,
executeCommandAsync
}
+63 -18
View File
@@ -17,37 +17,82 @@
const { env } = require('process')
const { resolve } = require('path')
const { parse } = require('yaml')
const { defaultConfigFile, defaultWebpackMode } = require('./constants/defaults')
const { existsFile } = require('server/utils/server')
const { defaultConfigFile, defaultWebpackMode, defaultSunstoneConfig, defaultProvisionConfig, defaultEmptyFunction } = require('./constants/defaults')
const { existsFile, defaultError } = require('server/utils/server')
const { messageTerminal } = require('server/utils/general')
const { global } = require('window-or-global')
const defaultPath = env && env.NODE_ENV === defaultWebpackMode ? ['../', '../', '../'] : ['../']
const basePaths = [__dirname, ...defaultPath, 'etc']
/**
* Get fireedge configurations.
*
* @param {string} pathfile - path config file
* @param {Function} errorFunction - callback error
* @returns {object} fireedge configurations
*/
const getConfig = () => {
const readYAMLFile = (pathfile = '', errorFunction = defaultEmptyFunction) => {
let rtn = {}
const defaultPath = env && env.NODE_ENV === defaultWebpackMode ? ['../', '../', '../'] : ['../']
const pathfile = (global && global.paths && global.paths.FIREEDGE_CONFIG) || resolve(__dirname, ...defaultPath, 'etc', defaultConfigFile)
const err = error => {
messageTerminal(
defaultError(error)
)
if (typeof errorFunction === 'function') {
errorFunction(error)
}
}
if (pathfile) {
existsFile(pathfile, filedata => {
rtn = parse(filedata)
}, err => {
const config = {
color: 'red',
message: 'Error: %s',
error: err.message || ''
}
messageTerminal(config)
})
existsFile(
pathfile,
filedata => {
try {
rtn = parse(filedata)
} catch (error) {
err(error && error.message)
}
},
err
)
}
return rtn
}
/**
* Get fireedge configurations.
*
* @param {Function} callbackError - callback error
* @returns {object} fireedge configurations
*/
const getFireedgeConfig = (callbackError = defaultEmptyFunction) => {
const pathfile = (global && global.paths && global.paths.FIREEDGE_CONFIG) || resolve(...basePaths, defaultConfigFile)
return readYAMLFile(pathfile, callbackError)
}
/**
* Get sunstone configurations.
*
* @param {Function} callbackError - callback error
* @returns {object} sunstone configurations
*/
const getSunstoneConfig = (callbackError = defaultEmptyFunction) => {
const pathfile = (global && global.paths && global.paths.SUNSTONE_CONFIG) || resolve(...basePaths, 'sunstone', defaultSunstoneConfig)
return readYAMLFile(pathfile, callbackError)
}
/**
* Get provision configurations.
*
* @param {Function} callbackError - callback error
* @returns {object} provision configurations
*/
const getProvisionConfig = (callbackError = defaultEmptyFunction) => {
const pathfile = (global && global.paths && global.paths.PROVISION_CONFIG) || resolve(...basePaths, 'provision', defaultProvisionConfig)
return readYAMLFile(pathfile, callbackError)
}
module.exports = {
getConfig
getFireedgeConfig,
getSunstoneConfig,
getProvisionConfig
}