-
Notifications
You must be signed in to change notification settings - Fork 254
/
utils.js
643 lines (527 loc) · 16.1 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
import getStream from 'get-stream'
import humanFormat from 'human-format'
import React from 'react'
import ReadableStream from 'readable-stream'
import { connect } from 'react-redux'
import { FormattedDate } from 'react-intl'
import {
clone,
every,
forEach,
isArray,
isEmpty,
isFunction,
isPlainObject,
isString,
map,
mapValues,
pick,
sample,
some,
} from 'lodash'
import _ from './intl'
import * as actions from './store/actions'
import invoke from './invoke'
import store from './store'
import { getObject, isAdmin } from './selectors'
import { satisfies as versionSatisfies } from 'semver'
export const EMPTY_ARRAY = Object.freeze([])
export const EMPTY_OBJECT = Object.freeze({})
export const VIRTUALIZATION_MODE_LABEL = {
hvm: 'hardwareVirtualizedMode',
pv: 'paraVirtualizedMode',
pvhvm: 'hvmModeWithPvDriversEnabled',
}
// ===================================================================
export addSubscriptions from './add-subscriptions'
// ===================================================================
export const getVirtualizationModeLabel = vm => {
const virtualizationMode =
vm.virtualizationMode === 'hvm' && Boolean(vm.xenTools)
? 'pvhvm'
: vm.virtualizationMode
return VIRTUALIZATION_MODE_LABEL[virtualizationMode]
}
// ===================================================================
export const ensureArray = value => {
if (value === undefined) {
return []
}
return Array.isArray(value) ? value : [value]
}
export const propsEqual = (o1, o2, props) => {
props = ensureArray(props)
for (const prop of props) {
if (o1[prop] !== o2[prop]) {
return false
}
}
return true
}
// ===================================================================
const _normalizeMapStateToProps = mapper => {
// accept a list of entries to extract from the state
if (Array.isArray(mapper)) {
return state => pick(state, mapper)
}
if (isFunction(mapper)) {
const factoryOrMapper = (state, props) => {
const result = mapper(state, props)
// Properly handles factory pattern.
if (isFunction(result)) {
mapper = result
return factoryOrMapper
}
if (isPlainObject(result)) {
if (isEmpty(result)) {
// Nothing can be determined, wait for it.
return result
}
if (every(result, isFunction)) {
indirection = (state, props) =>
mapValues(result, selector => selector(state, props))
return indirection(state, props)
}
}
indirection = mapper
return result
}
let indirection = factoryOrMapper
return (state, props) => indirection(state, props)
}
mapper = mapValues(mapper, _normalizeMapStateToProps)
return (state, props) => mapValues(mapper, fn => fn(state, props))
}
export const connectStore = (mapStateToProps, opts = {}) => {
const connector = connect(
_normalizeMapStateToProps(mapStateToProps),
actions,
undefined,
opts
)
return Component => {
const ConnectedComponent = connector(Component)
if (opts.withRef && 'value' in Component.prototype) {
Object.defineProperty(ConnectedComponent.prototype, 'value', {
configurable: true,
get() {
return this.getWrappedInstance().value
},
set(value) {
this.getWrappedInstance().value = value
},
})
}
return ConnectedComponent
}
}
// -------------------------------------------------------------------
export { default as Debug } from './debug'
// -------------------------------------------------------------------
// Returns the current XOA Plan or the Plan name if number given
export const getXoaPlan = plan => {
switch (plan || +process.env.XOA_PLAN) {
case 1:
return 'Free'
case 2:
return 'Starter'
case 3:
return 'Enterprise'
case 4:
return 'Premium'
case 5:
return 'Community'
}
return 'Unknown'
}
// -------------------------------------------------------------------
export const mapPlus = (collection, cb) => {
const result = []
const push = ::result.push
forEach(collection, (value, index) => cb(value, push, index))
return result
}
// -------------------------------------------------------------------
export const noop = () => {}
// -------------------------------------------------------------------
export const osFamily = invoke(
{
centos: ['centos'],
debian: ['debian'],
docker: ['coreos'],
fedora: ['fedora'],
freebsd: ['freebsd'],
gentoo: ['gentoo'],
'linux-mint': ['linux-mint'],
netbsd: ['netbsd'],
oracle: ['oracle'],
osx: ['osx'],
redhat: ['redhat', 'rhel'],
solaris: ['solaris'],
suse: ['sles', 'suse'],
ubuntu: ['ubuntu'],
windows: ['windows'],
},
osByFamily => {
const osToFamily = Object.create(null)
forEach(osByFamily, (list, family) => {
forEach(list, os => {
osToFamily[os] = family
})
})
return osName => osName && osToFamily[osName.toLowerCase()]
}
)
// -------------------------------------------------------------------
export const formatSize = bytes =>
humanFormat(bytes, { scale: 'binary', unit: 'B' })
export const formatSizeShort = bytes =>
humanFormat(bytes, { scale: 'binary', unit: 'B', decimals: 0 })
export const formatSizeRaw = bytes =>
humanFormat.raw(bytes, { scale: 'binary', unit: 'B' })
export const formatSpeed = (bytes, milliseconds) =>
humanFormat((bytes * 1e3) / milliseconds, { scale: 'binary', unit: 'B/s' })
const timeScale = new humanFormat.Scale({
ns: 1e-6,
µs: 1e-3,
ms: 1,
s: 1e3,
min: 60 * 1e3,
h: 3600 * 1e3,
d: 86400 * 1e3,
y: 2592000 * 1e3,
})
export const formatTime = milliseconds =>
humanFormat(milliseconds, { scale: timeScale, decimals: 0 })
export const parseSize = size => {
let bytes = humanFormat.parse.raw(size, { scale: 'binary' })
if (bytes.unit && bytes.unit !== 'B') {
bytes = humanFormat.parse.raw(size)
if (bytes.unit && bytes.unit !== 'B') {
throw new Error('invalid size: ' + size)
}
}
return Math.floor(bytes.value * bytes.factor)
}
// -------------------------------------------------------------------
const _NotFound = () => <h1>{_('errorPageNotFound')}</h1>
// Decorator to declare routes on a component.
//
// TODO: add support for function childRoutes (getChildRoutes).
export const routes = (indexRoute, childRoutes) => target => {
if (isArray(indexRoute)) {
childRoutes = indexRoute
indexRoute = undefined
} else if (isFunction(indexRoute)) {
indexRoute = {
component: indexRoute,
}
} else if (isString(indexRoute)) {
indexRoute = {
onEnter: invoke(indexRoute, pathname => (state, replace) => {
const current = state.location.pathname
replace((current === '/' ? '' : current) + '/' + pathname)
}),
}
}
if (isPlainObject(childRoutes)) {
childRoutes = map(childRoutes, (component, path) => {
// The logic can be bypassed by passing a plain object.
if (isPlainObject(component)) {
return { ...component, path }
}
return { ...component.route, component, path }
})
}
if (childRoutes) {
childRoutes.push({ component: _NotFound, path: '*' })
}
target.route = {
indexRoute,
childRoutes,
}
return target
}
// -------------------------------------------------------------------
// Creates a new function which throws an error.
//
// ```js
// promise.catch(throwFn('an error has occurred'))
//
// function foo (param = throwFn('param is required')) {}
// ```
export const throwFn = error => () => {
throw isString(error) ? new Error(error) : error
}
// ===================================================================
export const resolveResourceSet = resourceSet => {
if (!resourceSet) {
return
}
const { objects, ipPools, ...attrs } = resourceSet
const resolvedObjects = {}
const resolvedSet = {
...attrs,
missingObjects: [],
objectsByType: resolvedObjects,
ipPools,
}
const state = store.getState()
forEach(objects, id => {
const object = getObject(state, id, true) // true: useResourceSet to bypass permissions
// Error, missing resource.
if (!object) {
resolvedSet.missingObjects.push(id)
return
}
const { type } = object
if (!resolvedObjects[type]) {
resolvedObjects[type] = [object]
} else {
resolvedObjects[type].push(object)
}
})
return resolvedSet
}
export const resolveResourceSets = resourceSets =>
map(resourceSets, resolveResourceSet)
// ===================================================================
export const streamToString = getStream
// ===================================================================
/* global FileReader */
// Creates a readable stream from a HTML file.
export const htmlFileToStream = file => {
const reader = new FileReader()
const stream = new ReadableStream()
let offset = 0
reader.onloadend = evt => {
stream.push(evt.target.result)
}
reader.onerror = error => {
stream.emit('error', error)
}
stream._read = function(size) {
if (offset >= file.size) {
stream.push(null)
} else {
reader.readAsBinaryString(file.slice(offset, offset + size))
offset += size
}
}
return stream
}
// ===================================================================
export const resolveId = value =>
value != null && typeof value === 'object' && 'id' in value ? value.id : value
export const resolveIds = params => {
for (const key in params) {
const param = params[key]
if (param != null && typeof param === 'object' && 'id' in param) {
params[key] = param.id
}
}
return params
}
// ===================================================================
const OPs = {
'<': a => a < 0,
'<=': a => a <= 0,
'===': a => a === 0,
'>': a => a > 0,
'>=': a => a >= 0,
}
const makeNiceCompare = compare =>
function() {
const { length } = arguments
if (length === 2) {
return compare(arguments[0], arguments[1])
}
let i = 1
let v1 = arguments[0]
let op, v2
while (i < length) {
op = arguments[i++]
v2 = arguments[i++]
if (!OPs[op](compare(v1, v2))) {
return false
}
v1 = v2
}
return true
}
export const compareVersions = makeNiceCompare((v1, v2) => {
v1 = v1.split('.')
v2 = v2.split('.')
for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
const n1 = +v1[i] || 0
const n2 = +v2[i] || 0
if (n1 < n2) return -1
if (n1 > n2) return 1
}
return 0
})
export const isXosanPack = ({ name }) => name.startsWith('XOSAN')
// ===================================================================
export const getCoresPerSocketPossibilities = (maxCoresPerSocket, vCPUs) => {
// According to : https://www.citrix.com/blogs/2014/03/11/citrix-xenserver-setting-more-than-one-vcpu-per-vm-to-improve-application-performance-and-server-consolidation-e-g-for-cad3-d-graphical-applications/
const maxVCPUs = 16
const options = []
if (maxCoresPerSocket !== undefined && vCPUs !== '') {
const ratio = vCPUs / maxVCPUs
for (
let coresPerSocket = maxCoresPerSocket;
coresPerSocket >= ratio;
coresPerSocket--
) {
if (vCPUs % coresPerSocket === 0) options.push(coresPerSocket)
}
}
return options
}
// Generates a random human-readable string of length `length`
// Useful to generate random default names intended for the UI user
export const generateReadableRandomString = (() => {
const CONSONANTS = 'bdfgklmnprtvz'.split('')
const VOWELS = 'aeiou'.split('')
return (length = 8) => {
const result = new Array(length)
for (let i = 0; i < length; ++i) {
result[i] = sample((i & 1) === 0 ? VOWELS : CONSONANTS)
}
return result.join('')
}
})()
export const cowSet = (object, path, value, depth = 0) => {
if (depth >= path.length) {
return value
}
object = object != null ? clone(object) : {}
const prop = path[depth]
object[prop] = cowSet(object[prop], path, value, depth + 1)
return object
}
// Generates a function that returns a value between 0 and 1
// This function returns an estimated progress value between 0 and 1
// based on the elapsed time since the createFakeProgress call and
// the given estimated duration d
//
// const getProgress = createFakeProgress(120)
// setInterval(() => console.log(`Progress: ${getProgress() * 100} %`), 1000)
export const createFakeProgress = (() => {
const S = 0.95 // Progress value after d seconds
return d => {
const startTime = Date.now() / 1e3
return () => {
const x = Date.now() / 1e3 - startTime
return -Math.exp((x * Math.log(1 - S)) / d) + 1
}
}
})()
export const ShortDate = ({ timestamp }) => (
<FormattedDate value={timestamp} month='short' day='numeric' year='numeric' />
)
export const findLatestPack = (packs, hostsVersions) => {
const checkVersion = version =>
!version ||
every(hostsVersions, hostVersion => versionSatisfies(hostVersion, version))
let latestPack = { version: '0' }
forEach(packs, pack => {
if (
pack.type === 'iso' &&
compareVersions(pack.version, '>', latestPack.version) &&
checkVersion(pack.requirements && pack.requirements.xenserver)
) {
latestPack = pack
}
})
if (latestPack.version === '0') {
// No compatible pack was found
return
}
return latestPack
}
export const isLatestXosanPackInstalled = (latestXosanPack, hosts) =>
latestXosanPack !== undefined &&
every(hosts, host =>
some(
host.supplementalPacks,
({ name, version }) =>
name === 'XOSAN' && version === latestXosanPack.version
)
)
// ===================================================================
export const getMemoryUsedMetric = ({ memory, memoryFree = memory }) =>
map(memory, (value, key) => value - memoryFree[key])
// ===================================================================
export const generateRandomId = () =>
Math.random()
.toString(36)
.slice(2)
// ===================================================================
// it returns [nActivePaths, nPaths]
export const getIscsiPaths = pbd => {
const pathsInfo = pbd.otherConfig[`mpath-${pbd.device_config.SCSIid}`]
return pathsInfo !== undefined ? JSON.parse(pathsInfo) : []
}
// ===================================================================
export const downloadLog = ({ log, date, type }) => {
const file = new window.Blob([log], {
type: 'text/plain',
})
const anchor = document.createElement('a')
anchor.href = window.URL.createObjectURL(file)
anchor.download = `${new Date(date)
.toISOString()
.replace(/:/g, '_')} - ${type}.log`
anchor.style.display = 'none'
document.body.appendChild(anchor)
anchor.click()
document.body.removeChild(anchor)
}
// ===================================================================
// Creates compare function based on different criterias
//
// ```js
// [{ name: 'bar', value: v2 }, { name: 'foo', value: v1 }].sort(
// createCompare([
// o => o.value === v1,
// 'name'
// ])
// )
// ```
export const createCompare = criterias => (...items) => {
let res = 0
// Array.find to stop when the result is != 0
criterias.find(fn => {
const [v1, v2] = items.map(item => {
const v = typeof fn === 'string' ? item[fn] : fn(item)
return v === true ? -1 : v === false ? 1 : v
})
return (res = v1 < v2 ? -1 : v1 > v2 ? 1 : 0)
})
return res
}
// ===================================================================
export const hasLicenseRestrictions = host => {
const licenseType = host.license_params.sku_type
return (
host.productBrand !== 'XCP-ng' &&
versionSatisfies(host.version, '>=7.3.0') &&
(licenseType === 'free' || licenseType === 'express')
)
}
// ===================================================================
export const adminOnly = Component =>
connectStore({
_isAdmin: isAdmin,
})(({ _isAdmin, ...props }) =>
_isAdmin ? <Component {...props} /> : <_NotFound />
)
// ===================================================================
export const TryXoa = ({ page }) => (
<a
href={`https://xen-orchestra.com/#/xoa?pk_campaign=xoa_source_upgrade&pk_kwd=${page}`}
>
{_('tryXoa')}
</a>
)