forked from oracle-actions/setup-testpilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSession.java
More file actions
757 lines (660 loc) · 27.8 KB
/
Copy pathSession.java
File metadata and controls
757 lines (660 loc) · 27.8 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
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
/*
** Oracle Test Pilot
**
** Copyright (c) 2025-2026 Oracle
** Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
*/
package com.oracle.testpilot;
import com.oracle.testpilot.exception.TestPilotException;
import com.oracle.testpilot.json.JSON;
import com.oracle.testpilot.json.JSONArray;
import com.oracle.testpilot.model.*;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Base64;
import static com.oracle.testpilot.exception.TestPilotException.*;
import static com.oracle.testpilot.model.Action.*;
/**
* Oracle Test Pilot session.
*
* @author LLEFEVRE
* @since 1.0.0
*/
public class Session {
private static final int ONE_MINUTE_TIMEOUT = 60; // seconds
private static final int TEN_MINUTES_TIMEOUT = 600; // seconds
private static final int MAX_USERS = 10;
private static final int MAX_USER_LENGTH = 118;
private static final int COMMA_LENGTH = 1;
private static final int MAX_USERS_LENGTH = (MAX_USER_LENGTH + COMMA_LENGTH) * MAX_USERS - COMMA_LENGTH;
public Action action;
private final String githubOutput;
private final String runID;
private final String jobID;
private final String apiHOST;
private String token;
private final String clientId;
private String users;
private String technologyType;
private ConnectionStringFormat connectionStringFormat;
private String prefixList;
private String owner;
private String repository;
private String pullRequestNumber;
public Session(final String[] args) {
// ---------------------------------------------------------------------------------------------------------------------
// GITHUB_OUTPUT:
// The path on the runner to the file that sets the current step's outputs from workflow
// commands. The path to this file is unique to the current step and changes for each step
// in a job. For example, /home/runner/work/_temp/_runner_file_commands/set_output_a50ef383-b063-46d9-9157-57953fc9f3f0.
// see https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-commands#setting-an-output-parameter
githubOutput = System.getenv("GITHUB_OUTPUT");
// ---------------------------------------------------------------------------------------------------------------------
// RUNID:
// Variable initialized by this GitHub Action from within its action.yml file.
// env:
// RUNID: ${{ github.run_number }}
// github.run_number: A unique number for each run of a particular workflow in a repository.
// This number begins at 1 for the workflow's first run, and increments with each new run. This
// number does not change if you re-run the workflow run.
// see https://docs.github.com/en/actions/reference/workflows-and-actions/contexts#github-context
runID = System.getenv("RUNID");
// ---------------------------------------------------------------------------------------------------------------------
// JOBID:
// The check run ID of the current job.
// env:
// JOBID: ${{ job.check_run_id }}
// job.check_run_id: The check run ID of the current job.
// see https://docs.github.com/en/actions/reference/workflows-and-actions/contexts#job-context
jobID = System.getenv("JOBID");
// ---------------------------------------------------------------------------------------------------------------------
// API_HOST:
// URL targeting the private internal REST API endpoints to create and delete a user schema to be used to
// connect to the database to test the framework with. This environment variable is not exposed (read or write) to
// end users. It is also masked from standard GitHub Action log output.
apiHOST = System.getenv("API_HOST");
// ---------------------------------------------------------------------------------------------------------------------
// TESTPILOT_TOKEN:
// OAuth2 client secret to use for accessing the private internal REST API endpoints to create and delete a user schema.
// This environment variable is not exposed (read or write) to end users. It is also masked from standard GitHub Action log output.
token = System.getenv("TESTPILOT_TOKEN");
// ---------------------------------------------------------------------------------------------------------------------
// TESTPILOT_CLIENT_ID:
// OAuth2 client id to use for accessing the private internal REST API endpoints to create and delete a user schema.
// This environment variable is not exposed (read or write) to end users. It is also masked from standard GitHub Action log output.
clientId = System.getenv("TESTPILOT_CLIENT_ID");
analyzeCommandLineParameters(args);
}
private void analyzeCommandLineParameters(final String[] args) {
for (int i = 0; i < args.length; i++) {
final String arg = args[i].toLowerCase();
switch (arg) {
case "--help":
case "-h":
case "-?":
displayUsage();
System.exit(0);
break;
case "--create":
action = CREATE;
break;
case "--delete":
action = DELETE;
break;
case "--user":
if (i + 1 < args.length) {
users = args[++i];
if(users.length() > MAX_USERS_LENGTH) {
throw new TestPilotException(USER_PARAMETER_TOO_LONG, new IllegalArgumentException("Value for --user parameter is too long, maximum length: "+MAX_USERS_LENGTH));
}
}
else {
throw new TestPilotException(USER_MISSING_PARAMETER, new IllegalArgumentException("Missing value for --user parameter"));
}
break;
case "--oci-service":
if (i + 1 < args.length) {
try {
technologyType = args[++i];
switch (technologyType) {
case "autonomous-transaction-processing-serverless-19c":
case "autonomous-transaction-processing-serverless":
case "autonomous-transaction-processing-serverless-26ai":
case "base-database-service-19c":
case "base-database-service-21c":
case "base-database-service-23ai":
case "base-database-service-26ai":
break;
default:
throw new IllegalArgumentException(technologyType);
}
}
catch (IllegalArgumentException iae) {
throw new TestPilotException(WRONG_OCI_SERVICE_PARAMETER,
new IllegalArgumentException("--oci-service must be either autonomous-transaction-processing-serverless-19c, autonomous-transaction-processing-serverless-26ai, base-database-service-19c, base-database-service-21c, base-database-service-26ai, or base-database-service-23ai"));
}
}
else {
throw new TestPilotException(OCI_SERVICE_MISSING_PARAMETER, new IllegalArgumentException("Missing value for --oci-service parameter"));
}
break;
case "--connection-string-format":
if (i + 1 < args.length) {
final String temp = args[++i];
if("tns".equalsIgnoreCase(temp)) {
connectionStringFormat = ConnectionStringFormat.TNS;
} else {
connectionStringFormat = ConnectionStringFormat.EASY_CONNECT;
}
}
else {
throw new TestPilotException(CONNECTION_STRING_FORMAT_MISSING_PARAMETER, new IllegalArgumentException("Missing value for --connection-string-format parameter"));
}
break;
case "--skip-testing":
action = SKIP_TESTING;
break;
case "--prefix-list":
if (i + 1 < args.length) {
prefixList = args[++i];
}
else {
throw new TestPilotException(PREFIX_LIST_MISSING_PARAMETER, new IllegalArgumentException("Missing value for --prefix-list parameter"));
}
break;
case "--owner":
if (i + 1 < args.length) {
owner = args[++i];
}
else {
throw new TestPilotException(OWNER_MISSING_PARAMETER, new IllegalArgumentException("Missing value for --owner parameter"));
}
break;
case "--repository":
if (i + 1 < args.length) {
repository = args[++i];
}
else {
throw new TestPilotException(REPOSITORY_MISSING_PARAMETER, new IllegalArgumentException("Missing value for --repository parameter"));
}
break;
case "--pull-request-number":
if (i + 1 < args.length) {
pullRequestNumber = args[++i];
}
else {
throw new TestPilotException(PULL_REQUEST_NUMBER_MISSING_PARAMETER, new IllegalArgumentException("Missing value for --pull-request-number parameter"));
}
break;
default:
displayUsage();
//System.out.println("Wrong arg: "+arg);
throw new TestPilotException(UNKNOWN_COMMAND_LINE_ARGUMENT);
}
}
}
private void displayUsage() {
System.out.println("""
Usage: setup-testpilot <action> <options...>
Action:
--create: to provision the requested Oracle Cloud Infrastructure service to test
Options:
--oci-service <value> OCI service type (autonomous-transaction-processing-serverless, base-database-service-19c, base-database-service-21c, base-database-service-26ai)
--user <user> user name to be used (if several, then comma separated list without any space)
--connection-string-format requested connection string format (easy-connect*, or tns)
--delete: to de-provision the Oracle Cloud Infrastructure service
Options:
--oci-service <value> OCI service type (autonomous-transaction-processing-serverless, base-database-service-19c, base-database-service-21c, base-database-service-26ai)
--user <user> user name to be used (if several, then comma separated list without any space)
--skip-testing
Options:
--owner <owner> GitHub project owner
--repository <repository> GitHub project repository
--sha <sha> GitHub commit sha to check
--prefix-list <p1,p2,...> comma separated list of prefixes that will NOT trigger tests (can be file and folders)
""");
}
public void run() {
if (action == null) return;
switch (action) {
case CREATE:
create();
break;
case DELETE:
delete();
break;
case SKIP_TESTING:
skipTesting();
break;
}
}
private void create() {
if (users == null || users.isEmpty()) {
throw new TestPilotException(CREATE_DATABASE_MISSING_USER_NAME);
}
if(badChars(users)) {
throw new TestPilotException(CREATE_DATABASE_WRONG_USER_NAME);
}
if (technologyType == null) {
throw new TestPilotException(CREATE_DATABASE_MISSING_DB_TYPE);
}
try {
final String type = getInternalTechnologyType(technologyType);
final String uri = String.format("https://%s/ords/testpilot/resources/create", apiHOST);
boolean done = false;
int retryCount = 5;
do {
setOAuth2Token();
final HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(uri))
.headers("Accept", "application/json",
"Content-Type", "application/json",
"Pragma", "no-cache",
"Cache-Control", "no-store",
"User-Agent", "setup-testpilot/" + Main.VERSION,
"Authorization", "Bearer " + token)
.POST(HttpRequest.BodyPublishers.ofString(
String.format("{\"runID\":\"%s\",\"jobID\":\"%s\",\"type\":\"%s\",\"user\":[%s]}",
runID, jobID, type, buildUserList(users,true))
))
.build();
try (HttpClient client = HttpClient
.newBuilder()
.connectTimeout(Duration.ofSeconds(ONE_MINUTE_TIMEOUT))
.version(HttpClient.Version.HTTP_1_1)
.proxy(ProxySelector.getDefault())
.followRedirects(HttpClient.Redirect.NORMAL)
.build()) {
final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200 || response.statusCode() == 201) {
done = true;
// retrieve JSON response
final String jsonInformation = response.body();
switch (type) {
case TechnologyType.AUTONOMOUS26AI:
case TechnologyType.AUTONOMOUS19C: {
Database database = new JSON<>(Database.class).parse(jsonInformation);
database = new JSON<>(Database.class).parse(database.getDatabase());
final String connectionString = connectionStringFormat == ConnectionStringFormat.TNS ?
String.format("(description=(retry_count=5)(retry_delay=1)(address=(protocol=tcps)(port=1521)(host=%s.oraclecloud.com))(connect_data=(USE_TCP_FAST_OPEN=ON)(service_name=%s_tp.adb.oraclecloud.com))(security=(ssl_server_dn_match=no)))", database.getHost(), database.getService())
:
String.format("tcps://%s.oraclecloud.com:1521/%s_tp.adb.oraclecloud.com?retry_count=5&retry_delay=1&oracle.net.useTcpFastOpen=true&ssl_server_dn_match=false", database.getHost(), database.getService());
writeDatabaseInformationToGitHubOutput(database, connectionString);
}
break;
case TechnologyType.DB19C:
case TechnologyType.DB21C:
case TechnologyType.DB23AI:
case TechnologyType.DB26AI: {
Database database = new JSON<>(Database.class).parse(jsonInformation);
database = new JSON<>(Database.class).parse(database.getDatabase());
final String connectionString = connectionStringFormat == ConnectionStringFormat.TNS ?
String.format("(description=(retry_count=3)(retry_delay=1)(address=(protocol=tcp)(port=1521)(host=%s))(connect_data=(service_name=%s)))", database.getHost(), database.getService())
:
String.format("%s:1521/%s?retry_count=3&retry_delay=1", database.getHost(), database.getService());
writeDatabaseInformationToGitHubOutput(database, connectionString);
}
break;
case TechnologyType.DB26AIRAC: {
Database database = new JSON<>(Database.class).parse(jsonInformation);
database = new JSON<>(Database.class).parse(database.getDatabase());
// using scan listener as the host
final String connectionString = connectionStringFormat == ConnectionStringFormat.TNS ?
String.format("(description=(connect_timeout=5)(transport_connect_timeout=3)(retry_count=3)(retry_delay=1)(address_list=(load_balance=on)(address=(protocol=tcp)(host=%s)(port=1521)))(connect_data=(service_name=%s)))", database.getHost(), database.getService())
:
String.format("%s:1521/%s?retry_count=3&retry_delay=1", database.getHost(), database.getService());
writeDatabaseInformationToGitHubOutput(database, connectionString);
}
break;
}
if (githubOutput != null) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(githubOutput, true)))) {
out.println("create=ok");
}
}
}
else if(response.statusCode() == 429) {
// too many requests (rate limiting)
Thread.sleep(10 * 1000L);
}
else if(response.statusCode() == 504) {
// Gateway time-out (load balancer)
// retry 5 times with 1 minute time-out each time
retryCount--;
if(retryCount == 0) {
if(githubOutput != null) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(githubOutput, true)))) {
out.println("create=ko");
}
}
throw new TestPilotException(CREATE_DATABASE_REST_ENDPOINT_ISSUE,
new IllegalStateException("HTTP/S status code: " + response.statusCode(),
new IllegalStateException(response.body())));
} else {
System.out.printf("Gateway time-out, retrying in 10 seconds...%n");
Thread.sleep(10 * 1000L);
}
}
else {
if(githubOutput != null) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(githubOutput, true)))) {
out.println("create=ko");
}
}
throw new TestPilotException(CREATE_DATABASE_REST_ENDPOINT_ISSUE,
new IllegalStateException("HTTP/S status code: " + response.statusCode(),
new IllegalStateException(response.body())));
}
}
} while(!done);
}
catch (URISyntaxException e) {
if (githubOutput != null) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(githubOutput, true)))) {
out.println("delete=ko");
}
catch(IOException ignored) {}
}
throw new TestPilotException(WRONG_MAIN_CONTROLLER_URI, e);
}
catch (IOException | InterruptedException e) {
if (githubOutput != null) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(githubOutput, true)))) {
out.println("delete=ko");
}
catch(IOException ignored) {}
}
throw new TestPilotException(WRONG_MAIN_CONTROLLER_REST_CALL, e);
}
}
private void writeDatabaseInformationToGitHubOutput(Database database, String connectionString) throws FileNotFoundException {
if (githubOutput != null) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(githubOutput, true)))) {
System.out.printf("::add-mask::%s%n", database.getPassword());
out.printf("""
database_host=%s
database_service=%s
database_password=%s
database_version=%s
connection_string_suffix="%s"%n""",
database.getHost(), database.getService(), database.getPassword(), database.getVersion(),
connectionString);
}
}
}
private void delete() {
if (users == null || users.isEmpty()) {
throw new TestPilotException(DROP_DATABASE_MISSING_USER_NAME);
}
if(badChars(users)) {
throw new TestPilotException(DROP_DATABASE_WRONG_USER_NAME);
}
if (technologyType == null) {
throw new TestPilotException(DROP_DATABASE_MISSING_DB_TYPE);
}
try {
final String type = getInternalTechnologyType(technologyType);
final String uri = String.format("https://%s/ords/testpilot/resources/delete", apiHOST);
boolean done = false;
do {
setOAuth2Token();
final HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(uri))
.headers("Accept", "application/json",
"Content-Type", "application/json",
"Pragma", "no-cache",
"Cache-Control", "no-store",
"User-Agent", "setup-testpilot/" + Main.VERSION,
"Authorization", "Bearer " + token)
.POST(HttpRequest.BodyPublishers.ofString(
String.format("{\"runID\":\"%s\",\"jobID\":\"%s\",\"type\":\"%s\",\"user\":[%s]}",
runID, jobID, type, buildUserList(users,false))
))
.build();
try (HttpClient client = HttpClient
.newBuilder()
.connectTimeout(Duration.ofSeconds(TEN_MINUTES_TIMEOUT))
.version(HttpClient.Version.HTTP_1_1)
.proxy(ProxySelector.getDefault())
.followRedirects(HttpClient.Redirect.NORMAL)
.build()) {
final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200 || response.statusCode() == 204) {
done = true;
if (githubOutput != null) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(githubOutput, true)))) {
out.println("delete=ok");
}
}
}
else if(response.statusCode() == 429) {
// too many requests (rate limiting)
Thread.sleep(10 * 1000L);
}
else if(response.statusCode() == 503) {
// ORA-01940: cannot drop a user that is currently connected
Thread.sleep(10 * 1000L);
}
else if(response.statusCode() == 504) {
// time out after 10 minutes trying to delete the database
done = true;
if(githubOutput != null) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(githubOutput, true)))) {
out.println("delete=ko");
}
}
}
else {
if (githubOutput != null) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(githubOutput, true)))) {
out.println("delete=ko");
}
}
throw new TestPilotException(DROP_DATABASE_REST_ENDPOINT_ISSUE,
new IllegalStateException("HTTP/S status code: " + response.statusCode()));
}
}
} while(!done);
}
catch (URISyntaxException e) {
if(githubOutput != null) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(githubOutput, true)))) {
out.println("delete=ko");
}
catch(IOException ignored) {}
}
throw new TestPilotException(WRONG_MAIN_CONTROLLER_URI, e);
}
catch (IOException | InterruptedException e) {
if(githubOutput != null) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(githubOutput, true)))) {
out.println("delete=ko");
}
catch(IOException ignored) {}
}
throw new TestPilotException(WRONG_MAIN_CONTROLLER_REST_CALL, e);
}
}
private boolean badChars(final String users) {
for(int i = 0; i < users.length(); i++) {
final char c = users.charAt(i);
if( !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == ',' || c == '-' || c == ':' || c == '.' || (c >= '0' && c <= '9')) ) return true;
}
return false;
}
private void setOAuth2Token() throws URISyntaxException, IOException, InterruptedException {
final String uri = String.format("https://%s/ords/testpilot/oauth/token", apiHOST);
final HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(uri))
.headers("Accept", "application/json",
"Content-Type", "application/x-www-form-urlencoded",
"Pragma", "no-cache",
"Cache-Control", "no-store",
"User-Agent", "setup-testpilot/" + Main.VERSION,
"Authorization", basicAuth())
.POST(HttpRequest.BodyPublishers.ofString("grant_type=client_credentials"))
.build();
try (HttpClient client = HttpClient
.newBuilder()
.connectTimeout(Duration.ofSeconds(ONE_MINUTE_TIMEOUT))
.version(HttpClient.Version.HTTP_1_1)
.proxy(ProxySelector.getDefault())
.followRedirects(HttpClient.Redirect.NORMAL)
.build()) {
final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
OAuthToken oauthToken = new JSON<>(OAuthToken.class).parse(response.body());
token = oauthToken.getAccess_token();
}
else {
throw new TestPilotException(RETRIEVE_OAUTH2_TOKEN,
new IllegalStateException("HTTP/S status code: " + response.statusCode()));
}
}
}
private String buildUserList(final String users, boolean create) {
final StringBuilder sb = new StringBuilder();
int i = 0;
final String[] usersArray = users.split(",");
if(usersArray.length > MAX_USERS) {
throw new TestPilotException(TOO_MANY_USERS_PROVIDED);
}
for (String user : usersArray) {
if(user.isEmpty() || user.length() > MAX_USER_LENGTH) {
throw new TestPilotException(create ? CREATE_DATABASE_WRONG_USER_NAME_LENGTH : DROP_DATABASE_WRONG_USER_NAME_LENGTH);
}
if (i > 0) {
sb.append(',');
}
sb.append("\"").append(user).append("\"");
i++;
}
return sb.toString();
}
private String getInternalTechnologyType(final String technologyType) {
return switch (technologyType) {
case "autonomous-transaction-processing-serverless-19c" -> TechnologyType.AUTONOMOUS19C;
case "autonomous-transaction-processing-serverless", "autonomous-transaction-processing-serverless-26ai" -> TechnologyType.AUTONOMOUS26AI;
case "base-database-service-19c" -> TechnologyType.DB19C;
case "base-database-service-21c" -> TechnologyType.DB21C;
case "base-database-service-23ai" -> TechnologyType.DB23AI;
case "base-database-service-26ai" -> TechnologyType.DB26AI;
case "base-database-service-26ai-rac" -> TechnologyType.DB26AIRAC;
default -> throw new TestPilotException(CREATE_DATABASE_MISSING_DB_TYPE);
};
}
private String basicAuth() {
return String.format("Basic %s", Base64.getEncoder().encodeToString((String.format("%s:%s", clientId, token)).getBytes()));
}
/**
* Analyze the list of files present inside the commit(s) of a PR and compare it
* with a list of files and folder prefixes that must not trigger any
* build and test (example: documentation). In that case, the response
* is clear: no need to build.
*/
private void skipTesting() {
if (owner == null || owner.isEmpty()) {
throw new TestPilotException(SKIP_TESTING_MISSING_OWNER);
}
if (repository == null || repository.isEmpty()) {
throw new TestPilotException(SKIP_TESTING_MISSING_REPOSITORY);
}
if (pullRequestNumber == null || pullRequestNumber.isEmpty()) {
throw new TestPilotException(SKIP_TESTING_MISSING_PULL_REQUEST_NUMBER);
}
if (prefixList == null || prefixList.isEmpty()) {
throw new TestPilotException(SKIP_TESTING_MISSING_PREFIX_LIST);
}
try {
final String uri = String.format("https://api.github.com/repos/%s/%s/pulls/%s/commits", owner, repository, pullRequestNumber);
final HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(uri))
.headers("Accept", "application/vnd.github+json",
"Pragma", "no-cache",
"Cache-Control", "no-store",
"User-Agent", "setup-testpilot/" + Main.VERSION)
.GET()
.build();
try (HttpClient client = HttpClient
.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.proxy(ProxySelector.getDefault())
.followRedirects(HttpClient.Redirect.NORMAL)
.build()) {
final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
// prepare prefixes
final String[] prefixes = prefixList.split(",");
final GitHubPullRequestCommits[] commits = new JSONArray<>(GitHubPullRequestCommits[].class).parse(response.body());
System.out.println("Pull Request contains "+commits.length+" commit(s).");
int totalFilesNumber = 0;
int totalFilesMatchingAnyPrefix = 0;
for(GitHubPullRequestCommits commit : commits) {
final HttpRequest committedFilesRequest = HttpRequest.newBuilder()
.uri(new URI(commit.getUrl()))
.headers("Accept", "application/vnd.github+json",
"Pragma", "no-cache",
"Cache-Control", "no-store",
"User-Agent", "setup-testpilot/" + Main.VERSION)
.GET()
.build();
final HttpResponse<String> committedFilesResponse = client.send(committedFilesRequest, HttpResponse.BodyHandlers.ofString());
if (committedFilesResponse.statusCode() == 200) {
final GitHubCommittedFiles files = new JSON<>(GitHubCommittedFiles.class).parse(committedFilesResponse.body());
totalFilesNumber += files.getFiles().length;
for (GitHubFilename filename : files.getFiles()) {
final String filenameToTest = filename.getFilename();
for (String prefix : prefixes) {
if (filenameToTest.startsWith(prefix)) {
totalFilesMatchingAnyPrefix++;
break;
}
}
}
}
}
System.out.println("File(s) analyzed: "+totalFilesNumber+".");
System.out.println("File(s) matching avoidance prefix(es): "+totalFilesMatchingAnyPrefix+".");
if (totalFilesNumber == totalFilesMatchingAnyPrefix) {
System.out.println("Safe to skip tests? ==> YES");
if(githubOutput != null) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(githubOutput, true)))) {
out.println("skip_tests=yes");
}
}
System.exit(0);
}
else {
System.out.println("Safe to skip tests? ==> NO");
if(githubOutput != null) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(githubOutput, true)))) {
out.println("skip_tests=no");
}
}
System.exit(0);
}
}
else {
throw new TestPilotException(SKIP_TESTING_REST_ENDPOINT_ISSUE,
new IllegalStateException("HTTP/S status code: " + response.statusCode()));
}
}
}
catch (URISyntaxException e) {
throw new TestPilotException(SKIP_TESTING_WRONG_URI, e);
}
catch (IOException | InterruptedException e) {
throw new TestPilotException(SKIP_TESTING_WRONG_REST_CALL, e);
}
}
}