-
Notifications
You must be signed in to change notification settings - Fork 477
/
PerfTestService.java
1513 lines (1367 loc) · 52.7 KB
/
PerfTestService.java
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ngrinder.perftest.service;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import net.grinder.SingleConsole;
import net.grinder.StopReason;
import net.grinder.common.GrinderProperties;
import net.grinder.console.communication.AgentProcessControlImplementation.AgentStatus;
import net.grinder.console.model.ConsoleProperties;
import net.grinder.util.ConsolePropertiesFactory;
import net.grinder.util.Directory;
import net.grinder.util.Pair;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;
import org.ngrinder.common.constant.ControllerConstants;
import org.ngrinder.common.constants.GrinderConstants;
import org.ngrinder.common.exception.PerfTestPrepareException;
import org.ngrinder.common.util.JsonUtils;
import org.ngrinder.infra.config.Config;
import org.ngrinder.infra.hazelcast.HazelcastService;
import org.ngrinder.model.*;
import org.ngrinder.monitor.controller.model.SystemDataModel;
import org.ngrinder.perftest.model.PerfTestStatistics;
import org.ngrinder.perftest.model.ProcessAndThread;
import org.ngrinder.perftest.model.SamplingModel;
import org.ngrinder.perftest.repository.PerfTestRepository;
import org.ngrinder.script.handler.NullScriptHandler;
import org.ngrinder.script.handler.ProcessingResultPrintStream;
import org.ngrinder.script.handler.ScriptHandler;
import org.ngrinder.script.handler.ScriptHandlerFactory;
import org.ngrinder.script.model.FileEntry;
import org.ngrinder.script.model.GitHubConfig;
import org.ngrinder.script.service.FileEntryService;
import org.ngrinder.script.service.GitHubFileEntryService;
import org.ngrinder.service.AbstractPerfTestService;
import org.python.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import static java.lang.Long.parseLong;
import static java.lang.Long.valueOf;
import static java.time.Instant.now;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.io.FileUtils.deleteQuietly;
import static java.util.Arrays.asList;
import static net.grinder.SingleConsole.REPORT_DATA;
import static org.apache.commons.io.FilenameUtils.removeExtension;
import static org.ngrinder.common.constant.CacheConstants.*;
import static org.ngrinder.common.constants.MonitorConstants.MONITOR_FILE_PREFIX;
import static org.ngrinder.common.util.AccessUtils.getSafe;
import static org.ngrinder.common.util.AopUtils.proxy;
import static org.ngrinder.common.util.CollectionUtils.*;
import static org.ngrinder.common.util.ExceptionUtils.processException;
import static org.ngrinder.common.util.LoggingUtils.format;
import static org.ngrinder.common.util.NoOp.noOp;
import static org.ngrinder.common.util.Preconditions.checkNotEmpty;
import static org.ngrinder.common.util.Preconditions.checkNotNull;
import static org.ngrinder.common.util.TypeConvertUtils.cast;
import static org.ngrinder.model.Status.*;
import static org.ngrinder.perftest.repository.PerfTestSpecification.*;
/**
* {@link PerfTest} Service Class.
* <p/>
* This class contains various method which mainly get the {@link PerfTest} matching specific conditions from DB.
*
* @since 3.0
*/
@SuppressWarnings({"ResultOfMethodCallIgnored", "BooleanMethodIsAlwaysInverted", "UnusedReturnValue", "SameParameterValue", "ConstantConditions"})
@RequiredArgsConstructor
public class PerfTestService extends AbstractPerfTestService implements ControllerConstants, GrinderConstants {
private static final int MAX_POINT_COUNT = 100;
private static final Logger LOGGER = LoggerFactory.getLogger(PerfTestService.class);
private static final String NULL_STRING = "null";
private static final String UNDEFINED_STRING = "undefined";
@Getter
private final PerfTestRepository perfTestRepository;
private final ConsoleManager consoleManager;
private final AgentManager agentManager;
@Getter
private final Config config;
private final FileEntryService fileEntryService;
private final TagService tagService;
private final ScriptHandlerFactory scriptHandlerFactory;
private final HazelcastService hazelcastService;
private final GitHubFileEntryService gitHubFileEntryService;
/**
* Get {@link PerfTest} list for the given user.
*
* @param user user
* @param query query string on test name or description
* @param tag search tag.
* @param queryFilter "S" for querying scheduled test, "F" for querying finished test
* @param pageable paging info
* @return found {@link PerfTest} list
*/
public Page<PerfTest> getPagedAll(User user, String query, String tag, String queryFilter, Pageable pageable) {
Specification<PerfTest> spec = Specification.where(idEmptyPredicate());
// User can see only his own test
if (user.getRole().equals(Role.USER)) {
spec = spec.and(createdBy(user));
}
if (StringUtils.isNotBlank(tag)) {
spec = spec.and(hasTag(tag));
}
if ("F".equals(queryFilter)) {
spec = spec.and(statusSetEqual(Status.FINISHED));
} else if ("R".equals(queryFilter)) {
spec = spec.and(statusSetEqual(Status.TESTING));
} else if ("S".equals(queryFilter)) {
spec = spec.and(statusSetEqual(Status.READY));
} else if ("RS".equals(queryFilter) || "SR".equals(queryFilter)) {
spec = spec.and(statusSetEqual(Status.TESTING, Status.READY));
}
if (StringUtils.isNotBlank(query)) {
spec = spec.and(likeTestNameOrDescription(query));
}
return perfTestRepository.findAll(spec, pageable);
}
/**
* Get {@link PerfTest} list on the user.
*
* @param user user
* @return found {@link PerfTest} list
*/
private List<PerfTest> getAll(User user) {
Specification<PerfTest> spec = Specification.where(createdBy(user));
return perfTestRepository.findAll(spec);
}
@Override
public PerfTest getOne(User user, Long id) {
Specification<PerfTest> spec = Specification.where(idEmptyPredicate());
// User can see only his own test
if (user.getRole().equals(Role.USER)) {
spec = spec.and(createdBy(user));
}
spec = spec.and(idEqual(id));
return perfTestRepository.findOne(spec).orElse(null);
}
@Override
public List<PerfTest> getAll(User user, Long[] ids) {
if (ids.length == 0) {
return newArrayList();
}
Specification<PerfTest> spec = Specification.where(idEmptyPredicate());
// User can see only his own test
if (user.getRole().equals(Role.USER)) {
spec = spec.and(createdBy(user));
}
spec = requireNonNull(spec).and(idSetEqual(ids));
return perfTestRepository.findAll(spec);
}
@Override
public long count(User user, Status[] statuses) {
Specification<PerfTest> spec = Specification.where(idEmptyPredicate());
// User can see only his own test
if (user != null) {
spec = spec.and(createdBy(user));
}
if (statuses.length == 0) {
return 0;
} else {
return perfTestRepository.count(spec.and(statusSetEqual(statuses)));
}
}
@Override
public List<PerfTest> getAll(User user, Status[] statuses) {
Specification<PerfTest> spec = Specification.where(idEmptyPredicate());
// User can see only his own test
if (user != null) {
spec = spec.and(createdBy(user));
}
if (statuses.length != 0) {
spec = requireNonNull(spec).and(statusSetEqual(statuses));
}
return perfTestRepository.findAll(spec);
}
private List<PerfTest> getAll(User user, String region, Status[] statuses) {
Specification<PerfTest> spec = Specification.where(idEmptyPredicate());
// User can see only his own test
if (user != null) {
spec = spec.and(createdBy(user));
}
if (statuses.length != 0) {
spec = spec.and(statusSetEqual(statuses));
}
if (config.isClustered()) {
spec = spec.and(regionStartsWith(region));
}
return perfTestRepository.findAll(spec);
}
@Override
@Transactional
public PerfTest save(User user, PerfTest perfTest) {
attachFileRevision(user, perfTest);
attachTags(user, perfTest, perfTest.getTagString());
return save(perfTest);
}
private PerfTest save(PerfTest perfTest) {
checkNotNull(perfTest);
// Merge if necessary
if (perfTest.exist()) {
Optional<PerfTest> existingPerfTest = perfTestRepository.findOne(idEqual(perfTest.getId()));
existingPerfTest.ifPresent(perfTest1 -> perfTest1.merge(perfTest));
} else {
perfTest.clearMessages();
perfTestRepository.saveAndFlush(perfTest);
}
return perfTest;
}
private void attachFileRevision(User user, PerfTest perfTest) {
if (perfTest.getStatus() == Status.READY) {
if (perfTest.isGitHubScm()) {
perfTest.setScriptRevision(String.valueOf(perfTest.getScriptRevision()));
} else {
FileEntry scriptEntry = fileEntryService.getOne(user, perfTest.getScriptName());
long revision = scriptEntry != null ? scriptEntry.getRevision() : -1L;
perfTest.setScriptRevision(String.valueOf(revision));
}
}
}
private void attachTags(User user, PerfTest perfTest, String tagString) {
SortedSet<Tag> tags = tagService.addTags(user,
StringUtils.split(StringUtils.trimToEmpty(tagString), ","));
perfTest.setTags(tags);
perfTest.setTagString(buildTagString(tags));
}
private String buildTagString(Set<Tag> tags) {
List<String> tagStringResult = new ArrayList<>();
for (Tag each : tags) {
tagStringResult.add(each.getTagValue());
}
return StringUtils.join(tagStringResult, ",");
}
/**
* Mark test error on {@link PerfTest} instance.
*
* @param perfTest {@link PerfTest}
* @param reason stop reason
* @return perftest with updated data
*/
@Transactional
public PerfTest markAbnormalTermination(PerfTest perfTest, StopReason reason) {
return markAbnormalTermination(perfTest, reason.getDisplay());
}
/**
* Mark test error on {@link PerfTest} instance.
*
* @param perfTest {@link PerfTest}
* @param reason stop reason
* @return perftest with updated data
*/
@Transactional
public PerfTest markAbnormalTermination(PerfTest perfTest, String reason) {
// Leave last status as test error cause
perfTest.setTestErrorCause(cast(perfTest.getStatus()));
return markStatusAndProgress(perfTest, Status.ABNORMAL_TESTING, reason);
}
@Transactional
@Override
public PerfTest markStatusAndProgress(PerfTest perfTest, Status status, String message) {
perfTest.setStatus(checkNotNull(status, "status should not be null"));
return markProgress(perfTest, message);
}
/**
* Add a progress message on the given perfTest.
*
* @param perfTest perf test
* @param message message to be recorded.
* @return saved {@link PerfTest}
*/
@Transactional
public PerfTest markProgress(PerfTest perfTest, String message) {
checkNotNull(perfTest);
checkNotNull(perfTest.getId(), "perfTest should save Id");
perfTest.setLastProgressMessage(message);
LOGGER.debug("Progress : Test - {} : {}", perfTest.getId(), message);
return perfTestRepository.saveAndFlush(perfTest);
}
/**
* Add a progress message on the given perfTest and change the status.
*
* @param perfTest perf test
* @param status status to be recorded.
* @param message message to be recorded.
* @return perftest with latest status and data
*/
@Transactional
public PerfTest markProgressAndStatus(PerfTest perfTest, Status status, String message) {
perfTest.setStatus(status);
return markProgress(perfTest, message);
}
/**
* Add a progress message on the given perfTest and change the status. In addition, the finish time and various test
* statistic are recorded as well.
*
* @param perfTest perf test
* @param status status to be recorded.
* @param message message to be recorded.
* @return perftest with latest status and data
*/
@Transactional
public PerfTest markProgressAndStatusAndFinishTimeAndStatistics(PerfTest perfTest, Status status, String message) {
perfTest.setFinishTime(now());
updatePerfTestAfterTestFinish(perfTest);
return markProgressAndStatus(perfTest, status, message);
}
/**
* mark the perftest to "START_CONSOLE_FINISHED" status .
*
* @param perfTest perftest to mark
* @param consolePort port of the console, on which the test is running
* @return saved perftest
*/
@Transactional
public PerfTest markPerfTestConsoleStart(PerfTest perfTest, int consolePort) {
perfTest.setPort(consolePort);
return markProgressAndStatus(perfTest, Status.START_CONSOLE_FINISHED, "Console is started on port "
+ consolePort);
}
@Transactional
@Override
public PerfTest getOneWithTag(Long testId) {
Optional<PerfTest> findOne = perfTestRepository.findOne(idEqual(testId));
PerfTest perfTest = null;
if (findOne.isPresent()) {
perfTest = findOne.get();
Hibernate.initialize(perfTest.getTags());
}
return perfTest;
}
@Override
public PerfTest getOne(Long testId) {
return perfTestRepository.findOne(idEqual(testId)).orElse(null);
}
/**
* Get the next runnable {@link PerfTest}.
*
* @return found {@link PerfTest} which is ready to run, null otherwise
*/
@Transactional
public PerfTest getNextRunnablePerfTestPerfTestCandidate() {
List<PerfTest> readyPerfTests = perfTestRepository.findAllByStatusOrderByScheduledTimeAsc(Status.READY);
List<PerfTest> filteredPerfTests = filterCurrentlyRunningTestUsersTest(readyPerfTests);
return filteredPerfTests.isEmpty() ? null : filteredPerfTests.get(0);
}
/**
* Get currently running {@link PerfTest} list.
*
* @return running test list
*/
public List<PerfTest> getCurrentlyRunningTest() {
return getAll(null, Status.getProcessingOrTestingTestStatus());
}
/**
* Filter out {@link PerfTest} whose owner is running another test now..
*
* @param perfTestLists perf test
* @return filtered perf test
*/
protected List<PerfTest> filterCurrentlyRunningTestUsersTest(List<PerfTest> perfTestLists) {
List<PerfTest> currentlyRunningTests = getCurrentlyRunningTest();
final Set<User> currentlyRunningTestOwners = newHashSet();
for (PerfTest each : currentlyRunningTests) {
currentlyRunningTestOwners.add(each.getCreatedBy());
}
return perfTestLists.stream()
.filter(perfTest -> !currentlyRunningTestOwners.contains(perfTest.getCreatedBy()))
.collect(toList());
}
@Override
public List<PerfTest> getAllTesting() {
return getAll(null, config.getRegion(), Status.getTestStatesByCategory(StatusCategory.TESTING));
}
@Override
public List<PerfTest> getAllProgressing() {
return getAll(null, config.getRegion(), Status.getTestStatesByCategory(StatusCategory.PROGRESSING));
}
public List<PerfTest> getAllAbnormalTesting() {
return getAll(null, config.getRegion(), new Status[]{Status.ABNORMAL_TESTING});
}
/**
* Delete test {@link PerfTest} by user and test id.
*
* @param user user
* @param id test id
*/
@Transactional
public void delete(User user, long id) {
PerfTest perfTest = getOne(id);
// If it's not requested by user who started job. It's wrong request.
if (!hasPermission(perfTest, user, Permission.DELETE_TEST_OF_OTHER)) {
return;
}
SortedSet<Tag> tags = perfTest.getTags();
if (tags != null) {
tags.clear();
}
perfTestRepository.save(perfTest);
perfTestRepository.delete(perfTest);
deletePerfTestDirectory(perfTest);
}
/**
* Delete {@link PerfTest} directory.
*
* @param perfTest perfTest
*/
private void deletePerfTestDirectory(PerfTest perfTest) {
deleteQuietly(getPerfTestDirectory(perfTest));
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.service.IPerfTestService#getPerfTestFilePath(org .ngrinder.perftest. model.PerfTest)
*/
@Override
public File getStatisticPath(PerfTest perfTest) {
return config.getHome().getPerfTestStatisticPath(perfTest);
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.service.IPerfTestService#getPerfTestFilePath(org .ngrinder.perftest. model.PerfTest)
*/
@Override
public File getDistributionPath(PerfTest perfTest) {
return config.getHome().getPerfTestDistDirectory(perfTest);
}
/**
* Build user library classpath on the given {@link PerfTest}.
*
* @param perfTest perftest
* @return custom class path.
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public String geUserLibraryClassPath(PerfTest perfTest) {
File perfTestDirectory = getDistributionPath(perfTest);
File libFolder = new File(perfTestDirectory, "lib");
final StringBuffer customClassPath = new StringBuffer();
customClassPath.append(".");
if (libFolder.exists()) {
customClassPath.append(File.pathSeparator).append("lib");
libFolder.list((dir, name) -> {
if (name.endsWith(".jar")) {
customClassPath.append(File.pathSeparator).append("lib/").append(name);
}
return true;
});
}
return customClassPath.toString();
}
/**
* Create {@link GrinderProperties} based on the passed {@link PerfTest}.
*
* @param perfTest base data
* @return created {@link GrinderProperties} instance
*/
public GrinderProperties getGrinderProperties(PerfTest perfTest) {
return getGrinderProperties(perfTest, new NullScriptHandler());
}
/**
* Create {@link GrinderProperties} based on the passed {@link PerfTest}.
*
* @param perfTest base data
* @param scriptHandler scriptHandler
* @return created {@link GrinderProperties} instance
*/
public GrinderProperties getGrinderProperties(PerfTest perfTest, ScriptHandler scriptHandler) {
try {
// Use default properties first
GrinderProperties grinderProperties = new GrinderProperties(config.getHome().getDefaultGrinderProperties());
User user = perfTest.getCreatedBy();
// Get all files in the script path
String scriptName = perfTest.getScriptName();
FileEntry userDefinedGrinderProperties = fileEntryService.getOne(user,
FilenameUtils.concat(FilenameUtils.getPath(scriptName), DEFAULT_GRINDER_PROPERTIES), -1L);
if (!config.isSecurityEnabled() && userDefinedGrinderProperties != null) {
// Make the property overridden by user property.
GrinderProperties userProperties = new GrinderProperties();
userProperties.load(new StringReader(userDefinedGrinderProperties.getContent()));
grinderProperties.putAll(userProperties);
}
grinderProperties.setAssociatedFile(new File(DEFAULT_GRINDER_PROPERTIES));
grinderProperties.setProperty(GRINDER_PROP_SCRIPT, scriptHandler.getScriptExecutePath(scriptName));
grinderProperties.setProperty(GRINDER_PROP_TEST_ID, "test_" + perfTest.getId());
grinderProperties.setInt(GRINDER_PROP_AGENTS, getSafe(perfTest.getAgentCount()));
grinderProperties.setInt(GRINDER_PROP_PROCESSES, getSafe(perfTest.getProcesses()));
grinderProperties.setInt(GRINDER_PROP_THREAD, getSafe(perfTest.getThreads()));
if (perfTest.isThresholdDuration()) {
grinderProperties.setLong(GRINDER_PROP_DURATION, getSafe(perfTest.getDuration()));
grinderProperties.setInt(GRINDER_PROP_RUNS, 0);
} else {
grinderProperties.setInt(GRINDER_PROP_RUNS, getSafe(perfTest.getRunCount()));
grinderProperties.remove(GRINDER_PROP_DURATION);
}
grinderProperties.setProperty(GRINDER_PROP_ETC_HOSTS,
StringUtils.defaultIfBlank(perfTest.getTargetHosts(), ""));
grinderProperties.setBoolean(GRINDER_PROP_USE_CONSOLE, true);
if (BooleanUtils.isTrue(perfTest.getUseRampUp())) {
grinderProperties.setBoolean(GRINDER_PROP_THREAD_RAMPUP, perfTest.getRampUpType() == RampUp.THREAD);
grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT, getSafe(perfTest.getRampUpStep()));
grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT_INTERVAL,
getSafe(perfTest.getRampUpIncrementInterval()));
if (perfTest.getRampUpType() == RampUp.PROCESS) {
grinderProperties.setInt(GRINDER_PROP_INITIAL_SLEEP_TIME, getSafe(perfTest.getRampUpInitSleepTime()));
} else {
grinderProperties.setInt(GRINDER_PROP_INITIAL_THREAD_SLEEP_TIME,
getSafe(perfTest.getRampUpInitSleepTime()));
}
grinderProperties.setInt(GRINDER_PROP_INITIAL_PROCESS, getSafe(perfTest.getRampUpInitCount()));
} else {
grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT, 0);
}
grinderProperties.setInt(GRINDER_PROP_REPORT_TO_CONSOLE, 500);
grinderProperties.setProperty(GRINDER_PROP_USER, perfTest.getCreatedBy().getUserId());
grinderProperties.setProperty(GRINDER_PROP_JVM_USER_LIBRARY_CLASSPATH, geUserLibraryClassPath(perfTest));
grinderProperties.setInt(GRINDER_PROP_IGNORE_SAMPLE_COUNT, getSafe(perfTest.getIgnoreSampleCount()));
grinderProperties.setBoolean(GRINDER_PROP_CONNECTION_RESET, getSafe(perfTest.getConnectionReset()));
grinderProperties.setBoolean(GRINDER_PROP_SECURITY, config.isSecurityEnabled());
grinderProperties.setProperty(GRINDER_PROP_SECURITY_LEVEL, config.getSecurityLevel());
// For backward agent compatibility.
// If the security is not enabled, pass it as jvm argument.
// If enabled, pass it to grinder.param. In this case, I drop the
// compatibility.
if (StringUtils.isNotBlank(perfTest.getParam())) {
String param = perfTest.getParam().replace("'", "\\'").replace(" ", "");
if (config.isSecurityEnabled()) {
grinderProperties.setProperty(GRINDER_PROP_PARAM, StringUtils.trimToEmpty(param));
} else {
String property = grinderProperties.getProperty(GRINDER_PROP_JVM_ARGUMENTS, "");
property = property + " -Dparam=" + param + " ";
grinderProperties.setProperty(GRINDER_PROP_JVM_ARGUMENTS, property);
}
}
LOGGER.info(format(perfTest, "Grinder Properties : {} ", grinderProperties));
return grinderProperties;
} catch (Exception e) {
throw processException("error while prepare grinder property for " + perfTest.getTestName(), e);
}
}
/**
* Prepare files for distribution. This method stores the files on the path
* ${NGRINDER_HOME}/perftest/{test_id}/dist folder.
*
* @param perfTest perfTest
* @return File location in which the perftest script and resources are distributed.
*/
public ScriptHandler prepareDistribution(PerfTest perfTest) throws IOException {
File perfTestDistDirectory = getDistributionPath(perfTest);
User user = perfTest.getCreatedBy();
String scm = perfTest.getScm();
FileEntry scriptEntry;
if (isGitHubScript(scm)) {
String gitHubConfigName = extractGitHubConfigName(scm);
GitHubConfig gitHubConfig = gitHubFileEntryService.getGitHubConfig(user, gitHubConfigName);
GitHub gitHub = gitHubFileEntryService.getGitHubClient(gitHubConfig);
GHRepository ghRepository = gitHub.getRepository(gitHubConfig.getOwner() + "/" + gitHubConfig.getRepo());
String scriptName = perfTest.getScriptName();
gitHubFileEntryService.checkoutGitHubScript(perfTest, ghRepository, gitHubConfig);
scriptEntry = gitHubFileEntryService.getOne(ghRepository, gitHubConfig, scriptName);
gitHubFileEntryService.evictGitHubGroovyProjectScriptTypeCache(ghRepository, scriptName, gitHubConfig.getBranch());
} else {
scriptEntry = checkNotNull(
fileEntryService.getOne(user,
checkNotEmpty(perfTest.getScriptName(), "perfTest should have script name"),
getSafe(valueOf(perfTest.getScriptRevision()))), "script should exist");
}
// Get all files in the script path.
ScriptHandler handler = scriptHandlerFactory.getHandler(scriptEntry);
LOGGER.info(format(perfTest, "Script type is '{}'.", handler.getKey()));
ProcessingResultPrintStream processingResult = new ProcessingResultPrintStream(new ByteArrayOutputStream());
handler.prepareDist(perfTest, user, scriptEntry, perfTestDistDirectory, config.getControllerProperties(),
processingResult);
LOGGER.info(format(perfTest, "File write is completed in {}", perfTestDistDirectory));
if (!processingResult.isSuccess()) {
File logDir = new File(getLogFileDirectory(perfTest), "distribution_log.txt");
try {
FileUtils.writeByteArrayToFile(logDir, processingResult.getLogByteArray());
} catch (IOException e) {
noOp();
}
throw processException("Error while file distribution is prepared.\n" +
"If you run groovy project type script, Please check your build script and make sure Maven or Gradle is installed.");
}
return handler;
}
public GrinderProperties prepareTest(PerfTest perfTest) {
try {
proxy(this).markStatusAndProgress(perfTest,
PREPARE_DISTRIBUTION, "Distribution files are being prepared.");
cleanUpPerftestDistributionFolder(perfTest);
ScriptHandler prepareDistribution = prepareDistribution(perfTest);
GrinderProperties grinderProperties = getGrinderProperties(perfTest, prepareDistribution);
proxy(this).markStatusAndProgress(perfTest,
PREPARE_DISTRIBUTION, "Distribution files are prepared.");
return grinderProperties;
} catch (Throwable e) {
throw new PerfTestPrepareException(e.getMessage(), e);
}
}
// scm format in db is name:revision
private String extractGitHubConfigName(String scm) {
return scm.split(":")[0];
}
private boolean isGitHubScript(String scm) {
return scm != null && !scm.equals("svn");
}
private void cleanUpPerftestDistributionFolder(PerfTest perfTest) {
File distributedFolder = config.getHome().getDistributedFolderName(perfTest.getId().toString());
if (distributedFolder.exists()) {
deleteQuietly(distributedFolder);
}
}
/**
* Get the process and thread policy java script.
*
* @return policy javascript
*/
public String getProcessAndThreadPolicyScript() {
return config.getProcessAndThreadPolicyScript();
}
/**
* Get the optimal process and thread count.
*
* @param newVuser the count of virtual users per agent
* @return optimal process thread count
*/
public ProcessAndThread calcProcessAndThread(int newVuser) {
try {
String script = getProcessAndThreadPolicyScript();
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
engine.eval(script);
int processCount = ((Double) engine.eval("getProcessCount(" + newVuser + ")")).intValue();
int threadCount = ((Double) engine.eval("getThreadCount(" + newVuser + ")")).intValue();
return new ProcessAndThread(processCount, threadCount);
} catch (ScriptException e) {
LOGGER.error("Error occurs while calc process and thread", e);
}
return new ProcessAndThread(1, 1);
}
/**
* get the data point interval of report data. Use dataPointCount / imgWidth as the interval. if interval is 1, it
* means we will get all point from report. If interval is 2, it means we will get 1 point from every 2 data.
*
* @param testId test id
* @param dataType data type
* @param imgWidth image width
* @return interval interval value
*/
public int getReportDataInterval(long testId, String dataType, int imgWidth) {
int pointCount = Math.max(imgWidth, MAX_POINT_COUNT);
File reportFolder = config.getHome().getPerfTestReportDirectory(String.valueOf(testId));
int interval = 0;
File targetFile = new File(reportFolder, dataType + REPORT_DATA);
if (!targetFile.exists()) {
LOGGER.warn("Report {} for test {} does not exist.", dataType, testId);
return 0;
}
try (LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(targetFile)))) {
lnr.skip(targetFile.length());
int lineNumber = lnr.getLineNumber() + 1;
interval = Math.max(lineNumber / pointCount, 1);
} catch (Exception e) {
LOGGER.error("Failed to get report data for {}", dataType, e);
}
return interval;
}
/**
* Get report file(csv data) for give test .
*
* @param perfTest test
* @return reportFile data report file
*/
public File getCsvReportFile(PerfTest perfTest) {
return config.getHome().getPerfTestCsvFile(perfTest);
}
/**
* Get log file names for give test id.
*
* @param testId test id
* @param fileName file name of one logs of the test
* @return file report file path
*/
public File getLogFile(long testId, String fileName) {
return new File(getLogFileDirectory(String.valueOf(testId)), fileName);
}
/**
* Get report file directory for give test .
*
* @param perfTest perfTest
* @return logDir log file path of the test
*/
public File getLogFileDirectory(PerfTest perfTest) {
return config.getHome().getPerfTestLogDirectory(perfTest);
}
/**
* Get report file directory for give test id.
*
* @param testId test id
* @return logDir log file path of the test
*/
public File getLogFileDirectory(String testId) {
return config.getHome().getPerfTestLogDirectory(testId);
}
/**
* Get log files list on the given test is.
*
* @param testId testId
* @return logFilesList log file list of that test
*/
public List<String> getLogFiles(long testId) {
File logFileDirectory = getLogFileDirectory(String.valueOf(testId));
if (!logFileDirectory.exists() || !logFileDirectory.isDirectory()) {
return Collections.emptyList();
}
return asList(requireNonNull(logFileDirectory.list()));
}
/**
* Get report file directory for give test .
*
* @param perfTest perftest
* @return reportDir report file path
*/
public File getReportFileDirectory(PerfTest perfTest) {
return config.getHome().getPerfTestReportDirectory(perfTest);
}
/**
* To save statistics data when test is running and put into cache after that. If the console is not available, it
* returns null.
*
* @param singleConsole single console.
* @param perfTestId perfTest Id
*/
public void saveStatistics(SingleConsole singleConsole, Long perfTestId) {
String runningSample = getProperSizeRunningSample(singleConsole);
String agentState = getProperSizedStatusString(singleConsole);
hazelcastService.put(DIST_MAP_NAME_SAMPLING, perfTestId, new SamplingModel(runningSample, agentState));
}
private String getProperSizeRunningSample(SingleConsole singleConsole) {
Map<String, Object> statisticData = singleConsole.getStatisticsData();
String runningSample = JsonUtils.serialize(statisticData);
if (runningSample.length() > 9950) { // max column size is 10,000
Map<String, Object> tempData = newHashMap();
for (Entry<String, Object> each : statisticData.entrySet()) {
String key = each.getKey();
if (key.equals("totalStatistics") || key.equals("cumulativeStatistics")
|| key.equals("lastSampleStatistics")) {
continue;
}
tempData.put(key, each.getValue());
}
runningSample = JsonUtils.serialize(tempData);
}
return runningSample;
}
/**
* Get the limited size of agent status json string.
*
* @param singleConsole console which is connecting agents
* @return converted json
*/
public String getProperSizedStatusString(SingleConsole singleConsole) {
Map<String, SystemDataModel> agentStatusMap = Maps.newHashMap();
final int singleConsolePort = singleConsole.getConsolePort();
for (AgentStatus each : agentManager.getAttachedAgentStatusSetConnectingToPort(singleConsolePort)) {
agentStatusMap.put(each.getAgentName(), each.getSystemDataModel());
}
return getProperSizedStatusString(agentStatusMap);
}
String getProperSizedStatusString(Map<String, SystemDataModel> agentStatusMap) {
String json = JsonUtils.serialize(agentStatusMap);
int statusLength = StringUtils.length(json);
if (statusLength > 9950) { // max column size is 10,000
LOGGER.info("Agent status string length: {}, too long to save into table.", statusLength);
double ratio = 9900.0 / statusLength;
int pickSize = (int) (agentStatusMap.size() * ratio);
Map<String, SystemDataModel> pickAgentStateMap = Maps.newHashMap();
int pickIndex = 0;
for (Entry<String, SystemDataModel> each : agentStatusMap.entrySet()) {
if (pickIndex < pickSize) {
pickAgentStateMap.put(each.getKey(), each.getValue());
pickIndex++;
}
}
json = JsonUtils.serialize(pickAgentStateMap);
LOGGER.debug("Agent status string get {} outof {} agents, new size is {}.", pickSize, agentStatusMap.size(), json.length());
}
return json;
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.service.IPerfTestService#getAllPerfTest()
*/
@Override
public List<PerfTest> getAllPerfTest() {
return perfTestRepository.findAll();
}
/**
* Create {@link ConsoleProperties} based on given {@link PerfTest} instance.
*
* @param perfTest perfTest
* @return {@link ConsoleProperties}
*/
public ConsoleProperties createConsoleProperties(PerfTest perfTest) {
ConsoleProperties consoleProperties = ConsolePropertiesFactory.createEmptyConsoleProperties();
try {
consoleProperties.setAndSaveDistributionDirectory(new Directory(getDistributionPath(perfTest)));
consoleProperties.setConsoleHost(config.getCurrentIP());
consoleProperties.setIgnoreSampleCount(getSafe(perfTest.getIgnoreSampleCount()));
consoleProperties.setSampleInterval(1000 * getSafe(perfTest.getSamplingInterval()));
} catch (Exception e) {
throw processException("Error while setting console properties", e);
}
return consoleProperties;
}
double parseDoubleWithSafety(Map<?, ?> map, Object key, Double defaultValue) {
Double doubleValue = MapUtils.getDouble(map, key, defaultValue);
return Math.round(doubleValue * 100D) / 100D;
}
/**
* Check if the given perfTest has too many errors. (30%)
*
* @param perfTest perftest
* @return true if too many errors.
*/
@SuppressWarnings("unchecked")
public boolean hasTooManyError(PerfTest perfTest) {
SamplingModel samplingModel = hazelcastService.get(DIST_MAP_NAME_SAMPLING, perfTest.getId());
if (samplingModel == null) {
return false;
}
Map<String, Object> result = JsonUtils.deserialize(samplingModel.getRunningSample(), HashMap.class);
Map<String, Object> totalStatistics = MapUtils.getMap(result, "totalStatistics", MapUtils.EMPTY_MAP);
long tests = MapUtils.getDouble(totalStatistics, "Tests", 0D).longValue();
long errors = MapUtils.getDouble(totalStatistics, "Errors", 0D).longValue();
return ((((double) errors) / (tests + errors)) > 0.3d);
}
/**
* Update the given {@link PerfTest} properties after test finished.
*
* @param perfTest perfTest
*/
public void updatePerfTestAfterTestFinish(PerfTest perfTest) {
checkNotNull(perfTest);
Map<String, Object> result = consoleManager.getConsoleUsingPort(perfTest.getPort()).getStatisticsData();
@SuppressWarnings("unchecked")
Map<String, Object> totalStatistics = MapUtils.getMap(result, "totalStatistics", MapUtils.EMPTY_MAP);
LOGGER.info(format(perfTest, "Total Statistics is {}", totalStatistics));
perfTest.setTps(parseDoubleWithSafety(totalStatistics, "TPS", 0D));
perfTest.setMeanTestTime(parseDoubleWithSafety(totalStatistics, "Mean_Test_Time_(ms)", 0D));
perfTest.setPeakTps(parseDoubleWithSafety(totalStatistics, "Peak_TPS", 0D));
perfTest.setTests(MapUtils.getDouble(totalStatistics, "Tests", 0D).longValue());
perfTest.setErrors(MapUtils.getDouble(totalStatistics, "Errors", 0D).longValue());
}
/**
* Get maximum concurrent test count.
*
* @return maximum concurrent test
*/
public int getMaximumConcurrentTestCount() {
return config.getControllerProperties().getPropertyInt(PROP_CONTROLLER_MAX_CONCURRENT_TEST);
}