Compare commits

..

56 Commits
0.6 ... 0.11

Author SHA1 Message Date
cupcakearmy
678aa96c06 version bump 2019-12-21 23:38:07 +01:00
cupcakearmy
e51eacf13c support for tilde in optional arguments 2019-12-21 23:37:44 +01:00
12d2e010bb Update README.md 2019-12-10 14:03:13 +01:00
e25e65e052 Update README.md 2019-12-10 14:02:24 +01:00
4491cfd536 Update README.md 2019-12-10 14:00:44 +01:00
d0e82b47e1 Update README.md 2019-12-10 13:59:11 +01:00
cupcakearmy
90f9a998e8 Merge remote-tracking branch 'origin/master' 2019-12-10 13:45:09 +01:00
cupcakearmy
b40adcae1f added command to display some info about the config file 2019-12-10 13:44:59 +01:00
cupcakearmy
ad5afab355 version bump 2019-12-10 13:44:41 +01:00
cupcakearmy
5b0011330c now shows elapsed time on each backup and some depulication of code 2019-12-10 13:44:30 +01:00
fd2fd91635 Update README.md 2019-12-05 00:31:41 +01:00
9c09ce1d79 Update README.md 2019-12-05 00:31:05 +01:00
c2f6f51789 Update README.md 2019-12-05 00:27:01 +01:00
cupcakearmy
f09cf90653 hooks for backups 2019-12-05 00:24:20 +01:00
cupcakearmy
d352aced37 version bump 2019-12-05 00:24:11 +01:00
cupcakearmy
563d4ffb96 remove duplicate code 2019-12-05 00:23:49 +01:00
cupcakearmy
1c6a061dd1 cleanup types 2019-12-05 00:23:15 +01:00
cupcakearmy
504ad639ab function to convert a variable to an array if its not already 2019-12-05 00:23:06 +01:00
f7a15c6d86 Update README.md 2019-12-05 00:22:01 +01:00
cupcakearmy
2f0092befe Merge remote-tracking branch 'origin/master' 2019-12-04 23:50:07 +01:00
cupcakearmy
1026e68b68 version bump 2019-12-04 23:49:39 +01:00
2389c59aa9 Update README.md 2019-12-04 23:48:22 +01:00
087aeaf578 Update README.md 2019-12-04 23:43:01 +01:00
3b7062f733 Update README.md 2019-12-04 23:39:19 +01:00
cupcakearmy
96b63c744b switch to yarn & update typescript 2019-12-04 23:36:49 +01:00
cupcakearmy
9669b70e20 refactor forget and make compatible with new options api 2019-12-04 23:36:27 +01:00
cupcakearmy
bcb081234c formatting 2019-12-04 23:36:04 +01:00
cupcakearmy
336f44e9dc simplify for 2019-12-04 23:35:41 +01:00
cupcakearmy
d0cda7f1d5 always convert to string 2019-12-04 23:35:26 +01:00
cupcakearmy
a8f4c23254 version bump 2019-12-04 20:53:06 +01:00
cupcakearmy
1c9f6d7d91 Merge remote-tracking branch 'origin/master' 2019-12-04 20:50:41 +01:00
cupcakearmy
18c3f4a06f use a simpler restore flag 2019-12-04 20:50:32 +01:00
632062a23f Update README.md 2019-12-04 20:50:12 +01:00
3d1d7ba256 Update README.md 2019-12-04 20:45:58 +01:00
cupcakearmy
417c54db4d cleanup 2019-12-04 20:38:59 +01:00
cupcakearmy
a9696bbc0c parse the flags in the config file to an array for the exec command 2019-12-04 20:38:48 +01:00
cupcakearmy
45f7506478 added options to the location type 2019-12-04 20:38:27 +01:00
cupcakearmy
d7cdeafe60 moved around params 2019-12-04 20:38:14 +01:00
cupcakearmy
cf09cdbb30 cleanup and support for exclusion 2019-12-04 20:38:04 +01:00
cupcakearmy
88059fe405 method to get all the backends from a list of locations 2019-12-04 20:37:50 +01:00
cupcakearmy
cdf18430b6 remove old todo 2019-12-03 23:38:49 +01:00
cupcakearmy
352754dad9 formatting & trailing commas 2019-12-03 23:37:55 +01:00
cupcakearmy
b68dc75053 removed unused import 2019-12-03 23:31:20 +01:00
cupcakearmy
6a055d3114 moved path resolver into utils 2019-12-03 23:31:13 +01:00
cupcakearmy
b5daff07eb replace indead of adding 2019-12-03 23:30:53 +01:00
b2d01d77d9 Update README.md 2019-12-03 09:52:11 +01:00
f41c042fce Merge pull request #6 from EliotBerriot/2-forget
Fix #2: support pruning and forget via snapshot policies
2019-12-03 09:43:38 +01:00
a81498ac42 Merge branch 'master' into 2-forget 2019-12-03 09:43:28 +01:00
1731ee30b3 Update README.md 2019-12-03 09:39:51 +01:00
1f4f1a1855 Merge pull request #5 from EliotBerriot/1-s3
Fix #1: fixed broken initialization check under S3
2019-12-03 09:39:25 +01:00
13cb764067 Update README.md 2019-12-03 09:19:26 +01:00
8058f37368 Merge pull request #3 from ChanceM/patch-1
Update README.md spelling correction.
2019-12-03 09:16:02 +01:00
Eliot Berriot
57ffa1e3fa Fix #2: support pruning and forget via snapshot policies 2019-12-02 14:57:10 +01:00
Eliot Berriot
671542cd30 Fix #1: fixed broken initialization check under S3 2019-12-02 11:14:02 +01:00
Gregory Moore
322df9f0bd Update README.md spelling correction.
Habe to have.
2019-11-30 09:53:41 -08:00
cupcakearmy
652158d1ed use bash 2019-11-27 19:30:01 +01:00
12 changed files with 918 additions and 450 deletions

226
README.md
View File

@@ -1,7 +1,7 @@
# autorestic # autorestic
High backup level CLI utility for [restic](https://restic.net/). High backup level CLI utility for [restic](https://restic.net/).
Autorestic is a wrapper around the amazing [restic](https://restic.net/). While being amazing the restic cli can be a bit overwhelming and difficoult to manage if you habe many different location that you want to backup to multiple locations. This utility is aimed at making this easier 🙂 Autorestic is a wrapper around the amazing [restic](https://restic.net/). While being amazing the restic cli can be a bit overwhelming and difficoult to manage if you have many different location that you want to backup to multiple locations. This utility is aimed at making this easier 🙂
![Sketch](./docs/Sketch.png) ![Sketch](./docs/Sketch.png)
@@ -10,13 +10,25 @@ Autorestic is a wrapper around the amazing [restic](https://restic.net/). While
- Config files, no CLI - Config files, no CLI
- Predictable - Predictable
- Backup locations to multiple backends - Backup locations to multiple backends
- Snapshot policies and pruning
- Simple interface - Simple interface
- Fully encrypted - Fully encrypted
## Installation ### 📒 Docs
* [Locations](#-locations)
* [Pruning & Deleting old files](#pruning-and-snapshot-policies)
* [Excluding files](#excluding-filesfolders)
* [Hooks](#before--after-hooks)
* [Backends](#-backends)
* [Commands](#-commands)
## 🛳 Installation
Linux & macOS. Windows is not supported.
``` ```
curl -s https://raw.githubusercontent.com/CupCakeArmy/autorestic/master/install.sh | sh curl -s https://raw.githubusercontent.com/CupCakeArmy/autorestic/master/install.sh | bash
``` ```
## 🚀 Quickstart ## 🚀 Quickstart
@@ -53,24 +65,27 @@ backends:
Then we check if everything is correct by running the `check` command. We will pass the `-a` (or `--all`) to tell autorestic to check all the locations. Then we check if everything is correct by running the `check` command. We will pass the `-a` (or `--all`) to tell autorestic to check all the locations.
``` If we would check only one location we could run the following: `autorestic check -l home`. Otherwise simpply check all locations with `autorestic check -a`
autorestic check -a
```
If we would check only one location we could run the following: `autorestic -l home check`. ##### Note
### Backup Note that the data is automatically encrypted on the server. The key will be generated and added to your config file. Every backend will have a separate key. You should keep a copy of the keys somewhere in case your server dies. Otherwise DATA IS LOST!
### 📦 Backup
``` ```
autorestic backup -a autorestic backup -a
``` ```
### Restore ### 📼 Restore
``` ```
autorestic restore -a -- --target /path/where/to/restore autorestic restore -l home --from hdd --to /path/where/to/restore
``` ```
### 📲 Updates
Autorestic can update itself! Super handy right? Simply run `autorestic update` and we will check for you if there are updates for restic and autorestic and install them if necessary.
## 🗂 Locations ## 🗂 Locations
@@ -85,6 +100,95 @@ locations:
- also-backup-to-this-backend - also-backup-to-this-backend
``` ```
#### Pruning and snapshot policies
Autorestic supports declaring snapshot policies for location to avoid keeping old snapshot around if you don't need them.
This is based on [Restic's snapshots policies](https://restic.readthedocs.io/en/latest/060_forget.html#removing-snapshots-according-to-a-policy), and can be enabled for each location as shown below:
```yaml
locations:
etc:
from: /etc
to: local
options:
forget:
keep-last: 5 # always keep at least 5 snapshots
keep-hourly: 3 # keep 3 last hourly shapshots
keep-daily: 4 # keep 4 last daily shapshots
keep-weekly: 1 # keep 1 last weekly shapshots
keep-monthly: 12 # keep 12 last monthly shapshots
keep-yearly: 7 # keep 7 last yearly shapshots
keep-within: "2w" # keep snapshots from the last 2 weeks
```
Pruning can be triggered using `autorestic forget -a`, for all locations, or selectively with `autorestic forget -l <location>`. **please note that contrary to the restic CLI, `restic forget` will call `restic prune` internally.**
Run with the `--dry-run` flag to only print information about the process without actually pruning the snapshots. This is especially useful for debugging or testing policies:
```
$ autorestic forget -a --dry-run --verbose
Configuring Backends
local : Done ✓
Removing old shapshots according to policy
etc ▶ local : Removing old spnapshots… ⏳
etc ▶ local : Running in dry-run mode, not touching data
etc ▶ local : Forgeting old snapshots… ⏳Applying Policy: all snapshots within 2d of the newest
keep 3 snapshots:
ID Time Host Tags Reasons Paths
-----------------------------------------------------------------------------
531b692a 2019-12-02 12:07:28 computer within 2w /etc
51659674 2019-12-02 12:08:46 computer within 2w /etc
f8f8f976 2019-12-02 12:11:08 computer within 2w /etc
-----------------------------------------------------------------------------
3 snapshots
```
#### Excluding files/folders
If you want to exclude certain files or folders it done easily by specifiyng the right flags in the location you desire to filter. The flags are taken straight from the [restic cli exclude rules](https://restic.readthedocs.io/en/latest/040_backup.html#excluding-files).
```yaml
locations:
my-location:
from: /data
to:
- local
- remote
options:
backup:
exclude:
- '*.nope'
- '*.abc'
exclude-file: .gitignore
backends:
local:
...
remote:
...
```
#### Before / After hooks
Sometimes you might want to stop an app/db before backing up data and start the service again after the backup has completed. This is what the hooks are made for. Simply add them to your location config. You can have as many commands as you wish.
```yaml
locations:
my-location:
from: /data
to:
- local
- remote
hooks:
before:
- echo "Hello"
- echo "Human"
after:
- echo "kthxbye"
```
## 💽 Backends ## 💽 Backends
Backends are the place where you data will be saved. Backups are incremental and encrypted. Backends are the place where you data will be saved. Backups are incremental and encrypted.
@@ -121,9 +225,107 @@ backends:
B2_ACCOUNT_KEY: backblaze_account_key B2_ACCOUNT_KEY: backblaze_account_key
``` ```
## 👉 Commands
* [info](#info)
* [check](#check)
* [backup](#backup)
* [forget](#forget)
* [restore](#restore)
* [exec](#exec)
* [intall](#install)
* [uninstall](#uninstall)
* [upgrade](#upgrade)
##### Note ### Info
Note that the data is automatically encrypted on the server. The key will be generated and added to your config file. Every backend will have a separate key. You should keep a copy of the keys somewhere in case your server dies. Otherwise DATA IS LOST! ```
autorestic info
```
Shows all the information in the config file. Usefull for a quick overview of what location backups where.
Pro tip: if it gets a bit long you can read it more easily with `autorestic info | less` 😉
### Check
```
autorestic check [-b, --backend] [-a, --all]
```
Checks the backends and configures them if needed. Can be applied to all with the `-a` flag or by specifying one or more backends with the `-b` or `--backend` flag.
### Backup
```
autorestic backup [-l, --location] [-a, --all]
```
Performes a backup of all locations if the `-a` flag is passed. To only backup some locations pass one or more `-l` or `--location` flags.
### Restore
```
autorestic restore [-l, --location] [--from backend] [--to <out dir>]
```
This will restore all the locations to the selected target. If for one location there are more than one backends specified autorestic will take the first one.
Lets see a more realistic example (from the config above)
```
autorestic restore -l home --from hdd --to /path/where/to/restore
```
This will restore the location `home` to the `/path/where/to/restore` folder and taking the data from the backend `hdd`
```
autorestic restore
```
Performes a backup of all locations if the `-a` flag is passed. To only backup some locations pass one or more `-l` or `--location` flags.
### Forget
```
autorestic forget [-l, --location] [-a, --all] [--dry-run]
```
This will prune and remove old data form the backends according to the [keep policy you have specified for the location](#pruning-and-snapshot-policies)
The `--dry-run` flag will do a dry run showing what would have been deleted, but won't touch the actual data.
### Exec
```
autorestic exec [-b, --backend] [-a, --all] <command> -- [native options]
```
This is avery handy command which enables you to run any native restic command on desired backends. An example would be listing all the snapshots of all your backends:
```
autorestic exec -a -- snapshots
```
#### Install
Installs both restic and autorestic
#### Uninstall
Uninstall both restic and autorestic
#### Upgrade
Upgrades both restic and autorestic automagically
## Contributors
This amazing people helped the project!
- @ChanceM [Docs]
- @EliotBerriot [Docs, Pruning, S3]

View File

@@ -1,4 +1,4 @@
#!/bin/sh #!/bin/bash
OUT_FILE=/usr/local/bin/autorestic OUT_FILE=/usr/local/bin/autorestic

View File

@@ -4,22 +4,22 @@
"build": "tsc", "build": "tsc",
"build:watch": "tsc -w", "build:watch": "tsc -w",
"dev": "tsnd --no-notify --respawn ./src/autorestic.ts", "dev": "tsnd --no-notify --respawn ./src/autorestic.ts",
"bin": "npm run build && pkg lib/autorestic.js --targets latest-macos-x64,latest-linux-x64 --out-path bin" "bin": "yarn run build && pkg lib/autorestic.js --targets latest-macos-x64,latest-linux-x64 --out-path bin"
}, },
"devDependencies": { "devDependencies": {
"@types/decompress": "^4.2.3",
"@types/js-yaml": "^3.12.1", "@types/js-yaml": "^3.12.1",
"@types/minimist": "^1.2.0", "@types/minimist": "^1.2.0",
"@types/node": "^12.11.7", "@types/node": "^12.11.7",
"pkg": "^4.4.0", "pkg": "^4.4.0",
"ts-node-dev": "^1.0.0-pre.40", "ts-node-dev": "^1.0.0-pre.40",
"typescript": "^3.5.1" "typescript": "^3.7"
}, },
"dependencies": { "dependencies": {
"axios": "^0.19.0", "axios": "^0.19.0",
"clitastic": "0.0.1", "clitastic": "0.0.1",
"colors": "^1.3.3", "colors": "^1.3.3",
"js-yaml": "^3.13.1", "js-yaml": "^3.13.1",
"minimist": "^1.2.0" "minimist": "^1.2.0",
"uhrwerk": "^1.0.0"
} }
} }

View File

@@ -3,7 +3,8 @@ import minimist from 'minimist'
import { init } from './config' import { init } from './config'
import handlers, { error, help } from './handlers' import handlers, { error, help } from './handlers'
import { Config } from './types'
process.on('uncaughtException', err => { process.on('uncaughtException', err => {
console.log(err.message) console.log(err.message)
@@ -18,17 +19,19 @@ export const { _: commands, ...flags } = minimist(process.argv.slice(2), {
a: 'all', a: 'all',
l: 'location', l: 'location',
b: 'backend', b: 'backend',
d: 'dry-run',
}, },
boolean: ['a'], boolean: ['a', 'd'],
string: ['l', 'b'], string: ['l', 'b'],
}) })
export const VERSION = '0.6' export const VERSION = '0.11'
export const INSTALL_DIR = '/usr/local/bin' export const INSTALL_DIR = '/usr/local/bin'
export const VERBOSE = flags.verbose export const VERBOSE = flags.verbose
export const config = init() export const config = init()
function main() { function main() {
if (commands.length < 1) return help() if (commands.length < 1) return help()
@@ -37,4 +40,5 @@ function main() {
;(handlers[command] || error)(args, flags) ;(handlers[command] || error)(args, flags)
} }
main() main()

View File

@@ -1,10 +1,12 @@
import { Writer } from 'clitastic' import { Writer } from 'clitastic'
import { config, VERBOSE } from './autorestic' import { config, VERBOSE } from './autorestic'
import { Backend, Backends } from './types' import { Backend, Backends, Locations } from './types'
import { exec, ConfigError } from './utils' import { exec, ConfigError } from './utils'
const ALREADY_EXISTS = /(?=.*exists)(?=.*already)(?=.*config).*/
const ALREADY_EXISTS = /(?=.*already)(?=.*config).*/
export const getPathFromBackend = (backend: Backend): string => { export const getPathFromBackend = (backend: Backend): string => {
switch (backend.type) { switch (backend.type) {
@@ -32,6 +34,13 @@ export const getEnvFromBackend = (backend: Backend) => {
} }
} }
export const getBackendsFromLocations = (locations: Locations): string[] => {
const backends = new Set<string>()
for (const to of Object.values(locations).map(location => location.to))
Array.isArray(to) ? to.forEach(t => backends.add(t)) : backends.add(to)
return Array.from(backends)
}
export const checkAndConfigureBackend = (name: string, backend: Backend) => { export const checkAndConfigureBackend = (name: string, backend: Backend) => {
const writer = new Writer(name.blue + ' : ' + 'Configuring... ⏳') const writer = new Writer(name.blue + ' : ' + 'Configuring... ⏳')
const env = getEnvFromBackend(backend) const env = getEnvFromBackend(backend)

View File

@@ -3,49 +3,66 @@ import { Writer } from 'clitastic'
import { config, VERBOSE } from './autorestic' import { config, VERBOSE } from './autorestic'
import { getEnvFromBackend } from './backend' import { getEnvFromBackend } from './backend'
import { Locations, Location } from './types' import { Locations, Location } from './types'
import { exec, ConfigError } from './utils' import {
import { CONFIG_FILE } from './config' exec,
import { resolve, dirname, isAbsolute } from 'path' ConfigError,
pathRelativeToConfigFile,
getFlagsFromLocation,
makeArrayIfIsNot,
execPlain,
MeasureDuration, fill,
} from './utils'
export const backupSingle = (name: string, from: string, to: string) => {
export const backupSingle = (name: string, to: string, location: Location) => {
if (!config) throw ConfigError if (!config) throw ConfigError
const delta = new MeasureDuration()
const writer = new Writer(name + to.blue + ' : ' + 'Backing up... ⏳') const writer = new Writer(name + to.blue + ' : ' + 'Backing up... ⏳')
const backend = config.backends[to] const backend = config.backends[to]
const path = pathRelativeToConfigFile(location.from)
// Check if is an absolute path, otherwise get the path relative to the config file const cmd = exec(
const pathRelativeToConfigFile = isAbsolute(from) 'restic',
? from ['backup', path, ...getFlagsFromLocation(location, 'backup')],
: resolve(dirname(CONFIG_FILE), from) { env: getEnvFromBackend(backend) },
)
const cmd = exec('restic', ['backup', pathRelativeToConfigFile], {
env: getEnvFromBackend(backend),
})
if (VERBOSE) console.log(cmd.out, cmd.err) if (VERBOSE) console.log(cmd.out, cmd.err)
writer.done(name + to.blue + ' : ' + 'Done ✓'.green) writer.done(`${name}${to.blue} : ${'Done ✓'.green} (${delta.finished(true)})`)
} }
export const backupLocation = (name: string, backup: Location) => { export const backupLocation = (name: string, location: Location) => {
const display = name.yellow + ' ▶ ' const display = name.yellow + ' ▶ '
if (Array.isArray(backup.to)) { const filler = fill(name.length + 3)
let first = true let first = true
for (const t of backup.to) {
const nameOrBlankSpaces: string = first if (location.hooks && location.hooks.before)
? display for (const command of makeArrayIfIsNot(location.hooks.before)) {
: new Array(name.length + 3).fill(' ').join('') const cmd = execPlain(command)
backupSingle(nameOrBlankSpaces, backup.from, t) if (cmd) console.log(cmd.out, cmd.err)
}
for (const t of makeArrayIfIsNot(location.to)) {
backupSingle(first ? display : filler, t, location)
if (first) first = false if (first) first = false
} }
} else backupSingle(display, backup.from, backup.to)
if (location.hooks && location.hooks.after)
for (const command of makeArrayIfIsNot(location.hooks.after)) {
const cmd = execPlain(command)
if (cmd) console.log(cmd.out, cmd.err)
}
} }
export const backupAll = (backups?: Locations) => { export const backupAll = (locations?: Locations) => {
if (!backups) { if (!locations) {
if (!config) throw ConfigError if (!config) throw ConfigError
backups = config.locations locations = config.locations
} }
console.log('\nBacking Up'.underline.grey) console.log('\nBacking Up'.underline.grey)
for (const [name, backup] of Object.entries(backups)) for (const [name, location] of Object.entries(locations))
backupLocation(name, backup) backupLocation(name, location)
} }

View File

@@ -3,18 +3,20 @@ import { resolve } from 'path'
import yaml from 'js-yaml' import yaml from 'js-yaml'
import { flags } from './autorestic' import { flags } from './autorestic'
import { Backend, Config } from './types' import { Backend, Config } from './types'
import { makeObjectKeysLowercase, rand } from './utils' import { makeArrayIfIsNot, makeObjectKeysLowercase, rand } from './utils'
import { homedir } from 'os' import { homedir } from 'os'
export const normalizeAndCheckBackends = (config: Config) => { export const normalizeAndCheckBackends = (config: Config) => {
config.backends = makeObjectKeysLowercase(config.backends) config.backends = makeObjectKeysLowercase(config.backends)
for (const [name, { type, path, key, ...rest }] of Object.entries( for (const [name, { type, path, key, ...rest }] of Object.entries(
config.backends config.backends,
)) { )) {
if (!type || !path) if (!type || !path)
throw new Error( throw new Error(
`The backend "${name}" is missing some required attributes` `The backend "${name}" is missing some required attributes`,
) )
const tmp: any = { const tmp: any = {
@@ -39,15 +41,15 @@ export const normalizeAndCheckBackups = (config: Config) => {
} }
for (const [name, { from, to, ...rest }] of Object.entries( for (const [name, { from, to, ...rest }] of Object.entries(
config.locations config.locations,
)) { )) {
if (!from || !to) if (!from || !to)
throw new Error( throw new Error(
`The backup "${name}" is missing some required attributes` `The backup "${name}" is missing some required attributes`,
) )
if (Array.isArray(to)) for (const t of to) checkDestination(t, name) for (const t of makeArrayIfIsNot(to))
else checkDestination(to, name) checkDestination(t, name)
} }
} }
@@ -62,7 +64,8 @@ const findConfigFile = (): string | undefined => {
try { try {
const file = statSync(path) const file = statSync(path)
if (file.isFile()) return path if (file.isFile()) return path
} catch (e) {} } catch (e) {
}
} }
} }
@@ -74,7 +77,7 @@ export const init = (): Config | undefined => {
else return else return
const raw: Config = makeObjectKeysLowercase( const raw: Config = makeObjectKeysLowercase(
yaml.safeLoad(readFileSync(CONFIG_FILE).toString()) yaml.safeLoad(readFileSync(CONFIG_FILE).toString()),
) )
normalizeAndCheckBackends(raw) normalizeAndCheckBackends(raw)

67
src/forget.ts Normal file
View File

@@ -0,0 +1,67 @@
import { Writer } from 'clitastic'
import { config, VERBOSE } from './autorestic'
import { getEnvFromBackend } from './backend'
import { Locations, Location, Flags } from './types'
import {
exec,
ConfigError,
pathRelativeToConfigFile,
getFlagsFromLocation,
makeArrayIfIsNot,
fill,
} from './utils'
export const forgetSingle = (name: string, to: string, location: Location, dryRun: boolean) => {
if (!config) throw ConfigError
const base = name + to.blue + ' : '
const writer = new Writer(base + 'Removing old snapshots… ⏳')
const backend = config.backends[to]
const path = pathRelativeToConfigFile(location.from)
const flags = getFlagsFromLocation(location, 'forget')
if (flags.length == 0) {
writer.done(base + 'skipping, no policy declared')
return
}
if (dryRun) flags.push('--dry-run')
writer.replaceLn(base + 'Forgetting old snapshots… ⏳')
const cmd = exec(
'restic',
['forget', '--path', path, '--prune', ...flags],
{ env: getEnvFromBackend(backend) },
)
if (VERBOSE) console.log(cmd.out, cmd.err)
writer.done(base + 'Done ✓'.green)
}
export const forgetLocation = (name: string, backup: Location, dryRun: boolean) => {
const display = name.yellow + ' ▶ '
const filler = fill(name.length + 3)
let first = true
for (const t of makeArrayIfIsNot(backup.to)) {
const nameOrBlankSpaces: string = first ? display : filler
forgetSingle(nameOrBlankSpaces, t, backup, dryRun)
if (first) first = false
}
}
export const forgetAll = (backups?: Locations, flags?: Flags) => {
if (!config) throw ConfigError
if (!backups) {
backups = config.locations
}
console.log('\nRemoving old snapshots according to policy'.underline.grey)
const dryRun = flags ? flags['dry-run'] : false
if (dryRun) console.log('Running in dry-run mode, not touching data\n'.yellow)
for (const [name, backup] of Object.entries(backups))
forgetLocation(name, backup, dryRun)
}

View File

@@ -5,8 +5,10 @@ import { tmpdir } from 'os'
import { join, resolve } from 'path' import { join, resolve } from 'path'
import { config, INSTALL_DIR, VERSION } from './autorestic' import { config, INSTALL_DIR, VERSION } from './autorestic'
import { checkAndConfigureBackends, getEnvFromBackend } from './backend' import { checkAndConfigureBackends, getBackendsFromLocations, getEnvFromBackend } from './backend'
import { backupAll } from './backup' import { backupAll } from './backup'
import { forgetAll } from './forget'
import showAll from './info'
import { Backends, Flags, Locations } from './types' import { Backends, Flags, Locations } from './types'
import { import {
checkIfCommandIsAvailable, checkIfCommandIsAvailable,
@@ -14,10 +16,11 @@ import {
downloadFile, downloadFile,
exec, exec,
filterObjectByKey, filterObjectByKey,
singleToArray, ConfigError, makeArrayIfIsNot,
ConfigError,
} from './utils' } from './utils'
export type Handlers = { export type Handlers = {
[command: string]: (args: string[], flags: Flags) => void [command: string]: (args: string[], flags: Flags) => void
} }
@@ -28,11 +31,11 @@ const parseBackend = (flags: Flags): Backends => {
throw new Error( throw new Error(
'No backends specified.'.red + 'No backends specified.'.red +
'\n--all [-a]\t\t\t\tCheck all.' + '\n--all [-a]\t\t\t\tCheck all.' +
'\n--backend [-b] myBackend\t\tSpecify one or more backend' '\n--backend [-b] myBackend\t\tSpecify one or more backend',
) )
if (flags.all) return config.backends if (flags.all) return config.backends
else { else {
const backends = singleToArray<string>(flags.backend) const backends = makeArrayIfIsNot<string>(flags.backend)
for (const backend of backends) for (const backend of backends)
if (!config.backends[backend]) if (!config.backends[backend])
throw new Error('Invalid backend: '.red + backend) throw new Error('Invalid backend: '.red + backend)
@@ -46,13 +49,13 @@ const parseLocations = (flags: Flags): Locations => {
throw new Error( throw new Error(
'No locations specified.'.red + 'No locations specified.'.red +
'\n--all [-a]\t\t\t\tBackup all.' + '\n--all [-a]\t\t\t\tBackup all.' +
'\n--location [-l] site1\t\t\tSpecify one or more locations' '\n--location [-l] site1\t\t\tSpecify one or more locations',
) )
if (flags.all) { if (flags.all) {
return config.locations return config.locations
} else { } else {
const locations = singleToArray<string>(flags.location) const locations = makeArrayIfIsNot<string>(flags.location)
for (const location of locations) for (const location of locations)
if (!config.locations[location]) if (!config.locations[location])
throw new Error('Invalid location: '.red + location) throw new Error('Invalid location: '.red + location)
@@ -71,12 +74,8 @@ const handlers: Handlers = {
checkIfResticIsAvailable() checkIfResticIsAvailable()
const locations: Locations = parseLocations(flags) const locations: Locations = parseLocations(flags)
const backends = new Set<string>()
for (const to of Object.values(locations).map(location => location.to))
Array.isArray(to) ? to.forEach(t => backends.add(t)) : backends.add(to)
checkAndConfigureBackends( checkAndConfigureBackends(
filterObjectByKey(config.backends, Array.from(backends)) filterObjectByKey(config.backends, getBackendsFromLocations(locations)),
) )
backupAll(locations) backupAll(locations)
@@ -85,23 +84,50 @@ const handlers: Handlers = {
restore(args, flags) { restore(args, flags) {
if (!config) throw ConfigError if (!config) throw ConfigError
checkIfResticIsAvailable() checkIfResticIsAvailable()
if (!flags.to) {
console.log(`You need to specify the restore path with --to`.red)
return
}
const locations = parseLocations(flags) const locations = parseLocations(flags)
for (const [name, location] of Object.entries(locations)) { for (const [name, location] of Object.entries(locations)) {
const w = new Writer(name.green + `\t\tRestoring... ⏳`) const baseText = name.green + '\t\t'
const env = getEnvFromBackend( const w = new Writer(baseText + `Starting...`)
config.backends[
Array.isArray(location.to) ? location.to[0] : location.to let backend: string = Array.isArray(location.to) ? location.to[0] : location.to
] if (flags.from) {
) if (!location.to.includes(flags.from)) {
w.done(baseText + `Backend ${flags.from} is not a valid location for ${name}`.red)
continue
}
backend = flags.from
w.replaceLn(baseText + `Restoring from ${backend.blue}...`)
} else if (Array.isArray(location.to) && location.to.length > 1) {
w.replaceLn(baseText + `Restoring from ${backend.blue}...\tTo select a specific backend pass the ${'--from'.blue} flag`)
}
const env = getEnvFromBackend(config.backends[backend])
exec( exec(
'restic', 'restic',
['restore', 'latest', '--path', resolve(location.from), ...args], ['restore', 'latest', '--path', resolve(location.from), '--target', flags.to],
{ env } { env },
) )
w.done(name.green + '\t\tDone 🎉') w.done(name.green + '\t\tDone 🎉')
} }
}, },
forget(args, flags) {
if (!config) throw ConfigError
checkIfResticIsAvailable()
const locations: Locations = parseLocations(flags)
checkAndConfigureBackends(
filterObjectByKey(config.backends, getBackendsFromLocations(locations)),
)
forgetAll(locations, flags)
console.log('\nFinished!'.underline + ' 🎉')
},
exec(args, flags) { exec(args, flags) {
checkIfResticIsAvailable() checkIfResticIsAvailable()
const backends = parseBackend(flags) const backends = parseBackend(flags)
@@ -113,12 +139,16 @@ const handlers: Handlers = {
console.log(out, err) console.log(out, err)
} }
}, },
async info() {
showAll()
},
async install() { async install() {
try { try {
checkIfResticIsAvailable() checkIfResticIsAvailable()
console.log('Restic is already installed') console.log('Restic is already installed')
return return
} catch (e) {} } catch (e) {
}
const w = new Writer('Checking latest version... ⏳') const w = new Writer('Checking latest version... ⏳')
checkIfCommandIsAvailable('bzip2') checkIfCommandIsAvailable('bzip2')
@@ -141,7 +171,7 @@ const handlers: Handlers = {
if (!dl) if (!dl)
return console.log( return console.log(
'Cannot get the right binary.'.red, 'Cannot get the right binary.'.red,
'Please see https://bit.ly/2Y1Rzai' 'Please see https://bit.ly/2Y1Rzai',
) )
const tmp = join(tmpdir(), name) const tmp = join(tmpdir(), name)
@@ -149,8 +179,6 @@ const handlers: Handlers = {
await downloadFile(dl.browser_download_url, tmp) await downloadFile(dl.browser_download_url, tmp)
// TODO: Native bz2
// Decompress
w.replaceLn('Decompressing binary... 📦') w.replaceLn('Decompressing binary... 📦')
exec('bzip2', ['-dk', tmp]) exec('bzip2', ['-dk', tmp])
unlinkSync(tmp) unlinkSync(tmp)
@@ -160,7 +188,7 @@ const handlers: Handlers = {
exec('mv', [extracted, INSTALL_DIR + '/restic']) exec('mv', [extracted, INSTALL_DIR + '/restic'])
w.done( w.done(
`\nFinished! restic is installed under: ${INSTALL_DIR}`.underline + ' 🎉' `\nFinished! restic is installed under: ${INSTALL_DIR}`.underline + ' 🎉',
) )
}, },
uninstall() { uninstall() {
@@ -190,8 +218,7 @@ const handlers: Handlers = {
darwin: 'macos', darwin: 'macos',
} }
const name = `autorestic_${platformMap[process.platform] || const name = `autorestic_${platformMap[process.platform] || process.platform}_${process.arch}`
process.platform}_${process.arch}`
const dl = json.assets.find((asset: any) => asset.name === name) const dl = json.assets.find((asset: any) => asset.name === name)
const to = INSTALL_DIR + '/autorestic' const to = INSTALL_DIR + '/autorestic'
@@ -217,9 +244,11 @@ export const help = () => {
`\n -c, --config Specify config file. Default: .autorestic.yml` + `\n -c, --config Specify config file. Default: .autorestic.yml` +
'\n' + '\n' +
'\nCommands:'.yellow + '\nCommands:'.yellow +
'\n info Show all locations and backends' +
'\n check [-b, --backend] [-a, --all] Check backends' + '\n check [-b, --backend] [-a, --all] Check backends' +
'\n backup [-l, --location] [-a, --all] Backup all or specified locations' + '\n backup [-l, --location] [-a, --all] Backup all or specified locations' +
'\n restore [-l, --location] [-- --target <out dir>] Restore all or specified locations' + '\n forget [-l, --location] [-a, --all] [--dry-run] Forget old snapshots according to declared policies' +
'\n restore [-l, --location] [--from backend] [--to <out dir>] Restore all or specified locations' +
'\n' + '\n' +
'\n exec [-b, --backend] [-a, --all] <command> -- [native options] Execute native restic command' + '\n exec [-b, --backend] [-a, --all] <command> -- [native options] Execute native restic command' +
'\n' + '\n' +
@@ -230,14 +259,15 @@ export const help = () => {
'\n' + '\n' +
'\nExamples: '.yellow + '\nExamples: '.yellow +
'https://git.io/fjVbg' + 'https://git.io/fjVbg' +
'\n' '\n',
) )
} }
export const error = () => { export const error = () => {
help() help()
console.log( console.log(
`Invalid Command:`.red.underline, `Invalid Command:`.red.underline,
`${process.argv.slice(2).join(' ')}` `${process.argv.slice(2).join(' ')}`,
) )
} }

28
src/info.ts Normal file
View File

@@ -0,0 +1,28 @@
import { config } from './autorestic'
import { ConfigError, fill, treeToString } from './utils'
const showAll = () => {
if (!config) throw ConfigError
console.log('\n\n' + fill(32, '_') + 'LOCATIONS:'.underline)
for (const [key, data] of Object.entries(config.locations)) {
console.log(`\n${key.blue.underline}:`)
console.log(treeToString(
data,
['to:', 'from:', 'hooks:', 'options:'],
))
}
console.log('\n\n' + fill(32, '_') + 'BACKENDS:'.underline)
for (const [key, data] of Object.entries(config.backends)) {
console.log(`\n${key.blue.underline}:`)
console.log(treeToString(
data,
['type:', 'path:', 'key:'],
))
}
}
export default showAll

View File

@@ -1,3 +1,7 @@
export type StringOrArray = string | string[]
// BACKENDS
type BackendLocal = { type BackendLocal = {
type: 'local' type: 'local'
key: string key: string
@@ -62,13 +66,26 @@ export type Backend =
export type Backends = { [name: string]: Backend } export type Backends = { [name: string]: Backend }
// LOCATIONS
export type Location = { export type Location = {
from: string from: string
to: string | string[] to: StringOrArray
hooks?: {
before?: StringOrArray
after?: StringOrArray
}
options?: {
[key: string]: {
[key: string]: StringOrArray
}
}
} }
export type Locations = { [name: string]: Location } export type Locations = { [name: string]: Location }
// OTHER
export type Config = { export type Config = {
locations: Locations locations: Locations
backends: Backends backends: Backends

View File

@@ -1,12 +1,21 @@
import axios from 'axios'
import { spawnSync, SpawnSyncOptions } from 'child_process' import { spawnSync, SpawnSyncOptions } from 'child_process'
import { randomBytes } from 'crypto' import { randomBytes } from 'crypto'
import { createWriteStream } from 'fs' import { createWriteStream } from 'fs'
import { dirname, isAbsolute, join, resolve } from 'path'
import { homedir } from 'os'
import axios from 'axios'
import { Duration, Humanizer } from 'uhrwerk'
import { CONFIG_FILE } from './config'
import { Location } from './types'
export const exec = ( export const exec = (
command: string, command: string,
args: string[], args: string[],
{ env, ...rest }: SpawnSyncOptions = {} { env, ...rest }: SpawnSyncOptions = {},
) => { ) => {
const cmd = spawnSync(command, args, { const cmd = spawnSync(command, args, {
...rest, ...rest,
@@ -22,11 +31,21 @@ export const exec = (
return { out, err } return { out, err }
} }
export const execPlain = (command: string, opt: SpawnSyncOptions = {}) => {
const split = command.split(' ')
if (split.length < 1) {
console.log(`The command ${command} is not valid`.red)
return
}
return exec(split[0], split.slice(1), opt)
}
export const checkIfResticIsAvailable = () => export const checkIfResticIsAvailable = () =>
checkIfCommandIsAvailable( checkIfCommandIsAvailable(
'restic', 'restic',
'Restic is not installed'.red + 'Restic is not installed'.red +
' https://restic.readthedocs.io/en/latest/020_installation.html#stable-releases' ' https://restic.readthedocs.io/en/latest/020_installation.html#stable-releases',
) )
export const checkIfCommandIsAvailable = (cmd: string, errorMsg?: string) => { export const checkIfCommandIsAvailable = (cmd: string, errorMsg?: string) => {
@@ -36,25 +55,24 @@ export const checkIfCommandIsAvailable = (cmd: string, errorMsg?: string) => {
export const makeObjectKeysLowercase = (object: Object): any => export const makeObjectKeysLowercase = (object: Object): any =>
Object.fromEntries( Object.fromEntries(
Object.entries(object).map(([key, value]) => [key.toLowerCase(), value]) Object.entries(object).map(([key, value]) => [key.toLowerCase(), value]),
) )
export function rand(length = 32): string { export function rand(length = 32): string {
return randomBytes(length / 2).toString('hex') return randomBytes(length / 2).toString('hex')
} }
export const singleToArray = <T>(singleOrArray: T | T[]): T[] =>
Array.isArray(singleOrArray) ? singleOrArray : [singleOrArray]
export const filterObject = <T>( export const filterObject = <T>(
obj: { [key: string]: T }, obj: { [key: string]: T },
filter: (item: [string, T]) => boolean filter: (item: [string, T]) => boolean,
): { [key: string]: T } => ): { [key: string]: T } =>
Object.fromEntries(Object.entries(obj).filter(filter)) Object.fromEntries(Object.entries(obj).filter(filter))
export const filterObjectByKey = <T>( export const filterObjectByKey = <T>(
obj: { [key: string]: T }, obj: { [key: string]: T },
keys: string[] keys: string[],
) => filterObject(obj, ([key]) => keys.includes(key)) ) => filterObject(obj, ([key]) => keys.includes(key))
export const downloadFile = async (url: string, to: string) => export const downloadFile = async (url: string, to: string) =>
@@ -74,4 +92,77 @@ export const downloadFile = async (url: string, to: string) =>
}) })
}) })
// Check if is an absolute path, otherwise get the path relative to the config file
export const pathRelativeToConfigFile = (path: string): string => isAbsolute(path)
? path
: resolve(dirname(CONFIG_FILE), path)
export const resolveTildePath = (path: string): string | null =>
(path.length === 0 || path[0] !== '~')
? null
: join(homedir(), path.slice(1))
export const ConfigError = new Error('Config file not found') export const ConfigError = new Error('Config file not found')
export const getFlagsFromLocation = (location: Location, command?: string): string[] => {
if (!location.options) return []
const all = {
...location.options.global,
...(location.options[command || ''] || {}),
}
let flags: string[] = []
// Map the flags to an array for the exec function.
for (let [flag, values] of Object.entries(all))
for (const value of makeArrayIfIsNot(values)) {
const stringValue = String(value)
const resolvedTilde = resolveTildePath(stringValue)
flags = [...flags, `--${String(flag)}`, resolvedTilde === null ? stringValue : resolvedTilde]
}
return flags
}
export const makeArrayIfIsNot = <T>(maybeArray: T | T[]): T[] => Array.isArray(maybeArray) ? maybeArray : [maybeArray]
export const fill = (length: number, filler = ' '): string => new Array(length).fill(filler).join('')
export const capitalize = (string: string): string => string.charAt(0).toUpperCase() + string.slice(1)
export const treeToString = (obj: Object, highlight = [] as string[]): string => {
let cleaned = JSON.stringify(obj, null, 2)
.replace(/[{}"\[\],]/g, '')
.replace(/^ {2}/mg, '')
.replace(/\n\s*\n/g, '\n')
.trim()
for (const word of highlight)
cleaned = cleaned.replace(word, capitalize(word).green)
return cleaned
}
export class MeasureDuration {
private static Humanizer: Humanizer = [
[d => d.hours() > 0, d => `${d.hours()}h ${d.minutes()}min`],
[d => d.minutes() > 0, d => `${d.minutes()}min ${d.seconds()}s`],
[d => d.seconds() > 0, d => `${d.seconds()}s`],
[() => true, d => `${d.milliseconds()}ms`],
]
private start = Date.now()
finished(human?: false): number
finished(human?: true): string
finished(human?: boolean): number | string {
const delta = Date.now() - this.start
return human
? new Duration(delta, 'ms').humanize(MeasureDuration.Humanizer)
: delta
}
}