@datatruck/cli 0.38.2 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -645,9 +645,6 @@
645
645
  "server": {
646
646
  "type": "object",
647
647
  "properties": {
648
- "log": {
649
- "type": "boolean"
650
- },
651
648
  "repository": {
652
649
  "type": "object",
653
650
  "properties": {
@@ -757,14 +754,46 @@
757
754
  "type": "object",
758
755
  "properties": {
759
756
  "enabled": {
757
+ "default": true,
760
758
  "type": "boolean"
761
759
  },
762
- "logPath": {
763
- "default": "'/var/logs/datatruck'",
764
- "type": [
765
- "string",
766
- "boolean"
767
- ]
760
+ "log": {
761
+ "type": "object",
762
+ "properties": {
763
+ "enabled": {
764
+ "default": true,
765
+ "type": "boolean"
766
+ },
767
+ "path": {
768
+ "default": "/var/logs/datatruck",
769
+ "type": "string"
770
+ },
771
+ "rotate": {
772
+ "type": "object",
773
+ "properties": {
774
+ "maxAge": {
775
+ "default": {
776
+ "days": 14
777
+ },
778
+ "type": "object",
779
+ "properties": {
780
+ "days": {
781
+ "type": "number"
782
+ },
783
+ "hours": {
784
+ "type": "number"
785
+ },
786
+ "minutes": {
787
+ "type": "number"
788
+ }
789
+ },
790
+ "additionalProperties": false
791
+ }
792
+ },
793
+ "additionalProperties": false
794
+ }
795
+ },
796
+ "additionalProperties": false
768
797
  }
769
798
  },
770
799
  "additionalProperties": false
@@ -23,7 +23,6 @@ class RunCommand extends CommandAbstract_1.CommandAbstract {
23
23
  async exec() {
24
24
  const config = await ConfigAction_1.ConfigAction.fromGlobalOptionsWithPath(this.globalOptions);
25
25
  const verbose = !!this.globalOptions.verbose;
26
- const log = config.data.server?.log ?? true;
27
26
  const jobs = config.data.jobs || {};
28
27
  const jobName = this.options.jobName;
29
28
  const job = jobName ? jobs[jobName] : undefined;
@@ -33,10 +32,9 @@ class RunCommand extends CommandAbstract_1.CommandAbstract {
33
32
  return { exitCode: 1 };
34
33
  }
35
34
  await (0, job_1.runJob)(job, jobName, {
36
- log,
37
35
  verbose: verbose,
38
36
  configPath: config.path,
39
- logPath: config.data.server?.cron?.logPath,
37
+ log: "inherit",
40
38
  });
41
39
  return { exitCode: 0 };
42
40
  }
@@ -23,12 +23,10 @@ class StartServerCommand extends CommandAbstract_1.CommandAbstract {
23
23
  const config = await ConfigAction_1.ConfigAction.fromGlobalOptions(this.globalOptions);
24
24
  const configPath = this.configPath;
25
25
  const verbose = !!this.globalOptions.verbose;
26
- const log = config.server?.log ?? true;
27
26
  const repositoryOptions = config.server?.repository || {};
28
27
  if (repositoryOptions.enabled ?? true) {
29
28
  const server = (0, repository_server_1.createDatatruckRepositoryServer)(repositoryOptions, {
30
29
  configPath,
31
- log,
32
30
  });
33
31
  const port = repositoryOptions.listen?.port ?? 8888;
34
32
  const address = repositoryOptions.listen?.address ?? "127.0.0.1";
@@ -40,18 +38,15 @@ class StartServerCommand extends CommandAbstract_1.CommandAbstract {
40
38
  server.listen(port, address);
41
39
  }
42
40
  const cronOptions = config.server?.cron || {};
43
- const logPath = config.server?.cron?.logPath;
44
41
  if (cronOptions.enabled ?? true) {
45
42
  if (typeof configPath !== "string")
46
43
  throw new error_1.AppError(`Config path is required by cron server`);
47
44
  const server = await (0, cron_server_1.createCronServer)({
48
45
  configPath,
49
46
  verbose,
50
- log,
51
- logPath,
47
+ log: config.server?.cron?.log,
52
48
  });
53
49
  server.start();
54
- (0, cli_1.logJson)("cron-server", `server started`);
55
50
  }
56
51
  const exitCode = await new Promise((resolve) => {
57
52
  process.on("SIGINT", () => resolve(1)).on("SIGTERM", () => resolve(1));
@@ -23,7 +23,6 @@ export type Config = {
23
23
  prunePolicy?: DatatruckPolicyConfig;
24
24
  };
25
25
  export type DatatruckServerOptions = {
26
- log?: boolean;
27
26
  repository?: DatatruckRepositoryServerOptions;
28
27
  cron?: DatatruckCronServerOptions;
29
28
  };
@@ -1,11 +1,26 @@
1
+ import { MaxAge } from "../logs";
1
2
  import { JobConfig } from "./job";
2
- export declare const defaultsLogPath: string;
3
3
  export type DatatruckCronServerOptions = {
4
- enabled?: boolean;
5
4
  /**
6
- * @default '/var/logs/datatruck'
5
+ * @default true
7
6
  */
8
- logPath?: string | boolean;
7
+ enabled?: boolean;
8
+ log?: {
9
+ /**
10
+ * @default true
11
+ */
12
+ enabled?: boolean;
13
+ /**
14
+ * @default "/var/logs/datatruck"
15
+ */
16
+ path?: string;
17
+ rotate?: {
18
+ /**
19
+ * @default {"days":14}
20
+ */
21
+ maxAge?: MaxAge;
22
+ };
23
+ };
9
24
  };
10
25
  export declare function createCronServer(options: JobConfig): Promise<{
11
26
  start: () => void;
@@ -1,18 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createCronServer = exports.defaultsLogPath = void 0;
3
+ exports.createCronServer = void 0;
4
4
  const ConfigAction_1 = require("../../actions/ConfigAction");
5
5
  const cli_1 = require("../cli");
6
6
  const cron_1 = require("../cron");
7
+ const logs_1 = require("../logs");
7
8
  const string_1 = require("../string");
8
9
  const watcher_1 = require("../watcher");
9
10
  const job_1 = require("./job");
10
11
  const croner_1 = require("croner");
11
- const os_1 = require("os");
12
- const path_1 = require("path");
13
- exports.defaultsLogPath = (0, os_1.platform)() === "win32"
14
- ? (0, path_1.join)(process.env.APPDATA ?? `${process.env.HOMEDRIVE ?? "C:"}\\ProgramData`, "datatruck\\logs")
15
- : "/var/logs/datatruck";
16
12
  function createCrons(jobs, options) {
17
13
  const crons = [];
18
14
  for (const name in jobs) {
@@ -34,31 +30,55 @@ async function createCronServer(options) {
34
30
  config: options.configPath,
35
31
  });
36
32
  let crons = createCrons(config.jobs || {}, options);
33
+ let log = config.server?.cron?.log;
34
+ const getLogPath = () => log?.path ?? logs_1.defaultsLogPath;
35
+ let reloading = false;
37
36
  const watcher = (0, watcher_1.createWatcher)({
38
37
  onRead: () => ConfigAction_1.ConfigAction.findAndParseFile(options.configPath),
39
38
  onCheck: (prev, current) => (0, string_1.compareJsons)(prev, current),
40
39
  onError: (error) => {
41
- if (options.log) {
42
- (0, cli_1.logJson)("cron-server", "job update error");
43
- console.error(error);
44
- }
40
+ (0, cli_1.logJson)("cron-server", "job update error");
41
+ console.error(error);
45
42
  },
46
43
  onChange: (data) => {
47
- if (options.log)
48
- (0, cli_1.logJson)("cron-server", "jobs updated");
49
- handler.stop();
50
- const enabled = data?.server?.cron?.enabled ?? true;
51
- crons = enabled ? createCrons(data?.jobs || {}, options) : [];
52
- handler.start();
44
+ (0, cli_1.logJson)("cron-server", "jobs updated");
45
+ try {
46
+ reloading = true;
47
+ handler.stop();
48
+ const enabled = data?.server?.cron?.enabled ?? true;
49
+ crons = enabled ? createCrons(data?.jobs || {}, options) : [];
50
+ log = data?.server?.cron?.log;
51
+ handler.start();
52
+ }
53
+ finally {
54
+ reloading = false;
55
+ }
53
56
  },
54
57
  });
58
+ let rotateLogsInterval;
59
+ const rotateLogs = async () => {
60
+ const removed = await (0, logs_1.removeOldLogs)(getLogPath(), log?.rotate?.maxAge ?? { days: 14 });
61
+ if (removed.length)
62
+ (0, cli_1.logJson)("cron-server", "old logs removed", {
63
+ amount: removed.length,
64
+ });
65
+ };
55
66
  const handler = {
56
67
  start: () => {
68
+ if (!reloading) {
69
+ (0, cli_1.logJson)("cron-server", `server started`, {
70
+ "log.path": getLogPath(),
71
+ });
72
+ clearInterval(rotateLogsInterval);
73
+ rotateLogsInterval = setInterval(rotateLogs, 60_000);
74
+ }
57
75
  for (const cron of crons)
58
76
  cron.resume();
59
77
  watcher.start();
60
78
  },
61
79
  stop: () => {
80
+ if (!reloading)
81
+ clearInterval(rotateLogsInterval);
62
82
  watcher.stop();
63
83
  for (const cron of crons)
64
84
  cron.stop();
@@ -1,6 +1,7 @@
1
1
  import { BackupCommandOptions } from "../../commands/BackupCommand";
2
2
  import { CopyCommandOptions } from "../../commands/CopyCommand";
3
3
  import { PruneCommandOptions } from "../../commands/PruneCommand";
4
+ import { DatatruckCronServerOptions } from "./cron-server";
4
5
  export type JobScheduleObject = {
5
6
  minute?: number | {
6
7
  each: number;
@@ -33,8 +34,7 @@ export type Job = JobAction & {
33
34
  schedule?: JobSchedule;
34
35
  };
35
36
  export type JobConfig = {
36
- log: boolean;
37
- logPath: string | boolean | undefined;
37
+ log: DatatruckCronServerOptions["log"] | "inherit";
38
38
  verbose: boolean;
39
39
  configPath: string;
40
40
  };
@@ -4,12 +4,31 @@ exports.runJob = void 0;
4
4
  const async_process_1 = require("../async-process");
5
5
  const cli_1 = require("../cli");
6
6
  const fs_1 = require("../fs");
7
+ const logs_1 = require("../logs");
7
8
  const options_1 = require("../options");
8
9
  const command_1 = require("./command");
9
- const cron_server_1 = require("./cron-server");
10
10
  const fs_2 = require("fs");
11
11
  const promises_1 = require("fs/promises");
12
12
  const path_1 = require("path");
13
+ async function createJobLog(config, name) {
14
+ if (typeof config === "object" && (config?.enabled ?? true)) {
15
+ const dt = new Date().toISOString().replaceAll(":", "-");
16
+ const dir = config?.path ?? logs_1.defaultsLogPath;
17
+ const tmpLogPath = (0, path_1.join)(dir, `${dt}_${name}.tmp.log`);
18
+ await (0, promises_1.mkdir)(dir, { recursive: true });
19
+ return {
20
+ type: "file",
21
+ dt,
22
+ dir,
23
+ stream: (0, fs_2.createWriteStream)(tmpLogPath),
24
+ };
25
+ }
26
+ else if (config === "inherit") {
27
+ return {
28
+ type: "inherit",
29
+ };
30
+ }
31
+ }
13
32
  async function runJob(job, name, config) {
14
33
  let pid = 0;
15
34
  try {
@@ -19,14 +38,6 @@ async function runJob(job, name, config) {
19
38
  ? ({ ...job.options, confirm: true })
20
39
  : job.options);
21
40
  const [node, bin] = process.argv;
22
- const baseLogPath = typeof config.logPath === "string"
23
- ? config.logPath
24
- : config.logPath === true || config.logPath === undefined
25
- ? cron_server_1.defaultsLogPath
26
- : config.logPath;
27
- let stream;
28
- let logPath;
29
- const dt = new Date().toISOString().replaceAll(":", "-");
30
41
  const argv = [
31
42
  process.env.DTT_BIN_SCRIPT ?? process.env.pm_exec_path ?? bin,
32
43
  "--tty",
@@ -38,12 +49,9 @@ async function runJob(job, name, config) {
38
49
  job.action,
39
50
  ...cliOptions,
40
51
  ];
41
- if (baseLogPath) {
42
- const tmpLogPath = (0, path_1.join)(baseLogPath, dt) + ".log";
43
- await (0, promises_1.mkdir)(baseLogPath, { recursive: true });
44
- stream = (0, fs_2.createWriteStream)(tmpLogPath);
45
- stream.write(`+ dtt ${argv.join(" ")}\n`);
46
- }
52
+ const log = await createJobLog(config.log, name);
53
+ if (log?.type === "file")
54
+ log.stream.write(`+ dtt ${argv.join(" ")}\n`);
47
55
  const p = new async_process_1.AsyncProcess(node, argv, {
48
56
  $log: config.verbose,
49
57
  $exitCode: false,
@@ -53,29 +61,33 @@ async function runJob(job, name, config) {
53
61
  NO_COLOR: "1",
54
62
  JOB_NAME: name,
55
63
  },
64
+ ...(log?.type === "inherit" && {
65
+ stdio: "inherit",
66
+ }),
56
67
  });
57
68
  pid = p.child.pid || 0;
58
- if (config.log)
59
- (0, cli_1.logJson)("job", `'${name}' started`, { pid });
69
+ (0, cli_1.logJson)("job", `'${name}' started`, { pid });
60
70
  const [exitCode] = await Promise.all([
61
71
  p.waitForClose(),
62
- stream && p.stderr.pipe(stream),
63
- stream && p.stdout.pipe(stream),
72
+ ...(log?.stream
73
+ ? [p.stderr.pipe(log?.stream), p.stdout.pipe(log?.stream)]
74
+ : []),
64
75
  ]);
65
- if (stream) {
66
- const base = (0, path_1.dirname)(stream.path.toString());
67
- await (0, fs_1.safeRename)(stream.path.toString(), (logPath = (0, path_1.join)(base, `${dt}-${pid}.log`)));
76
+ let logData = {};
77
+ if (log?.stream) {
78
+ const base = (0, path_1.dirname)(log?.stream.path.toString());
79
+ const logPath = (0, path_1.join)(base, `${log.dt}_${name}_${pid}.log`);
80
+ await (0, fs_1.safeRename)(log?.stream.path.toString(), logPath);
81
+ logData["log"] = logPath;
68
82
  }
69
- if (config.log)
70
- (0, cli_1.logJson)("job", `'${name}' finished`, {
71
- pid,
72
- exitCode,
73
- ...(logPath && { log: logPath }),
74
- });
83
+ (0, cli_1.logJson)("job", `'${name}' finished`, {
84
+ pid,
85
+ exitCode,
86
+ ...logData,
87
+ });
75
88
  }
76
89
  catch (error) {
77
- if (config.log)
78
- (0, cli_1.logJson)("job", `'${name}' failed`, { pid });
90
+ (0, cli_1.logJson)("job", `'${name}' failed`, { pid });
79
91
  console.error(error);
80
92
  }
81
93
  }
@@ -37,7 +37,6 @@ export declare const headerKey: {
37
37
  password: string;
38
38
  };
39
39
  export declare function createDatatruckRepositoryServer(inOptions: Omit<DatatruckRepositoryServerOptions, "listen">, config?: {
40
- log?: boolean;
41
40
  configPath?: string;
42
41
  }): import("http").Server<typeof IncomingMessage, typeof import("http").ServerResponse>;
43
42
  export {};
@@ -80,8 +80,7 @@ function createDatatruckRepositoryServer(inOptions, config = {}) {
80
80
  const backend = findRepositoryBackend(req, repository, options);
81
81
  if (!backend)
82
82
  return res.writeHead(401);
83
- if (config.log)
84
- (0, cli_1.logJson)("repository-server", "request", { id, repository, url });
83
+ (0, cli_1.logJson)("repository-server", "request", { id, repository, url });
85
84
  const fs = new virtual_fs_1.LocalFs({ backend: backend.path });
86
85
  if (action === "comcheck") {
87
86
  res.write(JSON.stringify({ success: true }));
@@ -111,14 +110,11 @@ function createDatatruckRepositoryServer(inOptions, config = {}) {
111
110
  if (json !== undefined)
112
111
  res.write(JSON.stringify(json));
113
112
  }
114
- if (config.log)
115
- (0, cli_1.logJson)("repository-server", "request finished", { id });
113
+ (0, cli_1.logJson)("repository-server", "request finished", { id });
116
114
  }
117
115
  catch (error) {
118
- if (config.log) {
119
- (0, cli_1.logJson)("repository-server", "request failed", { id });
120
- console.error(error);
121
- }
116
+ (0, cli_1.logJson)("repository-server", "request failed", { id });
117
+ console.error(error);
122
118
  if (!res.writableEnded && !res.headersSent)
123
119
  res.writeHead(500, error.message);
124
120
  }
@@ -0,0 +1,8 @@
1
+ export type MaxAge = {
2
+ days?: number;
3
+ hours?: number;
4
+ minutes?: number;
5
+ };
6
+ export declare function maxAgeToMS(input: MaxAge): number;
7
+ export declare const defaultsLogPath: string;
8
+ export declare function removeOldLogs(path: string, inMaxAge: MaxAge): Promise<string[]>;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.removeOldLogs = exports.defaultsLogPath = exports.maxAgeToMS = void 0;
4
+ const promises_1 = require("fs/promises");
5
+ const os_1 = require("os");
6
+ const path_1 = require("path");
7
+ const maxAgeUnits = {
8
+ minutes: () => 60 * 1000,
9
+ hours: () => 60 * maxAgeUnits.minutes(),
10
+ days: () => 24 * maxAgeUnits.hours(),
11
+ };
12
+ function maxAgeToMS(input) {
13
+ let ms = 0;
14
+ for (const key in input) {
15
+ const units = input[key];
16
+ if (units && units >= 0) {
17
+ const factor = maxAgeUnits[key]();
18
+ ms += units * factor;
19
+ }
20
+ }
21
+ return ms;
22
+ }
23
+ exports.maxAgeToMS = maxAgeToMS;
24
+ exports.defaultsLogPath = (0, os_1.platform)() === "win32"
25
+ ? (0, path_1.join)(process.env.APPDATA ?? `${process.env.HOMEDRIVE ?? "C:"}\\ProgramData`, "datatruck\\logs")
26
+ : "/var/logs/datatruck";
27
+ async function removeOldLogs(path, inMaxAge) {
28
+ const maxAge = maxAgeToMS(inMaxAge);
29
+ const hasMaxAge = Object.values(inMaxAge).some((v) => typeof v === "number");
30
+ if (!hasMaxAge)
31
+ return [];
32
+ const files = (await (0, promises_1.readdir)(path)).filter((file) => file.endsWith(".log"));
33
+ const now = Date.now();
34
+ const paths = [];
35
+ for (const file of files) {
36
+ const filePath = (0, path_1.join)(path, file);
37
+ const { mtimeMs } = await (0, promises_1.stat)((0, path_1.join)(path, file));
38
+ const ms = now - mtimeMs;
39
+ if (ms > maxAge) {
40
+ await (0, promises_1.rm)(filePath);
41
+ paths.push(filePath);
42
+ }
43
+ }
44
+ return paths;
45
+ }
46
+ exports.removeOldLogs = removeOldLogs;
@@ -22,12 +22,12 @@ export declare function createMysqlCli(options: MysqlCliOptions): Promise<{
22
22
  dump: (input: {
23
23
  output: string;
24
24
  database: string;
25
- items?: string[] | undefined;
26
- onlyStoredPrograms?: boolean | undefined;
27
- controller?: AbortController | undefined;
28
- onProgress?: ((data: {
25
+ items?: string[];
26
+ onlyStoredPrograms?: boolean;
27
+ controller?: AbortController;
28
+ onProgress?: (data: {
29
29
  totalBytes: number;
30
- }) => void) | undefined;
30
+ }) => void;
31
31
  }) => Promise<void>;
32
32
  assertDumpFile: typeof assertDumpFile;
33
33
  fetchTableNames: (database: string, include?: string[], exclude?: string[]) => Promise<string[]>;
@@ -68,9 +68,9 @@ exports.createCommand = createCommand;
68
68
  function stringifyOptions(options, object) {
69
69
  const result = [];
70
70
  const prepend = [];
71
- for (const key in options) {
72
- const option = options[key];
73
- const value = object[key];
71
+ for (const name in options) {
72
+ const option = options[name];
73
+ const value = object[name];
74
74
  if (value === undefined)
75
75
  continue;
76
76
  if (option.flag === false) {
@@ -79,7 +79,7 @@ function stringifyOptions(options, object) {
79
79
  else {
80
80
  const flag = option.shortFlag
81
81
  ? `-${option.shortFlag}`
82
- : `--${option.flag ?? option.shortFlag}`;
82
+ : `--${option.flag ?? name}`;
83
83
  if (option.value === "boolean") {
84
84
  if (option.value)
85
85
  result.push(flag);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@datatruck/cli",
3
- "version": "0.38.2",
3
+ "version": "0.39.0",
4
4
  "description": "Tool for creating and managing backups",
5
5
  "homepage": "https://github.com/swordev/datatruck#readme",
6
6
  "bugs": {
@@ -35,7 +35,7 @@
35
35
  "dayjs": "^1.11.10",
36
36
  "fast-folder-size": "^2.2.0",
37
37
  "fast-glob": "^3.3.2",
38
- "listr2": "^8.0.2",
38
+ "listr2": "^8.2.1",
39
39
  "micromatch": "^4.0.5",
40
40
  "mysql2": "^3.9.3",
41
41
  "tty-table": "^4.2.3",