-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup.js
More file actions
193 lines (165 loc) · 5.27 KB
/
backup.js
File metadata and controls
193 lines (165 loc) · 5.27 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
import _ from 'lodash';
import path from 'path';
import { format } from 'date-fns';
import util from 'util';
import { exec as execRaw } from 'child_process';
import addMilliseconds from 'date-fns/addMilliseconds';
import formatDistance from 'date-fns/formatDistance';
import fetch from 'node-fetch';
import base64 from 'base-64';
import logger from './logger';
import {
DB_HOST,
DB_PORT,
DB_NAME,
DUMP_DIRECTORY,
DUMP_DATE_FORMAT,
BACKUP_DELAY_MIN,
SYNC_HOST,
SYNC_LOGIN,
SYNC_PASSWORD,
SYNC_CMD,
SYNC_SRC,
SYNC_DST,
SYNC_PORT,
SYNC_ENABLED
} from './config';
import db from './db';
const exec = util.promisify( execRaw );
const setTimeoutPromise = util.promisify( setTimeout );
const MS_PER_SECOND = 1000;
const SECONDS_PER_MINUTE = 60;
const BACKUP_DELAY_MS = BACKUP_DELAY_MIN * SECONDS_PER_MINUTE * MS_PER_SECOND;
const checkHTTPStatus = res => {
const { statusText, status, ok } = res;
if ( !ok ) {
throw new Error( `${statusText} (${status})` );
}
return res;
};
// rclone
const SYNC_DEFAULT_OPTS = {
_async: true
};
/**
* syncService
* Wrapper for the rClone remote control. See {@link https://rclone.org/rc/}
*
* @param {string} cmd the remote control command to run
* @param {object} opts options to configure the command
* @returns if _async = true, an object with rClone "jobid" else nothing
*/
const syncService = ( cmd, opts ) => {
const payload = _.defaults( opts, SYNC_DEFAULT_OPTS );
const body = JSON.stringify( payload );
let url = `http://${SYNC_HOST}:${SYNC_PORT}/${cmd}`;
return fetch( url, {
method: 'POST',
body,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Basic ${base64.encode(SYNC_LOGIN + ":" + SYNC_PASSWORD)}`
}
})
.then( checkHTTPStatus )
.then( res => res.json() )
.then( json => {
logger.info( `Sync request sent` );
logger.info( JSON.stringify( json, null, 2 ) );
})
.catch( err => {
logger.error( `sync: ${err}` );
throw err;
});
};
// RethinkDB
let loadTable = name => db.accessTable( name );
/**
* dump
* Dump the RethinkDB database
* The result is a zipped archive named `${DB_NAME}_dump_${DATETIME}.tar.gz` in DUMP_DIRECTORY
*/
const dump = async () => {
const DATETIME = format(new Date(), DUMP_DATE_FORMAT);
const FILENAME = `${DB_NAME}_dump_${DATETIME}.tar.gz`;
const DUMP_FOLDER = path.join( __dirname, DUMP_DIRECTORY );
const CMD = `cd ${DUMP_FOLDER} && rethinkdb dump --connect ${DB_HOST}:${DB_PORT} --export ${DB_NAME} --file ${FILENAME}`;
try {
const { stdout } = await exec( CMD );
logger.info( stdout );
return Promise.resolve();
} catch ( err ) {
logger.error( `dump error: ${err}` );
throw err;
}
};
let dumpScheduled = false;
let dumpTime = null;
let resetDump = () => { dumpScheduled = false; dumpTime = null; };
/**
* scheduleDump
* Schedule a dump in 'delay' ms. Ignore additional requests while scheduled.
*
* @param {number} delay ms delay for dumping (default 0)
* @param {object} next The callback to run after a dump
*/
const scheduleDump = async ( delay = 0, next = () => {} ) => {
let now = new Date();
logger.info( `A dump request has been received` );
if( dumpScheduled ){
logger.info( `A dump has already been scheduled for ${dumpTime} (${formatDistance( now, dumpTime )})` );
} else {
dumpTime = addMilliseconds( new Date(), delay );
logger.info( `A dump was scheduled for ${dumpTime} (${formatDistance( now, dumpTime )})` );
dumpScheduled = true;
setTimeoutPromise( delay )
.then( dump )
.then( next )
.catch( () => {} ) // swallow
.finally( resetDump ); // allow another backup request
}
return Promise.resolve();
};
const dumpNext = SYNC_ENABLED ?
() => syncService( SYNC_CMD, { srcFs: SYNC_SRC, dstFs: SYNC_DST } ) :
() => { logger.info(`SYNC_ENABLED: ${SYNC_ENABLED}`); };
/**
* backup
* Wrapper for the scheduleDump, using syncService as callaback
*
* @param {number} delay set a ms delay
*/
const backup = delay => scheduleDump( delay, dumpNext );
// Configure Changefeeds for the document table
const docChangefeeds = async delay => {
const docOpts = { includeTypes: true };
const { rethink: r, conn, table } = await loadTable( 'document' );
// Document not 'demo'
const notDemo = r.row( 'new_val' )( 'id' ).ne( 'demo' ).and( r.row( 'new_val' )( 'secret' ).ne( 'demo' ) );
// Document 'add'
const addedItem = r.row( 'type' ).eq( 'add' );
// Status changed to 'public' from other
const toPublicStatus = r.row( 'new_val' )( 'status' ).eq( 'public' ).and( r.row( 'old_val' )( 'status' ).ne( 'public' ) );
// Status is 'public' and updated
const publicUpdated = r.row( 'new_val' )( 'status' ).eq( 'public' )
.and( r.row( 'old_val' )( 'status' ).eq( 'public' ) );
const docFilter = notDemo.and( addedItem.or( toPublicStatus ).or( publicUpdated ) );
const cursor = await table.changes( docOpts ).filter( docFilter ).run( conn );
cursor.each( () => backup( delay ) );
// cursor.each( (err, item) => {
// const type = _.get( item, 'type' );
// console.log( type );
// });
};
/**
* setupChangefeeds
* Set up listeners for the specified Changefeeds
*/
const setupChangefeeds = async () => {
await docChangefeeds( BACKUP_DELAY_MS );
};
export {
setupChangefeeds,
backup
};