Created
September 7, 2017 14:04
-
-
Save Tim-Zhang/20561b2518eb9910325e4d3e056dbdb9 to your computer and use it in GitHub Desktop.
Issue a `hyper exec` from API in node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const aws4 = require('hyper-aws4') | |
const https = require('https') | |
const credential = require('./credential') | |
const createError = (status, message) => { | |
const error = new Error(message) | |
error.status = status | |
return error | |
} | |
const request = (opts) => { | |
return new Promise((resolve, reject) => { | |
const host = 'us-west-1.hyper.sh' | |
const port = '443' | |
let headers = aws4.sign({ | |
url: `https://${host}/v1.23` + opts.path, | |
method: opts.method, | |
credential, | |
body: opts.body | |
}) | |
const HTTP = https | |
if (opts.body) { | |
headers = Object.assign(headers, { | |
'Content-Length': Buffer.byteLength(opts.body) | |
}) | |
} | |
const options = { | |
host, | |
port, | |
path: '/v1.23' + opts.path, | |
method: opts.method, | |
headers | |
} | |
const req = HTTP.request(options, (res) => { | |
if (opts.readBySelf) { | |
resolve(res) | |
return | |
} | |
const data = [] | |
res.on('data', (chunk) => { | |
data.push(chunk) | |
}) | |
res.on('end', () => { | |
if (res.statusCode < 400) { | |
resolve(Buffer.concat(data)) | |
return | |
} | |
reject(new Error(res.statusCode)) | |
}) | |
}) | |
if (opts.body) { | |
req.write(opts.body) | |
} | |
req.end() | |
req.on('error', (err) => { | |
reject(err) | |
}) | |
req.on('upgrade', (res, socket) => { | |
resolve(socket) | |
}) | |
}) | |
} | |
const execCreate = (id, cmd) => { | |
return request({ | |
method: 'POST', | |
path: `/containers/${id}/exec`, | |
body: JSON.stringify({ | |
Cmd: cmd | |
}) | |
}) | |
} | |
const execStart = (id) => { | |
return request({ | |
method: 'POST', | |
path: `/exec/${id}/start`, | |
body: JSON.stringify({}) | |
}) | |
} | |
exports.exec = async (id, xxxId) => { | |
const createBuf = await execCreate(id, [ | |
'/opt/kafka/bin/kafka-topics.sh', | |
'--zookeeper', | |
'zoo1:2181,zoo2:2181,zoo3:2181', | |
'--delete', | |
'--topic', | |
`xxx-.*?-${xxxId}` | |
]) | |
const execId = JSON.parse(createBuf.toString()).Id | |
const startBuf = await execStart(execId) | |
const res = startBuf.toString() | |
if (res.includes('does not exist on ZK path')) throw createError(404, 'topic does not exist') | |
if (!((res.match(/is\smarked\sfor\sdeletion/g) || []).length === 2)) throw new Error(res) | |
console.log(res) // eslint-disable-line no-console | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment