-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
175 lines (154 loc) · 5.04 KB
/
index.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
const { default: axios } = require(`axios`);
const { CronJob } = require(`cron`);
const { v4 } = require(`uuid`);
const cfg = require(`./config.json`);
/**
* @typedef {object} Snapshot
* @property {string} tenantId
* @property {string} customerId
* @property {string} snapshotId
* @property {string} name
* @property {string} description
* @property {string} instanceId
* @property {string} createdDate
* @property {string} autoDeleteDate
* @property {string} imageId
* @property {string} imageName
*/
const auth = {
access: null,
refresh: null,
expires: null,
refetch: null
};
(async function() {
await obtainToken();
new CronJob(`0 0 * * *`, async () => {
if(Date.now() >= auth.refetch) await obtainToken();
else if(Date.now() >= auth.expires) await refreshToken();
const snapshots = await listSnapshots();
if(snapshots && snapshots.length >= cfg.maxSnapshots) {
const snapshotToDelete = snapshots.sort((a, b) => new Date(a.createdDate) - new Date(b.createdDate))[0];
const deleted = await deleteSnapshot(snapshotToDelete?.snapshotId);
if(deleted) console.log(`Deleted snapshot ${snapshotToDelete?.snapshotId}`);
} else console.log(`There are no snapshots to delete!`);
const created = await createSnapshot();
if(created) console.log(`Created snapshot ${created?.snapshotId}`);
}, null, true, `Europe/Berlin`);
console.log(`CronJob was loaded!`);
})();
/**
*
* @returns {Promise<void>}
*/
async function obtainToken() {
try {
const res = await axios.post(`https://auth.contabo.com/auth/realms/contabo/protocol/openid-connect/token`, {
client_id: cfg.clientId,
client_secret: cfg.clientSecret,
username: cfg.username,
password: cfg.password,
grant_type: `password`
}, {
headers: {
'Content-Type': `application/x-www-form-urlencoded`
}
});
auth.access = res.data.access_token;
auth.refresh = res.data.refresh_token;
auth.expires = Date.now() + (res.data.expires_in * 1000);
auth.refetch = Date.now() + (res.data.refresh_expires_in * 1000);
console.log(`New token obtained!`);
} catch(err) {
console.log(`Failed to obtain token: ${JSON.stringify(err.response?.data)}`);
return null;
}
}
/**
*
* @returns {Promise<void>}
*/
async function refreshToken() {
try {
const res = await axios.post(`https://auth.contabo.com/auth/realms/contabo/protocol/openid-connect/token`, {
client_id: cfg.clientId,
client_secret: cfg.clientSecret,
grant_type: `refresh_token`,
refresh_token: auth.refresh
}, {
headers: {
'Content-Type': `application/x-www-form-urlencoded`
}
});
auth.access = res.data.access_token;
auth.refresh = res.data.refresh_token;
auth.expires = Date.now() + (res.data.expires_in * 1000);
auth.refetch = Date.now() + (res.data.refresh_expires_in * 1000);
console.log(`Token refreshed!`);
} catch(err) {
console.log(`Failed to refresh token: ${JSON.stringify(err.response?.data)}`);
return null;
}
}
/**
*
* @returns {Promise<Snapshot|null>}
*/
async function createSnapshot() {
try {
const res = await axios.post(`https://api.contabo.com/v1/compute/instances/${cfg.instance}/snapshots`, {
name: `Automatic backup - ${Date.now().toString(36)}`,
description: `Backup created on ${new Date().toLocaleDateString()}`
}, {
headers: {
"Authorization": `Bearer ${auth.access}`,
"X-Request-ID": v4()
},
});
return res.data.data?.[0];
} catch(err) {
console.log(`Failed to create snapshot: ${JSON.stringify(err.response?.data)}`);
return null;
}
}
/**
*
* @param {string} id
* @returns {Promise<string|null>}
*/
async function deleteSnapshot(id) {
if(!id) {
console.log(`Invalid snapshot id: ${id}`);
return null;
}
try {
await axios.delete(`https://api.contabo.com/v1/compute/instances/${cfg.instance}/snapshots/${id}`, {
headers: {
"Authorization": `Bearer ${auth.access}`,
"X-Request-ID": v4()
}
});
return id;
} catch(err) {
console.log(`Failed to delete snapshot: ${JSON.stringify(err.response?.data)}`);
return null;
}
}
/**
*
* @returns {Promise<Snapshot[]>}
*/
async function listSnapshots() {
try {
const res = await axios.get(`https://api.contabo.com/v1/compute/instances/${cfg.instance}/snapshots`, {
headers: {
"Authorization": `Bearer ${auth.access}`,
"X-Request-ID": v4()
}
});
return res.data.data;
} catch(err) {
console.log(`Failed to list snapshots: ${JSON.stringify(err.response?.data)}`);
return null;
}
}