-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbackup.js
182 lines (163 loc) · 5.75 KB
/
backup.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
const fs = require('fs');
const path = require('path');
const tar = require('tar');
const { google } = require('googleapis');
const moment = require('moment-timezone');
const { WebClient } = require('@slack/web-api');
const SOURCE_DIR = process.env.SOURCE_DIR;
const BACKUP_DIR_NAME = process.env.BACKUP_DIR_NAME;
const TIMEZONE = process.env.TIMEZONE;
const MAX_BACKUPS = process.env.MAX_BACKUPS || 7;
const slackToken = process.env.SLACK_TOKEN;
const slackChannel = process.env.SLACK_CHANNEL;
const slackClient = new WebClient(slackToken);
if (!SOURCE_DIR || !BACKUP_DIR_NAME || !TIMEZONE) {
throw new Error('SOURCE_DIR, BACKUP_DIR_NAME, e TIMEZONE precisam estar definidos nas variáveis de ambiente.');
}
const log = (message) => {
console.log(`[${new Date().toISOString()}] ${message}`);
};
/**
* Envia uma notificação ao Slack.
*
* @param {string} message
*/
async function notifySlack(message) {
if (slackToken && slackChannel) {
await slackClient.chat.postMessage({
channel: slackChannel,
text: message
});
}
}
/**
* Limpa backups antigos, mantendo apenas os últimos MAX_BACKUPS.
*
* @param {string} backupDir
*/
async function cleanOldBackups(backupDir) {
const files = fs.readdirSync(backupDir)
.map(file => ({ name: file, time: fs.statSync(path.join(backupDir, file)).mtime.getTime() }))
.sort((a, b) => b.time - a.time)
.map(file => file.name);
while (files.length > MAX_BACKUPS) {
const fileToDelete = files.pop();
fs.unlinkSync(path.join(backupDir, fileToDelete));
log(`Excluindo backup antigo: ${fileToDelete}`);
}
}
/**
* Cria um backup do diretório SOURCE_DIR em formato tar.gz e salva em um diretório de backup.
*
* @returns {Promise<{ outputPath: string, date: string, time: string }>}
*/
async function createBackup() {
const now = moment().tz(TIMEZONE);
const date = now.format('YYYY-MM-DD');
const time = now.format('HH-mm-ss');
const parentDir = path.dirname(SOURCE_DIR); // Diretório pai de SOURCE_DIR
const backupDir = path.join(parentDir, BACKUP_DIR_NAME, date);
const outputPath = path.join(backupDir, `backup-${time}.tar.gz`);
if (!fs.existsSync(backupDir)) {
fs.mkdirSync(backupDir, { recursive: true });
}
log(`Iniciando backup de ${SOURCE_DIR} para ${outputPath}`);
await cleanOldBackups(path.join(parentDir, BACKUP_DIR_NAME));
return new Promise((resolve, reject) => {
tar.c(
{
gzip: true,
file: outputPath,
cwd: parentDir
},
[path.basename(SOURCE_DIR)]
).then(() => {
resolve({ outputPath, date, time });
}).catch((err) => {
log(`Erro ao criar o arquivo tar.gz: ${err.message}`);
reject(err);
});
});
}
/**
* Faz o upload do arquivo de backup para o Google Drive.
*
* @param {object} auth
* @param {string} filePath
* @param {string} date
* @param {number} retryCount
* @returns {Promise<object>}
*/
async function uploadBackup(auth, filePath, date, retryCount = 3) {
try {
const drive = google.drive({ version: 'v3', auth });
const backupCloudFolderId = await getOrCreateFolder(drive, BACKUP_DIR_NAME);
const dateFolderId = await getOrCreateFolder(drive, date, backupCloudFolderId);
const fileMetadata = {
name: path.basename(filePath),
parents: [dateFolderId]
};
const media = {
mimeType: 'application/gzip',
body: fs.createReadStream(filePath)
};
const response = await drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
});
// Excluir o arquivo local após o upload
fs.unlinkSync(filePath);
return response;
} catch (error) {
if (retryCount > 0) {
log(`Erro no upload, tentativas restantes: ${retryCount}, erro: ${error.message}`);
return uploadBackup(auth, filePath, date, retryCount - 1);
} else {
throw new Error(`Falha no upload após múltiplas tentativas: ${error.message}`);
}
}
}
/**
* Obtém ou cria uma pasta no Google Drive.
*
* @param {object} drive
* @param {string} folderName
* @param {string} parentFolderId
* @returns {Promise<string>}
*/
async function getOrCreateFolder(drive, folderName, parentFolderId = null) {
const query = `name='${folderName}' and mimeType='application/vnd.google-apps.folder'${parentFolderId ? ` and '${parentFolderId}' in parents` : ''}`;
const response = await drive.files.list({
q: query,
fields: 'files(id, name)'
});
const folder = response.data.files.find(file => file.name === folderName);
if (folder) {
return folder.id;
} else {
const fileMetadata = {
name: folderName,
mimeType: 'application/vnd.google-apps.folder',
parents: parentFolderId ? [parentFolderId] : []
};
const folder = await drive.files.create({
resource: fileMetadata,
fields: 'id'
});
return folder.data.id;
}
}
(async () => {
try {
const auth = await authenticate(); // Assumindo que você tem uma função de autenticação
const { outputPath, date, time } = await createBackup();
await uploadBackup(auth, outputPath, date);
log('Backup e upload concluídos com sucesso.');
await notifySlack(`Backup criado e carregado com sucesso: ${outputPath}`);
} catch (error) {
log(`Erro durante o processo de backup: ${error.message}`);
await notifySlack(`Erro durante o processo de backup: ${error.message}`);
}
})();
module.exports = { createBackup, uploadBackup };