B #3951: provision create (#432)

Signed-off-by: Jorge Lobo <jlobo@opennebula.io>

Co-authored-by: Jorge Lobo <jlobo@opennebula.systems>
This commit is contained in:
Jorge Miguel Lobo EscalonaandJorge Lobo authored and GitHub committed 2020-11-17 14:41:59 +01:00
1 parent 826d5e9af0
commit 701b9e30a7
9 files changed
+179 -84

No files matched your search

+1 -1
View File
@@ -32,7 +32,7 @@ defaultFilesRoutes.map(file => {
}
} catch (error) {
if (error instanceof Error && error.code === 'MODULE_NOT_FOUND') {
const config = defaultConfigErrorMessage;
const config = defaultConfigErrorMessage
config.type = error.message
messageTerminal(config)
}
@@ -13,13 +13,28 @@
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
const { v4 } = require('uuid')
const { dirname, basename } = require('path')
const events = require('events')
const { Document } = require('yaml')
const { writeFileSync, removeSync, readdirSync, statSync, existsSync, mkdirsSync } = require('fs-extra')
const {
writeFileSync,
removeSync,
readdirSync,
statSync,
existsSync,
mkdirsSync,
renameSync,
moveSync
} = require('fs-extra')
const { spawnSync, spawn } = require('child_process')
const { messageTerminal } = require('server/utils/general')
const eventsEmitter = new events.EventEmitter()
const defaultError = (err = '', message = 'Error: %s') => ({
color: 'red',
message,
type: err
})
const publish = (eventName = '', message = {}) => {
if (eventName && message) {
@@ -59,22 +74,41 @@ const getFiles = (dir = '', ext = '', errorCallback = () => undefined) => {
}
})
} catch (error) {
const config = {
color: 'red',
message: 'Error: %s',
type: (error && error.message) || ''
}
messageTerminal(config)
messageTerminal(defaultError((error && error.message) || ''))
errorCallback(error)
}
}
return pathFiles
}
const createFolderWithFiles = (path = '', files = [], filename = '') => {
const rtn = { name: '', files: [] }
const name = filename || v4().replace(/-/g, '').toUpperCase()
const internalPath = `${path}/${name}`
try {
if (!existsSync(internalPath)) {
mkdirsSync(internalPath)
}
rtn.name = name
if (files && Array.isArray(files)) {
files.forEach(file => {
if (file && file.name && file.ext) {
const filePath = `${internalPath}/${file.name}.${file.ext}`
rtn.files.push({ name: file.name, ext: file.ext, path: filePath })
writeFileSync(filePath, (file && file.content) || '')
}
})
}
} catch (error) {
messageTerminal(defaultError((error && error.message) || ''))
}
return rtn
}
const createTemporalFile = (path = '', ext = '', content = '') => {
let rtn
const name = v4().replace(/-/g, '').toUpperCase()
const file = `${path + name + ext}`
const file = `${path + name}.${ext}`
try {
if (!existsSync(path)) {
mkdirsSync(path)
@@ -82,12 +116,7 @@ const createTemporalFile = (path = '', ext = '', content = '') => {
writeFileSync(file, content)
rtn = { name, path: file }
} catch (error) {
const config = {
color: 'red',
message: 'Error: %s',
type: (error && error.message) || ''
}
messageTerminal(config)
messageTerminal(defaultError((error && error.message) || ''))
}
return rtn
}
@@ -101,12 +130,7 @@ const createYMLContent = (content = '') => {
doc.contents = content
rtn = doc
} catch (error) {
const config = {
color: 'red',
message: 'Error: %s',
type: (error && error.message) || ''
}
messageTerminal(config)
messageTerminal(defaultError((error && error.message) || ''))
}
}
return rtn
@@ -117,44 +141,91 @@ const removeFile = (path = '') => {
try {
removeSync(path, { force: true })
} catch (error) {
const config = {
color: 'red',
message: 'Error: %s',
type: (error && error.message) || ''
}
messageTerminal(config)
messageTerminal(defaultError((error && error.message) || ''))
}
}
}
const renameFolder = (path = '', name = '', type = 'replace') => {
let rtn = false
if (path) {
let internalPath = path
try {
if (statSync(path).isFile()) {
internalPath = dirname(path)
}
if (name && type && ['replace', 'prepend', 'append'].includes(type)) {
const base = dirname(internalPath)
let newPath = `${base}/${name}`
switch (type) {
case 'prepend':
newPath = `${base}/${name + basename(internalPath)}`
break
case 'append':
newPath = `${base}/${basename(internalPath) + name}`
break
default:
break
}
renameSync(internalPath, newPath)
rtn = newPath
}
} catch (error) {
messageTerminal(defaultError((error && error.message) || ''))
}
}
return rtn
}
const moveToFolder = (path = '', relative = '/../') => {
let rtn = false
if (path && relative) {
try {
moveSync(path, `${dirname(path + relative)}/${basename(path)}`)
rtn = true
} catch (error) {
messageTerminal(defaultError((error && error.message) || ''))
}
}
return rtn
}
const executeCommandAsync = (
command = '',
resource = '',
stderr = () => undefined,
stdout = () => undefined,
close = () => undefined
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 rsc = Array.isArray(resource) ? resource : [resource]
const execute = spawn(command, [...rsc])
if (execute) {
execute.stdout.on('data', (data) => {
if (stdout && typeof stdout === 'function') {
stdout(data)
if (out) {
out(data)
}
})
execute.stderr.on('data', (data) => {
if (stderr && typeof stderr === 'function') {
stderr(data)
if (err) {
err(data)
}
})
execute.on('error', error => {
messageTerminal(defaultError((error && error.message) || '', 'Error command: %s'))
})
execute.on('close', (code) => {
if (code !== 0) {
console.log(`ps process exited with code ${code}`)
}
if (close && typeof close === 'function') {
close(code)
if (close) {
// code === 0 is success command
close(code === 0)
}
})
}
@@ -171,12 +242,7 @@ const executeCommand = (command = '', resource = '') => {
}
if (execute.stderr && execute.stderr.length > 0) {
rtn.data = execute.stderr.toString()
const config = {
color: 'red',
message: 'Error command: %s',
type: execute.stderr.toString()
}
messageTerminal(config)
messageTerminal(defaultError(execute.stderr.toString(), 'Error command: %s'))
}
}
return rtn
@@ -186,7 +252,10 @@ const functionRoutes = {
createYMLContent,
executeCommand,
createTemporalFile,
createFolderWithFiles,
removeFile,
renameFolder,
moveToFolder,
getFiles,
executeCommandAsync,
publish,
@@ -103,8 +103,7 @@ const createProviders = (res = {}, next = () => undefined, params = {}, userData
if (valSchema.valid) {
const content = createYMLContent(resource)
if (content) {
const ext = '.yaml'
const file = createTemporalFile(tmpPath, ext, content)
const file = createTemporalFile(tmpPath, 'yaml', content)
if (file && file.name && file.path) {
const paramsCommand = ['create', file.path, ...authCommand]
const executedCommand = executeCommand(command, paramsCommand)
@@ -142,8 +141,7 @@ const updateProviders = (res = {}, next = () => undefined, params = {}, userData
if (valSchema.valid) {
const content = createYMLContent(resource)
if (content) {
const ext = '.yaml'
const file = createTemporalFile(tmpPath, ext, content)
const file = createTemporalFile(tmpPath, 'yaml', content)
if (file && file.name && file.path) {
const paramsCommand = ['update', params.id, file.path, ...authCommand]
const executedCommand = executeCommand(command, paramsCommand)
@@ -14,6 +14,7 @@
/* -------------------------------------------------------------------------- */
const { Validator } = require('jsonschema')
const { createWriteStream } = require('fs-extra')
const {
ok,
accepted,
@@ -25,8 +26,11 @@ const {
executeCommand,
executeCommandAsync,
createTemporalFile,
createFolderWithFiles,
createYMLContent,
removeFile,
renameFolder,
moveToFolder,
publish
} = require('./functions')
const { provision } = require('./schemas')
@@ -34,6 +38,14 @@ const { provision } = require('./schemas')
const httpInternalError = httpResponse(internalServerError, '', '')
const command = 'oneprovision'
const logFile = {
name: 'stdouterr',
ext: 'log'
}
const configFile = {
name: 'provision',
ext: 'yaml'
}
const getList = (res = {}, next = () => undefined, params = {}, userData = {}) => {
const { user, password } = userData
@@ -157,8 +169,8 @@ const hostCommandSSH = (res = {}, next = () => undefined, params = {}, userData
next()
}
const createProvision = (res = {}, next = () => undefined, params = {}, userData = {}) => { // falta
const { user, password } = userData
const createProvision = (res = {}, next = () => undefined, params = {}, userData = {}) => {
const { user, password, id } = userData
let rtn = httpInternalError
if (params && params.resource && user && password) {
const authCommand = ['--user', user, '--password', password]
@@ -168,23 +180,44 @@ const createProvision = (res = {}, next = () => undefined, params = {}, userData
if (valSchema.valid) {
const content = createYMLContent(resource)
if (content) {
const ext = '.yaml'
const file = createTemporalFile(`${global.CPI}/provision/`, ext, content)
if (file && file.name && file.path) {
const paramsCommand = ['create', file.path, '--debug', '--skip-provision', ...authCommand]
// esto tiene que estar vivo
executeCommandAsync(
command,
paramsCommand,
message => {
publish(command, { id: file.name, message: message.toString() })
const files = createFolderWithFiles(`${global.CPI}/provision/${id}/tmp`, [{ name: logFile.name, ext: logFile.ext }, { name: configFile.name, ext: configFile.ext, content }])
if (files && files.name && files.files) {
const find = (val = '', ext = '', arr = files.files) => arr.find(e => e && e.path && e.ext && e.name && e.name === val && e.ext === ext)
const config = find(configFile.name, configFile.ext)
const log = find(logFile.name, logFile.ext)
if (config && log) {
const paramsCommand = ['create', config.path, '--batch', '--debug', '--skip-provision', ...authCommand]
let lastLine = ''
var stream = createWriteStream(log.path, { flags: 'a' })
const emit = message => {
lastLine = message.toString()
stream.write(lastLine)
publish(command, { id: files.name, message: lastLine })
}
)
res.locals.httpCode = httpResponse(accepted, file.name)
next()
return
executeCommandAsync(
command,
paramsCommand,
{
err: emit,
out: emit,
close: success => {
stream.end()
if (success && /^ID: \d+/.test(lastLine)) {
const newPath = renameFolder(config.path, lastLine.match('\\d+'))
if (newPath) {
moveToFolder(newPath, '/../../../')
}
}
if (success === false) {
renameFolder(config.path, '.ERROR', 'append')
}
}
}
)
res.locals.httpCode = httpResponse(accepted, files.name)
next()
return
}
}
}
} else {
@@ -240,8 +273,7 @@ const validate = (res = {}, next = () => undefined, params = {}, userData = {})
if (valSchema.valid) {
const content = createYMLContent(resource)
if (content) {
const ext = '.yaml'
const file = createTemporalFile(tmpPath, ext, content)
const file = createTemporalFile(tmpPath, 'yaml', content)
if (file && file.name && file.path) {
const paramsCommand = ['validate', file.path, ...authCommand]
const executedCommand = executeCommand(command, paramsCommand)
@@ -62,8 +62,7 @@ const createProvisionTemplate = (res = {}, next = () => undefined, params = {},
if (valSchema.valid) {
const content = createYMLContent(resource)
if (content) {
const ext = '.yaml'
const file = createTemporalFile(tmpPath, ext, content)
const file = createTemporalFile(tmpPath, 'yaml', content)
if (file && file.name && file.path) {
const paramsCommand = ['create', file.path, ...authCommand]
const executedCommand = executeCommand(command, paramsCommand)
@@ -121,8 +120,7 @@ const updateProvisionTemplate = (res = {}, next = () => undefined, params = {},
if (valSchema.valid) {
const content = createYMLContent(resource)
if (content) {
const ext = '.yaml'
const file = createTemporalFile(tmpPath, ext, content)
const file = createTemporalFile(tmpPath, 'yaml', content)
if (file && file.name && file.path) {
const paramsCommand = ['update', params.id, file.path, ...authCommand]
const executedCommand = executeCommand(command, paramsCommand)
@@ -90,13 +90,14 @@ router.all(
httpMethod
)
if (valRouteFunction) {
const userIdOpennebula = getIdUserOpennebula()
valRouteFunction(
dataSources,
res,
next,
connectOpennebula,
getIdUserOpennebula(),
{ user: getUserOpennebula(), password: getPassOpennebula() }
userIdOpennebula,
{ id: userIdOpennebula, user: getUserOpennebula(), password: getPassOpennebula() }
)
} else {
next()
@@ -27,8 +27,7 @@ const main = (app = {}) => {
if (
server &&
server.handshake &&
server.handshake.query &&
server.handshake.query.zone
server.handshake.query
) {
const queryZone = server.handshake.query.zone
const zone = queryZone && queryZone !== 'undefined' ? queryZone : '0'
@@ -26,7 +26,6 @@ const main = (app = {}) => {
subscriber(
'oneprovision',
data => {
console.log('fill file')
app.emit(type, {
id: data.id,
data: data.message
+5 -6
View File
@@ -86,10 +86,11 @@ const existsFile = (path = '', success = () => undefined, error = () => undefine
rtn = true
}
} catch (err) {
errorData = (err && err.message) || ''
messageTerminal({
color: 'red',
message: 'Error: %s',
type: (err && err.message) || ''
type: errorData
})
}
if (rtn) {
@@ -97,7 +98,6 @@ const existsFile = (path = '', success = () => undefined, error = () => undefine
} else {
error(errorData)
}
return rtn
}
@@ -130,12 +130,11 @@ const genFireedgeKey = () => {
() => {
createFile(
global.FIREEDGE_KEY_PATH, uuidv4.replace(/-/g, ''), () => undefined, err => {
const config = {
messageTerminal({
color: 'red',
message: 'Error: %s',
type: err.message || ''
}
messageTerminal(config)
type: (err && err.message) || ''
})
})
}
)