forked from labring/sealos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.ts
More file actions
470 lines (416 loc) · 12.4 KB
/
Copy pathtools.ts
File metadata and controls
470 lines (416 loc) · 12.4 KB
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
import { I18nCommonKey } from '@/types/i18next';
import { useMessage } from '@sealos/ui';
import { addHours, format, set, startOfDay } from 'date-fns';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import { useTranslation } from 'next-i18next';
import { DBTypeEnum } from '@/constants/db';
dayjs.extend(utc);
dayjs.extend(timezone);
import yaml from 'js-yaml';
import ini from 'ini';
import { DBType, PodDetailType } from '@/types/db';
import { BinaryScale, Quantity, Scale } from '@sealos/shared';
export const formatTime = (time: string | number | Date, format = 'YYYY-MM-DD HH:mm:ss') => {
return dayjs(time).tz('Asia/Shanghai').format(format);
};
/**
* copy text data
*/
export const useCopyData = () => {
const { message: toast } = useMessage();
const { t } = useTranslation();
return {
copyData: (data: string, title: I18nCommonKey = 'copy_success') => {
try {
const textarea = document.createElement('textarea');
textarea.value = data;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
toast({
title: t(title),
status: 'success',
duration: 1000
});
} catch (error) {
console.error(error);
toast({
title: t('copy_failed'),
status: 'error'
});
}
}
};
};
/**
* A hook that provides clipboard functionality with error handling and i18n support.
*
* @returns {Object} An object containing clipboard utility functions
* @returns {Function} getClipboardData - Async function to read text from clipboard
* @throws {Error} When clipboard API is not supported or permission is denied
*
* @example
* const { getClipboardData } = useClipboard();
* const text = await getClipboardData();
*/
export const useClipboard = () => {
const { message: toast } = useMessage();
const { t } = useTranslation();
return {
getClipboardData: async () => {
try {
if (!navigator.clipboard) {
toast({
title: t('clipboard_unsupported'),
status: 'error'
});
return;
}
const clipboardData = await navigator.clipboard.readText();
return clipboardData;
} catch (error) {
console.error(error);
toast({
title: t('clipboard_read_failed'),
status: 'error'
});
}
}
};
};
/**
* format string to number or ''
*/
export const str2Num = (str?: string | number) => {
return !!str ? +str : 0;
};
/**
* Format CPU value to standard C format
* @param cpu CPU value, like "500m", "1", "2"
* @returns Standardized CPU value with C suffix, like "0.5C", "1C", "2C"
*
* @deprecated We need to migrate all resource representations to Quantity (in the near future).
*/
export const cpuFormatToC = (cpu: string | number = '0'): string => {
if (!cpu || cpu === '0') {
return '0C';
}
let value: number;
const cpuStr = cpu.toString();
if (/m$/i.test(cpuStr)) {
// Handle values with 'm' suffix, like "500m"
value = parseFloat(cpuStr) / 1000;
} else {
// Handle values without unit, like "1", "2"
value = parseFloat(cpuStr);
}
return `${value.toFixed(1)}C`;
};
/**
* Format memory value to standard Gi format
* @param memory Memory value, like "512Mi", "1Gi", "2048Mi"
* @returns Standardized memory value with Gi suffix, like "0.5Gi", "1Gi", "2Gi"
*
* @deprecated We need to migrate all resource representations to Quantity (in the near future).
*/
export const memoryFormatToGi = (memory: string | number = '0'): string => {
return Quantity.fromJSON(memory).formatForDisplay({
scale: BinaryScale.Gibi,
round: false,
digits: 3
});
};
/**
* storage format ()
*
* @deprecated We need to migrate all resource representations to Quantity (in the near future).
*/
export const storageFormatToNum = (storage = '0') => {
return (
Math.round(Number(Quantity.fromJSON(storage).scaledBinaryValue(BinaryScale.Gibi)) * 100) / 100
);
};
/**
* Parse storage value to Gi units
* @param value Storage value string
* @param defaultValue Default value if parsing fails
* @returns Storage value in Gi units
*
* @deprecated We need to migrate all resource representations to Quantity (in the near future).
*/
export const storageFormatToGi = (value: string | undefined, defaultValue: number = 0): number => {
try {
return (
Math.round(Number(Quantity.fromJSON(value).scaledBinaryValue(BinaryScale.Gibi)) * 100) / 100
);
} catch {
return defaultValue;
}
};
/**
* print memory to Mi of Gi
*
* @deprecated We need to migrate all resource representations to Quantity (in the near future).
*/
export const printMemory = (val: number) => {
return Quantity.newScaledQuantity(BigInt(val), Scale.Mega)
.withFormat('BinarySI')
.formatForDisplay();
};
/**
* format pod createTime
*/
export const formatPodTime = (createTimeStamp: Date = new Date()) => {
const podStartTimeStamp = dayjs(createTimeStamp);
let timeDiff = Math.floor(dayjs().diff(podStartTimeStamp) / 1000);
// 计算天数
const days = Math.floor(timeDiff / (24 * 60 * 60));
timeDiff -= days * 24 * 60 * 60;
// 计算小时数
const hours = Math.floor(timeDiff / (60 * 60));
timeDiff -= hours * 60 * 60;
// 计算分钟数
const minutes = Math.floor(timeDiff / 60);
timeDiff -= minutes * 60;
// 计算秒数
const seconds = timeDiff;
if (days > 0) {
return `${days}d${hours}h`;
}
if (hours > 0) {
return `${hours}h${minutes}m`;
}
if (minutes > 0) {
return `${minutes}m${seconds}s`;
}
return `${seconds}s`;
};
/**
* 下载文件到本地
*/
export function downLoadBold(content: BlobPart, type: string, fileName: string) {
// 创建一个 Blob 对象
const blob = new Blob([content], { type });
// 创建一个 URL 对象
const url = URL.createObjectURL(blob);
// 创建一个 a 标签
const link = document.createElement('a');
link.href = url;
link.download = fileName;
// 模拟点击 a 标签下载文件
link.click();
}
export const getErrText = (err: any, def = '') => {
const msg = typeof err === 'string' ? err : err?.message || def || '';
msg && console.log('error =>', msg);
return msg;
};
export const convertCronTime = (cronTime: string, offset: 8 | -8) => {
let [minute, hour, dayOfMonth, month, dayOfWeek] = cronTime.split(' ');
if (hour === '*') return cronTime;
const cronDate = set(startOfDay(new Date()), { hours: +hour, minutes: +minute });
const newCronDate = addHours(cronDate, offset);
// 更新 cron 时间表达式的各个部分
minute = format(newCronDate, 'mm');
hour = format(newCronDate, 'HH');
// 处理星期几
const daysOfWeek =
dayOfWeek === '*'
? [dayOfWeek]
: dayOfWeek.split(',').map((day) => {
if (offset < 0) {
const newDay = +day + (+hour >= 16 ? -1 : 0);
return newDay === -1 ? '7' : String(newDay);
}
const newDay = +day + (+hour < 8 ? 1 : 0);
return newDay === 7 ? '0' : String(newDay);
});
return `${minute} ${hour} ${dayOfMonth} ${month} ${daysOfWeek.join(',')}`;
};
// convertBytes 1024
export const convertBytes = (bytes: number, unit: 'kb' | 'mb' | 'gb' | 'tb') => {
switch (unit.toLowerCase()) {
case 'kb':
return bytes / 1024;
case 'mb':
return bytes / Math.pow(1024, 2);
case 'gb':
return bytes / Math.pow(1024, 3);
case 'tb':
return bytes / Math.pow(1024, 4);
default:
return bytes;
}
};
// formatTime second to day, hour or minute
export const formatTimeToDay = (seconds: number): { time: string; unit: I18nCommonKey } => {
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(seconds / 3600);
const days = Math.floor(seconds / (3600 * 24));
if (days > 0) {
return {
unit: 'Day',
time: (seconds / (3600 * 24)).toFixed(1)
};
} else if (hours > 0) {
return {
unit: 'Hour',
time: (seconds / 3600).toFixed(1)
};
} else {
return {
unit: 'start_minute',
time: (seconds / 60).toFixed(1)
};
}
};
export function encodeToHex(input: string) {
const encoded = Buffer.from(input).toString('hex');
return encoded;
}
export function decodeFromHex(encoded: string) {
const decoded = Buffer.from(encoded, 'hex').toString('utf-8');
return decoded;
}
export const parseConfig = ({
type,
configString
}: {
type: 'ini' | 'yaml';
configString: string;
}): Object => {
if (type === 'ini') {
return ini.parse(configString);
} else if (type === 'yaml') {
return yaml.load(configString) as Object;
} else {
throw new Error(`Unsupported config type: ${type}`);
}
};
export const flattenObject = (ob: any, prefix: string = ''): { key: string; value: string }[] => {
const result: { key: string; value: string }[] = [];
for (const i in ob) {
const key = prefix ? `${prefix}.${i}` : i;
if (typeof ob[i] === 'object' && ob[i] !== null) {
result.push(...flattenObject(ob[i], key));
} else {
result.push({ key, value: String(ob[i]) });
}
}
return result;
};
export const adjustDifferencesForIni = (
differences: { path: string; oldValue: any; newValue: any }[],
type: 'ini' | 'yaml',
dbType: DBType
): { path: string; newValue: string; oldValue: string }[] => {
if (type !== 'ini' || dbType === 'postgresql') {
return differences;
}
return differences.map((diff) => {
const pathParts = diff.path.split('.');
const adjustedPath = pathParts.slice(1).join('.');
return {
path: adjustedPath,
newValue: diff.newValue,
oldValue: diff.oldValue
};
});
};
/**
* Formats a number by rounding to 2 decimal places and removing trailing zeros
* @param num - The number to format
* @returns The formatted number as a string
*/
export function formatNumber(num: number) {
let rounded = Math.round(num * 100) / 100;
let str = rounded.toString();
if (str.indexOf('.') === -1) {
return str;
} else {
return str.replaceAll('0', '');
}
}
/**
* Parses a database connection URL string into its components
* @param url - The database connection URL to parse
* @returns An object containing the parsed URL components:
* - protocol: The URL protocol without trailing colon
* - hostname: The host name
* - port: The port number
* - username: The username for authentication
* - password: The password for authentication
* - pathname: The database name without leading slash
* @throws {Error} When the URL format is invalid
*/
export function parseDatabaseUrl(url: string) {
try {
const parsedUrl = new URL(url);
return {
protocol: parsedUrl.protocol.slice(0, -1),
hostname: parsedUrl.hostname,
port: parsedUrl.port,
username: parsedUrl.username,
password: parsedUrl.password,
pathname: parsedUrl.pathname.substring(1)
};
} catch (error) {
throw new Error('Invalid URL format');
}
}
enum MasterRoleName {
master = 'master',
primary = 'primary',
leader = 'leader'
}
enum SlaveRoleName {
slave = 'slave',
secondary = 'secondary',
follower = 'follower'
}
type PodRoleName = `${MasterRoleName | SlaveRoleName}`;
export function getPodRoleName(pod: PodDetailType): {
role: PodRoleName;
isMaster: boolean;
isCreating: boolean;
} {
if (pod?.metadata?.labels !== undefined) {
const role = pod.metadata.labels['kubeblocks.io/role'] as PodRoleName;
if (role !== undefined) {
return {
role,
isMaster:
role === MasterRoleName.master ||
role === MasterRoleName.primary ||
role === MasterRoleName.leader,
isCreating: false
};
}
}
return {
role: 'slave',
isMaster: false,
isCreating: true
};
}
export const getScore = (dbType: DBType, cpu: number, memory: number) => {
const cpuCores = cpu / 1000; // cpu in cores
const memoryGB = memory / 1024; // memory in GB
let score = 0;
if (
dbType === DBTypeEnum.postgresql ||
dbType === DBTypeEnum.mongodb ||
dbType === DBTypeEnum.mysql
) {
score = Math.min(cpuCores * 400 + memoryGB * 300, 100000);
} else if (dbType === DBTypeEnum.redis) {
score = Math.min(cpuCores * 1000 + memoryGB * 500, 100000);
}
return Math.floor(score);
};
export type RequiredByKeys<T, K extends keyof T> = {
[P in K]-?: T[P];
} & Pick<T, Exclude<keyof T, K>>;