From cc4ab944284ba0c1d7e1bbee477623f18549e6ba Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 11 Dec 2018 10:37:46 +0100 Subject: [PATCH] chore: reformat with Prettier --- @xen-orchestra/babel-config/index.js | 4 +- @xen-orchestra/cr-seed-cli/index.js | 4 +- @xen-orchestra/cron/src/index.js | 16 +-- @xen-orchestra/defined/src/index.js | 2 +- @xen-orchestra/emit-async/src/index.js | 2 +- @xen-orchestra/log/src/configure.js | 8 +- @xen-orchestra/mixin/src/index.js | 2 +- packages/complex-matcher/src/index.js | 100 +++++++------- packages/vhd-cli/src/commands/merge.js | 4 +- packages/vhd-cli/src/commands/synthetize.js | 2 +- packages/vhd-cli/src/index.js | 2 +- packages/vhd-lib/merge.integ.spec.js | 8 +- .../vhd-lib/src/_computeGeometryForSize.js | 2 +- packages/vhd-lib/src/_createFooterHeader.js | 4 +- packages/vhd-lib/src/_structs.js | 2 +- packages/vhd-lib/src/chain.js | 2 +- packages/vhd-lib/src/createContentStream.js | 2 +- .../vhd-lib/src/createReadableRawStream.js | 8 +- .../vhd-lib/src/createReadableSparseStream.js | 24 ++-- packages/vhd-lib/src/createSyntheticStream.js | 12 +- packages/vhd-lib/src/merge.js | 2 +- packages/vhd-lib/src/vhd.js | 50 +++---- packages/xapi-explore-sr/src/index.js | 2 +- .../xen-api/src/_replaceSensitiveValues.js | 4 +- packages/xen-api/src/cli.js | 2 +- packages/xen-api/src/transports/auto.js | 2 +- packages/xo-cli/src/config.js | 22 ++-- packages/xo-cli/src/index.js | 48 +++---- packages/xo-collection/src/clear-object.js | 2 +- packages/xo-collection/src/collection.js | 68 +++++----- packages/xo-collection/src/collection.spec.js | 86 ++++++------ packages/xo-collection/src/index.js | 18 +-- packages/xo-collection/src/index.spec.js | 20 +-- packages/xo-collection/src/is-empty.js | 2 +- packages/xo-collection/src/is-object.js | 2 +- packages/xo-collection/src/not-implemented.js | 2 +- packages/xo-collection/src/unique-index.js | 16 +-- .../xo-collection/src/unique-index.spec.js | 16 +-- packages/xo-collection/src/view.example.js | 2 +- packages/xo-collection/src/view.js | 18 +-- packages/xo-common/src/api-errors.js | 4 +- packages/xo-lib/example.js | 26 ++-- packages/xo-lib/src/index.js | 12 +- packages/xo-server-auth-github/src/index.js | 6 +- packages/xo-server-auth-google/src/index.js | 6 +- packages/xo-server-auth-ldap/src/index.js | 12 +- .../xo-server-auth-ldap/src/prompt-schema.js | 2 +- packages/xo-server-auth-saml/src/index.js | 6 +- .../xo-server-backup-reports/src/index.js | 18 +-- packages/xo-server-cloud/src/index.js | 18 +-- .../src/density-plan.js | 10 +- packages/xo-server-load-balancer/src/index.js | 12 +- .../src/performance-plan.js | 8 +- packages/xo-server-load-balancer/src/plan.js | 28 ++-- packages/xo-server-perf-alert/src/index.js | 26 ++-- packages/xo-server-test-plugin/index.js | 10 +- .../xo-server-transport-email/src/index.js | 12 +- .../xo-server-transport-nagios/src/index.js | 18 +-- .../xo-server-transport-slack/src/index.js | 12 +- .../xo-server-transport-xmpp/src/index.js | 10 +- packages/xo-server-usage-report/src/index.js | 54 ++++---- packages/xo-server/better-stacks.js | 4 +- packages/xo-server/src/api/acl.js | 8 +- packages/xo-server/src/api/backup-ng.js | 30 ++--- packages/xo-server/src/api/backup.js | 10 +- packages/xo-server/src/api/cloud-config.js | 8 +- packages/xo-server/src/api/disk.js | 12 +- packages/xo-server/src/api/docker.js | 14 +- packages/xo-server/src/api/group.js | 14 +- packages/xo-server/src/api/ip-pool.js | 8 +- packages/xo-server/src/api/job.js | 14 +- packages/xo-server/src/api/log.js | 4 +- packages/xo-server/src/api/message.js | 2 +- packages/xo-server/src/api/network.js | 10 +- packages/xo-server/src/api/pbd.js | 6 +- packages/xo-server/src/api/pif.js | 14 +- packages/xo-server/src/api/plugin.js | 16 +-- packages/xo-server/src/api/pool.js | 22 ++-- packages/xo-server/src/api/remote.js | 14 +- packages/xo-server/src/api/resource-set.js | 24 ++-- packages/xo-server/src/api/role.js | 2 +- packages/xo-server/src/api/schedule.js | 10 +- packages/xo-server/src/api/server.js | 12 +- packages/xo-server/src/api/session.js | 6 +- packages/xo-server/src/api/sr.js | 46 +++---- packages/xo-server/src/api/system.js | 6 +- packages/xo-server/src/api/tag.js | 4 +- packages/xo-server/src/api/task.js | 4 +- packages/xo-server/src/api/test.js | 8 +- packages/xo-server/src/api/token.js | 4 +- packages/xo-server/src/api/user.js | 10 +- packages/xo-server/src/api/vbd.js | 10 +- packages/xo-server/src/api/vdi.js | 6 +- packages/xo-server/src/api/vif.js | 8 +- packages/xo-server/src/api/xo.js | 10 +- packages/xo-server/src/collection.js | 30 ++--- packages/xo-server/src/collection/redis.js | 14 +- packages/xo-server/src/connection.js | 12 +- packages/xo-server/src/decorators.js | 2 +- packages/xo-server/src/decorators.spec.js | 2 +- packages/xo-server/src/fatfs-buffer.js | 2 +- packages/xo-server/src/glob-matcher.js | 6 +- packages/xo-server/src/logs-cli.js | 8 +- packages/xo-server/src/math.spec.js | 8 +- packages/xo-server/src/model.js | 8 +- packages/xo-server/src/models/acl.js | 10 +- packages/xo-server/src/models/group.js | 8 +- .../xo-server/src/models/plugin-metadata.js | 8 +- packages/xo-server/src/models/remote.js | 4 +- packages/xo-server/src/models/server.js | 6 +- packages/xo-server/src/models/user.js | 8 +- packages/xo-server/src/proxy-console.js | 2 +- packages/xo-server/src/utils.spec.js | 38 +++--- packages/xo-server/src/xapi-object-to-xo.js | 56 ++++---- packages/xo-server/src/xapi-stats.js | 22 ++-- packages/xo-server/src/xapi/mixins/gpu.js | 4 +- .../xo-server/src/xapi/mixins/networking.js | 16 +-- .../xo-server/src/xapi/mixins/patching.js | 54 ++++---- packages/xo-server/src/xapi/mixins/storage.js | 24 ++-- packages/xo-server/src/xapi/utils.js | 10 +- packages/xo-server/src/xo-mixins/acls.js | 26 ++-- .../xo-server/src/xo-mixins/authentication.js | 18 +-- .../src/xo-mixins/backups-ng-logs.js | 2 +- .../src/xo-mixins/backups-ng/index.js | 38 +++--- packages/xo-server/src/xo-mixins/backups.js | 50 +++---- .../xo-server/src/xo-mixins/cloud-configs.js | 14 +- .../src/xo-mixins/config-management.js | 8 +- packages/xo-server/src/xo-mixins/hooks.js | 4 +- packages/xo-server/src/xo-mixins/http.js | 4 +- packages/xo-server/src/xo-mixins/ip-pools.js | 26 ++-- .../src/xo-mixins/jobs/execute-call.js | 12 +- .../src/xo-mixins/jobs/execute-call.spec.js | 4 +- .../xo-server/src/xo-mixins/jobs/index.js | 28 ++-- .../xo-server/src/xo-mixins/logs/index.js | 8 +- .../src/xo-mixins/logs/loggers/abstract.js | 2 +- .../src/xo-mixins/logs/loggers/leveldb.js | 10 +- packages/xo-server/src/xo-mixins/plugins.js | 28 ++-- packages/xo-server/src/xo-mixins/remotes.js | 20 +-- .../xo-server/src/xo-mixins/resource-sets.js | 46 +++---- .../xo-server/src/xo-mixins/scheduling.js | 18 +-- packages/xo-server/src/xo-mixins/store.js | 6 +- packages/xo-server/src/xo-mixins/subjects.js | 42 +++--- .../xo-server/src/xo-mixins/workers/index.js | 4 +- .../xo-server/src/xo-mixins/workers/worker.js | 2 +- packages/xo-server/src/xo.js | 30 ++--- packages/xo-vmdk-to-vhd/src/index.js | 2 +- packages/xo-vmdk-to-vhd/src/virtual-buffer.js | 6 +- packages/xo-vmdk-to-vhd/src/vmdk-read.js | 24 ++-- .../src/vmdk-to-vhd.integ.spec.js | 2 +- packages/xo-web/gulpfile.js | 56 ++++---- packages/xo-web/src/common/action-button.js | 8 +- packages/xo-web/src/common/base-component.js | 8 +- packages/xo-web/src/common/collapse.js | 2 +- packages/xo-web/src/common/combobox.js | 4 +- packages/xo-web/src/common/d3-utils.js | 2 +- packages/xo-web/src/common/debug.js | 6 +- packages/xo-web/src/common/dropzone/index.js | 2 +- packages/xo-web/src/common/editable/index.js | 42 +++--- packages/xo-web/src/common/form/index.js | 24 ++-- packages/xo-web/src/common/form/select.js | 10 +- packages/xo-web/src/common/form/toggle.js | 2 +- packages/xo-web/src/common/home-tags.js | 2 +- .../xo-web/src/common/hosts-patches-table.js | 12 +- packages/xo-web/src/common/intl/index.js | 9 +- packages/xo-web/src/common/invoke.js | 2 +- packages/xo-web/src/common/ip-utils.js | 6 +- packages/xo-web/src/common/iso-device.js | 2 +- .../common/json-schema-input/array-input.js | 2 +- .../common/json-schema-input/boolean-input.js | 2 +- .../common/json-schema-input/enum-input.js | 2 +- .../common/json-schema-input/generic-input.js | 2 +- .../common/json-schema-input/integer-input.js | 2 +- .../common/json-schema-input/number-input.js | 2 +- .../common/json-schema-input/object-input.js | 2 +- .../common/json-schema-input/string-input.js | 2 +- packages/xo-web/src/common/link.js | 2 +- packages/xo-web/src/common/modal.js | 20 +-- packages/xo-web/src/common/notification.js | 8 +- packages/xo-web/src/common/object-name.js | 2 +- packages/xo-web/src/common/pagination.js | 4 +- packages/xo-web/src/common/react-novnc.js | 16 +-- .../xo-web/src/common/resource-set-quotas.js | 2 +- packages/xo-web/src/common/scheduling.js | 14 +- packages/xo-web/src/common/select-files.js | 2 +- packages/xo-web/src/common/select-objects.js | 122 +++++++++++------- packages/xo-web/src/common/selectors.js | 2 +- packages/xo-web/src/common/shortcuts.js | 6 +- .../xo-web/src/common/smart-backup/preview.js | 7 +- packages/xo-web/src/common/store/actions.js | 2 +- packages/xo-web/src/common/tags.js | 4 +- packages/xo-web/src/common/timezone-picker.js | 10 +- .../xo-web/src/common/tooltip/get-position.js | 2 +- packages/xo-web/src/common/tooltip/index.js | 22 ++-- packages/xo-web/src/common/user-error.js | 2 +- packages/xo-web/src/common/wizard/index.js | 4 +- .../xo-highlevel-object-input.js | 2 +- .../xo-json-schema-input/xo-host-input.js | 2 +- .../xo-json-schema-input/xo-pool-input.js | 2 +- .../xo-json-schema-input/xo-remote-input.js | 2 +- .../xo-json-schema-input/xo-role-input.js | 2 +- .../xo-json-schema-input/xo-snapshot-input.js | 2 +- .../xo-json-schema-input/xo-sr-input.js | 2 +- .../xo-json-schema-input/xo-subject-input.js | 2 +- .../xo-json-schema-input/xo-tag-input.js | 2 +- .../xo-json-schema-input/xo-vdi-input.js | 2 +- .../xo-json-schema-input/xo-vm-input.js | 2 +- .../xo-web/src/common/xo-parallel-chart.js | 10 +- .../xo-web/src/common/xo-week-charts/index.js | 22 ++-- .../src/common/xo-week-heatmap/index.js | 8 +- .../src/common/xo/add-host-modal/index.js | 4 +- .../common/xo/add-user-filter-modal/index.js | 4 +- .../xo/choose-sr-for-each-vdis-modal/index.js | 67 +++++----- .../src/common/xo/copy-vm-modal/index.js | 4 +- .../src/common/xo/copy-vms-modal/index.js | 6 +- .../xo/create-bonded-network-modal/index.js | 6 +- .../common/xo/create-network-modal/index.js | 4 +- .../src/common/xo/import-vdi-modal/index.js | 4 +- .../xo/install-pool-patches-modal/index.js | 26 ++-- .../src/common/xo/migrate-vm-modal/index.js | 60 +++++---- .../src/common/xo/migrate-vms-modal/index.js | 24 +++- .../src/common/xo/new-ssh-key-modal/index.js | 4 +- .../common/xo/revert-snapshot-modal/index.js | 4 +- .../xo/update-xosan-packs-modal/index.js | 6 +- packages/xo-web/src/common/xoa-updater.js | 48 +++---- packages/xo-web/src/xo-app/about/index.js | 4 +- .../backup-ng/file-restore-legacy/index.js | 2 +- .../file-restore-legacy/restore-file-modal.js | 4 +- .../xo-app/backup-ng/file-restore/index.js | 4 +- .../file-restore/restore-file-modal.js | 4 +- .../src/xo-app/backup-ng/health/index.js | 2 +- packages/xo-web/src/xo-app/backup-ng/index.js | 2 +- .../src/xo-app/backup-ng/new/smart-backup.js | 6 +- .../xo-app/backup-ng/restore-legacy/index.js | 10 +- .../restore/delete-backups-modal-body.js | 4 +- .../src/xo-app/backup-ng/restore/index.js | 4 +- .../restore/restore-backups-modal-body.js | 8 +- .../xo-web/src/xo-app/backup/edit/index.js | 4 +- .../xo-web/src/xo-app/backup/new/index.js | 4 +- .../src/xo-app/backup/overview/index.js | 2 +- .../src/xo-app/dashboard/overview/index.js | 64 ++++----- .../src/xo-app/dashboard/stats/index.js | 6 +- .../xo-app/dashboard/visualizations/index.js | 2 +- packages/xo-web/src/xo-app/home/mini-stats.js | 6 +- packages/xo-web/src/xo-app/home/pool-item.js | 17 ++- packages/xo-web/src/xo-app/home/sr-item.js | 7 +- .../xo-web/src/xo-app/home/template-item.js | 2 +- packages/xo-web/src/xo-app/home/vm-item.js | 4 +- packages/xo-web/src/xo-app/host/index.js | 51 +++++--- .../xo-web/src/xo-app/host/tab-advanced.js | 7 +- .../xo-web/src/xo-app/host/tab-console.js | 2 +- packages/xo-web/src/xo-app/host/tab-logs.js | 4 +- .../xo-web/src/xo-app/host/tab-network.js | 16 +-- .../xo-web/src/xo-app/host/tab-patches.js | 6 +- packages/xo-web/src/xo-app/host/tab-stats.js | 14 +- .../xo-web/src/xo-app/host/tab-storage.js | 40 +++--- packages/xo-web/src/xo-app/index.js | 6 +- .../xo-web/src/xo-app/jobs/overview/index.js | 8 +- .../xo-web/src/xo-app/jobs/schedules/index.js | 6 +- packages/xo-web/src/xo-app/logs/index.js | 6 +- packages/xo-web/src/xo-app/menu/index.js | 13 +- packages/xo-web/src/xo-app/new/sr/index.js | 24 ++-- packages/xo-web/src/xo-app/pool/action-bar.js | 2 +- packages/xo-web/src/xo-app/pool/index.js | 28 +++- .../xo-web/src/xo-app/pool/tab-advanced.js | 4 +- packages/xo-web/src/xo-app/pool/tab-logs.js | 2 +- .../xo-web/src/xo-app/pool/tab-network.js | 25 ++-- .../xo-web/src/xo-app/pool/tab-patches.js | 2 +- packages/xo-web/src/xo-app/pool/tab-stats.js | 6 +- packages/xo-web/src/xo-app/self/helpers.js | 6 +- packages/xo-web/src/xo-app/self/index.js | 14 +- .../xo-web/src/xo-app/settings/acls/index.js | 4 +- .../src/xo-app/settings/config/index.js | 4 +- .../src/xo-app/settings/groups/index.js | 6 +- .../xo-web/src/xo-app/settings/ips/index.js | 6 +- .../xo-web/src/xo-app/settings/logs/index.js | 2 +- .../src/xo-app/settings/plugins/index.js | 6 +- .../src/xo-app/settings/servers/index.js | 2 +- .../src/xo-app/sr/add-subvolume-modal.js | 4 +- packages/xo-web/src/xo-app/sr/index.js | 23 +++- .../src/xo-app/sr/replace-brick-modal.js | 4 +- packages/xo-web/src/xo-app/sr/tab-advanced.js | 5 +- packages/xo-web/src/xo-app/sr/tab-disks.js | 9 +- packages/xo-web/src/xo-app/sr/tab-general.js | 4 +- packages/xo-web/src/xo-app/sr/tab-logs.js | 4 +- packages/xo-web/src/xo-app/sr/tab-stats.js | 8 +- packages/xo-web/src/xo-app/sr/tab-xosan.js | 8 +- packages/xo-web/src/xo-app/tasks/index.js | 21 ++- packages/xo-web/src/xo-app/user/index.js | 12 +- packages/xo-web/src/xo-app/vm/tab-console.js | 4 +- .../xo-web/src/xo-app/vm/tab-containers.js | 2 +- packages/xo-web/src/xo-app/vm/tab-general.js | 5 +- packages/xo-web/src/xo-app/vm/tab-logs.js | 2 +- packages/xo-web/src/xo-app/vm/tab-network.js | 19 +-- .../xo-web/src/xo-app/vm/tab-snapshots.js | 2 +- packages/xo-web/src/xo-app/vm/tab-stats.js | 14 +- .../xo-web/src/xo-app/xoa/licenses/index.js | 4 +- .../xo-web/src/xo-app/xoa/licenses/xosan.js | 4 +- .../src/xo-app/xosan/creation-progress.js | 10 +- .../xo-web/src/xo-app/xosan/graph/index.js | 2 +- packages/xo-web/src/xo-app/xosan/index.js | 13 +- 300 files changed, 1880 insertions(+), 1728 deletions(-) diff --git a/@xen-orchestra/babel-config/index.js b/@xen-orchestra/babel-config/index.js index 6f00cc74c..a42790afb 100644 --- a/@xen-orchestra/babel-config/index.js +++ b/@xen-orchestra/babel-config/index.js @@ -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 = {}) diff --git a/@xen-orchestra/cr-seed-cli/index.js b/@xen-orchestra/cr-seed-cli/index.js index f45fae714..61d672cec 100755 --- a/@xen-orchestra/cr-seed-cli/index.js +++ b/@xen-orchestra/cr-seed-cli/index.js @@ -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( diff --git a/@xen-orchestra/cron/src/index.js b/@xen-orchestra/cron/src/index.js index 1d1f4efee..1bfdcb349 100644 --- a/@xen-orchestra/cron/src/index.js +++ b/@xen-orchestra/cron/src/index.js @@ -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) diff --git a/@xen-orchestra/defined/src/index.js b/@xen-orchestra/defined/src/index.js index a2c34e03d..45fbe3863 100644 --- a/@xen-orchestra/defined/src/index.js +++ b/@xen-orchestra/defined/src/index.js @@ -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) { diff --git a/@xen-orchestra/emit-async/src/index.js b/@xen-orchestra/emit-async/src/index.js index 177dff6c9..15e05fa9a 100644 --- a/@xen-orchestra/emit-async/src/index.js +++ b/@xen-orchestra/emit-async/src/index.js @@ -1,4 +1,4 @@ -export default function emitAsync (event) { +export default function emitAsync(event) { let opts let i = 1 diff --git a/@xen-orchestra/log/src/configure.js b/@xen-orchestra/log/src/configure.js index c2bd3f496..b4c005042 100644 --- a/@xen-orchestra/log/src/configure.js +++ b/@xen-orchestra/log/src/configure.js @@ -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 diff --git a/@xen-orchestra/mixin/src/index.js b/@xen-orchestra/mixin/src/index.js index 3d945dd07..602d430a3 100644 --- a/@xen-orchestra/mixin/src/index.js +++ b/@xen-orchestra/mixin/src/index.js @@ -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) { diff --git a/packages/complex-matcher/src/index.js b/packages/complex-matcher/src/index.js index c7449d352..4f815c10d 100644 --- a/packages/complex-matcher/src/index.js +++ b/packages/complex-matcher/src/index.js @@ -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) { diff --git a/packages/vhd-cli/src/commands/merge.js b/packages/vhd-cli/src/commands/merge.js index db319585e..4a68a0f0c 100644 --- a/packages/vhd-cli/src/commands/merge.js +++ b/packages/vhd-cli/src/commands/merge.js @@ -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} ` } @@ -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: diff --git a/packages/vhd-cli/src/commands/synthetize.js b/packages/vhd-cli/src/commands/synthetize.js index ee3c2c8f2..01c27398f 100644 --- a/packages/vhd-cli/src/commands/synthetize.js +++ b/packages/vhd-cli/src/commands/synthetize.js @@ -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} ` } diff --git a/packages/vhd-cli/src/index.js b/packages/vhd-cli/src/index.js index 7e1950c00..4abf5886a 100755 --- a/packages/vhd-cli/src/index.js +++ b/packages/vhd-cli/src/index.js @@ -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' } diff --git a/packages/vhd-lib/merge.integ.spec.js b/packages/vhd-lib/merge.integ.spec.js index 361b8df19..93a236cb4 100644 --- a/packages/vhd-lib/merge.integ.spec.js +++ b/packages/vhd-lib/merge.integ.spec.js @@ -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]) } diff --git a/packages/vhd-lib/src/_computeGeometryForSize.js b/packages/vhd-lib/src/_computeGeometryForSize.js index de6aa251e..48262ec17 100644 --- a/packages/vhd-lib/src/_computeGeometryForSize.js +++ b/packages/vhd-lib/src/_computeGeometryForSize.js @@ -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 diff --git a/packages/vhd-lib/src/_createFooterHeader.js b/packages/vhd-lib/src/_createFooterHeader.js index 416f6e455..ba5ed8193 100644 --- a/packages/vhd-lib/src/_createFooterHeader.js +++ b/packages/vhd-lib/src/_createFooterHeader.js @@ -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 diff --git a/packages/vhd-lib/src/_structs.js b/packages/vhd-lib/src/_structs.js index 8f53d6a85..43d537eae 100644 --- a/packages/vhd-lib/src/_structs.js +++ b/packages/vhd-lib/src/_structs.js @@ -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 diff --git a/packages/vhd-lib/src/chain.js b/packages/vhd-lib/src/chain.js index a77d38238..3f545e7f8 100644 --- a/packages/vhd-lib/src/chain.js +++ b/packages/vhd-lib/src/chain.js @@ -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, diff --git a/packages/vhd-lib/src/createContentStream.js b/packages/vhd-lib/src/createContentStream.js index bf4afc053..91ab7671d 100644 --- a/packages/vhd-lib/src/createContentStream.js +++ b/packages/vhd-lib/src/createContentStream.js @@ -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) diff --git a/packages/vhd-lib/src/createReadableRawStream.js b/packages/vhd-lib/src/createReadableRawStream.js index 2e84371c3..ff8baf056 100644 --- a/packages/vhd-lib/src/createReadableRawStream.js +++ b/packages/vhd-lib/src/createReadableRawStream.js @@ -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 }) diff --git a/packages/vhd-lib/src/createReadableSparseStream.js b/packages/vhd-lib/src/createReadableSparseStream.js index 4ef742d06..e0fc93797 100644 --- a/packages/vhd-lib/src/createReadableSparseStream.js +++ b/packages/vhd-lib/src/createReadableSparseStream.js @@ -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()) diff --git a/packages/vhd-lib/src/createSyntheticStream.js b/packages/vhd-lib/src/createSyntheticStream.js index 81960d4ff..c79995e09 100644 --- a/packages/vhd-lib/src/createSyntheticStream.js +++ b/packages/vhd-lib/src/createSyntheticStream.js @@ -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 { diff --git a/packages/vhd-lib/src/merge.js b/packages/vhd-lib/src/merge.js index 12595ad05..c31e6a713 100644 --- a/packages/vhd-lib/src/merge.js +++ b/packages/vhd-lib/src/merge.js @@ -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, diff --git a/packages/vhd-lib/src/vhd.js b/packages/vhd-lib/src/vhd.js index 8266fcbd9..4546aa4d4 100644 --- a/packages/vhd-lib/src/vhd.js +++ b/packages/vhd-lib/src/vhd.js @@ -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') diff --git a/packages/xapi-explore-sr/src/index.js b/packages/xapi-explore-sr/src/index.js index f9d87a9f3..516cf2ed9 100755 --- a/packages/xapi-explore-sr/src/index.js +++ b/packages/xapi-explore-sr/src/index.js @@ -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) diff --git a/packages/xen-api/src/_replaceSensitiveValues.js b/packages/xen-api/src/_replaceSensitiveValues.js index 637cb1000..c235c1a0b 100644 --- a/packages/xen-api/src/_replaceSensitiveValues.js +++ b/packages/xen-api/src/_replaceSensitiveValues.js @@ -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 } diff --git a/packages/xen-api/src/cli.js b/packages/xen-api/src/cli.js index 2bd6aa916..aff116f91 100755 --- a/packages/xen-api/src/cli.js +++ b/packages/xen-api/src/cli.js @@ -15,7 +15,7 @@ import { createClient } from './' // =================================================================== -function askPassword (prompt = 'Password: ') { +function askPassword(prompt = 'Password: ') { if (prompt) { process.stdout.write(prompt) } diff --git a/packages/xen-api/src/transports/auto.js b/packages/xen-api/src/transports/auto.js index 845e9987d..7785b0a6e 100644 --- a/packages/xen-api/src/transports/auto.js +++ b/packages/xen-api/src/transports/auto.js @@ -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 diff --git a/packages/xo-cli/src/config.js b/packages/xo-cli/src/config.js index 2f6575c18..e096d3438 100644 --- a/packages/xo-cli/src/config.js +++ b/packages/xo-cli/src/config.js @@ -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) diff --git a/packages/xo-cli/src/index.js b/packages/xo-cli/src/index.js index d0bc33d59..8346d0deb 100755 --- a/packages/xo-cli/src/index.js +++ b/packages/xo-cli/src/index.js @@ -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') } diff --git a/packages/xo-collection/src/clear-object.js b/packages/xo-collection/src/clear-object.js index 0250f65c2..21b603ecf 100644 --- a/packages/xo-collection/src/clear-object.js +++ b/packages/xo-collection/src/clear-object.js @@ -1,4 +1,4 @@ -export default function clearObject (object) { +export default function clearObject(object) { for (const key in object) { delete object[key] } diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index f64335331..8d5ca21db 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -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() diff --git a/packages/xo-collection/src/collection.spec.js b/packages/xo-collection/src/collection.spec.js index deb681437..dcb87add3 100644 --- a/packages/xo-collection/src/collection.spec.js +++ b/packages/xo-collection/src/collection.spec.js @@ -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) }) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 8e1e62e48..eb89d5589 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -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) { diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js index 8cfdfda67..f4519d665 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -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(() => { diff --git a/packages/xo-collection/src/is-empty.js b/packages/xo-collection/src/is-empty.js index 9e688ac7c..cad76524c 100644 --- a/packages/xo-collection/src/is-empty.js +++ b/packages/xo-collection/src/is-empty.js @@ -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 diff --git a/packages/xo-collection/src/is-object.js b/packages/xo-collection/src/is-object.js index 1453776e7..1fbba1e27 100644 --- a/packages/xo-collection/src/is-object.js +++ b/packages/xo-collection/src/is-object.js @@ -1,3 +1,3 @@ -export default function isObject (value) { +export default function isObject(value) { return value !== null && typeof value === 'object' } diff --git a/packages/xo-collection/src/not-implemented.js b/packages/xo-collection/src/not-implemented.js index ddb70c6a1..916b44bd1 100644 --- a/packages/xo-collection/src/not-implemented.js +++ b/packages/xo-collection/src/not-implemented.js @@ -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') } } diff --git a/packages/xo-collection/src/unique-index.js b/packages/xo-collection/src/unique-index.js index e3a9114b7..812179d9e 100644 --- a/packages/xo-collection/src/unique-index.js +++ b/packages/xo-collection/src/unique-index.js @@ -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) { diff --git a/packages/xo-collection/src/unique-index.spec.js b/packages/xo-collection/src/unique-index.spec.js index ed4ab3b2d..602310db7 100644 --- a/packages/xo-collection/src/unique-index.spec.js +++ b/packages/xo-collection/src/unique-index.spec.js @@ -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, diff --git a/packages/xo-collection/src/view.example.js b/packages/xo-collection/src/view.example.js index 2b45345fe..a5c42daf4 100644 --- a/packages/xo-collection/src/view.example.js +++ b/packages/xo-collection/src/view.example.js @@ -43,7 +43,7 @@ activeUsers.on('remove', users => { }) // Make some changes in the future. -setTimeout(function () { +setTimeout(function() { console.log('-----') users.set({ diff --git a/packages/xo-collection/src/view.js b/packages/xo-collection/src/view.js index 821ca9f25..c2bda8def 100644 --- a/packages/xo-collection/src/view.js +++ b/packages/xo-collection/src/view.js @@ -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) diff --git a/packages/xo-common/src/api-errors.js b/packages/xo-common/src/api-errors.js index d118026f6..aba03592e 100644 --- a/packages/xo-common/src/api-errors.js +++ b/packages/xo-common/src/api-errors.js @@ -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, diff --git a/packages/xo-lib/example.js b/packages/xo-lib/example.js index 207ce8823..cd42fad21 100644 --- a/packages/xo-lib/example.js +++ b/packages/xo-lib/example.js @@ -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() }) diff --git a/packages/xo-lib/src/index.js b/packages/xo-lib/src/index.js index ac085fa8e..836ff3582 100644 --- a/packages/xo-lib/src/index.js +++ b/packages/xo-lib/src/index.js @@ -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 diff --git a/packages/xo-server-auth-github/src/index.js b/packages/xo-server-auth-github/src/index.js index 4a71a35e0..781851a91 100644 --- a/packages/xo-server-auth-github/src/index.js +++ b/packages/xo-server-auth-github/src/index.js @@ -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( diff --git a/packages/xo-server-auth-google/src/index.js b/packages/xo-server-auth-google/src/index.js index d8c099c48..e0d358a96 100644 --- a/packages/xo-server-auth-google/src/index.js +++ b/packages/xo-server-auth-google/src/index.js @@ -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 diff --git a/packages/xo-server-auth-ldap/src/index.js b/packages/xo-server-auth-ldap/src/index.js index 777a85a6f..e7a952ffa 100644 --- a/packages/xo-server-auth-ldap/src/index.js +++ b/packages/xo-server-auth-ldap/src/index.js @@ -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!') diff --git a/packages/xo-server-auth-ldap/src/prompt-schema.js b/packages/xo-server-auth-ldap/src/prompt-schema.js index a1e6cef7a..7707f2588 100644 --- a/packages/xo-server-auth-ldap/src/prompt-schema.js +++ b/packages/xo-server-auth-ldap/src/prompt-schema.js @@ -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()] diff --git a/packages/xo-server-auth-saml/src/index.js b/packages/xo-server-auth-saml/src/index.js index 3d66749bb..88aa51881 100644 --- a/packages/xo-server-auth-saml/src/index.js +++ b/packages/xo-server-auth-saml/src/index.js @@ -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( diff --git a/packages/xo-server-backup-reports/src/index.js b/packages/xo-server-backup-reports/src/index.js index 1d1022667..a53df7724 100644 --- a/packages/xo-server-backup-reports/src/index.js +++ b/packages/xo-server-backup-reports/src/index.js @@ -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) diff --git a/packages/xo-server-cloud/src/index.js b/packages/xo-server-cloud/src/index.js index c066192ad..78a80630d 100644 --- a/packages/xo-server-cloud/src/index.js +++ b/packages/xo-server-cloud/src/index.js @@ -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) { diff --git a/packages/xo-server-load-balancer/src/density-plan.js b/packages/xo-server-load-balancer/src/density-plan.js index bccf7bac4..077fb0738 100644 --- a/packages/xo-server-load-balancer/src/density-plan.js +++ b/packages/xo-server-load-balancer/src/density-plan.js @@ -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( diff --git a/packages/xo-server-load-balancer/src/index.js b/packages/xo-server-load-balancer/src/index.js index 31f3ee2f3..ff4887da0 100644 --- a/packages/xo-server-load-balancer/src/index.js +++ b/packages/xo-server-load-balancer/src/index.js @@ -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())) diff --git a/packages/xo-server-load-balancer/src/performance-plan.js b/packages/xo-server-load-balancer/src/performance-plan.js index 08f0fe06f..9723d0089 100644 --- a/packages/xo-server-load-balancer/src/performance-plan.js +++ b/packages/xo-server-load-balancer/src/performance-plan.js @@ -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) diff --git a/packages/xo-server-load-balancer/src/plan.js b/packages/xo-server-load-balancer/src/plan.js index 885bacc04..cc462e8aa 100644 --- a/packages/xo-server-load-balancer/src/plan.js +++ b/packages/xo-server-load-balancer/src/plan.js @@ -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), diff --git a/packages/xo-server-perf-alert/src/index.js b/packages/xo-server-perf-alert/src/index.js index e90da3430..74e6f1451 100644 --- a/packages/xo-server-perf-alert/src/index.js +++ b/packages/xo-server-perf-alert/src/index.js @@ -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) } diff --git a/packages/xo-server-test-plugin/index.js b/packages/xo-server-test-plugin/index.js index 4cc96140d..d946c0f88 100644 --- a/packages/xo-server-test-plugin/index.js +++ b/packages/xo-server-test-plugin/index.js @@ -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. }, diff --git a/packages/xo-server-transport-email/src/index.js b/packages/xo-server-transport-email/src/index.js index b57e1117a..a3670d76a 100644 --- a/packages/xo-server-transport-email/src/index.js +++ b/packages/xo-server-transport-email/src/index.js @@ -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, diff --git a/packages/xo-server-transport-nagios/src/index.js b/packages/xo-server-transport-nagios/src/index.js index e67306bfc..4b34a91a2 100644 --- a/packages/xo-server-transport-nagios/src/index.js +++ b/packages/xo-server-transport-nagios/src/index.js @@ -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') diff --git a/packages/xo-server-transport-slack/src/index.js b/packages/xo-server-transport-slack/src/index.js index cec681c1c..6719e4c58 100644 --- a/packages/xo-server-transport-slack/src/index.js +++ b/packages/xo-server-transport-slack/src/index.js @@ -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) } diff --git a/packages/xo-server-transport-xmpp/src/index.js b/packages/xo-server-transport-xmpp/src/index.js index 2a02bb933..6599a1252 100644 --- a/packages/xo-server-transport-xmpp/src/index.js +++ b/packages/xo-server-transport-xmpp/src/index.js @@ -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', { diff --git a/packages/xo-server-usage-report/src/index.js b/packages/xo-server-usage-report/src/index.js index 92e0f091d..d6aa9ccad 100644 --- a/packages/xo-server-usage-report/src/index.js +++ b/packages/xo-server-usage-report/src/index.js @@ -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, diff --git a/packages/xo-server/better-stacks.js b/packages/xo-server/better-stacks.js index c48101cfd..fd8b7f3dd 100644 --- a/packages/xo-server/better-stacks.js +++ b/packages/xo-server/better-stacks.js @@ -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 ( diff --git a/packages/xo-server/src/api/acl.js b/packages/xo-server/src/api/acl.js index 929f1257b..a79037e34 100644 --- a/packages/xo-server/src/api/acl.js +++ b/packages/xo-server/src/api/acl.js @@ -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) } diff --git a/packages/xo-server/src/api/backup-ng.js b/packages/xo-server/src/api/backup-ng.js index fd2a0661a..f5b6f7477 100644 --- a/packages/xo-server/src/api/backup-ng.js +++ b/packages/xo-server/src/api/backup-ng.js @@ -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) { diff --git a/packages/xo-server/src/api/backup.js b/packages/xo-server/src/api/backup.js index 79d7fa68b..896674636 100644 --- a/packages/xo-server/src/api/backup.js +++ b/packages/xo-server/src/api/backup.js @@ -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}` diff --git a/packages/xo-server/src/api/cloud-config.js b/packages/xo-server/src/api/cloud-config.js index 057ca0c41..9ef15ecda 100644 --- a/packages/xo-server/src/api/cloud-config.js +++ b/packages/xo-server/src/api/cloud-config.js @@ -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) } diff --git a/packages/xo-server/src/api/disk.js b/packages/xo-server/src/api/disk.js index 1f0eddc35..17173e8f3 100644 --- a/packages/xo-server/src/api/disk.js +++ b/packages/xo-server/src/api/disk.js @@ -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)) } diff --git a/packages/xo-server/src/api/docker.js b/packages/xo-server/src/api/docker.js index f3bcdd66d..e93c4bbbe 100644 --- a/packages/xo-server/src/api/docker.js +++ b/packages/xo-server/src/api/docker.js @@ -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) } diff --git a/packages/xo-server/src/api/group.js b/packages/xo-server/src/api/group.js index bf54aca4d..0d0d6ff6f 100644 --- a/packages/xo-server/src/api/group.js +++ b/packages/xo-server/src/api/group.js @@ -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 }) } diff --git a/packages/xo-server/src/api/ip-pool.js b/packages/xo-server/src/api/ip-pool.js index 7f195b4d9..ce3409d9c 100644 --- a/packages/xo-server/src/api/ip-pool.js +++ b/packages/xo-server/src/api/ip-pool.js @@ -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) } diff --git a/packages/xo-server/src/api/job.js b/packages/xo-server/src/api/job.js index 8447a33de..5c1e4ee1b 100644 --- a/packages/xo-server/src/api/job.js +++ b/packages/xo-server/src/api/job.js @@ -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) } diff --git a/packages/xo-server/src/api/log.js b/packages/xo-server/src/api/log.js index f495f5894..e8e09479d 100644 --- a/packages/xo-server/src/api/log.js +++ b/packages/xo-server/src/api/log.js @@ -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) } diff --git a/packages/xo-server/src/api/message.js b/packages/xo-server/src/api/message.js index a559bc39b..edad1a816 100644 --- a/packages/xo-server/src/api/message.js +++ b/packages/xo-server/src/api/message.js @@ -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 } diff --git a/packages/xo-server/src/api/network.js b/packages/xo-server/src/api/network.js index e689aa049..0af927457 100644 --- a/packages/xo-server/src/api/network.js +++ b/packages/xo-server/src/api/network.js @@ -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 } diff --git a/packages/xo-server/src/api/pbd.js b/packages/xo-server/src/api/pbd.js index 3ba4be422..4a2231d2e 100644 --- a/packages/xo-server/src/api/pbd.js +++ b/packages/xo-server/src/api/pbd.js @@ -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) } diff --git a/packages/xo-server/src/api/pif.js b/packages/xo-server/src/api/pif.js index f48c3cfad..376a49d07 100644 --- a/packages/xo-server/src/api/pif.js +++ b/packages/xo-server/src/api/pif.js @@ -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 }) } diff --git a/packages/xo-server/src/api/plugin.js b/packages/xo-server/src/api/plugin.js index 46c4af4f4..eb1dd1a4d 100644 --- a/packages/xo-server/src/api/plugin.js +++ b/packages/xo-server/src/api/plugin.js @@ -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) } diff --git a/packages/xo-server/src/api/pool.js b/packages/xo-server/src/api/pool.js index 71dd948c8..d391aa473 100644 --- a/packages/xo-server/src/api/pool.js +++ b/packages/xo-server/src/api/pool.js @@ -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, diff --git a/packages/xo-server/src/api/remote.js b/packages/xo-server/src/api/remote.js index 051776fe3..cf7a66cb0 100644 --- a/packages/xo-server/src/api/remote.js +++ b/packages/xo-server/src/api/remote.js @@ -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) } diff --git a/packages/xo-server/src/api/resource-set.js b/packages/xo-server/src/api/resource-set.js index 4a0ca5f4a..fa59b2c6c 100644 --- a/packages/xo-server/src/api/resource-set.js +++ b/packages/xo-server/src/api/resource-set.js @@ -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() } diff --git a/packages/xo-server/src/api/role.js b/packages/xo-server/src/api/role.js index 63f72df45..4e5d2643a 100644 --- a/packages/xo-server/src/api/role.js +++ b/packages/xo-server/src/api/role.js @@ -1,4 +1,4 @@ -export async function getAll () { +export async function getAll() { return /* await */ this.getRoles() } diff --git a/packages/xo-server/src/api/schedule.js b/packages/xo-server/src/api/schedule.js index 763b5ce30..4d713c1a7 100644 --- a/packages/xo-server/src/api/schedule.js +++ b/packages/xo-server/src/api/schedule.js @@ -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) } diff --git a/packages/xo-server/src/api/server.js b/packages/xo-server/src/api/server.js index 5f2162f39..a34b0a71f 100644 --- a/packages/xo-server/src/api/server.js +++ b/packages/xo-server/src/api/server.js @@ -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) } diff --git a/packages/xo-server/src/api/session.js b/packages/xo-server/src/api/session.js index a2caad4e1..52f07a779 100644 --- a/packages/xo-server/src/api/session.js +++ b/packages/xo-server/src/api/session.js @@ -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 diff --git a/packages/xo-server/src/api/sr.js b/packages/xo-server/src/api/sr.js index 8df4d31dd..7945de030 100644 --- a/packages/xo-server/src/api/sr.js +++ b/packages/xo-server/src/api/sr.js @@ -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) } diff --git a/packages/xo-server/src/api/system.js b/packages/xo-server/src/api/system.js index ad2494134..59e479c8d 100644 --- a/packages/xo-server/src/api/system.js +++ b/packages/xo-server/src/api/system.js @@ -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) { diff --git a/packages/xo-server/src/api/tag.js b/packages/xo-server/src/api/tag.js index 5a8c4cd22..279e11d2d 100644 --- a/packages/xo-server/src/api/tag.js +++ b/packages/xo-server/src/api/tag.js @@ -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) } diff --git a/packages/xo-server/src/api/task.js b/packages/xo-server/src/api/task.js index 71fe4a48c..98b0b8cd2 100644 --- a/packages/xo-server/src/api/task.js +++ b/packages/xo-server/src/api/task.js @@ -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) } diff --git a/packages/xo-server/src/api/test.js b/packages/xo-server/src/api/test.js index 15b8e5d08..9b1ec3bb8 100644 --- a/packages/xo-server/src/api/test.js +++ b/packages/xo-server/src/api/test.js @@ -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) diff --git a/packages/xo-server/src/api/token.js b/packages/xo-server/src/api/token.js index 08bf9284e..76f30de1b 100644 --- a/packages/xo-server/src/api/token.js +++ b/packages/xo-server/src/api/token.js @@ -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) } diff --git a/packages/xo-server/src/api/user.js b/packages/xo-server/src/api/user.js index c4e6fe093..f688ad997 100644 --- a/packages/xo-server/src/api/user.js +++ b/packages/xo-server/src/api/user.js @@ -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) } diff --git a/packages/xo-server/src/api/vbd.js b/packages/xo-server/src/api/vbd.js index db825a187..7f5b3ccff 100644 --- a/packages/xo-server/src/api/vbd.js +++ b/packages/xo-server/src/api/vbd.js @@ -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) diff --git a/packages/xo-server/src/api/vdi.js b/packages/xo-server/src/api/vdi.js index cb08a3b0c..31712791e 100644 --- a/packages/xo-server/src/api/vdi.js +++ b/packages/xo-server/src/api/vdi.js @@ -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) diff --git a/packages/xo-server/src/api/vif.js b/packages/xo-server/src/api/vif.js index 0b9c8a73d..533bbc352 100644 --- a/packages/xo-server/src/api/vif.js +++ b/packages/xo-server/src/api/vif.js @@ -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, diff --git a/packages/xo-server/src/api/xo.js b/packages/xo-server/src/api/xo.js index bdde3252d..8e0625e3a 100644 --- a/packages/xo-server/src/api/xo.js +++ b/packages/xo-server/src/api/xo.js @@ -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))) diff --git a/packages/xo-server/src/collection.js b/packages/xo-server/src/collection.js index a696c30cb..bb49af3e1 100644 --- a/packages/xo-server/src/collection.js +++ b/packages/xo-server/src/collection.js @@ -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 diff --git a/packages/xo-server/src/collection/redis.js b/packages/xo-server/src/collection/redis.js index 795b422bd..05161f6b9 100644 --- a/packages/xo-server/src/collection/redis.js +++ b/packages/xo-server/src/collection/redis.js @@ -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 }) } } diff --git a/packages/xo-server/src/connection.js b/packages/xo-server/src/connection.js index d98cdef75..7fedff4bd 100644 --- a/packages/xo-server/src/connection.js +++ b/packages/xo-server/src/connection.js @@ -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] } } diff --git a/packages/xo-server/src/decorators.js b/packages/xo-server/src/decorators.js index ea87c92df..d837b3901 100644 --- a/packages/xo-server/src/decorators.js +++ b/packages/xo-server/src/decorators.js @@ -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] = { diff --git a/packages/xo-server/src/decorators.spec.js b/packages/xo-server/src/decorators.spec.js index 9816d2e51..ed24794f9 100644 --- a/packages/xo-server/src/decorators.spec.js +++ b/packages/xo-server/src/decorators.spec.js @@ -9,7 +9,7 @@ describe('debounce()', () => { class Foo { @debounce(10) - foo () { + foo() { ++i } } diff --git a/packages/xo-server/src/fatfs-buffer.js b/packages/xo-server/src/fatfs-buffer.js index 8620a058d..b0356119d 100644 --- a/packages/xo-server/src/fatfs-buffer.js +++ b/packages/xo-server/src/fatfs-buffer.js @@ -23,7 +23,7 @@ const SECTOR_SIZE = 512 const TEN_MIB = 10 * 1024 * 1024 // Creates a 10MB buffer and initializes it as a FAT 16 volume. -export function init () { +export function init() { const buf = Buffer.alloc(TEN_MIB) // https://github.com/natevw/fatfs/blob/master/structs.js diff --git a/packages/xo-server/src/glob-matcher.js b/packages/xo-server/src/glob-matcher.js index 380e7a99f..b4c3ac50a 100644 --- a/packages/xo-server/src/glob-matcher.js +++ b/packages/xo-server/src/glob-matcher.js @@ -2,11 +2,11 @@ const matcher = require('micromatch').matcher -module.exports = function globMatcher (patterns, opts) { +module.exports = function globMatcher(patterns, opts) { if (!Array.isArray(patterns)) { if (patterns[0] === '!') { const m = matcher(patterns.slice(1), opts) - return function (string) { + return function(string) { return !m(string) } } else { @@ -30,7 +30,7 @@ module.exports = function globMatcher (patterns, opts) { const nNone = noneMustMatch.length const nAny = anyMustMatch.length - return function (string) { + return function(string) { let i for (i = 0; i < nNone; ++i) { diff --git a/packages/xo-server/src/logs-cli.js b/packages/xo-server/src/logs-cli.js index 917892bb9..9eb8b1df7 100644 --- a/packages/xo-server/src/logs-cli.js +++ b/packages/xo-server/src/logs-cli.js @@ -13,7 +13,7 @@ import globMatcher from './glob-matcher' // =================================================================== -async function printLogs (db, args) { +async function printLogs(db, args) { let stream = highland(db.createReadStream({ reverse: true })) if (args.since) { @@ -58,7 +58,7 @@ async function printLogs (db, args) { // =================================================================== -function helper () { +function helper() { console.error(` xo-server-logs --help, -h @@ -96,7 +96,7 @@ xo-server-logs --repair // =================================================================== -function getArgs () { +function getArgs() { const stringArgs = ['since', 'until', 'limit'] const args = parseArgs(process.argv.slice(2), { string: stringArgs, @@ -165,7 +165,7 @@ function getArgs () { // =================================================================== -export default async function main () { +export default async function main() { const args = getArgs() if (args.help) { diff --git a/packages/xo-server/src/math.spec.js b/packages/xo-server/src/math.spec.js index 88cb83a01..99923721d 100644 --- a/packages/xo-server/src/math.spec.js +++ b/packages/xo-server/src/math.spec.js @@ -4,7 +4,7 @@ import { forEach } from 'lodash' import { thunkToArray } from './utils' import { crossProduct, mergeObjects } from './math' -describe('mergeObjects', function () { +describe('mergeObjects', function() { forEach( { 'Two sets of one': [{ a: 1, b: 2 }, { a: 1 }, { b: 2 }], @@ -26,7 +26,7 @@ describe('mergeObjects', function () { }, ([resultSet, ...sets], name) => { describe(`with ${name}`, () => { - it('Assembles all given param sets in on set', function () { + it('Assembles all given param sets in on set', function() { expect(mergeObjects(sets)).toEqual(resultSet) }) }) @@ -34,7 +34,7 @@ describe('mergeObjects', function () { ) }) -describe('crossProduct', function () { +describe('crossProduct', function() { // Gives the sum of all args const addTest = args => args.reduce((prev, curr) => prev + curr, 0) // Gives the product of all args @@ -71,7 +71,7 @@ describe('crossProduct', function () { }, ([product, items, cb], name) => { describe(`with ${name}`, () => { - it('Crosses sets of values with a crossProduct callback', function () { + it('Crosses sets of values with a crossProduct callback', function() { expect(thunkToArray(crossProduct(items, cb)).sort()).toEqual( product.sort() ) diff --git a/packages/xo-server/src/model.js b/packages/xo-server/src/model.js index 1e40a5b73..f92b9e339 100644 --- a/packages/xo-server/src/model.js +++ b/packages/xo-server/src/model.js @@ -5,7 +5,7 @@ import { forEach, isEmpty, isString } from './utils' // =================================================================== export default class Model extends EventEmitter { - constructor (properties) { + constructor(properties) { super() this.properties = { ...this.default } @@ -16,18 +16,18 @@ export default class Model extends EventEmitter { } // Get a property. - get (name, def) { + get(name, def) { const value = this.properties[name] return value !== undefined ? value : def } // Check whether a property exists. - has (name) { + has(name) { return this.properties[name] !== undefined } // Set properties. - set (properties, value) { + set(properties, value) { // This method can also be used with two arguments to set a single // property. if (isString(properties)) { diff --git a/packages/xo-server/src/models/acl.js b/packages/xo-server/src/models/acl.js index 997dbc32f..977d010ff 100644 --- a/packages/xo-server/src/models/acl.js +++ b/packages/xo-server/src/models/acl.js @@ -15,11 +15,11 @@ export default class Acl extends Model {} // ------------------------------------------------------------------- export class Acls extends Collection { - get Model () { + get Model() { return Acl } - create (subject, object, action) { + create(subject, object, action) { return multiKeyHash(subject, object, action) .then( hash => @@ -33,15 +33,15 @@ export class Acls extends Collection { .then(acl => this.add(acl)) } - delete (subject, object, action) { + delete(subject, object, action) { return multiKeyHash(subject, object, action).then(hash => this.remove(hash)) } - aclExists (subject, object, action) { + aclExists(subject, object, action) { return multiKeyHash(subject, object, action).then(hash => this.exists(hash)) } - async get (properties) { + async get(properties) { const acls = await super.get(properties) // Finds all records that are missing a action and need to be updated. diff --git a/packages/xo-server/src/models/group.js b/packages/xo-server/src/models/group.js index 225705109..6bc7d6ec0 100644 --- a/packages/xo-server/src/models/group.js +++ b/packages/xo-server/src/models/group.js @@ -14,15 +14,15 @@ export default class Group extends Model {} // =================================================================== export class Groups extends Collection { - get Model () { + get Model() { return Group } - create (name) { + create(name) { return this.add(new Group({ name })) } - async save (group) { + async save(group) { // Serializes. let tmp group.users = isEmpty((tmp = group.users)) ? undefined : JSON.stringify(tmp) @@ -30,7 +30,7 @@ export class Groups extends Collection { return /* await */ this.update(group) } - async get (properties) { + async get(properties) { const groups = await super.get(properties) // Deserializes. diff --git a/packages/xo-server/src/models/plugin-metadata.js b/packages/xo-server/src/models/plugin-metadata.js index c1a1c2f44..8de8a777c 100644 --- a/packages/xo-server/src/models/plugin-metadata.js +++ b/packages/xo-server/src/models/plugin-metadata.js @@ -12,11 +12,11 @@ export default class PluginMetadata extends Model {} // =================================================================== export class PluginsMetadata extends Collection { - get Model () { + get Model() { return PluginMetadata } - async save ({ id, autoload, configuration }) { + async save({ id, autoload, configuration }) { return /* await */ this.update({ id, autoload: autoload ? 'true' : 'false', @@ -24,7 +24,7 @@ export class PluginsMetadata extends Collection { }) } - async merge (id, data) { + async merge(id, data) { const pluginMetadata = await this.first(id) if (pluginMetadata === undefined) { throw new Error('no such plugin metadata') @@ -36,7 +36,7 @@ export class PluginsMetadata extends Collection { }) } - async get (properties) { + async get(properties) { const pluginsMetadata = await super.get(properties) // Deserializes. diff --git a/packages/xo-server/src/models/remote.js b/packages/xo-server/src/models/remote.js index 6946527f1..0d7c6104c 100644 --- a/packages/xo-server/src/models/remote.js +++ b/packages/xo-server/src/models/remote.js @@ -7,11 +7,11 @@ import { forEach } from '../utils' export default class Remote extends Model {} export class Remotes extends Collection { - get Model () { + get Model() { return Remote } - async get (properties) { + async get(properties) { const remotes = await super.get(properties) forEach(remotes, remote => { remote.enabled = remote.enabled === 'true' diff --git a/packages/xo-server/src/models/server.js b/packages/xo-server/src/models/server.js index 47090ed6a..73ea6aa88 100644 --- a/packages/xo-server/src/models/server.js +++ b/packages/xo-server/src/models/server.js @@ -11,11 +11,11 @@ export default class Server extends Model {} // ------------------------------------------------------------------- export class Servers extends Collection { - get Model () { + get Model() { return Server } - async create (params) { + async create(params) { const { host } = params if (await this.exists({ host })) { @@ -25,7 +25,7 @@ export class Servers extends Collection { return /* await */ this.add(params) } - async get (properties) { + async get(properties) { const servers = await super.get(properties) // Deserializes diff --git a/packages/xo-server/src/models/user.js b/packages/xo-server/src/models/user.js index d51924a1e..0ba558be9 100644 --- a/packages/xo-server/src/models/user.js +++ b/packages/xo-server/src/models/user.js @@ -17,11 +17,11 @@ User.prototype.default = { // ------------------------------------------------------------------- export class Users extends Collection { - get Model () { + get Model() { return User } - async create (properties) { + async create(properties) { const { email } = properties // Avoid duplicates. @@ -36,7 +36,7 @@ export class Users extends Collection { return /* await */ this.add(user) } - async save (user) { + async save(user) { // Serializes. let tmp user.groups = isEmpty((tmp = user.groups)) ? undefined : JSON.stringify(tmp) @@ -47,7 +47,7 @@ export class Users extends Collection { return /* await */ this.update(user) } - async get (properties) { + async get(properties) { const users = await super.get(properties) // Deserializes diff --git a/packages/xo-server/src/proxy-console.js b/packages/xo-server/src/proxy-console.js index b723fb673..11f35c2ee 100644 --- a/packages/xo-server/src/proxy-console.js +++ b/packages/xo-server/src/proxy-console.js @@ -5,7 +5,7 @@ import { parse } from 'url' const log = createLogger('xo:proxy-console') -export default function proxyConsole (ws, vmConsole, sessionId) { +export default function proxyConsole(ws, vmConsole, sessionId) { const url = parse(vmConsole.location) let { hostname } = url if (hostname === null || hostname === '') { diff --git a/packages/xo-server/src/utils.spec.js b/packages/xo-server/src/utils.spec.js index 24eee18ce..89b75a060 100644 --- a/packages/xo-server/src/utils.spec.js +++ b/packages/xo-server/src/utils.spec.js @@ -13,18 +13,18 @@ import { // =================================================================== -describe('camelToSnakeCase()', function () { - it('converts a string from camelCase to snake_case', function () { +describe('camelToSnakeCase()', function() { + it('converts a string from camelCase to snake_case', function() { expect(camelToSnakeCase('fooBar')).toBe('foo_bar') expect(camelToSnakeCase('ipv4Allowed')).toBe('ipv4_allowed') }) - it('does not alter snake_case strings', function () { + it('does not alter snake_case strings', function() { expect(camelToSnakeCase('foo_bar')).toBe('foo_bar') expect(camelToSnakeCase('ipv4_allowed')).toBe('ipv4_allowed') }) - it('does not alter upper case letters expect those from the camelCase', function () { + it('does not alter upper case letters expect those from the camelCase', function() { expect(camelToSnakeCase('fooBar_BAZ')).toBe('foo_bar_BAZ') }) }) @@ -42,18 +42,18 @@ describe('diffItems', () => { // ------------------------------------------------------------------- -describe('ensureArray()', function () { - it('wrap the value in an array', function () { +describe('ensureArray()', function() { + it('wrap the value in an array', function() { const value = 'foo' expect(ensureArray(value)).toEqual([value]) }) - it('returns an empty array for undefined', function () { + it('returns an empty array for undefined', function() { expect(ensureArray(undefined)).toEqual([]) }) - it('returns the object itself if is already an array', function () { + it('returns the object itself if is already an array', function() { const array = ['foo', 'bar', 'baz'] expect(ensureArray(array)).toBe(array) @@ -62,15 +62,15 @@ describe('ensureArray()', function () { // ------------------------------------------------------------------- -describe('extractProperty()', function () { - it('returns the value of the property', function () { +describe('extractProperty()', function() { + it('returns the value of the property', function() { const value = {} const obj = { prop: value } expect(extractProperty(obj, 'prop')).toBe(value) }) - it('removes the property from the object', function () { + it('removes the property from the object', function() { const value = {} const obj = { prop: value } @@ -81,8 +81,8 @@ describe('extractProperty()', function () { // ------------------------------------------------------------------- -describe('formatXml()', function () { - it('formats a JS object to an XML string', function () { +describe('formatXml()', function() { + it('formats a JS object to an XML string', function() { expect( formatXml({ foo: { @@ -106,22 +106,22 @@ describe('generateToken()', () => { // ------------------------------------------------------------------- -describe('parseSize()', function () { - it('parses a human size', function () { +describe('parseSize()', function() { + it('parses a human size', function() { expect(parseSize('1G')).toBe(1e9) }) - it('returns the parameter if already a number', function () { + it('returns the parameter if already a number', function() { expect(parseSize(1e6)).toBe(1e6) }) - it('throws if the string cannot be parsed', function () { - expect(function () { + it('throws if the string cannot be parsed', function() { + expect(function() { parseSize('foo') }).toThrow() }) - it('supports the B unit as suffix', function () { + it('supports the B unit as suffix', function() { expect(parseSize('3MB')).toBe(3e6) }) }) diff --git a/packages/xo-server/src/xapi-object-to-xo.js b/packages/xo-server/src/xapi-object-to-xo.js index 1a8c5adde..86695d9a2 100644 --- a/packages/xo-server/src/xapi-object-to-xo.js +++ b/packages/xo-server/src/xapi-object-to-xo.js @@ -22,7 +22,7 @@ import { useUpdateSystem } from './xapi/utils' const { defineProperties, freeze } = Object -function link (obj, prop, idField = '$id') { +function link(obj, prop, idField = '$id') { const dynamicValue = obj[`$${prop}`] if (dynamicValue == null) { return dynamicValue // Properly handles null and undefined. @@ -41,7 +41,7 @@ function link (obj, prop, idField = '$id') { // to already be a timestamp and returned. // // If there are no data or if the timestamp is 0, returns null. -function toTimestamp (date) { +function toTimestamp(date) { if (!date) { return null } @@ -65,7 +65,7 @@ function toTimestamp (date) { // =================================================================== const TRANSFORMS = { - pool (obj) { + pool(obj) { const cpuInfo = obj.cpu_info return { default_SR: link(obj, 'default_SR'), @@ -97,7 +97,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - host (obj) { + host(obj) { const { $metrics: metrics, other_config: otherConfig, @@ -154,7 +154,7 @@ const TRANSFORMS = { logging: obj.logging, name_description: obj.name_description, name_label: obj.name_label, - memory: (function () { + memory: (function() { if (metrics) { const free = +metrics.memory_free const total = +metrics.memory_total @@ -223,7 +223,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - vm (obj, dependents) { + vm(obj, dependents) { dependents[obj.guest_metrics] = obj.$id dependents[obj.metrics] = obj.$id @@ -285,7 +285,7 @@ const TRANSFORMS = { : +obj.VCPUs_at_startup, }, current_operations: obj.current_operations, - docker: (function () { + docker: (function() { const monitor = otherConfig['xscontainer-monitor'] if (!monitor) { return @@ -314,7 +314,7 @@ const TRANSFORMS = { expNestedHvm: obj.platform['exp-nested-hvm'] === 'true', high_availability: obj.ha_restart_priority, - memory: (function () { + memory: (function() { const dynamicMin = +obj.memory_dynamic_min const dynamicMax = +obj.memory_dynamic_max const staticMin = +obj.memory_static_min @@ -398,7 +398,7 @@ const TRANSFORMS = { vm.CPUs.number = +obj.VCPUs_at_startup vm.template_info = { arch: otherConfig['install-arch'], - disks: (function () { + disks: (function() { const { disks: xml } = otherConfig let data if (!xml || !(data = parseXml(xml)).provision) { @@ -406,7 +406,7 @@ const TRANSFORMS = { } const disks = ensureArray(data.provision.disk) - forEach(disks, function normalize (disk) { + forEach(disks, function normalize(disk) { disk.bootable = disk.bootable === 'true' disk.size = +disk.size disk.SR = extractProperty(disk, 'sr') @@ -414,7 +414,7 @@ const TRANSFORMS = { return disks })(), - install_methods: (function () { + install_methods: (function() { const methods = otherConfig['install-methods'] return methods ? methods.split(',') : [] @@ -438,7 +438,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - sr (obj) { + sr(obj) { return { type: 'SR', @@ -468,7 +468,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - pbd (obj) { + pbd(obj) { return { type: 'PBD', @@ -481,7 +481,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - pif (obj) { + pif(obj) { const metrics = obj.$metrics return { @@ -512,7 +512,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - vdi (obj) { + vdi(obj) { const vdi = { type: 'VDI', @@ -540,7 +540,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - vbd (obj) { + vbd(obj) { return { type: 'VBD', @@ -557,7 +557,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - vif (obj) { + vif(obj) { return { type: 'VIF', @@ -575,7 +575,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - network (obj) { + network(obj) { return { bridge: obj.bridge, defaultIsLocked: obj.default_locking_mode === 'disabled', @@ -591,7 +591,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - message (obj) { + message(obj) { return { body: obj.body, name: obj.name, @@ -603,7 +603,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - task (obj) { + task(obj) { return { allowedOperations: obj.allowed_operations, created: toTimestamp(obj.created), @@ -621,7 +621,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - host_patch (obj) { + host_patch(obj) { return { applied: Boolean(obj.applied), time: toTimestamp(obj.timestamp_applied), @@ -633,7 +633,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - pool_patch (obj) { + pool_patch(obj) { return { id: obj.$ref, @@ -654,7 +654,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - pci (obj) { + pci(obj) { return { type: 'PCI', @@ -668,7 +668,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - pgpu (obj) { + pgpu(obj) { return { type: 'PGPU', @@ -690,7 +690,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - vgpu (obj) { + vgpu(obj) { return { type: 'vgpu', @@ -706,7 +706,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - gpu_group (obj) { + gpu_group(obj) { return { type: 'gpuGroup', @@ -724,7 +724,7 @@ const TRANSFORMS = { // ----------------------------------------------------------------- - vgpu_type (obj) { + vgpu_type(obj) { return { type: 'vgpuType', @@ -744,7 +744,7 @@ const TRANSFORMS = { // =================================================================== -export default function xapiObjectToXo (xapiObj, dependents) { +export default function xapiObjectToXo(xapiObj, dependents) { const transform = TRANSFORMS[xapiObj.$type.toLowerCase()] if (!transform) { return diff --git a/packages/xo-server/src/xapi-stats.js b/packages/xo-server/src/xapi-stats.js index 1fdfef6bd..6e6f8a79d 100644 --- a/packages/xo-server/src/xapi-stats.js +++ b/packages/xo-server/src/xapi-stats.js @@ -52,15 +52,15 @@ const RRD_POINTS_PER_STEP = { // ------------------------------------------------------------------- // Return current local timestamp in seconds -function getCurrentTimestamp () { +function getCurrentTimestamp() { return Date.now() / 1000 } -function convertNanToNull (value) { +function convertNanToNull(value) { return isNaN(value) ? null : value } -async function getServerTimestamp (xapi, hostRef) { +async function getServerTimestamp(xapi, hostRef) { const serverLocalTime = await xapi.call('host.get_servertime', hostRef) return Math.floor(parseDateTime(serverLocalTime).getTime() / 1e3) } @@ -246,14 +246,14 @@ const STATS = { // ------------------------------------------------------------------- export default class XapiStats { - constructor () { + constructor() { this._statsByObject = {} } // Execute one http request on a XenServer for get stats // Return stats (Json format) or throws got exception @limitConcurrency(3) - _getJson (xapi, host, timestamp, step) { + _getJson(xapi, host, timestamp, step) { return xapi .getResource('/rrd_updates', { host, @@ -268,7 +268,7 @@ export default class XapiStats { .then(response => response.readAll().then(JSON5.parse)) } - async _getNextTimestamp (xapi, host, step) { + async _getNextTimestamp(xapi, host, step) { const currentTimeStamp = await getServerTimestamp(xapi, host.$ref) const maxDuration = step * RRD_POINTS_PER_STEP[step] const lastTimestamp = get(this._statsByObject, [ @@ -286,7 +286,7 @@ export default class XapiStats { return lastTimestamp } - _getStats (hostUuid, step, vmUuid) { + _getStats(hostUuid, step, vmUuid) { const hostStats = this._statsByObject[hostUuid][step] // Return host stats @@ -305,7 +305,7 @@ export default class XapiStats { } } - async _getAndUpdateStats (xapi, { host, vmUuid, granularity }) { + async _getAndUpdateStats(xapi, { host, vmUuid, granularity }) { const step = granularity === undefined ? RRD_STEP_SECONDS @@ -411,14 +411,14 @@ export default class XapiStats { return this._getStats(hostUuid, step, vmUuid) } - getHostStats (xapi, hostId, granularity) { + getHostStats(xapi, hostId, granularity) { return this._getAndUpdateStats(xapi, { host: xapi.getObject(hostId), granularity, }) } - async getVmStats (xapi, vmId, granularity) { + async getVmStats(xapi, vmId, granularity) { const vm = xapi.getObject(vmId) const host = vm.$resident_on if (!host) { @@ -432,7 +432,7 @@ export default class XapiStats { }) } - async getSrStats (xapi, srId, granularity) { + async getSrStats(xapi, srId, granularity) { const sr = xapi.getObject(srId) const hostsStats = {} diff --git a/packages/xo-server/src/xapi/mixins/gpu.js b/packages/xo-server/src/xapi/mixins/gpu.js index 860551168..aec7cddc2 100644 --- a/packages/xo-server/src/xapi/mixins/gpu.js +++ b/packages/xo-server/src/xapi/mixins/gpu.js @@ -1,5 +1,5 @@ export default { - createVgpu (vm, gpuGroup, vgpuType) { + createVgpu(vm, gpuGroup, vgpuType) { // TODO: properly handle device. Can a VM have 2 vGPUS? return this.call( 'VGPU.create', @@ -10,7 +10,7 @@ export default { this.getObject(vgpuType).$ref ) }, - deleteVgpu (vgpu) { + deleteVgpu(vgpu) { return this.call('VGPU.destroy', this.getObject(vgpu).$ref) }, } diff --git a/packages/xo-server/src/xapi/mixins/networking.js b/packages/xo-server/src/xapi/mixins/networking.js index a9ccd3da0..3e3e76605 100644 --- a/packages/xo-server/src/xapi/mixins/networking.js +++ b/packages/xo-server/src/xapi/mixins/networking.js @@ -3,26 +3,26 @@ import { isEmpty } from '../../utils' import { makeEditObject } from '../utils' export default { - async _connectVif (vif) { + async _connectVif(vif) { await this.call('VIF.plug', vif.$ref) }, - async connectVif (vifId) { + async connectVif(vifId) { await this._connectVif(this.getObject(vifId)) }, - async _deleteVif (vif) { + async _deleteVif(vif) { await this.call('VIF.destroy', vif.$ref) }, - async deleteVif (vifId) { + async deleteVif(vifId) { const vif = this.getObject(vifId) if (vif.currently_attached) { await this._disconnectVif(vif) } await this._deleteVif(vif) }, - async _disconnectVif (vif) { + async _disconnectVif(vif) { await this.call('VIF.unplug_force', vif.$ref) }, - async disconnectVif (vifId) { + async disconnectVif(vifId) { await this._disconnectVif(this.getObject(vifId)) }, editVif: makeEditObject({ @@ -30,7 +30,7 @@ export default { get: true, set: [ 'ipv4Allowed', - function (value, vif) { + function(value, vif) { const lockingMode = isEmpty(value) && isEmpty(vif.ipv6_allowed) ? 'network_default' @@ -46,7 +46,7 @@ export default { get: true, set: [ 'ipv6Allowed', - function (value, vif) { + function(value, vif) { const lockingMode = isEmpty(value) && isEmpty(vif.ipv4_allowed) ? 'network_default' diff --git a/packages/xo-server/src/xapi/mixins/patching.js b/packages/xo-server/src/xapi/mixins/patching.js index 369321547..fdb0985ec 100644 --- a/packages/xo-server/src/xapi/mixins/patching.js +++ b/packages/xo-server/src/xapi/mixins/patching.js @@ -28,7 +28,7 @@ const log = createLogger('xo:xapi') export default { // FIXME: should be static @debounce(24 * 60 * 60 * 1000) - async _getXenUpdates () { + async _getXenUpdates() { const { readAll, statusCode } = await this.xo.httpRequest( 'http://updates.xensource.com/XenServer/updates.xml' ) @@ -68,7 +68,7 @@ export default { } }) - const resolveVersionPatches = function (uuids) { + const resolveVersionPatches = function(uuids) { const versionPatches = { __proto__: null } forEach(ensureArray(uuids), ({ uuid }) => { @@ -104,7 +104,7 @@ export default { // ================================================================= // Returns installed and not installed patches for a given host. - async _getPoolPatchesForHost (host) { + async _getPoolPatchesForHost(host) { const versions = (await this._getXenUpdates()).versions const hostVersions = host.software_version @@ -115,7 +115,7 @@ export default { return version ? version.patches : [] }, - _getInstalledPoolPatchesOnHost (host) { + _getInstalledPoolPatchesOnHost(host) { const installed = { __proto__: null } // platform_version < 2.1.1 @@ -131,7 +131,7 @@ export default { return installed }, - async _listMissingPoolPatchesOnHost (host) { + async _listMissingPoolPatchesOnHost(host) { const all = await this._getPoolPatchesForHost(host) const installed = this._getInstalledPoolPatchesOnHost(host) @@ -153,7 +153,7 @@ export default { return installable }, - async listMissingPoolPatchesOnHost (hostId) { + async listMissingPoolPatchesOnHost(hostId) { const host = this.getObject(hostId) // Returns an array to not break compatibility. return mapToArray( @@ -163,7 +163,7 @@ export default { ) }, - async _ejectToolsIsos (hostRef) { + async _ejectToolsIsos(hostRef) { return Promise.all( mapFilter(this.objects.all, vm => { if (vm.$type !== 'vm' || (hostRef && vm.resident_on !== hostRef)) { @@ -185,7 +185,7 @@ export default { // ----------------------------------------------------------------- - _isPoolPatchInstallableOnHost (patchUuid, host) { + _isPoolPatchInstallableOnHost(patchUuid, host) { const installed = this._getInstalledPoolPatchesOnHost(host) if (installed[patchUuid]) { @@ -205,7 +205,7 @@ export default { return installable }, - _isPoolPatchInstallableOnPool (patchUuid) { + _isPoolPatchInstallableOnPool(patchUuid) { return every( this.objects.all, obj => @@ -217,7 +217,7 @@ export default { // ----------------------------------------------------------------- // platform_version < 2.1.1 ---------------------------------------- - async uploadPoolPatch (stream, patchName) { + async uploadPoolPatch(stream, patchName) { const patchRef = await this.putResource(stream, '/pool_patch_upload', { task: this.createTask('Patch upload', patchName), }).then(extractOpaqueRef) @@ -225,7 +225,7 @@ export default { return this._getOrWaitObject(patchRef) }, - async _getOrUploadPoolPatch (uuid) { + async _getOrUploadPoolPatch(uuid) { try { return this.getObjectByUuid(uuid) } catch (error) {} @@ -257,7 +257,7 @@ export default { }, // patform_version >= 2.1.1 ---------------------------------------- - async _getUpdateVdi ($defer, patchUuid, hostId) { + async _getUpdateVdi($defer, patchUuid, hostId) { log.debug(`downloading patch ${patchUuid}`) const patchInfo = (await this._getXenUpdates()).patches[patchUuid] @@ -308,7 +308,7 @@ export default { // ----------------------------------------------------------------- // patform_version < 2.1.1 ----------------------------------------- - async _installPoolPatchOnHost (patchUuid, host) { + async _installPoolPatchOnHost(patchUuid, host) { const [patch] = await Promise.all([ this._getOrUploadPoolPatch(patchUuid), this._ejectToolsIsos(host.$ref), @@ -318,7 +318,7 @@ export default { }, // patform_version >= 2.1.1 - _installPatchUpdateOnHost: deferrable(async function ( + _installPatchUpdateOnHost: deferrable(async function( $defer, patchUuid, host @@ -341,7 +341,7 @@ export default { // ----------------------------------------------------------------- - async installPoolPatchOnHost (patchUuid, host) { + async installPoolPatchOnHost(patchUuid, host) { log.debug(`installing patch ${patchUuid}`) if (!isObject(host)) { host = this.getObject(host) @@ -355,7 +355,7 @@ export default { // ----------------------------------------------------------------- // platform_version < 2.1.1 - async _installPoolPatchOnAllHosts (patchUuid) { + async _installPoolPatchOnAllHosts(patchUuid) { const [patch] = await Promise.all([ this._getOrUploadPoolPatch(patchUuid), this._ejectToolsIsos(), @@ -365,7 +365,7 @@ export default { }, // platform_version >= 2.1.1 - _installPatchUpdateOnAllHosts: deferrable(async function ($defer, patchUuid) { + _installPatchUpdateOnAllHosts: deferrable(async function($defer, patchUuid) { await this._assertConsistentHostServerTime(this.pool.master) let [vdi] = await Promise.all([ @@ -382,7 +382,7 @@ export default { ) }), - async installPoolPatchOnAllHosts (patchUuid) { + async installPoolPatchOnAllHosts(patchUuid) { log.debug(`installing patch ${patchUuid} on all hosts`) return useUpdateSystem(this.pool.$master) @@ -393,7 +393,7 @@ export default { // ----------------------------------------------------------------- // If no host is provided, install on pool - async _installPoolPatchAndRequirements (patch, patchesByUuid, host) { + async _installPoolPatchAndRequirements(patch, patchesByUuid, host) { if ( host == null ? !this._isPoolPatchInstallableOnPool(patch.uuid) @@ -424,7 +424,7 @@ export default { : this.installPoolPatchOnHost(patch.uuid, host) }, - async installSpecificPatchesOnHost (patchNames, hostId) { + async installSpecificPatchesOnHost(patchNames, hostId) { const host = this.getObject(hostId) const missingPatches = await this._listMissingPoolPatchesOnHost(host) @@ -451,7 +451,7 @@ export default { } }, - async installAllPoolPatchesOnHost (hostId) { + async installAllPoolPatchesOnHost(hostId) { const host = this.getObject(hostId) if (host.software_version.product_brand === 'XCP-ng') { return this._xcpInstallHostUpdates(host) @@ -459,7 +459,7 @@ export default { return this._installAllPoolPatchesOnHost(host) }, - async _installAllPoolPatchesOnHost (host) { + async _installAllPoolPatchesOnHost(host) { const installableByUuid = host.license_params.sku_type !== 'free' ? pickBy(await this._listMissingPoolPatchesOnHost(host), { @@ -498,14 +498,14 @@ export default { } }, - async installAllPoolPatchesOnAllHosts () { + async installAllPoolPatchesOnAllHosts() { if (this.pool.$master.software_version.product_brand === 'XCP-ng') { return this._xcpInstallAllPoolUpdatesOnHost() } return this._installAllPoolPatchesOnAllHosts() }, - async _installAllPoolPatchesOnAllHosts () { + async _installAllPoolPatchesOnAllHosts() { const installableByUuid = assign( {}, ...(await Promise.all( @@ -550,7 +550,7 @@ export default { // ---------------------------------- // list all yum updates available for a XCP-ng host - async _xcpListHostUpdates (host) { + async _xcpListHostUpdates(host) { return JSON.parse( await this.call( 'host.call_plugin', @@ -563,7 +563,7 @@ export default { }, // install all yum updates for a XCP-ng host - async _xcpInstallHostUpdates (host) { + async _xcpInstallHostUpdates(host) { const update = await this.call( 'host.call_plugin', host.$ref, @@ -582,7 +582,7 @@ export default { }, // install all yum updates for all XCP-ng hosts in a give pool - async _xcpInstallAllPoolUpdatesOnHost () { + async _xcpInstallAllPoolUpdatesOnHost() { await asyncMap(filter(this.objects.all, { $type: 'host' }), host => this._xcpInstallHostUpdates(host) ) diff --git a/packages/xo-server/src/xapi/mixins/storage.js b/packages/xo-server/src/xapi/mixins/storage.js index 86139f8d8..91ae5bf15 100644 --- a/packages/xo-server/src/xapi/mixins/storage.js +++ b/packages/xo-server/src/xapi/mixins/storage.js @@ -6,51 +6,51 @@ import { mapToArray } from '../../utils' const log = createLogger('xo:storage') export default { - _connectAllSrPbds (sr) { + _connectAllSrPbds(sr) { return Promise.all(mapToArray(sr.$PBDs, pbd => this._plugPbd(pbd))) }, - async connectAllSrPbds (id) { + async connectAllSrPbds(id) { await this._connectAllSrPbds(this.getObject(id)) }, - _disconnectAllSrPbds (sr) { + _disconnectAllSrPbds(sr) { return Promise.all(mapToArray(sr.$PBDs, pbd => this._unplugPbd(pbd))) }, - async disconnectAllSrPbds (id) { + async disconnectAllSrPbds(id) { await this._disconnectAllSrPbds(this.getObject(id)) }, - async destroySr (id) { + async destroySr(id) { const sr = this.getObject(id) await this._disconnectAllSrPbds(sr) await this.call('SR.destroy', sr.$ref) }, - async forgetSr (id) { + async forgetSr(id) { const sr = this.getObject(id) await this._disconnectAllSrPbds(sr) await this.call('SR.forget', sr.$ref) }, - _plugPbd (pbd) { + _plugPbd(pbd) { return this.call('PBD.plug', pbd.$ref) }, - async plugPbd (id) { + async plugPbd(id) { await this._plugPbd(this.getObject(id)) }, - _unplugPbd (pbd) { + _unplugPbd(pbd) { return this.call('PBD.unplug', pbd.$ref) }, - async unplugPbd (id) { + async unplugPbd(id) { await this._unplugPbd(this.getObject(id)) }, - _getUnhealthyVdiChainLength (uuid, childrenMap, cache) { + _getUnhealthyVdiChainLength(uuid, childrenMap, cache) { let length = cache[uuid] if (length === undefined) { const children = childrenMap[uuid] @@ -68,7 +68,7 @@ export default { return length }, - getUnhealthyVdiChainsLength (sr) { + getUnhealthyVdiChainsLength(sr) { const vdis = this.getObject(sr).$VDIs const unhealthyVdis = { __proto__: null } const children = groupBy(vdis, 'sm_config.vhd-parent') diff --git a/packages/xo-server/src/xapi/utils.js b/packages/xo-server/src/xapi/utils.js index 4640f1043..eb5e96a17 100644 --- a/packages/xo-server/src/xapi/utils.js +++ b/packages/xo-server/src/xapi/utils.js @@ -186,7 +186,7 @@ export const makeEditObject = specs => { if (set === true) { const prop = camelToSnakeCase(name) - return function (value) { + return function(value) { return this._set(prop, value) } } @@ -195,7 +195,7 @@ export const makeEditObject = specs => { const index = set.indexOf('.') if (index === -1) { const prop = camelToSnakeCase(set) - return function (value) { + return function(value) { return this._set(prop, value) } } @@ -203,7 +203,7 @@ export const makeEditObject = specs => { const map = set.slice(0, index) const prop = set.slice(index + 1) - return function (value, object) { + return function(value, object) { return this._updateObjectMapProperty(object, map, { [prop]: value }) } } @@ -223,7 +223,7 @@ export const makeEditObject = specs => { return set[0] } - return function (value, object) { + return function(value, object) { return Promise.all(mapToArray(set, set => set.call(this, value, object))) } } @@ -283,7 +283,7 @@ export const makeEditObject = specs => { specs[(tmp = camelToSnakeCase(name))] || (specs[tmp] = spec) }) - return async function _editObject_ (id, values, checkLimits) { + return async function _editObject_(id, values, checkLimits) { const limits = checkLimits && {} const object = this.getObject(id) diff --git a/packages/xo-server/src/xo-mixins/acls.js b/packages/xo-server/src/xo-mixins/acls.js index d003c987f..c062008c3 100644 --- a/packages/xo-server/src/xo-mixins/acls.js +++ b/packages/xo-server/src/xo-mixins/acls.js @@ -7,7 +7,7 @@ import { Acls } from '../models/acl' // =================================================================== export default class { - constructor (xo) { + constructor(xo) { this._xo = xo const aclsDb = (this._acls = new Acls({ @@ -38,7 +38,7 @@ export default class { }) } - async _getAclsForUser (userId) { + async _getAclsForUser(userId) { const user = await this._xo.getUser(userId) const { groups } = user @@ -56,7 +56,7 @@ export default class { return acls } - async addAcl (subjectId, objectId, action) { + async addAcl(subjectId, objectId, action) { try { await this._acls.create(subjectId, objectId, action) } catch (error) { @@ -66,20 +66,20 @@ export default class { } } - async removeAcl (subjectId, objectId, action) { + async removeAcl(subjectId, objectId, action) { await this._acls.delete(subjectId, objectId, action) } // TODO: remove when new collection. - async getAllAcls () { + async getAllAcls() { return this._acls.get() } - async getAclsForSubject (subjectId) { + async getAclsForSubject(subjectId) { return this._acls.get({ subject: subjectId }) } - async getPermissionsForUser (userId) { + async getPermissionsForUser(userId) { const [acls, permissionsByRole] = await Promise.all([ this._getAclsForUser(userId), this._getPermissionsByRole(), @@ -102,7 +102,7 @@ export default class { return permissions } - async checkPermissions (userId, permissions) { + async checkPermissions(userId, permissions) { const user = await this._xo.getUser(userId) // Special case for super XO administrators. @@ -117,7 +117,7 @@ export default class { ) } - async hasPermissions (userId, permissions) { + async hasPermissions(userId, permissions) { const user = await this._xo.getUser(userId) // Special case for super XO administrators. @@ -132,14 +132,14 @@ export default class { ) } - async removeAclsForObject (objectId) { + async removeAclsForObject(objectId) { const acls = this._acls await acls.remove(map(await acls.get({ object: objectId }), 'id')) } // ----------------------------------------------------------------- - async _getPermissionsByRole () { + async _getPermissionsByRole() { const roles = await this.getRoles() const permissions = { __proto__: null } @@ -150,7 +150,7 @@ export default class { } // TODO: delete when merged with the new collection. - async getRoles () { + async getRoles() { return [ { id: 'viewer', @@ -171,7 +171,7 @@ export default class { } // Returns an array of roles which have a given permission. - async getRolesForPermission (permission) { + async getRolesForPermission(permission) { const roles = [] forEach(await this.getRoles(), role => { diff --git a/packages/xo-server/src/xo-mixins/authentication.js b/packages/xo-server/src/xo-mixins/authentication.js index 2c77f6de4..2ec8cdb6f 100644 --- a/packages/xo-server/src/xo-mixins/authentication.js +++ b/packages/xo-server/src/xo-mixins/authentication.js @@ -14,7 +14,7 @@ const noSuchAuthenticationToken = id => noSuchObject(id, 'authenticationToken') const ONE_MONTH = 1e3 * 60 * 60 * 24 * 30 export default class { - constructor (xo) { + constructor(xo) { this._xo = xo // Store last failures by user to throttle tries (slow bruteforce @@ -75,15 +75,15 @@ export default class { }) } - registerAuthenticationProvider (provider) { + registerAuthenticationProvider(provider) { return this._providers.add(provider) } - unregisterAuthenticationProvider (provider) { + unregisterAuthenticationProvider(provider) { return this._providers.delete(provider) } - async _authenticateUser (credentials) { + async _authenticateUser(credentials) { for (const provider of this._providers) { try { // A provider can return: @@ -112,7 +112,7 @@ export default class { return false } - async authenticateUser (credentials) { + async authenticateUser(credentials) { // don't even attempt to authenticate with empty password const { password } = credentials if (password === '') { @@ -151,7 +151,7 @@ export default class { // ----------------------------------------------------------------- - async createAuthenticationToken ({ expiresIn = ONE_MONTH, userId }) { + async createAuthenticationToken({ expiresIn = ONE_MONTH, userId }) { const token = new Token({ id: await generateToken(), user_id: userId, @@ -166,13 +166,13 @@ export default class { return token.properties } - async deleteAuthenticationToken (id) { + async deleteAuthenticationToken(id) { if (!(await this._tokens.remove(id))) { throw noSuchAuthenticationToken(id) } } - async getAuthenticationToken (id) { + async getAuthenticationToken(id) { let token = await this._tokens.first(id) if (token === undefined) { throw noSuchAuthenticationToken(id) @@ -189,7 +189,7 @@ export default class { return token } - async getAuthenticationTokensForUser (userId) { + async getAuthenticationTokensForUser(userId) { return this._tokens.get({ user_id: userId }) } } diff --git a/packages/xo-server/src/xo-mixins/backups-ng-logs.js b/packages/xo-server/src/xo-mixins/backups-ng-logs.js index 4615783e3..6da4ea2dc 100644 --- a/packages/xo-server/src/xo-mixins/backups-ng-logs.js +++ b/packages/xo-server/src/xo-mixins/backups-ng-logs.js @@ -49,7 +49,7 @@ const taskTimeComparator = ({ start: s1, end: e1 }, { start: s2, end: e2 }) => { } export default { - async getBackupNgLogs (runId?: string) { + async getBackupNgLogs(runId?: string) { const [jobLogs, restoreLogs] = await Promise.all([ this.getLogs('jobs'), this.getLogs('restore'), diff --git a/packages/xo-server/src/xo-mixins/backups-ng/index.js b/packages/xo-server/src/xo-mixins/backups-ng/index.js index 492dc922f..63962d6e4 100644 --- a/packages/xo-server/src/xo-mixins/backups-ng/index.js +++ b/packages/xo-server/src/xo-mixins/backups-ng/index.js @@ -217,7 +217,7 @@ const importers: $Dict< ) => Promise, Mode > = { - async delta (handler, metadataFilename, metadata, xapi, sr, taskId, logger) { + async delta(handler, metadataFilename, metadata, xapi, sr, taskId, logger) { metadata = ((metadata: any): MetadataDelta) const { vdis, vhds, vm } = metadata @@ -261,7 +261,7 @@ const importers: $Dict< ) return newVm.$id }, - async full (handler, metadataFilename, metadata, xapi, sr, taskId, logger) { + async full(handler, metadataFilename, metadata, xapi, sr, taskId, logger) { metadata = ((metadata: any): MetadataFull) const xva = await handler.createReadStream( @@ -314,7 +314,7 @@ const unboxIds = (pattern?: SimpleIdPattern): string[] => { } // similar to Promise.all() but do not gather results -async function waitAll ( +async function waitAll( promises: Promise[], onRejection: Function ): Promise { @@ -388,7 +388,7 @@ const wrapTaskFn = ( opts: any, task: (...any) => Promise ): ((taskId: string, ...any) => Promise) => - async function () { + async function() { const { data, logger, message, parentId, result } = typeof opts === 'function' ? opts.apply(this, arguments) : opts @@ -511,11 +511,11 @@ export default class BackupNg { _logger: Logger _runningRestores: Set - get runningRestores () { + get runningRestores() { return this._runningRestores } - constructor (app: any) { + constructor(app: any) { this._app = app this._logger = undefined this._runningRestores = new Set() @@ -676,7 +676,7 @@ export default class BackupNg { }) } - async createBackupNgJob ( + async createBackupNgJob( props: $Diff, schedules?: $Dict<$Diff> ): Promise { @@ -700,7 +700,7 @@ export default class BackupNg { return job } - async deleteBackupNgJob (id: string): Promise { + async deleteBackupNgJob(id: string): Promise { const app = this._app const [schedules] = await Promise.all([ app.getAllSchedules(), @@ -716,7 +716,7 @@ export default class BackupNg { ]) } - async deleteVmBackupNg (id: string): Promise { + async deleteVmBackupNg(id: string): Promise { const app = this._app const { metadataFilename, remoteId } = parseVmBackupId(id) const handler = await app.getRemoteHandler(remoteId) @@ -740,7 +740,7 @@ export default class BackupNg { // ├─ task.start(message: 'transfer') // │ └─ task.end(result: { id: string, size: number }) // └─ task.end - async importVmBackupNg (id: string, srId: string): Promise { + async importVmBackupNg(id: string, srId: string): Promise { const app = this._app const { metadataFilename, remoteId } = parseVmBackupId(id) const handler = await app.getRemoteHandler(remoteId) @@ -783,7 +783,7 @@ export default class BackupNg { )() } - async listVmBackupsNg (remotes: string[]) { + async listVmBackupsNg(remotes: string[]) { const backupsByVmByRemote: $Dict<$Dict> = {} const app = this._app @@ -839,7 +839,7 @@ export default class BackupNg { return backupsByVmByRemote } - async migrateLegacyBackupJob (jobId: string) { + async migrateLegacyBackupJob(jobId: string) { const [job, schedules] = await Promise.all([ this._app.getJob(jobId, 'call'), this._app.getAllSchedules(), @@ -889,7 +889,7 @@ export default class BackupNg { // - [x] validate VHDs after exports and before imports, how? // - [x] check merge/transfert duration/size are what we want for delta @defer - async _backupVm ( + async _backupVm( $defer: any, $cancelToken: any, vmUuid: string, @@ -1408,7 +1408,7 @@ export default class BackupNg { // wait for all targets to require the stream and then starts // the real export and create the forks. const resolves = [] - function resolver (resolve) { + function resolver(resolve) { resolves.push(resolve) if (resolves.length === nTargets) { @@ -1620,7 +1620,7 @@ export default class BackupNg { ) } - async _deleteDeltaVmBackups ( + async _deleteDeltaVmBackups( handler: RemoteHandler, backups: MetadataDelta[] ): Promise { @@ -1636,7 +1636,7 @@ export default class BackupNg { }).then(sum) } - async _deleteFullVmBackups ( + async _deleteFullVmBackups( handler: RemoteHandler, backups: MetadataFull[] ): Promise { @@ -1651,7 +1651,7 @@ export default class BackupNg { // FIXME: synchronize by job/VDI, otherwise it can cause issues with the merge @defer - async _deleteVhd ( + async _deleteVhd( $defer: any, handler: RemoteHandler, path: string @@ -1697,11 +1697,11 @@ export default class BackupNg { return mergedDataSize } - async _deleteVms (xapi: Xapi, vms: Vm[]): Promise { + async _deleteVms(xapi: Xapi, vms: Vm[]): Promise { await asyncMap(vms, vm => xapi.deleteVm(vm)) } - async _listVmBackups ( + async _listVmBackups( handler: RemoteHandler, vm: Object | string, predicate?: Metadata => boolean diff --git a/packages/xo-server/src/xo-mixins/backups.js b/packages/xo-server/src/xo-mixins/backups.js index c01dad7bc..9e84e8c60 100644 --- a/packages/xo-server/src/xo-mixins/backups.js +++ b/packages/xo-server/src/xo-mixins/backups.js @@ -300,11 +300,11 @@ const mountLvmPv = (device, partition) => { // =================================================================== export default class { - constructor (xo) { + constructor(xo) { this._xo = xo } - async listRemoteBackups (remoteId) { + async listRemoteBackups(remoteId) { const handler = await this._xo.getRemoteHandler(remoteId) // List backups. (No delta) @@ -330,7 +330,7 @@ export default class { return backups } - async listVmBackups (remoteId) { + async listVmBackups(remoteId) { const handler = await this._xo.getRemoteHandler(remoteId) const backups = [] @@ -363,7 +363,7 @@ export default class { return backups } - async importVmBackup (remoteId, file, sr) { + async importVmBackup(remoteId, file, sr) { const handler = await this._xo.getRemoteHandler(remoteId) const stream = await handler.createReadStream(file) const xapi = this._xo.getXapi(sr) @@ -384,7 +384,7 @@ export default class { // ----------------------------------------------------------------- @deferrable - async deltaCopyVm ($defer, srcVm, targetSr, force = false, retention = 1) { + async deltaCopyVm($defer, srcVm, targetSr, force = false, retention = 1) { const transferStart = Date.now() const srcXapi = this._xo.getXapi(srcVm) const targetXapi = this._xo.getXapi(targetSr) @@ -478,7 +478,7 @@ export default class { // TODO: The other backup methods must use this function ! // Prerequisite: The backups array must be ordered. (old to new backups) - async _removeOldBackups (backups, handler, dir, n) { + async _removeOldBackups(backups, handler, dir, n) { if (n <= 0) { return } @@ -492,7 +492,7 @@ export default class { // ----------------------------------------------------------------- - async _listVdiBackups (handler, dir) { + async _listVdiBackups(handler, dir) { let files try { @@ -516,7 +516,7 @@ export default class { } // fix the parent UUID and filename in delta files after download from xapi or backup compression - async _chainDeltaVdiBackups ({ handler, dir }) { + async _chainDeltaVdiBackups({ handler, dir }) { const backups = await this._listVdiBackups(handler, dir) for (let i = 1; i < backups.length; i++) { const childPath = dir + '/' + backups[i] @@ -524,7 +524,7 @@ export default class { } } - async _mergeDeltaVdiBackups ({ handler, dir, retention }) { + async _mergeDeltaVdiBackups({ handler, dir, retention }) { const backups = await this._listVdiBackups(handler, dir) const i = backups.length - retention @@ -567,12 +567,12 @@ export default class { // ----------------------------------------------------------------- - async _listDeltaVmBackups (handler, dir) { + async _listDeltaVmBackups(handler, dir) { const files = await handler.list(dir) return sortBy(filter(files, isDeltaBackup)) } - async _saveDeltaVdiBackup ( + async _saveDeltaVdiBackup( xapi, { vdiParent, isFull, handler, stream, dir, retention } ) { @@ -625,7 +625,7 @@ export default class { } } - async _removeOldDeltaVmBackups (xapi, { handler, dir, retention }) { + async _removeOldDeltaVmBackups(xapi, { handler, dir, retention }) { const backups = await this._listDeltaVmBackups(handler, dir) const nOldBackups = backups.length - retention @@ -638,7 +638,7 @@ export default class { } @deferrable - async rollingDeltaVmBackup ($defer, { vm, remoteId, tag, retention }) { + async rollingDeltaVmBackup($defer, { vm, remoteId, tag, retention }) { const transferStart = Date.now() const handler = await this._xo.getRemoteHandler(remoteId) const xapi = this._xo.getXapi(vm) @@ -793,7 +793,7 @@ export default class { } } - async importDeltaVmBackup ({ sr, remoteId, filePath, mapVdisSrs = {} }) { + async importDeltaVmBackup({ sr, remoteId, filePath, mapVdisSrs = {} }) { filePath = `${filePath}${DELTA_BACKUP_EXT}` const { datetime } = parseVmBackupPath(filePath) @@ -843,13 +843,13 @@ export default class { // ----------------------------------------------------------------- - async backupVm ({ vm, remoteId, file, compress }) { + async backupVm({ vm, remoteId, file, compress }) { const handler = await this._xo.getRemoteHandler(remoteId) return this._backupVm(vm, handler, file, { compress }) } @deferrable - async _backupVm ($defer, vm, handler, file, { compress }) { + async _backupVm($defer, vm, handler, file, { compress }) { const targetStream = await handler.createOutputStream(file) $defer.onFailure.call(handler, 'unlink', file) $defer.onFailure.call(targetStream, 'close') @@ -869,7 +869,7 @@ export default class { } } - async rollingBackupVm ({ vm, remoteId, tag, retention, compress }) { + async rollingBackupVm({ vm, remoteId, tag, retention, compress }) { const transferStart = Date.now() const handler = await this._xo.getRemoteHandler(remoteId) @@ -895,7 +895,7 @@ export default class { return data } - async rollingSnapshotVm (vm, tag, retention) { + async rollingSnapshotVm(vm, tag, retention) { const xapi = this._xo.getXapi(vm) vm = xapi.getObject(vm._xapiId) @@ -927,7 +927,7 @@ export default class { await Promise.all(promises) } - _removeVms (xapi, vms) { + _removeVms(xapi, vms) { return Promise.all( mapToArray(vms, vm => // Do not consider a failure to delete an old copy as a fatal error. @@ -936,7 +936,7 @@ export default class { ) } - async rollingDrCopyVm ({ vm, sr, tag, retention, deleteOldBackupsFirst }) { + async rollingDrCopyVm({ vm, sr, tag, retention, deleteOldBackupsFirst }) { const transferStart = Date.now() tag = 'DR_' + tag const reg = new RegExp( @@ -993,7 +993,7 @@ export default class { // ----------------------------------------------------------------- - _mountVhd (remoteId, vhdPath) { + _mountVhd(remoteId, vhdPath) { return Promise.all([this._xo.getRemoteHandler(remoteId), tmpDir()]).then( ([handler, mountDir]) => { if (!handler._getRealPath) { @@ -1049,7 +1049,7 @@ export default class { ) } - _mountPartition (remoteId, vhdPath, partitionId) { + _mountPartition(remoteId, vhdPath, partitionId) { return this._mountVhd(remoteId, vhdPath).then(device => mountPartition2(device, partitionId) .then(partition => ({ @@ -1065,7 +1065,7 @@ export default class { } @deferrable - async scanDiskBackup ($defer, remoteId, vhdPath) { + async scanDiskBackup($defer, remoteId, vhdPath) { const device = await this._mountVhd(remoteId, vhdPath) $defer(device.unmount) @@ -1075,7 +1075,7 @@ export default class { } @deferrable - async scanFilesInDiskBackup ($defer, remoteId, vhdPath, partitionId, path) { + async scanFilesInDiskBackup($defer, remoteId, vhdPath, partitionId, path) { const partition = await this._mountPartition(remoteId, vhdPath, partitionId) $defer(partition.unmount) @@ -1097,7 +1097,7 @@ export default class { return entriesMap } - async fetchFilesInDiskBackup (remoteId, vhdPath, partitionId, paths) { + async fetchFilesInDiskBackup(remoteId, vhdPath, partitionId, paths) { const partition = await this._mountPartition(remoteId, vhdPath, partitionId) let i = 0 diff --git a/packages/xo-server/src/xo-mixins/cloud-configs.js b/packages/xo-server/src/xo-mixins/cloud-configs.js index cc97c8d0d..4d1c9d26f 100644 --- a/packages/xo-server/src/xo-mixins/cloud-configs.js +++ b/packages/xo-server/src/xo-mixins/cloud-configs.js @@ -11,7 +11,7 @@ type CloudConfig = {| |} class CloudConfigs extends Collection { - get (properties) { + get(properties) { return super.get(properties) } } @@ -26,7 +26,7 @@ export default class { update: Function, |} - constructor (app: any) { + constructor(app: any) { this._app = app const db = (this._db = new CloudConfigs({ connection: app._redis, @@ -43,25 +43,25 @@ export default class { ) } - createCloudConfig (cloudConfig: $Diff) { + createCloudConfig(cloudConfig: $Diff) { return this._db.add(cloudConfig).properties } - async updateCloudConfig ({ id, name, template }: $Shape) { + async updateCloudConfig({ id, name, template }: $Shape) { const cloudConfig = await this.getCloudConfig(id) patch(cloudConfig, { name, template }) return this._db.update(cloudConfig) } - deleteCloudConfig (id: string) { + deleteCloudConfig(id: string) { return this._db.remove(id) } - getAllCloudConfigs (): Promise> { + getAllCloudConfigs(): Promise> { return this._db.get() } - async getCloudConfig (id: string): Promise { + async getCloudConfig(id: string): Promise { const cloudConfig = await this._db.first(id) if (cloudConfig === undefined) { throw noSuchObject(id, 'cloud config') diff --git a/packages/xo-server/src/xo-mixins/config-management.js b/packages/xo-server/src/xo-mixins/config-management.js index 3b7f9d7c2..09f3ff513 100644 --- a/packages/xo-server/src/xo-mixins/config-management.js +++ b/packages/xo-server/src/xo-mixins/config-management.js @@ -6,13 +6,13 @@ import { pAll } from 'promise-toolbox' const log = createLogger('xo:config-management') export default class ConfigManagement { - constructor (app) { + constructor(app) { this._app = app this._depTree = new DepTree() this._managers = { __proto__: null } } - addConfigManager (id, exporter, importer, dependencies) { + addConfigManager(id, exporter, importer, dependencies) { const managers = this._managers if (id in managers) { throw new Error(`${id} is already taken`) @@ -22,11 +22,11 @@ export default class ConfigManagement { this._managers[id] = { exporter, importer } } - exportConfig () { + exportConfig() { return mapValues(this._managers, ({ exporter }, key) => exporter())::pAll() } - async importConfig (config) { + async importConfig(config) { const managers = this._managers for (const key of this._depTree.resolve()) { const manager = managers[key] diff --git a/packages/xo-server/src/xo-mixins/hooks.js b/packages/xo-server/src/xo-mixins/hooks.js index c47616e1b..1b15edff4 100644 --- a/packages/xo-server/src/xo-mixins/hooks.js +++ b/packages/xo-server/src/xo-mixins/hooks.js @@ -5,7 +5,7 @@ const log = createLogger('xo:xo-mixins:hooks') const makeSingletonHook = (hook, postEvent) => { let promise - return function () { + return function() { if (promise === undefined) { promise = runHook(this, hook) promise.then(() => { @@ -37,7 +37,7 @@ export default { // Run *clean* async listeners. // // They normalize existing data, clear invalid entries, etc. - clean () { + clean() { return runHook(this, 'clean') }, diff --git a/packages/xo-server/src/xo-mixins/http.js b/packages/xo-server/src/xo-mixins/http.js index 5ba2f1056..251db0679 100644 --- a/packages/xo-server/src/xo-mixins/http.js +++ b/packages/xo-server/src/xo-mixins/http.js @@ -4,14 +4,14 @@ import ProxyAgent from 'proxy-agent' import { firstDefined } from '../utils' export default class Http { - constructor ( + constructor( _, { httpProxy = firstDefined(process.env.http_proxy, process.env.HTTP_PROXY) } ) { this._proxy = httpProxy && new ProxyAgent(httpProxy) } - httpRequest (...args) { + httpRequest(...args) { return hrp( { agent: this._proxy, diff --git a/packages/xo-server/src/xo-mixins/ip-pools.js b/packages/xo-server/src/xo-mixins/ip-pools.js index 8f3feb381..a09357513 100644 --- a/packages/xo-server/src/xo-mixins/ip-pools.js +++ b/packages/xo-server/src/xo-mixins/ip-pools.js @@ -50,7 +50,7 @@ const _isAddressInIpPool = (address, network, ipPool) => // Note: an address cannot be in two different pools sharing a // network. export default class IpPools { - constructor (xo) { + constructor(xo) { this._store = null this._xo = xo @@ -66,7 +66,7 @@ export default class IpPools { }) } - async createIpPool ({ addresses, name, networks }) { + async createIpPool({ addresses, name, networks }) { const id = await this._generateId() await this._save({ @@ -79,7 +79,7 @@ export default class IpPools { return id } - async deleteIpPool (id) { + async deleteIpPool(id) { const store = this._store if (await store.has(id)) { @@ -99,14 +99,14 @@ export default class IpPools { throw noSuchObject(id, 'ipPool') } - _getAllIpPools (filter) { + _getAllIpPools(filter) { return streamToArray(this._store.createValueStream(), { filter, mapper: normalize, }) } - async getAllIpPools (userId) { + async getAllIpPools(userId) { let filter if (userId != null) { const user = await this._xo.getUser(userId) @@ -120,13 +120,13 @@ export default class IpPools { return this._getAllIpPools(filter) } - getIpPool (id) { + getIpPool(id) { return this._store.get(id).then(normalize, error => { throw error.notFound ? noSuchObject(id, 'ipPool') : error }) } - async _getAddressIpPool (address, network) { + async _getAddressIpPool(address, network) { const ipPools = await this._getAllIpPools(ipPool => _isAddressInIpPool(address, network, ipPool) ) @@ -136,7 +136,7 @@ export default class IpPools { // Returns a map that indicates how many IPs from each IP pool the VM uses // e.g.: { 'ipPool:abc': 3, 'ipPool:xyz': 7 } - async computeVmIpPoolsUsage (vm) { + async computeVmIpPoolsUsage(vm) { const vifs = vm.VIFs const ipPools = [] for (const vifId of vifs) { @@ -159,7 +159,7 @@ export default class IpPools { } @synchronized - allocIpAddresses (vifId, addAddresses, removeAddresses) { + allocIpAddresses(vifId, addAddresses, removeAddresses) { const updatedIpPools = {} const limits = {} @@ -231,7 +231,7 @@ export default class IpPools { }).then(allocAndSave) } - async _removeIpAddressesFromVifs (mapAddressVifs) { + async _removeIpAddressesFromVifs(mapAddressVifs) { const mapVifAddresses = {} forEach(mapAddressVifs, (vifs, address) => { forEach(vifs, vifId => { @@ -270,7 +270,7 @@ export default class IpPools { ) } - async updateIpPool (id, { addresses, name, networks, resourceSets }) { + async updateIpPool(id, { addresses, name, networks, resourceSets }) { const ipPool = await this.getIpPool(id) const previousAddresses = { ...ipPool.addresses } @@ -311,7 +311,7 @@ export default class IpPools { await this._save(ipPool) } - async _generateId () { + async _generateId() { let id do { id = generateUnsecureToken(8) @@ -319,7 +319,7 @@ export default class IpPools { return id } - _save (ipPool) { + _save(ipPool) { ipPool = normalize(ipPool) return this._store.put(ipPool.id, ipPool) } diff --git a/packages/xo-server/src/xo-mixins/jobs/execute-call.js b/packages/xo-server/src/xo-mixins/jobs/execute-call.js index 03269944b..1aa41d5f5 100644 --- a/packages/xo-server/src/xo-mixins/jobs/execute-call.js +++ b/packages/xo-server/src/xo-mixins/jobs/execute-call.js @@ -9,22 +9,22 @@ import { serializeError, thunkToArray } from '../../utils' // =================================================================== const paramsVectorActionsMap = { - extractProperties ({ mapping, value }) { + extractProperties({ mapping, value }) { return mapValues(mapping, key => value[key]) }, - crossProduct ({ items }) { + crossProduct({ items }) { return thunkToArray( crossProduct(map(items, value => resolveParamsVector.call(this, value))) ) }, - fetchObjects ({ pattern }) { + fetchObjects({ pattern }) { const objects = filter(this.getObjects(), createPredicate(pattern)) if (isEmpty(objects)) { throw new Error('no objects match this pattern') } return objects }, - map ({ collection, iteratee, paramName = 'value' }) { + map({ collection, iteratee, paramName = 'value' }) { return map(resolveParamsVector.call(this, collection), value => { return resolveParamsVector.call(this, { ...iteratee, @@ -35,7 +35,7 @@ const paramsVectorActionsMap = { set: ({ values }) => values, } -export function resolveParamsVector (paramsVector) { +export function resolveParamsVector(paramsVector) { const visitor = paramsVectorActionsMap[paramsVector.type] if (!visitor) { throw new Error(`Unsupported function '${paramsVector.type}'.`) @@ -46,7 +46,7 @@ export function resolveParamsVector (paramsVector) { // =================================================================== -export default async function executeJobCall ({ +export default async function executeJobCall({ app, job, logger, diff --git a/packages/xo-server/src/xo-mixins/jobs/execute-call.spec.js b/packages/xo-server/src/xo-mixins/jobs/execute-call.spec.js index 742a94249..8925c4205 100644 --- a/packages/xo-server/src/xo-mixins/jobs/execute-call.spec.js +++ b/packages/xo-server/src/xo-mixins/jobs/execute-call.spec.js @@ -3,7 +3,7 @@ import { forEach } from 'lodash' import { resolveParamsVector } from './execute-call' -describe('resolveParamsVector', function () { +describe('resolveParamsVector', function() { forEach( { 'cross product with three sets': [ @@ -68,7 +68,7 @@ describe('resolveParamsVector', function () { // Context. { - getObjects: function () { + getObjects: function() { return [ { id: 'vm:1', diff --git a/packages/xo-server/src/xo-mixins/jobs/index.js b/packages/xo-server/src/xo-mixins/jobs/index.js index 6f2cd0129..39be578b2 100644 --- a/packages/xo-server/src/xo-mixins/jobs/index.js +++ b/packages/xo-server/src/xo-mixins/jobs/index.js @@ -100,15 +100,15 @@ const serialize = (job: {| [string]: any |}) => { } class JobsDb extends Collection { - async create (job): Promise { + async create(job): Promise { return normalize((await this.add(serialize((job: any)))).properties) } - async save (job): Promise { + async save(job): Promise { await this.update(serialize((job: any))) } - async get (properties): Promise> { + async get(properties): Promise> { const jobs = await super.get(properties) jobs.forEach(normalize) return jobs @@ -125,11 +125,11 @@ export default class Jobs { _runningJobs: { __proto__: null, [string]: string } _runs: { __proto__: null, [string]: () => void } - get runningJobs () { + get runningJobs() { return this._runningJobs } - constructor (xo: any) { + constructor(xo: any) { this._app = xo const executors = (this._executors = { __proto__: null }) const jobsDb = (this._jobs = new JobsDb({ @@ -175,14 +175,14 @@ export default class Jobs { ) } - cancelJobRun (id: string) { + cancelJobRun(id: string) { const run = this._runs[id] if (run !== undefined) { return run.cancel() } } - async getAllJobs (type?: string): Promise> { + async getAllJobs(type?: string): Promise> { // $FlowFixMe don't know what is the problem (JFT) const jobs = await this._jobs.get() const runningJobs = this._runningJobs @@ -196,7 +196,7 @@ export default class Jobs { return result } - async getJob (id: string, type?: string): Promise { + async getJob(id: string, type?: string): Promise { let job = await this._jobs.first(id) if ( job === undefined || @@ -211,11 +211,11 @@ export default class Jobs { return job } - createJob (job: $Diff): Promise { + createJob(job: $Diff): Promise { return this._jobs.create(job) } - async updateJob (job: $Shape, merge: boolean = true) { + async updateJob(job: $Shape, merge: boolean = true) { if (merge) { const { id, ...props } = job job = await this.getJob(id) @@ -224,7 +224,7 @@ export default class Jobs { return /* await */ this._jobs.save(job) } - registerJobExecutor (type: string, executor: Executor): void { + registerJobExecutor(type: string, executor: Executor): void { const executors = this._executors if (type in executors) { throw new Error(`there is already a job executor for type ${type}`) @@ -232,7 +232,7 @@ export default class Jobs { executors[type] = executor } - async removeJob (id: string) { + async removeJob(id: string) { const promises = [this._jobs.remove(id)] ;(await this._app.getAllSchedules()).forEach(schedule => { if (schedule.jobId === id) { @@ -242,7 +242,7 @@ export default class Jobs { return Promise.all(promises) } - async _runJob (job: Job, schedule?: Schedule, data_?: any) { + async _runJob(job: Job, schedule?: Schedule, data_?: any) { const { id } = job const runningJobs = this._runningJobs @@ -337,7 +337,7 @@ export default class Jobs { } } - async runJobSequence ( + async runJobSequence( idSequence: Array, schedule?: Schedule, data?: any diff --git a/packages/xo-server/src/xo-mixins/logs/index.js b/packages/xo-server/src/xo-mixins/logs/index.js index b347d29d0..b8d13c5e3 100644 --- a/packages/xo-server/src/xo-mixins/logs/index.js +++ b/packages/xo-server/src/xo-mixins/logs/index.js @@ -3,13 +3,13 @@ import { defer, fromEvent } from 'promise-toolbox' import LevelDbLogger from './loggers/leveldb' export default class Logs { - constructor (app) { + constructor(app) { this._app = app app.on('clean', () => this._gc()) } - async _gc (keep = 2e4) { + async _gc(keep = 2e4) { const db = await this._app.getStore('logs') let count = 1 @@ -46,13 +46,13 @@ export default class Logs { return promise } - getLogger (namespace) { + getLogger(namespace) { return this._app .getStore('logs') .then(store => new LevelDbLogger(store, namespace)) } - async getLogs (namespace) { + async getLogs(namespace) { const logger = await this.getLogger(namespace) return new Promise((resolve, reject) => { diff --git a/packages/xo-server/src/xo-mixins/logs/loggers/abstract.js b/packages/xo-server/src/xo-mixins/logs/loggers/abstract.js index 15fbc354b..f2c5565a2 100644 --- a/packages/xo-server/src/xo-mixins/logs/loggers/abstract.js +++ b/packages/xo-server/src/xo-mixins/logs/loggers/abstract.js @@ -15,7 +15,7 @@ const LEVELS = [ // Create high level log methods. for (const level of LEVELS) { Object.defineProperty(AbstractLogger.prototype, level, { - value (message, data, returnPromise) { + value(message, data, returnPromise) { return this._add(level, message, data, returnPromise) }, }) diff --git a/packages/xo-server/src/xo-mixins/logs/loggers/leveldb.js b/packages/xo-server/src/xo-mixins/logs/loggers/leveldb.js index 7ace5c297..c61bcd09a 100644 --- a/packages/xo-server/src/xo-mixins/logs/loggers/leveldb.js +++ b/packages/xo-server/src/xo-mixins/logs/loggers/leveldb.js @@ -8,7 +8,7 @@ import { forEach, noop } from '../../../utils' let lastDate = 0 let increment = 0 -function generateUniqueKey (date) { +function generateUniqueKey(date) { if (date === lastDate) { return `${date}:${increment++}` } @@ -18,14 +18,14 @@ function generateUniqueKey (date) { } export default class LevelDbLogger extends AbstractLogger { - constructor (db, namespace) { + constructor(db, namespace) { super() this._db = db this._namespace = namespace } - _add (level, message, data, returnPromise = false) { + _add(level, message, data, returnPromise = false) { const time = Date.now() const log = { @@ -48,13 +48,13 @@ export default class LevelDbLogger extends AbstractLogger { return key } - createReadStream () { + createReadStream() { return highland(this._db.createReadStream()).filter( ({ value }) => value.namespace === this._namespace ) } - del (id) { + del(id) { forEach(Array.isArray(id) ? id : [id], id => { this._db.get(id).then(value => { if (value.namespace === this._namespace) { diff --git a/packages/xo-server/src/xo-mixins/plugins.js b/packages/xo-server/src/xo-mixins/plugins.js index f2071fd56..6ac05dd70 100644 --- a/packages/xo-server/src/xo-mixins/plugins.js +++ b/packages/xo-server/src/xo-mixins/plugins.js @@ -11,7 +11,7 @@ import { isFunction, mapToArray } from '../utils' const log = createLogger('xo:xo-mixins:plugins') export default class { - constructor (xo) { + constructor(xo) { this._ajv = new Ajv({ useDefaults: true, }) @@ -34,7 +34,7 @@ export default class { }) } - _getRawPlugin (id) { + _getRawPlugin(id) { const plugin = this._plugins[id] if (!plugin) { throw noSuchObject(id, 'plugin') @@ -42,12 +42,12 @@ export default class { return plugin } - async _getPluginMetadata (id) { + async _getPluginMetadata(id) { const metadata = await this._pluginsMetadata.first(id) return metadata?.properties } - async registerPlugin ( + async registerPlugin( name, instance, configurationSchema, @@ -97,7 +97,7 @@ export default class { } } - async _getPlugin (id) { + async _getPlugin(id) { const { configurationPresets, configurationSchema, @@ -128,14 +128,14 @@ export default class { } } - async getPlugins () { + async getPlugins() { return /* await */ Promise.all( mapToArray(this._plugins, ({ id }) => this._getPlugin(id)) ) } // Validate the configuration and configure the plugin instance. - async _configurePlugin (plugin, configuration) { + async _configurePlugin(plugin, configuration) { const { configurationSchema } = plugin if (!configurationSchema) { @@ -164,7 +164,7 @@ export default class { // Validate the configuration, configure the plugin instance and // save the new configuration. - async configurePlugin (id, configuration) { + async configurePlugin(id, configuration) { const plugin = this._getRawPlugin(id) const metadata = await this._getPluginMetadata() @@ -181,19 +181,19 @@ export default class { await this._pluginsMetadata.merge(id, { configuration }) } - async disablePluginAutoload (id) { + async disablePluginAutoload(id) { // TODO: handle case where autoload is already disabled. await this._pluginsMetadata.merge(id, { autoload: false }) } - async enablePluginAutoload (id) { + async enablePluginAutoload(id) { // TODO: handle case where autoload is already enabled. await this._pluginsMetadata.merge(id, { autoload: true }) } - async loadPlugin (id) { + async loadPlugin(id) { const plugin = this._getRawPlugin(id) if (plugin.loaded) { throw invalidParameters('plugin already loaded') @@ -207,7 +207,7 @@ export default class { plugin.loaded = true } - async unloadPlugin (id) { + async unloadPlugin(id) { const plugin = this._getRawPlugin(id) if (!plugin.loaded) { throw invalidParameters('plugin already unloaded') @@ -221,11 +221,11 @@ export default class { plugin.loaded = false } - async purgePluginConfiguration (id) { + async purgePluginConfiguration(id) { await this._pluginsMetadata.merge(id, { configuration: undefined }) } - async testPlugin (id, data) { + async testPlugin(id, data) { const plugin = this._getRawPlugin(id) if (!plugin.testable) { throw invalidParameters('plugin not testable') diff --git a/packages/xo-server/src/xo-mixins/remotes.js b/packages/xo-server/src/xo-mixins/remotes.js index 5c7f6f956..56ae4ac01 100644 --- a/packages/xo-server/src/xo-mixins/remotes.js +++ b/packages/xo-server/src/xo-mixins/remotes.js @@ -17,7 +17,7 @@ const obfuscateRemote = ({ url, ...remote }) => { } export default class { - constructor (xo, { remoteOptions }) { + constructor(xo, { remoteOptions }) { this._remoteOptions = remoteOptions this._remotes = new Remotes({ connection: xo._redis, @@ -52,7 +52,7 @@ export default class { }) } - async getRemoteHandler (remote) { + async getRemoteHandler(remote) { if (typeof remote === 'string') { remote = await this._getRemote(remote) } @@ -79,16 +79,16 @@ export default class { return handler } - async testRemote (remote) { + async testRemote(remote) { const handler = await this.getRemoteHandler(remote) return handler.test() } - async getAllRemotes () { + async getAllRemotes() { return (await this._remotes.get()).map(_ => obfuscateRemote(_)) } - async _getRemote (id) { + async _getRemote(id) { const remote = await this._remotes.first(id) if (remote === undefined) { throw noSuchObject(id, 'remote') @@ -96,11 +96,11 @@ export default class { return remote.properties } - getRemote (id) { + getRemote(id) { return this._getRemote(id).then(obfuscateRemote) } - async createRemote ({ name, url, options }) { + async createRemote({ name, url, options }) { const params = { name, url, @@ -114,7 +114,7 @@ export default class { return /* await */ this.updateRemote(remote.get('id'), { enabled: true }) } - updateRemote (id, { name, url, options, enabled }) { + updateRemote(id, { name, url, options, enabled }) { const handlers = this._handlers const handler = handlers[id] if (handler !== undefined) { @@ -131,7 +131,7 @@ export default class { } @synchronized() - async _updateRemote (id, { url, ...props }) { + async _updateRemote(id, { url, ...props }) { const remote = await this._getRemote(id) // url is handled separately to take care of obfuscated values @@ -144,7 +144,7 @@ export default class { return (await this._remotes.update(remote)).properties } - async removeRemote (id) { + async removeRemote(id) { const handler = this._handlers[id] if (handler !== undefined) { ignoreErrors.call(handler.forget()) diff --git a/packages/xo-server/src/xo-mixins/resource-sets.js b/packages/xo-server/src/xo-mixins/resource-sets.js index 838c71f26..031214cd2 100644 --- a/packages/xo-server/src/xo-mixins/resource-sets.js +++ b/packages/xo-server/src/xo-mixins/resource-sets.js @@ -74,7 +74,7 @@ const normalize = set => ({ // =================================================================== export default class { - constructor (xo) { + constructor(xo) { this._xo = xo this._store = null @@ -93,7 +93,7 @@ export default class { }) } - async _generateId () { + async _generateId() { let id do { id = generateUnsecureToken(8) @@ -101,11 +101,11 @@ export default class { return id } - _save (set) { + _save(set) { return this._store.put(set.id, set) } - async checkResourceSetConstraints (id, userId, objectIds) { + async checkResourceSetConstraints(id, userId, objectIds) { const set = await this.getResourceSet(id) const user = await this._xo.getUser(userId) @@ -122,14 +122,14 @@ export default class { } } - async computeVmResourcesUsage (vm) { + async computeVmResourcesUsage(vm) { return assign( computeVmResourcesUsage(this._xo.getXapi(vm).getObject(vm._xapiId)), await this._xo.computeVmIpPoolsUsage(vm) ) } - async createResourceSet ( + async createResourceSet( name, subjects = undefined, objects = undefined, @@ -149,7 +149,7 @@ export default class { return set } - async deleteResourceSet (id) { + async deleteResourceSet(id) { const store = this._store if (await store.has(id)) { @@ -159,7 +159,7 @@ export default class { throw noSuchObject(id, 'resourceSet') } - async updateResourceSet ( + async updateResourceSet( id, { name = undefined, @@ -207,7 +207,7 @@ export default class { // If userId is provided, only resource sets available to that user // will be returned. - async getAllResourceSets (userId = undefined) { + async getAllResourceSets(userId = undefined) { let filter if (userId != null) { const user = await this._xo.getUser(userId) @@ -223,7 +223,7 @@ export default class { }) } - getResourceSet (id) { + getResourceSet(id) { return this._store.get(id).then(normalize, error => { if (error.notFound) { throw noSuchObject(id, 'resourceSet') @@ -233,56 +233,56 @@ export default class { }) } - async addObjectToResourceSet (objectId, setId) { + async addObjectToResourceSet(objectId, setId) { const set = await this.getResourceSet(setId) set.objects.push(objectId) await this._save(set) } - async removeObjectFromResourceSet (objectId, setId) { + async removeObjectFromResourceSet(objectId, setId) { const set = await this.getResourceSet(setId) remove(set.objects, id => id === objectId) await this._save(set) } - async addIpPoolToResourceSet (ipPoolId, setId) { + async addIpPoolToResourceSet(ipPoolId, setId) { const set = await this.getResourceSet(setId) set.ipPools.push(ipPoolId) await this._save(set) } - async removeIpPoolFromResourceSet (ipPoolId, setId) { + async removeIpPoolFromResourceSet(ipPoolId, setId) { const set = await this.getResourceSet(setId) remove(set.ipPools, id => id === ipPoolId) await this._save(set) } - async addSubjectToResourceSet (subjectId, setId) { + async addSubjectToResourceSet(subjectId, setId) { const set = await this.getResourceSet(setId) set.subjects.push(subjectId) await this._save(set) } - async removeSubjectToResourceSet (subjectId, setId) { + async removeSubjectToResourceSet(subjectId, setId) { const set = await this.getResourceSet(setId) remove(set.subjects, id => id === subjectId) await this._save(set) } - async addLimitToResourceSet (limitId, quantity, setId) { + async addLimitToResourceSet(limitId, quantity, setId) { const set = await this.getResourceSet(setId) set.limits[limitId] = quantity await this._save(set) } - async removeLimitFromResourceSet (limitId, setId) { + async removeLimitFromResourceSet(limitId, setId) { const set = await this.getResourceSet(setId) delete set.limits[limitId] await this._save(set) } @synchronizedResourceSets - async allocateLimitsInResourceSet (limits, setId, force = false) { + async allocateLimitsInResourceSet(limits, setId, force = false) { const set = await this.getResourceSet(setId) forEach(limits, (quantity, id) => { const limit = set.limits[id] @@ -298,7 +298,7 @@ export default class { } @synchronizedResourceSets - async releaseLimitsInResourceSet (limits, setId) { + async releaseLimitsInResourceSet(limits, setId) { const set = await this.getResourceSet(setId) forEach(limits, (quantity, id) => { const limit = set.limits[id] @@ -313,7 +313,7 @@ export default class { await this._save(set) } - async recomputeResourceSetsLimits () { + async recomputeResourceSetsLimits() { const sets = keyBy(await this.getAllResourceSets(), 'id') forEach(sets, ({ limits }) => { forEach(limits, (limit, id) => { @@ -355,7 +355,7 @@ export default class { await Promise.all(mapToArray(sets, set => this._save(set))) } - async setVmResourceSet (vmId, resourceSetId) { + async setVmResourceSet(vmId, resourceSetId) { const xapi = this._xo.getXapi(vmId) const previousResourceSetId = xapi.xo.getData(vmId, 'resourceSet') @@ -398,7 +398,7 @@ export default class { } } - async shareVmResourceSet (vmId) { + async shareVmResourceSet(vmId) { const xapi = this._xo.getXapi(vmId) const resourceSetId = xapi.xo.getData(vmId, 'resourceSet') if (resourceSetId === undefined) { diff --git a/packages/xo-server/src/xo-mixins/scheduling.js b/packages/xo-server/src/xo-mixins/scheduling.js index 45e125417..6f123c9d9 100644 --- a/packages/xo-server/src/xo-mixins/scheduling.js +++ b/packages/xo-server/src/xo-mixins/scheduling.js @@ -31,7 +31,7 @@ const normalize = schedule => { } class Schedules extends Collection { - async get (properties) { + async get(properties) { const schedules = await super.get(properties) schedules.forEach(normalize) return schedules @@ -49,7 +49,7 @@ export default class Scheduling { |} _runs: { __proto__: null, [string]: () => void } - constructor (app: any) { + constructor(app: any) { this._app = app const db = (this._db = new Schedules({ @@ -92,7 +92,7 @@ export default class Scheduling { }) } - async createSchedule ({ + async createSchedule({ cron, enabled, jobId, @@ -112,7 +112,7 @@ export default class Scheduling { return schedule } - async getSchedule (id: string): Promise { + async getSchedule(id: string): Promise { const schedule = await this._db.first(id) if (schedule === undefined) { throw noSuchObject(id, 'schedule') @@ -120,16 +120,16 @@ export default class Scheduling { return schedule.properties } - async getAllSchedules (): Promise> { + async getAllSchedules(): Promise> { return this._db.get() } - async deleteSchedule (id: string) { + async deleteSchedule(id: string) { this._stop(id) await this._db.remove(id) } - async updateSchedule ({ + async updateSchedule({ cron, enabled, id, @@ -146,7 +146,7 @@ export default class Scheduling { await this._db.update(schedule) } - _start (schedule: Schedule) { + _start(schedule: Schedule) { const { id } = schedule this._stop(id) @@ -159,7 +159,7 @@ export default class Scheduling { } } - _stop (id: string) { + _stop(id: string) { const runs = this._runs if (id in runs) { runs[id]() diff --git a/packages/xo-server/src/xo-mixins/store.js b/packages/xo-server/src/xo-mixins/store.js index 508621f4b..c1884a6ff 100644 --- a/packages/xo-server/src/xo-mixins/store.js +++ b/packages/xo-server/src/xo-mixins/store.js @@ -8,7 +8,7 @@ import { forEach, isFunction, promisify } from '../utils' // =================================================================== -const _levelHas = function has (key, cb) { +const _levelHas = function has(key, cb) { if (cb) { return this.get(key, (error, value) => error ? (error.notFound ? cb(null, false) : cb(error)) : cb(null, true) @@ -51,7 +51,7 @@ const levelPromise = db => { // =================================================================== export default class { - constructor (xo) { + constructor(xo) { const dir = `${xo._config.datadir}/leveldb` this._db = ensureDir(dir).then(() => { return sublevel( @@ -62,7 +62,7 @@ export default class { }) } - getStore (namespace) { + getStore(namespace) { return this._db.then(db => levelPromise(levelHas(db.sublevel(namespace)))) } } diff --git a/packages/xo-server/src/xo-mixins/subjects.js b/packages/xo-server/src/xo-mixins/subjects.js index dee8e2388..d4d64b319 100644 --- a/packages/xo-server/src/xo-mixins/subjects.js +++ b/packages/xo-server/src/xo-mixins/subjects.js @@ -20,7 +20,7 @@ const removeFromArraySet = (set, value) => // =================================================================== export default class { - constructor (xo) { + constructor(xo) { this._xo = xo const redis = xo._redis @@ -79,7 +79,7 @@ export default class { // ----------------------------------------------------------------- - async createUser ({ name, password, ...properties }) { + async createUser({ name, password, ...properties }) { if (name) { properties.email = name } @@ -94,7 +94,7 @@ export default class { return user.properties } - async deleteUser (id) { + async deleteUser(id) { const user = await this.getUser(id) await this._users.remove(id) @@ -124,7 +124,7 @@ export default class { }) } - async updateUser ( + async updateUser( id, { // TODO: remove @@ -166,7 +166,7 @@ export default class { } // Merge this method in getUser() when plain objects. - async _getUser (id) { + async _getUser(id) { const user = await this._users.first(id) if (user === undefined) { throw noSuchObject(id, 'user') @@ -177,7 +177,7 @@ export default class { // TODO: this method will no longer be async when users are // integrated to the main collection. - async getUser (id) { + async getUser(id) { const user = (await this._getUser(id)).properties // TODO: remove when no longer the email property has been @@ -187,11 +187,11 @@ export default class { return user } - async getAllUsers () { + async getAllUsers() { return this._users.get() } - async getUserByName (username, returnNullIfMissing) { + async getUserByName(username, returnNullIfMissing) { // TODO: change `email` by `username`. const user = await this._users.first({ email: username }) if (user !== undefined) { @@ -206,7 +206,7 @@ export default class { } // Get or create a user associated with an auth provider. - async registerUser (provider, name) { + async registerUser(provider, name) { const user = await this.getUserByName(name, true) if (user) { if (user._provider !== provider) { @@ -226,7 +226,7 @@ export default class { }) } - async changeUserPassword (userId, oldPassword, newPassword) { + async changeUserPassword(userId, oldPassword, newPassword) { if (!(await this.checkUserPassword(userId, oldPassword, false))) { throw invalidCredentials() } @@ -234,7 +234,7 @@ export default class { await this.updateUser(userId, { password: newPassword }) } - async checkUserPassword (userId, password, updateIfNecessary = true) { + async checkUserPassword(userId, password, updateIfNecessary = true) { const { pw_hash: hash } = await this.getUser(userId) if (!(hash && (await verify(password, hash)))) { return false @@ -249,14 +249,14 @@ export default class { // ----------------------------------------------------------------- - async createGroup ({ name }) { + async createGroup({ name }) { // TODO: use plain objects. const group = (await this._groups.create(name)).properties return group } - async deleteGroup (id) { + async deleteGroup(id) { const group = await this.getGroup(id) await this._groups.remove(id) @@ -276,7 +276,7 @@ export default class { }) } - async updateGroup (id, { name }) { + async updateGroup(id, { name }) { const group = await this.getGroup(id) if (name) group.name = name @@ -284,7 +284,7 @@ export default class { await this._groups.save(group) } - async getGroup (id) { + async getGroup(id) { const group = await this._groups.first(id) if (group === undefined) { throw noSuchObject(id, 'group') @@ -293,11 +293,11 @@ export default class { return group.properties } - async getAllGroups () { + async getAllGroups() { return this._groups.get() } - async addUserToGroup (userId, groupId) { + async addUserToGroup(userId, groupId) { const [user, group] = await Promise.all([ this.getUser(userId), this.getGroup(groupId), @@ -309,17 +309,17 @@ export default class { await Promise.all([this._users.save(user), this._groups.save(group)]) } - async _removeUserFromGroup (userId, group) { + async _removeUserFromGroup(userId, group) { group.users = removeFromArraySet(group.users, userId) return this._groups.save(group) } - async _removeGroupFromUser (groupId, user) { + async _removeGroupFromUser(groupId, user) { user.groups = removeFromArraySet(user.groups, groupId) return this._users.save(user) } - async removeUserFromGroup (userId, groupId) { + async removeUserFromGroup(userId, groupId) { const [user, group] = await Promise.all([ this.getUser(userId), this.getGroup(groupId), @@ -331,7 +331,7 @@ export default class { ]) } - async setGroupUsers (groupId, userIds) { + async setGroupUsers(groupId, userIds) { const group = await this.getGroup(groupId) let newUsersIds = lightSet(userIds) diff --git a/packages/xo-server/src/xo-mixins/workers/index.js b/packages/xo-server/src/xo-mixins/workers/index.js index 0adc21730..51595f92a 100644 --- a/packages/xo-server/src/xo-mixins/workers/index.js +++ b/packages/xo-server/src/xo-mixins/workers/index.js @@ -1,11 +1,11 @@ import Worker from 'jest-worker' export default class Workers { - get worker () { + get worker() { return this._worker } - constructor (app, config) { + constructor(app, config) { app.on('start', () => { process.env.XO_CONFIG = JSON.stringify(config) diff --git a/packages/xo-server/src/xo-mixins/workers/worker.js b/packages/xo-server/src/xo-mixins/workers/worker.js index d2e5db567..555348001 100644 --- a/packages/xo-server/src/xo-mixins/workers/worker.js +++ b/packages/xo-server/src/xo-mixins/workers/worker.js @@ -12,7 +12,7 @@ global.Promise = require('bluebird') // $FlowFixMe const config: Object = JSON.parse(process.env.XO_CONFIG) -export function mergeVhd ( +export function mergeVhd( parentRemote: Remote, parentPath: string, childRemote: Remote, diff --git a/packages/xo-server/src/xo.js b/packages/xo-server/src/xo.js index ea3b01c66..7e2f85afe 100644 --- a/packages/xo-server/src/xo.js +++ b/packages/xo-server/src/xo.js @@ -26,7 +26,7 @@ const log = createLogger('xo:xo') @mixin(mapToArray(mixins)) export default class Xo extends EventEmitter { - constructor (config) { + constructor(config) { super() // a lot of mixins adds listener for start/stop/… events @@ -60,7 +60,7 @@ export default class Xo extends EventEmitter { // ----------------------------------------------------------------- // Returns an object from its key or UUID. - getObject (key, type) { + getObject(key, type) { const { all, indexes: { byRef }, @@ -81,7 +81,7 @@ export default class Xo extends EventEmitter { return obj } - getObjects ({ filter, limit } = {}) { + getObjects({ filter, limit } = {}) { const { all } = this._objects if (filter === undefined) { @@ -111,7 +111,7 @@ export default class Xo extends EventEmitter { // ----------------------------------------------------------------- - createUserConnection () { + createUserConnection() { const { _connections: connections } = this const connection = new Connection() @@ -127,7 +127,7 @@ export default class Xo extends EventEmitter { // ----------------------------------------------------------------- - _handleHttpRequest (req, res, next) { + _handleHttpRequest(req, res, next) { const { url } = req const { _httpRequestWatchers: watchers } = this @@ -164,10 +164,10 @@ export default class Xo extends EventEmitter { ) } - async registerHttpRequest (fn, data, { suffix = '' } = {}) { + async registerHttpRequest(fn, data, { suffix = '' } = {}) { const { _httpRequestWatchers: watchers } = this - const url = await (function generateUniqueUrl () { + const url = await (function generateUniqueUrl() { return generateToken().then(token => { const url = `/api/${token}${suffix}` @@ -183,7 +183,7 @@ export default class Xo extends EventEmitter { return url } - async registerHttpRequestHandler ( + async registerHttpRequestHandler( url, fn, { data = undefined, persistent = true } = {} @@ -201,14 +201,14 @@ export default class Xo extends EventEmitter { } } - async unregisterHttpRequestHandler (url) { + async unregisterHttpRequestHandler(url) { delete this._httpRequestWatchers[url] } // ----------------------------------------------------------------- // Plugins can use this method to expose methods directly on XO. - defineProperty (name, value, thisArg = null) { + defineProperty(name, value, thisArg = null) { if (name in this) { throw new Error(`Xo#${name} is already defined`) } @@ -216,7 +216,7 @@ export default class Xo extends EventEmitter { // For security, prevent from accessing `this`. if (isFunction(value)) { value = (value => - function () { + function() { return value.apply(thisArg, arguments) })(value) } @@ -234,7 +234,7 @@ export default class Xo extends EventEmitter { } // Convenience method to define multiple properties at once. - defineProperties (props, thisArg) { + defineProperties(props, thisArg) { const unsets = [] const unset = () => forEach(unsets, unset => unset()) @@ -256,17 +256,17 @@ export default class Xo extends EventEmitter { // // Some should be forwarded to connected clients. // Some should be persistently saved. - _watchObjects () { + _watchObjects() { const { _connections: connections, _objects: objects } = this let entered, exited - function reset () { + function reset() { entered = { __proto__: null } exited = { __proto__: null } } reset() - function onAdd (items) { + function onAdd(items) { forEach(items, (item, id) => { entered[id] = item }) diff --git a/packages/xo-vmdk-to-vhd/src/index.js b/packages/xo-vmdk-to-vhd/src/index.js index 4d66e403c..09757a19b 100644 --- a/packages/xo-vmdk-to-vhd/src/index.js +++ b/packages/xo-vmdk-to-vhd/src/index.js @@ -3,7 +3,7 @@ import { createReadableSparseStream } from 'vhd-lib' import VMDKDirectParser from './vmdk-read' import readVmdkGrainTable from './vmdk-read-table' -async function convertFromVMDK (vmdkReadStream, table) { +async function convertFromVMDK(vmdkReadStream, table) { const parser = new VMDKDirectParser(vmdkReadStream) const header = await parser.readHeader() return createReadableSparseStream( diff --git a/packages/xo-vmdk-to-vhd/src/virtual-buffer.js b/packages/xo-vmdk-to-vhd/src/virtual-buffer.js index a7bea15a0..2b9d05908 100644 --- a/packages/xo-vmdk-to-vhd/src/virtual-buffer.js +++ b/packages/xo-vmdk-to-vhd/src/virtual-buffer.js @@ -3,17 +3,17 @@ import { Slicer } from 'pipette' export class VirtualBuffer { - constructor (readStream) { + constructor(readStream) { this.slicer = new Slicer(readStream) this.position = 0 this.promise = null } - get isDepleted () { + get isDepleted() { return !this.slicer.readable } - async readChunk (length, label) { + async readChunk(length, label) { const _this = this if (this.promise !== null) { throw new Error('pomise already there !!!', this.promise) diff --git a/packages/xo-vmdk-to-vhd/src/vmdk-read.js b/packages/xo-vmdk-to-vhd/src/vmdk-read.js index 2a354424a..5e2502450 100644 --- a/packages/xo-vmdk-to-vhd/src/vmdk-read.js +++ b/packages/xo-vmdk-to-vhd/src/vmdk-read.js @@ -12,7 +12,7 @@ const compressionDeflate = 'COMPRESSION_DEFLATE' const compressionNone = 'COMPRESSION_NONE' const compressionMap = [compressionNone, compressionDeflate] -function parseS64b (buffer, offset, valueName) { +function parseS64b(buffer, offset, valueName) { const low = buffer.readInt32LE(offset) const high = buffer.readInt32LE(offset + 4) // here there might be a surprise because we are reading 64 integers into double floats (53 bits mantissa) @@ -23,7 +23,7 @@ function parseS64b (buffer, offset, valueName) { return value } -function parseU64b (buffer, offset, valueName) { +function parseU64b(buffer, offset, valueName) { const low = buffer.readUInt32LE(offset) const high = buffer.readUInt32LE(offset + 4) // here there might be a surprise because we are reading 64 integers into double floats (53 bits mantissa) @@ -34,7 +34,7 @@ function parseU64b (buffer, offset, valueName) { return value } -function parseDescriptor (descriptorSlice) { +function parseDescriptor(descriptorSlice) { const descriptorText = descriptorSlice.toString('ascii').replace(/\x00+$/, '') // eslint-disable-line no-control-regex const descriptorDict = {} const extentList = [] @@ -60,7 +60,7 @@ function parseDescriptor (descriptorSlice) { return { descriptor: descriptorDict, extents: extentList } } -function parseFlags (flagBuffer) { +function parseFlags(flagBuffer) { const number = flagBuffer.readUInt32LE(0) return { newLineTest: !!(number & (1 << 0)), @@ -71,7 +71,7 @@ function parseFlags (flagBuffer) { } } -function parseHeader (buffer) { +function parseHeader(buffer) { const magicString = buffer.slice(0, 4).toString('ascii') if (magicString !== 'KDMV') { throw new Error('not a VMDK file') @@ -121,7 +121,7 @@ function parseHeader (buffer) { numGTEsPerGT, } } -async function readGrain (offsetSectors, buffer, compressed) { +async function readGrain(offsetSectors, buffer, compressed) { const offset = offsetSectors * SECTOR_SIZE const size = buffer.readUInt32LE(offset + 8) const grainBuffer = buffer.slice(offset + 12, offset + 12 + size) @@ -141,26 +141,26 @@ async function readGrain (offsetSectors, buffer, compressed) { } } -function tryToParseMarker (buffer) { +function tryToParseMarker(buffer) { const value = buffer.readUInt32LE(0) const size = buffer.readUInt32LE(8) const type = buffer.readUInt32LE(12) return { value, size, type } } -function alignSectors (number) { +function alignSectors(number) { return Math.ceil(number / SECTOR_SIZE) * SECTOR_SIZE } export default class VMDKDirectParser { - constructor (readStream) { + constructor(readStream) { this.virtualBuffer = new VirtualBuffer(readStream) this.header = null } // I found a VMDK file whose L1 and L2 table did not have a marker, but they were at the top // I detect this case and eat those tables first then let the normal loop go over the grains. - async _readL1 () { + async _readL1() { const position = this.virtualBuffer.position const l1entries = Math.floor( (this.header.capacitySectors + this.header.l1EntrySectors - 1) / @@ -216,7 +216,7 @@ export default class VMDKDirectParser { } } - async readHeader () { + async readHeader() { const headerBuffer = await this.virtualBuffer.readChunk( HEADER_SIZE, 'readHeader' @@ -262,7 +262,7 @@ export default class VMDKDirectParser { return this.header } - async * blockIterator () { + async *blockIterator() { while (!this.virtualBuffer.isDepleted) { const position = this.virtualBuffer.position const sector = await this.virtualBuffer.readChunk( diff --git a/packages/xo-vmdk-to-vhd/src/vmdk-to-vhd.integ.spec.js b/packages/xo-vmdk-to-vhd/src/vmdk-to-vhd.integ.spec.js index 1b03612d1..ffbcdfc4f 100644 --- a/packages/xo-vmdk-to-vhd/src/vmdk-to-vhd.integ.spec.js +++ b/packages/xo-vmdk-to-vhd/src/vmdk-to-vhd.integ.spec.js @@ -24,7 +24,7 @@ afterEach(async () => { await pFromCallback(cb => rimraf(tmpDir, cb)) }) -function createFileAccessor (file) { +function createFileAccessor(file) { return async (start, end) => { if (start < 0 || end < 0) { const fileLength = (await stat(file)).size diff --git a/packages/xo-web/gulpfile.js b/packages/xo-web/gulpfile.js index 1b517a8fa..c74a8218a 100644 --- a/packages/xo-web/gulpfile.js +++ b/packages/xo-web/gulpfile.js @@ -24,20 +24,20 @@ const gulp = require('gulp') // =================================================================== -function lazyFn (factory) { - let fn = function () { +function lazyFn(factory) { + let fn = function() { fn = factory() return fn.apply(this, arguments) } - return function () { + return function() { return fn.apply(this, arguments) } } // ------------------------------------------------------------------- -const livereload = lazyFn(function () { +const livereload = lazyFn(function() { const livereload = require('gulp-refresh') livereload.listen({ port: LIVERELOAD_PORT, @@ -46,9 +46,9 @@ const livereload = lazyFn(function () { return livereload }) -const pipe = lazyFn(function () { +const pipe = lazyFn(function() { let current - function pipeCore (streams) { + function pipeCore(streams) { let i, n, stream for (i = 0, n = streams.length; i < n; ++i) { stream = streams[i] @@ -63,7 +63,7 @@ const pipe = lazyFn(function () { } const push = Array.prototype.push - return function (streams) { + return function(streams) { try { if (!(streams instanceof Array)) { streams = [] @@ -79,7 +79,7 @@ const pipe = lazyFn(function () { } }) -const resolvePath = lazyFn(function () { +const resolvePath = lazyFn(function() { return require('path').resolve }) @@ -87,13 +87,13 @@ const resolvePath = lazyFn(function () { // Similar to `gulp.src()` but the pattern is relative to `SRC_DIR` // and files are automatically watched when not in production mode. -const src = lazyFn(function () { - function resolve (path) { +const src = lazyFn(function() { + function resolve(path) { return path ? resolvePath(SRC_DIR, path) : SRC_DIR } return PRODUCTION - ? function src (pattern, opts) { + ? function src(pattern, opts) { const base = resolve(opts && opts.base) return gulp.src(pattern, { @@ -103,7 +103,7 @@ const src = lazyFn(function () { sourcemaps: opts && opts.sourcemaps, }) } - : function src (pattern, opts) { + : function src(pattern, opts) { const base = resolve(opts && opts.base) return pipe( @@ -125,8 +125,8 @@ const src = lazyFn(function () { // Similar to `gulp.dest()` but the output directory is relative to // `DIST_DIR` and default to `./`, and files are automatically live- // reloaded when not in production mode. -const dest = lazyFn(function () { - function resolve (path) { +const dest = lazyFn(function() { + function resolve(path) { return path ? resolvePath(DIST_DIR, path) : DIST_DIR } @@ -135,10 +135,10 @@ const dest = lazyFn(function () { } return PRODUCTION - ? function dest (path) { + ? function dest(path) { return gulp.dest(resolve(path), opts) } - : function dest (path) { + : function dest(path) { const stream = gulp.dest(resolve(path), opts) stream.pipe(livereload()) return stream @@ -147,7 +147,7 @@ const dest = lazyFn(function () { // =================================================================== -function browserify (path, opts) { +function browserify(path, opts) { if (opts == null) { opts = {} } @@ -193,8 +193,8 @@ function browserify (path, opts) { }) let write - function bundle () { - bundler.bundle(function onBundle (error, buffer) { + function bundle() { + bundler.bundle(function onBundle(error, buffer) { if (error) { stream.emit('error', error) return @@ -211,21 +211,21 @@ function browserify (path, opts) { } if (PRODUCTION) { - write = function (data) { + write = function(data) { stream.push(data) stream.push(null) } } else { stream = require('gulp-plumber')().pipe(stream) - write = function (data) { + write = function(data) { stream.push(data) } bundler.on('update', bundle) } - stream._read = function () { - this._read = function () {} + stream._read = function() { + this._read = function() {} bundle() } @@ -234,7 +234,7 @@ function browserify (path, opts) { // =================================================================== -gulp.task(function buildPages () { +gulp.task(function buildPages() { return pipe( src('index.pug'), require('gulp-pug')(), @@ -246,7 +246,7 @@ gulp.task(function buildPages () { ) }) -gulp.task(function buildScripts () { +gulp.task(function buildScripts() { return pipe( browserify('./index.js', { plugins: [ @@ -266,7 +266,7 @@ gulp.task(function buildScripts () { ) }) -gulp.task(function buildStyles () { +gulp.task(function buildStyles() { return pipe( src('index.scss', { sourcemaps: true }), require('gulp-sass')(), @@ -276,7 +276,7 @@ gulp.task(function buildStyles () { ) }) -gulp.task(function copyAssets () { +gulp.task(function copyAssets() { return pipe( src(['assets/**/*', 'favicon.*']), src('fontawesome-webfont.*', { @@ -298,6 +298,6 @@ gulp.task( // ------------------------------------------------------------------- -gulp.task(function clean (done) { +gulp.task(function clean(done) { require('rimraf')(DIST_DIR, done) }) diff --git a/packages/xo-web/src/common/action-button.js b/packages/xo-web/src/common/action-button.js index e7c370a5c..d8b3a121c 100644 --- a/packages/xo-web/src/common/action-button.js +++ b/packages/xo-web/src/common/action-button.js @@ -57,7 +57,7 @@ export default class ActionButton extends Component { tooltip: PropTypes.node, } - async _execute () { + async _execute() { const { props } = this if (props.pending || this.state.working) { @@ -131,7 +131,7 @@ export default class ActionButton extends Component { this._execute() } - componentDidMount () { + componentDidMount() { const { form } = this.props if (form) { @@ -141,7 +141,7 @@ export default class ActionButton extends Component { } } - componentWillUnmount () { + componentWillUnmount() { const { form } = this.props if (form) { @@ -151,7 +151,7 @@ export default class ActionButton extends Component { } } - render () { + render() { const { props: { children, icon, iconColor, pending, tooltip, ...props }, state: { error, working }, diff --git a/packages/xo-web/src/common/base-component.js b/packages/xo-web/src/common/base-component.js index 9ee83aea9..b803ad700 100644 --- a/packages/xo-web/src/common/base-component.js +++ b/packages/xo-web/src/common/base-component.js @@ -21,7 +21,7 @@ const get = (object, path, depth) => { } export default class BaseComponent extends PureComponent { - constructor (props, context) { + constructor(props, context) { super(props, context) // It really should have been done in React.Component! @@ -39,7 +39,7 @@ export default class BaseComponent extends PureComponent { } // See https://preactjs.com/guide/linked-state - linkState (name, targetPath) { + linkState(name, targetPath) { const key = targetPath !== undefined ? `${name}##${targetPath}` : name let linkedState = this._linkedState @@ -72,7 +72,7 @@ export default class BaseComponent extends PureComponent { }) } - toggleState (name) { + toggleState(name) { let linkedState = this._linkedState let cb if (linkedState === null) { @@ -111,7 +111,7 @@ if (VERBOSE) { } } - BaseComponent.prototype.componentDidUpdate = function (oldProps, oldState) { + BaseComponent.prototype.componentDidUpdate = function(oldProps, oldState) { const prefix = `${this.constructor.name} updated because of its` diff(`${prefix} props:`, oldProps, this.props) diff(`${prefix} state:`, oldState, this.state) diff --git a/packages/xo-web/src/common/collapse.js b/packages/xo-web/src/common/collapse.js index 935b0395f..56630e005 100644 --- a/packages/xo-web/src/common/collapse.js +++ b/packages/xo-web/src/common/collapse.js @@ -24,7 +24,7 @@ export default class Collapse extends Component { }) } - render () { + render() { const { props } = this const { isOpened } = this.state diff --git a/packages/xo-web/src/common/combobox.js b/packages/xo-web/src/common/combobox.js index 92f17487f..9f825b3ab 100644 --- a/packages/xo-web/src/common/combobox.js +++ b/packages/xo-web/src/common/combobox.js @@ -24,11 +24,11 @@ export default class Combobox extends Component { this.props.onChange(event.target.value) } - _setText (value) { + _setText(value) { this.props.onChange(value) } - render () { + render() { const { options, ...props } = this.props props.className = 'form-control' diff --git a/packages/xo-web/src/common/d3-utils.js b/packages/xo-web/src/common/d3-utils.js index 68b475611..d8bab8f3b 100644 --- a/packages/xo-web/src/common/d3-utils.js +++ b/packages/xo-web/src/common/d3-utils.js @@ -1,6 +1,6 @@ import forEach from 'lodash/forEach' -export function setStyles (style) { +export function setStyles(style) { forEach(style, (value, key) => { this.style(key, value) }) diff --git a/packages/xo-web/src/common/debug.js b/packages/xo-web/src/common/debug.js index dc1aca8e2..18e8e0036 100644 --- a/packages/xo-web/src/common/debug.js +++ b/packages/xo-web/src/common/debug.js @@ -11,7 +11,7 @@ class DebugAsync extends Component { promise: PropTypes.object.isRequired, } - constructor (props) { + constructor(props) { super() this.state = { @@ -24,11 +24,11 @@ class DebugAsync extends Component { ) } - shouldComponentUpdate (_, newState) { + shouldComponentUpdate(_, newState) { return this.state.status !== newState.status } - render () { + render() { const { status, value } = this.state if (status === 'pending') { diff --git a/packages/xo-web/src/common/dropzone/index.js b/packages/xo-web/src/common/dropzone/index.js index 58011b479..392f6dd7f 100644 --- a/packages/xo-web/src/common/dropzone/index.js +++ b/packages/xo-web/src/common/dropzone/index.js @@ -12,7 +12,7 @@ export default class Dropzone extends Component { multiple: PropTypes.bool, } - render () { + render() { const { onDrop, message, multiple } = this.props return ( diff --git a/packages/xo-web/src/common/editable/index.js b/packages/xo-web/src/common/editable/index.js index b24ccbd1e..a03dc9999 100644 --- a/packages/xo-web/src/common/editable/index.js +++ b/packages/xo-web/src/common/editable/index.js @@ -43,7 +43,7 @@ class Hover extends Component { alt: PropTypes.node.isRequired, } - constructor () { + constructor() { super() this.state = { @@ -54,7 +54,7 @@ class Hover extends Component { this._onMouseLeave = () => this.setState({ hover: false }) } - render () { + render() { if (this.state.hover) { return {this.props.alt} } @@ -73,7 +73,7 @@ class Editable extends Component { value: PropTypes.any.isRequired, } - get value () { + get value() { throw new Error('not implemented') } @@ -113,11 +113,11 @@ class Editable extends Component { ) } - _save () { + _save() { return this.__save(() => this.value, this.props.onChange) } - async __save (getValue, saveValue) { + async __save(getValue, saveValue) { const { props } = this try { @@ -159,7 +159,7 @@ class Editable extends Component { } __stopTimer = () => clearTimeout(this._timeout) - render () { + render() { const { state, props } = this if (!state.editing) { @@ -232,7 +232,7 @@ export class Text extends Editable { value: PropTypes.string.isRequired, } - get value () { + get value() { const { input } = this.refs // FIXME: should be properly forwarded to the user. @@ -248,7 +248,7 @@ export class Text extends Editable { target.style.width = `${target.value.length + 1}ex` } - _renderDisplay () { + _renderDisplay() { const { children, value } = this.props if (children || value) { @@ -267,7 +267,7 @@ export class Text extends Editable { ) } - _renderEdition () { + _renderEdition() { const { value } = this.props const { saving } = this.state @@ -311,7 +311,7 @@ export class Number extends Component { value: PropTypes.number, } - get value () { + get value() { return +this.refs.input.value } @@ -329,7 +329,7 @@ export class Number extends Component { this.props.onChange(value, params) } - render () { + render() { const { value } = this.props return ( {renderer ? renderer(value) : value} } - _renderEdition () { + _renderEdition() { const { saving, valueKey } = this.state const { options } = this.props @@ -429,11 +429,11 @@ export class XoSelect extends Editable { value: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), } - get value () { + get value() { return this.state.value } - _renderDisplay () { + _renderDisplay() { return ( this.props.children || ( {this.props.value[this.props.labelProp]} @@ -443,7 +443,7 @@ export class XoSelect extends Editable { _onChange = object => this.setState({ value: object }, object && this._save) - _renderEdition () { + _renderEdition() { const { saving, xoType, ...props } = this.props const Select = MAP_TYPE_SELECT[xoType] @@ -473,11 +473,11 @@ export class Size extends Editable { value: PropTypes.number.isRequired, } - get value () { + get value() { return this.refs.input.value } - _renderDisplay () { + _renderDisplay() { return this.props.children || formatSize(this.props.value) } @@ -492,7 +492,7 @@ export class Size extends Editable { this._focused = true } - _renderEdition () { + _renderEdition() { const { saving } = this.state const { value } = this.props diff --git a/packages/xo-web/src/common/form/index.js b/packages/xo-web/src/common/form/index.js index 9b99060fc..0d0206385 100644 --- a/packages/xo-web/src/common/form/index.js +++ b/packages/xo-web/src/common/form/index.js @@ -26,11 +26,11 @@ export class Password extends Component { enableGenerator: PropTypes.bool, } - get value () { + get value() { return this.refs.field.value } - set value (value) { + set value(value) { this.refs.field.value = value } @@ -56,7 +56,7 @@ export class Password extends Component { }) } - render () { + render() { const { className, enableGenerator = false, ...props } = this.props const { visible } = this.state @@ -97,7 +97,7 @@ export class Range extends Component { value: PropTypes.number, } - componentDidMount () { + componentDidMount() { const { min, onChange, required, value } = this.props if (value === undefined && required) { @@ -107,7 +107,7 @@ export class Range extends Component { _onChange = value => this.props.onChange(getEventValue(value)) - render () { + render() { const { max, min, step, value } = this.props return ( @@ -152,7 +152,7 @@ export class SizeInput extends BaseComponent { value: PropTypes.oneOfType([PropTypes.number, PropTypes.oneOf([null])]), } - constructor (props) { + constructor(props) { super(props) this.state = this._createStateFromBytes( @@ -160,14 +160,14 @@ export class SizeInput extends BaseComponent { ) } - componentWillReceiveProps (props) { + componentWillReceiveProps(props) { const { value } = props if (value !== undefined && value !== this.props.value) { this.setState(this._createStateFromBytes(value)) } } - _createStateFromBytes (bytes) { + _createStateFromBytes(bytes) { if (bytes === this._bytes) { return { input: this._input, @@ -189,7 +189,7 @@ export class SizeInput extends BaseComponent { } } - get value () { + get value() { const { input, unit } = this.state if (!input) { @@ -199,7 +199,7 @@ export class SizeInput extends BaseComponent { return parseSize(`${+input} ${unit}`) } - set value (value) { + set value(value) { if ( process.env.NODE_ENV !== 'production' && this.props.value !== undefined @@ -209,7 +209,7 @@ export class SizeInput extends BaseComponent { this.setState(this._createStateFromBytes(value)) } - _onChange (input, unit) { + _onChange(input, unit) { const { onChange } = this.props // Empty input equals null. @@ -267,7 +267,7 @@ export class SizeInput extends BaseComponent { } } - render () { + render() { const { autoFocus, className, diff --git a/packages/xo-web/src/common/form/select.js b/packages/xo-web/src/common/form/select.js index f7c5c42c0..d0226ef88 100644 --- a/packages/xo-web/src/common/form/select.js +++ b/packages/xo-web/src/common/form/select.js @@ -41,7 +41,7 @@ export default class Select extends React.PureComponent { }) // https://github.com/JedWatson/react-select/blob/dd32c27d7ea338a93159da5e40bc06697d0d86f9/src/utils/defaultMenuRenderer.js#L4 - _renderMenu (opts) { + _renderMenu(opts) { const { focusOption, options, selectValue } = opts const focusFromEvent = event => @@ -87,7 +87,7 @@ export default class Select extends React.PureComponent { } _renderMenu = this._renderMenu.bind(this) - _renderRow ( + _renderRow( { focusedOption, focusOption, @@ -129,11 +129,11 @@ export default class Select extends React.PureComponent { ) } - componentDidMount () { + componentDidMount() { this.componentDidUpdate() } - componentDidUpdate () { + componentDidUpdate() { const { props } = this const { autoSelectSingleOption = props.required, @@ -157,7 +157,7 @@ export default class Select extends React.PureComponent { } } - render () { + render() { const { props } = this const { multi } = props return ( diff --git a/packages/xo-web/src/common/form/toggle.js b/packages/xo-web/src/common/form/toggle.js index 728bc32f6..72f29a4bf 100644 --- a/packages/xo-web/src/common/form/toggle.js +++ b/packages/xo-web/src/common/form/toggle.js @@ -32,7 +32,7 @@ export default class Toggle extends Component { } } - render () { + render() { const { props } = this return ( diff --git a/packages/xo-web/src/common/home-tags.js b/packages/xo-web/src/common/home-tags.js index 79dddc832..df1d4e85a 100644 --- a/packages/xo-web/src/common/home-tags.js +++ b/packages/xo-web/src/common/home-tags.js @@ -27,7 +27,7 @@ export default class HomeTags extends Component { this.context.router.push(`/home?t=${t}&s=${s}`) } - render () { + render() { return ( ( // =================================================================== class HostsPatchesTable extends Component { - constructor (props) { + constructor(props) { super(props) this.state.missingPatches = {} } @@ -118,24 +118,24 @@ class HostsPatchesTable extends Component { return Promise.all(map(keys(pools), installAllPatchesOnPool)) } - componentDidMount () { + componentDidMount() { // Force one Portal refresh. // Because Portal cannot see the container reference at first rendering. this.forceUpdate() this._subscribeMissingPatches() } - componentWillReceiveProps (nextProps) { + componentWillReceiveProps(nextProps) { if (nextProps.hosts !== this.props.hosts) { this._subscribeMissingPatches(nextProps.hosts) } } - componentWillUnmount () { + componentWillUnmount() { this.unsubscribeMissingPatches() } - render () { + render() { const { buttonsGroupContainer, container, @@ -196,7 +196,7 @@ class HostsPatchesTable extends Component { } }) class HostsPatchesTableByPool extends Component { - render () { + render() { const { props } = this return } diff --git a/packages/xo-web/src/common/intl/index.js b/packages/xo-web/src/common/intl/index.js index 88bab4e20..0836c3b4c 100644 --- a/packages/xo-web/src/common/intl/index.js +++ b/packages/xo-web/src/common/intl/index.js @@ -60,7 +60,7 @@ export class IntlProvider extends Component { lang: PropTypes.string.isRequired, } - render () { + render() { const { lang, children } = this.props // Adding a key prop is a work-around suggested by react-intl documentation // to make sure changes to the locale trigger a re-render of the child components @@ -88,7 +88,10 @@ const parseDuration = milliseconds => { @connect(({ lang }) => ({ lang })) export class FormattedDuration extends Component { - _parseDuration = createSelector(() => this.props.duration, parseDuration) + _parseDuration = createSelector( + () => this.props.duration, + parseDuration + ) _humanizeDuration = createSelector( () => this.props.duration, @@ -100,7 +103,7 @@ export class FormattedDuration extends Component { .humanize() ) - render () { + render() { const parsedDuration = this._parseDuration() return ( parseInt(str, 10)) let n = 0 @@ -24,13 +24,13 @@ function ip2hex (ip) { return n } -function assertIpv4 (str, msg) { +function assertIpv4(str, msg) { if (!ipv4.test(str)) { throw new Error(msg) } } -function * range (ip1, ip2) { +function* range(ip1, ip2) { assertIpv4(ip1, 'argument "ip1" must be a valid IPv4 address') assertIpv4(ip2, 'argument "ip2" must be a valid IPv4 address') diff --git a/packages/xo-web/src/common/iso-device.js b/packages/xo-web/src/common/iso-device.js index 9eaf3bf55..e9fbc25fe 100644 --- a/packages/xo-web/src/common/iso-device.js +++ b/packages/xo-web/src/common/iso-device.js @@ -86,7 +86,7 @@ export default class IsoDevice extends Component { _showWarning = () => alert(_('cdDriveNotInstalled'), _('cdDriveInstallation')) - render () { + render() { const { cdDrive, isAdmin, mountedIso } = this.props const resourceSet = this._getResolvedResourceSet() const useResourceSet = !(isAdmin || resourceSet === undefined) diff --git a/packages/xo-web/src/common/json-schema-input/array-input.js b/packages/xo-web/src/common/json-schema-input/array-input.js index fbca9ab48..894794741 100644 --- a/packages/xo-web/src/common/json-schema-input/array-input.js +++ b/packages/xo-web/src/common/json-schema-input/array-input.js @@ -45,7 +45,7 @@ export default class ObjectInput extends Component { props.onChange(filter(props.value, (_, i) => i !== key)) } - render () { + render() { const { props: { depth = 0, diff --git a/packages/xo-web/src/common/json-schema-input/boolean-input.js b/packages/xo-web/src/common/json-schema-input/boolean-input.js index b1fedd4a6..90a97655a 100644 --- a/packages/xo-web/src/common/json-schema-input/boolean-input.js +++ b/packages/xo-web/src/common/json-schema-input/boolean-input.js @@ -10,7 +10,7 @@ import { PrimitiveInputWrapper } from './helpers' @uncontrollableInput() export default class BooleanInput extends Component { - render () { + render() { const { disabled, onChange, value, ...props } = this.props return ( diff --git a/packages/xo-web/src/common/json-schema-input/enum-input.js b/packages/xo-web/src/common/json-schema-input/enum-input.js index 0b755612f..a98286b37 100644 --- a/packages/xo-web/src/common/json-schema-input/enum-input.js +++ b/packages/xo-web/src/common/json-schema-input/enum-input.js @@ -27,7 +27,7 @@ export default class EnumInput extends Component { this.props.onChange(this.props.schema.enum[event.target.value]) } - render () { + render() { const { disabled, schema: { enum: enumValues, enumNames = enumValues }, diff --git a/packages/xo-web/src/common/json-schema-input/generic-input.js b/packages/xo-web/src/common/json-schema-input/generic-input.js index c874e2a18..3e5b52f44 100644 --- a/packages/xo-web/src/common/json-schema-input/generic-input.js +++ b/packages/xo-web/src/common/json-schema-input/generic-input.js @@ -44,7 +44,7 @@ export default class GenericInput extends Component { onChange && onChange(getEventValue(event), name) } - render () { + render() { const { schema, value, uiSchema = EMPTY_OBJECT, ...opts } = this.props const props = { diff --git a/packages/xo-web/src/common/json-schema-input/integer-input.js b/packages/xo-web/src/common/json-schema-input/integer-input.js index dbe566ba7..319956f57 100644 --- a/packages/xo-web/src/common/json-schema-input/integer-input.js +++ b/packages/xo-web/src/common/json-schema-input/integer-input.js @@ -16,7 +16,7 @@ export default class IntegerInput extends Component { this.props.onChange(value ? +value : undefined) } - render () { + render() { const { required, schema } = this.props const { disabled, diff --git a/packages/xo-web/src/common/json-schema-input/number-input.js b/packages/xo-web/src/common/json-schema-input/number-input.js index 7b2d52ff2..2365e2ed2 100644 --- a/packages/xo-web/src/common/json-schema-input/number-input.js +++ b/packages/xo-web/src/common/json-schema-input/number-input.js @@ -16,7 +16,7 @@ export default class NumberInput extends Component { this.props.onChange(value ? +value : undefined) } - render () { + render() { const { required, schema } = this.props const { disabled, diff --git a/packages/xo-web/src/common/json-schema-input/object-input.js b/packages/xo-web/src/common/json-schema-input/object-input.js index d1d679831..352d92b11 100644 --- a/packages/xo-web/src/common/json-schema-input/object-input.js +++ b/packages/xo-web/src/common/json-schema-input/object-input.js @@ -38,7 +38,7 @@ export default class ObjectInput extends Component { required => (required ? keyBy(required) : EMPTY_OBJECT) ) - render () { + render() { const { props: { depth = 0, diff --git a/packages/xo-web/src/common/json-schema-input/string-input.js b/packages/xo-web/src/common/json-schema-input/string-input.js index 6853b7e36..02872603b 100644 --- a/packages/xo-web/src/common/json-schema-input/string-input.js +++ b/packages/xo-web/src/common/json-schema-input/string-input.js @@ -23,7 +23,7 @@ export default class StringInput extends Component { this.props.onChange(value !== '' ? value : undefined) } - render () { + render() { const { required, schema } = this.props const { disabled, diff --git a/packages/xo-web/src/common/link.js b/packages/xo-web/src/common/link.js index 3d3c30339..7c3e2bd5a 100644 --- a/packages/xo-web/src/common/link.js +++ b/packages/xo-web/src/common/link.js @@ -55,7 +55,7 @@ export class BlockLink extends Component { } } - render () { + render() { const { children, tagName = 'div', className } = this.props const Component = tagName return ( diff --git a/packages/xo-web/src/common/modal.js b/packages/xo-web/src/common/modal.js index 6ed2e44fb..22f0d19f8 100644 --- a/packages/xo-web/src/common/modal.js +++ b/packages/xo-web/src/common/modal.js @@ -82,7 +82,7 @@ class GenericModal extends Component { instance.close() } - render () { + render() { const { buttons, icon, title } = this.props const body = _addRef(this.props.children, 'body') @@ -208,7 +208,7 @@ class StrongConfirm extends Component { } } - render () { + render() { const { body, strongConfirm: { messageId, values }, @@ -324,7 +324,7 @@ export const FormModal = decorate([ provideState({ initialState: getInitialState, effects: { - initialize () { + initialize() { if (formModalState !== undefined) { throw new Error('FormModal is a singleton!') } @@ -336,14 +336,14 @@ export const FormModal = decorate([ onChange: (_, value) => () => ({ value: getEventValue(value), }), - onCancel () { + onCancel() { const { state } = this if (!state.isHandlerRunning) { state.opened = false state.reject() } }, - async onSubmit ({ close }) { + async onSubmit({ close }) { const { state } = this state.isHandlerRunning = true @@ -411,24 +411,24 @@ export const FormModal = decorate([ // ----------------------------------------------------------------------------- export default class Modal extends Component { - constructor () { + constructor() { super() this.state = { showModal: false } } - componentDidMount () { + componentDidMount() { if (instance) { throw new Error('Modal is a singleton!') } instance = this } - componentWillUnmount () { + componentWillUnmount() { instance = undefined } - close () { + close() { this.setState({ showModal: false }, enableShortcuts) } @@ -439,7 +439,7 @@ export default class Modal extends Component { onClose && onClose() } - render () { + render() { const { content, showModal, props } = this.state return ( diff --git a/packages/xo-web/src/common/notification.js b/packages/xo-web/src/common/notification.js index 985d655f3..2988cb7d3 100644 --- a/packages/xo-web/src/common/notification.js +++ b/packages/xo-web/src/common/notification.js @@ -16,23 +16,23 @@ export let success isAdmin, }) export class Notification extends Component { - componentDidMount () { + componentDidMount() { if (instance) { throw new Error('Notification is a singleton!') } instance = this } - componentWillUnmount () { + componentWillUnmount() { instance = undefined } // This special component never have to rerender! - shouldComponentUpdate () { + shouldComponentUpdate() { return false } - render () { + render() { return ( { diff --git a/packages/xo-web/src/common/object-name.js b/packages/xo-web/src/common/object-name.js index eca61df28..380fd0a98 100644 --- a/packages/xo-web/src/common/object-name.js +++ b/packages/xo-web/src/common/object-name.js @@ -8,7 +8,7 @@ import React, { Component } from 'react' return (state, props) => ({ object: object(state, props) }) }) export default class ObjectName extends Component { - render () { + render() { const { object } = this.props return {object && object.name_label} } diff --git a/packages/xo-web/src/common/pagination.js b/packages/xo-web/src/common/pagination.js index 22ded2c66..dbbdfe8f9 100644 --- a/packages/xo-web/src/common/pagination.js +++ b/packages/xo-web/src/common/pagination.js @@ -37,13 +37,13 @@ export default class Pagination extends React.PureComponent { value: PropTypes.number.isRequired, } - _onClick (event) { + _onClick(event) { event.preventDefault() this.props.onChange(+event.currentTarget.dataset.value) } _onClick = this._onClick.bind(this) - render () { + render() { const { ariaLabel, ellipsis, diff --git a/packages/xo-web/src/common/react-novnc.js b/packages/xo-web/src/common/react-novnc.js index 9f81209f9..a0dcbea2a 100644 --- a/packages/xo-web/src/common/react-novnc.js +++ b/packages/xo-web/src/common/react-novnc.js @@ -25,7 +25,7 @@ export default class NoVnc extends Component { url: PropTypes.string.isRequired, } - constructor (props) { + constructor(props) { super(props) this._rfb = null this._retryGen = createBackoff(Infinity) @@ -51,21 +51,21 @@ export default class NoVnc extends Component { } } - sendCtrlAltDel () { + sendCtrlAltDel() { const rfb = this._rfb if (rfb) { rfb.sendCtrlAltDel() } } - setClipboard (text) { + setClipboard(text) { const rfb = this._rfb if (rfb) { rfb.clipboardPasteFrom(text) } } - _clean () { + _clean() { const rfb = this._rfb if (rfb) { this._rfb = null @@ -118,15 +118,15 @@ export default class NoVnc extends Component { disableShortcuts() } - componentDidMount () { + componentDidMount() { this._connect() } - componentWillUnmount () { + componentWillUnmount() { this._clean() } - componentWillReceiveProps (props) { + componentWillReceiveProps(props) { const rfb = this._rfb if (rfb && this.props.scale !== props.scale) { rfb.get_display().set_scale(props.scale || 1) @@ -159,7 +159,7 @@ export default class NoVnc extends Component { } } - render () { + render() { return ( { this.setState({ defaultTimezone: serverTimezone, @@ -127,7 +127,7 @@ export class SchedulePreview extends Component { }) } - render () { + render() { const { defaultTimezone, value } = this.state const { cronPattern, timezone = defaultTimezone } = this.props const dates = createSchedule(cronPattern, timezone).next(value) @@ -174,7 +174,7 @@ class ToggleTd extends Component { props.onChange(props.tdId, !props.value) } - render () { + render() { const { props } = this return ( { @@ -451,7 +451,7 @@ export default class Scheduler extends Component { return timezone } - render () { + render() { const cronPatternArr = this._getCronPattern().split(' ') const timezone = this._getTimezone() diff --git a/packages/xo-web/src/common/select-files.js b/packages/xo-web/src/common/select-files.js index 23ef9b75d..b718545d2 100644 --- a/packages/xo-web/src/common/select-files.js +++ b/packages/xo-web/src/common/select-files.js @@ -19,7 +19,7 @@ export default class SelectFiles extends Component { onChange(multi ? files : files[0]) } - render () { + render() { return (