/
m1client.js
executable file
·252 lines (233 loc) · 10.6 KB
/
m1client.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#!/usr/bin/env node
'use strict';
const program = require('commander');
const { mkdirp } = require('mkdirp');
const crypto = require('crypto');
const fs = require('fs-extra');
const lodash = require('lodash');
const dateTime = require('date-and-time');
const Base32 = require('base32.js');
const azure = require('azure-storage');
const glob = require('glob');
const path = require('path');
const azureOp = require('../src/azureOp');
const secrets = require('../src/secrets');
const config = require('../src/config');
const os = require('../src/os');
const logger = require('../src/logger');
const logContainer = 'm1-3200-logs';
const secretsContainer = 'm1-3200-secrets';
const firmwareContainer = 'firmware';
process.env.SNAP_DATA = '/var/snap/m1tfd1/current';
const publicKey = path.join(process.env.SNAP_DATA, 'public.key');
const debuglevel = '2';
program
.name('m1cli')
.description('CLI utility retrieve M1-3200 manufacturing logs')
.version('0.2.0');
program.command('update')
.description('download and update software and firmware i the test fixture')
.option('-f, --force', 'force update')
.action(async (options) => {
let logfile;
let dir;
let blobSvc;
try {
const str = '/root snap install/d';
os.executeShellCommand(`sudo sed -i '${str}' /etc/crontab`, logfile);
const configData = await config({});
dir = configData.m1mtfDir;
logfile = logger.getLogger('m1cli', 'update', 'm1cli', `${configData.m1mtfDir}/logs/m1cli`, debuglevel);
logfile.info('Checking for SW & FW update ...');
blobSvc = azure.createBlobService(configData.conString);
logfile.info('Downloading manifestFile');
mkdirp.sync(path.join(dir, 'tmp'));
await azureOp.downloadFile(blobSvc, firmwareContainer, 'manifestFile.json', path.join(dir, 'tmp', 'manifestFile.json'));
const newManifestFile = fs.readJSONSync(path.join(dir, 'tmp', 'manifestFile.json'));
let localManifestFile;
try {
if (options.force) throw Error('force');
localManifestFile = fs.readJSONSync(path.join(dir, 'tmp', 'manifestFileLocal.json'));
}
catch (err) {
localManifestFile = [];
}
if (lodash.isEqual(newManifestFile, localManifestFile)) {
logfile.info('No new firmware to update');
return;
}
logfile.info('New FW is available');
const isSnapUpdate = newManifestFile.find(element => element.filetype === 'snap');
if (isSnapUpdate) {
logfile.info('sending kill to apps');
await os.executeShellCommand('killall -9 gui', logfile, true);
}
const fileList = newManifestFile.map((item) => {
logfile.info(`Downloading ${item.filename}`);
return azureOp.downloadFile(blobSvc, firmwareContainer, item.filename, path.join(dir, 'tmp', item.filename));
});
await Promise.all(fileList);
logfile.info('Download complete, checking hashes');
azureOp.checkFilesHash(newManifestFile, path.join(dir, 'tmp'));
logfile.info('Hashes are fine');
const promises = newManifestFile.map(async (item) => {
logfile.info(`updating ${item.filetype}`);
switch (item.filetype) {
case 'snapclient':
return os.executeShellCommand(`kill -9 ${os.getFrontendPid()}`, logfile, true)
.then(() => {
os.executeShellCommand(`sudo echo "20 4 * * * root snap install --classic --dangerous ${path.join(dir, 'tmp', item.filename)}" >> /home/lenel/log`, logfile);
});
case 'snap':
return os.executeShellCommand(`kill -9 ${os.getFrontendPid()}`, logfile, true)
.then(() => {
return os.executeShellCommand(`sudo snap install --classic --dangerous ${path.join(dir, 'tmp', item.filename)}`, logfile, false);
});
case 'stm':
return os.executeShellCommand(`cp -f ${path.join(dir, 'tmp', item.filename)} ${dir}`, logfile, false);
case 'txz':
await os.executeShellCommand(`rm -fr ${path.join(dir, 'stm32mp15')}*`, logfile, false);
return os.executeShellCommand(`tar -xf ${path.join(dir, 'tmp', item.filename)} -C ${dir}`, logfile, false);
default: throw new Error(`Invalid filetype ${item.filetype}`);
}
});
await Promise.all(promises);
await os.executeShellCommand(`cp -f ${path.join(dir, 'tmp', 'manifestFile.json')} ${path.join(dir, 'tmp', 'manifestFileLocal.json')}`, logfile);
logfile.info('Done');
}
catch (err) {
const logconsole = console;
if (logfile !== undefined) logfile.error(err);
else logconsole.error(err);
}
finally {
const now = new Date();
const timeStamp = dateTime.format(now, 'YYYY_MM_DD_HH_MM_SS');
const filename = `${dir}/logs/${timeStamp}_m1cli.txz`;
await os.executeShellCommand(`tar -cJf ${filename} -C ${path.join(dir, 'logs/m1cli/logs', 'm1cli')} .`, false);
await os.executeShellCommand(`rm -fr ${path.join(dir, 'logs/m1cli/logs', 'm1cli')}`, false);
await new Promise(async (resolve, reject) => {
blobSvc.createBlockBlobFromLocalFile('m1-3200-logs', path.basename(filename), filename, async (error) => {
if (!error) {
resolve();
logfile.info(`uploaded file ${filename}`);
return;
}
reject(new Error(error));
});
});
}
});
program.command('synclogs')
.description('sync logs into Cloud AS')
.action(async () => {
const configData = await config({});
const logfile = logger.getLogger('m1cli', 'synclogs', 'synclogs', `${configData.m1mtfDir}/logs/m1cli`, debuglevel);
const matches = glob.sync(`${configData.m1mtfDir}/logs/*.txz`, { nonull: false, realpath: true });
const blobSvc = azure.createBlobService(configData.conString);
if (!matches.length) {
logfile.info('No log files to upload');
return;
}
try {
await azureOp.syncFiles(blobSvc, logContainer, matches);
}
catch (err) {
logfile.error(err.message);
return;
}
logfile.info('Download complete files uploaded:');
const syncedLogsDir = `${configData.m1mtfDir}/logs/syncedlogs`;
mkdirp.sync(syncedLogsDir);
matches.forEach((item) => {
logfile.info(path.basename(item));
fs.moveSync(item, path.join(`${syncedLogsDir}`, path.basename(item)));
});
});
program.command('backupdb')
.description('backup DB to the cloud')
.action(async () => {
const configData = await config({});
const logfile = logger.getLogger('m1cli', 'backupdb', 'backupdb', `${configData.m1mtfDir}/logs/m1cli`, debuglevel);
const dbFile = path.join(configData.m1mtfDir, 'tf.db');
const blobSvc = azure.createBlobService(configData.conString);
blobSvc.createBlockBlobFromLocalFile('backup', `${configData.vendorSite}_${path.basename(dbFile)}`, dbFile, (err) => {
if (err) {
logfile.error(err.message);
}
});
logfile.info(`Download complete DB file ${dbFile} is uploaded:`);
});
function padBase32(str) {
switch (str.length % 8) {
case 2:
return `${str}======`;
case 4:
return `${str}====`;
case 5:
return `${str}===`;
case 7:
return `${str}=`;
default:
return str;
}
}
function fromHexString(hexString) {
return Uint8Array.from(Buffer.from(hexString, 'hex'));
}
function getEncryptedSecretBase32(buffer) {
const publicKeyData = fs.readFileSync(publicKey);
const encryptedBuffer = crypto.publicEncrypt(publicKeyData, buffer);
const encoder = new Base32.Encoder({ type: 'rfc4648', lc: false, pad: '=' });
const str = encoder.write(encryptedBuffer).finalize();
return padBase32(str);
}
program.command('syncsecrets')
.description('sync M1-3200 secrets into Cloud AS')
.action(async () => {
const configData = await config({});
const logfile = logger.getLogger('m1cli', 'syncsecrets', 'syncsecrets', `${configData.m1mtfDir}/logs/m1cli`, debuglevel);
secrets.initialize(configData.m1mtfDir, logfile);
const now = new Date();
const filename = `/tmp/${dateTime.format(now, 'YYYY_MM_DD_HH_mm_ss')}.csv`;
const pattern = dateTime.compile('YYYY-MM-DDTHH:mm:ssZZ');
const date = dateTime.format(now, pattern);
try {
const blobSvc = azure.createBlobService(configData.conString);
const db = secrets.initialize(configData.m1mtfDir, logfile);
const records = db.getRecords();
if (!records.length) {
logfile.info('nothing to do');
return;
}
let firstLine = true;
records.forEach((board) => {
if (!board.uid || !board.secret || !board.boardS2Serial) return;
const data = {
date,
uid: `0000${board.uid.split(':').join('')}`,
secret: board.secret,
serial: board.boardS2Serial
};
const secretBuffer = getEncryptedSecretBase32(fromHexString(data.secret.substring(3)));
const line = `${data.date}|${data.uid}|${secretBuffer}|${data.serial.substring(3)}`;
if (firstLine) fs.writeFileSync(filename, `${line}\n`);
else fs.writeFileSync(filename, `${line}\n`, { flag: 'a+' });
firstLine = false;
});
if (firstLine) {
logfile.info('no secrets to sync');
return;
}
await azureOp.syncFiles(blobSvc, secretsContainer, [filename]);
fs.unlinkSync(filename);
records.forEach((board) => {
db.updateRecord(board.vendorSerial);
});
logfile.info('Done');
}
catch (err) {
logfile.error(err.message);
}
});
program.parse(process.argv);