-
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathValidator.cpp
More file actions
542 lines (441 loc) · 19 KB
/
Validator.cpp
File metadata and controls
542 lines (441 loc) · 19 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
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
/*==============================================================================
Copyright 2018 by Tracktion Corporation.
For more information visit www.tracktion.com
You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
pluginval IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================*/
#include "Validator.h"
#include "PluginTests.h"
#include "CrashHandler.h"
#include "CommandLine.h"
#include <numeric>
#include <thread>
#include <chrono>
//==============================================================================
struct PluginsUnitTestRunner : public juce::UnitTestRunner,
private juce::Thread
{
PluginsUnitTestRunner (std::function<void (const juce::String&)> logCallback, std::unique_ptr<juce::FileOutputStream> logDestination, juce::int64 timeoutInMs)
: Thread ("TimoutThread"),
callback (std::move (logCallback)),
outputStream (std::move (logDestination)),
timeoutMs (timeoutInMs)
{
jassert (callback);
resetTimeout();
if (timeoutInMs > 0)
startThread (juce::Thread::Priority::low);
}
~PluginsUnitTestRunner() override
{
stopThread (5000);
}
juce::FileOutputStream* getOutputFileStream() const
{
return outputStream.get();
}
void resultsUpdated() override
{
resetTimeout();
}
void logMessage (const juce::String& message) override
{
if (! canSendLogMessage)
return;
resetTimeout();
if (message.isNotEmpty())
{
if (outputStream)
*outputStream << message << "\n";
callback (message + "\n");
}
}
private:
std::function<void (const juce::String&)> callback;
std::unique_ptr<juce::FileOutputStream> outputStream;
const juce::int64 timeoutMs = -1;
std::atomic<juce::int64> timoutTime { -1 };
std::atomic<bool> canSendLogMessage { true };
void resetTimeout()
{
timoutTime = (juce::Time::getCurrentTime() + juce::RelativeTime::milliseconds (timeoutMs)).toMilliseconds();
}
void run() override
{
while (! threadShouldExit())
{
if (juce::Time::getCurrentTime().toMilliseconds() > timoutTime)
{
logMessage ("*** FAILED: Timeout after " + juce::RelativeTime::milliseconds (timeoutMs).getDescription());
canSendLogMessage = false;
outputStream.reset();
// Give the log a second to flush the message before terminating
juce::Thread::sleep (1000);
juce::Process::terminate();
}
juce::Thread::sleep (200);
}
}
};
//==============================================================================
//==============================================================================
static juce::String getFileNameFromDescription (PluginTests& test)
{
auto getBaseName = [&]() -> juce::String
{
if (auto pd = test.getDescriptions().getFirst())
return pd->manufacturerName + " - " + pd->name + " " + pd->version + " - " + juce::SystemStats::getOperatingSystemName() + " " + pd->pluginFormatName;
const auto fileOrID = test.getFileOrID();
if (fileOrID.isNotEmpty())
{
if (juce::File::isAbsolutePath (fileOrID))
return juce::File (fileOrID).getFileName();
}
return "pluginval Log";
};
return getBaseName() + "_" + juce::Time::getCurrentTime().toISO8601 (false).replace (":", ",") + ".txt";
}
static juce::File getDestinationFile (PluginTests& test)
{
const auto dir = test.getOptions().outputDir;
const auto filename = test.getOptions().outputFilename;
if (dir == juce::File())
{
if (juce::String() == filename)
return {};
return juce::File(filename);
}
if (dir.existsAsFile() || ! dir.createDirectory())
{
jassertfalse;
return {};
}
if (juce::String() == filename)
return dir.getChildFile (getFileNameFromDescription (test));
return dir.getChildFile (filename);
}
static std::unique_ptr<juce::FileOutputStream> createDestinationFileStream (PluginTests& test)
{
auto file = getDestinationFile (test);
if (file == juce::File())
return {};
std::unique_ptr<juce::FileOutputStream> fos (file.createOutputStream());
if (fos && fos->openedOk())
return fos;
jassertfalse;
return {};
}
/** Renames a file based upon its description.
This is useful if a path or AU ID was passed in as the plugin info isn't known at that point.
*/
static void updateFileNameIfPossible (PluginTests& test, PluginsUnitTestRunner& runner)
{
if (auto os = runner.getOutputFileStream())
{
const auto sourceFile = os->getFile();
const auto filename = test.getOptions().outputFilename;
const auto destName = (filename == juce::String())?getFileNameFromDescription (test) : filename;
if (destName.isEmpty() || sourceFile.getFileName() == destName)
return;
const bool success = sourceFile.moveFileTo (sourceFile.getParentDirectory().getChildFile (destName));
juce::ignoreUnused (success);
jassert (success);
}
}
//==============================================================================
//==============================================================================
inline int getNumFailures (juce::Array<juce::UnitTestRunner::TestResult> results);
inline juce::Array<juce::UnitTestRunner::TestResult> runTests (PluginTests& test, std::function<void (const juce::String&)> callback)
{
const auto options = test.getOptions();
juce::Array<juce::UnitTestRunner::TestResult> results;
PluginsUnitTestRunner testRunner (std::move (callback), createDestinationFileStream (test), options.timeoutMs);
testRunner.setAssertOnFailure (false);
juce::Array<juce::UnitTest*> testsToRun;
testsToRun.add (&test);
testRunner.runTests (testsToRun, options.randomSeed);
for (int i = 0; i < testRunner.getNumResults(); ++i)
results.add (*testRunner.getResult (i));
updateFileNameIfPossible (test, testRunner);
const int failures = getNumFailures (results);
if (! failures)
testRunner.logMessage("SUCCESS");
else
testRunner.logMessage("FAILURE");
return results;
}
inline juce::Array<juce::UnitTestRunner::TestResult> validate (const juce::String& fileOrIDToValidate, PluginTests::Options options, std::function<void (const juce::String&)> callback)
{
PluginTests test (fileOrIDToValidate, options);
return runTests (test, std::move (callback));
}
inline int getNumFailures (juce::Array<juce::UnitTestRunner::TestResult> results)
{
return std::accumulate (results.begin(), results.end(), 0,
[] (int count, const juce::UnitTestRunner::TestResult& r) { return count + r.failures; });
}
//==============================================================================
//==============================================================================
class ChildProcessValidator
{
public:
//==============================================================================
ChildProcessValidator (const juce::String& fileOrID_, PluginTests::Options options_,
std::function<void (juce::String)> validationStarted_,
std::function<void (juce::String, uint32_t /*exitCode*/)> validationEnded_,
std::function<void (const juce::String&)> outputGenerated_)
: fileOrID (fileOrID_),
options (options_),
validationStarted (std::move (validationStarted_)),
validationEnded (std::move (validationEnded_)),
outputGenerated (std::move (outputGenerated_))
{
thread = std::thread ([this] { run(); });
}
~ChildProcessValidator()
{
thread.join();
}
bool hasFinished() const
{
return ! isRunning;
}
private:
//==============================================================================
JUCE_DECLARE_WEAK_REFERENCEABLE (ChildProcessValidator)
const juce::String fileOrID;
PluginTests::Options options;
juce::ChildProcess childProcess;
std::thread thread;
std::atomic<bool> isRunning { true };
std::function<void (juce::String)> validationStarted;
std::function<void (juce::String, uint32_t)> validationEnded;
std::function<void(const juce::String&)> outputGenerated;
//==============================================================================
void run()
{
isRunning = childProcess.start (createCommandLine (fileOrID, options));
if (! isRunning)
return;
juce::MessageManager::callAsync ([this, wr = juce::WeakReference<ChildProcessValidator> (this)]
{
if (wr != nullptr && validationStarted)
validationStarted (fileOrID);
});
// Flush the output from the process
for (;;)
{
for (;;)
{
char buffer[2048];
if (const auto numBytesRead = childProcess.readProcessOutput (buffer, sizeof (buffer));
numBytesRead > 0)
{
std::string msg (buffer, (size_t) numBytesRead);
if (outputGenerated)
outputGenerated (msg);
}
else
{
break;
}
}
if (! childProcess.isRunning())
break;
using namespace std::literals;
std::this_thread::sleep_for (100ms);
}
juce::MessageManager::callAsync ([this, wr = juce::WeakReference<ChildProcessValidator> (this), exitCode = childProcess.getExitCode()]
{
if (wr != nullptr)
{
if (validationEnded)
validationEnded (fileOrID, exitCode);
isRunning = false;
}
});
}
};
//==============================================================================
//==============================================================================
class AsyncValidator
{
public:
//==============================================================================
AsyncValidator (const juce::String& fileOrID_, PluginTests::Options options_,
std::function<void (juce::String)> validationStarted_,
std::function<void (juce::String, uint32_t /*exitCode*/)> validationEnded_,
std::function<void (const juce::String&)> outputGenerated_)
: fileOrID (fileOrID_),
options (options_),
validationStarted (std::move (validationStarted_)),
validationEnded (std::move (validationEnded_)),
outputGenerated (std::move (outputGenerated_))
{
thread = std::thread ([this] { run(); });
}
~AsyncValidator()
{
thread.join();
}
bool hasFinished() const
{
return ! isRunning;
}
private:
//==============================================================================
JUCE_DECLARE_WEAK_REFERENCEABLE (AsyncValidator)
const juce::String fileOrID;
PluginTests::Options options;
std::thread thread;
std::atomic<bool> isRunning { true };
std::function<void (juce::String)> validationStarted;
std::function<void (juce::String, uint32_t)> validationEnded;
std::function<void (const juce::String&)> outputGenerated;
//==============================================================================
void run()
{
juce::MessageManager::callAsync ([this, wr = juce::WeakReference<AsyncValidator> (this)]
{
if (wr != nullptr && validationStarted)
validationStarted (fileOrID);
});
const auto numFailues = getNumFailures (validate (fileOrID, options, outputGenerated));
juce::MessageManager::callAsync ([this, wr = juce::WeakReference<AsyncValidator> (this), numFailues]
{
if (wr != nullptr)
{
if (validationEnded)
validationEnded (fileOrID, numFailues > 0 ? 1 : 0);
isRunning = false;
}
});
}
};
//==============================================================================
//==============================================================================
ValidationPass::ValidationPass (const juce::String& fileOrIdToValidate, PluginTests::Options opts, ValidationType vt,
std::function<void (juce::String)> validationStarted,
std::function<void (juce::String, uint32_t)> validationEnded,
std::function<void(const juce::String&)> outputGenerated)
{
if (vt == ValidationType::inProcess)
{
asyncValidator = std::make_unique<AsyncValidator> (fileOrIdToValidate, opts,
std::move (validationStarted),
std::move (validationEnded),
std::move (outputGenerated));
}
else if (vt == ValidationType::childProcess)
{
childProcessValidator = std::make_unique<ChildProcessValidator> (fileOrIdToValidate, opts,
std::move (validationStarted),
std::move (validationEnded),
std::move (outputGenerated));
}
}
ValidationPass::~ValidationPass()
{
}
bool ValidationPass::hasFinished() const
{
return asyncValidator ? asyncValidator->hasFinished()
: childProcessValidator->hasFinished();
}
//==============================================================================
//==============================================================================
class MultiValidator : public juce::Timer
{
public:
MultiValidator (juce::StringArray fileOrIDsToValidate,
PluginTests::Options options_,
ValidationType validationType_,
std::function<void (juce::String)> validationStarted_,
std::function<void (juce::String, uint32_t /*exitCode*/)> validationEnded_,
std::function<void(const juce::String&)> outputGenerated_,
std::function<void()> allCompleteCallback_)
: pluginsToValidate (std::move (fileOrIDsToValidate)),
options (std::move (options_)),
validationType (validationType_),
validationStarted (std::move (validationStarted_)),
validationEnded (std::move (validationEnded_)),
outputGenerated (std::move (outputGenerated_)),
completeCallback (std::move (allCompleteCallback_))
{
startTimerHz (20);
timerCallback();
}
private:
juce::StringArray pluginsToValidate;
const PluginTests::Options options;
const ValidationType validationType;
std::unique_ptr<ValidationPass> validationPass;
std::function<void (juce::String)> validationStarted;
std::function<void (juce::String, uint32_t /*exitCode*/)> validationEnded;
std::function<void(const juce::String&)> outputGenerated;
std::function<void()> completeCallback;
//==============================================================================
bool isRunning() const
{
return validationPass ? ! validationPass->hasFinished()
: false;
}
//==============================================================================
void timerCallback() override
{
if (pluginsToValidate.isEmpty())
{
if (isRunning())
return;
validationPass.reset();
if (completeCallback)
completeCallback();
stopTimer();
return;
}
if (isRunning())
return;
validationPass = std::make_unique<ValidationPass> (pluginsToValidate[0], options, validationType,
validationStarted,
validationEnded,
outputGenerated);
pluginsToValidate.remove (0);
}
};
//==============================================================================
Validator::Validator() {}
Validator::~Validator() {}
bool Validator::isConnected() const
{
return multiValidator != nullptr;
}
bool Validator::validate (const juce::StringArray& fileOrIDsToValidate, PluginTests::Options options)
{
sendChangeMessage();
multiValidator = std::make_unique<MultiValidator> (fileOrIDsToValidate, options, launchInProcess ? ValidationType::inProcess : ValidationType::childProcess,
[this] (juce::String id) { listeners.call (&Listener::validationStarted, id); },
[this] (juce::String id, uint32_t exitCode) { listeners.call (&Listener::itemComplete, id, exitCode); },
[this] (const juce::String& m) { listeners.call (&Listener::logMessage, m); },
[this] { listeners.call (&Listener::allItemsComplete); triggerAsyncUpdate(); });
return true;
}
bool Validator::validate (const juce::Array<juce::PluginDescription>& pluginsToValidate, PluginTests::Options options)
{
juce::StringArray fileOrIDsToValidate;
for (auto pd : pluginsToValidate)
fileOrIDsToValidate.add (pd.fileOrIdentifier);
return validate (fileOrIDsToValidate, options);
}
void Validator::setValidateInProcess (bool useSameProcess)
{
launchInProcess = useSameProcess;
}
//==============================================================================
void Validator::handleAsyncUpdate()
{
multiValidator.reset();
sendChangeMessage();
}