chore: reformat with Prettier

This commit is contained in:
Julien Fontanet 2018-12-11 10:37:46 +01:00
parent 48727740c4
commit cc4ab94428
300 changed files with 1880 additions and 1728 deletions

View File

@ -14,7 +14,7 @@ const configs = {
'@babel/plugin-proposal-pipeline-operator': {
proposal: 'minimal',
},
'@babel/preset-env' (pkg) {
'@babel/preset-env'(pkg) {
return {
debug: !__TEST__,
@ -46,7 +46,7 @@ const getConfig = (key, ...args) => {
: config
}
module.exports = function (pkg, plugins, presets) {
module.exports = function(pkg, plugins, presets) {
plugins === undefined && (plugins = {})
presets === undefined && (presets = {})

View File

@ -5,7 +5,7 @@ const { NULL_REF, Xapi } = require('xen-api')
const pkg = require('./package.json')
Xapi.prototype.getVmDisks = async function (vm) {
Xapi.prototype.getVmDisks = async function(vm) {
const disks = { __proto__: null }
await Promise.all([
...vm.VBDs.map(async vbdRef => {
@ -19,7 +19,7 @@ Xapi.prototype.getVmDisks = async function (vm) {
return disks
}
defer(async function main ($defer, args) {
defer(async function main($defer, args) {
if (args.length === 0 || args.includes('-h') || args.includes('--help')) {
const cliName = Object.keys(pkg.bin)[0]
return console.error(

View File

@ -6,7 +6,7 @@ import parse from './parse'
const MAX_DELAY = 2 ** 31 - 1
class Job {
constructor (schedule, fn) {
constructor(schedule, fn) {
const wrapper = () => {
let result
try {
@ -33,18 +33,18 @@ class Job {
this._timeout = undefined
}
start () {
start() {
this.stop()
this._scheduleNext()
}
stop () {
stop() {
clearTimeout(this._timeout)
}
}
class Schedule {
constructor (pattern, zone = 'utc') {
constructor(pattern, zone = 'utc') {
this._schedule = parse(pattern)
this._createDate =
zone.toLowerCase() === 'utc'
@ -54,11 +54,11 @@ class Schedule {
: () => moment.tz(zone)
}
createJob (fn) {
createJob(fn) {
return new Job(this, fn)
}
next (n) {
next(n) {
const dates = new Array(n)
const schedule = this._schedule
let date = this._createDate()
@ -68,12 +68,12 @@ class Schedule {
return dates
}
_nextDelay () {
_nextDelay() {
const now = this._createDate()
return next(this._schedule, now) - now
}
startJob (fn) {
startJob(fn) {
const job = this.createJob(fn)
job.start()
return job.stop.bind(job)

View File

@ -13,7 +13,7 @@
// process.env.http_proxy
// ])
// ```
export default function defined () {
export default function defined() {
let args = arguments
let n = args.length
if (n === 1) {

View File

@ -1,4 +1,4 @@
export default function emitAsync (event) {
export default function emitAsync(event) {
let opts
let i = 1

View File

@ -12,7 +12,7 @@ const createTransport = config => {
if (Array.isArray(config)) {
const transports = config.map(createTransport)
const { length } = transports
return function () {
return function() {
for (let i = 0; i < length; ++i) {
transports[i].apply(this, arguments)
}
@ -29,14 +29,14 @@ const createTransport = config => {
}
const orig = transport
transport = function (log) {
transport = function(log) {
if ((level !== undefined && log.level >= level) || filter(log)) {
return orig.apply(this, arguments)
}
}
} else if (level !== undefined) {
const orig = transport
transport = function (log) {
transport = function(log) {
if (log.level >= level) {
return orig.apply(this, arguments)
}
@ -85,7 +85,7 @@ export const catchGlobalErrors = logger => {
const EventEmitter = require('events')
const { prototype } = EventEmitter
const { emit } = prototype
function patchedEmit (event, error) {
function patchedEmit(event, error) {
if (event === 'error' && this.listenerCount(event) === 0) {
logger.error('unhandled error event', { error })
return false

View File

@ -61,7 +61,7 @@ const mixin = Mixins => Class => {
const n = Mixins.length
function DecoratedClass (...args) {
function DecoratedClass(...args) {
const instance = new Class(...args)
for (let i = 0; i < n; ++i) {

View File

@ -33,17 +33,17 @@ const isRawString = string => {
// -------------------------------------------------------------------
class Node {
createPredicate () {
createPredicate() {
return value => this.match(value)
}
}
export class Null extends Node {
match () {
match() {
return true
}
toString () {
toString() {
return ''
}
}
@ -51,7 +51,7 @@ export class Null extends Node {
const formatTerms = terms => terms.map(term => term.toString(true)).join(' ')
export class And extends Node {
constructor (children) {
constructor(children) {
super()
if (children.length === 1) {
@ -60,29 +60,29 @@ export class And extends Node {
this.children = children
}
match (value) {
match(value) {
return this.children.every(child => child.match(value))
}
toString (isNested) {
toString(isNested) {
const terms = formatTerms(this.children)
return isNested ? `(${terms})` : terms
}
}
export class Comparison extends Node {
constructor (operator, value) {
constructor(operator, value) {
super()
this._comparator = Comparison.comparators[operator]
this._operator = operator
this._value = value
}
match (value) {
match(value) {
return typeof value === 'number' && this._comparator(value, this._value)
}
toString () {
toString() {
return this._operator + String(this._value)
}
}
@ -94,7 +94,7 @@ Comparison.comparators = {
}
export class Or extends Node {
constructor (children) {
constructor(children) {
super()
if (children.length === 1) {
@ -103,33 +103,33 @@ export class Or extends Node {
this.children = children
}
match (value) {
match(value) {
return this.children.some(child => child.match(value))
}
toString () {
toString() {
return `|(${formatTerms(this.children)})`
}
}
export class Not extends Node {
constructor (child) {
constructor(child) {
super()
this.child = child
}
match (value) {
match(value) {
return !this.child.match(value)
}
toString () {
toString() {
return '!' + this.child.toString(true)
}
}
export class NumberNode extends Node {
constructor (value) {
constructor(value) {
super()
this.value = value
@ -140,21 +140,21 @@ export class NumberNode extends Node {
})
}
match (value) {
match(value) {
return (
value === this.value ||
(value !== null && typeof value === 'object' && some(value, this.match))
)
}
toString () {
toString() {
return String(this.value)
}
}
export { NumberNode as Number }
export class NumberOrStringNode extends Node {
constructor (value) {
constructor(value) {
super()
this.value = value
@ -165,7 +165,7 @@ export class NumberOrStringNode extends Node {
})
}
match (lcValue, numValue, value) {
match(lcValue, numValue, value) {
return (
value === numValue ||
(typeof value === 'string'
@ -175,25 +175,25 @@ export class NumberOrStringNode extends Node {
)
}
toString () {
toString() {
return this.value
}
}
export { NumberOrStringNode as NumberOrString }
export class Property extends Node {
constructor (name, child) {
constructor(name, child) {
super()
this.name = name
this.child = child
}
match (value) {
match(value) {
return value != null && this.child.match(value[this.name])
}
toString () {
toString() {
return `${formatString(this.name)}:${this.child.toString(true)}`
}
}
@ -207,7 +207,7 @@ const formatString = value =>
: `"${value}"`
export class GlobPattern extends Node {
constructor (value) {
constructor(value) {
// fallback to string node if no wildcard
if (value.indexOf('*') === -1) {
return new StringNode(value)
@ -232,7 +232,7 @@ export class GlobPattern extends Node {
})
}
match (re, value) {
match(re, value) {
if (typeof value === 'string') {
return re.test(value)
}
@ -244,13 +244,13 @@ export class GlobPattern extends Node {
return false
}
toString () {
toString() {
return this.value
}
}
export class RegExpNode extends Node {
constructor (pattern, flags) {
constructor(pattern, flags) {
super()
this.re = new RegExp(pattern, flags)
@ -261,7 +261,7 @@ export class RegExpNode extends Node {
})
}
match (value) {
match(value) {
if (typeof value === 'string') {
return this.re.test(value)
}
@ -273,14 +273,14 @@ export class RegExpNode extends Node {
return false
}
toString () {
toString() {
return this.re.toString()
}
}
export { RegExpNode as RegExp }
export class StringNode extends Node {
constructor (value) {
constructor(value) {
super()
this.value = value
@ -291,7 +291,7 @@ export class StringNode extends Node {
})
}
match (lcValue, value) {
match(lcValue, value) {
if (typeof value === 'string') {
return value.toLowerCase().indexOf(lcValue) !== -1
}
@ -303,24 +303,24 @@ export class StringNode extends Node {
return false
}
toString () {
toString() {
return formatString(this.value)
}
}
export { StringNode as String }
export class TruthyProperty extends Node {
constructor (name) {
constructor(name) {
super()
this.name = name
}
match (value) {
match(value) {
return value != null && !!value[this.name]
}
toString () {
toString() {
return formatString(this.name) + '?'
}
}
@ -330,12 +330,12 @@ export class TruthyProperty extends Node {
// https://gist.github.com/yelouafi/556e5159e869952335e01f6b473c4ec1
class Failure {
constructor (pos, expected) {
constructor(pos, expected) {
this.expected = expected
this.pos = pos
}
get value () {
get value() {
throw new Error(
`parse error: expected ${this.expected} at position ${this.pos}`
)
@ -343,7 +343,7 @@ class Failure {
}
class Success {
constructor (pos, value) {
constructor(pos, value) {
this.pos = pos
this.value = value
}
@ -352,7 +352,7 @@ class Success {
// -------------------------------------------------------------------
class P {
static alt (...parsers) {
static alt(...parsers) {
const { length } = parsers
return new P((input, pos, end) => {
for (let i = 0; i < length; ++i) {
@ -365,7 +365,7 @@ class P {
})
}
static grammar (rules) {
static grammar(rules) {
const grammar = {}
Object.keys(rules).forEach(k => {
const rule = rules[k]
@ -374,14 +374,14 @@ class P {
return grammar
}
static lazy (parserCreator, arg) {
static lazy(parserCreator, arg) {
const parser = new P((input, pos, end) =>
(parser._parse = parserCreator(arg)._parse)(input, pos, end)
)
return parser
}
static regex (regex) {
static regex(regex) {
regex = new RegExp(regex.source, 'y')
return new P((input, pos) => {
regex.lastIndex = pos
@ -392,7 +392,7 @@ class P {
})
}
static seq (...parsers) {
static seq(...parsers) {
const { length } = parsers
return new P((input, pos, end) => {
const values = new Array(length)
@ -408,7 +408,7 @@ class P {
})
}
static text (text) {
static text(text) {
const { length } = text
return new P((input, pos) =>
input.startsWith(text, pos)
@ -417,11 +417,11 @@ class P {
)
}
constructor (parse) {
constructor(parse) {
this._parse = parse
}
map (fn) {
map(fn) {
return new P((input, pos, end) => {
const result = this._parse(input, pos, end)
if (result instanceof Success) {
@ -431,11 +431,11 @@ class P {
})
}
parse (input, pos = 0, end = input.length) {
parse(input, pos = 0, end = input.length) {
return this._parse(input, pos, end).value
}
repeat (min = 0, max = Infinity) {
repeat(min = 0, max = Infinity) {
return new P((input, pos, end) => {
const value = []
let result
@ -461,7 +461,7 @@ class P {
})
}
skip (otherParser) {
skip(otherParser) {
return new P((input, pos, end) => {
const result = this._parse(input, pos, end)
if (result instanceof Failure) {

View File

@ -3,7 +3,7 @@ import { mergeVhd } from 'vhd-lib'
import { getHandler } from '@xen-orchestra/fs'
import { resolve } from 'path'
export default async function main (args) {
export default async function main(args) {
if (args.length < 2 || args.some(_ => _ === '-h' || _ === '--help')) {
return `Usage: ${this.command} <child VHD> <parent VHD>`
}
@ -11,7 +11,7 @@ export default async function main (args) {
const handler = getHandler({ url: 'file:///' })
let bar
await mergeVhd(handler, resolve(args[1]), handler, resolve(args[0]), {
onProgress ({ done, total }) {
onProgress({ done, total }) {
if (bar === undefined) {
bar = new Bar({
format:

View File

@ -3,7 +3,7 @@ import { createSyntheticStream } from 'vhd-lib'
import { createWriteStream } from 'fs'
import { getHandler } from '@xen-orchestra/fs'
export default async function main (args) {
export default async function main(args) {
if (args.length < 2 || args.some(_ => _ === '-h' || _ === '--help')) {
return `Usage: ${this.command} <input VHD> <output VHD>`
}

View File

@ -4,7 +4,7 @@ import execPromise from 'exec-promise'
import commands from './commands'
function runCommand (commands, [command, ...args]) {
function runCommand(commands, [command, ...args]) {
if (command === undefined || command === '-h' || command === '--help') {
command = 'help'
}

View File

@ -28,18 +28,18 @@ afterEach(async () => {
await pFromCallback(cb => rimraf(tmpDir, cb))
})
async function createRandomFile (name, sizeMb) {
async function createRandomFile(name, sizeMb) {
await execa('bash', [
'-c',
`< /dev/urandom tr -dc "\\t\\n [:alnum:]" | head -c ${sizeMb}M >${name}`,
])
}
async function checkFile (vhdName) {
async function checkFile(vhdName) {
await execa('vhd-util', ['check', '-p', '-b', '-t', '-n', vhdName])
}
async function recoverRawContent (vhdName, rawName, originalSize) {
async function recoverRawContent(vhdName, rawName, originalSize) {
await checkFile(vhdName)
await execa('qemu-img', ['convert', '-fvpc', '-Oraw', vhdName, rawName])
if (originalSize !== undefined) {
@ -47,7 +47,7 @@ async function recoverRawContent (vhdName, rawName, originalSize) {
}
}
async function convertFromRawToVhd (rawName, vhdName) {
async function convertFromRawToVhd(rawName, vhdName) {
await execa('qemu-img', ['convert', '-f', 'raw', '-Ovpc', rawName, vhdName])
}

View File

@ -1,6 +1,6 @@
import { SECTOR_SIZE } from './_constants'
export default function computeGeometryForSize (size) {
export default function computeGeometryForSize(size) {
const totalSectors = Math.min(Math.ceil(size / 512), 65535 * 16 * 255)
let sectorsPerTrackCylinder
let heads

View File

@ -14,7 +14,7 @@ import {
PLATFORM_WI2K,
} from './_constants'
export function createFooter (
export function createFooter(
size,
timestamp,
geometry,
@ -39,7 +39,7 @@ export function createFooter (
return footer
}
export function createHeader (
export function createHeader(
maxTableEntries,
tableOffset = HEADER_SIZE + FOOTER_SIZE,
blockSize = VHD_BLOCK_SIZE_BYTES

View File

@ -95,7 +95,7 @@ export const unpackField = (field, buf) => {
// Returns the checksum of a raw struct.
// The raw struct (footer or header) is altered with the new sum.
export function checksumStruct (buf, struct) {
export function checksumStruct(buf, struct) {
const checksumField = struct.fields.checksum
let sum = 0

View File

@ -3,7 +3,7 @@ import { dirname, relative } from 'path'
import Vhd from './vhd'
import { DISK_TYPE_DIFFERENCING } from './_constants'
export default async function chain (
export default async function chain(
parentHandler,
parentPath,
childHandler,

View File

@ -2,7 +2,7 @@ import asyncIteratorToStream from 'async-iterator-to-stream'
import Vhd from './vhd'
export default asyncIteratorToStream(async function * (handler, path) {
export default asyncIteratorToStream(async function*(handler, path) {
const fd = await handler.openFile(path, 'r')
try {
const vhd = new Vhd(handler, fd)

View File

@ -3,7 +3,7 @@ import asyncIteratorToStream from 'async-iterator-to-stream'
import computeGeometryForSize from './_computeGeometryForSize'
import { createFooter } from './_createFooterHeader'
export default asyncIteratorToStream(async function * (size, blockParser) {
export default asyncIteratorToStream(async function*(size, blockParser) {
const geometry = computeGeometryForSize(size)
const actualSize = geometry.actualSize
const footer = createFooter(
@ -13,7 +13,7 @@ export default asyncIteratorToStream(async function * (size, blockParser) {
)
let position = 0
function * filePadding (paddingLength) {
function* filePadding(paddingLength) {
if (paddingLength > 0) {
const chunkSize = 1024 * 1024 // 1Mo
for (
@ -33,10 +33,10 @@ export default asyncIteratorToStream(async function * (size, blockParser) {
if (paddingLength < 0) {
throw new Error('Received out of order blocks')
}
yield * filePadding(paddingLength)
yield* filePadding(paddingLength)
yield next.data
position = next.offsetBytes + next.data.length
}
yield * filePadding(actualSize - position)
yield* filePadding(actualSize - position)
yield footer
})

View File

@ -19,7 +19,7 @@ const VHD_BLOCK_SIZE_SECTORS = VHD_BLOCK_SIZE_BYTES / SECTOR_SIZE
/**
* @returns currentVhdPositionSector the first free sector after the data
*/
function createBAT (
function createBAT(
firstBlockPosition,
blockAddressList,
ratio,
@ -39,7 +39,7 @@ function createBAT (
return currentVhdPositionSector
}
export default async function createReadableStream (
export default async function createReadableStream(
diskSize,
incomingBlockSize,
blockAddressList,
@ -89,7 +89,7 @@ export default async function createReadableStream (
)
const fileSize = endOfData * SECTOR_SIZE + FOOTER_SIZE
let position = 0
function * yieldAndTrack (buffer, expectedPosition) {
function* yieldAndTrack(buffer, expectedPosition) {
if (expectedPosition !== undefined) {
assert.strictEqual(position, expectedPosition)
}
@ -98,7 +98,7 @@ export default async function createReadableStream (
position += buffer.length
}
}
async function * generateFileContent (blockIterator, bitmapSize, ratio) {
async function* generateFileContent(blockIterator, bitmapSize, ratio) {
let currentBlock = -1
let currentVhdBlockIndex = -1
let currentBlockWithBitmap = Buffer.alloc(0)
@ -108,7 +108,7 @@ export default async function createReadableStream (
const batIndex = Math.floor(next.offsetBytes / VHD_BLOCK_SIZE_BYTES)
if (batIndex !== currentVhdBlockIndex) {
if (currentVhdBlockIndex >= 0) {
yield * yieldAndTrack(
yield* yieldAndTrack(
currentBlockWithBitmap,
bat.readUInt32BE(currentVhdBlockIndex * 4) * SECTOR_SIZE
)
@ -126,15 +126,15 @@ export default async function createReadableStream (
bitmapSize + (next.offsetBytes % VHD_BLOCK_SIZE_BYTES)
)
}
yield * yieldAndTrack(currentBlockWithBitmap)
yield* yieldAndTrack(currentBlockWithBitmap)
}
async function * iterator () {
yield * yieldAndTrack(footer, 0)
yield * yieldAndTrack(header, FOOTER_SIZE)
yield * yieldAndTrack(bat, FOOTER_SIZE + HEADER_SIZE)
yield * generateFileContent(blockIterator, bitmapSize, ratio)
yield * yieldAndTrack(footer)
async function* iterator() {
yield* yieldAndTrack(footer, 0)
yield* yieldAndTrack(header, FOOTER_SIZE)
yield* yieldAndTrack(bat, FOOTER_SIZE + HEADER_SIZE)
yield* generateFileContent(blockIterator, bitmapSize, ratio)
yield* yieldAndTrack(footer)
}
const stream = asyncIteratorToStream(iterator())

View File

@ -15,7 +15,7 @@ import { test as mapTestBit } from './_bitmap'
const resolveRelativeFromFile = (file, path) =>
resolve('/', dirname(file), path).slice(1)
export default async function createSyntheticStream (handler, path) {
export default async function createSyntheticStream(handler, path) {
const fds = []
const cleanup = () => {
for (let i = 0, n = fds.length; i < n; ++i) {
@ -85,7 +85,7 @@ export default async function createSyntheticStream (handler, path) {
}
const fileSize = blockOffset * SECTOR_SIZE + FOOTER_SIZE
const iterator = function * () {
const iterator = function*() {
try {
footer = fuFooter.pack(footer)
checksumStruct(footer, fuFooter)
@ -108,14 +108,14 @@ export default async function createSyntheticStream (handler, path) {
yield bitmap
const blocksByVhd = new Map()
const emitBlockSectors = function * (iVhd, i, n) {
const emitBlockSectors = function*(iVhd, i, n) {
const vhd = vhds[iVhd]
const isRootVhd = vhd === rootVhd
if (!vhd.containsBlock(iBlock)) {
if (isRootVhd) {
yield Buffer.alloc((n - i) * SECTOR_SIZE)
} else {
yield * emitBlockSectors(iVhd + 1, i, n)
yield* emitBlockSectors(iVhd + 1, i, n)
}
return
}
@ -138,11 +138,11 @@ export default async function createSyntheticStream (handler, path) {
if (hasData) {
yield data.slice(start * SECTOR_SIZE, i * SECTOR_SIZE)
} else {
yield * emitBlockSectors(iVhd + 1, start, i)
yield* emitBlockSectors(iVhd + 1, start, i)
}
}
}
yield * emitBlockSectors(owner, 0, sectorsPerBlockData)
yield* emitBlockSectors(owner, 0, sectorsPerBlockData)
}
yield footer
} finally {

View File

@ -10,7 +10,7 @@ import { DISK_TYPE_DIFFERENCING, DISK_TYPE_DYNAMIC } from './_constants'
// Merge vhd child into vhd parent.
//
// TODO: rename the VHD file during the merge
export default concurrency(2)(async function merge (
export default concurrency(2)(async function merge(
parentHandler,
parentPath,
childHandler,

View File

@ -79,11 +79,11 @@ BUF_BLOCK_UNUSED.writeUInt32BE(BLOCK_UNUSED, 0)
// - sectorSize = 512
export default class Vhd {
get batSize () {
get batSize() {
return computeBatSize(this.header.maxTableEntries)
}
constructor (handler, path) {
constructor(handler, path) {
this._handler = handler
this._path = path
}
@ -92,7 +92,7 @@ export default class Vhd {
// Read functions.
// =================================================================
async _read (start, n) {
async _read(start, n) {
const { bytesRead, buffer } = await this._handler.read(
this._path,
Buffer.alloc(n),
@ -102,12 +102,12 @@ export default class Vhd {
return buffer
}
containsBlock (id) {
containsBlock(id) {
return this._getBatEntry(id) !== BLOCK_UNUSED
}
// Returns the first address after metadata. (In bytes)
getEndOfHeaders () {
getEndOfHeaders() {
const { header } = this
let end = FOOTER_SIZE + HEADER_SIZE
@ -132,7 +132,7 @@ export default class Vhd {
}
// Returns the first sector after data.
getEndOfData () {
getEndOfData() {
let end = Math.ceil(this.getEndOfHeaders() / SECTOR_SIZE)
const fullBlockSize = this.sectorsOfBitmap + this.sectorsPerBlock
@ -153,7 +153,7 @@ export default class Vhd {
// TODO: extract the checks into reusable functions:
// - better human reporting
// - auto repair if possible
async readHeaderAndFooter (checkSecondFooter = true) {
async readHeaderAndFooter(checkSecondFooter = true) {
const buf = await this._read(0, FOOTER_SIZE + HEADER_SIZE)
const bufFooter = buf.slice(0, FOOTER_SIZE)
const bufHeader = buf.slice(FOOTER_SIZE)
@ -206,7 +206,7 @@ export default class Vhd {
}
// Returns a buffer that contains the block allocation table of a vhd file.
async readBlockAllocationTable () {
async readBlockAllocationTable() {
const { header } = this
this.blockTable = await this._read(
header.tableOffset,
@ -215,11 +215,11 @@ export default class Vhd {
}
// return the first sector (bitmap) of a block
_getBatEntry (block) {
_getBatEntry(block) {
return this.blockTable.readUInt32BE(block * 4)
}
_readBlock (blockId, onlyBitmap = false) {
_readBlock(blockId, onlyBitmap = false) {
const blockAddr = this._getBatEntry(blockId)
if (blockAddr === BLOCK_UNUSED) {
throw new Error(`no such block ${blockId}`)
@ -243,7 +243,7 @@ export default class Vhd {
// get the identifiers and first sectors of the first and last block
// in the file
//
_getFirstAndLastBlocks () {
_getFirstAndLastBlocks() {
const n = this.header.maxTableEntries
const bat = this.blockTable
let i = 0
@ -288,7 +288,7 @@ export default class Vhd {
// =================================================================
// Write a buffer/stream at a given position in a vhd file.
async _write (data, offset) {
async _write(data, offset) {
debug(
`_write offset=${offset} size=${
Buffer.isBuffer(data) ? data.length : '???'
@ -307,7 +307,7 @@ export default class Vhd {
: fromEvent(data.pipe(stream), 'finish')
}
async _freeFirstBlockSpace (spaceNeededBytes) {
async _freeFirstBlockSpace(spaceNeededBytes) {
try {
const { first, firstSector, lastSector } = this._getFirstAndLastBlocks()
const tableOffset = this.header.tableOffset
@ -347,7 +347,7 @@ export default class Vhd {
}
}
async ensureBatSize (entries) {
async ensureBatSize(entries) {
const { header } = this
const prevMaxTableEntries = header.maxTableEntries
if (prevMaxTableEntries >= entries) {
@ -372,7 +372,7 @@ export default class Vhd {
}
// set the first sector (bitmap) of a block
_setBatEntry (block, blockSector) {
_setBatEntry(block, blockSector) {
const i = block * 4
const { blockTable } = this
@ -383,7 +383,7 @@ export default class Vhd {
// Make a new empty block at vhd end.
// Update block allocation table in context and in file.
async createBlock (blockId) {
async createBlock(blockId) {
const blockAddr = Math.ceil(this.getEndOfData() / SECTOR_SIZE)
debug(`create block ${blockId} at ${blockAddr}`)
@ -402,7 +402,7 @@ export default class Vhd {
}
// Write a bitmap at a block address.
async writeBlockBitmap (blockAddr, bitmap) {
async writeBlockBitmap(blockAddr, bitmap) {
const { bitmapSize } = this
if (bitmap.length !== bitmapSize) {
@ -419,7 +419,7 @@ export default class Vhd {
await this._write(bitmap, sectorsToBytes(blockAddr))
}
async writeEntireBlock (block) {
async writeEntireBlock(block) {
let blockAddr = this._getBatEntry(block.id)
if (blockAddr === BLOCK_UNUSED) {
@ -428,7 +428,7 @@ export default class Vhd {
await this._write(block.buffer, sectorsToBytes(blockAddr))
}
async writeBlockSectors (block, beginSectorId, endSectorId, parentBitmap) {
async writeBlockSectors(block, beginSectorId, endSectorId, parentBitmap) {
let blockAddr = this._getBatEntry(block.id)
if (blockAddr === BLOCK_UNUSED) {
@ -460,7 +460,7 @@ export default class Vhd {
)
}
async coalesceBlock (child, blockId) {
async coalesceBlock(child, blockId) {
const block = await child._readBlock(blockId)
const { bitmap, data } = block
@ -502,7 +502,7 @@ export default class Vhd {
}
// Write a context footer. (At the end and beginning of a vhd file.)
async writeFooter (onlyEndFooter = false) {
async writeFooter(onlyEndFooter = false) {
const { footer } = this
const rawFooter = fuFooter.pack(footer)
@ -522,7 +522,7 @@ export default class Vhd {
await this._write(rawFooter, offset)
}
writeHeader () {
writeHeader() {
const { header } = this
const rawHeader = fuHeader.pack(header)
header.checksum = checksumStruct(rawHeader, fuHeader)
@ -535,7 +535,7 @@ export default class Vhd {
return this._write(rawHeader, offset)
}
async writeData (offsetSectors, buffer) {
async writeData(offsetSectors, buffer) {
const bufferSizeSectors = Math.ceil(buffer.length / SECTOR_SIZE)
const startBlock = Math.floor(offsetSectors / this.sectorsPerBlock)
const endBufferSectors = offsetSectors + bufferSizeSectors
@ -588,7 +588,7 @@ export default class Vhd {
await this.writeFooter()
}
async ensureSpaceForParentLocators (neededSectors) {
async ensureSpaceForParentLocators(neededSectors) {
const firstLocatorOffset = FOOTER_SIZE + HEADER_SIZE
const currentSpace =
Math.floor(this.header.tableOffset / SECTOR_SIZE) -
@ -602,7 +602,7 @@ export default class Vhd {
return firstLocatorOffset
}
async setUniqueParentLocator (fileNameString) {
async setUniqueParentLocator(fileNameString) {
const { header } = this
header.parentLocatorEntry[0].platformCode = PLATFORM_W2KU
const encodedFilename = Buffer.from(fileNameString, 'utf16le')

View File

@ -49,7 +49,7 @@ const getStyle = vdi => {
}
const mapFilter = (collection, iteratee, results = []) => {
forEach(collection, function () {
forEach(collection, function() {
const result = iteratee.apply(this, arguments)
if (result !== undefined) {
results.push(result)

View File

@ -1,7 +1,7 @@
import mapValues from 'lodash/mapValues'
export default function replaceSensitiveValues (value, replacement) {
function helper (value, name) {
export default function replaceSensitiveValues(value, replacement) {
function helper(value, name) {
if (name === 'password' && typeof value === 'string') {
return replacement
}

View File

@ -15,7 +15,7 @@ import { createClient } from './'
// ===================================================================
function askPassword (prompt = 'Password: ') {
function askPassword(prompt = 'Password: ') {
if (prompt) {
process.stdout.write(prompt)
}

View File

@ -10,7 +10,7 @@ export default opts => {
let i = 0
let call
function create () {
function create() {
const current = factories[i++](opts)
if (i < length) {
const currentI = i

View File

@ -19,36 +19,36 @@ const configFile = configPath + '/config.json'
// ===================================================================
const load = (exports.load = function () {
const load = (exports.load = function() {
return readFile(configFile)
.then(JSON.parse)
.catch(function () {
.catch(function() {
return {}
})
})
exports.get = function (path) {
return load().then(function (config) {
exports.get = function(path) {
return load().then(function(config) {
return l33t(config).tap(path)
})
}
const save = (exports.save = function (config) {
return mkdirp(configPath).then(function () {
const save = (exports.save = function(config) {
return mkdirp(configPath).then(function() {
return writeFile(configFile, JSON.stringify(config))
})
})
exports.set = function (data) {
return load().then(function (config) {
exports.set = function(data) {
return load().then(function(config) {
return save(assign(config, data))
})
}
exports.unset = function (paths) {
return load().then(function (config) {
exports.unset = function(paths) {
return load().then(function(config) {
const l33tConfig = l33t(config)
;[].concat(paths).forEach(function (path) {
;[].concat(paths).forEach(function(path) {
l33tConfig.purge(path, true)
})
return save(config)

View File

@ -36,7 +36,7 @@ const config = require('./config')
// ===================================================================
async function connect () {
async function connect() {
const { server, token } = await config.load()
if (server === undefined) {
throw new Error('no server to connect to!')
@ -53,7 +53,7 @@ async function connect () {
}
const FLAG_RE = /^--([^=]+)(?:=([^]*))?$/
function extractFlags (args) {
function extractFlags(args) {
const flags = {}
let i = 0
@ -71,9 +71,9 @@ function extractFlags (args) {
}
const PARAM_RE = /^([^=]+)=([^]*)$/
function parseParameters (args) {
function parseParameters(args) {
const params = {}
forEach(args, function (arg) {
forEach(args, function(arg) {
let matches
if (!(matches = arg.match(PARAM_RE))) {
throw new Error('invalid arg: ' + arg)
@ -107,7 +107,7 @@ const humanFormatOpts = {
scale: 'binary',
}
function printProgress (progress) {
function printProgress(progress) {
if (progress.length) {
console.warn(
'%s% of %s @ %s/s - ETA %s',
@ -125,8 +125,8 @@ function printProgress (progress) {
}
}
function wrap (val) {
return function wrappedValue () {
function wrap(val) {
return function wrappedValue() {
return val
}
}
@ -134,7 +134,7 @@ function wrap (val) {
// ===================================================================
const help = wrap(
(function (pkg) {
(function(pkg) {
return require('strip-indent')(
`
Usage:
@ -168,7 +168,7 @@ const help = wrap(
$name v$version
`
).replace(/<([^>]+)>|\$(\w+)/g, function (_, arg, key) {
).replace(/<([^>]+)>|\$(\w+)/g, function(_, arg, key) {
if (arg) {
return '<' + chalk.yellow(arg) + '>'
}
@ -184,12 +184,12 @@ const help = wrap(
// -------------------------------------------------------------------
function main (args) {
function main(args) {
if (!args || !args.length || args[0] === '-h') {
return help()
}
const fnName = args[0].replace(/^--|-\w/g, function (match) {
const fnName = args[0].replace(/^--|-\w/g, function(match) {
if (match === '--') {
return ''
}
@ -208,7 +208,7 @@ exports = module.exports = main
exports.help = help
async function register (args) {
async function register(args) {
let expiresIn
if (args[0] === '--expiresIn') {
expiresIn = args[1]
@ -218,7 +218,7 @@ async function register (args) {
const [
url,
email,
password = await new Promise(function (resolve) {
password = await new Promise(function(resolve) {
process.stdout.write('Password: ')
pw(resolve)
}),
@ -236,18 +236,18 @@ async function register (args) {
}
exports.register = register
function unregister () {
function unregister() {
return config.unset(['server', 'token'])
}
exports.unregister = unregister
async function listCommands (args) {
async function listCommands(args) {
const xo = await connect()
let methods = await xo.call('system.getMethodsInfo')
let json = false
const patterns = []
forEach(args, function (arg) {
forEach(args, function(arg) {
if (arg === '--json') {
json = true
} else {
@ -264,7 +264,7 @@ async function listCommands (args) {
}
methods = pairs(methods)
methods.sort(function (a, b) {
methods.sort(function(a, b) {
a = a[0]
b = b[0]
if (a < b) {
@ -274,11 +274,11 @@ async function listCommands (args) {
})
const str = []
forEach(methods, function (method) {
forEach(methods, function(method) {
const name = method[0]
const info = method[1]
str.push(chalk.bold.blue(name))
forEach(info.params || [], function (info, name) {
forEach(info.params || [], function(info, name) {
str.push(' ')
if (info.optional) {
str.push('[')
@ -305,10 +305,10 @@ async function listCommands (args) {
}
exports.listCommands = listCommands
async function listObjects (args) {
async function listObjects(args) {
const properties = getKeys(extractFlags(args))
const filterProperties = properties.length
? function (object) {
? function(object) {
return pick(object, properties)
}
: identity
@ -321,7 +321,7 @@ async function listObjects (args) {
const stdout = process.stdout
stdout.write('[\n')
const keys = Object.keys(objects)
for (let i = 0, n = keys.length; i < n;) {
for (let i = 0, n = keys.length; i < n; ) {
stdout.write(JSON.stringify(filterProperties(objects[keys[i]]), null, 2))
stdout.write(++i < n ? ',\n' : '\n')
}
@ -329,7 +329,7 @@ async function listObjects (args) {
}
exports.listObjects = listObjects
function ensurePathParam (method, value) {
function ensurePathParam(method, value) {
if (typeof value !== 'string') {
const error =
method +
@ -338,7 +338,7 @@ function ensurePathParam (method, value) {
}
}
async function call (args) {
async function call(args) {
if (!args.length) {
throw new Error('missing command name')
}

View File

@ -1,4 +1,4 @@
export default function clearObject (object) {
export default function clearObject(object) {
for (const key in object) {
delete object[key]
}

View File

@ -20,43 +20,43 @@ export const ACTION_REMOVE = 'remove'
// ===================================================================
export class BufferAlreadyFlushed extends BaseError {
constructor () {
constructor() {
super('buffer flush already requested')
}
}
export class DuplicateIndex extends BaseError {
constructor (name) {
constructor(name) {
super('there is already an index with the name ' + name)
}
}
export class DuplicateItem extends BaseError {
constructor (key) {
constructor(key) {
super('there is already a item with the key ' + key)
}
}
export class IllegalTouch extends BaseError {
constructor (value) {
constructor(value) {
super('only an object value can be touched (found a ' + kindOf(value) + ')')
}
}
export class InvalidKey extends BaseError {
constructor (key) {
constructor(key) {
super('invalid key of type ' + kindOf(key))
}
}
export class NoSuchIndex extends BaseError {
constructor (name) {
constructor(name) {
super('there is no index with the name ' + name)
}
}
export class NoSuchItem extends BaseError {
constructor (key) {
constructor(key) {
super('there is no item with the key ' + key)
}
}
@ -64,7 +64,7 @@ export class NoSuchItem extends BaseError {
// -------------------------------------------------------------------
export default class Collection extends EventEmitter {
constructor () {
constructor() {
super()
this._buffer = createObject(null)
@ -79,7 +79,7 @@ export default class Collection extends EventEmitter {
// unspecified.
//
// Default implementation returns the `id` property.
getKey (value) {
getKey(value) {
return value && value.id
}
@ -87,15 +87,15 @@ export default class Collection extends EventEmitter {
// Properties
// -----------------------------------------------------------------
get all () {
get all() {
return this._items
}
get indexes () {
get indexes() {
return this._indexedItems
}
get size () {
get size() {
return this._size
}
@ -103,7 +103,7 @@ export default class Collection extends EventEmitter {
// Manipulation
// -----------------------------------------------------------------
add (keyOrObjectWithId, valueIfKey = undefined) {
add(keyOrObjectWithId, valueIfKey = undefined) {
const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey)
this._assertHasNot(key)
@ -112,18 +112,18 @@ export default class Collection extends EventEmitter {
this._touch(ACTION_ADD, key)
}
clear () {
clear() {
forEach(this._items, (_, key) => this._remove(key))
}
remove (keyOrObjectWithId) {
remove(keyOrObjectWithId) {
const [key] = this._resolveItem(keyOrObjectWithId)
this._assertHas(key)
this._remove(key)
}
set (keyOrObjectWithId, valueIfKey = undefined) {
set(keyOrObjectWithId, valueIfKey = undefined) {
const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey)
const action = this.has(key) ? ACTION_UPDATE : ACTION_ADD
@ -134,7 +134,7 @@ export default class Collection extends EventEmitter {
this._touch(action, key)
}
touch (keyOrObjectWithId) {
touch(keyOrObjectWithId) {
const [key] = this._resolveItem(keyOrObjectWithId)
this._assertHas(key)
const value = this.get(key)
@ -147,7 +147,7 @@ export default class Collection extends EventEmitter {
return this.get(key)
}
unset (keyOrObjectWithId) {
unset(keyOrObjectWithId) {
const [key] = this._resolveItem(keyOrObjectWithId)
if (this.has(key)) {
@ -155,7 +155,7 @@ export default class Collection extends EventEmitter {
}
}
update (keyOrObjectWithId, valueIfKey = undefined) {
update(keyOrObjectWithId, valueIfKey = undefined) {
const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey)
this._assertHas(key)
@ -167,7 +167,7 @@ export default class Collection extends EventEmitter {
// Query
// -----------------------------------------------------------------
get (key, defaultValue) {
get(key, defaultValue) {
if (this.has(key)) {
return this._items[key]
}
@ -180,7 +180,7 @@ export default class Collection extends EventEmitter {
this._assertHas(key)
}
has (key) {
has(key) {
return hasOwnProperty.call(this._items, key)
}
@ -188,7 +188,7 @@ export default class Collection extends EventEmitter {
// Indexes
// -----------------------------------------------------------------
createIndex (name, index) {
createIndex(name, index) {
const { _indexes: indexes } = this
if (hasOwnProperty.call(indexes, name)) {
throw new DuplicateIndex(name)
@ -200,7 +200,7 @@ export default class Collection extends EventEmitter {
index._attachCollection(this)
}
deleteIndex (name) {
deleteIndex(name) {
const { _indexes: indexes } = this
if (!hasOwnProperty.call(indexes, name)) {
throw new NoSuchIndex(name)
@ -217,7 +217,7 @@ export default class Collection extends EventEmitter {
// Iteration
// -----------------------------------------------------------------
* [Symbol.iterator] () {
*[Symbol.iterator]() {
const { _items: items } = this
for (const key in items) {
@ -225,7 +225,7 @@ export default class Collection extends EventEmitter {
}
}
* keys () {
*keys() {
const { _items: items } = this
for (const key in items) {
@ -233,7 +233,7 @@ export default class Collection extends EventEmitter {
}
}
* values () {
*values() {
const { _items: items } = this
for (const key in items) {
@ -245,7 +245,7 @@ export default class Collection extends EventEmitter {
// Events buffering
// -----------------------------------------------------------------
bufferEvents () {
bufferEvents() {
++this._buffering
let called = false
@ -294,35 +294,35 @@ export default class Collection extends EventEmitter {
// =================================================================
_assertHas (key) {
_assertHas(key) {
if (!this.has(key)) {
throw new NoSuchItem(key)
}
}
_assertHasNot (key) {
_assertHasNot(key) {
if (this.has(key)) {
throw new DuplicateItem(key)
}
}
_assertValidKey (key) {
_assertValidKey(key) {
if (!this._isValidKey(key)) {
throw new InvalidKey(key)
}
}
_isValidKey (key) {
_isValidKey(key) {
return typeof key === 'number' || typeof key === 'string'
}
_remove (key) {
_remove(key) {
delete this._items[key]
this._size--
this._touch(ACTION_REMOVE, key)
}
_resolveItem (keyOrObjectWithId, valueIfKey = undefined) {
_resolveItem(keyOrObjectWithId, valueIfKey = undefined) {
if (valueIfKey !== undefined) {
this._assertValidKey(keyOrObjectWithId)
@ -339,7 +339,7 @@ export default class Collection extends EventEmitter {
return [key, keyOrObjectWithId]
}
_touch (action, key) {
_touch(action, key) {
if (this._buffering === 0) {
const flush = this.bufferEvents()

View File

@ -7,11 +7,11 @@ import Collection, { DuplicateItem, NoSuchItem } from './collection'
// ===================================================================
function waitTicks (n = 2) {
function waitTicks(n = 2) {
const { nextTick } = process
return new Promise(function (resolve) {
;(function waitNextTick () {
return new Promise(function(resolve) {
;(function waitNextTick() {
// The first tick is handled by Promise#then()
if (--n) {
nextTick(waitNextTick)
@ -22,24 +22,24 @@ function waitTicks (n = 2) {
})
}
describe('Collection', function () {
describe('Collection', function() {
let col
beforeEach(function () {
beforeEach(function() {
col = new Collection()
col.add('bar', 0)
return waitTicks()
})
it('is iterable', function () {
it('is iterable', function() {
const iterator = col[Symbol.iterator]()
expect(iterator.next()).toEqual({ done: false, value: ['bar', 0] })
expect(iterator.next()).toEqual({ done: true, value: undefined })
})
describe('#keys()', function () {
it('returns an iterator over the keys', function () {
describe('#keys()', function() {
it('returns an iterator over the keys', function() {
const iterator = col.keys()
expect(iterator.next()).toEqual({ done: false, value: 'bar' })
@ -47,8 +47,8 @@ describe('Collection', function () {
})
})
describe('#values()', function () {
it('returns an iterator over the values', function () {
describe('#values()', function() {
it('returns an iterator over the values', function() {
const iterator = col.values()
expect(iterator.next()).toEqual({ done: false, value: 0 })
@ -56,8 +56,8 @@ describe('Collection', function () {
})
})
describe('#add()', function () {
it('adds item to the collection', function () {
describe('#add()', function() {
it('adds item to the collection', function() {
const spy = jest.fn()
col.on('add', spy)
@ -69,17 +69,17 @@ describe('Collection', function () {
expect(spy).not.toHaveBeenCalled()
// Async event.
return eventToPromise(col, 'add').then(function (added) {
return eventToPromise(col, 'add').then(function(added) {
expect(Object.keys(added)).toEqual(['foo'])
expect(added.foo).toBe(true)
})
})
it('throws an exception if the item already exists', function () {
it('throws an exception if the item already exists', function() {
expect(() => col.add('bar', true)).toThrowError(DuplicateItem)
})
it('accepts an object with an id property', function () {
it('accepts an object with an id property', function() {
const foo = { id: 'foo' }
col.add(foo)
@ -88,8 +88,8 @@ describe('Collection', function () {
})
})
describe('#update()', function () {
it('updates an item of the collection', function () {
describe('#update()', function() {
it('updates an item of the collection', function() {
const spy = jest.fn()
col.on('update', spy)
@ -102,17 +102,17 @@ describe('Collection', function () {
expect(spy).not.toHaveBeenCalled()
// Async event.
return eventToPromise(col, 'update').then(function (updated) {
return eventToPromise(col, 'update').then(function(updated) {
expect(Object.keys(updated)).toEqual(['bar'])
expect(updated.bar).toBe(2)
})
})
it('throws an exception if the item does not exist', function () {
it('throws an exception if the item does not exist', function() {
expect(() => col.update('baz', true)).toThrowError(NoSuchItem)
})
it('accepts an object with an id property', function () {
it('accepts an object with an id property', function() {
const bar = { id: 'bar' }
col.update(bar)
@ -121,8 +121,8 @@ describe('Collection', function () {
})
})
describe('#remove()', function () {
it('removes an item of the collection', function () {
describe('#remove()', function() {
it('removes an item of the collection', function() {
const spy = jest.fn()
col.on('remove', spy)
@ -134,17 +134,17 @@ describe('Collection', function () {
expect(spy).not.toHaveBeenCalled()
// Async event.
return eventToPromise(col, 'remove').then(function (removed) {
return eventToPromise(col, 'remove').then(function(removed) {
expect(Object.keys(removed)).toEqual(['bar'])
expect(removed.bar).toBeUndefined()
})
})
it('throws an exception if the item does not exist', function () {
it('throws an exception if the item does not exist', function() {
expect(() => col.remove('baz', true)).toThrowError(NoSuchItem)
})
it('accepts an object with an id property', function () {
it('accepts an object with an id property', function() {
const bar = { id: 'bar' }
col.remove(bar)
@ -153,8 +153,8 @@ describe('Collection', function () {
})
})
describe('#set()', function () {
it('adds item if collection has not key', function () {
describe('#set()', function() {
it('adds item if collection has not key', function() {
const spy = jest.fn()
col.on('add', spy)
@ -166,13 +166,13 @@ describe('Collection', function () {
expect(spy).not.toHaveBeenCalled()
// Async events.
return eventToPromise(col, 'add').then(function (added) {
return eventToPromise(col, 'add').then(function(added) {
expect(Object.keys(added)).toEqual(['foo'])
expect(added.foo).toBe(true)
})
})
it('updates item if collection has key', function () {
it('updates item if collection has key', function() {
const spy = jest.fn()
col.on('udpate', spy)
@ -184,13 +184,13 @@ describe('Collection', function () {
expect(spy).not.toHaveBeenCalled()
// Async events.
return eventToPromise(col, 'update').then(function (updated) {
return eventToPromise(col, 'update').then(function(updated) {
expect(Object.keys(updated)).toEqual(['bar'])
expect(updated.bar).toBe(1)
})
})
it('accepts an object with an id property', function () {
it('accepts an object with an id property', function() {
const foo = { id: 'foo' }
col.set(foo)
@ -199,36 +199,36 @@ describe('Collection', function () {
})
})
describe('#unset()', function () {
it('removes an existing item', function () {
describe('#unset()', function() {
it('removes an existing item', function() {
col.unset('bar')
expect(col.has('bar')).toBe(false)
return eventToPromise(col, 'remove').then(function (removed) {
return eventToPromise(col, 'remove').then(function(removed) {
expect(Object.keys(removed)).toEqual(['bar'])
expect(removed.bar).toBeUndefined()
})
})
it('does not throw if the item does not exists', function () {
it('does not throw if the item does not exists', function() {
col.unset('foo')
})
it('accepts an object with an id property', function () {
it('accepts an object with an id property', function() {
col.unset({ id: 'bar' })
expect(col.has('bar')).toBe(false)
return eventToPromise(col, 'remove').then(function (removed) {
return eventToPromise(col, 'remove').then(function(removed) {
expect(Object.keys(removed)).toEqual(['bar'])
expect(removed.bar).toBeUndefined()
})
})
})
describe('touch()', function () {
it('can be used to signal an indirect update', function () {
describe('touch()', function() {
it('can be used to signal an indirect update', function() {
const foo = { id: 'foo' }
col.add(foo)
@ -243,8 +243,8 @@ describe('Collection', function () {
})
})
describe('clear()', function () {
it('removes all items from the collection', function () {
describe('clear()', function() {
it('removes all items from the collection', function() {
col.clear()
expect(col.size).toBe(0)
@ -256,7 +256,7 @@ describe('Collection', function () {
})
})
describe('deduplicates events', function () {
describe('deduplicates events', function() {
forEach(
{
'add & update → add': [
@ -298,7 +298,7 @@ describe('Collection', function () {
],
},
([operations, results], label) => {
it(label, function () {
it(label, function() {
forEach(operations, ([method, ...args]) => {
col[method](...args)
})

View File

@ -8,7 +8,7 @@ import { ACTION_ADD, ACTION_UPDATE, ACTION_REMOVE } from './collection'
// ===================================================================
export default class Index {
constructor (computeHash) {
constructor(computeHash) {
if (computeHash) {
this.computeHash = iteratee(computeHash)
}
@ -24,12 +24,12 @@ export default class Index {
// This method is used to compute the hash under which an item must
// be saved.
computeHash (value, key) {
computeHash(value, key) {
throw new NotImplemented('this method must be overridden')
}
// Remove empty items lists.
sweep () {
sweep() {
const { _itemsByHash: itemsByHash } = this
for (const hash in itemsByHash) {
if (isEmpty(itemsByHash[hash])) {
@ -40,13 +40,13 @@ export default class Index {
// -----------------------------------------------------------------
get items () {
get items() {
return this._itemsByHash
}
// -----------------------------------------------------------------
_attachCollection (collection) {
_attachCollection(collection) {
// Add existing entries.
//
// FIXME: I think there may be a race condition if the `add` event
@ -58,7 +58,7 @@ export default class Index {
collection.on(ACTION_REMOVE, this._onRemove)
}
_detachCollection (collection) {
_detachCollection(collection) {
collection.removeListener(ACTION_ADD, this._onAdd)
collection.removeListener(ACTION_UPDATE, this._onUpdate)
collection.removeListener(ACTION_REMOVE, this._onRemove)
@ -69,7 +69,7 @@ export default class Index {
// -----------------------------------------------------------------
_onAdd (items) {
_onAdd(items) {
const {
computeHash,
_itemsByHash: itemsByHash,
@ -93,7 +93,7 @@ export default class Index {
}
}
_onUpdate (items) {
_onUpdate(items) {
const {
computeHash,
_itemsByHash: itemsByHash,
@ -122,7 +122,7 @@ export default class Index {
}
}
_onRemove (items) {
_onRemove(items) {
const { _itemsByHash: itemsByHash, _keysToHash: keysToHash } = this
for (const key in items) {

View File

@ -12,7 +12,7 @@ const waitTicks = (n = 2) => {
const { nextTick } = process
return new Promise(resolve => {
;(function waitNextTick () {
;(function waitNextTick() {
// The first tick is handled by Promise#then()
if (--n) {
nextTick(waitNextTick)
@ -25,7 +25,7 @@ const waitTicks = (n = 2) => {
// ===================================================================
describe('Index', function () {
describe('Index', function() {
let col, byGroup
const item1 = {
id: '2ccb8a72-dc65-48e4-88fe-45ef541f2cba',
@ -43,7 +43,7 @@ describe('Index', function () {
id: 'd90b7335-e540-4a44-ad22-c4baae9cd0a9',
}
beforeEach(function () {
beforeEach(function() {
col = new Collection()
forEach([item1, item2, item3, item4], item => {
col.add(item)
@ -56,7 +56,7 @@ describe('Index', function () {
return waitTicks()
})
it('works with existing items', function () {
it('works with existing items', function() {
expect(col.indexes).toEqual({
byGroup: {
foo: {
@ -70,7 +70,7 @@ describe('Index', function () {
})
})
it('works with added items', function () {
it('works with added items', function() {
const item5 = {
id: '823b56c4-4b96-4f3a-9533-5d08177167ac',
group: 'baz',
@ -96,7 +96,7 @@ describe('Index', function () {
})
})
it('works with updated items', function () {
it('works with updated items', function() {
const item1bis = {
id: item1.id,
group: 'bar',
@ -119,7 +119,7 @@ describe('Index', function () {
})
})
it('works with removed items', function () {
it('works with removed items', function() {
col.remove(item2)
return waitTicks().then(() => {
@ -135,7 +135,7 @@ describe('Index', function () {
})
})
it('correctly updates the value even the same object has the same hash', function () {
it('correctly updates the value even the same object has the same hash', function() {
const item1bis = {
id: item1.id,
group: item1.group,
@ -159,8 +159,8 @@ describe('Index', function () {
})
})
describe('#sweep()', function () {
it('removes empty items lists', function () {
describe('#sweep()', function() {
it('removes empty items lists', function() {
col.remove(item2)
return waitTicks().then(() => {

View File

@ -1,4 +1,4 @@
export default function isEmpty (object) {
export default function isEmpty(object) {
/* eslint no-unused-vars: 0 */
for (const key in object) {
return false

View File

@ -1,3 +1,3 @@
export default function isObject (value) {
export default function isObject(value) {
return value !== null && typeof value === 'object'
}

View File

@ -1,7 +1,7 @@
import { BaseError } from 'make-error'
export default class NotImplemented extends BaseError {
constructor (message) {
constructor(message) {
super(message || 'this method is not implemented')
}
}

View File

@ -7,7 +7,7 @@ import { ACTION_ADD, ACTION_UPDATE, ACTION_REMOVE } from './collection'
// ===================================================================
export default class UniqueIndex {
constructor (computeHash) {
constructor(computeHash) {
if (computeHash) {
this.computeHash = iteratee(computeHash)
}
@ -23,19 +23,19 @@ export default class UniqueIndex {
// This method is used to compute the hash under which an item must
// be saved.
computeHash (value, key) {
computeHash(value, key) {
throw new NotImplemented('this method must be overridden')
}
// -----------------------------------------------------------------
get items () {
get items() {
return this._itemByHash
}
// -----------------------------------------------------------------
_attachCollection (collection) {
_attachCollection(collection) {
// Add existing entries.
//
// FIXME: I think there may be a race condition if the `add` event
@ -47,7 +47,7 @@ export default class UniqueIndex {
collection.on(ACTION_REMOVE, this._onRemove)
}
_detachCollection (collection) {
_detachCollection(collection) {
collection.removeListener(ACTION_ADD, this._onAdd)
collection.removeListener(ACTION_UPDATE, this._onUpdate)
collection.removeListener(ACTION_REMOVE, this._onRemove)
@ -58,7 +58,7 @@ export default class UniqueIndex {
// -----------------------------------------------------------------
_onAdd (items) {
_onAdd(items) {
const {
computeHash,
_itemByHash: itemByHash,
@ -77,7 +77,7 @@ export default class UniqueIndex {
}
}
_onUpdate (items) {
_onUpdate(items) {
const {
computeHash,
_itemByHash: itemByHash,
@ -103,7 +103,7 @@ export default class UniqueIndex {
}
}
_onRemove (items) {
_onRemove(items) {
const { _itemByHash: itemByHash, _keysToHash: keysToHash } = this
for (const key in items) {

View File

@ -12,7 +12,7 @@ const waitTicks = (n = 2) => {
const { nextTick } = process
return new Promise(resolve => {
;(function waitNextTick () {
;(function waitNextTick() {
// The first tick is handled by Promise#then()
if (--n) {
nextTick(waitNextTick)
@ -25,7 +25,7 @@ const waitTicks = (n = 2) => {
// ===================================================================
describe('UniqueIndex', function () {
describe('UniqueIndex', function() {
let col, byKey
const item1 = {
id: '2ccb8a72-dc65-48e4-88fe-45ef541f2cba',
@ -39,7 +39,7 @@ describe('UniqueIndex', function () {
id: '668c1274-4442-44a6-b99a-512188e0bb09',
}
beforeEach(function () {
beforeEach(function() {
col = new Collection()
forEach([item1, item2, item3], item => {
col.add(item)
@ -52,7 +52,7 @@ describe('UniqueIndex', function () {
return waitTicks()
})
it('works with existing items', function () {
it('works with existing items', function() {
expect(col.indexes).toEqual({
byKey: {
[item1.key]: item1,
@ -61,7 +61,7 @@ describe('UniqueIndex', function () {
})
})
it('works with added items', function () {
it('works with added items', function() {
const item4 = {
id: '823b56c4-4b96-4f3a-9533-5d08177167ac',
key: '1437af14-429a-40db-8a51-8a2f5ed03201',
@ -80,7 +80,7 @@ describe('UniqueIndex', function () {
})
})
it('works with updated items', function () {
it('works with updated items', function() {
const item1bis = {
id: item1.id,
key: 'e03d4a3a-0331-4aca-97a2-016bbd43a29b',
@ -98,7 +98,7 @@ describe('UniqueIndex', function () {
})
})
it('works with removed items', function () {
it('works with removed items', function() {
col.remove(item2)
return waitTicks().then(() => {
@ -110,7 +110,7 @@ describe('UniqueIndex', function () {
})
})
it('correctly updates the value even the same object has the same hash', function () {
it('correctly updates the value even the same object has the same hash', function() {
const item1bis = {
id: item1.id,
key: item1.key,

View File

@ -43,7 +43,7 @@ activeUsers.on('remove', users => {
})
// Make some changes in the future.
setTimeout(function () {
setTimeout(function() {
console.log('-----')
users.set({

View File

@ -9,7 +9,7 @@ import Collection, {
// ===================================================================
export default class View extends Collection {
constructor (collection, predicate) {
constructor(collection, predicate) {
super()
this._collection = collection
@ -31,29 +31,29 @@ export default class View extends Collection {
// This method is necessary to free the memory of the view if its
// life span is shorter than the collection.
destroy () {
destroy() {
this._collection.removeListener(ACTION_ADD, this._onAdd)
this._collection.removeListener(ACTION_UPDATE, this._onUpdate)
this._collection.removeListener(ACTION_REMOVE, this._onRemove)
}
add () {
add() {
throw new Error('a view is read only')
}
clear () {
clear() {
throw new Error('a view is read only')
}
set () {
set() {
throw new Error('a view is read only')
}
update () {
update() {
throw new Error('a view is read only')
}
_onAdd (items) {
_onAdd(items) {
const { _predicate: predicate } = this
forEach(items, (value, key) => {
@ -66,7 +66,7 @@ export default class View extends Collection {
})
}
_onUpdate (items) {
_onUpdate(items) {
const { _predicate: predicate } = this
forEach(items, (value, key) => {
@ -78,7 +78,7 @@ export default class View extends Collection {
})
}
_onRemove (items) {
_onRemove(items) {
forEach(items, (value, key) => {
if (super.has(key)) {
super.remove(key)

View File

@ -2,13 +2,13 @@ import { BaseError } from 'make-error'
import { isArray, iteratee } from 'lodash'
class XoError extends BaseError {
constructor ({ code, message, data }) {
constructor({ code, message, data }) {
super(message)
this.code = code
this.data = data
}
toJsonRpcError () {
toJsonRpcError() {
return {
message: this.message,
code: this.code,

View File

@ -1,6 +1,6 @@
'use strict'
process.on('unhandledRejection', function (error) {
process.on('unhandledRejection', function(error) {
console.log(error)
})
@ -11,51 +11,51 @@ const xo = new Xo({
})
xo.open()
.then(function () {
.then(function() {
return xo
.call('acl.get', {})
.then(function (result) {
.then(function(result) {
console.log('success:', result)
})
.catch(function (error) {
.catch(function(error) {
console.log('failure:', error)
})
})
.then(function () {
.then(function() {
return xo
.signIn({
email: 'admin@admin.net',
password: 'admin',
})
.then(function () {
.then(function() {
console.log('connected as ', xo.user)
})
.catch(function (error) {
.catch(function(error) {
console.log('failure:', error)
})
})
.then(function () {
.then(function() {
return xo
.signIn({
email: 'tom',
password: 'tom',
})
.then(function () {
.then(function() {
console.log('connected as', xo.user)
return xo
.call('acl.get', {})
.then(function (result) {
.then(function(result) {
console.log('success:', result)
})
.catch(function (error) {
.catch(function(error) {
console.log('failure:', error)
})
})
.catch(function (error) {
.catch(function(error) {
console.log('failure', error)
})
})
.then(function () {
.then(function() {
return xo.close()
})

View File

@ -13,7 +13,7 @@ export class XoError extends BaseError {}
// -------------------------------------------------------------------
export default class Xo extends JsonRpcWebSocketClient {
constructor (opts) {
constructor(opts) {
const url = opts != null ? opts.url : '.'
super(`${url === '/' ? '' : url}/api/`)
@ -30,11 +30,11 @@ export default class Xo extends JsonRpcWebSocketClient {
})
}
get user () {
get user() {
return this._user
}
call (method, args, i) {
call(method, args, i) {
if (startsWith(method, 'session.')) {
return Promise.reject(
new XoError('session.*() methods are disabled from this interface')
@ -53,20 +53,20 @@ export default class Xo extends JsonRpcWebSocketClient {
return promise
}
refreshUser () {
refreshUser() {
return super.call('session.getUser').then(user => {
return (this._user = user)
})
}
signIn (credentials) {
signIn(credentials) {
// Register this credentials for future use.
this._credentials = credentials
return this._signIn(credentials)
}
_signIn (credentials) {
_signIn(credentials) {
return super.call('session.signIn', credentials).then(
user => {
this._user = user

View File

@ -18,15 +18,15 @@ export const configurationSchema = {
// ===================================================================
class AuthGitHubXoPlugin {
constructor (xo) {
constructor(xo) {
this._xo = xo
}
configure (conf) {
configure(conf) {
this._conf = conf
}
load () {
load() {
const { _xo: xo } = this
xo.registerPassportStrategy(

View File

@ -29,16 +29,16 @@ export const configurationSchema = {
// ===================================================================
class AuthGoogleXoPlugin {
constructor ({ xo }) {
constructor({ xo }) {
this._conf = null
this._xo = xo
}
configure (conf) {
configure(conf) {
this._conf = conf
}
load () {
load() {
const conf = this._conf
const xo = this._xo

View File

@ -113,13 +113,13 @@ export const testSchema = {
// ===================================================================
class AuthLdap {
constructor (xo) {
constructor(xo) {
this._xo = xo
this._authenticate = bind(this._authenticate, this)
}
async configure (conf) {
async configure(conf) {
const clientOpts = (this._clientOpts = {
url: conf.uri,
maxConnections: 5,
@ -155,15 +155,15 @@ class AuthLdap {
this._searchFilter = searchFilter
}
load () {
load() {
this._xo.registerAuthenticationProvider(this._authenticate)
}
unload () {
unload() {
this._xo.unregisterAuthenticationProvider(this._authenticate)
}
test ({ username, password }) {
test({ username, password }) {
return this._authenticate({
username,
password,
@ -174,7 +174,7 @@ class AuthLdap {
})
}
async _authenticate ({ username, password }, logger = noop) {
async _authenticate({ username, password }, logger = noop) {
if (username === undefined || password === undefined) {
logger('require `username` and `password` to authenticate!')

View File

@ -171,7 +171,7 @@ const promptByType = {
}),
}
export default function promptGeneric (schema, defaultValue, path) {
export default function promptGeneric(schema, defaultValue, path) {
const type = schema.enum ? 'enum' : schema.type
const prompt = promptByType[type.toLowerCase()]

View File

@ -34,18 +34,18 @@ export const configurationSchema = {
// ===================================================================
class AuthSamlXoPlugin {
constructor ({ xo }) {
constructor({ xo }) {
this._conf = null
this._usernameField = null
this._xo = xo
}
configure ({ usernameField, ...conf }) {
configure({ usernameField, ...conf }) {
this._usernameField = usernameField
this._conf = conf
}
load () {
load() {
const xo = this._xo
xo.registerPassportStrategy(

View File

@ -131,29 +131,29 @@ const addWarnings = (text, warnings, nbIndent = 0) => {
}
class BackupReportsXoPlugin {
constructor (xo) {
constructor(xo) {
this._xo = xo
this._report = this._wrapper.bind(this)
}
configure ({ toMails, toXmpp }) {
configure({ toMails, toXmpp }) {
this._mailsReceivers = toMails
this._xmppReceivers = toXmpp
}
load () {
load() {
this._xo.on('job:terminated', this._report)
}
test ({ runId }) {
test({ runId }) {
return this._backupNgListener(undefined, undefined, undefined, runId)
}
unload () {
unload() {
this._xo.removeListener('job:terminated', this._report)
}
_wrapper (status, job, schedule, runJobId) {
_wrapper(status, job, schedule, runJobId) {
return new Promise(resolve =>
resolve(
job.type === 'backup'
@ -163,7 +163,7 @@ class BackupReportsXoPlugin {
).catch(logError)
}
async _backupNgListener (_1, _2, schedule, runJobId) {
async _backupNgListener(_1, _2, schedule, runJobId) {
const xo = this._xo
const log = await xo.getBackupNgLogs(runJobId)
if (log === undefined) {
@ -480,7 +480,7 @@ class BackupReportsXoPlugin {
})
}
_sendReport ({ markdown, subject, nagiosStatus, nagiosMarkdown }) {
_sendReport({ markdown, subject, nagiosStatus, nagiosMarkdown }) {
const xo = this._xo
return Promise.all([
xo.sendEmail !== undefined &&
@ -506,7 +506,7 @@ class BackupReportsXoPlugin {
])
}
_listener (status) {
_listener(status) {
const { calls, timezone, error } = status
const formatDate = createDateFormater(timezone)

View File

@ -7,7 +7,7 @@ const HTTP_URL = 'http://localhost:9002'
// ===================================================================
class XoServerCloud {
constructor ({ xo }) {
constructor({ xo }) {
this._xo = xo
// Defined in configure().
@ -15,11 +15,11 @@ class XoServerCloud {
this._key = null
}
configure (configuration) {
configure(configuration) {
this._conf = configuration
}
async load () {
async load() {
const getResourceCatalog = () => this._getCatalog()
getResourceCatalog.description = 'Get the list of all available resources'
getResourceCatalog.permission = 'admin'
@ -59,14 +59,14 @@ class XoServerCloud {
connect()
}
unload () {
unload() {
this._unsetApiMethods()
this._unsetRequestResource()
}
// ----------------------------------------------------------------
async _getCatalog () {
async _getCatalog() {
const catalog = await this._updater.call('getResourceCatalog')
if (!catalog) {
@ -78,7 +78,7 @@ class XoServerCloud {
// ----------------------------------------------------------------
async _getNamespaces () {
async _getNamespaces() {
const catalog = await this._getCatalog()
if (!catalog._namespaces) {
@ -90,7 +90,7 @@ class XoServerCloud {
// ----------------------------------------------------------------
async _registerResource (namespace) {
async _registerResource(namespace) {
const _namespace = (await this._getNamespaces())[namespace]
if (_namespace === undefined) {
@ -106,7 +106,7 @@ class XoServerCloud {
// ----------------------------------------------------------------
async _getNamespaceCatalog (namespace) {
async _getNamespaceCatalog(namespace) {
const namespaceCatalog = (await this._getCatalog())[namespace]
if (!namespaceCatalog) {
@ -118,7 +118,7 @@ class XoServerCloud {
// ----------------------------------------------------------------
async _requestResource (namespace, id, version) {
async _requestResource(namespace, id, version) {
const _namespace = (await this._getNamespaces())[namespace]
if (!_namespace || !_namespace.registered) {

View File

@ -6,7 +6,7 @@ import { debug } from './utils'
// ===================================================================
export default class DensityPlan extends Plan {
_checkRessourcesThresholds (objects, averages) {
_checkRessourcesThresholds(objects, averages) {
const { low } = this._thresholds.memoryFree
return filter(objects, object => {
const { memory, memoryFree = memory } = averages[object.id]
@ -14,7 +14,7 @@ export default class DensityPlan extends Plan {
})
}
async execute () {
async execute() {
const results = await this._findHostsToOptimize()
if (!results) {
@ -89,7 +89,7 @@ export default class DensityPlan extends Plan {
debug(`Density mode: ${optimizationsCount} optimizations.`)
}
async _simulate ({ host, destinations, hostsAverages }) {
async _simulate({ host, destinations, hostsAverages }) {
const { id: hostId } = host
debug(`Try to optimize Host (${hostId}).`)
@ -145,7 +145,7 @@ export default class DensityPlan extends Plan {
}
// Test if a VM migration on a destination (of a destinations set) is possible.
_testMigration ({ vm, destinations, hostsAverages, vmsAverages }) {
_testMigration({ vm, destinations, hostsAverages, vmsAverages }) {
const {
_thresholds: { critical: criticalThreshold },
} = this
@ -181,7 +181,7 @@ export default class DensityPlan extends Plan {
// Migrate the VMs of one host.
// Try to shutdown the VMs host.
async _migrate (hostId, moves) {
async _migrate(hostId, moves) {
const xapiSrc = this.xo.getXapi(hostId)
await Promise.all(

View File

@ -93,7 +93,7 @@ export const configurationSchema = {
// ===================================================================
class LoadBalancerPlugin {
constructor (xo) {
constructor(xo) {
this.xo = xo
this._job = createSchedule(`*/${EXECUTION_DELAY} * * * *`).createJob(
@ -110,7 +110,7 @@ class LoadBalancerPlugin {
)
}
async configure ({ plans }) {
async configure({ plans }) {
this._plans = []
this._poolIds = [] // Used pools.
@ -124,15 +124,15 @@ class LoadBalancerPlugin {
}
}
load () {
load() {
this._job.start()
}
unload () {
unload() {
this._job.stop()
}
_addPlan (mode, { name, pools, ...options }) {
_addPlan(mode, { name, pools, ...options }) {
pools = uniq(pools)
// Check already used pools.
@ -148,7 +148,7 @@ class LoadBalancerPlugin {
)
}
_executePlans () {
_executePlans() {
debug('Execute plans!')
return Promise.all(mapToArray(this._plans, plan => plan.execute()))

View File

@ -4,7 +4,7 @@ import Plan from './plan'
import { debug } from './utils'
// Compare a list of objects and give the best.
function searchBestObject (objects, fun) {
function searchBestObject(objects, fun) {
let object = objects[0]
for (let i = 1; i < objects.length; i++) {
@ -19,7 +19,7 @@ function searchBestObject (objects, fun) {
// ===================================================================
export default class PerformancePlan extends Plan {
_checkRessourcesThresholds (objects, averages) {
_checkRessourcesThresholds(objects, averages) {
return filter(objects, object => {
const objectAverages = averages[object.id]
@ -30,7 +30,7 @@ export default class PerformancePlan extends Plan {
})
}
async execute () {
async execute() {
// Try to power on a hosts set.
try {
await Promise.all(
@ -80,7 +80,7 @@ export default class PerformancePlan extends Plan {
}
}
async _optimize ({ exceededHost, hosts, hostsAverages }) {
async _optimize({ exceededHost, hosts, hostsAverages }) {
const vms = await this._getVms(exceededHost.id)
const vmsAverages = await this._getVmsAverages(vms, exceededHost)

View File

@ -23,7 +23,7 @@ const numberOrDefault = (value, def) => (value >= 0 ? value : def)
// Averages.
// ===================================================================
function computeAverage (values, nPoints) {
function computeAverage(values, nPoints) {
if (values === undefined) {
return
}
@ -47,7 +47,7 @@ function computeAverage (values, nPoints) {
return sum / tot
}
function computeRessourcesAverage (objects, objectsStats, nPoints) {
function computeRessourcesAverage(objects, objectsStats, nPoints) {
const averages = {}
for (const object of objects) {
@ -67,7 +67,7 @@ function computeRessourcesAverage (objects, objectsStats, nPoints) {
return averages
}
function computeRessourcesAverageWithWeight (averages1, averages2, ratio) {
function computeRessourcesAverageWithWeight(averages1, averages2, ratio) {
const averages = {}
for (const id in averages1) {
@ -87,7 +87,7 @@ function computeRessourcesAverageWithWeight (averages1, averages2, ratio) {
return averages
}
function setRealCpuAverageOfVms (vms, vmsAverages, nCpus) {
function setRealCpuAverageOfVms(vms, vmsAverages, nCpus) {
for (const vm of vms) {
const averages = vmsAverages[vm.id]
averages.cpu *= averages.nCpus / nCpus
@ -97,7 +97,7 @@ function setRealCpuAverageOfVms (vms, vmsAverages, nCpus) {
// ===================================================================
export default class Plan {
constructor (xo, name, poolIds, { excludedHosts, thresholds } = {}) {
constructor(xo, name, poolIds, { excludedHosts, thresholds } = {}) {
this.xo = xo
this._name = name
this._poolIds = poolIds
@ -132,7 +132,7 @@ export default class Plan {
}
}
execute () {
execute() {
throw new Error('Not implemented')
}
@ -140,7 +140,7 @@ export default class Plan {
// Get hosts to optimize.
// ===================================================================
async _findHostsToOptimize () {
async _findHostsToOptimize() {
const hosts = this._getHosts()
const hostsStats = await this._getHostsStats(hosts, 'minutes')
@ -181,7 +181,7 @@ export default class Plan {
}
}
_checkRessourcesThresholds () {
_checkRessourcesThresholds() {
throw new Error('Not implemented')
}
@ -189,7 +189,7 @@ export default class Plan {
// Get objects.
// ===================================================================
_getPlanPools () {
_getPlanPools() {
const pools = {}
try {
@ -204,7 +204,7 @@ export default class Plan {
}
// Compute hosts for each pool. They can change over time.
_getHosts ({ powerState = 'Running' } = {}) {
_getHosts({ powerState = 'Running' } = {}) {
return filter(
this.xo.getObjects(),
object =>
@ -215,7 +215,7 @@ export default class Plan {
)
}
async _getVms (hostId) {
async _getVms(hostId) {
return filter(
this.xo.getObjects(),
object =>
@ -229,7 +229,7 @@ export default class Plan {
// Get stats.
// ===================================================================
async _getHostsStats (hosts, granularity) {
async _getHostsStats(hosts, granularity) {
const hostsStats = {}
await Promise.all(
@ -247,7 +247,7 @@ export default class Plan {
return hostsStats
}
async _getVmsStats (vms, granularity) {
async _getVmsStats(vms, granularity) {
const vmsStats = {}
await Promise.all(
@ -265,7 +265,7 @@ export default class Plan {
return vmsStats
}
async _getVmsAverages (vms, host) {
async _getVmsAverages(vms, host) {
const vmsStats = await this._getVmsStats(vms, 'minutes')
const vmsAverages = computeRessourcesAverageWithWeight(
computeRessourcesAverage(vms, vmsStats, EXECUTION_DELAY),

View File

@ -343,7 +343,7 @@ const raiseOrLowerAlarm = (
}
}
async function getServerTimestamp (xapi, host) {
async function getServerTimestamp(xapi, host) {
const serverLocalTime = await xapi.call('host.get_servertime', host.$ref)
return Math.floor(
utcParse('%Y%m%dT%H:%M:%SZ')(serverLocalTime).getTime() / 1000
@ -351,7 +351,7 @@ async function getServerTimestamp (xapi, host) {
}
class PerfAlertXoPlugin {
constructor (xo) {
constructor(xo) {
this._xo = xo
this._job = createSchedule('* * * * *').createJob(async () => {
try {
@ -365,20 +365,20 @@ class PerfAlertXoPlugin {
})
}
async configure (configuration) {
async configure(configuration) {
this._configuration = configuration
clearCurrentAlarms()
}
load () {
load() {
this._job.start()
}
unload () {
unload() {
this._job.stop()
}
_generateUrl (type, object) {
_generateUrl(type, object) {
const { baseUrl } = this._configuration
const { uuid } = object
switch (type) {
@ -393,7 +393,7 @@ class PerfAlertXoPlugin {
}
}
async test () {
async test() {
const monitorBodies = await Promise.all(
map(
this._getMonitors(),
@ -413,7 +413,7 @@ ${monitorBodies.join('\n')}`
)
}
_parseDefinition (definition) {
_parseDefinition(definition) {
const alarmId = `${definition.objectType}|${definition.variableName}|${
definition.alarmTriggerLevel
}`
@ -533,7 +533,7 @@ ${monitorBodies.join('\n')}`
}
}
_getMonitors () {
_getMonitors() {
return map(this._configuration.hostMonitors, def =>
this._parseDefinition({ ...def, objectType: 'host' })
)
@ -583,7 +583,7 @@ ${monitorBodies.join('\n')}`
// shouldAlarm: true,
// listItem: ' * [lab1](localhost:3000#/hosts/485ea1f-b475-f6f2-58a7-895ab626ce5d/stats): 70%\n'
// }
async _checkMonitors () {
async _checkMonitors() {
const monitors = this._getMonitors()
for (const monitor of monitors) {
const snapshot = await monitor.snapshot()
@ -654,7 +654,7 @@ ${entry.listItem}
}
}
_sendAlertEmail (subjectSuffix, markdownBody) {
_sendAlertEmail(subjectSuffix, markdownBody) {
if (
this._configuration.toEmails !== undefined &&
this._xo.sendEmail !== undefined
@ -673,7 +673,7 @@ ${entry.listItem}
}
}
async getRrd (xoObject, secondsAgo) {
async getRrd(xoObject, secondsAgo) {
const host = xoObject.$type === 'host' ? xoObject : xoObject.$resident_on
if (host == null) {
return null
@ -700,7 +700,7 @@ ${entry.listItem}
}
}
exports.default = function ({ xo }) {
exports.default = function({ xo }) {
return new PerfAlertXoPlugin(xo)
}

View File

@ -33,7 +33,7 @@ exports.testSchema = {
//
// Its only parameter is an object which currently only contains a
// `xo` property: the instance of the currently running xo-server.
exports.default = function (opts) {
exports.default = function(opts) {
// For simplicity's sake, this plugin returns a plain object, but
// usually it returns a new instance of an existing class.
return {
@ -42,7 +42,7 @@ exports.default = function (opts) {
//
// Note: before being called, the configuration is validated
// against the provided configuration schema.
configure: function (configuration, state) {
configure: function(configuration, state) {
console.log('stub configured', configuration)
console.log('sub is currently', state.loaded ? 'loaded' : 'unloaded')
},
@ -54,14 +54,14 @@ exports.default = function (opts) {
//
// Note 2: if the plugin is configurable, will only be called if
// the plugin has been successfully configured.
load: function () {
load: function() {
console.log('stub loaded')
},
// This (optional) method is called to unload the plugin.
//
// Note: will only be called if the plugin is currently loaded.
unload: function () {
unload: function() {
console.log('stub unloaded')
},
@ -70,7 +70,7 @@ exports.default = function (opts) {
// Note 2: before being called, the test configuration is validated
// against the provided test data.
// Note 3: will only be called if the test option is activated.
test: function (data) {
test: function(data) {
console.log('the configuration is about to be tested')
// TODO: test the configuration, i.e, use the main feature of the plugin and throws any errors.
},

View File

@ -133,7 +133,7 @@ export const testSchema = {
// ===================================================================
class TransportEmailPlugin {
constructor ({ xo }) {
constructor({ xo }) {
this._xo = xo
this._unset = null
@ -141,7 +141,7 @@ class TransportEmailPlugin {
this._send = null
}
configure ({
configure({
from,
transport: { ignoreUnauthorized, password, secure, user, ...transportConf },
}) {
@ -173,15 +173,15 @@ class TransportEmailPlugin {
this._send = promisify(transport.sendMail, transport)
}
load () {
load() {
this._unset = this._xo.defineProperty('sendEmail', this._sendEmail, this)
}
unload () {
unload() {
this._unset()
}
test ({ to }) {
test({ to }) {
return this._sendEmail({
to,
subject: '[Xen Orchestra] Test of transport-email plugin',
@ -198,7 +198,7 @@ The transport-email plugin for Xen Orchestra server seems to be working fine, ni
})
}
_sendEmail ({ from, to, cc, bcc, subject, markdown, attachments }) {
_sendEmail({ from, to, cc, bcc, subject, markdown, attachments }) {
return this._send(
removeUndefined({
from,

View File

@ -36,11 +36,11 @@ export const configurationSchema = {
// ===================================================================
const bind = (fn, thisArg) =>
function __bound__ () {
function __bound__() {
return fn.apply(thisArg, arguments)
}
function nscaPacketBuilder ({ host, iv, message, service, status, timestamp }) {
function nscaPacketBuilder({ host, iv, message, service, status, timestamp }) {
// Building NSCA packet
const SIZE = 720
const packet = Buffer.alloc(SIZE)
@ -56,7 +56,7 @@ function nscaPacketBuilder ({ host, iv, message, service, status, timestamp }) {
return packet
}
function xor (data, mask) {
function xor(data, mask) {
const dataSize = data.length
const maskSize = mask.length
const result = Buffer.allocUnsafe(dataSize)
@ -81,7 +81,7 @@ const VERSION = 3
const ENCODING = 'binary'
class XoServerNagios {
constructor ({ xo }) {
constructor({ xo }) {
this._sendPassiveCheck = bind(this._sendPassiveCheck, this)
this._set = bind(xo.defineProperty, xo)
this._unset = null
@ -91,20 +91,20 @@ class XoServerNagios {
this._key = null
}
configure (configuration) {
configure(configuration) {
this._conf = configuration
this._key = Buffer.from(configuration.key, ENCODING)
}
load () {
load() {
this._unset = this._set('sendPassiveCheck', this._sendPassiveCheck)
}
unload () {
unload() {
this._unset()
}
test () {
test() {
return this._sendPassiveCheck({
message:
'The server-nagios plugin for Xen Orchestra server seems to be working fine, nicely done :)',
@ -112,7 +112,7 @@ class XoServerNagios {
})
}
_sendPassiveCheck ({ message, status }) {
_sendPassiveCheck({ message, status }) {
return new Promise((resolve, reject) => {
if (/\r|\n/.test(message)) {
throw new Error('the message must not contain a line break')

View File

@ -41,7 +41,7 @@ export const configurationSchema = {
// ===================================================================
class XoServerTransportSlack {
constructor ({ xo }) {
constructor({ xo }) {
this._sendSlack = this._sendSlack.bind(this)
this._set = xo.defineProperty.bind(xo)
this._unset = null
@ -51,22 +51,22 @@ class XoServerTransportSlack {
this._send = null
}
configure ({ webhookUri, ...conf }) {
configure({ webhookUri, ...conf }) {
const slack = new Slack()
slack.setWebhook(webhookUri)
this._conf = conf
this._send = promisify(slack.webhook)
}
load () {
load() {
this._unset = this._set('sendSlackMessage', this._sendSlack)
}
unload () {
unload() {
this._unset()
}
test () {
test() {
return this._sendSlack({
message: `Hi there,
@ -74,7 +74,7 @@ The transport-slack plugin for Xen Orchestra server seems to be working fine, ni
})
}
_sendSlack ({ message }) {
_sendSlack({ message }) {
// TODO: handle errors
return this._send({ ...this._conf, text: message }).catch(logAndRethrow)
}

View File

@ -34,7 +34,7 @@ export const configurationSchema = {
// ===================================================================
class TransportXmppPlugin {
constructor ({ xo }) {
constructor({ xo }) {
this._sendToXmppClient = this._sendToXmppClient.bind(this)
this._set = xo.defineProperty.bind(xo)
this._unset = null
@ -46,12 +46,12 @@ class TransportXmppPlugin {
this._client = null
}
configure (conf) {
configure(conf) {
this._conf = conf
this._conf.reconnect = true
}
async load () {
async load() {
this._client = new XmppClient(this._conf)
this._client.on('error', () => {})
@ -61,14 +61,14 @@ class TransportXmppPlugin {
this._unset = this._set('sendToXmppClient', this._sendToXmppClient)
}
unload () {
unload() {
this._unset()
this._client.end()
this._unset = this._client = null
}
_sendToXmppClient ({ to, message }) {
_sendToXmppClient({ to, message }) {
for (const receiver of to) {
this._client.send(
new XmppClient.Stanza('message', {

View File

@ -112,7 +112,7 @@ const normaliseValue = value => (isFinite(value) ? round(value, 2) : '-')
// ===================================================================
Handlebars.registerHelper('compare', function (
Handlebars.registerHelper('compare', function(
lvalue,
operator,
rvalue,
@ -133,7 +133,7 @@ Handlebars.registerHelper('compare', function (
: options.inverse(this)
})
Handlebars.registerHelper('math', function (lvalue, operator, rvalue, options) {
Handlebars.registerHelper('math', function(lvalue, operator, rvalue, options) {
if (arguments.length < 3) {
throw new Error('Handlebars Helper "math" needs 2 parameters')
}
@ -205,7 +205,7 @@ Handlebars.registerHelper(
// ===================================================================
function computeMean (values) {
function computeMean(values) {
let sum = 0
let n = 0
forEach(values, val => {
@ -220,14 +220,14 @@ function computeMean (values) {
const computeDoubleMean = val => computeMean(map(val, computeMean))
function computeMeans (objects, options) {
function computeMeans(objects, options) {
return zipObject(
options,
map(options, opt => computeMean(map(objects, opt)), 2)
)
}
function getTop (objects, options) {
function getTop(objects, options) {
return zipObject(
options,
map(options, opt =>
@ -251,7 +251,7 @@ function getTop (objects, options) {
)
}
function computePercentage (curr, prev, options) {
function computePercentage(curr, prev, options) {
return zipObject(
options,
map(options, opt =>
@ -262,14 +262,14 @@ function computePercentage (curr, prev, options) {
)
}
function getDiff (oldElements, newElements) {
function getDiff(oldElements, newElements) {
return {
added: differenceBy(newElements, oldElements, 'uuid'),
removed: differenceBy(oldElements, newElements, 'uuid'),
}
}
function getMemoryUsedMetric ({ memory, memoryFree = memory }) {
function getMemoryUsedMetric({ memory, memoryFree = memory }) {
return map(memory, (value, key) => value - memoryFree[key])
}
@ -284,7 +284,7 @@ const METRICS_MEAN = {
// ===================================================================
async function getVmsStats ({ runningVms, xo }) {
async function getVmsStats({ runningVms, xo }) {
return orderBy(
await Promise.all(
map(runningVms, async vm => {
@ -322,7 +322,7 @@ async function getVmsStats ({ runningVms, xo }) {
)
}
async function getHostsStats ({ runningHosts, xo }) {
async function getHostsStats({ runningHosts, xo }) {
return orderBy(
await Promise.all(
map(runningHosts, async host => {
@ -354,7 +354,7 @@ async function getHostsStats ({ runningHosts, xo }) {
)
}
async function getSrsStats ({ xo, xoObjects }) {
async function getSrsStats({ xo, xoObjects }) {
return orderBy(
await asyncMap(
filter(
@ -406,7 +406,7 @@ async function getSrsStats ({ xo, xoObjects }) {
)
}
function computeGlobalVmsStats ({ haltedVms, vmsStats, xo }) {
function computeGlobalVmsStats({ haltedVms, vmsStats, xo }) {
const allVms = concat(
map(vmsStats, vm => ({
uuid: vm.uuid,
@ -434,7 +434,7 @@ function computeGlobalVmsStats ({ haltedVms, vmsStats, xo }) {
)
}
function computeGlobalHostsStats ({ haltedHosts, hostsStats, xo }) {
function computeGlobalHostsStats({ haltedHosts, hostsStats, xo }) {
const allHosts = concat(
map(hostsStats, host => ({
uuid: host.uuid,
@ -461,7 +461,7 @@ function computeGlobalHostsStats ({ haltedHosts, hostsStats, xo }) {
)
}
function getTopVms ({ vmsStats, xo }) {
function getTopVms({ vmsStats, xo }) {
return getTop(vmsStats, [
'cpu',
'ram',
@ -475,7 +475,7 @@ function getTopVms ({ vmsStats, xo }) {
])
}
function getTopHosts ({ hostsStats, xo }) {
function getTopHosts({ hostsStats, xo }) {
return getTop(hostsStats, [
'cpu',
'ram',
@ -485,11 +485,11 @@ function getTopHosts ({ hostsStats, xo }) {
])
}
function getTopSrs (srsStats) {
function getTopSrs(srsStats) {
return getTop(srsStats, ['usedSpace', 'iopsRead', 'iopsWrite', 'iopsTotal'])
}
async function getHostsMissingPatches ({ runningHosts, xo }) {
async function getHostsMissingPatches({ runningHosts, xo }) {
const hostsMissingPatches = await Promise.all(
map(runningHosts, async host => {
let hostsPatches = await xo
@ -519,15 +519,15 @@ async function getHostsMissingPatches ({ runningHosts, xo }) {
return filter(hostsMissingPatches, host => host !== undefined)
}
function getAllUsersEmail (users) {
function getAllUsersEmail(users) {
return map(users, 'email')
}
async function storeStats ({ data, storedStatsPath }) {
async function storeStats({ data, storedStatsPath }) {
await pWriteFile(storedStatsPath, JSON.stringify(data))
}
async function computeEvolution ({ storedStatsPath, ...newStats }) {
async function computeEvolution({ storedStatsPath, ...newStats }) {
try {
const oldStats = JSON.parse(await pReadFile(storedStatsPath, 'utf8'))
const newStatsVms = newStats.vms
@ -616,7 +616,7 @@ async function computeEvolution ({ storedStatsPath, ...newStats }) {
}
}
async function dataBuilder ({ xo, storedStatsPath, all }) {
async function dataBuilder({ xo, storedStatsPath, all }) {
const xoObjects = values(xo.getObjects())
const runningVms = filter(xoObjects, { type: 'VM', power_state: 'Running' })
const haltedVms = filter(xoObjects, { type: 'VM', power_state: 'Halted' })
@ -707,7 +707,7 @@ const CRON_BY_PERIODICITY = {
}
class UsageReportPlugin {
constructor ({ xo, getDataDir }) {
constructor({ xo, getDataDir }) {
this._xo = xo
this._dir = getDataDir
// Defined in configure().
@ -718,7 +718,7 @@ class UsageReportPlugin {
)
}
configure (configuration, state) {
configure(configuration, state) {
this._conf = configuration
if (this._job !== undefined) {
@ -743,22 +743,22 @@ class UsageReportPlugin {
}
}
async load () {
async load() {
const dir = await this._dir()
this._storedStatsPath = `${dir}/stats.json`
this._job.start()
}
unload () {
unload() {
this._job.stop()
}
test () {
test() {
return this._sendReport(true)
}
async _sendReport (storeData) {
async _sendReport(storeData) {
const data = await dataBuilder({
xo: this._xo,
storedStatsPath: this._storedStatsPath,

View File

@ -4,8 +4,8 @@ Error.stackTraceLimit = 100
try {
const sep = require('path').sep
require('stack-chain').filter.attach(function (_, frames) {
const filtered = frames.filter(function (frame) {
require('stack-chain').filter.attach(function(_, frames) {
const filtered = frames.filter(function(frame) {
const name = frame && frame.getFileName()
return (

View File

@ -1,4 +1,4 @@
export async function get () {
export async function get() {
return /* await */ this.getAllAcls()
}
@ -8,7 +8,7 @@ get.description = 'get existing ACLs'
// -------------------------------------------------------------------
export async function getCurrentPermissions () {
export async function getCurrentPermissions() {
return /* await */ this.getPermissionsForUser(this.session.get('user_id'))
}
@ -19,7 +19,7 @@ getCurrentPermissions.description =
// -------------------------------------------------------------------
export async function add ({ subject, object, action }) {
export async function add({ subject, object, action }) {
await this.addAcl(subject, object, action)
}
@ -35,7 +35,7 @@ add.description = 'add a new ACL entry'
// -------------------------------------------------------------------
export async function remove ({ subject, object, action }) {
export async function remove({ subject, object, action }) {
await this.removeAcl(subject, object, action)
}

View File

@ -3,7 +3,7 @@ import { isEmpty, pickBy } from 'lodash'
import { safeDateFormat } from '../utils'
export function createJob ({ schedules, ...job }) {
export function createJob({ schedules, ...job }) {
job.userId = this.user.id
return this.createBackupNgJob(job, schedules)
}
@ -41,7 +41,7 @@ createJob.params = {
},
}
export function migrateLegacyJob ({ id }) {
export function migrateLegacyJob({ id }) {
return this.migrateLegacyBackupJob(id)
}
migrateLegacyJob.permission = 'admin'
@ -51,7 +51,7 @@ migrateLegacyJob.params = {
},
}
export function deleteJob ({ id }) {
export function deleteJob({ id }) {
return this.deleteBackupNgJob(id)
}
deleteJob.permission = 'admin'
@ -61,7 +61,7 @@ deleteJob.params = {
},
}
export function editJob (props) {
export function editJob(props) {
return this.updateJob(props)
}
@ -100,13 +100,13 @@ editJob.params = {
},
}
export function getAllJobs () {
export function getAllJobs() {
return this.getAllJobs('backup')
}
getAllJobs.permission = 'admin'
export function getJob ({ id }) {
export function getJob({ id }) {
return this.getJob(id, 'backup')
}
@ -118,7 +118,7 @@ getJob.params = {
},
}
export async function runJob ({
export async function runJob({
id,
schedule,
vm,
@ -151,7 +151,7 @@ runJob.params = {
// -----------------------------------------------------------------------------
export async function getAllLogs (filter) {
export async function getAllLogs(filter) {
const logs = await this.getBackupNgLogs()
return isEmpty(filter) ? logs : pickBy(logs, filter)
}
@ -160,7 +160,7 @@ getAllLogs.permission = 'admin'
// -----------------------------------------------------------------------------
export function deleteVmBackup ({ id }) {
export function deleteVmBackup({ id }) {
return this.deleteVmBackupNg(id)
}
@ -172,7 +172,7 @@ deleteVmBackup.params = {
},
}
export function listVmBackups ({ remotes }) {
export function listVmBackups({ remotes }) {
return this.listVmBackupsNg(remotes)
}
@ -187,7 +187,7 @@ listVmBackups.params = {
},
}
export function importVmBackup ({ id, sr }) {
export function importVmBackup({ id, sr }) {
return this.importVmBackupNg(id, sr)
}
@ -204,7 +204,7 @@ importVmBackup.params = {
// -----------------------------------------------------------------------------
export function listPartitions ({ remote, disk }) {
export function listPartitions({ remote, disk }) {
return this.listBackupNgDiskPartitions(remote, disk)
}
@ -219,7 +219,7 @@ listPartitions.params = {
},
}
export function listFiles ({ remote, disk, partition, path }) {
export function listFiles({ remote, disk, partition, path }) {
return this.listBackupNgPartitionFiles(remote, disk, partition, path)
}
@ -241,7 +241,7 @@ listFiles.params = {
},
}
async function handleFetchFiles (req, res, { remote, disk, partition, paths }) {
async function handleFetchFiles(req, res, { remote, disk, partition, paths }) {
const zipStream = await this.fetchBackupNgPartitionFiles(
remote,
disk,
@ -254,7 +254,7 @@ async function handleFetchFiles (req, res, { remote, disk, partition, paths }) {
return zipStream
}
export async function fetchFiles (params) {
export async function fetchFiles(params) {
const { paths } = params
let filename = `restore_${safeDateFormat(new Date())}`
if (paths.length === 1) {

View File

@ -8,7 +8,7 @@ const log = createLogger('xo:backup')
// ===================================================================
export function list ({ remote }) {
export function list({ remote }) {
return this.listVmBackups(remote)
}
@ -19,7 +19,7 @@ list.params = {
// -------------------------------------------------------------------
export function scanDisk ({ remote, disk }) {
export function scanDisk({ remote, disk }) {
return this.scanDiskBackup(remote, disk)
}
@ -31,7 +31,7 @@ scanDisk.params = {
// -------------------------------------------------------------------
export function scanFiles ({ remote, disk, partition, path }) {
export function scanFiles({ remote, disk, partition, path }) {
return this.scanFilesInDiskBackup(remote, disk, partition, path)
}
@ -45,7 +45,7 @@ scanFiles.params = {
// -------------------------------------------------------------------
function handleFetchFiles (
function handleFetchFiles(
req,
res,
{ remote, disk, partition, paths, format: archiveFormat }
@ -83,7 +83,7 @@ function handleFetchFiles (
})
}
export async function fetchFiles ({ format = 'zip', ...params }) {
export async function fetchFiles({ format = 'zip', ...params }) {
const fileName =
params.paths.length > 1
? `restore_${new Date().toJSON()}.${format}`

View File

@ -1,10 +1,10 @@
export function getAll () {
export function getAll() {
return this.getAllCloudConfigs()
}
getAll.description = 'Gets all existing cloud configs templates'
export function create (props) {
export function create(props) {
return this.createCloudConfig(props)
}
@ -15,7 +15,7 @@ create.params = {
template: { type: 'string' },
}
export function update (props) {
export function update(props) {
return this.updateCloudConfig(props)
}
@ -27,7 +27,7 @@ update.params = {
template: { type: 'string', optional: true },
}
function delete_ ({ id }) {
function delete_({ id }) {
return this.deleteCloudConfig(id)
}

View File

@ -9,7 +9,7 @@ const log = createLogger('xo:disk')
// ===================================================================
export async function create ({ name, size, sr, vm, bootable, position, mode }) {
export async function create({ name, size, sr, vm, bootable, position, mode }) {
const attach = vm !== undefined
do {
@ -73,7 +73,7 @@ create.resolve = {
// -------------------------------------------------------------------
async function handleExportContent (req, res, { xapi, id }) {
async function handleExportContent(req, res, { xapi, id }) {
const stream = await xapi.exportVdiContent(id)
req.on('close', () => stream.cancel())
@ -92,7 +92,7 @@ async function handleExportContent (req, res, { xapi, id }) {
})
}
export async function exportContent ({ vdi }) {
export async function exportContent({ vdi }) {
return {
$getFrom: await this.registerHttpRequest(
handleExportContent,
@ -117,7 +117,7 @@ exportContent.resolve = {
// -------------------------------------------------------------------
async function handleImportContent (req, res, { xapi, id }) {
async function handleImportContent(req, res, { xapi, id }) {
// Timeout seems to be broken in Node 4.
// See https://github.com/nodejs/node/issues/3319
req.setTimeout(43200000) // 12 hours
@ -132,7 +132,7 @@ async function handleImportContent (req, res, { xapi, id }) {
}
}
export async function importContent ({ vdi }) {
export async function importContent({ vdi }) {
return {
$sendTo: await this.registerHttpRequest(handleImportContent, {
id: vdi._xapiId,
@ -151,7 +151,7 @@ importContent.resolve = {
// -------------------------------------------------------------------
export async function resize ({ vdi, size }) {
export async function resize({ vdi, size }) {
await this.getXapi(vdi).resizeVdi(vdi._xapiId, parseSize(size))
}

View File

@ -1,4 +1,4 @@
export async function register ({ vm }) {
export async function register({ vm }) {
await this.getXapi(vm).registerDockerContainer(vm._xapiId)
}
register.description = 'Register the VM for Docker management'
@ -13,7 +13,7 @@ register.resolve = {
// -----------------------------------------------------------------------------
export async function deregister ({ vm }) {
export async function deregister({ vm }) {
await this.getXapi(vm).unregisterDockerContainer(vm._xapiId)
}
deregister.description = 'Deregister the VM for Docker management'
@ -28,23 +28,23 @@ deregister.resolve = {
// -----------------------------------------------------------------------------
export async function start ({ vm, container }) {
export async function start({ vm, container }) {
await this.getXapi(vm).startDockerContainer(vm._xapiId, container)
}
export async function stop ({ vm, container }) {
export async function stop({ vm, container }) {
await this.getXapi(vm).stopDockerContainer(vm._xapiId, container)
}
export async function restart ({ vm, container }) {
export async function restart({ vm, container }) {
await this.getXapi(vm).restartDockerContainer(vm._xapiId, container)
}
export async function pause ({ vm, container }) {
export async function pause({ vm, container }) {
await this.getXapi(vm).pauseDockerContainer(vm._xapiId, container)
}
export async function unpause ({ vm, container }) {
export async function unpause({ vm, container }) {
await this.getXapi(vm).unpauseDockerContainer(vm._xapiId, container)
}

View File

@ -1,4 +1,4 @@
export async function create ({ name }) {
export async function create({ name }) {
return (await this.createGroup({ name })).id
}
@ -11,7 +11,7 @@ create.params = {
// -------------------------------------------------------------------
// Deletes an existing group.
async function delete_ ({ id }) {
async function delete_({ id }) {
await this.deleteGroup(id)
}
@ -26,7 +26,7 @@ delete_.params = {
// -------------------------------------------------------------------
export async function getAll () {
export async function getAll() {
return /* await */ this.getAllGroups()
}
@ -36,7 +36,7 @@ getAll.permission = 'admin'
// -------------------------------------------------------------------
// sets group.users with an array of user ids
export async function setUsers ({ id, userIds }) {
export async function setUsers({ id, userIds }) {
await this.setGroupUsers(id, userIds)
}
@ -50,7 +50,7 @@ setUsers.params = {
// -------------------------------------------------------------------
// adds the user id to group.users
export async function addUser ({ id, userId }) {
export async function addUser({ id, userId }) {
await this.addUserToGroup(userId, id)
}
@ -64,7 +64,7 @@ addUser.params = {
// -------------------------------------------------------------------
// remove the user id from group.users
export async function removeUser ({ id, userId }) {
export async function removeUser({ id, userId }) {
await this.removeUserFromGroup(userId, id)
}
@ -79,7 +79,7 @@ removeUser.params = {
// -------------------------------------------------------------------
export async function set ({ id, name }) {
export async function set({ id, name }) {
await this.updateGroup(id, { name })
}

View File

@ -1,4 +1,4 @@
export function create (props) {
export function create(props) {
return this.createIpPool(props)
}
@ -7,7 +7,7 @@ create.description = 'Creates a new ipPool'
// -------------------------------------------------------------------
function delete_ ({ id }) {
function delete_({ id }) {
return this.deleteIpPool(id)
}
export { delete_ as delete }
@ -17,7 +17,7 @@ delete_.description = 'Delete an ipPool'
// -------------------------------------------------------------------
export function getAll (params) {
export function getAll(params) {
const { user } = this
return this.getAllIpPools(
@ -30,7 +30,7 @@ getAll.description = 'List all ipPools'
// -------------------------------------------------------------------
export function set ({ id, ...props }) {
export function set({ id, ...props }) {
return this.updateIpPool(id, props)
}

View File

@ -1,20 +1,20 @@
// FIXME so far, no acls for jobs
export function cancel ({ runId }) {
export function cancel({ runId }) {
return this.cancelJobRun(runId)
}
cancel.permission = 'admin'
cancel.description = 'Cancel a current run'
export async function getAll () {
export async function getAll() {
return /* await */ this.getAllJobs('call')
}
getAll.permission = 'admin'
getAll.description = 'Gets all available jobs'
export async function get (id) {
export async function get(id) {
return /* await */ this.getJob(id, 'call')
}
@ -24,7 +24,7 @@ get.params = {
id: { type: 'string' },
}
export async function create ({ job }) {
export async function create({ job }) {
if (!job.userId) {
job.userId = this.session.get('user_id')
}
@ -61,7 +61,7 @@ create.params = {
},
}
export async function set ({ job }) {
export async function set({ job }) {
await this.updateJob(job)
}
@ -94,7 +94,7 @@ set.params = {
},
}
async function delete_ ({ id }) {
async function delete_({ id }) {
await this.removeJob(id)
}
@ -106,7 +106,7 @@ delete_.params = {
export { delete_ as delete }
export async function runSequence ({ idSequence }) {
export async function runSequence({ idSequence }) {
await this.runJobSequence(idSequence)
}

View File

@ -1,4 +1,4 @@
export function get ({ namespace }) {
export function get({ namespace }) {
return this.getLogs(namespace)
}
@ -10,7 +10,7 @@ get.permission = 'admin'
// -------------------------------------------------------------------
async function delete_ ({ namespace, id }) {
async function delete_({ namespace, id }) {
const logger = await this.getLogger(namespace)
logger.del(id)
}

View File

@ -1,4 +1,4 @@
async function delete_ ({ message }) {
async function delete_({ message }) {
await this.getXapi(message).call('message.destroy', message._xapiRef)
}
export { delete_ as delete }

View File

@ -1,10 +1,10 @@
import { mapToArray } from '../utils'
export function getBondModes () {
export function getBondModes() {
return ['balance-slb', 'active-backup', 'lacp']
}
export async function create ({
export async function create({
pool,
name,
description,
@ -37,7 +37,7 @@ create.permission = 'admin'
// =================================================================
export async function createBonded ({
export async function createBonded({
pool,
name,
description,
@ -84,7 +84,7 @@ createBonded.description =
// ===================================================================
export async function set ({
export async function set({
network,
name_description: nameDescription,
@ -123,7 +123,7 @@ set.resolve = {
// =================================================================
export async function delete_ ({ network }) {
export async function delete_({ network }) {
return this.getXapi(network).deleteNetwork(network._xapiId)
}
export { delete_ as delete }

View File

@ -3,7 +3,7 @@
// ===================================================================
// Delete
async function delete_ ({ PBD }) {
async function delete_({ PBD }) {
// TODO: check if PBD is attached before
await this.getXapi(PBD).call('PBD.destroy', PBD._xapiRef)
}
@ -20,7 +20,7 @@ delete_.resolve = {
// ===================================================================
// Disconnect
export async function disconnect ({ pbd }) {
export async function disconnect({ pbd }) {
return this.getXapi(pbd).unplugPbd(pbd._xapiId)
}
@ -35,7 +35,7 @@ disconnect.resolve = {
// ===================================================================
// Connect
export async function connect ({ PBD }) {
export async function connect({ PBD }) {
// TODO: check if PBD is attached before
await this.getXapi(PBD).call('PBD.plug', PBD._xapiRef)
}

View File

@ -2,18 +2,18 @@
import { IPV4_CONFIG_MODES, IPV6_CONFIG_MODES } from '../xapi'
export function getIpv4ConfigurationModes () {
export function getIpv4ConfigurationModes() {
return IPV4_CONFIG_MODES
}
export function getIpv6ConfigurationModes () {
export function getIpv6ConfigurationModes() {
return IPV6_CONFIG_MODES
}
// ===================================================================
// Delete
async function delete_ ({ pif }) {
async function delete_({ pif }) {
// TODO: check if PIF is attached before
await this.getXapi(pif).call('PIF.destroy', pif._xapiRef)
}
@ -30,7 +30,7 @@ delete_.resolve = {
// ===================================================================
// Disconnect
export async function disconnect ({ pif }) {
export async function disconnect({ pif }) {
// TODO: check if PIF is attached before
await this.getXapi(pif).call('PIF.unplug', pif._xapiRef)
}
@ -45,7 +45,7 @@ disconnect.resolve = {
// ===================================================================
// Connect
export async function connect ({ pif }) {
export async function connect({ pif }) {
// TODO: check if PIF is attached before
await this.getXapi(pif).call('PIF.plug', pif._xapiRef)
}
@ -60,7 +60,7 @@ connect.resolve = {
// ===================================================================
// Reconfigure IP
export async function reconfigureIp ({
export async function reconfigureIp({
pif,
mode = 'DHCP',
ip = '',
@ -94,7 +94,7 @@ reconfigureIp.resolve = {
// ===================================================================
export async function editPif ({ pif, vlan }) {
export async function editPif({ pif, vlan }) {
await this.getXapi(pif).editPif(pif._xapiId, { vlan })
}

View File

@ -1,4 +1,4 @@
export async function get () {
export async function get() {
return /* await */ this.getPlugins()
}
@ -8,7 +8,7 @@ get.permission = 'admin'
// -------------------------------------------------------------------
export async function configure ({ id, configuration }) {
export async function configure({ id, configuration }) {
await this.configurePlugin(id, configuration)
}
@ -25,7 +25,7 @@ configure.permission = 'admin'
// -------------------------------------------------------------------
export async function disableAutoload ({ id }) {
export async function disableAutoload({ id }) {
await this.disablePluginAutoload(id)
}
@ -41,7 +41,7 @@ disableAutoload.permission = 'admin'
// -------------------------------------------------------------------
export async function enableAutoload ({ id }) {
export async function enableAutoload({ id }) {
await this.enablePluginAutoload(id)
}
@ -57,7 +57,7 @@ enableAutoload.permission = 'admin'
// -------------------------------------------------------------------
export async function load ({ id }) {
export async function load({ id }) {
await this.loadPlugin(id)
}
@ -73,7 +73,7 @@ load.permission = 'admin'
// -------------------------------------------------------------------
export async function unload ({ id }) {
export async function unload({ id }) {
await this.unloadPlugin(id)
}
@ -89,7 +89,7 @@ unload.permission = 'admin'
// -------------------------------------------------------------------
export async function purgeConfiguration ({ id }) {
export async function purgeConfiguration({ id }) {
await this.purgePluginConfiguration(id)
}
@ -105,7 +105,7 @@ purgeConfiguration.permission = 'admin'
// ---------------------------------------------------------------------
export async function test ({ id, data }) {
export async function test({ id, data }) {
await this.testPlugin(id, data)
}

View File

@ -4,7 +4,7 @@ import { mapToArray } from '../utils'
// ===================================================================
export async function set ({
export async function set({
pool,
// TODO: use camel case.
@ -37,7 +37,7 @@ set.resolve = {
// -------------------------------------------------------------------
export async function setDefaultSr ({ sr }) {
export async function setDefaultSr({ sr }) {
await this.hasPermissions(this.user.id, [[sr.$pool, 'administrate']])
await this.getXapi(sr).setDefaultSr(sr._xapiId)
@ -57,7 +57,7 @@ setDefaultSr.resolve = {
// -------------------------------------------------------------------
export async function setPoolMaster ({ host }) {
export async function setPoolMaster({ host }) {
await this.hasPermissions(this.user.id, [[host.$pool, 'administrate']])
await this.getXapi(host).setPoolMaster(host._xapiId)
@ -75,7 +75,7 @@ setPoolMaster.resolve = {
// -------------------------------------------------------------------
export async function installPatch ({ pool, patch: patchUuid }) {
export async function installPatch({ pool, patch: patchUuid }) {
await this.getXapi(pool).installPoolPatchOnAllHosts(patchUuid)
}
@ -93,7 +93,7 @@ installPatch.resolve = {
}
// -------------------------------------------------------------------
export async function installAllPatches ({ pool }) {
export async function installAllPatches({ pool }) {
await this.getXapi(pool).installAllPoolPatchesOnAllHosts()
}
@ -112,7 +112,7 @@ installAllPatches.description =
// -------------------------------------------------------------------
async function handlePatchUpload (req, res, { pool }) {
async function handlePatchUpload(req, res, { pool }) {
const contentLength = req.headers['content-length']
if (!contentLength) {
res.writeHead(411)
@ -123,7 +123,7 @@ async function handlePatchUpload (req, res, { pool }) {
await this.getXapi(pool).uploadPoolPatch(req, contentLength)
}
export async function uploadPatch ({ pool }) {
export async function uploadPatch({ pool }) {
return {
$sendTo: await this.registerHttpRequest(handlePatchUpload, { pool }),
}
@ -144,7 +144,7 @@ export { uploadPatch as patch }
// -------------------------------------------------------------------
export async function mergeInto ({ source, target, force }) {
export async function mergeInto({ source, target, force }) {
const sourceHost = this.getObject(source.master)
const targetHost = this.getObject(target.master)
@ -188,7 +188,7 @@ mergeInto.resolve = {
// -------------------------------------------------------------------
export async function getLicenseState ({ pool }) {
export async function getLicenseState({ pool }) {
return this.getXapi(pool).call('pool.get_license_state', pool._xapiId.$ref)
}
@ -204,7 +204,7 @@ getLicenseState.resolve = {
// -------------------------------------------------------------------
async function handleInstallSupplementalPack (req, res, { poolId }) {
async function handleInstallSupplementalPack(req, res, { poolId }) {
const xapi = this.getXapi(poolId)
// Timeout seems to be broken in Node 4.
@ -221,7 +221,7 @@ async function handleInstallSupplementalPack (req, res, { poolId }) {
}
}
export async function installSupplementalPack ({ pool }) {
export async function installSupplementalPack({ pool }) {
return {
$sendTo: await this.registerHttpRequest(handleInstallSupplementalPack, {
poolId: pool.id,

View File

@ -1,11 +1,11 @@
export async function getAll () {
export async function getAll() {
return this.getAllRemotes()
}
getAll.permission = 'admin'
getAll.description = 'Gets all existing fs remote points'
export async function get ({ id }) {
export async function get({ id }) {
return this.getRemote(id)
}
@ -15,7 +15,7 @@ get.params = {
id: { type: 'string' },
}
export async function test ({ id }) {
export async function test({ id }) {
return this.testRemote(id)
}
@ -25,7 +25,7 @@ test.params = {
id: { type: 'string' },
}
export async function list ({ id }) {
export async function list({ id }) {
return this.listRemoteBackups(id)
}
@ -35,7 +35,7 @@ list.params = {
id: { type: 'string' },
}
export async function create ({ name, url, options }) {
export async function create({ name, url, options }) {
return this.createRemote({ name, url, options })
}
@ -47,7 +47,7 @@ create.params = {
options: { type: 'string', optional: true },
}
export async function set ({ id, name, url, options, enabled }) {
export async function set({ id, name, url, options, enabled }) {
await this.updateRemote(id, { name, url, options, enabled })
}
@ -61,7 +61,7 @@ set.params = {
enabled: { type: 'boolean', optional: true },
}
async function delete_ ({ id }) {
async function delete_({ id }) {
await this.removeRemote(id)
}

View File

@ -1,4 +1,4 @@
export function create ({ name, subjects, objects, limits }) {
export function create({ name, subjects, objects, limits }) {
return this.createResourceSet(name, subjects, objects, limits)
}
@ -30,7 +30,7 @@ create.params = {
// -------------------------------------------------------------------
function delete_ ({ id }) {
function delete_({ id }) {
return this.deleteResourceSet(id)
}
export { delete_ as delete }
@ -45,7 +45,7 @@ delete_.params = {
// -------------------------------------------------------------------
export function set ({ id, name, subjects, objects, ipPools, limits }) {
export function set({ id, name, subjects, objects, ipPools, limits }) {
return this.updateResourceSet(id, {
limits,
name,
@ -94,7 +94,7 @@ set.params = {
// -------------------------------------------------------------------
export function get ({ id }) {
export function get({ id }) {
return this.getResourceSet(id)
}
@ -107,7 +107,7 @@ get.params = {
// -------------------------------------------------------------------
export async function getAll () {
export async function getAll() {
return this.getAllResourceSets(this.user.id)
}
@ -116,7 +116,7 @@ getAll.description = 'Get the list of all existing resource set'
// -------------------------------------------------------------------
export function addObject ({ id, object }) {
export function addObject({ id, object }) {
return this.addObjectToResourceSet(object, id)
}
@ -133,7 +133,7 @@ addObject.params = {
// -------------------------------------------------------------------
export function removeObject ({ id, object }) {
export function removeObject({ id, object }) {
return this.removeObjectFromResourceSet(object, id)
}
@ -150,7 +150,7 @@ removeObject.params = {
// -------------------------------------------------------------------
export function addSubject ({ id, subject }) {
export function addSubject({ id, subject }) {
return this.addSubjectToResourceSet(subject, id)
}
@ -167,7 +167,7 @@ addSubject.params = {
// -------------------------------------------------------------------
export function removeSubject ({ id, subject }) {
export function removeSubject({ id, subject }) {
return this.removeSubjectFromResourceSet(subject, id)
}
@ -184,7 +184,7 @@ removeSubject.params = {
// -------------------------------------------------------------------
export function addLimit ({ id, limitId, quantity }) {
export function addLimit({ id, limitId, quantity }) {
return this.addLimitToResourceSet(limitId, quantity, id)
}
@ -204,7 +204,7 @@ addLimit.params = {
// -------------------------------------------------------------------
export function removeLimit ({ id, limitId }) {
export function removeLimit({ id, limitId }) {
return this.removeLimitFromResourceSet(limitId, id)
}
@ -221,7 +221,7 @@ removeLimit.params = {
// -------------------------------------------------------------------
export function recomputeAllLimits () {
export function recomputeAllLimits() {
return this.recomputeResourceSetsLimits()
}

View File

@ -1,4 +1,4 @@
export async function getAll () {
export async function getAll() {
return /* await */ this.getRoles()
}

View File

@ -1,13 +1,13 @@
// FIXME so far, no acls for schedules
export async function getAll () {
export async function getAll() {
return /* await */ this.getAllSchedules()
}
getAll.permission = 'admin'
getAll.description = 'Gets all existing schedules'
export async function get (id) {
export async function get(id) {
return /* await */ this.getSchedule(id)
}
@ -17,7 +17,7 @@ get.params = {
id: { type: 'string' },
}
export function create ({ cron, enabled, jobId, name, timezone }) {
export function create({ cron, enabled, jobId, name, timezone }) {
return this.createSchedule({
cron,
enabled,
@ -38,7 +38,7 @@ create.params = {
timezone: { type: 'string', optional: true },
}
export async function set ({ cron, enabled, id, jobId, name, timezone }) {
export async function set({ cron, enabled, id, jobId, name, timezone }) {
await this.updateSchedule({ cron, enabled, id, jobId, name, timezone })
}
@ -53,7 +53,7 @@ set.params = {
timezone: { type: 'string', optional: true },
}
async function delete_ ({ id }) {
async function delete_({ id }) {
await this.deleteSchedule(id)
}

View File

@ -1,6 +1,6 @@
import { ignoreErrors } from 'promise-toolbox'
export async function add ({ autoConnect = true, ...props }) {
export async function add({ autoConnect = true, ...props }) {
const server = await this.registerXenServer(props)
if (autoConnect) {
@ -40,7 +40,7 @@ add.params = {
// -------------------------------------------------------------------
export async function remove ({ id }) {
export async function remove({ id }) {
await this.unregisterXenServer(id)
}
@ -58,7 +58,7 @@ remove.params = {
// TODO: remove this function when users are integrated to the main
// collection.
export function getAll () {
export function getAll() {
return this.getAllXenServers()
}
@ -68,7 +68,7 @@ getAll.permission = 'admin'
// -------------------------------------------------------------------
export async function set ({ id, ...props }) {
export async function set({ id, ...props }) {
await this.updateXenServer(id, props)
}
@ -104,7 +104,7 @@ set.params = {
// -------------------------------------------------------------------
export async function connect ({ id }) {
export async function connect({ id }) {
this.updateXenServer(id, { enabled: true })::ignoreErrors()
await this.connectXenServer(id)
}
@ -121,7 +121,7 @@ connect.params = {
// -------------------------------------------------------------------
export async function disconnect ({ id }) {
export async function disconnect({ id }) {
this.updateXenServer(id, { enabled: false })::ignoreErrors()
await this.disconnectXenServer(id)
}

View File

@ -5,7 +5,7 @@ import { invalidCredentials } from 'xo-common/api-errors'
// ===================================================================
export async function signIn (credentials) {
export async function signIn(credentials) {
const user = await this.authenticateUser(credentials)
if (!user) {
throw invalidCredentials()
@ -39,7 +39,7 @@ signInWithToken.params = {
// -------------------------------------------------------------------
export function signOut () {
export function signOut() {
this.session.unset('user_id')
}
@ -50,7 +50,7 @@ signOut.permission = ''
// -------------------------------------------------------------------
export async function getUser () {
export async function getUser() {
const userId = this.session.get('user_id')
return userId === undefined

View File

@ -6,7 +6,7 @@ import { ensureArray, forEach, parseXml } from '../utils'
// ===================================================================
export async function set ({
export async function set({
sr,
// TODO: use camel case.
@ -33,7 +33,7 @@ set.resolve = {
// -------------------------------------------------------------------
export async function scan ({ SR }) {
export async function scan({ SR }) {
await this.getXapi(SR).call('SR.scan', SR._xapiRef)
}
@ -50,7 +50,7 @@ const srIsBackingHa = sr =>
sr.$pool.ha_enabled && some(sr.$pool.$ha_statefiles, f => f.$SR === sr)
// TODO: find a way to call this "delete" and not destroy
export async function destroy ({ sr }) {
export async function destroy({ sr }) {
const xapi = this.getXapi(sr)
if (sr.SR_type !== 'xosan') {
await xapi.destroySr(sr._xapiId)
@ -82,7 +82,7 @@ destroy.resolve = {
// -------------------------------------------------------------------
export async function forget ({ SR }) {
export async function forget({ SR }) {
await this.getXapi(SR).forgetSr(SR._xapiId)
}
@ -96,7 +96,7 @@ forget.resolve = {
// -------------------------------------------------------------------
export async function connectAllPbds ({ SR }) {
export async function connectAllPbds({ SR }) {
await this.getXapi(SR).connectAllSrPbds(SR._xapiId)
}
@ -110,7 +110,7 @@ connectAllPbds.resolve = {
// -------------------------------------------------------------------
export async function disconnectAllPbds ({ SR }) {
export async function disconnectAllPbds({ SR }) {
await this.getXapi(SR).disconnectAllSrPbds(SR._xapiId)
}
@ -124,7 +124,7 @@ disconnectAllPbds.resolve = {
// -------------------------------------------------------------------
export async function createIso ({
export async function createIso({
host,
nameLabel,
nameDescription,
@ -183,7 +183,7 @@ createIso.resolve = {
// This functions creates a NFS SR
export async function createNfs ({
export async function createNfs({
host,
nameLabel,
nameDescription,
@ -245,7 +245,7 @@ createNfs.resolve = {
// This functions creates an HBA SR
export async function createHba ({ host, nameLabel, nameDescription, scsiId }) {
export async function createHba({ host, nameLabel, nameDescription, scsiId }) {
const xapi = this.getXapi(host)
const deviceConfig = {
@ -285,7 +285,7 @@ createHba.resolve = {
// This functions creates a local LVM SR
export async function createLvm ({ host, nameLabel, nameDescription, device }) {
export async function createLvm({ host, nameLabel, nameDescription, device }) {
const xapi = this.getXapi(host)
const deviceConfig = {
@ -325,7 +325,7 @@ createLvm.resolve = {
// This functions creates a local ext SR
export async function createExt ({ host, nameLabel, nameDescription, device }) {
export async function createExt({ host, nameLabel, nameDescription, device }) {
const xapi = this.getXapi(host)
const deviceConfig = {
@ -364,7 +364,7 @@ createExt.resolve = {
// This function helps to detect all NFS shares (exports) on a NFS server
// Return a table of exports with their paths and ACLs
export async function probeNfs ({ host, server }) {
export async function probeNfs({ host, server }) {
const xapi = this.getXapi(host)
const deviceConfig = {
@ -408,7 +408,7 @@ probeNfs.resolve = {
// -------------------------------------------------------------------
// This function helps to detect all HBA devices on the host
export async function probeHba ({ host }) {
export async function probeHba({ host }) {
const xapi = this.getXapi(host)
let xml
@ -452,7 +452,7 @@ probeHba.resolve = {
// This functions creates a iSCSI SR
export async function createIscsi ({
export async function createIscsi({
host,
nameLabel,
nameDescription,
@ -520,7 +520,7 @@ createIscsi.resolve = {
// This function helps to detect all iSCSI IQN on a Target (iSCSI "server")
// Return a table of IQN or empty table if no iSCSI connection to the target
export async function probeIscsiIqns ({
export async function probeIscsiIqns({
host,
target: targetIp,
port,
@ -590,7 +590,7 @@ probeIscsiIqns.resolve = {
// This function helps to detect all iSCSI ID and LUNs on a Target
// It will return a LUN table
export async function probeIscsiLuns ({
export async function probeIscsiLuns({
host,
target: targetIp,
port,
@ -661,7 +661,7 @@ probeIscsiLuns.resolve = {
// This function helps to detect if this target already exists in XAPI
// It returns a table of SR UUID, empty if no existing connections
export async function probeIscsiExists ({
export async function probeIscsiExists({
host,
target: targetIp,
port,
@ -720,7 +720,7 @@ probeIscsiExists.resolve = {
// This function helps to detect if this HBA already exists in XAPI
// It returns a table of SR UUID, empty if no existing connections
export async function probeHbaExists ({ host, scsiId }) {
export async function probeHbaExists({ host, scsiId }) {
const xapi = this.getXapi(host)
const deviceConfig = {
@ -748,7 +748,7 @@ probeHbaExists.resolve = {
// This function helps to detect if this NFS SR already exists in XAPI
// It returns a table of SR UUID, empty if no existing connections
export async function probeNfsExists ({ host, server, serverPath }) {
export async function probeNfsExists({ host, server, serverPath }) {
const xapi = this.getXapi(host)
const deviceConfig = {
@ -783,7 +783,7 @@ probeNfsExists.resolve = {
// -------------------------------------------------------------------
// This function helps to reattach a forgotten NFS/iSCSI SR
export async function reattach ({
export async function reattach({
host,
uuid,
nameLabel,
@ -826,7 +826,7 @@ reattach.resolve = {
// -------------------------------------------------------------------
// This function helps to reattach a forgotten ISO SR
export async function reattachIso ({
export async function reattachIso({
host,
uuid,
nameLabel,
@ -868,7 +868,7 @@ reattachIso.resolve = {
// -------------------------------------------------------------------
export function getUnhealthyVdiChainsLength ({ sr }) {
export function getUnhealthyVdiChainsLength({ sr }) {
return this.getXapi(sr).getUnhealthyVdiChainsLength(sr)
}
@ -882,7 +882,7 @@ getUnhealthyVdiChainsLength.resolve = {
// -------------------------------------------------------------------
export function stats ({ sr, granularity }) {
export function stats({ sr, granularity }) {
return this.getXapiSrStats(sr._xapiId, granularity)
}

View File

@ -7,7 +7,7 @@ import { version as xoServerVersion } from '../../package.json'
// ===================================================================
export function getMethodsInfo () {
export function getMethodsInfo() {
const methods = {}
forEach(this.apiMethods, (method, name) => {
@ -40,14 +40,14 @@ getVersion.description = 'API version (unstable)'
// -------------------------------------------------------------------
export function listMethods () {
export function listMethods() {
return getKeys(this.apiMethods)
}
listMethods.description = 'returns the name of all available API methods'
// -------------------------------------------------------------------
export function methodSignature ({ method: name }) {
export function methodSignature({ method: name }) {
const method = this.apiMethods[name]
if (!method) {

View File

@ -1,4 +1,4 @@
export async function add ({ tag, object }) {
export async function add({ tag, object }) {
await this.getXapi(object).addTag(object._xapiId, tag)
}
@ -15,7 +15,7 @@ add.params = {
// -------------------------------------------------------------------
export async function remove ({ tag, object }) {
export async function remove({ tag, object }) {
await this.getXapi(object).removeTag(object._xapiId, tag)
}

View File

@ -1,4 +1,4 @@
export async function cancel ({ task }) {
export async function cancel({ task }) {
await this.getXapi(task).call('task.cancel', task._xapiRef)
}
@ -12,7 +12,7 @@ cancel.resolve = {
// -------------------------------------------------------------------
export async function destroy ({ task }) {
export async function destroy({ task }) {
await this.getXapi(task).call('task.destroy', task._xapiRef)
}

View File

@ -1,4 +1,4 @@
export function getPermissionsForUser ({ userId }) {
export function getPermissionsForUser({ userId }) {
return this.getPermissionsForUser(userId)
}
@ -12,7 +12,7 @@ getPermissionsForUser.params = {
// -------------------------------------------------------------------
export function hasPermission ({ userId, objectId, permission }) {
export function hasPermission({ userId, objectId, permission }) {
return this.hasPermissions(userId, [[objectId, permission]])
}
@ -32,7 +32,7 @@ hasPermission.params = {
// -------------------------------------------------------------------
export function wait ({ duration, returnValue }) {
export function wait({ duration, returnValue }) {
return new Promise(resolve => {
setTimeout(() => {
resolve(returnValue)
@ -48,7 +48,7 @@ wait.params = {
// -------------------------------------------------------------------
export async function copyVm ({ vm, sr }) {
export async function copyVm({ vm, sr }) {
const srcXapi = this.getXapi(vm)
const tgtXapi = this.getXapi(sr)

View File

@ -1,6 +1,6 @@
// TODO: Prevent token connections from creating tokens.
// TODO: Token permission.
export async function create ({ expiresIn }) {
export async function create({ expiresIn }) {
return (await this.createAuthenticationToken({
expiresIn,
userId: this.session.get('user_id'),
@ -21,7 +21,7 @@ create.permission = '' // sign in
// -------------------------------------------------------------------
// TODO: an user should be able to delete its own tokens.
async function delete_ ({ token: id }) {
async function delete_({ token: id }) {
await this.deleteAuthenticationToken(id)
}

View File

@ -3,7 +3,7 @@ import { getUserPublicProperties, mapToArray } from '../utils'
// ===================================================================
export async function create ({ email, password, permission }) {
export async function create({ email, password, permission }) {
return (await this.createUser({ email, password, permission })).id
}
@ -20,7 +20,7 @@ create.params = {
// -------------------------------------------------------------------
// Deletes an existing user.
async function delete_ ({ id }) {
async function delete_({ id }) {
if (id === this.session.get('user_id')) {
throw invalidParameters('a user cannot delete itself')
}
@ -43,7 +43,7 @@ delete_.params = {
// TODO: remove this function when users are integrated to the main
// collection.
export async function getAll () {
export async function getAll() {
// Retrieves the users.
const users = await this.getAllUsers()
@ -57,7 +57,7 @@ getAll.permission = 'admin'
// -------------------------------------------------------------------
export async function set ({ id, email, password, permission, preferences }) {
export async function set({ id, email, password, permission, preferences }) {
const isAdmin = this.user && this.user.permission === 'admin'
if (isAdmin) {
if (permission && id === this.session.get('user_id')) {
@ -86,7 +86,7 @@ set.params = {
// -------------------------------------------------------------------
export async function changePassword ({ oldPassword, newPassword }) {
export async function changePassword({ oldPassword, newPassword }) {
const id = this.session.get('user_id')
await this.changeUserPassword(id, oldPassword, newPassword)
}

View File

@ -1,6 +1,6 @@
// FIXME: too low level, should be removed.
async function delete_ ({ vbd }) {
async function delete_({ vbd }) {
await this.getXapi(vbd).deleteVbd(vbd)
}
@ -16,7 +16,7 @@ export { delete_ as delete }
// -------------------------------------------------------------------
export async function disconnect ({ vbd }) {
export async function disconnect({ vbd }) {
const xapi = this.getXapi(vbd)
await xapi.disconnectVbd(vbd._xapiRef)
}
@ -31,7 +31,7 @@ disconnect.resolve = {
// -------------------------------------------------------------------
export async function connect ({ vbd }) {
export async function connect({ vbd }) {
const xapi = this.getXapi(vbd)
await xapi.connectVbd(vbd._xapiRef)
}
@ -46,7 +46,7 @@ connect.resolve = {
// -------------------------------------------------------------------
export async function set ({ position, vbd }) {
export async function set({ position, vbd }) {
if (position !== undefined) {
const xapi = this.getXapi(vbd)
await xapi.call('VBD.set_userdevice', vbd._xapiRef, String(position))
@ -66,7 +66,7 @@ set.resolve = {
// -------------------------------------------------------------------
export async function setBootable ({ vbd, bootable }) {
export async function setBootable({ vbd, bootable }) {
const xapi = this.getXapi(vbd)
await xapi.call('VBD.set_bootable', vbd._xapiRef, bootable)

View File

@ -7,7 +7,7 @@ import { parseSize } from '../utils'
// ====================================================================
export async function delete_ ({ vdi }) {
export async function delete_({ vdi }) {
const resourceSet = reduce(
vdi.$VBDs,
(resourceSet, vbd) =>
@ -35,7 +35,7 @@ export { delete_ as delete }
// -------------------------------------------------------------------
// FIXME: human readable strings should be handled.
export async function set (params) {
export async function set(params) {
const { vdi } = params
const xapi = this.getXapi(vdi)
const ref = vdi._xapiRef
@ -109,7 +109,7 @@ set.resolve = {
// -------------------------------------------------------------------
export async function migrate ({ vdi, sr }) {
export async function migrate({ vdi, sr }) {
const xapi = this.getXapi(vdi)
await xapi.moveVdi(vdi._xapiRef, sr._xapiRef)

View File

@ -5,7 +5,7 @@ import { diffItems } from '../utils'
// ===================================================================
// TODO: move into vm and rename to removeInterface
async function delete_ ({ vif }) {
async function delete_({ vif }) {
this.allocIpAddresses(
vif.id,
null,
@ -27,7 +27,7 @@ delete_.resolve = {
// -------------------------------------------------------------------
// TODO: move into vm and rename to disconnectInterface
export async function disconnect ({ vif }) {
export async function disconnect({ vif }) {
// TODO: check if VIF is attached before
await this.getXapi(vif).disconnectVif(vif._xapiId)
}
@ -42,7 +42,7 @@ disconnect.resolve = {
// -------------------------------------------------------------------
// TODO: move into vm and rename to connectInterface
export async function connect ({ vif }) {
export async function connect({ vif }) {
// TODO: check if VIF is attached before
await this.getXapi(vif).connectVif(vif._xapiId)
}
@ -57,7 +57,7 @@ connect.resolve = {
// -------------------------------------------------------------------
export async function set ({
export async function set({
vif,
network,
mac,

View File

@ -3,7 +3,7 @@ import { forEach } from 'lodash'
// ===================================================================
export function clean () {
export function clean() {
return this.clean()
}
@ -11,7 +11,7 @@ clean.permission = 'admin'
// -------------------------------------------------------------------
export async function exportConfig () {
export async function exportConfig() {
return {
$getFrom: await this.registerHttpRequest(
(req, res) => {
@ -31,7 +31,7 @@ exportConfig.permission = 'admin'
// -------------------------------------------------------------------
function handleGetAllObjects (req, res, { filter, limit }) {
function handleGetAllObjects(req, res, { filter, limit }) {
forEach(this.getObjects({ filter, limit }), object => {
res.write(JSON.stringify(object))
res.write('\n')
@ -39,7 +39,7 @@ function handleGetAllObjects (req, res, { filter, limit }) {
res.end()
}
export function getAllObjects ({ filter, limit, ndjson = false }) {
export function getAllObjects({ filter, limit, ndjson = false }) {
return ndjson
? this.registerHttpRequest(handleGetAllObjects, { filter, limit }).then(
$getFrom => ({ $getFrom })
@ -57,7 +57,7 @@ getAllObjects.params = {
// -------------------------------------------------------------------
export async function importConfig () {
export async function importConfig() {
return {
$sendTo: await this.registerHttpRequest(async (req, res) => {
await this.importConfig(JSON.parse(await getStream.buffer(req)))

View File

@ -6,7 +6,7 @@ import { isArray, isObject, map } from './utils'
// ===================================================================
export class ModelAlreadyExists extends BaseError {
constructor (id) {
constructor(id) {
super('this model already exists: ' + id)
}
}
@ -15,12 +15,12 @@ export class ModelAlreadyExists extends BaseError {
export default class Collection extends EventEmitter {
// Default value for Model.
get Model () {
get Model() {
return Model
}
// Make this property writable.
set Model (Model) {
set Model(Model) {
Object.defineProperty(this, 'Model', {
configurable: true,
enumerale: true,
@ -29,7 +29,7 @@ export default class Collection extends EventEmitter {
})
}
async add (models, opts) {
async add(models, opts) {
const array = isArray(models)
if (!array) {
models = [models]
@ -48,7 +48,7 @@ export default class Collection extends EventEmitter {
return array ? models : new this.Model(models[0])
}
async first (properties) {
async first(properties) {
if (!isObject(properties)) {
properties = properties !== undefined ? { id: properties } : {}
}
@ -57,7 +57,7 @@ export default class Collection extends EventEmitter {
return model && new this.Model(model)
}
async get (properties) {
async get(properties) {
if (!isObject(properties)) {
properties = properties !== undefined ? { id: properties } : {}
}
@ -65,7 +65,7 @@ export default class Collection extends EventEmitter {
return /* await */ this._get(properties)
}
async remove (ids) {
async remove(ids) {
if (!isArray(ids)) {
ids = [ids]
}
@ -76,7 +76,7 @@ export default class Collection extends EventEmitter {
return true
}
async update (models) {
async update(models) {
const array = isArray(models)
if (!isArray(models)) {
models = [models]
@ -113,34 +113,34 @@ export default class Collection extends EventEmitter {
// Methods to override in implementations.
_add () {
_add() {
throw new Error('not implemented')
}
_get () {
_get() {
throw new Error('not implemented')
}
_remove () {
_remove() {
throw new Error('not implemented')
}
_update () {
_update() {
throw new Error('not implemented')
}
// Methods which may be overridden in implementations.
count (properties) {
count(properties) {
return this.get(properties).get('count')
}
exists (properties) {
exists(properties) {
/* jshint eqnull: true */
return this.first(properties).then(model => model !== undefined)
}
async _first (properties) {
async _first(properties) {
const models = await this.get(properties)
return models.length ? models[0] : undefined

View File

@ -35,7 +35,7 @@ import Collection, { ModelAlreadyExists } from '../collection'
const VERSION = '20170905'
export default class Redis extends Collection {
constructor ({ connection, indexes = [], prefix, uri }) {
constructor({ connection, indexes = [], prefix, uri }) {
super()
this.indexes = indexes
@ -64,7 +64,7 @@ export default class Redis extends Collection {
::ignoreErrors()
}
rebuildIndexes () {
rebuildIndexes() {
const { indexes, prefix, redis } = this
if (indexes.length === 0) {
@ -95,7 +95,7 @@ export default class Redis extends Collection {
)
}
_extract (ids) {
_extract(ids) {
const prefix = this.prefix + ':'
const { redis } = this
@ -117,7 +117,7 @@ export default class Redis extends Collection {
).then(() => models)
}
_add (models, { replace = false } = {}) {
_add(models, { replace = false } = {}) {
// TODO: remove “replace” which is a temporary measure, implement
// “set()” instead.
@ -186,7 +186,7 @@ export default class Redis extends Collection {
)
}
_get (properties) {
_get(properties) {
const { prefix, redis } = this
if (isEmpty(properties)) {
@ -217,7 +217,7 @@ export default class Redis extends Collection {
return redis.sinter(...keys).then(ids => this._extract(ids))
}
_remove (ids) {
_remove(ids) {
if (isEmpty(ids)) {
return
}
@ -255,7 +255,7 @@ export default class Redis extends Collection {
)
}
_update (models) {
_update(models) {
return this._add(models, { replace: true })
}
}

View File

@ -5,14 +5,14 @@ import { noop } from './utils'
// ===================================================================
export default class Connection extends EventEmitter {
constructor () {
constructor() {
super()
this._data = { __proto__: null }
}
// Close the connection.
close () {
close() {
// Prevent errors when the connection is closed more than once.
this.close = noop
@ -20,7 +20,7 @@ export default class Connection extends EventEmitter {
}
// Gets the value for this key.
get (key, defaultValue) {
get(key, defaultValue) {
const { _data: data } = this
if (key in data) {
@ -35,16 +35,16 @@ export default class Connection extends EventEmitter {
}
// Checks whether there is a value for this key.
has (key) {
has(key) {
return key in this._data
}
// Sets the value for this key.
set (key, value) {
set(key, value) {
this._data[key] = value
}
unset (key) {
unset(key) {
delete this._data[key]
}
}

View File

@ -10,7 +10,7 @@ export const debounce = duration => (target, name, descriptor) => {
// current object.
const s = Symbol(`debounced ${name} data`)
function debounced () {
function debounced() {
const data =
this[s] ||
(this[s] = {

View File

@ -9,7 +9,7 @@ describe('debounce()', () => {
class Foo {
@debounce(10)
foo () {
foo() {
++i
}
}

Some files were not shown because too many files have changed in this diff Show More