1331 Commits

Author SHA1 Message Date
Christopher McCarthy
cfec1fdd7e Merged PR 479: merged 3.1.0 into main for git history alignment
merged 3.1.0 into main for git history alignment

Related work items: #1847, #2502, #2610, #2618, #2628, #2646, #2658, #2659, #2660, #2661, #2682
2024-07-22 13:33:10 +00:00
Christopher McCarthy
2b93941a6b Merged PR 478: merged 3.0.0 into main for git history alignment
merged 3.0.0 into main for git history alignment

Related work items: #2457, #2472, #2536, #2552, #2560, #2561, #2563, #2570, #2588, #2606, #2626, #2628, #2637, #2639
2024-07-22 13:24:33 +00:00
Chris McCarthy
9dd1d6b742 merged 3.0.0 into 3.1.0 for git history alignment [skip ci] 2024-07-22 13:50:29 +01:00
Defence Science and Technology Laboratory UK
3f7d6c6ba6 Automated benchmark output commit for version 3.1.0 [skip ci] 2024-07-20 18:36:58 +00:00
Chris McCarthy
fba85cebfd retrospectively benchmarked 3.1.0 using the new benchmark process 2024-07-20 17:15:53 +01:00
Defence Science and Technology Laboratory UK
7f9acc4329 Automated benchmark output commit for version 3.0.0 [skip ci] 2024-07-20 16:11:46 +00:00
Chris McCarthy
213e301e58 retrospectively benchmarked 3.0.0 using the new benchmark process 2024-07-20 15:05:56 +01:00
Marek Wolan
e915d5e090 Updated VERSION 2024-06-25 10:44:15 +00:00
Marek Wolan
9b195ea0f4 Merged PR 431: #2682 Backport changes to core PrimAITE
Related work items: #2682
2024-06-25 10:32:10 +00:00
Marek Wolan
a861ccb1ee Fix typo in log message 2024-06-25 10:31:28 +00:00
Marek Wolan
28dabad66b #2682 Backport changes to core PrimAITE 2024-06-25 11:04:52 +01:00
Marek Wolan
4a81dc3b2c Merged PR 424: fix infini-ARP bug when pinging broadcast/network address
Related work items: #2661
2024-06-19 11:09:52 +00:00
Chris McCarthy
636ec0cdd4 #26661 - Added tests for testing arp doesn't work but also doesn't crash the network if attempting to resolve a broadcast or network address 2024-06-19 11:31:13 +01:00
Marek Wolan
7375bb383a #2661 Improve style on ARP check code to be more concise 2024-06-18 10:09:06 +01:00
Marek Wolan
c90c059411 fix infini-ARP bug when pinging broadcast/network address 2024-06-14 14:48:28 +00:00
Charlie Crane
923d2629ca Merged PR 418: Update Pre-Commit to check for valid copyright
## Summary
Updates Pre-commit with the a check to ensure valid copyright headers

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2646
2024-06-13 18:54:48 +00:00
Czar Echavez
4ac352bf3b Merged PR 419: integrate NIC traffic into observation space
## Summary
- Integrates the NIC traffic into the observation space
- Added `monitored_traffic` property into agent config which specifies which traffic is going to be included in observation

## Test process
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/419?_a=files&path=/tests/integration_tests/game_layer/observations/test_nic_observations.py

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2658
2024-06-13 17:53:43 +00:00
Czar Echavez
101fa3ebdb #2658: change key of observation to match what is in CAOS document 2024-06-13 16:29:02 +01:00
Marek Wolan
823e7d81a6 Merged PR 385: #2502 add more info about config placeholders
## Summary
Add to the config placeholder notebook. Now we also explain how to vary the simulation between episodes.

## Test process
precommit pass. notebook runs.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2502 add more info about config placeholders

Related work items: #2502
2024-06-13 15:19:31 +00:00
Czar Echavez
65d9cfa7dc #2658: I cast uncast on NIC space 2024-06-13 15:11:34 +01:00
Charlie Crane
d095138ef7 Merged PR 413: One line change to try and resolve build docs pipeline failure
## Summary
The build-docs pipeline has been failing to run. This PR corrects it.

## Test process
Link to successfully running:
https://dev.azure.com/ma-dev-uk/PrimAITE/_build/results?buildId=4849&view=results

Previous failures can be seen in the pipeline history.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

One line change to try and resolve build docs pipeline failure

Related work items: #2659
2024-06-13 13:11:03 +00:00
Charlie Crane
3c8e1d1035 #2646 - Amending a merge conflict resolution in preparation for review 2024-06-13 13:25:29 +01:00
Marek Wolan
d22117a614 Merge remote-tracking branch 'origin/dev' into bugfix/fix_pipeline_bug 2024-06-13 12:53:33 +01:00
Marek Wolan
0bd52b1c15 Merge remote-tracking branch 'origin/dev' into feature/2502-placeholders-docs 2024-06-13 12:52:59 +01:00
Marek Wolan
fad8d936e6 Merge remote-tracking branch 'origin/dev' into feature/2646_Update-pre-commit-to-check-for-valid-copyright 2024-06-13 12:52:09 +01:00
Czar Echavez
1798674d39 #2658: fix space 2024-06-13 12:37:20 +01:00
Charlie Crane
6762fd805e #2646 - Adding back the dns client/server python that was deleted 2024-06-13 12:13:16 +01:00
Czar Echavez
539577ddc3 #2658: added monitored traffic into config + default obs space 2024-06-13 11:48:13 +01:00
Marek Wolan
ae2bbd3e00 Merged PR 416: Fix database client uninstall failing due to persistent connection
## Summary
Change the way db client uninstall happens.

Now if a client_connection disconnect fails, we just drop it anyway, not sure if this causes other issues so pls review this diligently, especially @<Charlie Crane> . in case there's a potential issue with not fully dropping connections.

## Test process
pytest is running very nicely

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Fix database client uninstall failing due to persistent connection
2024-06-13 10:23:24 +00:00
Marek Wolan
c070bcc253 Fix database client uninstall failing due to persistent connection 2024-06-13 10:33:59 +01:00
Charlie Crane
0dce49484d Pip install command doesn't work.Trying a different fix 2024-06-12 08:36:42 +01:00
Charlie Crane
eeca9e4555 One line change to try and resolve build docs pipeline failure 2024-06-12 08:20:12 +01:00
Czar Echavez
969daeb490 Merged PR 412: NMAP application
## Summary
NMAP application added which will be utilised by red agents

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1847, #2618, #2628
2024-06-11 16:19:44 +00:00
Czar Echavez
bbcde47fa5 #1847: fix test 2024-06-11 16:43:38 +01:00
Czar Echavez
76e954d1a1 Merge remote-tracking branch 'origin/dev' into feature/1847-more-red-agents 2024-06-11 14:26:11 +01:00
Marek Wolan
da7d93a892 Merged PR 411: merge 3.0.0 into dev :) 2024-06-11 13:22:27 +00:00
Marek Wolan
935b6bd343 Merge remote-tracking branch 'origin/release/3.0.0' into merge-3.0.0-to-dev 2024-06-11 11:55:01 +01:00
Archer Bowen
3eacad200e Merged PR 408: User Guide & Notebook changes to align with 3.0.0+internal
## Summary

They are a few changes made in 3.0.0-internal that cannot be synced up.
For example, some of the RLIB Notebooks were changed around to use uc6 or tap003 which don't exist in 3.0.0:
![image (2).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/408/attachments/image%20%282%29.png)

Additionally, as my python env is different to that of the pipeline there is some meta-data differences such as:
![image.png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/408/attachments/image.png)

Which I'm pretty certain will sort it self out after the pipeline is finished.
2024-06-10 14:47:47 +00:00
Marek Wolan
d1bbab71b7 Updated session_output_writer.py 2024-06-10 14:46:06 +00:00
Marek Wolan
2d54d482a0 Updated session_output_reader.py 2024-06-10 14:45:56 +00:00
Marek Wolan
c538aee022 Rename benchmark variables and add h1 to notebooks 2024-06-10 12:58:07 +01:00
Chris McCarthy
05a6a4f7bd added manual benchmark pdf report and graphs 2024-06-10 11:12:41 +01:00
Archer.Bowen
2a6a16b222 Space inbetween title to prevent merge conflicts. 2024-06-10 10:50:58 +01:00
Archer.Bowen
af0e67a61a User-Guide update: Very minor changes to notebook code cells to match release version identically. 2024-06-10 10:41:05 +01:00
Archer.Bowen
1ad3adbec2 Merge remote-tracking branch 'origin/release/3.0.0' into user-guide-feedback-core-fixes 2024-06-10 09:54:02 +01:00
Chris McCarthy
4068231547 Refactored the benchmarking process 2024-06-07 19:59:55 +01:00
Archer.Bowen
ae242694f3 Minor change to title to prevent merge conflicts. 2024-06-07 17:13:21 +01:00
Archer.Bowen
146afea44f Updated copyright clause on .rst 2024-06-07 16:44:33 +01:00
Archer.Bowen
2954ca966f Updated core user guide to match exactly that of 3.0.0/internal. 2024-06-07 16:35:33 +01:00
Archer.Bowen
29d42a88dc Core user guide updated to reflect changes made down stream. 2024-06-07 14:48:22 +01:00
Czar Echavez
578d790c87 Merged PR 401: 2628 update benchmark script
## Summary
Updated the benchmark script so that it's compatible with PrimAITE v3.0.0

Chris also ran the benchmark and included the results

the script should also now work via cli (`python ./benchmark/primaite_benchmark.py`)

## Test process
n/a

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2628
2024-06-06 18:46:50 +00:00
Christopher McCarthy
477d7fe58e Merged PR 388: #2618 - NMAP
## Summary
Added NMAP application, documentation, and tests.

## Test process
*Multiple tests for ping and port scan. Predefined expected results against actual results.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [X] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2618 - Added NMAP application, documentation, and tests.

Related work items: #2618
2024-06-06 13:44:59 +00:00
Chris McCarthy
85325361b3 #2618 - Fixed the error that had NIC traffic describe state with enums as keys in the dict 2024-06-06 14:13:26 +01:00
Czar Echavez
6f655631e3 Merged PR 404: #2610: removed tap logic from ransomware script
## Summary
Removed irrelevant stages from the ransomware script application

## Test process
no big changes, so existing tests were used. only a minor change in test, which no longer applies

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2610: removed tap logic from ransomware script

Related work items: #2610
2024-06-06 11:32:18 +00:00
Czar Echavez
3d63c30b75 #2610: remove irrelevant params in doc 2024-06-06 11:45:17 +01:00
Czar Echavez
e1ba0ff125 #2610: apply suggestions from PR 2024-06-06 01:46:42 +01:00
Chris McCarthy
86092604e2 #2628 - ran the primaite v3 benchmarking script 2024-06-05 19:39:39 +01:00
Christopher McCarthy
e55f52742d Apply suggestions from code review 2024-06-05 15:25:24 +00:00
Christopher McCarthy
ace67894b2 Apply suggestions from code review 2024-06-05 14:57:00 +00:00
Czar Echavez
dbc30fc296 #2628: commit 2024-06-05 11:03:39 +01:00
Chris McCarthy
81bcf99855 #2646 - Added a custom pre-commit hook that ensure the copyright clause is added to .py and .rst files. 2024-06-05 09:11:37 +01:00
Chris McCarthy
3c17ef0a69 #2628 - added _can_perform_network_action to nmap.py. made some changes following PR suggestions. 2024-06-04 22:29:00 +01:00
Czar Echavez
5c23276be5 #2610: removed tap logic from ransomware script 2024-06-04 13:17:26 +01:00
Archer.Bowen
71e0c4179e Merge branch 'user-guide-feedback-core-fixes' of https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE into user-guide-feedback-core-fixes 2024-06-03 15:51:55 +01:00
Archer.Bowen
18e6886381 User guide updates 2024-06-03 15:51:14 +01:00
Czar Echavez
3bad9aa51e #2628: committing to be reviewed 2024-06-01 13:23:27 +01:00
Czar Echavez
472040aa70 Merge remote-tracking branch 'origin/dev' into feature/2628-update-benchmarking-script-branched 2024-06-01 00:20:21 +01:00
Archer Bowen
c705a15d00 Merged PR 397: User Guide Feed Back Core Changes
Further changes to be made post sync.
2024-05-31 17:55:27 +00:00
Marek Wolan
2406579c78 format using precommit 2024-05-31 18:50:56 +01:00
Archer.Bowen
9f0c6ddbb4 Fix primaite dependencies formatting issue 2024-05-31 18:18:40 +01:00
Archer.Bowen
4a9b92eab1 Removing data-manp notebook outputs 2024-05-31 17:17:07 +01:00
Archer.Bowen
93a729029c Merge remote-tracking branch 'origin/dev' into user-guide-feedback-core-fixes 2024-05-31 17:13:27 +01:00
Archer.Bowen
0ac57147cd Updated index following new primAITE 2 Pager 2024-05-31 17:05:30 +01:00
Marek Wolan
262390b74d Merged PR 396: Merge fixes for bugs found during testing and updates to docs
- Merge branch 'feature/2588-minimal-deps' into bugfix/2626-too-many-open-files
- #2626 fix too many open files bug
- Merge remote-tracking branch 'origin/dev' into bugfix/reward-logging
- fix reward logging
- Merge remote-tracking branch 'origin/dev' into bugfix/reward-logging
- get ray to stop crashing
- Merged PR 394: Fix 'too many open files'
- Merged PR 395: Fix reward logging and get ray to stop complaining
- Fix firewall diagram

Related work items: #2588, #2626
2024-05-31 15:47:41 +00:00
Marek Wolan
f9cff42856 glossary fact check 2024-05-31 16:03:47 +01:00
Marek Wolan
97d4c38298 remove tests from api docs 2024-05-31 15:56:27 +01:00
Chris McCarthy
4d61e857df dropped the automatic creation of primaite-dependencies.rst and made it manual as we now only need immediate dependencies 2024-05-31 15:42:41 +01:00
Marek Wolan
4ee29d129d Fix firewall diagram 2024-05-31 15:41:40 +01:00
Marek Wolan
53f01ca1e1 Merged PR 395: Fix reward logging and get ray to stop complaining
## Summary
Change the agent history log to also spit out rewards correctly.
Make ray adhere to new ray API

## Test process
Unit test pass
All notebooks run without crash

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code
2024-05-31 14:38:05 +00:00
Marek Wolan
f7cb5bd370 Merged PR 394: Fix 'too many open files'
## Summary
Add a method to PCAP to clear file handlers. Invoke this method while resetting environment.

## Test process
no longer crashes on windows when i run too many episodes

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [n] written **tests** for any new functionality added with this PR
- [n] updated the **documentation** if this PR changes or adds functionality
- [n] written/updated **design docs** if this PR implements new functionality
- [n] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2588, #2626
2024-05-31 14:31:25 +00:00
Marek Wolan
e48b71ea1a get ray to stop crashing 2024-05-31 15:25:08 +01:00
Czar Echavez
5f02846879 #2628: commit changes to combined av per episode 2024-05-31 15:20:10 +01:00
Marek Wolan
46ef3b8041 Merge remote-tracking branch 'origin/dev' into bugfix/reward-logging 2024-05-31 15:00:25 +01:00
Marek Wolan
c5f131ece5 fix reward logging 2024-05-31 15:00:18 +01:00
Marek Wolan
acfe49fd9f Merged PR 389: #2588 optional RL deps
## Summary
Make it optional to install ray, sb3, and their dependencies.

## Test process
pytest and notebooks

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2588 optional RL deps

Related work items: #2588
2024-05-31 13:17:27 +00:00
Archer.Bowen
71190a41c2 Fix to red agent image not loading 2024-05-31 14:10:01 +01:00
Marek Wolan
04dc486708 Merge remote-tracking branch 'origin/dev' into bugfix/reward-logging 2024-05-31 14:01:34 +01:00
Archer.Bowen
efc4e3e9b0 Core User Guide Feeedback Implemented.
Feedback Issues left:

1.Issues with red-agent image not embeded correctly in data_manipulation_e2e notebook

2._autosummary/tests.unit_tests.html is still completely blank.

3. _index.html is not updated with new 2-pager

4. _dependencies is not updated to just include tier-1 and primary for v3.

5. definiton of user_app_home is not confirmed
2024-05-31 13:55:20 +01:00
Chris McCarthy
5eea5bf4f9 #2618 - Integrated the NMAP into the action and requests functionality to enable agent usage. added NMAP agents tests. 2024-05-31 13:53:18 +01:00
Czar Echavez
add8cc0ab1 #2628: temp commit 2024-05-31 13:47:02 +01:00
Marek Wolan
10ff2e008e Merge remote-tracking branch 'origin/dev' into feature/2588-minimal-deps 2024-05-31 13:31:22 +01:00
Marek Wolan
f8336d07bd #2626 fix too many open files bug 2024-05-31 13:28:56 +01:00
Marek Wolan
a96cd0064d Merged PR 393: drop python 3.8 builds 2024-05-31 12:00:53 +00:00
Marek Wolan
ac9184b7d8 Merge branch 'feature/2588-minimal-deps' into bugfix/2626-too-many-open-files 2024-05-31 12:42:52 +01:00
Marek Wolan
ae8b726beb drop python 3.8 builds 2024-05-31 11:27:27 +00:00
Marek Wolan
1c86948d61 #2588 fix import in notebook 2024-05-31 12:12:35 +01:00
Marek Wolan
c7b2ed7f86 Merge branch 'dev' into feature/2588-minimal-deps 2024-05-31 12:11:16 +01:00
Marek Wolan
a5cd902175 Merged PR 390: Updated pyproject.toml
ADD deepdiff to dependency list

Related work items: #2637
2024-05-31 10:30:47 +00:00
Marek Wolan
4c9b2334da Merged PR 391: #2639 Fix reset signature
I don't want to write a description for this.

Related work items: #2639
2024-05-31 09:01:16 +00:00
Czar Echavez
40b4c9dac3 Merged PR 384: #2563: notebook explaining how to get simulation information from PrimAITE
## Summary
*Replace this text with an explanation of what the changes are and how you implemented them. Can this impact any other parts of the codebase that we should keep in mind?*

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2563: notebook explaining how to get simulation information from PrimAITE

Related work items: #2563
2024-05-30 15:10:04 +00:00
Marek Wolan
a161a3a5ec #2639 Fix reset signature 2024-05-30 15:34:46 +01:00
Marek Wolan
d2f82a1535 Updated pyproject.toml 2024-05-30 12:31:35 +00:00
Marek Wolan
0c19546322 #2588 optional RL deps 2024-05-29 14:54:45 +01:00
Chris McCarthy
9c4d47b0b9 #2618 - Fixed up some formatting in the nmap.rst documentation 2024-05-29 13:29:08 +01:00
Chris McCarthy
716f3ece1e #2618 - Added NMAP application, documentation, and tests. 2024-05-29 13:13:42 +01:00
Czar Echavez
d62ce7f86b #2563: apply PR suggestions 2024-05-29 12:01:14 +01:00
Marek Wolan
4d1f84dc27 #2502 add more info about config placeholders 2024-05-28 15:45:26 +01:00
Czar Echavez
69aa12f49b #2563: notebook explaining how to get simulation information from PrimAITE 2024-05-23 17:12:48 +01:00
Charlie Crane
85f03570f7 Merged PR 376: 2457 - Remove Hardcoding from Links
## Summary
This PR removes the hardcoding of Link bandwidth, and makes it possible to be configured via the network yaml definitions.
Link bandwidth will still default to 100 if this is not present, to prevent breaking all previous defined networks.

## Test process
All tests continue to pass.
`basic_network_config.yaml` now provides a non-default link bandwidth which is confirmed within unit tests.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2457
2024-05-22 11:35:48 +00:00
Charlie Crane
a676982dc5 Apply suggestions from code review 2024-05-22 10:50:59 +00:00
Charlie Crane
20d7f589d7 #2457 - Removing the ci-pipeline changes. These were explorative to entertain a possible fix to some flaky pipeline behaviour 2024-05-22 09:17:48 +01:00
Charlie Crane
417c02eaaa Merged PR 379: #2560 - Network_simulator_demo.ipynb cell fixes
## Summary
Some minor changes to the network_simulator_demo jupyter notebook so that all cells run.
I've updated the notebook to use a **very lightly** modified version of the ARCD UC2 network that it has been using.
_I've added a single route into the router_1 route table so that `network.get_node_by_hostname("router_1").route_table.show()` returns something visible. I didn't want to have this within the 'normal' uc2 network. Don't @ me._

![image.png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/379/attachments/image.png)

Corrected a path typo in `basic_lan_network_example()` so it correctly loads that network config.

## Test process
I've not broken any existing tests, and the notebook now runs with fully populated cells.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [X] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2560
2024-05-21 16:11:12 +00:00
Czar Echavez
af71fe52be Merged PR 378: Add create file/folder and file access requests
## Summary
Added requests in file system that allows:
- file to be created
- folder to be created
- file to be "accessed"

## Test process
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/378?_a=files&path=/tests/integration_tests/test_simulation/test_request_response.py

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2606
2024-05-21 10:35:49 +00:00
Christopher McCarthy
be0cf10847 Merged PR 380: #2561 - Set the DatabaseServer service to automatically install the FTPClient
## Summary
- Set the DatabaseServer service to automatically install the upon install to enable backup. Added some defensive statements that gracefully handle backup/restore requests when FTPClient is not installed.

## Test process
Added test that installs `DatabaseServer` on a new node then checks for an installed `FTPClient`.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2561 - Set the DatabaseServer service to automatically install the  upon install to enable backup. Added some defensive statements that gracefully handle backup/restore requests when FTPClient is not

Related work items: #2561, #2570
2024-05-21 08:56:50 +00:00
Czar Echavez
b7b87996d8 #2606: add metadata to file access 2024-05-20 17:21:20 +01:00
Charlie Crane
a759a6f5c3 #2457 - Addressing review comments 2024-05-20 16:52:17 +01:00
Czar Echavez
582cdb1f9a Merged PR 372: Integrate executed notebooks into primaite docs
## Summary
Integrating the notebooks into the primaite sphinx socumentation

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2472
2024-05-20 15:46:27 +00:00
Chris McCarthy
3be72ab6be Merge remote-tracking branch 'devops/feature/2561_Training-fails-because-database-service-can't-access-ftp-client-on-own-node' into feature/2561_Training-fails-because-database-service-can't-access-ftp-client-on-own-node 2024-05-20 16:27:09 +01:00
Chris McCarthy
18c837ff0e #2561 - Fixed issue relating to no access to software manager from inside service during install 2024-05-20 16:16:19 +01:00
Charlie Crane
7584271ad0 #2560 - Addressing review comments 2024-05-20 15:24:21 +01:00
Czar Echavez
f45df780c9 #2606: correcting the access verb 2024-05-20 15:02:05 +01:00
Christopher McCarthy
2170f6bc90 Apply suggestions from code review 2024-05-20 12:51:06 +00:00
Czar Echavez
80b1988ab9 #2606: add agent actions + test 2024-05-20 13:10:21 +01:00
Chris McCarthy
7a404773ac #2561 - Ran pre-commit hook 2024-05-20 12:44:58 +01:00
Charlie Crane
e9f3cef805 #2560 - Removing a sys_log.show() call in create-simulation_demo notebook that was used for debugging. 2024-05-20 12:32:03 +01:00
Charlie Crane
103c7f8d39 #2560 - Addressing the sys_log bug that could occur when scripts run across two time intervals. Additional updates to network_simulator notebook so that sys_log works in production mode 2024-05-20 12:28:02 +01:00
Czar Echavez
406d4e889b #2606: pre-commit check 2024-05-17 17:05:14 +01:00
Czar Echavez
e98ae0bd09 #2606: altered so that the request is done in file system + also completing access request 2024-05-17 16:59:24 +01:00
Charlie Crane
dc8105e8d6 2560 - Some minor tweaks to network_simulator_demo.ipynb and networks.py after looking through some bugs. Sys_log should print 2024-05-17 16:55:41 +01:00
Czar Echavez
8e17151696 #2472: apply PR suggestions 2024-05-17 11:17:00 +01:00
Archer Bowen
13fcda7a26 #2606 - Added initial attempts and created for visibility 2024-05-17 09:28:03 +01:00
Czar Echavez
7530b5b7a6 #2472: prevent notebook outputs when building documentation 2024-05-16 15:36:40 +01:00
Czar Echavez
fb7571ceae #2472: apply PR suggestions + minor fixes to make the notebooks output beautifuller 2024-05-16 14:06:43 +01:00
Czar Echavez
82953b4b0a #2472: add install pandoc to docs build pipeline + fix RLlib running for a long time 2024-05-16 10:55:17 +01:00
Czar Echavez
cb90c63c18 Merge remote-tracking branch 'origin/dev' into feature/2472-add-executed-notebook-to-html-documentation 2024-05-16 09:12:03 +01:00
Czar Echavez
d2cf0f2d22 #2472: revert make.bat changes 2024-05-15 14:03:17 +01:00
Czar Echavez
f7de3e6425 #2472: clean up 2024-05-15 14:00:14 +01:00
Charlie Crane
c1f4cb050e #2457 - Retesting the use of --no-cache-dir to see if that prevents hash issue 2024-05-15 09:00:54 +01:00
Charlie Crane
dc0f46270f #2457 - Adding a line to build pipeline to purge pip cache. Seeing if this could resolve hash error seen on some pipeline failures 2024-05-14 14:50:06 +01:00
Charlie Crane
f66d9d5817 Merge branch 'dev' into feature/2457-Set_link_bandwidth_via_config 2024-05-14 14:44:20 +01:00
Charlie Crane
084f48c721 #2457 - Updating changelog and testing a minor change in pipeline config to see if it resolves package hash errors 2024-05-14 11:11:42 +01:00
Charlie Crane
74514e977d #2457 - Syncing changes made. Updates to documentation and tests 2024-05-14 11:05:37 +01:00
Christopher McCarthy
7367fc67cf Merged PR 373: 2536 - Removed 'real files' from FileSystem and FTP
## Summary
Removed 'real files' from FileSystem and FTP

## Test process
- Dropped any tests that contain 'real files'
- Ran remaining tests to check that everything still works

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

2536 - Removed 'real files' from FileSystem and FTP

Related work items: #2536
2024-05-14 08:05:56 +00:00
Czar Echavez
2774623fba #2472: switch to using nbsphinx + added readme steps to setup pandoc + revert changes 2024-05-14 07:36:29 +01:00
Charlie Crane
71684dc5f0 #2457 - Initial commit removing the hardcoding of bandwidth values within links. Now pull it from configuration files, defaulting to 100 if not implemented 2024-05-13 14:42:15 +01:00
Chris McCarthy
e2f061fde0 #2561 - Set the DatabaseServer service to automatically install the upon install to enable backup. Added some defensive statements that gracefully handle backup/restore requests when FTPClient is not installed. 2024-05-13 07:58:43 +01:00
Chris McCarthy
ebbdea517e 2536 - Removed 'real files' from FileSystem and FTP 2024-05-13 07:30:33 +01:00
Marek Wolan
22e4b04a21 Merged PR 370: Merge back release
bump version basically.

Related work items: #2552
2024-05-10 14:48:08 +00:00
Czar Echavez
795004be5b #2472: copy image assets + applying change to makefile 2024-05-09 14:16:29 +01:00
Czar Echavez
81c523dc67 #2472: integrating jupyter notebooks into documentation 2024-05-09 13:43:55 +01:00
Nick Todd
d80eb15fa2 #2560: Fix typos and punctuation. 2024-05-08 14:56:44 +01:00
Marek Wolan
c6b6753aeb Updated VERSION 2024-05-08 11:13:32 +00:00
Marek Wolan
d02b7744ae Merged PR 368: #2550 Backport changes into core
## Summary
Backport changes from sensitive into core.

Mainly the application install and a couple of test changes.

## Test process
pytest

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2550 Backport changes into core

Related work items: #2549, #2550
2024-05-08 08:38:44 +00:00
Marek Wolan
4d3c85bc14 #2550 Backport changes into core 2024-05-07 15:35:02 +01:00
Charlie Crane
75fd6b923a Merged PR 361: #2464 - v3b7 install errors when using Python 3.11
## Summary
This is a two line change to `README.md` to correct the Python versions listed as a pre-requisite for PrimAITE, contradicting what is in `pyproject.toml`
We do not currently support Python3.11, which the README suggests we do.

## Test process
Not Applicable - Although I have installed v3b7 using Python3.11 as part of the bugfix investigation on a blank Ubuntu VM, and the install looks to of ran smoothly.
`Data-Manipulation-E2E-Demonstration` & `Training-an-SB3-Agent` both ran fine.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [X] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

#2464 - Correcting Python versioning pre-req range on README.md as we do not currently support Python3.11

Related work items: #2464
2024-05-07 13:23:35 +00:00
Nick Todd
bfb8fbd1bf Merged PR 365: Run SB3 training in SubprocVecEnv
## Summary
Demonstration notebook show how to use SB3 SubprocVecEnv to vectorise environments to speed up training.
## Test process
Successfully run notebook on Windows and Linux.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2442
2024-05-03 16:02:34 +00:00
Nick Todd
e510c3ceff #2442: Removed 'primaite setup' call 2024-05-03 15:10:24 +01:00
Marek Wolan
727a05f291 Merged PR 363: Make ftp client only default on computers, not servers
## Summary
REMOVE ftp client from host node default software and add it to computer default software, effectively removing it from servers.

Ensure tests are using the uc2 yaml file instead of outdated network generator function.

Fix some tests to make sure it all passing

## Test process
I have tested it.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Make ftp client only default on computers, not servers

Related work items: #2546
2024-05-03 12:40:17 +00:00
Marek Wolan
535e064af5 unflake test 2024-05-03 11:05:33 +01:00
Marek Wolan
4f38184959 remove redundant comment 2024-05-03 09:08:26 +01:00
Charlie Crane
4cd15a39aa #2457 - Commit before switching branches to review 2024-05-03 08:35:24 +01:00
Nick Todd
689400e95c Merge branch 'dev' into bugfix/2442-add_SubprocVecEnv_support 2024-05-02 17:04:43 +01:00
Marek Wolan
4a02d1d8e5 Readd import statement 2024-05-02 17:00:29 +01:00
Nick Todd
3c5e107f81 Merge branch 'dev' into bugfix/2442-add_SubprocVecEnv_support 2024-05-02 16:59:08 +01:00
Nick Todd
5a3b6ade2f #2442: Updated changelog. 2024-05-02 16:52:35 +01:00
Marek Wolan
6ef6a5cd18 Merge remote-tracking branch 'origin/dev' into feature/remove-ftp-client-default-app 2024-05-02 16:52:24 +01:00
Nick Todd
7c689a0d35 #2442: Markdown changes. 2024-05-02 16:32:54 +01:00
Nick Todd
a37ed4e487 #2442: Fix config file path to be OS independent. 2024-05-02 16:16:36 +01:00
Marek Wolan
b9b922e776 Make ftp client only default on computers, not servers 2024-05-02 15:51:06 +01:00
Nick Todd
2774442561 Merge branch 'bugfix/2442-add_SubprocVecEnv_support' of ssh.dev.azure.com:v3/ma-dev-uk/PrimAITE/PrimAITE into bugfix/2442-add_SubprocVecEnv_support 2024-05-02 15:48:30 +01:00
Nick Todd
db29d33629 #2442: Add multi-processing notebook example. 2024-05-02 15:44:18 +01:00
Czar Echavez
a5794e5df1 Merged PR 359: Improved Dev CLI tools
## Summary
Improved dev tools:
- can configure what the dev mode can override
  - sys log level
  - outputting sys log
  - outputting pcap logs
  - outputting to terminal
  - the location where to output session (by default will print to the primaite repo root)

## Test process
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/359?_a=files&path=/tests/integration_tests/cli/test_dev_cli.py

and a lot of manually checking if the thing outputs to the correct directories

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2447, #2533
2024-05-02 13:37:16 +00:00
Czar Echavez
e599e03c10 #2533: cleaner output text for dev-mode show + consistent colors 2024-05-02 12:21:24 +01:00
Charlie Crane
5cfa9c7fa2 #2464 - Version typo in README.md 2024-05-02 08:54:37 +01:00
Charlie Crane
ec582c0002 #2464 - Reverting flake8 change 2024-05-01 17:08:08 +01:00
Charlie Crane
d25a8aa0ef #2464 - Reverting changes from Python3.12 investigations, updating README and prproject.toml so that python 3.11 is allowed 2024-05-01 17:06:58 +01:00
Czar Echavez
ec6d2bf640 #2533: fix missing implementation of output_dir override in io.py + moving the dev mode override in SIM_OUTPUT to prevent the override from being overridden 2024-05-01 16:53:37 +01:00
Charlie Crane
0fd85722ae #2464 I missed a linting error 2024-05-01 16:37:16 +01:00
Czar Echavez
952f6ee225 #2533: fix is_dev_mode for missing or outdated configs 2024-05-01 16:23:44 +01:00
Charlie Crane
a2482dc744 #2464 - Forgot to save and add a file that would cause flake8 failure 2024-05-01 16:22:26 +01:00
Charlie Crane
c2cc5228ae #2464 - Linting changes to see if the python 3.12 pipeline will pass 2024-05-01 16:20:01 +01:00
Czar Echavez
25807653f4 Merge remote-tracking branch 'origin/dev' into feature/2533-improve-dev-tools-in-primaite-cli 2024-05-01 16:11:52 +01:00
Czar Echavez
d7572dc18b #2533: changelog 2024-05-01 16:10:27 +01:00
Czar Echavez
61e7a4e439 #2533: documentation on use of dev-mode 2024-05-01 16:04:18 +01:00
Charlie Crane
57cff8d4e3 #2464 - Seeing if python 3.12 will also run... 2024-05-01 16:01:08 +01:00
Czar Echavez
5516fbc6fc #2533: output directory for sessions 2024-05-01 14:48:10 +01:00
Charlie Crane
392b83fc64 #2464 - Correcting use of spaces in pipeline job names 2024-05-01 14:34:38 +01:00
Charlie Crane
efdc979495 #2464 Changing pyproject.toml to allow the use of python 3.11 and tweaking the pipeline to use python 3.11. Seeing what happens... 2024-05-01 14:33:38 +01:00
Czar Echavez
b6b5ce91c2 #2533: clean up temp items in tests + fixing the CLI tests 2024-05-01 14:33:33 +01:00
Czar Echavez
a2fb04e6f6 #2533: set default dev output path + clean up 2024-05-01 14:02:40 +01:00
Charlie Crane
8d9ffab514 #2464 - Correcting Python versioning pre-req range on README.md as we do not currently support Python3.11 2024-05-01 12:04:11 +01:00
Nick Todd
831f80f617 Merge branch 'bugfix/2442-add_SubprocVecEnv_support' of ssh.dev.azure.com:v3/ma-dev-uk/PrimAITE/PrimAITE into bugfix/2442-add_SubprocVecEnv_support 2024-05-01 11:22:08 +01:00
Nick Todd
b7fa826d95 #2442: Initial commit of MP test script 2024-05-01 11:16:45 +01:00
Christopher McCarthy
4763344835 Merged PR 358: #2519 - refactored all air-space usage to that a new instance of AirSpace is...
## Summary
- Refactored all air-space usage to that a new instance of `AirSpace` is created for each instance of Network. This 1:1 relationship between network and airspace will allow parallelization.

## Test process
- Original test remains the same. TDD, init.
- Added additional `WirelessRouter` test that tests wireless connectivity from config file too.
``` text
C:\Users\ChristopherMcCarthy\source\azure_devops\ma-dev-uk\PrimAITE\venv\Scripts\python.exe "C:/Program Files/JetBrains/PyCharm 2023.3.5/plugins/python/helpers/pycharm/_jb_pytest_runner.py" --path C:\Users\ChristopherMcCarthy\source\azure_devops\ma-dev-uk\PrimAITE\tests\integration_tests\network\test_wireless_router.py
Testing started at 15:33 ...
Launching pytest with arguments C:\Users\ChristopherMcCarthy\source\azure_devops\ma-dev-uk\PrimAITE\tests\integration_tests\network\test_wireless_router.py --no-header --no-summary -q in C:\Users\ChristopherMcCarthy\source\azure_devops\ma-dev-uk\PrimAITE\tests\integration_tests\network

============================= test session starts =============================
collecting ... collected 2 items

test_wireless_router.py::test_cross_wireless_wan_connectivity
test_wireless_router.py::test_cross_wireless_wan_connectivity_from_yaml

======================== 2 passed, 1 warning in 0.14s =========================
+----------------+-------------------+-------------+---------------+--------------+---------+
| Connected Node |    MAC Address    |  IP Address |  Subnet Mask  |  Frequency   |  Status |
+----------------+-------------------+-------------+---------------+--------------+---------+
|    router_1    | da:9a:08:17:80:a4 | 192.168.1.1 | 255.255.255.0 | WiFi 2.4 GHz | Enabled |
|    router_2    | 0d:67:76:5e:c2:fb | 192.168.1.2 | 255.255.255.0 | WiFi 2.4 GHz | Enabled |
+----------------+-------------------+-------------+---------------+--------------+---------+
PASSED     [ 50%]+----------------+-------------------+-------------+---------------+--------------+---------+
| Connected Node |    MAC Address    |  IP Address |  Subnet Mask  |  Frequency   |  Status |
+----------------+-------------------+-------------+---------------+--------------+---------+
|    router_1    | 1a:46:f6:cb:8c:15 | 192.168.1.1 | 255.255.255.0 | WiFi 2.4 GHz | Enabled |
|    router_2    | 7a:9f:d8:2b:4b:90 | 192.168.1.2 | 255.255.255.0 | WiFi 2.4 GHz | Enabled |
+----------------+-------------------+-------------+---------------+--------------+---------+
PASSED [100%]
Process finished with exit code 0
```

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] atte...
2024-05-01 10:12:28 +00:00
Chris McCarthy
7552872430 #2519 - Fixed the broked multi-lan network topology diagrams while I was in doing a PR too 2024-05-01 10:28:54 +01:00
Chris McCarthy
d72622f3f7 Merge branch 'dev' into feature/2519_Make-airspace-an-attribute-of-Simulation
# Conflicts:
#	CHANGELOG.md
2024-05-01 10:22:44 +01:00
Czar Echavez
95643d3255 #2533: optimise so we are not reading from file all the time 2024-04-30 19:36:22 +01:00
Czar Echavez
729f9c5064 #2533: fix primaite config recreated when running setup 2024-04-30 19:15:54 +01:00
Czar Echavez
73f64cd89c Merge remote-tracking branch 'origin/dev' into feature/2533-improve-dev-tools-in-primaite-cli 2024-04-30 18:27:05 +01:00
Charlie Crane
13cabf8e21 Merged PR 360: 2523 - Logging Rewards updates.
## Summary
This PR updates `PrimaiteGymEnv` and `PrimaiteRayMARLEnv` within `environment.py` to log reward values per step and per episode.
Corrects an import statement within `io.py` - removing the use of `src`.
Fixes an error within notebooks that saw them failing following a rename of `game_config` to `env_config`.

## Test process
 - Tests all continue to pass, and notebooks now run without error. This PR does not change any functionality, just adds some logging.
 - Searched for the catch-22 that would trip me up as part of this ticket. A 3 line change felt like too simple an implementation...

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2523
2024-04-30 17:13:50 +00:00
Charlie Crane
9c89fe4143 #2523 - Typo corrections within notebooks that stopped them from running 2024-04-30 16:14:34 +01:00
Chris McCarthy
04eb33e28a #2519 - Dropped failed unit test in test_wireless_router.py as it didn't actually test any functionality and simply just tested the config parser, which we now do in the integration test. 2024-04-30 16:07:38 +01:00
Charlie Crane
bb99e46651 #2523 - Updating CHANGELOG.md 2024-04-30 16:03:31 +01:00
Czar Echavez
ab3d23785d #2533: precommit 2024-04-30 15:50:53 +01:00
Chris McCarthy
bc573dfed0 #2519 - refactored all air-space usage to that a new instance of AirSpace is created for each instance of Network. This 1:1 relationship between network and airspace will allow parallelization. Added additional WirelessRouter test that tests wireless connectivity from config file too. 2024-04-30 15:46:16 +01:00
Czar Echavez
59990813f5 #2533: added tests + log level for output 2024-04-30 15:43:25 +01:00
Charlie Crane
9b3699389a #2523 - Adding in some additional logging for other agent classes. This currently prints total_reward instead of average reward 2024-04-30 15:36:59 +01:00
Christopher McCarthy
a82ee2b8e1 Merged PR 354: Network focussed dev config documentation
## Summary
Built three networks, one is the minimal network, one is a basic LAN, and another is a nice beefy multi-LAN setup with ISP and DNS along with applications, services. Documented the process when building the config files. Included the config files as example configs for use.

## Test process
Tested the shit out of the big multi-lan network.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2266
2024-04-30 13:53:28 +00:00
Charlie Crane
b8c46a92e9 #2523 - Minor typos/corrections to make things run locally. Added one logging line to record Blue agent reward per step in environment.py 2024-04-30 14:16:29 +01:00
Chris McCarthy
a141c8d212 #2266 - fixed typos from PR suggestions 2024-04-30 14:08:12 +01:00
Nick Todd
137f2a9648 Merged PR 306: Fix issues with check_hash function.
## Summary
The current implementation of check_hash() as triggered by NODE_FILE_CHECKHASH and NODE_FOLDER_CHECKHASH is incorrect. However, a correct implementation is a future task so the code is disabled and a deprecation warning has been added.

## Test process
Disabled tests that exercise check_hash() functionality. Added tests to show that deprecation warning is present.

## Checklist
- [X ] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

2299: Remove calls to corrupt.

Related work items: #2299
2024-04-30 12:08:19 +00:00
Nick Todd
3d0ebe1aba #2299: Correct possible mis-merge. 2024-04-30 10:39:33 +01:00
Nick Todd
9906ba20ae Merge branch 'dev' into bugfix/2299-check_hash_function_corrupts_files_and_folders 2024-04-30 09:17:40 +01:00
Marek Wolan
8a97d197b9 Merged PR 355: Document request success
## Summary
Add a doc page and a notebook to go over the request manager.

## Test process
Notebook runs.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [na] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [x] written/updated **design docs** if this PR implements new functionality
- [na] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2514
2024-04-29 17:36:29 +00:00
Czar Echavez
c94fa653f7 Merge remote-tracking branch 'origin/dev' into feature/2533-improve-dev-tools-in-primaite-cli 2024-04-29 16:24:19 +01:00
Nick Todd
5b03013e3f Merge branch 'dev' into bugfix/2299-check_hash_function_corrupts_files_and_folders 2024-04-29 15:44:06 +01:00
Nick Todd
e667223a98 #2299: Remove debug cell from notebook. 2024-04-29 15:34:23 +01:00
Nick Todd
e7db5c7f58 #2299: Review comments 2024-04-29 15:30:24 +01:00
Czar Echavez
a7492ba39f #2447: cli commands for dev mode 2024-04-29 13:45:10 +01:00
Marek Wolan
68d4751f73 Apply suggestions from code review 2024-04-29 11:56:40 +00:00
Marek Wolan
27d1cd460b #2514 Provide more friendly messages on validation failure 2024-04-29 11:13:32 +01:00
Marek Wolan
3c046b838b #2514 Document request response. 2024-04-29 11:11:51 +01:00
Nick Todd
75f404416c #2299: Update CHANGELOG.md 2024-04-29 10:30:47 +01:00
Marek Wolan
32a0542b73 Merged PR 353: Episode Schedule
## Summary
* Made It Possible™ to vary the layout and agents between episodes.
* Standardised the environments to all use `env_config` as the __init__ parameter name, previously PrimaiteGymEnv was using `game_config`
* Added a notebook that demonstrates how to use the variable episodes.

## Test process
Checked that existing pytests run. Added more tests. Checked that notebooks run.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2269, #2334, #2336, #2475, #2476
2024-04-29 09:08:37 +00:00
Chris McCarthy
81d4006240 #2266 - Finalised the tests and fleshed out the documentation more. 2024-04-26 23:18:09 +01:00
Marek Wolan
394e76048f Merge remote-tracking branch 'origin/dev' into feature/2476-training-schedules-mockup 2024-04-26 16:23:41 +01:00
Marek Wolan
30cc04411d #2476 apply pr comments 2024-04-26 16:23:02 +01:00
Chris McCarthy
0ccd53e907 Merge branch 'dev' into feature/2266_network-focussed-dev-documentation 2024-04-26 16:19:33 +01:00
Charlie Crane
5ee23dcb17 Merged PR 348: #2462 - Refactor of DatabaseClient and DatabaseServer
## Summary
Refactor of `DatabaseClient` and `DatabaseService` to update how connection IDs are generated. These are now provided by DatabaseService when establishing a connection.
Creation of `DatabaseClientConnection` class. This is used by `DatabaseClient` to hold a dictionary of active db connections.

## Test process
Tests have been updated to reflect the changes and all pass

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2462
2024-04-26 14:52:21 +00:00
Chris McCarthy
058ca3987f #2266 - Added more docs. Now need to test 2024-04-26 14:32:54 +01:00
Nick Todd
ec8b46f3bc #2299: Add tests to check for 'not implemented' warning message. 2024-04-25 17:56:55 +01:00
Nick Todd
0c375ebe4d #2299: Disable tests using CHECKHASH functionality 2024-04-25 17:08:03 +01:00
Nick Todd
0fa9fa32bc #2299: Add not implemented warning message. 2024-04-25 16:20:57 +01:00
Marek Wolan
be5cf0b877 Merge remote-tracking branch 'origin/dev' into feature/2476-training-schedules-mockup 2024-04-25 15:17:08 +01:00
Chris McCarthy
0fff7d2240 Merge branch 'dev' into feature/2266_network-focussed-dev-documentation 2024-04-25 15:16:28 +01:00
Marek Wolan
37945c0065 #2476 Remove temporary testing file 2024-04-25 15:16:20 +01:00
Chris McCarthy
c93c432bf1 #2266 - Added final complex network to the examples. Just need to finalise the building the config section 2024-04-25 15:14:40 +01:00
Czar Echavez
e1ac6255ad Merged PR 352: #2447: added mode to primaite cli + printing session to current working direc...
## Summary
- Added the mode command in PrimAITE CLI
- command allows users to switch between developer mode and production mode
- developer mode changes where the simulation_output is written
  - dev mode writes simulation output where the current working directory is

## Test process
CLI:
![primaite mode.gif](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/352/attachments/primaite%20mode.gif)

Running prod mode:
![primaite mode prod.gif](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/352/attachments/primaite%20mode%20prod.gif)

Running dev mode:
![primaite mode dev.gif](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/352/attachments/primaite%20mode%20dev.gif)

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2447: added mode to primaite cli + printing session to current working directory if in dev mode

Related work items: #2447
2024-04-25 14:13:55 +00:00
Marek Wolan
736408f8b4 Reference the episode schedule notebook in docs 2024-04-25 15:12:46 +01:00
Marek Wolan
66f31e8ed1 #2476 Add test for episode scheduler 2024-04-25 15:09:46 +01:00
Marek Wolan
42ce264e73 #2476 Fix string formatting 2024-04-25 13:54:05 +01:00
Czar Echavez
0fff29ef27 #2447: changelog + documentation 2024-04-25 13:50:41 +01:00
Marek Wolan
e3f9162a77 Merge remote-tracking branch 'origin/dev' into feature/2476-training-schedules-mockup 2024-04-25 13:50:11 +01:00
Czar Echavez
96b6fb81da #2447: added mode to primaite cli + printing session to current working directory if in dev mode 2024-04-25 13:32:57 +01:00
Marek Wolan
a92898d001 #2476 Finalise explanation notebook for episode schedule 2024-04-25 13:25:26 +01:00
Nick Todd
228a8099a3 #2299: Revert changes to disable check_hash() 2024-04-24 17:27:27 +01:00
Chris McCarthy
081ff0647f Merge branch 'dev' into feature/2266_network-focussed-dev-documentation
# Conflicts:
#	src/primaite/game/agent/observations/observations.py
2024-04-24 16:04:46 +01:00
Czar Echavez
f01c30864d Merged PR 347: Implementing log levels
## Summary
- Implementation of log levels
- log levels can be set via io_settings.log_level in the yaml config file

## Test process
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/347?_a=files&path=/tests/unit_tests/_primaite/_simulator/_system/core/test_sys_log.py

set up a test where the test checks the contents of the terminal so make sure that specific log level messages appear (or not) depending on the log level

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2470
2024-04-24 11:09:48 +00:00
Czar Echavez
d4aaeda4b6 #2470: update doc to reflect the default log level 2024-04-24 10:11:23 +01:00
Czar Echavez
23231e432e Merge remote-tracking branch 'origin/dev' into feature/2470-refactor-syslog-to-be-able-to-leverage-a-configured-log-level 2024-04-24 09:17:28 +01:00
Czar Echavez
16fc6f4fd0 Merge remote-tracking branch 'origin/dev' into feature/2470-refactor-syslog-to-be-able-to-leverage-a-configured-log-level 2024-04-23 16:54:03 +01:00
Czar Echavez
32cd7dba04 Merged PR 350: #2510: cleaning up logs and add logging handler clearing to prevent duplicate...
## Summary
- Cleaning up multiple logs that say the same thing
- Added Nick's suggestion to clear log handlers before adding a handler on SysLog initialisation

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2510: cleaning up logs and add logging handler clearing to prevent duplicate logs

Related work items: #2510
2024-04-23 15:53:58 +00:00
Czar Echavez
90343bd5ec #2470: apply PR suggestions 2024-04-23 16:52:53 +01:00
Nick Todd
3eea70f7d8 Merge branch 'dev' into bugfix/2299-check_hash_function_corrupts_files_and_folders 2024-04-23 16:40:02 +01:00
Christopher McCarthy
a60e8b2203 Merged PR 349: #2511 - Upgraded pydantic to version 2.7.0
## Summary
- Upgraded pydantic to version 2.7.0.
- Added ipywidgets to the dependencies (for #2300)

## Test process
N/A

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2511 - Upgraded pydantic to version 2.7.0. Added ipywidgets to the dependencies (for #2300)

Related work items: #2300, #2511
2024-04-23 13:43:44 +00:00
Marek Wolan
8e008b6d24 #2511 Appease isort pre commit hook 2024-04-23 13:54:56 +01:00
Czar Echavez
c13b7d7c81 #2510: cleaning up logs and add logging handler clearing to prevent duplicate logs 2024-04-23 11:54:34 +01:00
Marek Wolan
28c8b7c9d9 #2476 Get episode schedule working 2024-04-23 11:51:50 +01:00
Marek Wolan
1eca20157b Updated CHANGELOG.md 2024-04-23 09:04:49 +00:00
Marek Wolan
2b19c8c91d #2551 upgrade ray to >2.9 and resolve logging error in db client 2024-04-23 09:51:56 +01:00
Marek Wolan
2b3664ce36 #2476 Add proof of concept yaml combining notebook 2024-04-23 09:29:59 +01:00
Chris McCarthy
6060cbbc5b #2511 - Put the ray rlllib dep back to "ray[rllib] == 2.8.0, < 3" 2024-04-23 09:04:17 +01:00
Nick Todd
779a9587bc Merged PR 338: #2455: Fix typo in config file and notebook
## Summary
Fixed small typo in data_manipulation_marl.yaml. Correct database key in Data-Manipulation-Customising-Red-Agent notebook.

## Test process
Successfully re-ran all notebooks in src/primaite/notebooks on Windows and Linux (WSL).
Successfully re-ran all tests in primaite/tests.
Also checked that Ransomware-Kill-Chain-E2E and UC6-E2E-Demo ran correctly in PrimAITE Sensitive repo.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2455: Fix typo in config file and notebook

Related work items: #2455
2024-04-22 15:35:51 +00:00
Nick Todd
6726a2da37 #2245: Add comment 2024-04-22 14:09:12 +01:00
Chris McCarthy
a7dae6e373 #2511 - Upgraded pydantic to version 2.7.0. Added ipywidgets to the dependencies (for #2300) 2024-04-22 08:49:08 +01:00
Chris McCarthy
9a55b7b864 #2266 - Fixed some minor bugs that prevented basic networks without a default gateway from being parsed. Completed the basic client-server P2P network documentation, file and retrieval method. 2024-04-19 15:58:50 +01:00
Chris McCarthy
455c8cdcd5 Merge branch 'dev' into feature/2266_network-focussed-dev-documentation 2024-04-19 14:57:40 +01:00
Chris McCarthy
cbb8da61c8 #2266 - Finally started to add some user documentation around how to properly create networks 2024-04-19 14:56:56 +01:00
Czar Echavez
57e6f8bca7 #2470: update documentation 2024-04-19 11:55:38 +01:00
Nick Todd
873b70c2c9 Merge branch 'dev' into bugfix/2455-notebook_updates 2024-04-19 11:52:09 +01:00
Czar Echavez
b8d4a8cc8d #2470: changed default log level to warning + changed sys logging in code to be more aligned with severity of messages 2024-04-19 11:37:52 +01:00
Nick Todd
9334b1e79b #2455: Add NICObservation.ConfigSchema to NIC list. 2024-04-19 11:07:32 +01:00
Czar Echavez
833fd18936 #2470: add write_sys_log_to_terminal to documentation 2024-04-18 16:44:18 +01:00
Czar Echavez
cbea0fd595 #2470: fix documentation 2024-04-18 16:40:05 +01:00
Czar Echavez
34773ed225 #2470: implement PR suggestions 2024-04-18 16:38:42 +01:00
Czar Echavez
2a1203675d #2470: changelog + documentation 2024-04-18 15:57:02 +01:00
Czar Echavez
94ca13c0f9 #2470: add log level via config + test 2024-04-18 15:14:40 +01:00
Charlie Crane
56d03aaf7b Merged PR 339: #2453 - Example Notebooks Refactor
## Summary
Updates to `create-simulation_demo.ipynb` and `network_simulator_demo.ipynb` to reflect changes within repo.
 - Corrected import paths
 - Corrected typo in create-simulation_demo: my_swtich -> my_switch and switch.sys_log.show -> computer.sys_log.show()
 - Changes to ARP implementation within nodes. Now defined as a property within HostNode and NetworkNode, allowing router.arp.show() to work as intended within the notebook.

## Test process
 - Both notebooks now run without issue when ran.
 - All tests pass

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2453, #2477, #2478
2024-04-18 13:36:23 +00:00
Charlie Crane
abf94fc4bb #2453 - Committing additional explanations to notebook 2024-04-18 13:52:43 +01:00
Charlie Crane
bb88d43b90 #2453 - Updating with some explanation to improve the readability of the notebook 2024-04-18 13:50:47 +01:00
Charlie Crane
49be3b3639 #2453 - Updates to Training-an-SB3-agent.ipynb following review 2024-04-18 10:23:26 +01:00
Charlie Crane
d05ded0dc2 Merge branch 'dev' into bugfix/2453-Example_Notebooks_require_refactor 2024-04-18 09:30:12 +01:00
Czar Echavez
b57deaf9e1 #2470: implementing log levels into sys log 2024-04-17 18:13:00 +01:00
Charlie Crane
999044a444 2453 - removal of notebook metadata 2024-04-17 10:44:44 +01:00
Marek Wolan
137a203acc Merged PR 346: Deprecate PrimaiteSession
## Summary
A while ago we have added several notebooks to get users started training their own agents. These notebooks overlap in functionality with PrimAITE session but they are more suitable.

* removed primaite session
* removed any tests relying on primaite session (except some tests were converted into environment tests.
* removed any CLI commands that rely on `PrimaiteSession`
* Added deprecation warnings to any benchmarking code that will break now because they rely on the old Primaite 2 session. (I left the code in because when we update benchmarking to v3, this will be a useful starting point)
* added similar deprecation warnings to Session metadata writer, reader and transaction stuff, for the same reason.
* removed parts of the documentation that are no longer relevant (session, training config, policy)
* went through all existing yaml config files and removed training options (as they were for session only)

## Test process
Checked that existing pytests all pass, and updated some pytests to use environment instead of session.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2374
2024-04-17 08:25:43 +00:00
Nick Todd
796c0553a4 Merge branch 'dev' into bugfix/2455-notebook_updates 2024-04-17 09:15:29 +01:00
Charlie Crane
750cc98703 #2453 - Actioning review comments 2024-04-16 16:52:36 +01:00
Charlie Crane
dcfcfc0c54 #2453 - Merging in updates on dev branch 2024-04-16 16:51:29 +01:00
Nick Todd
4903c77f65 #2455: Add missing source_wildcard_id and dest_wildcard_id data. 2024-04-16 14:17:58 +01:00
Marek Wolan
db56eea4ce #2374 Update readme and minor fix to yaml 2024-04-16 13:20:07 +01:00
Marek Wolan
e12fd8f1a2 Merged PR 344: Bump version and reenable multi-platform builds
Yes

Related work items: #2471
2024-04-16 11:19:20 +00:00
Marek Wolan
7c0a7702c4 #2374 update changelog 2024-04-16 11:39:13 +01:00
Marek Wolan
9679b898fe Merge remote-tracking branch 'origin/dev' into feature/2471-bump-version 2024-04-16 11:28:30 +01:00
Marek Wolan
8d0d323e0b #2374 Remove primaite session 2024-04-16 11:26:17 +01:00
Nick Todd
8fac8be6c2 Merge branch 'dev' into bugfix/2455-notebook_updates 2024-04-16 11:03:48 +01:00
Christopher McCarthy
2410d5ab37 Merged PR 345: PrimAITE v3.0.0b8 release
Merge the PrimAITE v3.0.0b3 release back into dev

gitflow, init
2024-04-16 09:45:43 +00:00
Marek Wolan
2d444f71c9 Updated VERSION 2024-04-16 08:53:55 +00:00
Marek Wolan
f0ed9d2240 re-enable multi platform builds 2024-04-15 14:16:09 +01:00
Marek Wolan
b797662b1d bump version 2024-04-15 14:15:58 +01:00
Marek Wolan
72dd84886b Merged PR 343: #2459 back-sync b8 changes into core
Copy pasta job

Related work items: #2459
2024-04-15 12:56:26 +00:00
Marek Wolan
39ec55c7b6 #2459 strip notebook outputs to appease pre-commit 2024-04-15 13:12:51 +01:00
Marek Wolan
72283e6184 #2459 Align whitespace and typing 2024-04-15 12:40:50 +01:00
Marek Wolan
e876bb5d41 #2459 update doc page 2024-04-15 11:59:17 +01:00
Marek Wolan
0828f70b4c #2459 back-sync b8 changes into core 2024-04-15 11:50:08 +01:00
Charlie Crane
9496441169 #2453 - Ignore this commit. Removing saved output in Training-an-SB3-Agent Notebook 2024-04-09 15:19:45 +01:00
Charlie Crane
3245c7e81e #2453 - Renaming Server hostname in create-simulation_demo and removing saved output 2024-04-09 14:48:49 +01:00
Nick Todd
89de5a298d #2455: Fix typo in config file and notebook 2024-04-09 14:47:31 +01:00
Charlie Crane
265f25b442 #2453 - One final typo correction found in network_simulator_demo.ipynb. Correcting switch.sys_log.show() to computer.sys_log.show() in Computer/Server Nodes section 2024-04-09 14:15:51 +01:00
Charlie Crane
8e6689d881 #2453 - Corrected flake8 linting errors ahead of creating PR, after finally managing to get it to run locally. This should now be ready for review 2024-04-09 13:56:21 +01:00
Charlie Crane
d02b12d1e5 #2453 Addressing some flake8 corrections 2024-04-09 13:45:27 +01:00
Charlie Crane
c13d3f191f #2453 - Correcting errors found from pipeline pre-commit checks 2024-04-09 13:34:57 +01:00
Charlie Crane
f8432bf53b #2453 - Example Notebooks Require Refactor
- create_simulation_demo and network_simulator_demo notebooks have been updated with correct import paths to reflect refactoring within condebase.
 - Corrected typo within create-simulation_demo: my_swtich -> my_switch
 - updates to ARP implementation. This is now a property in HostNode and NetworkNode, meaning router.arp.show() now works in network_simulator_demo notebook as intended.
2024-04-09 13:26:35 +01:00
Czar Echavez
bce32fb376 Merged PR 330: #2448: store last query response for db client
## Summary
Required to complete #2448
DB Client will store last query response - Data Fusion Service will use this to know the difference between no response and invalid response

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2448: store last query response for db client

Related work items: #2448
2024-04-04 13:30:55 +00:00
Czar Echavez
383cf051df #2448: store last query response for db client 2024-04-04 14:17:34 +01:00
Marek Wolan
5408611c73 Merged PR 329: Remove link refs and put nice naming convention instead
instead of UUID for link primary key in describe state, we are using something more like

router_1:eth-3<->switch_1:eth-8
**all configs need to change the observation space link schema as a result of this change**

It looks like there are a lot of changed files, but it's mostly just removing the `game` parameter from observations and removing 'ref' from config files.

:)

also we no longer need to specify `ref` for nodes, services, or applications. (**but existing configs will not break based on this change!**)

Related work items: #2450
2024-04-04 09:11:23 +00:00
Marek Wolan
3b4962830a #2450 remove unused ref maps in PrimaiteGame 2024-04-03 22:52:06 +01:00
Marek Wolan
698cb83e41 #2450 change link definition schema 2024-04-03 22:20:33 +01:00
Marek Wolan
526dcc7ffe #2450 remove the need to pass Game to observation objects 2024-04-03 22:16:54 +01:00
Marek Wolan
53de4bf7dd Update test assets to new link naming convention 2024-04-03 21:46:42 +01:00
Marek Wolan
e99d238568 #2450 remove link refs and put nice naming convention instead 2024-04-03 21:39:13 +01:00
Marek Wolan
c9a552b836 Merged PR 328: #2449 fix observation integration
small fix

Related work items: #2449
2024-04-03 20:32:32 +00:00
Marek Wolan
2cd9e58994 temp disable extra platforms for build pipeline 2024-04-03 20:18:23 +00:00
Marek Wolan
5f9af03cd9 Merge remote-tracking branch 'origin/dev' into bugfix/2449-observation-where 2024-04-03 20:00:19 +01:00
Marek Wolan
06fd15abaa Merged PR 325: #2446 Fix io config parsing order
Tiny small bugfix.

make sure IO settings are read before the game config in the environments. This is so that SIM_OUTPUT global variable is set before constructing game objects.

Related work items: #2446
2024-04-03 16:33:51 +00:00
Marek Wolan
a4caa3dfe4 #2449 fix observation integration 2024-04-03 15:58:01 +01:00
Czar Echavez
985628f2da Merged PR 324: #2437: fix the visible health status not being carried on after restoring bac...
## Summary
The file being backed up by the database service does not restore the last visible health status of the db file before being restored

## Test process
- Tests that the visible health status is carried forward when the file is corrupted and then restored
- Tests that the visible health status is carried forward when the file is corrupted, deleted and then restored

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2437: fix the visible health status not being carried on after restoring backup file

Related work items: #2437
2024-04-02 15:37:01 +00:00
Czar Echavez
989e7481f3 #2437: fix the visible health status not being carried on after restoring backup file 2024-04-02 15:10:48 +01:00
Marek Wolan
e3d3a94da2 Merged PR 321: CAOS 0.8 observations
## Summary
* Remove the usecase-specific and agent-specific observation classes, replacing with a more flexible system
* Add configuration schemas to every observation class
* Add router, firewall, port, and application observation
* Re-shape the dict structure of observations to make it adhere to CAOS 0.8
* Change existing configs to use the new structure
* make host observation separate

## Test process
existing and new unit tests as well as ad hoc notebooks

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2417
2024-04-02 14:00:27 +00:00
Christopher McCarthy
742f1be81b Merged PR 320: #2419- Created a Router-specific version of SessionManager
## Summary
Created a Router-specific version of `SessionManager` that looks at route table rather than default gateway when dst ip address isn't for a locally attached network. Carried these changes through to arp. Added test for this. Made some minor improvements to show functions in container and node that assist debugging.

## Test process
TDD approach: wrote the test, ran it and watched it fail. The implemented the fix and re-ran the test; it passes.

**Before fix:**
![image (2).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/320/attachments/image%20%282%29.png)

**After fix:**
![image.png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/320/attachments/image.png)

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2419

Related work items: #2419
2024-04-02 12:58:21 +00:00
Chris McCarthy
bb937c1092 #2149 - docstring changes following PR suggestions. 2024-04-02 12:56:15 +01:00
Marek Wolan
82143a2a2e #2446 Fix io config parsing order 2024-04-02 00:31:06 +01:00
Marek Wolan
d2c7ae481c #2417 Add categorisation and updated new configs from merge 2024-04-01 22:03:28 +01:00
Marek Wolan
e4300faa1c Merge remote-tracking branch 'origin/dev' into feature/2417-observation-refactor 2024-04-01 19:21:40 +01:00
Marek Wolan
2513646205 #2417 fix last observation tests 2024-04-01 16:50:59 +01:00
Cristian Genes
1dd911b417 Merged PR 322: #2402 Add ACL actions for routers and firewalls
## Summary
Added ACL addrule and removerule for routers and firewalls

## Test process
New test created to cover all possibilities

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2402, #2415
2024-04-01 15:34:26 +00:00
Marek Wolan
709486d739 #2417 test firewall and router obs 2024-04-01 16:06:12 +01:00
Cristian-VM2
80c13adfdf #2402 add action maps on all yaml scenarios used for testing 2024-04-01 14:28:41 +00:00
Cristian-VM2
2096b619ec #2402 raise error if action map is not specified. update comment in firewall.py 2024-04-01 12:32:44 +00:00
Marek Wolan
0ba767d2a0 #2417 update observation tests and make old tests pass 2024-04-01 00:54:55 +01:00
Marek Wolan
0e0df1012f #2417 update observations init to autoimport all obs types 2024-03-31 23:39:24 +01:00
Marek Wolan
8da53db822 #2417 Finalise parsing of observation space 2024-03-31 23:20:48 +01:00
Marek Wolan
62ebca8c08 #2417 Remove references to old obs names and add link obs 2024-03-31 21:39:24 +01:00
Marek Wolan
15cb2e6970 #2417 Add NestedObservation 2024-03-31 17:31:10 +01:00
Cristian-VM2
2546f268eb #2402 refactor port actions to take same input params (hostname) as new acl actions for routers and firewalls 2024-03-31 11:59:31 +00:00
Cristian-VM2
2d1f38bcb7 #2402 fix test 2024-03-29 17:28:40 +00:00
Cristian-VM2
d1301002d3 #2402 run pre-commits 2024-03-29 17:07:08 +00:00
Cristian-VM2
8763a27cca Merge remote-tracking branch 'origin/dev' into feature/2402-add-acl-actions-for-routers-and-firewalls 2024-03-29 16:37:37 +00:00
Cristian-VM2
7299a12c64 #2402 add firewall acl actions 2024-03-29 16:30:39 +00:00
Marek Wolan
22e1dfea2f #2417 Move classes to correct files 2024-03-29 14:14:03 +00:00
Marek Wolan
9123aff592 #2417 Add hella docstrings 2024-03-29 13:15:31 +00:00
Marek Wolan
1751714d3d Tidy up node observation file 2024-03-29 12:21:52 +00:00
Marek Wolan
d8a66104f5 Fixed observations 2024-03-29 11:55:22 +00:00
Cristian-VM2
2eb900746b #2402 rename network_acl actions to router_acl and refactor how router_name is given 2024-03-29 11:34:43 +00:00
Marek Wolan
f88b4c0f97 #2417 more observations 2024-03-28 17:40:27 +00:00
Cristian Genes
d415ef9c3e Merged PR 319: Add application install and remove actions
## Summary
Add application install and remove (uninstall) actions

## Test process
Both actions are tested in the same (new) test

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2405
2024-03-28 16:37:01 +00:00
Cristian-VM2
2a5432fb0a Merge branch 'feature/2402-add-acl-actions-for-routers-and-firewalls' of ssh.dev.azure.com:v3/ma-dev-uk/PrimAITE/PrimAITE into feature/2402-add-acl-actions-for-routers-and-firewalls 2024-03-28 16:09:55 +00:00
Chris McCarthy
1ac3e1c6b4 #2149 - Created a Router-specific version of SessionManager that looks at route table rather than default gateway when dst ip address isn't for a locally attached network. Carried these changes through to arp. Added test for this. Made some minor improvements to show functions in container and node that assist debugging. 2024-03-28 15:52:08 +00:00
Cristian-VM2
cfea38c5a7 #2405 refactor e2e test, fix uninstalled apps not being removed from the request manager 2024-03-28 15:34:47 +00:00
Cristian-VM2
1e1eea47f1 #2405 add e2e test for application install and uninstall, refactor input params 2024-03-28 14:08:08 +00:00
Cristian-VM2
f83d9cb1b0 #2405 refactor application_uninstall_action to re-use existing code in uninstall_application 2024-03-28 12:14:05 +00:00
Cristian-VM2
8612842b74 #2405 remove .lower from _read_application_type, rename _software_manager to _software_request_manager in base.py 2024-03-28 12:01:36 +00:00
Marek Wolan
350b988318 #2418 Fix broken property 2024-03-28 11:29:22 +00:00
Marek Wolan
09caa55c65 #2418 - Add printer and wireless router as node types in network show 2024-03-28 11:29:22 +00:00
Marek Wolan
c29c3971fa #2418 - add wildcard masks and from_config tests to routers 2024-03-28 11:29:22 +00:00
Marek Wolan
e21c59dff1 #2418 - Change test config 2024-03-28 11:29:22 +00:00
Marek Wolan
b12dee73ba #2418 Fix wireless router from config 2024-03-28 11:29:22 +00:00
Marek Wolan
4301f3fdba #2418 Add Printer and Wireless router to config parser 2024-03-28 11:29:22 +00:00
Cristian-VM2
9b6135524e #2504 update application_install_action docstring 2024-03-28 11:08:30 +00:00
Cristian-VM2
d5b5c7d47a #2405 simplify implementation 2024-03-28 11:02:26 +00:00
Cristian-VM2
cddb39e8e9 #2405 update docstrings 2024-03-28 10:43:57 +00:00
Marek Wolan
0d0b5bc7d9 fix previous commit 2024-03-27 22:11:37 +00:00
Marek Wolan
cae9f64b93 New observations 2024-03-27 22:11:02 +00:00
Cristian-VM2
8bb7f8a177 #2405 add application install and remove actions 2024-03-27 17:07:12 +00:00
Marek Wolan
3d996f05bd Merged PR 318: #2418 Add Printer and Wireless router to config parser
## Summary
Add ability to parse printers and wireless routers from yaml config.

## Test process
Existing unit tests pass. Added a printer to one of the test yamls. Adding a wireless router as well now.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2418
2024-03-27 13:35:33 +00:00
Cristian Genes
de2e5d0b7d Merged PR 317: Add actions for application close, scan and fix. Rename software patch to fix
## Summary
Added actions for application close, scan and fix
Renamed software patch to software fix
Fixed and enabled `test_node_service_scan_integration`

## Test process
All tests passed locally

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2404
2024-03-27 09:21:12 +00:00
Marek Wolan
fbb4eba6b7 Draft new observation space config 2024-03-27 03:27:44 +00:00
Marek Wolan
27bee58bf7 #2418 Fix broken property 2024-03-27 00:00:06 +00:00
Marek Wolan
368542df03 #2418 - Add printer and wireless router as node types in network show 2024-03-26 21:51:27 +00:00
Marek Wolan
9a8a42f3ec #2418 - add wildcard masks and from_config tests to routers 2024-03-26 21:48:17 +00:00
Cristian-VM2
94e637375d #2404 update software state to fixing in UC2 e2e notebook [skip ci] 2024-03-26 17:02:51 +00:00
Cristian-VM2
5860c74ef9 #2404 change software state from patching to fixing to align with CAOS v0.8 2024-03-26 16:41:11 +00:00
Marek Wolan
0e90e6a262 #2418 - Change test config 2024-03-26 16:23:39 +00:00
Marek Wolan
dca26b832d #2418 Fix wireless router from config 2024-03-26 13:21:22 +00:00
Cristian-VM2
b3c1b6b7a5 #2404 quick fix for failing test_query_fail_to_connect 2024-03-26 12:52:16 +00:00
Cristian-VM2
53126e79df #2404 remove extra code in test_query_when_client_is_closed 2024-03-26 12:43:45 +00:00
Cristian-VM2
128e2227d6 #2404 add missing test and revert some name changes 2024-03-26 12:39:11 +00:00
Marek Wolan
e560529639 #2418 Add Printer and Wireless router to config parser 2024-03-26 12:06:23 +00:00
Cristian-VM2
944b248300 #2404 rename software patch to fix 2024-03-26 10:51:33 +00:00
Cristian-VM2
600dc3f016 #2404 add application scan, close, and fix actions, fix and enable service scan test 2024-03-25 16:58:27 +00:00
Cristian Genes
8b8940f465 Merged PR 314: Add actions to enable/disable ports in routers/firewalls
## Summary
Added actions to enable/disable ports for routers/firewalls
Added tests for routers and added ticket in the backlog to test on firewalls (it's not possible to test at the moment because the game_and_agent fixture cannot build from a yaml file)

Improved the notebook for training sb3 agents on UC2 to include validated value for learning rate and fix for loading sb3 PPO from IY as well as code to evaluate agents

## Test process
Run new tests locally

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2403
2024-03-25 12:34:21 +00:00
Cristian-VM2
78b966ace4 fix port/nic enable/disable actions returning failure when they succeed 2024-03-25 11:41:07 +00:00
Cristian-VM2
4a5dd9ba0f fix typo 2024-03-25 11:08:36 +00:00
Cristian-VM2
bef2bd8084 add actions to enable/disable ports in routers/firewalls, improve notebook for training PPO agents 2024-03-22 16:35:53 +00:00
Marek Wolan
cb9c14c87e Merged PR 310: Pull last-minute beta 7 changes into dev
## Summary
the step label for actions was off by one from the step label in the step metadata log. Also the last episode was not outputting an action log because the reset method wasn't being called (there's a close method for this instead).

## Test process
Notebooks, pytests

## Checklist
- [~] PR is linked to a **work item**
- [~] **acceptance criteria** of linked ticket are met
- [y] performed **self-review** of the code
- [n] written **tests** for any new functionality added with this PR
- [n] updated the **documentation** if this PR changes or adds functionality
- [n] written/updated **design docs** if this PR implements new functionality
- [n] updated the **change log**
- [y] ran **pre-commit** checks for code style
- [y] attended to any **TO-DOs** left in the code

Related work items: #2230
2024-03-18 10:39:01 +00:00
Marek Wolan
bb01619918 Bump version 2024-03-15 16:17:45 +00:00
Marek Wolan
b4d310eda2 Align step counts in logging 2024-03-15 16:17:38 +00:00
Marek Wolan
a8c98c28f1 Merge remote-tracking branch 'origin/dev' into release/3.0.0b7 2024-03-15 16:13:50 +00:00
Czar Echavez
d5fb2f2309 Merged PR 307: #2369: commiting work done so far
## Summary
Added a page to explain how to use the Jupyter notebooks via jupyter command and VSCode

Also added Nick's suggestion to fix #2226

Going to be honest - not my finest pull request

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2369: commiting work done so far

Related work items: #2369
2024-03-15 15:59:42 +00:00
Nick Todd
d8b75a33e4 Merged PR 309: 2384: Updates for 3.0.0b7 release.
## Summary
Updated CHANGELOG.md, lightly edited and corrected.

## Test process
N/A

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

2384: Updates for 3.0.0b7 release.

Related work items: #2384
2024-03-15 15:06:22 +00:00
Marek Wolan
b217869dd1 Improve clarity in docs 2024-03-15 15:03:27 +00:00
Marek Wolan
fc67fc4833 Fix notebook parsing data 2024-03-15 14:37:28 +00:00
Marek Wolan
9a38fcdae2 Fix broken config 2024-03-15 14:19:30 +00:00
Marek Wolan
8a9d8fb17c Calm logging again 2024-03-15 14:10:34 +00:00
Marek Wolan
7f4f3e9bfe Calm logging 2024-03-15 14:09:02 +00:00
Marek Wolan
c8beb39fac clear notebook output 2024-03-15 14:03:49 +00:00
Marek Wolan
33dd6e4dcd Make sure notebook is using correct dict key 2024-03-15 14:03:37 +00:00
Nick Todd
6f780f20d7 2384: Updates for 3.0.0b7 release. 2024-03-15 13:55:00 +00:00
Marek Wolan
d9b6506572 Mention python version in getting started guide. 2024-03-15 13:42:59 +00:00
Marek Wolan
6ce96f00fe Merge branch 'feature/2369-document-how-to-use-primaite-notebooks' of https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE into feature/2369-document-how-to-use-primaite-notebooks 2024-03-15 13:25:54 +00:00
Marek Wolan
2fde071789 Update docs on example notebooks 2024-03-15 13:25:50 +00:00
Marek Wolan
505f9dfb09 Merge remote-tracking branch 'origin/dev' into feature/2369-document-how-to-use-primaite-notebooks 2024-03-15 13:25:30 +00:00
Marek Wolan
40ba8c5ac0 Merged PR 308: Fix stubborn logs and default config values
## Summary
Ensure that the logging options are being read correctly from the config. Makes logs actually optional.

Also temporarily disable checkhash and replace it with file scan because checkhash is buggy.

## Test process
By inspection

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Fix some stuff

Related work items: #2382
2024-03-15 13:20:26 +00:00
Czar Echavez
e580fa0464 Merge remote-tracking branch 'origin/dev' into feature/2369-document-how-to-use-primaite-notebooks 2024-03-15 13:14:31 +00:00
Czar Echavez
1ed2f48f54 #2369: missed items 2024-03-15 13:13:54 +00:00
Marek Wolan
e0eef8e56e Fix tests 2024-03-15 12:19:56 +00:00
Marek Wolan
04c86e30c9 Fix some stuff 2024-03-15 11:15:02 +00:00
Marek Wolan
d257501703 Merged PR 304: Reward sharing
## Summary
* add ability for agents to share rewards - the calculated reward value for one agent can be used as a component of another agent's reward.
* Update UC2 configs to use the reward sharing functionality - green agents have a reward based on their two actions. Blue agent reward adds green agent rewards to itself.
* Add agent action history - This allows the rewards to react to agent actions.
* Make action logging use the new agent history.
* Make the webpage and database reward components treat failed requests the same as if the webpage was unavailable / database was unreachable.
* reorder the PrimaiteGame step to be the same as the Gymnasium env step
* update uc2 notebook accordingly.

## Test process
Tested with ad-hoc notebooks and debugging tool to verify correct data is being used. Tested notebooks run properly and pytests pass. Added unit and integration tests.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2372
2024-03-15 10:42:12 +00:00
Nick Todd
90224960e5 2299: Backup Jupyter notebook changes. 2024-03-15 10:33:58 +00:00
Marek Wolan
a9bf0981e6 Doc fixes 2024-03-15 09:22:55 +00:00
Czar Echavez
1d09f0791a #2369: Reduce dependency on manually replacing primaite version across documentation 2024-03-14 23:17:34 +00:00
Czar Echavez
88a3c42f2f #2369: commiting work done so far 2024-03-14 22:15:27 +00:00
Marek Wolan
d33c80d0d6 Minor fixes 2024-03-14 14:33:04 +00:00
Nick Todd
c5e142a500 2299: Remove calls to corrupt. 2024-03-13 17:43:56 +00:00
Marek Wolan
f438acf745 Add shared reward test 2024-03-13 14:01:17 +00:00
Marek Wolan
ee26554ef0 merge origin/dev into feature branch 2024-03-13 12:11:50 +00:00
Marek Wolan
10ee9b300f Update docs on rewards 2024-03-13 12:08:20 +00:00
Czar Echavez
c7c34e1fb6 Merged PR 301: #2350: Confirm action / observation space conforms to CAOS v0.7
## Summary
### **work related to v0.7 CAOS**
- Split observations.py into:
  - agent_observations.py
  - file_system_observations.py
  - node_observations.py
  - nic_observations.py
  - observation_manager.py
  - observations.py
  - software_observations.py
- added tests to ensure that the observations align with [QTSL-820-2450 - ARCD Track 2 Common Action Observation Space Definition v0.7](https://nscuk.sharepoint.com//r/sites/SSE32ARCDIDT/Shared%20Documents/General/ARCD/Architecture%20%26%20Design%20Documentation/Common/CAOS%20Related%20Documents/QTSL-820-2450%20-%20ARCD%20Track%202%20Common%20Action%20Observation%20Space%20Definition%20v0.7.xlsx?d=wee5713d8640b4b5bb3cb5624936e417e&csf=1&web=1&e=lByVQ5)

### preparation for v0.8 CAOS
WILL NOT AFFECT OBSERVATION SPACE FOR V0.7

**DO NOT PANIC**

these features are needed for v0.8

- integrated `num_access` to file (not used yet in file observations)
- integrated `num_file_deletions` and `num_file_creations` to file_system (not used yet in node observations)

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2350
2024-03-13 09:20:23 +00:00
Marek Wolan
6dedb91099 Remove redundant TODOs 2024-03-13 09:17:29 +00:00
Czar Echavez
f2c6f10c21 #2350: apply PR suggestions 2024-03-12 12:20:02 +00:00
Marek Wolan
045f467407 Update marl config 2024-03-12 11:51:17 +00:00
Marek Wolan
24fdb8dc17 Fix minor reward sharing bugs 2024-03-12 11:40:26 +00:00
Marek Wolan
03ee976a2d remove extra print statement 2024-03-12 11:00:55 +00:00
Marek Wolan
a76f5b0efb Merge remote-tracking branch 'origin/dev' into feature/2327-green-action-failure-part-II 2024-03-12 10:59:41 +00:00
Czar Echavez
ec4818e4d3 Merge remote-tracking branch 'origin/dev' into feature/2350-confirm-action-observation-space-conforms-to-CAOS-0.7 2024-03-12 09:11:30 +00:00
Marek Wolan
c3f1cfb33d Add shared reward 2024-03-11 22:53:39 +00:00
Marek Wolan
7599655879 Add agent action history 2024-03-11 20:10:08 +00:00
Marek Wolan
f46980b5f5 Merged PR 302: Make simulator requests able to provide a response
this PR is a pre-requisite to the work im doing today where green agents actions that fail to reach their target still incur a negative reward.

## Summary
- Requests now return a response.
- Added the request response to the agent logging and info output of env step.
- Changed all request types in the simulator to return a response
- Added a new 'validator' that allows nodes to execute actions only if the node is on (this check happens at the request level rather than in every single function)
- Fixed NMNE - made nic observation responsible for converting total NMNE this episode to NMNE last step because apply_timestep is applied after actions but before observations in the step method.
- Fixed arcd_uc2_network to configure the db clients and web browsers correctly
- Added tests for request responses

## Test process
New tests, existing tests pass.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2372
2024-03-11 19:48:18 +00:00
Czar Echavez
cd6d6325db #2350: add tests to check spaces + acl obs test + nmne space changes 2024-03-11 17:47:33 +00:00
Marek Wolan
1faefbccac Add docstring for init request manager 2024-03-11 10:20:47 +00:00
Marek Wolan
66ab5ec980 Fix last tests 2024-03-11 09:18:31 +00:00
Czar Echavez
a228a09917 #2350: documentation 2024-03-10 15:13:37 +00:00
Marek Wolan
d2afcaa939 Update changelog 2024-03-10 13:06:45 +00:00
Marek Wolan
e5c5a85003 Add docs on request response 2024-03-10 13:05:57 +00:00
Marek Wolan
f4684b0349 Fix how nmnes are getting put into obs space. 2024-03-09 23:32:00 +00:00
Marek Wolan
359777f4f8 Add tests for request success/fail 2024-03-09 23:06:53 +00:00
Marek Wolan
31ae4672ac Make nodes only accept requests when they're on 2024-03-09 20:47:57 +00:00
Czar Echavez
cc721056d8 #2350: configurable NMNE category thresholds 2024-03-08 19:32:07 +00:00
Marek Wolan
289b5c548a Make a type alias for request & fix typo 2024-03-08 17:14:41 +00:00
Marek Wolan
0447a05084 Add call validation 2024-03-08 15:57:43 +00:00
Marek Wolan
beb51834f9 Make all requests return a RequestResponse 2024-03-08 14:58:34 +00:00
Czar Echavez
61aa242128 #2350: tests + application 2024-03-08 14:48:31 +00:00
Czar Echavez
ba58204542 #2350: split observations into smaller files 2024-03-08 14:08:35 +00:00
Czar Echavez
b13725721d #2350: splitting observations into separate files 2024-03-08 13:49:00 +00:00
Marek Wolan
d331224b45 Start introducing RequestResponse 2024-03-08 12:42:22 +00:00
Czar Echavez
e9eef2b4c0 #2350: add num_access, num_file_deletions and num_creations to file system 2024-03-08 11:16:27 +00:00
Marek Wolan
59bbc0e733 Merged PR 299: Match default reward configs to Imaginary Yak.
## Summary
Change the default rewards for the data manipulation configs
Also I renamed the config files to make their names more descriptive.

## Test process
Pytests and all notebooks run without fail.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2365
2024-03-07 21:52:55 +00:00
Marek Wolan
81a375d6c4 Merged PR 298: Update NMNE to only count MNEs in the last step.
## Summary
The NMNE counts MNEs since last step rather than since last episode.

## Test process
Updated unit tests to check for the new behaviour and added new test.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

There's no update necessary to the docs or change log because it NMNE is already documented, and the text is still correct given this minor change.

Related work items: #2348
2024-03-07 16:20:39 +00:00
Marek Wolan
618da8abe9 Rename notebooks 2024-03-07 15:25:11 +00:00
Marek Wolan
76752fd9af Change the nmne clear to happen at apply_timestep instead of within describe_state 2024-03-07 14:44:44 +00:00
Marek Wolan
17d4807660 Rename configs 2024-03-07 14:33:21 +00:00
Marek Wolan
2547361daf Change default reward weights 2024-03-07 13:52:26 +00:00
Marek Wolan
a900d59f7b Update NMNE to only count MNEs in the last step. 2024-03-07 12:15:30 +00:00
Marek Wolan
8589ce449a Merged PR 295: Agent action logging
## Summary
Added a new optional capability to create a JSON log each episode with a list of action each agent took each step (including scripted, RL, and red agents).

Also I had to slightly refactor the IO system to not rely on PrimaiteSession, as it's gonna be deprecated soon. Therefore the IO module is now linked to the gym environment. Each time you init a gym environment, it creates a session directory.

## Test process
Tried the SB3, Ray SARL and Ray MARL notebooks to see that the outputs get generated.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Move IO to environments from session and add agent logging

Related work items: #2278
2024-03-05 16:39:44 +00:00
Marek Wolan
e117f94f43 Minor doc fix 2024-03-05 15:46:30 +00:00
Marek Wolan
72e0c3b402 Merged PR 296: Add a notebook to customise red agent behaviour
## Summary
just run the notebook and see if the explanation makes sense.

I also renamed some stuff to make it more user friendly

Related work items: #2343
2024-03-05 12:02:19 +00:00
Marek Wolan
a7bfc56b98 Apply documentation changes based on PR review. 2024-03-05 11:21:49 +00:00
Marek Wolan
3e495c4622 Cosmetic changes to notebook 2024-03-05 09:28:22 +00:00
Marek Wolan
758f892b74 Make notebook for varying red agent behaviour in uc2 2024-03-04 21:04:27 +00:00
Marek Wolan
a222a8c58f Give the UC2 config load function a meaningful name 2024-03-04 19:43:51 +00:00
Marek Wolan
1e8dfa40cf Give uc2 notebook a meaningful name 2024-03-04 19:36:54 +00:00
Marek Wolan
d0225bf3e1 Merge remote-tracking branch 'origin/dev' into feature/2278-log-agent-actions 2024-03-04 19:00:03 +00:00
Marek Wolan
c3010ff816 Update changelog and docs 2024-03-04 18:59:03 +00:00
Marek Wolan
2f456e7ae0 Move IO to environments from session and add agent logging 2024-03-04 18:47:50 +00:00
Marek Wolan
84f5d45540 Merged PR 294: Update actions set in uc2 to match Yak
## Summary
Expand the available actions.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2243
2024-03-04 14:39:07 +00:00
Marek Wolan
bc830e6458 Merge remote-tracking branch 'origin/dev' into feature/2243-sync-uc2-action-to-iy 2024-03-04 13:39:22 +00:00
Marek Wolan
c32bd3f941 Merged PR 285: Green agent that sometimes performs database connections
## Summary
* removed `GreenWebBrowsingAgent` because it was replaced by probabilistic agent
* created new 'probabilistic agent' which selects actions randomly from its action map, with configurable probabilities
* slightly refactored action manager to decouple it from `PrimaiteGame` (as a consequence, agents should be given the current timestep if their `get_action()` method is time-dependent)
* refactored `data_manipulation_bot` to use an existing db client on the host rather than inheriting from it
* added new type of SQL query to databases: `"SELECT * FROM pg_stat_activity"` to model checking connection status
* added new execution definition on the `DatabaseClient` app which just performs that new SQL query
* added reward for the green admin being able to connect to the db
* updated uc2 notebook to reflect new changes.
* updated documentation for data manipulation bot
* added new test for probabilistic agent
* added test for new reward

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2319
2024-03-04 12:06:55 +00:00
Marek Wolan
2c3652979b Add helpful error messages to action index errors 2024-03-04 11:17:54 +00:00
Marek Wolan
ac9d550e9b Change get_action signature for agents 2024-03-04 10:43:38 +00:00
Marek Wolan
d1480e4477 Apply suggestions from PR review. 2024-03-04 09:58:57 +00:00
Marek Wolan
0d490d618c Update MARL config 2024-03-03 16:59:14 +00:00
Marek Wolan
a4c723858b Update action map in second 2024-03-03 16:57:53 +00:00
Marek Wolan
afc3635bfe Update changelog 2024-03-03 16:56:52 +00:00
Marek Wolan
ea1d016bc2 Merge remote-tracking branch 'origin/feature/2319-database-admin' into feature/2243-sync-uc2-action-to-iy 2024-03-03 16:55:42 +00:00
Marek Wolan
0e8c60df4c Update actions 2024-03-03 16:53:18 +00:00
Marek Wolan
a6031d568d Remove unused import 2024-03-03 16:36:08 +00:00
Marek Wolan
ef1a2dc3f4 clear uc2 notebook outputs 2024-03-03 16:00:10 +00:00
Marek Wolan
afa775baff Add test for new reward 2024-03-03 15:52:34 +00:00
Marek Wolan
4d51b1a414 Update configs to new db manipulation bot approach 2024-03-03 14:57:28 +00:00
Marek Wolan
070655cfce Update data manipulation bot documentation 2024-03-03 11:47:50 +00:00
Marek Wolan
9762927289 Update notebook with new changes 2024-03-03 11:43:24 +00:00
Marek Wolan
fe13583d2a Merge remote-tracking branch 'origin/dev' into feature/2319-database-admin 2024-03-03 11:24:09 +00:00
Marek Wolan
4a292a6239 Fix checking connection in db client 2024-03-03 11:23:24 +00:00
Marek Wolan
80158fd9b4 Make db manipulation bot work with db client 2024-03-03 11:18:06 +00:00
Christopher McCarthy
e8b1177c18 Merged PR 291: #2357 - Allow empty nodes, links, and agents arrays in config file
## Summary
Allowed the config to not have nodes, links and agents and still be parsed

## Test process
Tested with config file that doesn't have any simulation key/value pair

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2357 - Allowed the config to not have nodes, links and agents and still be parsed

Related work items: #2357
2024-03-02 19:30:22 +00:00
Christopher McCarthy
e5ebf6a745 Merged PR 292: #2358 - Use class name for node type properties in network container
## Summary
The node-specific properties in Network class now simply use node.__class__.__name__ to check their type for filtering by type

## Test process
Tests updated to use the new property function names

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2358 - the node-specific properties in Network class now simply use node.__class__.__name__ to check their type for filtering by type. Tests updated to use the new property function names

Related work items: #2358
2024-03-02 18:34:51 +00:00
Chris McCarthy
81fd43035d #2358 - the node-specific properties in Network class now simply use node.__class__.__name__ to check their type for filtering by type. Tests updated to use the new property function names 2024-03-01 22:51:01 +00:00
Chris McCarthy
af036f63f1 #2357 - Allowed the config to not have nodes, links and agents and still be parsed 2024-03-01 22:37:51 +00:00
Czar Echavez
ac304c85a3 Merged PR 290: #2356: optional dmz port + optional external acl rules
## Summary
Bug fix to allow firewall dmz port to be optional as well as external acl rules to be optional

## Test process
See https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/290?_a=files&path=/tests/integration_tests/configuration_file_parsing/nodes/network/test_firewall_config.py

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2356: optional dmz port + optional external acl rules

Related work items: #2356
2024-03-01 17:49:37 +00:00
Czar Echavez
78ff658e30 #2356: optional dmz port + optional external acl rules 2024-03-01 16:48:05 +00:00
Marek Wolan
2a1d99ccce Fix problem with checking connection for db admin 2024-03-01 16:36:41 +00:00
Marek Wolan
ed01293b86 Make db admin reward persistent 2024-03-01 16:02:27 +00:00
Marek Wolan
10a4053887 Fix tests 2024-03-01 15:14:00 +00:00
Marek Wolan
9ff8adab1a Merge remote-tracking branch 'origin/dev' into feature/2319-database-admin 2024-03-01 09:23:00 +00:00
Czar Echavez
b849bfd6e2 Merged PR 280: Router Routes and Configuration documentation updates
## Summary

- Updated Sphinx 6.1.3 => 7.1.2
- Updated furo 2023.3.27 => 2024.01.29
- Added tests to check that firewall, routers and nodes are properly added via config (config parser tests)
- Added some reference points in code comments for Sphinx documentation to reference
- Created a list of System Software so it can be referenced in docs and by code
- Added default values to config within game.py (The defaults are pulled from example_config.yaml)
- Created a section for creating a session via config files:
    - set up a lot of stuff so documentation is easier to maintain
    - Template for things that are repeated in places
    - added how to create nodes via config
    - added how to install applications and services via config
- diagrams to make it easier to understand some stuff e.g. ACL rules for firewall

see https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/280?_a=files&path=/CHANGELOG.md

## Test process
- Firewall:
  - Created a DMZ Network example config
  - Tested the creation of Firewall
  - Tested the ACL Rules of Firewall

https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/280?_a=files&path=/tests/integration_tests/configuration_file_parsing/nodes/network/test_firewall_config.py

https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/280?_a=files&path=/tests/integration_tests/configuration_file_parsing/nodes/network/test_router_config.py

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2257
2024-02-29 16:22:55 +00:00
Czar Echavez
69b7ca1703 Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-29 15:21:20 +00:00
Czar Echavez
49a4e1fb56 #2257: added common node attributes page + ability to set node operating state via config + tests 2024-02-29 15:20:54 +00:00
Christopher McCarthy
90d51c071c Merged PR 288: #2326 - Network Interface port name/num fixed so that it carries through to s...
## Summary
This pull request fixes the issue o network interface port name and number not being pulled through into sys log and PCAP output files.

## Test process
Manually checked:
![image (4).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/288/attachments/image%20%284%29.png)
![image (2).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/288/attachments/image%20%282%29.png)
![image (3).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/288/attachments/image%20%283%29.png)

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2326 - Network Interface port name/num fixed so that it carries through to sys log and PCAP outputs.

Related work items: #2326
2024-02-29 15:14:08 +00:00
Chris McCarthy
8f0de8521e #2326 - removed port_name print statement 2024-02-29 14:08:42 +00:00
Marek Wolan
bd0b2e0033 Remove redundant notebook cells 2024-02-29 13:22:41 +00:00
Marek Wolan
2f3e40fb6b Fix issue around reset 2024-02-29 13:22:05 +00:00
Marek Wolan
f7c535b557 Merge 'origin/dev' into feature/2319-database-admin 2024-02-29 13:21:44 +00:00
Chris McCarthy
cf0674ce22 #2326 - Network Interface port name/num fixed so that it carries through to sys log and PCAP outputs. 2024-02-29 13:00:27 +00:00
Czar Echavez
eefc2739c8 Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-29 11:34:56 +00:00
Marek Wolan
312b5c35bd Merged PR 283: Refactor episode reset
## Summary
Instead of setting all attributes back to a snapshot, simply recreate the entire game and all agents from a cached copy of the config.

This removes the need for `set_original_state` and `reset_component_for_episode` methods on SimComponents.

## Test process
* Unit tests passing
* I've also tried adding a `__del__` method to simcomponent and agent and press env.reset() to verify that the ref count reaches 0, and nothing is secretly keeping using an old part of the simulation.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2317
2024-02-29 11:11:03 +00:00
Czar Echavez
9a4587155b #2257: specifically stating that enpoint refs are node hostnames + remove TODO 2024-02-29 11:07:21 +00:00
Marek Wolan
ce39387f92 Merge 'origin/dev' into feature/2317-refactor-reset 2024-02-29 10:16:42 +00:00
Marek Wolan
8730330f73 Apply PR suggestions 2024-02-29 10:14:31 +00:00
Czar Echavez
13db07dc11 Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-28 15:09:23 +00:00
Czar Echavez
6d43c61058 #2257: apply PR suggestions 2024-02-28 15:08:00 +00:00
Christopher McCarthy
98427b0e73 Merged PR 279: #2238 - Implement NMNE detection and capture
## Summary

This pull request introduces new features for capturing Malicious Network Events (NMNE) within the `NetworkInterface` class and extends the functionality to the `NicObservation` class .Additionally, it updates the simulation configuration to allow customizable NMNE capturing settings.

### Changes
- `NetworkInterface` Enhancements: Added NMNE capturing capabilities to detect and log specified malicious activities.
- `NicObservation` Integration: Updated to support detailed monitoring and analysis based on NMNE capturing results.
- Simulation Configuration: Introduced nmne_config options allowing users to enable NMNE capturing and define specific keywords, enhancing the adaptability of network security measures.

### New Configuration Options
Added to simulation.yml:
``` yaml
simulation:
  network:
    nmne_config:
      capture_nmne: true
      nmne_capture_keywords:
        - DELETE
```

Tests

Documentation
Updated README and related documentation to guide users on how to utilize the new NMNE capturing features and configure them in their simulations.

## Test process
- **NMNE Capture Testing**: Implemented tests using the UC2 network setup, where DELETE SQL queries are initiated by the database client residing on the web server and targeted towards the database service on the database server. Post-query, the network interface cards (NICs) on both servers are examined to verify accurate counting and logging of NMNE (Malicious Network Events) as expected per configuration.

- **NicObservation Testing**: Introduced additional tests to ensure proper integration of the `NicObservation `class, focusing on its ability to accurately observe and report NMNE occurrences.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [X] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

#2238

Related work items: #2238
2024-02-28 14:57:46 +00:00
Chris McCarthy
63ea5478ab #2238 - Updated uc2_demo.ipynb to explain the NMNE in observation space 2024-02-28 13:56:19 +00:00
Chris McCarthy
d55b6a5b48 #2238 - Fixed the observations issue causing tests to fail 2024-02-28 12:03:58 +00:00
Marek Wolan
af8ca82fcb Get the db admin green agent working 2024-02-27 13:30:16 +00:00
Marek Wolan
c54f82fb1b Start implementing green agent logic for UC2 2024-02-26 20:08:13 +00:00
Marek Wolan
922298eaf0 Make database admin action possible 2024-02-26 20:07:02 +00:00
Marek Wolan
33d2ecc26a Apply suggestions from code review. 2024-02-26 16:58:43 +00:00
Marek Wolan
f9cc5af7aa Not sure how this test was passing before 2024-02-26 16:06:58 +00:00
Czar Echavez
f2d7a2fc16 #2257: added way to ensure nodes are on at start + more test to make sure nodes are on when added via config 2024-02-26 14:34:34 +00:00
Marek Wolan
2076b011ba Put back default router rules 2024-02-26 14:26:47 +00:00
Marek Wolan
a5043a8fbe Modify tests based on refactoring 2024-02-26 12:15:53 +00:00
Czar Echavez
d738a23709 #2257: list of db payloads 2024-02-26 11:35:17 +00:00
Marek Wolan
ccb10f1160 Update docs based on reset refactor 2024-02-26 11:02:37 +00:00
Marek Wolan
e5982c4599 Change agents list in game object to dictionary 2024-02-26 10:26:28 +00:00
Czar Echavez
634f634097 #2257: fix text and make examples in node configs more specific 2024-02-26 09:47:12 +00:00
Czar Echavez
e964b8a3ea #2257: more in depth changelog 2024-02-26 08:58:03 +00:00
Czar Echavez
1d5c153752 #2257: changelog update 2024-02-26 08:49:11 +00:00
Czar Echavez
07373d941e #2257: Downgrade version of sphinx - 7.2.0 drops support for Python 3.8 2024-02-26 08:44:08 +00:00
Marek Wolan
63c9a36c30 Fix typos 2024-02-25 18:36:20 +00:00
Marek Wolan
994dbc3501 Finalise the refactor. It works well now. 2024-02-25 17:44:41 +00:00
Marek Wolan
a34cf08209 Merge remote-tracking branch 'origin/dev' into feature/2317-refactor-reset 2024-02-25 16:41:40 +00:00
Marek Wolan
c115095157 Fix router from config using wrong method 2024-02-25 16:17:12 +00:00
Czar Echavez
fb148dc4fb #2257: applications and services docs 2024-02-23 16:49:01 +00:00
Chris McCarthy
52677538a8 #2238 - Tidied up code, added more docstrings, and implemented suggestions from PR. 2024-02-23 15:12:46 +00:00
Marek Wolan
f933341df5 eod commit 2024-02-23 10:06:48 +00:00
Czar Echavez
ef61fe219c Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-23 08:56:35 +00:00
Czar Echavez
5836ea68e3 #2257: rearrange software pages + creating a list of applications and services which is hopefully a single point that should be referred to 2024-02-23 08:55:32 +00:00
Chris McCarthy
771a68dccb #2238 - Implement NMNE detection and logging in NetworkInterface.
- Enhance NicObservation for detailed NMNE event monitoring.
- Add nmne_config options to simulation settings for customizable NMNE capturing.
- Update documentation and tests for new NMNE features and simulation config.
2024-02-22 22:43:14 +00:00
Czar Echavez
98fb28cbbc #2257: setting up application and service docs 2024-02-21 18:19:16 +00:00
Czar Echavez
deb7a3aa9d #2257: massive docs addition for config file 2024-02-21 14:49:59 +00:00
Marek Wolan
8f85555709 Merged PR 278: Enable the red agent to vary its start node
## Summary
- Made the data manipulation red agent be able to choose between the two clients to start operating on
- changed the attacker name in the config to 'data_manipulation_attacker' to because it is no longer tied to any client
- Updated the documentation notebook accordingly.
- Fixed a bug where the database client made a new connection every time it sent a SQL query (it tries to reuse its most recent one instead)
- Fixed a bug where link loads were not being cleared between episodes (?)

**warning** - the green agents are not working properly after reset right now, but I'm gonna fix this in the next ticket where I refactor episode reset.

## Test process
- unit tests pass
- UC2 notebook passes with both clients. (currently this doesn't work after an episode reset, but the very next thing I'm gonna work on is refactoring the reset, so I don't want to waste time fixing this.)

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [n] attended to any **TO-DOs** left in the code

Related work items: #2232
2024-02-20 20:22:20 +00:00
Marek Wolan
72f4cc0a50 Remove reset methods from most classes 2024-02-20 16:56:25 +00:00
Marek Wolan
f82506023b Delete set_original_state method definitions 2024-02-20 16:29:27 +00:00
Marek Wolan
64b9ba3ecf Make environment reset reinstantiate the game 2024-02-20 16:21:03 +00:00
Marek Wolan
88f8e9cb42 Add todo comment. 2024-02-20 12:09:32 +00:00
Marek Wolan
f7c1da3118 Update MARL config. 2024-02-20 12:06:30 +00:00
Marek Wolan
76db5dbaa2 Update changelog 2024-02-20 12:05:02 +00:00
Marek Wolan
4a3c66bdc6 Clear notebook code cells. 2024-02-20 12:04:07 +00:00
Marek Wolan
701781b23e Clear link load in new timestep 2024-02-20 11:05:09 +00:00
Marek Wolan
945db1341b Make database client try to use most recent connection instead of generating new one 2024-02-20 11:04:53 +00:00
Czar Echavez
2e2d83c3e9 #2257: update sphinx version + cleaning up some errors + splitting configuration page into multiple pages 2024-02-16 16:14:36 +00:00
Nick Todd
317fbdbb9c 2230: Version bump 2024-02-16 12:46:36 +00:00
Czar Echavez
e390d8385c #2257: acl tests 2024-02-15 16:29:36 +00:00
Czar Echavez
48d7f9f85a Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-15 15:45:44 +00:00
Czar Echavez
b739823318 #2257: add firewall via config + fix router hop ip address + shuffling around tests 2024-02-15 15:45:18 +00:00
Czar Echavez
23a56ca59f Merged PR 270: #2258: DoSBot cannot be added via configuration file
## Summary
- Added ability to set DoSBot in nodes via config file
- Fixed missing configuration items in other services/applications
- Created a variable which contains the list of applications and services
- Moved `DatabaseClient` from list of services to list of applications

## Test process
Created a configuration file where a node has all services and applications installed, this is then used by an integration test which loads the configuration file. The test checks to make sure that the configuration file is correctly read and the Service and Application objects are properly created

## Checklist
- [X] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2258
2024-02-15 09:36:08 +00:00
Nick Todd
0af2eef89c Merged PR 274: Add INSERT query functionality into database service.
## Summary
Add support for SQL INSERT query in database_service.py.

## Test process
Updated test_database_on_node.py to test for database INSERTions.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2306
2024-02-14 16:51:25 +00:00
Nick Todd
8520f22e22 2306: Updated documentation 2024-02-14 13:35:08 +00:00
Nick Todd
4a38672fea 2306: Handle INSERT query 2024-02-14 13:18:20 +00:00
Nick Todd
07a934ab66 2306: Update tests to verify INSERT query. 2024-02-14 12:00:08 +00:00
Czar Echavez
ab7c7b9c06 Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-13 17:37:34 +00:00
Czar Echavez
98a4fbecb5 Merge remote-tracking branch 'origin/dev' into feature/2258-dosbot-cannot-be-added-via-configuration-file 2024-02-13 16:04:02 +00:00
Christopher McCarthy
9835b31dc5 Merged PR 272: #2205 - Firewall Node
## Description:

This pull request introduces the Firewall class and extends the ACLRule functionality within PrimAITE to provide comprehensive network traffic management and security capabilities. These enhancements enable detailed control over data flow through network simulations, mimicking real-world firewall operations and ACL configurations. The updates focus on the addition of a Firewall node that extends the Router class functionalities and the enhancement of ACLRule to support IP ranges through wildcard masking, thus offering granular traffic filtering based on IP addresses, protocols, ports, and more.

## Key Features:

**Firewall Class:** A new class that extends the Router class, incorporating firewall-specific logic for inspecting, directing, and filtering traffic between the internal, external, and DMZ (De-Militarized Zone) network interfaces. The Firewall class supports configuring network interfaces and applying Access Control Lists (ACLs) for inbound and outbound traffic control.

**Enhanced ACLRule:** The ACLRule class has been updated to support IP ranges using wildcard masking. This allows for more flexible rule definitions, enabling users to specify broad network ranges or individual IP addresses in ACL rules.

**Comprehensive ACL Configuration:** Six distinct ACLs (internal inbound, internal outbound, DMZ inbound, DMZ outbound, external inbound, and external outbound) provide meticulous control over traffic flow, ensuring robust network security. Examples included in the documentation illustrate how to configure ACLs for common scenarios, such as blocking external threats, permitting specific services, and restricting access to sensitive internal resources.

**Intuitive Interface and ACL Management:** Simplified methods for configuring firewall interfaces and ACL rules enhance usability. The Firewall class offers intuitive functions for rule management, including adding, removing, and listing ACL rules.

**Detailed Documentation and Examples:** Accompanying the code updates, comprehensive documentation and example configurations are provided, detailing the use and configuration of the Firewall node and ACL rules within PrimAITE simulations.

## Impact:

The introduction of the Firewall class and the enhancement of ACLRule significantly broaden PrimAITE's capabilities for simulating realistic network security scenarios. Users can now accurately model the behavior of firewalls in their network simulations, applying complex ACLs to control traffic flow and enforce security policies. This update enables more detailed network security analyses, teaching, and experimentation within the PrimAITE environment.

## Test process
Extensive unit tests have been added to cover the new functionality, ensuring reliability and correctness. Tests include scenarios for firewall configuration, ACL rule application, traffic filtering based on various criteria, and interaction between different network zones.

## Checklist
- [X] PR is linked to ...
2024-02-13 13:56:56 +00:00
Czar Echavez
b277034e8b #2257: temporarily commit changes - added startup and shut down durations to node config + adding routes 2024-02-13 13:02:24 +00:00
Chris McCarthy
7b64d99a63 #2205 - Final suggestions from PR 2024-02-13 12:56:41 +00:00
Czar Echavez
f4369a4fff Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-13 10:50:45 +00:00
Chris McCarthy
426c0a6682 2205 - Slimmed down the capability of the wireless router for now 2024-02-13 10:18:06 +00:00
Nick Todd
a6f3c458d5 Merged PR 273: 2297: Convert NTP Client and Server to UDP
## Summary
Replaced references to TCP with UDP in NTP client and server code. Updated docs.

## Test process
Re-ran and passed existing tests.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

2297: Convert NTP Client and Server to UDP

Related work items: #2297
2024-02-13 09:43:09 +00:00
Czar Echavez
2c743005cd #2257: moved config tests into its own directory + added dmz_network.yaml to use in tests 2024-02-12 18:58:10 +00:00
Nick Todd
4c66d2b252 2297: Change missed reference TCP to UDP. 2024-02-12 17:24:28 +00:00
Nick Todd
697e53def8 2297: Doc update. 2024-02-12 17:12:59 +00:00
Nick Todd
fa08e53b15 2297: Convert NTP Client and Server to UDP 2024-02-12 17:01:53 +00:00
Chris McCarthy
add09a0280 #2205 - Tidied up interface creation and applied some suggestions from PR 2024-02-12 14:08:55 +00:00
Chris McCarthy
cfd64333e2 #2205 - Added wireless router tests and documentation. Refactored some code based on PR suggestions. 2024-02-12 12:31:08 +00:00
Czar Echavez
7beacfd95f #2258: missing some configuration items + added more tests 2024-02-12 11:41:55 +00:00
Czar Echavez
da92d74236 #2258: remove unnecessary ntp server check 2024-02-12 09:01:30 +00:00
Czar Echavez
66a3e8d02c Merge remote-tracking branch 'origin/dev' into feature/2258-dosbot-cannot-be-added-via-configuration-file 2024-02-12 08:57:47 +00:00
Chris McCarthy
9df7ceed3d #2205 - feat: Implement AirSpace and WirelessRouter for Enhanced Network Simulations
This commit introduces the AirSpace and WirelessRouter classes, expanding the PrimAITE's capabilities to simulate wireless networking environments. The AirSpace class manages wireless communications, ensuring seamless transmission across different frequencies. Meanwhile, the WirelessRouter class integrates both wired and wireless networking functionalities.
2024-02-10 23:44:08 +00:00
Chris McCarthy
a8c1e2b9d9 #2205 - Fixed ACLRule.is_permitted function by returning a bool that indicates whether the rule was matched or not to allow the AccessControlList to know whether to pay attention to the rule or not when it's iterating over them. 2024-02-10 21:32:13 +00:00
Chris McCarthy
58af58810d #2205 - Introduced a Firewall class for enhanced network security and control, extending Router functionalities. Updated ACLRule to support IP ranges via wildcard masking for refined traffic filtering. Includes documentation updates. 2024-02-09 23:29:06 +00:00
Christopher McCarthy
a960741f66 Merged PR 269: Refactor Network Infrastructure: Introduce ARP & ICMP Services and Network Interface Hierarchy
## Summary

This pull request encompasses a series of significant refactoring and enhancements aimed at improving the network simulation framework's architecture and functionality. Central to these changes is the introduction of ARP and ICMP as standalone services, the creation of a structured hierarchy for network interfaces, and a comprehensive overhaul of the testing suite to align with these new developments.

### Key Changes:

ARP and ICMP as Services: Transitioned ARP into a dedicated service, laying the groundwork for more sophisticated network interaction simulations. This shift involved substantial refactoring but has resulted in the successful integration of ARP requests within the network service architecture. Following this, ICMP was also encapsulated as a service, utilizing the session manager for packet transmission, thereby enhancing modularity and interaction within the network.

Network Interface Hierarchy: Introduced a hierarchy for network interfaces, differentiating between wired (NIC, SwitchPort) and wireless (WirelessNIC, WirelessAccessPoint) interfaces. This structure is further enriched with the Layer3Interface abstract base class, facilitating IP-based communications across both wired and wireless mediums.

PCAPs (Packet Capture) are now logged separately for inbound and outbound frames.

Test Suite Overhaul: Undertook a significant refactor of the testing suite, shifting to utilize the newly introduced Node subclasses (Computer, Server, Router, Switch) and the Network() class for node management and connection setup. This effort ensures that tests more accurately reflect the intended usage patterns and configurations within the simulation framework.

IPV4Address Validation and Conversion: Added a new IPV4Address type with pre-validation and auto-conversion capabilities, streamlining the handling of IPv4 addresses throughout the framework.

### Commit Highlights:

1. Commenced by integrating ARP as a service, facing initial challenges but achieving a functional ARP request capability as a milestone (Initial crack at getting ARP into a Service).
1. Progressed to fully integrate ARP service and link it with ICMP operations, marking a significant advancement in service-based network interactions (Lots more progress).
1. Began the process of encapsulating ICMP within the service model, necessitating further adjustments and test fixes (Initial work has been done on moving ICMP into services).
1. Completed the ICMP service integration, enhancing PCAP logging for inbound and outbound frames, and began addressing test suite discrepancies (ICMP now working as a service).
1. Implemented a broad refactor of the base network model to introduce a clear network interface hierarchy and started troubleshooting routing tests affected by ARP integration issues (Big refactor of base).

### Conclusion:

These changes collectively represent a leap forward in the framework's architecture, laying a robust foundation for future enhancements and ...
2024-02-09 12:50:58 +00:00
Czar Echavez
d1c3f891bf #2258: moving applications to application types - more tests 2024-02-09 11:41:06 +00:00
Chris McCarthy
6b3829dc48 #2248 - Removed redundant Union from single type params 2024-02-09 11:37:47 +00:00
Chris McCarthy
cceb6208e0 #2248 - Reset the auto save pcap and syslog to False 2024-02-09 11:09:44 +00:00
Chris McCarthy
2518a42604 #2248 - Dropped old router_arp.py module. Fixed the ICMP codes as per IANA (https://www.iana.org/assignments/icmp-parameters/icmp-parameters.xhtml) 2024-02-09 11:03:48 +00:00
Chris McCarthy
bebfbd53be #2248 - MAde tests use new way of accessing network interfaces by their port number 2024-02-09 10:30:39 +00:00
Chris McCarthy
0acd9a2938 #2248 - Removed redundant code and added more documentation from PR suggestions 2024-02-09 10:27:22 +00:00
Chris McCarthy
a036160515 #2248 - Enhances the PrimAITE documentation, covering the Node, network interfaces, Session Manager, Software Manager, PCAP service, SysLog functionality, and network devices like Routers, Switches, Computers, and Switch Nodes. It details their roles, workflows, and integration within the simulation, focusing on frame processing, software management, and logging. The documentation also clarifies the frame reception process, including port checks and application-level dispatching, ensuring a thorough understanding of network operations within the simulation 2024-02-08 22:37:21 +00:00
Czar Echavez
0590f956e3 #2258: ntp client should not request if ntp server is not set 2024-02-08 16:21:08 +00:00
Chris McCarthy
5eed467271 #2248 - synced wth dev 2024-02-08 16:15:57 +00:00
Czar Echavez
e1237625a5 Merge remote-tracking branch 'origin/dev' into feature/2258-dosbot-cannot-be-added-via-configuration-file 2024-02-08 16:03:41 +00:00
Czar Echavez
b31a9943d7 #2258: testing individual application install 2024-02-08 16:02:37 +00:00
Chris McCarthy
114fb8c077 #2248 - synced wth dev 2024-02-08 15:27:02 +00:00
Marek Wolan
c3ea06aeec Merged PR 268: Make build fail if tests fail 2024-02-08 15:21:19 +00:00
Marek Wolan
1a2298ebfb Merged PR 267: Make web status rewards based on web browser instead of web server.
## Summary
- added a second green agent on client 1
- added browser history
- added a reward component based on the most recent return code in browser history
- modified the UC2 notebook to adhere to new reward.
- (also there were some issues in example_config from a previous merge that I failed to notice prior)

## Test process
New unit tests. Ran uc2 notebook to check that it produces results aligning with what is described in the markdown cells.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Add second green agent and make rewards based on webbrowser

Related work items: #2247
2024-02-08 15:19:24 +00:00
Marek Wolan
9b350ddd6f Apply suggestions from code review. 2024-02-08 13:20:32 +00:00
Czar Echavez
1dcb9214af #2258: Added DoSBot to list of applications 2024-02-08 12:04:49 +00:00
Chris McCarthy
411f0a320f #2248 - Final run over all the docstrings after running pre-commit. All tests now working. Updated CHANGELOG.md. 2024-02-08 10:53:30 +00:00
Czar Echavez
a4b7878604 #2258: added NTPClient to system software + testing all installable software on client1 in config 2024-02-08 10:36:07 +00:00
Marek Wolan
ff17062e1c Vary start node of red agent. 2024-02-08 09:19:18 +00:00
Chris McCarthy
0c96fef3ec #2248 - All tests (bar the one config file test) now working. Still need to tidy up docstrings and some docs. Almost there 2024-02-07 23:05:34 +00:00
Chris McCarthy
5e25fefa14 #2248 - Further fixes. All router integration tests now passing. 2024-02-07 19:44:40 +00:00
Czar Echavez
f21ee857a7 #2258: setting up test that verifies game config parsing 2024-02-07 18:09:54 +00:00
Marek Wolan
b7ff520d55 make task fail if tests fail 2024-02-06 18:58:50 +00:00
Marek Wolan
c35c060448 Cosmetic changes based on PR feedback 2024-02-06 17:32:15 +00:00
Marek Wolan
e500eccaf7 Finish upgrading folder actions to work with names instead of uuids & get tests fixed 2024-02-06 16:58:08 +00:00
Marek Wolan
41bc932f52 Add reward test. 2024-02-06 15:05:44 +00:00
Marek Wolan
5b5b750d4d Add second green agent and make rewards based on webbrowser 2024-02-06 14:42:59 +00:00
Chris McCarthy
7bbfd564fb #2248 - Big refactor of base with all Network Interface subclasses created to allow for proper management of ports on devices as it was starting to get messy with the Router. Some routing tests still need fixing as ARP doesn't seem to be working properly 2024-02-05 08:44:10 +00:00
Chris McCarthy
a0253ce6c4 #2248 - TSome further fixess to ARP. Also refactored PCAP to log inbound and outbound frames separately 2024-02-02 17:14:34 +00:00
Chris McCarthy
cb002d644f #2248 - Tidying up the tests so that they use updated networks 2024-02-02 16:55:43 +00:00
Chris McCarthy
dc5aeede33 #2248 - ICMP now working as a service using the session manager for transmission. Now started to comb through the tests to fix anything up. 2024-02-02 16:20:15 +00:00
Marek Wolan
cfc254753f Merged PR 265: Make requests work with names instead of uuids
## Summary
Make actions work with object names instead of UUIDs. This makes it possible to define action spaces which can act on network elements that don't exist yet (as long as you can anticipate what they will be called).

## Test process
Many new tests. Old tests pass. Notebooks run.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [no time] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2137
2024-02-02 15:39:38 +00:00
Chris McCarthy
87d9d6da04 #2248 - Initial work has been done on moving ICMP into services. still tidying up to be done. Need to fix tests too. 2024-02-02 15:35:02 +00:00
Marek Wolan
4c6ae135cd Fix typos 2024-02-02 14:48:49 +00:00
Chris McCarthy
1964ab4635 #2248 - Lots more progress. Can now use ARP as a service properly. Also integrated the new ARP into the old ICMP which works. Next step is to more ICMP into services. 2024-02-01 23:05:14 +00:00
Chris McCarthy
9577f212f8 #2248 - Initial crack at getting ARP into a Service. Lots of refactoring has been done. It's a mess at the minute, but I can successfully send an ARP request so committing as a successful point in time 2024-02-01 22:19:55 +00:00
Marek Wolan
c163fb37ea Update request system docs. 2024-02-01 11:19:42 +00:00
Marek Wolan
261423bc78 Update changelog 2024-01-31 13:54:15 +00:00
Marek Wolan
83db5b1eb5 Fix node file delete action 2024-01-31 13:50:20 +00:00
Marek Wolan
41a7f83887 Add file scan test 2024-01-31 13:29:46 +00:00
Marek Wolan
d6a83fd1fb Update action tests to use name, not uuid 2024-01-31 11:55:38 +00:00
Marek Wolan
6aa6383fb7 Fix broken test configs 2024-01-31 11:44:56 +00:00
Marek Wolan
9f993dda57 Fix test config discrepancies 2024-01-31 10:48:40 +00:00
Marek Wolan
0dbaa66aa3 Merge remote-tracking branch 'origin/dev' into feature/2137-refactor-request-api 2024-01-31 10:05:09 +00:00
Marek Wolan
0c3304b1fd Merged PR 263: Several hotfixes
## Summary
Hotfixes from 3.0.0b4, b5, b6. These have all gone thru the PR process already we just need to sync dev back.

## Test process
Merge conflicts resolved and all automated tests pass.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [~] updated the **documentation** if this PR changes or adds functionality
- [~] written/updated **design docs** if this PR implements new functionality
- [~] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2161, #2173, #2174, #2175, #2176, #2179, #2208, #2218, #2219, #2220
2024-01-30 15:18:21 +00:00
Marek Wolan
def52f94e3 Add docstrings and update typos 2024-01-30 09:56:16 +00:00
Marek Wolan
bea72aa6a9 Fix ftp client connection list 2024-01-29 12:28:44 +00:00
Marek Wolan
555802baaa Merge remote-tracking branch 'origin/dev' into dev-v3.0.0b6 2024-01-29 10:26:28 +00:00
Marek Wolan
2ba05e7348 Fixed being unable to specify all addresses in acl rule 2024-01-25 15:17:09 +00:00
Marek Wolan
0056bfddee Bump version to 3.0.0b6 2024-01-25 14:59:24 +00:00
Marek Wolan
5a9eaeb185 Update the readme 2024-01-25 14:59:00 +00:00
Marek Wolan
a3a7d11ff7 Merged PR 261: Make sure notebook images get copied
Just made sure that notebook images get copied to user notebook directory.
2024-01-25 15:24:38 +00:00
Marek Wolan
51be271928 Merged PR 260: Beta 6 Fixes
Please run some of these changes locally. Read the notebook, check that it makes sense, and run the code cells to see if they produce the result you expect.

## Summary
Apologies that all these fixes are part of 1 massive PR instead of individual PRs. I thought it was going to be a quick job and it spiralled out of control.

Changes:
- Fixed a bug where ACL rules were not resetting on episode reset.
- Fixed a bug where blue agent's ACL actions were being applied against the wrong IP addresses
- Fixed a bug where deleted files and folders did not reset correctly on episode reset.
- Fixed a bug where service health status was using the actual health state instead of the visible health state
- Fixed a bug where the database file health status was using the incorrect value for negative rewards
- Fixed a bug preventing file actions from reaching their intended file
- Made database patch correctly take 2 timesteps instead of being immediate
- Made database patch only possible when the software is compromised or good, it's no longer possible when the software is OFF or RESETTING
- Temporarily disable the blue agent file delete action due to crashes. This issue is resolved in another branch that will be merged into dev soon.
- Fix a bug where ACLs were not showing up correctly in the observation space.
- Added a recap of agent actions to the `info` output of `step()`
- Added a notebook which explains UC2, demonstrates the attack, and shows off blue agent's action space, observation space, and reward function.

## Test process
New notebook verifies end-to-end UC2 functionality.

## Checklist
- [y] PR is linked to a **work item**
- [y] **acceptance criteria** of linked ticket are met
- [y] performed **self-review** of the code
- [~] written **tests** for any new functionality added with this PR
- [y] updated the **documentation** if this PR changes or adds functionality
- [n] written/updated **design docs** if this PR implements new functionality
- [y] updated the **change log**
- [y] ran **pre-commit** checks for code style
- [y] attended to any **TO-DOs** left in the code

Related work items: #2208, #2218, #2219, #2220
2024-01-25 15:15:48 +00:00
Marek Wolan
7f996ca16a Make sure notebook images get copied 2024-01-25 14:52:48 +00:00
Marek Wolan
4b98c1f630 Update uc2 notebook 2024-01-25 14:43:49 +00:00
Marek Wolan
73a75c497b Fix test 2024-01-25 13:13:50 +00:00
Marek Wolan
e7aac754a0 Update the changelog 2024-01-25 12:38:28 +00:00
Marek Wolan
99723b6578 Update notebook with more images. 2024-01-25 12:33:18 +00:00
Marek Wolan
28acb5dcae Populate step info in environment, and finish notebook 2024-01-25 12:04:09 +00:00
Marek Wolan
0a65f32adf Fix ACL observations 2024-01-25 09:27:08 +00:00
Marek Wolan
88c1d16f11 Fix Router acl not clearing 2024-01-23 14:34:05 +00:00
Marek Wolan
8e19e05f57 Fix acl actions for blue agent. 2024-01-21 17:29:19 +00:00
Marek Wolan
42d00e0440 Fix issue where file deleted flag wouldn't be reset 2024-01-21 16:33:51 +00:00
Marek Wolan
7d218c5201 bump version 2024-01-15 10:31:13 +00:00
Marek Wolan
edc9772d0a Fix typo in database restore 2024-01-15 10:10:30 +00:00
Marek Wolan
728f80cc21 Temporarily disable file delete action 2024-01-15 09:48:14 +00:00
Marek Wolan
e0033de7b6 Fix folder reset 2024-01-12 14:54:55 +00:00
Marek Wolan
842e59f596 Database patch 2024-01-11 15:40:37 +00:00
Marek Wolan
ed5591caf8 Minor fix 2024-01-11 14:49:36 +00:00
Marek Wolan
63b9bc5bc6 3.0.0b5 2024-01-11 11:13:43 +00:00
Marek Wolan
40ad446ff2 Merged PR 257: Fix reward data type
Related work items: #2179
2024-01-11 11:07:01 +00:00
Marek Wolan
4d1c0d268e Fix reward data type 2024-01-11 11:05:55 +00:00
Marek Wolan
b11e4c8ccd update changelog 2024-01-11 11:05:00 +00:00
Marek Wolan
f283afc04a Merged PR 256: Align the database backup and corruption processes with IYak
## Summary
**Changed:**
- Copying a file via FTP also copies its health status
- The database automatically attempts to make a backup on step 1
- make the db file a property that is fetched by name from the file system instead of a handle to a file (bruh)
- fixed ftp server re-sending requests back to the client
- fix issue where links with >100% bandwidth cause the observation space to crash
- fix issue where starting a node didn't start services. (not sure how that one passed tests previously)

**To align with Yak:**
- database service removed from uc2 observation space
- sql attack affects the file health status instead of the service
- when the web server fails to fetch data, it goes into compromised state until a successful data fetch

## Test process
Notebooks

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2176
2024-01-11 10:54:25 +00:00
Marek Wolan
d2a2472e5f Apply bugfix 2151 2024-01-11 10:49:32 +00:00
Marek Wolan
e57c240b9b Apply cosmetic changes based on review. 2024-01-11 09:55:09 +00:00
Marek Wolan
2d1041e7b3 Fix final bugs 2024-01-10 18:38:37 +00:00
Marek Wolan
1505d08721 Fix backup issues and align with Yak 2024-01-10 18:04:48 +00:00
Marek Wolan
b34f2a5c8c Merged PR 253: Make observations use software health state visible instead of actual.
We already merged this change into dev, I just replicated it for b5.

Related work items: #2161, #2174
2024-01-10 13:53:05 +00:00
Marek Wolan
3486347566 Merged PR 252: Align Software health state enum with CAOS
Related work items: #2175
2024-01-10 13:52:46 +00:00
Marek Wolan
9fce9ceea4 Merged PR 255: Fix issue where red agent acted too early
## Fixed:
- data manipulation red agent now considers episode reset when calculating next action time
- Moved attack logic out of data manipulation bot `run` method into dedicated `attack` method, because `run` is triggered by episode reset logic. This means the attack no longer always happens at step 1 of every episode.

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [na] updated the **documentation** if this PR changes or adds functionality
- [na] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2173
2024-01-10 13:52:33 +00:00
Czar Echavez
62197fe72b Merged PR 254: #2151: remove changing of health_state_actual in actions and tests
## Summary
Removed the changing of health_state_actual from the actions - only few places where the health_state_actual is changed:
- compromised in specific scripted events
- set to good when started (if the state is still at UNUSED
- set to good after patching

## Test process
unit tests
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/254?_a=files&path=/tests/unit_tests/_primaite/_simulator/_system/_services/test_services.py

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2151: remove changing of health_state_actual in actions and tests

Related work items: #2151, #2166
2024-01-10 13:35:51 +00:00
Marek Wolan
9d06284edb Merge remote-tracking branch 'origin/dev-v3.0.0b5' into bugfix/2176-attack-observation-symptoms 2024-01-10 13:07:23 +00:00
Marek Wolan
66a42ebc69 Make database failure based on file status not service status 2024-01-10 13:06:48 +00:00
Czar Echavez
c985b8793d #2151 and #2166: added tests for application being unused + even more tests 2024-01-10 11:58:36 +00:00
Marek Wolan
b6e414bd70 Update changelog 2024-01-10 09:14:07 +00:00
Marek Wolan
b7cc940e9d Remove temporary print statements 2024-01-10 09:07:51 +00:00
Marek Wolan
e73783f6fa Fixed issue where data manipulation was always executing 2024-01-09 17:10:12 +00:00
Czar Echavez
a4d372d3eb #2151: utilise set_health_state method instead of directly changing software states 2024-01-09 16:29:40 +00:00
Czar Echavez
9eb0102069 Merge remote-tracking branch 'origin/dev' into bugfix/2151-service-status-set-to-overwhelmed-at-incorrect-actions 2024-01-09 15:29:49 +00:00
Czar Echavez
6fc4e15660 #2151: remove changing of health_state_actual in actions and tests 2024-01-09 15:18:31 +00:00
Marek Wolan
daa34385e5 Add agent reset for episodes 2024-01-09 14:53:15 +00:00
Marek Wolan
f2a496893c Bump VERSION 2024-01-09 14:33:24 +00:00
Marek Wolan
716bd626a5 Hide software health state until scan. 2024-01-09 14:29:23 +00:00
Marek Wolan
91addee09d Merged PR 248: Make observation flattening optional for agents.
## Summary
Same as other PR but this time we are merging into DEV.

The Proxy agent has a new config option, `flatten_obs`. If true, we use gymnasium flatten.

## Test process
Unit tests and inspection.

Related work items: #2143, #2154, #2161
2024-01-09 14:28:36 +00:00
Marek Wolan
82cd8780f9 Align Software health state enum with CAOS 2024-01-09 14:03:10 +00:00
Marek Wolan
5d89820a15 Apply PR review suggestions 2024-01-09 12:38:01 +00:00
Marek Wolan
7c0ff8e3f0 Add acl remove rule integration test. 2024-01-08 16:24:09 +00:00
Marek Wolan
534f84ccd1 Add action tests. 2024-01-08 13:29:17 +00:00
Marek Wolan
294c8b982f Add convenience method for router acl 2024-01-08 13:28:55 +00:00
Marek Wolan
27f70204ed Fix minor issues in actions 2024-01-08 13:28:34 +00:00
Christopher McCarthy
7c0ab1a19e Merged PR 243: #2139 - Implemented routing
## Summary
- Integrated the RouteTable into the Routers frame processing.
- Frames are now dropped when their TTL reaches 0

## Test process
Added five tests that check routing passes and fails with correct/incorrect route tables.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2139 - Implemented routing

Related work items: #2139
2024-01-08 11:17:16 +00:00
Marek Wolan
2f97dcb6f9 Merge remote-tracking branch 'origin/dev' into feature/2137-refactor-request-api 2024-01-08 10:39:24 +00:00
Chris McCarthy
8b43f6abe3 #2139 - updated docstring in send_arp_request function in base.py 2024-01-08 10:30:38 +00:00
Chris McCarthy
59d1a6668e #2139 - Updated the CHANGELOG.md with broadcast entry 2024-01-05 22:19:54 +00:00
Chris McCarthy
d2d628b676 #2139 - Fixed unicast and broadcast functionality properly 2024-01-05 22:11:37 +00:00
Chris McCarthy
ddf7fbf88b #2139 - Included a test that tests services over multi-hop routing. Added some PR suggestions around logging. 2024-01-05 15:27:10 +00:00
Marek Wolan
33f72db1cb Updated VERSION 2024-01-05 14:03:06 +00:00
Marek Wolan
0d07364669 Merged PR 246: Make flattening observation spaces optional.
## Summary
Simple change that gives the user an option to turn on/off observation space flattening.

## Test process
Confirmed that if the new setting is set to 'false', SB3 complains about composite spaces, but RL agents notebook works fine.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Make flattening observation spaces optional.

Related work items: #2161
2024-01-05 13:50:22 +00:00
Marek Wolan
d038f63fda Clear notebook output 2024-01-05 13:11:47 +00:00
Marek Wolan
f75c10aafb Make flattening observation spaces optional. 2024-01-05 13:10:49 +00:00
Marek Wolan
b8312b8a2b Merged PR 244: Make pcap and sys logging optional (beta 4)
## Summary
Very straightforward change. Just added some config parameters to make pcap and sys logs optional. These options default to false.

## Test process
Verified that both options produce the desired result by running a primaite session with logs enabled and disabled in the config. Unit tests still pass.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2143, #2154
2024-01-05 12:40:13 +00:00
Marek Wolan
4266618ba5 Make pcap logs and sys logs optional 2024-01-05 11:25:57 +00:00
Marek Wolan
81734e7ad3 Merged PR 241: Add service patch and fix apply timestep issues.
## Summary
Replaces Action ID 13 in UC2 with SERVICE.PATCH.
Fixes issue where apply_timestep was not happening at all
Fixes issue where file actions were not correctly being forwarded

## Test process
All pytests passing including a new one for service patch.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2143
2024-01-05 09:58:16 +00:00
Marek Wolan
bc08db6b7e Merged PR 240: Add service patch action and fix some clangers.
## Summary
- Replaces Action ID 13 in UC2 with SERVICE.PATCH.
- Fixes issue where `apply_timestep` was not happening at all
- Fixes issue where file actions were not correctly being forwarded

## Test process
Unit tests passing
Running primaite session works without errors
Ran primaite session on UC2 in debug mode and inspected that correct changes are being reflected after actions are applied.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2143
2024-01-05 09:56:33 +00:00
Marek Wolan
7d81b1cb07 Merged PR 242: Change software describe state keys
## Summary
Tiny change to change the names of the keys in `software.describe_state()`
Also fixed the observation to use the visible health state instead of the actual health state (and therefore the blue agent will actually have to scan to learn the health state)

## Test process
Unit tests pass

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Change software describe state keys

Related work items: #2160
2024-01-04 14:50:37 +00:00
Marek Wolan
ec7723732b Merge remote-tracking branch 'origin/dev' into feature/2137-refactor-request-api 2024-01-04 14:40:20 +00:00
Marek Wolan
bc367222a8 Change software describe state keys 2024-01-04 12:55:46 +00:00
Marek Wolan
528e3b22a9 Add integration tests 2024-01-04 12:47:35 +00:00
Marek Wolan
25c8ec2ec9 Add skeleton for action integration and unit tests 2024-01-03 18:19:10 +00:00
Marek Wolan
48f1d13fd8 Minor refactor and add comment 2024-01-03 16:23:44 +00:00
Marek Wolan
3adf1f9f6a bump version 2024-01-03 14:49:40 +00:00
Marek Wolan
2aa7c18ad3 Merge remote-tracking branch 'origin/dev' into bugfix/2143-node-service-patch-main 2024-01-03 14:43:46 +00:00
Chris McCarthy
ade5f133d0 #2139 - Implemented routing 2023-12-22 10:31:11 +00:00
Marek Wolan
2135bdcd10 Add unit test 2023-12-21 16:08:09 +00:00
Marek Wolan
fa585168de update marl config with service patch bugfix 2023-12-21 15:10:23 +00:00
Marek Wolan
96f8435c5e Add service patch and fix other bugs 2023-12-21 15:07:41 +00:00
Marek Wolan
e33f74e3f2 bump version to 3.0.0b3dev 2023-12-21 09:28:14 +00:00
Marek Wolan
a1dcfa291b Update test configs with new action spec 2023-12-21 09:25:54 +00:00
Marek Wolan
a798d262b8 use names instead of uuids for requests 2023-12-18 14:03:47 +00:00
Marek Wolan
ffeb04d6ed Merged PR 235: Refactor describe_state to use name/hostname instead of UUID as primary key
## Summary
- Refactor Simulator state to use service/application name instead of UUID, and node hostname instead of UUID.
- Refactor observations to read the hostname/name instead of UUID.
- Refactor rewards as well.
- Refactor configs to specify name instead of reference that will be translated to UUID.

## Test process
Existing unit tests pass. Inspected the printout from running 'describe_state' on arcd_uc2_network' to verify that names are used to report state.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [na] written **tests** for any new functionality added with this PR
- [na] updated the **documentation** if this PR changes or adds functionality
- [x] written/updated **design docs** if this PR implements new functionality
- [na] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2131
2023-12-15 16:02:29 +00:00
Nick Todd
360a86188c Merged PR 233: NTP server and client
## Summary
The NTP Server and Client are created as two separate classes NTPServer and NTPClient which define the methods used to send and receive time data. A set of classes used in the sending and receiving of requests and data is in ntp.py. A single file, test_ntp_client_server.py is used to run the unit tests.
The changes have no impact on other parts of the codebase.

## Test process
Created simple two node network representing NTP server and client. Created NTP server and client objects and client requests and receives date/time from server.

## Checklist
- [Y] PR is linked to a **work item**
- [Y] **acceptance criteria** of linked ticket are met
- [Y] performed **self-review** of the code
- [Y] written **tests** for any new functionality added with this PR
- [Y] updated the **documentation** if this PR changes or adds functionality
- [N] written/updated **design docs** if this PR implements new functionality
- [Y] updated the **change log**
- [Y] ran **pre-commit** checks for code style
- [N] attended to any **TO-DOs** left in the code

Related work items: #2041, #2042
2023-12-15 14:26:17 +00:00
Marek Wolan
7a1abb1ef8 Minor fixes based on code review 2023-12-15 13:09:50 +00:00
Marek Wolan
495d847a71 Use service and app name for node software requests 2023-12-15 13:04:18 +00:00
Nick Todd
2d892d4a5a 2041: Tidy up test comments 2023-12-15 10:52:46 +00:00
Nick Todd
0cfd525ab8 2041: change comparison operator in test 2023-12-15 10:14:35 +00:00
Marek Wolan
a16028d10c Merge remote-tracking branch 'origin/feature/2131-refactor-describe-state' into feature/2137-refactor-request-api 2023-12-15 10:10:39 +00:00
Nick Todd
fab39b1506 Merge branch 'dev' into feature/2041_2042-Add-NTP-Services 2023-12-15 09:50:19 +00:00
Marek Wolan
6a80f4cc77 Make game layer work with new state api 2023-12-14 14:04:43 +00:00
Marek Wolan
1ec7df1170 Change describe_state to use names instead of uuids 2023-12-14 11:19:32 +00:00
Czar Echavez
0aeaeaa60f Merged PR 234: #2059: Denial of Service Bot
## Summary
- Moved DataManipulationBot into red applications - these are applications, not services
- moved the connection handling from Service base class to the IOSoftware base class
  - Applications and Services can track the connections they make
  - increased default max sessions to 100
  - made sure the services/applications that are dependent on connections use the IOSoftware connections
- DoSBot follows some sort of kill chain, although at the moment it just:
  - runs a port scan with a 10% success chance (by default)
  - runs a DoS attack that fills a service's max sessions

## Test process
unit test in https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/234?path=/tests/unit_tests/_primaite/_simulator/_system/_applications/_red_applications/test_dos_bot.py&_a=files

integration test in https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/234?path=/tests/integration_tests/system/red_applications/test_dos_bot_and_server.py&_a=files

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2059
2023-12-14 10:16:34 +00:00
Czar Echavez
592e1a3610 #2059: apply suggestions from PR + adding another test that checks for dos affecting green agent 2023-12-13 11:56:25 +00:00
Nick Todd
f7b5c8ae2f 2041: Remove NTPRequest class (review comment) 2023-12-13 10:34:52 +00:00
Czar Echavez
f0be77c79b #2059: configure missing configurable items 2023-12-12 17:20:31 +00:00
Nick Todd
e620771c8d 2041: Remove IP address from NTP client (review comment) 2023-12-12 17:08:11 +00:00
Czar Echavez
4f79d2ad36 #2059: moved connection handling from Service to IOSoftware + changes that now utilise connections from IOSoftware + dos bot attacking now works + tests 2023-12-12 17:01:03 +00:00
Czar Echavez
1b124035a1 Merge remote-tracking branch 'origin/dev' into feature/2059-denial-of-service-bot-post-beta-2 2023-12-11 08:57:59 +00:00
Czar Echavez
cd5ed48b00 #2059: implementing the service connections limit 2023-12-08 17:07:57 +00:00
Czar Echavez
094e89fff1 #2059: Renamed Red service to red application and moved the datamanipulation bot to the red application folder 2023-12-08 14:54:29 +00:00
Nick Todd
c3015b7f0e Merge branch 'dev' into feature/2041_2042-Add-NTP-Services 2023-12-07 14:55:01 +00:00
Nick Todd
44ada941e6 2041: Reinstate test for ntp_server failure 2023-12-07 14:22:27 +00:00
Marek Wolan
e93fb85672 Merged PR 232: Allow cancelling jobs
## Summary
Fix the azure build pipeline job conditions to correctly stop the job if we cancel the build.

Related work items: #2103
2023-12-07 13:49:08 +00:00
Marek Wolan
385a4997ce New parameter for publishing code coverage 2023-12-07 10:35:50 +00:00
Nick Todd
50a6e17fab 2041: Make NTP work with TCP transport layer 2023-12-06 16:42:28 +00:00
Nick Todd
12ede2329b 2041: Add network config and pytest fixture 2023-12-06 16:41:10 +00:00
Marek Wolan
75f732dacf bump version to 3.0.0b2 2023-12-04 13:08:13 +00:00
Marek Wolan
30b0f12a8d Allow cancelling jobs 2023-12-04 11:34:17 +00:00
Nick Todd
39694fcec2 Merge branch 'dev' into feature/2041_2042-Add-NTP-Services 2023-12-04 11:23:35 +00:00
Christopher McCarthy
4cc2674745 Merged PR 229: Step metadata json output
## Summary
- Added step metadata json file dumps to the environments. Fixed serialization issues in the Switch and ACLRule classes.

## Test process
Nothing outside of a manual inspection for now.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2085
2023-12-04 10:47:09 +00:00
Marek Wolan
01b9e661ce Clean up print statements. 2023-12-04 10:45:33 +00:00
Marek Wolan
a5c4f7797d Make saving step metadata optional 2023-12-04 10:42:20 +00:00
Marek Wolan
8ea9db2d34 Merge remote-tracking branch 'origin/dev' into feature/2085-dump_describe_state 2023-12-04 10:38:41 +00:00
Marek Wolan
2203877302 Merged PR 231: Add docpage for config
## Summary
*Replace this text with an explanation of what the changes are and how you implemented them. Can this impact any other parts of the codebase that we should keep in mind?*

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Add docpage for config

Related work items: #2088
2023-12-04 10:17:56 +00:00
Marek Wolan
9fa6f0b7ab Formatting improvements in cfg doc page 2023-12-04 10:16:29 +00:00
Marek Wolan
ec8e6b5ff7 Merged PR 228: Fix annoying Ray issues
## Summary
Fix ray episode issues. Allow ray to manage its environment fully - this fixes the perma-zero reward.

## Test process
Running notebooks and primaite sessions.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2095
2023-12-04 10:10:10 +00:00
Czar Echavez
6ca28f5d17 Merged PR 230: #2084: add coverage fail condition
## Summary
Added a fail condition for coverage

## Test process
n/a

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2084: add coverage fail condition

Related work items: #2084
2023-12-04 10:02:24 +00:00
Marek Wolan
ba3d37316b Apply suggestions from review 2023-12-04 09:21:47 +00:00
Marek Wolan
de5fead9a4 Add docpage for config 2023-12-04 09:14:20 +00:00
Czar Echavez
8f063aa339 #2084: apply previous PR suggestions 2023-12-04 09:07:42 +00:00
Czar Echavez
534d4f96f3 #2084: add coverage fail condition 2023-12-04 08:58:03 +00:00
Czar Echavez
f55e18c4c8 Merged PR 225: #2084: Adding more tests
## Summary
Added tests and integrating code coverage checks - current target set to 80% of code to be covered by tests

## Test process
The pull request is literally to add more tests (lol)

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2084: beginning the introduction of code coverage + adding tests to try to meet the 80% code coverage target

Related work items: #2084
2023-12-03 14:55:20 +00:00
Marek Wolan
105763971d Merge 'origin/dev' into bugfix/episode-length-and-rewards 2023-12-03 14:49:34 +00:00
Czar Echavez
1d5337153b #2084: fix pr autocancel 2023-12-02 19:46:04 +00:00
Czar Echavez
1cc0020381 #2084: only upload copy of html report once 2023-12-02 19:38:45 +00:00
Czar Echavez
53f43dde0d #2084: cleaning up 2023-12-02 19:07:10 +00:00
Czar Echavez
060a46e251 #2084: more debugging 2023-12-02 18:44:27 +00:00
Czar Echavez
7b21f390c0 #2084: more debugging 2023-12-02 15:31:36 +00:00
Czar Echavez
e48f0a6d68 #2084: more debugging 2023-12-02 14:41:45 +00:00
Czar Echavez
2123fbb8f4 #2084: more debugging 2023-12-02 14:17:34 +00:00
Czar Echavez
47287ad1eb #2084: fixing 0% coverage 2023-12-02 13:44:39 +00:00
Czar Echavez
6ecb47f5ae #2084: debug coverage file 2023-12-02 01:19:38 +00:00
Czar Echavez
31c4287f46 #2084: applying github example fix to pipeline 2023-12-02 01:05:13 +00:00
Chris McCarthy
cc04efb31d #2085 - Added step metadata json file dumps to the environments. Fixed serialization issues in the Switch and ACLRule classes. 2023-12-01 16:37:58 +00:00
Czar Echavez
af8401440d #2084: using v2 publish codecov 2023-12-01 16:29:05 +00:00
Czar Echavez
88f74d9eec #2084: remove debugs and comment out the uploading of report 2023-12-01 16:08:02 +00:00
Czar Echavez
8a4978cf96 #2084: remove 80% requirement - causes tests to fail 2023-12-01 15:59:34 +00:00
Chris McCarthy
32c13e06f6 Merge remote-tracking branch 'devops/bugfix/episode-length-and-rewards' into feature/2085-dump_describe_state 2023-12-01 15:58:32 +00:00
Chris McCarthy
008efa1e9d Merge remote-tracking branch 'devops/bugfix/episode-length-and-rewards' into feature/2085-dump_describe_state 2023-12-01 15:55:22 +00:00
Czar Echavez
9a8350fd8f #2084: artifact the report 2023-12-01 15:49:20 +00:00
Marek Wolan
3e3fd89618 Minor string fix 2023-12-01 15:41:10 +00:00
Marek Wolan
eeedea2eff Make more friendly user outputs when training SB3 2023-12-01 15:36:07 +00:00
Czar Echavez
f0327da9b6 #2084: remove 80% requirement - causes tests to fail 2023-12-01 15:33:43 +00:00
Czar Echavez
6598c66da1 #2084: i hope no one is keeping an eye on these atrocious commit messages 2023-12-01 15:18:38 +00:00
Czar Echavez
294f57c292 #2084: find paths with wildcard 2023-12-01 15:08:42 +00:00
Marek Wolan
321d1f7219 Fix rllib marl problems 2023-12-01 14:58:34 +00:00
Czar Echavez
d6fedf0079 #2084: maybe pointing to different source might help 2023-12-01 14:58:22 +00:00
Czar Echavez
656cb03b16 #2084: print content of coverage.xml 2023-12-01 14:34:42 +00:00
Czar Echavez
4f57403751 #2084: debug pipeline 2023-12-01 13:52:06 +00:00
Czar Echavez
c21a52d3f7 #2084: debug pipeline 2023-12-01 13:26:27 +00:00
Czar Echavez
1dbea3041a #2084: add files + remove extra slash 2023-12-01 12:46:12 +00:00
Czar Echavez
738aeed0a5 #2084: debug pipeline 2023-12-01 12:05:12 +00:00
Czar Echavez
6430a7588d #2084: debug pipeline 2023-12-01 11:38:34 +00:00
Czar Echavez
74b8f58b36 #2084: debug pipeline 2023-12-01 11:22:30 +00:00
Marek Wolan
3642e87eda Remove distracting debug print statements 2023-12-01 11:07:57 +00:00
Czar Echavez
4ad93b0961 #2084: publish coverage report + more verbose test output 2023-12-01 10:32:48 +00:00
Czar Echavez
f1c706631f #2084: publish coverage report 2023-12-01 10:02:12 +00:00
Nick Todd
a073038ec0 #2085: Get enum value data 2023-12-01 09:52:31 +00:00
Czar Echavez
3eb9a5ef1c #2084: publish coverage report 2023-12-01 09:13:17 +00:00
Czar Echavez
c2f7d737f7 #2084: missed change to logger 2023-11-30 21:11:35 +00:00
Czar Echavez
5b50213626 #2084: upload reports - debug 2023-11-30 19:58:35 +00:00
Czar Echavez
4c1bb7d786 #2084: upload reports - debug 2023-11-30 19:43:23 +00:00
Czar Echavez
4572afac69 #2084: upload reports - debug 2023-11-30 19:34:18 +00:00
Czar Echavez
d60250e1b8 #2084: upload reports - azure cannot find things 2023-11-30 19:21:11 +00:00
Czar Echavez
bfb631f88c #2084: upload reports - use default htmlcov location 2023-11-30 18:45:27 +00:00
Czar Echavez
9d4e564e0e #2084: upload reports 2023-11-30 18:32:03 +00:00
Czar Echavez
423436c3ad #2084: testing webbrowser requesting database service user data via web server 2023-11-30 16:32:31 +00:00
Nick Todd
10d4b61c73 Merge branch 'feature/2087_Full-reset-functionality' into feature/2085-dump_describe_state 2023-11-30 16:16:44 +00:00
Nick Todd
5cd69f343f #2085: generate time based log files 2023-11-30 16:11:44 +00:00
Czar Echavez
d9de57757f #2084: more tests + remove concurrency in test to make sure coverage works 2023-11-30 15:47:31 +00:00
Czar Echavez
3cf21e4015 #2084: change all instances of retrieving software from software['software_name'] to software.get() + adding some tests for describe state 2023-11-30 13:49:37 +00:00
Czar Echavez
7c1ffb5ba1 #2084: change all instances of retrieving software from software['software_name'] to software.get() + adding some tests for describe state 2023-11-30 13:48:57 +00:00
Czar Echavez
349f9dee38 Merge remote-tracking branch 'origin/dev' into feature/2084-add-more-tests-to-make-primaite-more-robust 2023-11-30 09:29:34 +00:00
Marek Wolan
deea09f88d Merged PR 226: Episode Reset
## Summary
After initial setup, get sim components to save their state. Then, during episode reset, set attributes to original values.

## Test process
Test script that checks for web client ability to resolve requests after a reset. Formal tests don't exist.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1859, #2087
2023-11-30 09:10:06 +00:00
Marek Wolan
9d39458ef3 Deleted sandbox.py 2023-11-29 22:30:12 +00:00
Czar Echavez
b2a52b2ec0 #2084: created a fixture that we can use to test things at a non end to end level 2023-11-29 16:31:21 +00:00
Marek Wolan
ac2f7ba757 Fix web browser tests. 2023-11-29 14:33:52 +00:00
Marek Wolan
a16116a688 Fix file system reset error 2023-11-29 13:22:15 +00:00
Marek Wolan
05d62a956d Fix software reset issues 2023-11-29 13:18:38 +00:00
Chris McCarthy
bf73cc2eb7 #1859 - Re-ordered the node reset function again 2023-11-29 13:45:34 +00:00
Nick Todd
3ab911f6af #2085: Change output file type 2023-11-29 11:41:02 +00:00
Nick Todd
957702fa5d #2085: Remove JSON file handling 2023-11-29 10:10:23 +00:00
Czar Echavez
19d534395b #2084: beginning the introduction of code coverage + adding tests to try to meet the 80% code coverage target 2023-11-29 01:28:40 +00:00
Nick Todd
28da7bb648 #2085: Merge branch 'feature/2087_Full-reset-functionality' into feature/2085-dump_describe_state 2023-11-28 16:19:16 +00:00
Chris McCarthy
94f8a45a4d #1859 - Re-ordered the node reset function 2023-11-28 15:29:13 +00:00
Nick Todd
e63727fa3a #2058 - Fix up log file path 2023-11-28 14:12:01 +00:00
Nick Todd
2eeb896099 #2085 - Dump describe_state output to JSON file. 2023-11-28 12:16:04 +00:00
Chris McCarthy
9a4855e7bd #1859 - Added the call to file system reset 2023-11-28 11:58:09 +00:00
Marek Wolan
da955038f5 Merged PR 224: Enhanced probabilistic red agent.
## Summary
This is @<Jake Walker> 's and @<Christopher McCarthy> 's PR.

- The red agent now performs attacks in stages.
- There is now a random probability of each stage being successfully run.
- There are start settings for the red agent which set the start time, frequency and variance for both.

## Test process
Additional unit tests have been added to test new functionality.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1859
2023-11-28 10:47:39 +00:00
Marek Wolan
2de1d02c48 Fix app install logic 2023-11-27 22:55:00 +00:00
Marek Wolan
3df3e113d1 Change data manipulation test to use the right func 2023-11-27 22:24:30 +00:00
Marek Wolan
b0399195bb Fix software manager usage in uc2 network func 2023-11-27 22:20:44 +00:00
Marek Wolan
21b865d8a8 Merge origin/dev into feature/1859 2023-11-27 22:13:42 +00:00
Chris McCarthy
517f99b04b #1859 - Added the call to file system reset 2023-11-28 09:45:45 +00:00
Chris McCarthy
37663c941d #1859 - Added route table reset, still not working 2023-11-28 00:51:48 +00:00
Chris McCarthy
39dfbb741f #1859 - Made some fixes to resets. Still an issue with the Router reset. 2023-11-28 00:21:41 +00:00
Chris McCarthy
58e9033a4c #1859 - First pass at an implementation of the full reset method. Will now start testing... 2023-11-27 23:01:56 +00:00
Nick Todd
95f6cf6691 Merged PR 221: Version 3 beta 2 doc changes
## Summary
*Replace this text with an explanation of what the changes are and how you implemented them. Can this impact any other parts of the codebase that we should keep in mind?*

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [Y] PR is linked to a **work item**
- [Y] **acceptance criteria** of linked ticket are met
- [Y ] performed **self-review** of the code
- [N] written **tests** for any new functionality added with this PR
- [Y] updated the **documentation** if this PR changes or adds functionality
- [N] written/updated **design docs** if this PR implements new functionality
- [N] updated the **change log**
- [Y] ran **pre-commit** checks for code style
- [N] attended to any **TO-DOs** left in the code

Related work items: #2068
2023-11-27 21:35:37 +00:00
Czar Echavez
58a84da7af Merged PR 217: #2064: fix for services still running after node is turned off
## Summary
- Added a check for services so that they should not do anything unless the node it is installed in is turned on

## Test process
- Added tests everywhere

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2064
2023-11-27 20:23:37 +00:00
Chris McCarthy
ae5046b8fb #1859 - As disccused 2023-11-27 17:05:12 +00:00
Nick Todd
40d596c373 Merge branch 'dev' into feature/2041_2042-Add-NTP-Services 2023-11-27 15:07:06 +00:00
Nick Todd
6fd37a609a #2068: code review comments. 2023-11-27 14:38:59 +00:00
Chris McCarthy
c3bb78c5a3 Merge remote-tracking branch 'devops/feature/1859-red-agent-marek' into feature/1859-red-agent-marek 2023-11-27 13:50:41 +00:00
Chris McCarthy
4d4a578555 #1859 - Integrated the runtime execution for web client. Added in the webclient application execution action. Now fixing http status code issues. 2023-11-27 13:47:59 +00:00
Marek Wolan
89cbc08352 Apply suggestions from code review 2023-11-27 13:28:11 +00:00
Marek Wolan
43fee23600 Fix incorrect order in session from config 2023-11-27 11:55:58 +00:00
Czar Echavez
299729d5b4 #2064: documentation EVERYWHERE 2023-11-27 11:38:03 +00:00
Marek Wolan
84bd9b1bff Merge remote-tracking branch 'origin/dev' into feature/1859-red-agent-marek 2023-11-26 23:45:10 +00:00
Marek Wolan
ece9b14d63 Resolve merge conflicts 2023-11-26 23:29:14 +00:00
Czar Echavez
cd49f1eb85 #2064: Apply PR suggestions 2023-11-25 13:19:32 +00:00
Jake Walker
cbdaa6c444 Move data manipulation agent into individual file 2023-11-24 16:32:04 +00:00
Jake Walker
afce6ca515 Update changelog for data manipulator bot & agent 2023-11-24 16:04:11 +00:00
Jake Walker
08c1b3cfb9 Fix code style issues 2023-11-24 15:56:04 +00:00
Jake Walker
e62ca22cb7 Fix data manipulation bot tests 2023-11-24 15:53:07 +00:00
Nick Todd
2ce27080a6 #2068: Remove reference to ARCD GATE 2023-11-24 15:48:13 +00:00
Nick Todd
76b3a5ab6f #2068: Updated version 2023-11-24 15:43:52 +00:00
Nick Todd
a2a27697a3 Merge branch 'dev' into feature/2068-Validate_documentation 2023-11-24 15:27:33 +00:00
Nick Todd
355cbedbae #2068: Further typo and formatting changes. 2023-11-24 15:17:08 +00:00
Czar Echavez
330e87698e Merge remote-tracking branch 'origin/dev' into bugfix/2064-software-continues-running-after-node-is-turned-off 2023-11-24 15:16:25 +00:00
Czar Echavez
b7b718f25d #2064: added a method that checks if the class can perform actions and added it where necessary + tests everywhere 2023-11-24 15:15:56 +00:00
Jake Walker
c5cfbb825a Fix database client connect method 2023-11-24 15:15:45 +00:00
Jake Walker
e6f75f8b32 Improve data manipulation bot documentation 2023-11-24 15:15:24 +00:00
Marek Wolan
5a03db9ff3 Merged PR 219: Skip slow tests for now.
Related work items: #1971
2023-11-24 14:58:00 +00:00
Marek Wolan
e609f8eb50 Fix misconfiguration in uc2 config and session 2023-11-24 14:56:17 +00:00
Marek Wolan
82116e6c92 Merged PR 218: Get Ray agents working
## Summary
- PrimaiteSession class was separated into 'game' and 'session' classes. Game manages the interfacing of agents and the simulator. Session manages the environment, IO, and RL algorithms, as well as the game.
- Add ray single and multi agent support
- Add environments that can be interacted with directly so that users who want to manually configure RL policies can do so.
- Add notebooks demonstrating manual environment interfacing.

## Test process
Unit tests added, all pass. Example notebooks run to demonstrate compatibility with SB3 and Ray.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

![PrimAITE High Level Design - Page 1 (4).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/218/attachments/PrimAITE%20High%20Level%20Design%20-%20Page%201%20%284%29.png)

Related work items: #1970, #1971
2023-11-24 13:57:54 +00:00
Marek Wolan
64c7dd3c84 Skip slow tests for now. 2023-11-24 12:03:46 +00:00
Chris McCarthy
dfb08b8cf3 #1859 - DB query now returns false if the query isn't ran due to the node being off 2023-11-24 11:52:33 +00:00
Nick Todd
dd351f8143 #2068: Remove duplicated index entries. 2023-11-24 11:21:25 +00:00
Jake Walker
ff8b773c10 Database Manipulation Bot bug fixes 2023-11-24 11:10:34 +00:00
Marek Wolan
d8975078b3 Fix game reset test. 2023-11-24 10:50:10 +00:00
Jake Walker
4e104a4d99 Update data manipulation bot 2023-11-24 10:33:19 +00:00
Jake Walker
178d911be0 Update data manipulation bot 2023-11-24 10:05:36 +00:00
Jake Walker
92dabe59f7 Fix data manipulation bot configuration 2023-11-24 10:04:19 +00:00
Marek Wolan
bfd5f054dc Merge 'origin/dev' into feature/1971-ray-agents-2 2023-11-24 09:50:37 +00:00
Marek Wolan
abba1ef86b Remove hardcoded checkpoint frequency in rllib 2023-11-24 09:37:26 +00:00
Marek Wolan
6754dbf541 Remove GATE and fix a few spelling mistakes. 2023-11-24 09:28:50 +00:00
Jake Walker
b13a9d3daf Add application execution action for data manipulation bot 2023-11-24 09:25:55 +00:00
Marek Wolan
50c9ef16cb Move policy module into session 2023-11-24 09:18:18 +00:00
Marek Wolan
bd109a7cfc Complete session->game rename refactor 2023-11-24 09:14:55 +00:00
Christopher McCarthy
0caeb60e01 Merged PR 216: #2034 - Implemented the Simulation reset functionality
## Summary
Implemented the Simulation reset functionality by doing a deepcopy of the Simulation object inside the PrimaiteSession upon instantiation and assigning it to a `_simulation_initial_state` variable. Then when reset called, the sessions `simulation` variable is assigned the value of the `_simulation_initial_state` variable.

## Test process
Added a test that uninstalls a service before performing a reset then checks that the service reappears.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

#2034 - Implemented the Simulation reset functionality by doing a deepcopy of the Simulation object inside the PrimaiteSession upon instantiation. Added a test that uninstalls a service before performing a reset then checks that the service reappears.

Related work items: #2034
2023-11-23 22:33:12 +00:00
Czar Echavez
8aa743188f #2064: fix layout of test so it passes in pipeline 2023-11-23 22:28:08 +00:00
Czar Echavez
2ce03e0262 #2064: turn on everything when node is turned on 2023-11-23 22:10:53 +00:00
Czar Echavez
f0fc6518a0 #2064: add handling of offline service to dns, ftp and database 2023-11-23 21:48:11 +00:00
Chris McCarthy
dfe07ad926 #2034 - Fixed deepcopy reference issue 2023-11-23 21:25:52 +00:00
Czar Echavez
bd6c27244c #2064: Edited services and applications to handle when they are shut down 2023-11-23 19:49:03 +00:00
Nick Todd
3dfd7a2e14 #2068: Fix malformed Windows path 2023-11-23 17:57:51 +00:00
Nick Todd
3894a9615d #2068: Replace refs to OpenAI Gym with Gymnasium 2023-11-23 17:42:26 +00:00
Nick Todd
47112aafcf #2068: Removed references to ARCD GATE 2023-11-23 16:19:39 +00:00
Jake Walker
5f1a5af1b4 Add data manipulation bot action manager 2023-11-23 16:06:19 +00:00
Nick Todd
87dde6ee0b #2042: Test tidying changes. 2023-11-23 15:55:58 +00:00
Jake Walker
c93705867f Move configuration from agent to data manipulation bot 2023-11-23 15:53:47 +00:00
Christopher McCarthy
76939fb8e8 Apply suggestions from code review 2023-11-23 15:45:22 +00:00
Chris McCarthy
efeaa4c1cc #2034 - Implemented the Simulation reset functionality by doing a deepcopy of the Simulation object inside the PrimaiteSession upon instantiation. Added a test that uninstalls a service before performing a reset then checks that the service reappears. 2023-11-23 15:31:06 +00:00
Marek Wolan
4ee29efd1f Merged PR 213: Replace SQLite database implementation with a simulation
## Summary
Remove SQLLite and real sql queries and replace them with `SELECT` and `DELETE` queries that interact with the node's file system and service operating status.

## Test process
Existing unit tests pass after logic was changed.

## Checklist
- [x] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #1971
2023-11-23 10:18:06 +00:00
Nick Todd
8584fa8f51 # 2041: Minor test changes 2023-11-23 10:04:52 +00:00
Marek Wolan
dd63563ba1 Update doc page on primaite session. 2023-11-23 03:07:39 +00:00
Marek Wolan
f1f516c51a Add multi agent session test 2023-11-23 02:51:31 +00:00
Marek Wolan
8a2279c6cb Update end to end tests after session changes 2023-11-23 01:40:27 +00:00
Marek Wolan
14ae8be5e2 Update session after it was split from game 2023-11-23 00:54:19 +00:00
Marek Wolan
1fd5298fc5 Fix multi agent system 2023-11-22 20:22:34 +00:00
Jake Walker
061e508187 Add repeat option to data manipulation bot 2023-11-22 16:24:17 +00:00
Nick Todd
006a37d268 #2042: extract code into request_time() method. 2023-11-22 14:40:44 +00:00
Nick Todd
3f76e09521 #2042: remove apply_timestep() return value 2023-11-22 14:13:50 +00:00
Marek Wolan
9070fb44d4 Check that ray single agent training works 2023-11-22 13:26:29 +00:00
Marek Wolan
b81dd26b71 Add Ray env class 2023-11-22 13:12:08 +00:00
Marek Wolan
1138644a4b Update to make things work with new layout 2023-11-22 12:59:33 +00:00
Marek Wolan
afd64e4674 Separate game, environment, and session 2023-11-22 11:59:25 +00:00
Nick Todd
dd7c2b05f8 #2041: Add RST doc 2023-11-22 08:54:39 +00:00
Nick Todd
984d165364 #2041: Fix long line 2023-11-21 17:24:50 +00:00
Nick Todd
eb2e37429a #2042: Add time attribute 2023-11-21 17:24:24 +00:00
Jake Walker
aa65c53a95 Pass probability of success through to functions 2023-11-21 15:09:51 +00:00
Jake Walker
48af022963 Run agent at configured timesteps 2023-11-21 13:41:38 +00:00
Nick Todd
243f2dd938 #2041: Update CHANGELOG 2023-11-21 12:11:30 +00:00
Jake Walker
d8154bbebd Add tests for data manipulation bot attack stages 2023-11-21 11:43:47 +00:00
Jake Walker
2975aa8827 Execute data manipulation bots from agent 2023-11-21 11:42:01 +00:00
Nick Todd
9ab33a4aa4 Merge branch 'dev' into feature/2041_2042-Add-NTP-Services 2023-11-21 11:28:50 +00:00
Nick Todd
60d94bf4b5 #2041: Remove test 2023-11-21 11:17:38 +00:00
Nick Todd
4f0f758ce9 #2041: Correct return value from receive() 2023-11-21 11:16:34 +00:00
Nick Todd
813a1f356e #2042: Remove debug statement 2023-11-21 11:15:07 +00:00
Marek Wolan
e9d2437db8 Merged PR 212: GATE-less agents
## Summary
Remove gate and integrate SB3 agent natively.
This includes:
- agent saving
- checkpoints
- session output directory
- simulation output (such as syslogs) are now in the session output directory
- agent loading
- training progress bar (with `enlighten`)

## Test process
End to end tests that verify that a session is being created correctly with a network
They also check the outputs exist.

## Checklist
- [y] PR is linked to a **work item**
- [upcoming PR] **acceptance criteria** of linked ticket are met
- [y] performed **self-review** of the code
- [loading not tested but need to move onto Ray now] written **tests** for any new functionality added with this PR
- [n] updated the **documentation** if this PR changes or adds functionality
- [n] written/updated **design docs** if this PR implements new functionality
- [n] updated the **change log**
- [y] ran **pre-commit** checks for code style
- [n] attended to any **TO-DOs** left in the code

Related work items: #1971
2023-11-21 09:33:29 +00:00
Nick Todd
f7215847d4 #2041: ntp_server test fixes. 2023-11-20 18:08:55 +00:00
Nick Todd
b0b37f9da5 #2042: ntp_client test fixes. 2023-11-20 18:06:50 +00:00
Nick Todd
95ad55a783 #2041: change deprecated logger levels. 2023-11-20 18:04:49 +00:00
Jake Walker
7e0e8a4768 Pass agent settings from config to agent 2023-11-20 10:38:01 +00:00
Marek Wolan
66d5612e92 Merge remote-tracking branch 'origin/feature/1972-remove-sqlite' into feature/1971-ray-agents-2 2023-11-18 04:54:17 +00:00
Marek Wolan
fdb48c0ded Update docs for Database 2023-11-18 03:46:24 +00:00
Marek Wolan
7d800cbbc9 Merge remote-tracking branch 'origin/dev' into feature/1972-remove-sqlite 2023-11-18 03:41:22 +00:00
Marek Wolan
77f3806ba7 Remove real database in favour of simulated 2023-11-18 03:40:08 +00:00
Marek Wolan
9d0a98b221 Apply suggestions from code review 2023-11-17 20:30:07 +00:00
Marek Wolan
5d9d8fe92c merge PR updates from parent branch 2023-11-17 17:59:45 +00:00
Marek Wolan
3fb7bce3ce Get RLLib to stop crashing. 2023-11-17 17:57:57 +00:00
Nick Todd
d28bd0d1c3 #2041: Fix names 2023-11-17 14:19:36 +00:00
Nick Todd
dbecc681dc #2041: Install NTPServer and NTPClient. 2023-11-17 12:59:06 +00:00
Nick Todd
6081f02caa #2041: Add missing return statement 2023-11-17 12:41:53 +00:00
Nick Todd
622c6931d8 #2041: Create test network + extra test 2023-11-17 12:07:46 +00:00
Jake Walker
227e73602f Pass execution definition from config to agent 2023-11-17 11:51:19 +00:00
Marek Wolan
c5b4ae45be Remove problematic progress bars 2023-11-17 11:40:36 +00:00
Marek Wolan
6e5e1e6456 Begin rllib 2023-11-17 11:38:29 +00:00
Marek Wolan
5bda952ead Fix sim output 2023-11-17 10:20:26 +00:00
Marek Wolan
ba580b00b4 Improve config validation and fix tests 2023-11-16 16:14:50 +00:00
Marek Wolan
0861663cc1 Add agent loading 2023-11-16 15:40:49 +00:00
Marek Wolan
e52d1fbd45 Add enlighten dependency 2023-11-16 15:29:48 +00:00
Marek Wolan
0b9bdedebd Fix typehints 2023-11-16 15:28:38 +00:00
Marek Wolan
13c49bf3ea Fix session path monkeypatch 2023-11-16 15:19:14 +00:00
Marek Wolan
7545c25a46 Make pytest patch with temporary session dir 2023-11-16 15:11:03 +00:00
Nick Todd
7ee2c4220a #2042: ntp_client test 2023-11-16 15:04:01 +00:00
Marek Wolan
829500a60f Get sb3 checkpoints saving during training 2023-11-16 14:37:37 +00:00
Jake Walker
1c5ff66d26 Pass execution definition from config to agent 2023-11-16 13:26:30 +00:00
Marek Wolan
4cc7ba1522 Add ability to save sb3 final model 2023-11-15 16:59:56 +00:00
Marek Wolan
64e8b3bcea Add basic primaite session e2e tests 2023-11-15 16:04:16 +00:00
Nick Todd
0c544a9a26 #2042: Add support for apply_timestep() 2023-11-15 15:58:10 +00:00
Marek Wolan
6182b53bfd Fix incorrect number of steps per episode 2023-11-15 14:49:44 +00:00
Marek Wolan
c8f2f193bd Implement agent training with sb3 2023-11-15 12:52:18 +00:00
Nick Todd
9deb130d10 #2042: pre-commit changes 2023-11-15 10:58:24 +00:00
Nick Todd
d31fce202c #2041: pre-commit changes. 2023-11-15 10:57:56 +00:00
Nick Todd
195e8a4e84 #2042: Implement NTP protocol for client 2023-11-14 15:13:28 +00:00
Nick Todd
f320487128 #2041: Implement NTP protocol for server 2023-11-14 15:13:05 +00:00
Marek Wolan
e6ead6e532 Update agent interface to work better with envs 2023-11-14 15:10:07 +00:00
Nick Todd
764d9561bd #2042: NTP client initial commit 2023-11-13 17:40:25 +00:00
Nick Todd
2ee8203397 #2041: NTP server initial commits 2023-11-13 17:39:27 +00:00
Marek Wolan
1cb54da2dd Remove more GATE stuff 2023-11-13 17:12:50 +00:00
Marek Wolan
08e88e52b0 Begin implementing training loop in session 2023-11-13 16:35:35 +00:00
Marek Wolan
707f2b59af Add SB3 RL agent 2023-11-13 16:08:39 +00:00
Marek Wolan
21c06dbea1 Remove GATE-related code. 2023-11-13 16:04:25 +00:00
Chris McCarthy
23fd9c3839 #1859 - Started giving the red agent some 'intelligence' and a sense of a state. Changed Application.run to .execute. 2023-11-13 15:55:14 +00:00
Czar Echavez
815bdfe603 Merged PR 206: 1962-Folder and File restore
## Summary
- Implement the folder/file restore
- Split the FileSystem and its classes into their own files so that it is easier to maintain.
- Reimplement how deleted folders and files are stored in a deleted list, so that it is possible to restore later

## Test process
See https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/206?_a=files&path=/tests/unit_tests/_primaite/_simulator/_file_system
- Unit tests written to make sure methods work as intended
- Integration tests with the apply_request method which tests that the agents can send the request to the simulation to affect it

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1962
2023-11-09 11:55:53 +00:00
Czar.Echavez
6e1f9bd63d #1962: add gate installation for docs build pipeline 2023-11-08 13:00:07 +00:00
Czar.Echavez
be4a467877 #1962: revert pulling from src 2023-11-08 10:48:41 +00:00
Czar.Echavez
f5df1366a7 #1962: merge dev into branch + fix minor diffs + ensure that imports pull from src 2023-11-08 10:36:47 +00:00
Marek Wolan
c060991084 Merged PR 207: Game layer
## Summary
- Remove v2-specific code, documentation, and tests
- Reconnect CLI, to new v3 classes and functions
- Add Game layer
- Minor changes to simulation layer to ensure compatibility with game layer actions and observations

### Game layer
- Add a primaite session, which is the main entry point to running a session. This encompasses agents, the simulation, and a connection with GATE.
- Add an agent interface, random agents, and RL agents.
- Add new observation space management
- Add new action space management
- Add new reward function management

## Test process
Ran primaite session without crash. Majority of integration and unit tests have not been written yet. (sorry)

I know it's not ideal to merge in this not-tested-state, but it doesn't make sense to continue diverging `dev` and `dev-game-layer`.

Instead of reviewing the diff, I would recommend downloading this code and getting familiarised with the new `game` module by reading the code and playing around with it.

Related work items: #1622, #1759, #1760, #1761, #1764, #1765, #1766, #1767, #1768, #1879, #1924, #1986, #1987, #1988, #1989, #1990, #1998
2023-11-07 16:03:43 +00:00
Czar Echavez
729ef2ebac Merged PR 208: #2025: added GATE installation as part of pipeline
## Summary
Installing GATE before running the primaite setup command so that the pipeline passes

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

#2025: added GATE installation as part of pipeline

Related work items: #2025
2023-11-07 15:03:00 +00:00
Czar.Echavez
d4679bb0e3 #2025: Missing character for GATE path 2023-11-07 14:09:22 +00:00
Czar.Echavez
e0d694a736 #2025: added GATE installation as part of pipeline 2023-11-07 14:00:08 +00:00
Marek Wolan
0ea282166d Merge remote-tracking branch 'origin/dev' into dev-game-layer 2023-11-06 16:23:29 +00:00
Czar.Echavez
eba10ae5ef #1962: clean up tests + improve the show command which shows the folders and files in file system 2023-11-06 11:56:44 +00:00
Czar.Echavez
535c1b19ab #1962: attempt to make the timestep actions look neater + adding logic that allows restoring a folder take multiple timesteps 2023-11-06 11:12:06 +00:00
Czar.Echavez
e70ceec716 #1962: folder/file restore logic 2023-11-06 10:22:08 +00:00
Czar.Echavez
51713bad74 #1962: split tests into managable files + implement deletion of folders and files + tests 2023-11-03 15:15:18 +00:00
Czar.Echavez
b2c3e273b7 #1962: separating file system into more managable files 2023-11-02 15:10:51 +00:00
Czar.Echavez
b67eb1bb34 #1962: separating file system into more managable files 2023-11-02 13:14:08 +00:00
Czar.Echavez
11848aa180 #1962: keeping track of deleted files 2023-10-31 15:52:44 +00:00
Czar Echavez
870707f86b Merged PR 200: Implement node scan and reset
## Summary
Implementing the ability for the simulation to scan all node components as well as the ability for the red agent to reveal the node and its components.

Implementing the ability for the simulation to reset a node

## Test process
Unit tests added

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1961
2023-10-30 16:47:28 +00:00
Czar.Echavez
98ca33e994 #1961: scanning no longer happens every timestep - the scan is all done in one timestep after the required timestep countdown is complete 2023-10-30 15:34:13 +00:00
Czar.Echavez
1ddf400d6f #1961: node resetting 2023-10-27 18:28:34 +01:00
Czar.Echavez
68b22b6444 #1961: node scanning + applying timestep to all components within node + node revealing to red 2023-10-27 17:50:41 +01:00
Marek Wolan
2923921559 Merged PR 199: Fix setup and session commands
## Summary
Make PrimAITE work with the new:
- configs
- CLI commands

## Test process
I ran primaite setup and primaite session to check that they work

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1987, #1998
2023-10-27 15:14:06 +00:00
Marek Wolan
a37ce051c5 Add ARCD GATE setup to primaite setup 2023-10-27 14:50:31 +01:00
Marek Wolan
75d1fd20c3 Remove temporary files 2023-10-27 14:41:53 +01:00
Marek Wolan
b81c1739f8 Fix CLI and Session to work with new classes 2023-10-27 14:26:52 +01:00
Marek Wolan
6378ff3087 Merged PR 198: Updates to documentation
* STILL IN PROGRESS *

## Summary
Delete old documentation, write some more up-to-date documentation.

## Test process

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Updates to documentation

Related work items: #1988, #1990
2023-10-27 11:33:09 +00:00
Marek Wolan
1ec1b319e5 Fix formatting in docs 2023-10-27 12:24:22 +01:00
Marek Wolan
d4eb499729 Start fixing up cli and setup 2023-10-27 12:20:23 +01:00
Marek Wolan
a06629ed0b Bump version 2023-10-27 11:48:54 +01:00
Marek Wolan
6ac7dcf9ac Update README.md 2023-10-27 11:48:22 +01:00
Marek Wolan
318c9f8c5a Fix formatting issues 2023-10-27 11:43:11 +01:00
Czar.Echavez
8783574442 #1961: os scan set up 2023-10-27 10:17:59 +01:00
Marek Wolan
11fad5084e Merged PR 197: Remove deprecated functionality
## Summary
* Delete many files which are not used with the new V3 approach. Including all the previous simulation files, as well as the old config, old session, etc.
* Delete tests for the removed functionality
* Note: this PR can only be merged after !195

## Test process
This PR Changes our Unit Test suite to only keep tests related to V3 code. All tests pass as of my recent attempt.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [~] written **tests** for any new functionality added with this PR
- [~] updated the **documentation** if this PR changes or adds functionality
- [n] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [n] attended to any **TO-DOs** left in the code

Related work items: #1989, #1986
2023-10-26 14:33:31 +00:00
Marek Wolan
4f387cf092 Merged PR 195: Initial game layer functionality
## Summary
* add a new module `game` to PrimAITE
* this includes a new PrimaiteSession which creates a simulation, and multiple agents, and talks to GATE
* agent interface
* agent actions to work with Simulator requests
* agent observations that work with Simulator State
* agent rewards also with Simulator state

**note** that this branch is currently still in a broken state. Still need to do things like updating readme, install instructions, refactoring some poorly designed classes, and removing legacy code. These will be done in subsequent PRs to avoid making this PR even bigger than it needs to be. Still, please review this to familiarise yourself.

## Test process
Some unit tests exist but their coverage will be expanded.
I performed some test runs with to train a SB3 agent in GATE with a primaite simulation.

## Checklist
- [y] PR is linked to a **work item**
- [y] **acceptance criteria** of linked ticket are met
- [~] performed **self-review** of the code
- [n] written **tests** for any new functionality added with this PR
- [~] updated the **documentation** if this PR changes or adds functionality
- [~] written/updated **design docs** if this PR implements new functionality
- [~] updated the **change log**
- [y] ran **pre-commit** checks for code style
- [n] attended to any **TO-DOs** left in the code

Related work items: #1622, #1759, #1760, #1761, #1764, #1765, #1766, #1767, #1768, #1879, #1924
2023-10-26 12:49:11 +00:00
Marek Wolan
afa7916db0 Updates to documentation 2023-10-25 23:32:52 +01:00
Marek Wolan
450aa150ae Merge remote-tracking branch 'origin/dev-game-layer' into feature/1989-remove-v2-modules 2023-10-25 19:19:34 +01:00
Marek Wolan
02901a7c99 Apply suggestions from code review. 2023-10-25 19:07:45 +01:00
Marek Wolan
38b71c0c8e Update CHANGELOG 2023-10-25 18:06:33 +01:00
Marek Wolan
78a8d2be3e Fix File observation test 2023-10-25 17:57:19 +01:00
Marek Wolan
59e2c23c04 Merge remote-tracking branch 'origin/feature/1924-Agent-Interface' into feature/1989-remove-v2-modules 2023-10-25 17:56:21 +01:00
Marek Wolan
4872c939ff Apply suggestions from code review 2023-10-25 17:19:24 +01:00
Marek Wolan
c57b5152c0 Remove broken tests 2023-10-25 17:08:01 +01:00
Marek Wolan
1e811148ed Fix dependency versions to align with GATE 2023-10-25 17:04:30 +01:00
Marek Wolan
2b8462d38d Fix link import in v3 code 2023-10-25 17:04:04 +01:00
Marek Wolan
e8e14ae68a Comment out tests for primaite v2 2023-10-25 13:56:02 +01:00
Marek Wolan
f861b1897a Remove deprecated code from v2 2023-10-25 13:36:55 +01:00
Marek Wolan
ffe80f215e Merge 'origin/dev-game-layer' into feature/1924-Agent-Interface 2023-10-25 09:58:04 +01:00
Czar Echavez
091920c6f7 Merged PR 192: Implement missing actions
## Summary

#1947
Implementation of actions from the QTSL-820-2450 - ARCD Track 2 Common Interface Definition for Environments UC2 document

Covers:
- [X] BAS-12 NODE  SERVICE SCAN
- [X] BAS-15 NODE  SERVICE STOP
- [X] BAS-16 NODE  SERVICE START
- [X] BAS-17 NODE  SERVICE PAUSE
- [X] BAS-18 NODE  SERVICE RESUME
- [X] BAS-19 NODE  SERVICE RESTART
- [X] BAS-20 NODE  SERVICE DISABLE
- [X] BAS-21 NODE  SERVICE ENABLE

- [X] BAS-29 NODE  FILE SCAN
- [X] BAS-30 NODE  FILE CHECKHASH
- [X] BAS-33 NODE  FILE DELETE
- [X] BAS-34 NODE  FILE REPAIR

- [X] BAS-38 NODE  FOLDER SCAN
- [X] BAS-39 NODE  FOLDER CHECKHASH
- [X] BAS-41 NODE  FOLDER REPAIR

- [X] BAS-44 NODE SHUTDOWN
- [X] BAS-45 NODE STARTUP

- [X] RAS-30 NODE FILE DELETE
- [X] RAS-31 NODE FILE CORRUPT
- [X] RAS-36 NODE FOLDER DELETE
- [X] RAS-37 NODE FOLDER CORRUPT

## Test process

### node actions test
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/192?_a=files&path=/tests/unit_tests/_primaite/_simulator/_network/_hardware/test_node_actions.py

### service actions
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/192?_a=files&path=/tests/unit_tests/_primaite/_simulator/_system/_services/test_service_actions.py

### file/folder actions
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/192?_a=files&path=/tests/unit_tests/_primaite/_simulator/_file_system/test_file_system_actions.py

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #1947
2023-10-25 08:35:59 +00:00
Marek Wolan
c9b06e1bfb Delete sandbox file 2023-10-24 17:06:58 +01:00
Marek Wolan
cb60b6f785 Update text in docs 2023-10-24 17:02:29 +01:00
Marek Wolan
d49d5b292d Add a bit of documentation 2023-10-24 15:51:29 +01:00
Czar.Echavez
ac23633d82 #1947: Added documentation on how the node initialisation works 2023-10-24 15:41:39 +01:00
Czar.Echavez
c4b43c479e #1947: remove storing deleted files in a list and banish them to the shadow realm instead 2023-10-24 11:53:21 +01:00
Marek Wolan
174de013fb Align blue actions with common env 2023-10-24 11:43:25 +01:00
Marek Wolan
6b7c483a67 Align observations to Common approach 2023-10-24 11:07:25 +01:00
Czar.Echavez
1e66795aff #1947: remove scan from components that cannot be scanned 2023-10-24 10:43:00 +01:00
Czar.Echavez
8b85d5d55b #1947: node startup/shutdown now take multiple timesteps to complete 2023-10-24 10:11:50 +01:00
Marek Wolan
d4eee36b7b Fix software registration for game layer and simulator interface 2023-10-23 17:23:14 +01:00
Marek Wolan
975aa9ffc2 Minor changes to rewards and services. 2023-10-23 16:26:34 +01:00
Czar.Echavez
724beb1a29 #1947: folder/file scan now take multiple time steps to complete 2023-10-23 15:58:37 +01:00
Czar.Echavez
ffc4711afb #1947: added test for agent actions + clearing up the implementation of the request managers for filesystem 2023-10-20 12:58:58 +01:00
Marek Wolan
0f24b4a646 Remove broken import 2023-10-19 15:34:46 +01:00
Marek Wolan
49e78d5291 Add docstrings and fix formatting on many things 2023-10-19 09:36:23 +01:00
Marek Wolan
e0f8c3c5ea Add documentation 2023-10-19 01:56:40 +01:00
Czar.Echavez
0edb9b46a7 #1947: clean up existing work and clear up some itesm left in TODO 2023-10-18 13:21:05 +01:00
Czar.Echavez
4ee2235dd1 #1947: temp commit what is done so far 2023-10-16 11:42:56 +01:00
Czar.Echavez
9b5d95cbb9 #1947: refactor am->rm to align with refactor of ActionManager->RequestManager 2023-10-13 10:41:27 +01:00
Czar.Echavez
5e419455f1 Merge branch 'dev' into feature/1947-implement-missing-node-actions 2023-10-12 13:17:04 +01:00
Czar.Echavez
c9e4ba3c7d #1947: File and Folder hash checks 2023-10-12 11:16:25 +01:00
Marek Wolan
027addc485 Merge remote-tracking branch 'origin/dev' into feature/1924-Agent-Interface 2023-10-12 10:00:46 +01:00
Marek Wolan
1c5eb392d0 Merged PR 184: Connect up actions in the simulator
## Summary
Finishes (?) the action system.
- Defines all UC2 common action space actions on SimComponents
- Links up SimComponents and their children, so actions can be passed from parent to child
- Add a function for enumerating all possible actions that exist on a SimComponent. (will be used for generating action space)
- add documentation for action management

note: I know that the way I approached this is a bit convoluted but It's just what I came up with to allow the actions to be as flexible and modular as the SimComponents themselves.

## Test process
Tested that the functionality works in scratch notebook. But also in the process of adding unit/integration tests now.

## Checklist
- [x] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1923
2023-10-12 09:00:30 +00:00
Marek Wolan
565af11dba Minor fixes to rewards 2023-10-12 09:59:45 +01:00
Marek Wolan
70c1857bbc Implement rewards for UC2 (draft) 2023-10-11 15:49:41 +01:00
Marek Wolan
b84ab84385 Fix GATE Client to work successfully with GATE Server 2023-10-11 14:08:55 +01:00
Marek Wolan
def2c3699b Add empty obs placeholders 2023-10-10 21:01:09 +01:00
Czar.Echavez
060bbf0506 #1947: added ability for files and folders to be scanned, corrupted and repaired 2023-10-10 15:14:47 +01:00
Czar.Echavez
a1b4d3d5e0 Merge branch 'feature/1812-traverse-actions-dict' into feature/1947-implement-missing-node-actions 2023-10-10 09:59:34 +01:00
Czar.Echavez
56eda38a6e #1947: git merge did not change add_action -> add_request 2023-10-10 09:52:40 +01:00
Marek Wolan
f3451b2fbb Replace request overwrite error with warning 2023-10-10 09:50:39 +01:00
Marek Wolan
b53c3856dd Add GATE wheel temporarily 2023-10-10 09:48:04 +01:00
Czar.Echavez
80d371c238 Merge branch 'feature/1812-traverse-actions-dict' into feature/1947-implement-missing-node-actions 2023-10-10 08:58:58 +01:00
Marek Wolan
91f06c15f6 Fix formatting with precommit 2023-10-09 18:35:30 +01:00
Marek Wolan
c9bc8fbf3d Fix file observation test 2023-10-09 18:33:30 +01:00
Marek Wolan
37c851b5c5 Merge remote-tracking branch 'origin/dev' into feature/1924-Agent-Interface 2023-10-09 18:29:48 +01:00
Marek Wolan
18706be4ff Merge branch 'origin/dev' into feature/1812-traverse-actions-dict 2023-10-09 18:26:25 +01:00
Marek Wolan
560e416eda Merge 'origin/feature/1812' into feature/1924 2023-10-09 18:25:46 +01:00
Marek Wolan
e85c5977d0 remove redundant code from sandbox notebook 2023-10-09 18:22:30 +01:00
Marek Wolan
f68886d5df Fix bugged actions 2023-10-09 17:29:50 +01:00
Czar.Echavez
bbf2b09f96 #1947: Add ability for all simcomponents to be scanned - sets up ability for service, files, folders and nodes to be scanned 2023-10-09 16:47:36 +01:00
Czar Echavez
e06c51e5d6 Merged PR 191: Web Service and Client
## Summary
Added a WebServer service and a Web Browser (client) so that the simulation can emulate HTTP requests across the network via HTTPPacket transfer

## Test process
Written an integration test that tests Web Server and Web Browser sending and returning requests

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #1752, #1816, #1866, #1916, #1943
2023-10-09 13:21:17 +00:00
Czar.Echavez
318539fd8f #1943: apply suggestions from PR + fixing FTP bug + elaborating 2023-10-09 13:25:12 +01:00
Marek Wolan
5a5710c6ae Rename Sim Actions to request 2023-10-09 13:24:08 +01:00
Marek Wolan
2722abe428 Fix typos and formattig (based on PR Review) 2023-10-09 11:49:38 +01:00
Marek Wolan
df22d0de0b Merge remote-tracking branch 'origin/dev' into feature/1812-traverse-actions-dict 2023-10-09 11:39:31 +01:00
Marek Wolan
081a3e519a Fix certain observation bugs 2023-10-08 17:57:45 +01:00
Marek Wolan
ccb36f8400 Change observations to make loading from config better 2023-10-08 17:02:54 +01:00
Marek Wolan
3dea9743c3 Get primaite session step working 2023-10-06 20:32:52 +01:00
Czar.Echavez
853bb9eecc #1943: unit tests + refactoring HTTP -> Http 2023-10-06 12:10:57 +01:00
Marek Wolan
2a8df074b9 Add network action 2023-10-06 10:36:29 +01:00
Czar.Echavez
be6b904db9 - Fixed FTP client server infinite recursion - ftp server and clients can be installed on the same node, this could cause a loop of requests
- fixed tests broken by merged with dev
2023-10-05 16:24:48 +01:00
Czar.Echavez
4699e87ea8 Merge branch 'dev' into feature/1943-service-web-server 2023-10-04 16:35:23 +01:00
Czar Echavez
c71e989ac6 Merged PR 187: Database Service backup using FTP
## Summary
- Used FTP changes to allow the database service to create a copy of the database.db file in the backup server
- Used FTP changes to allow the database service to restore the database.db file from a copy made in the backup server

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #1752, #1796, #1816, #1866, #1916
2023-10-04 14:06:32 +00:00
Czar.Echavez
97f0267539 #1796: apply PR suggestions + fix tests 2023-10-04 11:33:18 +01:00
Marek Wolan
fabd4fd5dd Add ACL Action to game layer 2023-10-04 09:07:04 +01:00
Czar.Echavez
82da21b073 \#1943:
- changelog added
- added documentation + example of using web server + web browser
- extended web server so that it also accepts ip addresses
- web server can differentiate between a normal page request and one that propagates into a DB request
- rename WebServerService -> WebServer
2023-10-03 16:56:35 +01:00
Czar.Echavez
4b5a73bd32 #1943: web server + client + tests + a few improvements to syslogging 2023-10-03 14:59:48 +01:00
Marek Wolan
2b617e01a3 Finalise actions interface 2023-10-02 17:21:43 +01:00
Czar.Echavez
fdebfce406 #1796: Fix test + making the restore test better 2023-10-02 12:14:59 +01:00
Chris McCarthy
84405d7ed3 #1796 - Added docstring to the test_uc2_data_manipulation_scenario.py 2023-09-29 20:19:26 +01:00
Chris McCarthy
3dc8a0f222 #1796 - Made the FTP copy real files. Hardcoded the DatabaseService backup folder and filename. Added db restore and final query check to the data manipulation e2e test. 2023-09-29 20:14:42 +01:00
Czar.Echavez
bca3e6344e #1796: documentation 2023-09-28 14:09:32 +01:00
Czar.Echavez
6202d320a6 #1796: Add ability to create and restore database backups + add more sys log messages + remove the link size checks temporarily 2023-09-28 12:23:49 +01:00
Czar.Echavez
c096d06bcd #1796: pre installing system software 2023-09-26 15:14:24 +01:00
Czar Echavez
161d441ad6 Merged PR 185: FTP - client/server
## Summary
Initial implementation of an FTP Client/Server service used to emulate a transfer of files across nodes

## Test process
Added an integration and unit test

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1752, #1816, #1916
2023-09-26 13:38:42 +00:00
Marek Wolan
f1346ae278 put in agent parsing skeleton 2023-09-26 12:54:56 +01:00
Czar.Echavez
79615243e4 #1916: Added example usage for FTP 2023-09-26 12:09:41 +01:00
Marek Wolan
92e0110e73 yaml parse and connect links 2023-09-26 11:48:22 +01:00
Marek Wolan
fdf66ba3de Make yaml parser work with services 2023-09-26 10:52:14 +01:00
Marek Wolan
f79ed99bd2 end of day 2023-09-25 19:17:57 +01:00
Marek Wolan
493014ca19 draft yaml parser 2023-09-25 17:57:47 +01:00
Marek Wolan
9d4e41435d End-of-day commit 2023-09-25 16:04:04 +01:00
Czar.Echavez
0140fe7c48 #1916: fix a problem with process_ftp_command method 2023-09-25 15:59:31 +01:00
Czar.Echavez
2520b67889 #1916:
- Added FTP to changelog
- Added FTP to documentation
- Added documentation in code
- Clean up of methods - prevent repeats of the same code
2023-09-25 14:31:57 +01:00
Czar.Echavez
98ca71aaba Merge branch 'dev' into feature/1916-ftp-client-server 2023-09-25 10:40:51 +01:00
Czar.Echavez
2c234ab67a #1916: Setting up a connected states + added tests + error states for if service is interacted with when not running 2023-09-22 15:38:01 +01:00
Czar.Echavez
58edb6d3e4 #1916: Created FTP superclass + working retrieve file method for FTP 2023-09-21 15:13:30 +01:00
Marek Wolan
53fd4ed828 Finish File Observation 2023-09-21 10:42:26 +01:00
Marek Wolan
d98d303dda Merge remote-tracking branch 'origin/feature/1812-traverse-actions-dict' into feature/1924-Agent-Interface 2023-09-21 10:13:31 +01:00
Marek Wolan
f54f278fca Initialise observations in agent interface 2023-09-21 10:13:01 +01:00
Czar.Echavez
2e76b3f162 #1916: FTP client STOR request to FTP server 2023-09-20 16:23:35 +01:00
Marek Wolan
860b3fb801 Add test to new action functionliaty 2023-09-19 16:11:42 +01:00
Marek Wolan
682091b4ba Remove redundant method 2023-09-19 15:30:02 +01:00
Marek Wolan
93476554a9 Undo experimental changes to request format 2023-09-19 15:17:13 +01:00
Marek Wolan
68f67f13da Fix formatting on docs for actions. 2023-09-19 15:13:51 +01:00
Marek Wolan
d523ccc3cb Improve docs on action system 2023-09-19 14:23:14 +01:00
Marek Wolan
fd1a4403f4 Merged PR 179: Updated pull_request_template.md
## Summary
*Replace this text with an explanation of what the changes are and how you implemented them. Can this impact any other parts of the codebase that we should keep in mind?*

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [ ] This PR is linked to a **work item**
- [ ] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [ ] I have update the **change log**
- [ ] I have run **pre-commit** checks for code style

Updated pull_request_template.md

Related work items: #1866
2023-09-19 12:43:17 +00:00
Marek Wolan
3ee5e22b24 Add router action 2023-09-19 12:48:55 +01:00
Marek Wolan
898123cb10 Stub out more actions 2023-09-19 11:46:02 +01:00
Marek Wolan
aa6834ad08 Check service actions work. 2023-09-19 11:41:02 +01:00
Marek Wolan
610517d817 Underscore 'parent' refs to make pydantic happy.
Rename attributes like connected_link and connected_node to start with
an underscore.

This will prevent circular dependency and stack recursion depth error.
2023-09-19 11:28:13 +01:00
Marek Wolan
a719389e05 Add placeholder actions 2023-09-19 11:24:42 +01:00
Marek Wolan
77108634e8 Merge remote-tracking branch 'origin/dev' into feature/1812-traverse-actions-dict 2023-09-19 10:12:47 +01:00
Czar.Echavez
f913294058 #1916: moved services into their own subdirectories 2023-09-18 14:20:19 +01:00
Czar Echavez
f180c6f680 Merged PR 177: DNS Server and Client
## Summary
Carrying on where Sunil left the task. Added more functionality to the DNS.
- DNS Server can keep a list of domain names that the DNS Client can request
- DNS Client has a cache of domain names that are valid from the DNS Server

## Test process
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/177?_a=files&path=/tests/unit_tests/_primaite/_simulator/_system/_services/test_dns.py

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [X] I have update the **change log**
- [x] I have run **pre-commit** checks for code style

Related work items: #1752
2023-09-18 10:31:16 +00:00
Chris McCarthy
939de40f1e #1752 - Moved dns_server ip address from the NIC to the Node. Updated the arcd_uc2_network so that clients and servers have a dns server. Added sys_log entries for DNSServer and DNSClient. MAde the DNSServer always rend a reply, but for the resolved IP address to be empty if it cannot be resolved. 2023-09-18 10:25:26 +01:00
Czar.Echavez
b1e46b4f9e #1752: Apply suggestions from PR review 2023-09-14 20:08:06 +01:00
Czar Echavez
98e103a984 #1752: added documentation for DNS Client and Server 2023-09-13 09:48:38 +01:00
Czar Echavez
b0478f4e88 #1752: added positions to ACL rules for UC2 network to prevent rules being overwritten 2023-09-13 08:46:22 +01:00
Czar Echavez
f29477a50a Merge branch 'dev' into feature/1752-dns-server-and-client 2023-09-12 14:34:15 +01:00
Christopher McCarthy
69c3f97cd9 Merged PR 178: Database Client/Server Simulation
## Summary
This pull request focuses on implementing key functionalities needed for network frame processing and database interactions. The primary changes are:

1. **Internal Frame Processing:** The logic has been implemented in various components like `NIC`, `Node`, `SessionManager`, and `SoftwareManager`. These changes enable the system to process incoming and outgoing network frames in a structured manner.
2. **Database Service and Client:** The `DatabaseService` simulates a SQL database server, while the `DatabaseClient` provides a client interface for connecting to this service. These functionalities have been built and integrated into the existing architecture.
3. **Networking and Communication:** Tests have been added to confirm that database queries can be sent over the network, demonstrating end-to-end functionality.

## Commits

- #1816 Simplified a bunch of stuff in the file system in prep for services and applications. Started adding the database logic. Waiting for the software manager/session manager work from another tick. Merge branch 'dev' into feature/1816_Database-Service-(Network-and-User-Interaction)
- #1816 Added the final pieces of the puzzle to get data up from NIC → session manager → software manager → service.
- #1816 DatabaseService now uses the send function when responding.
- #1816 Added database client. Installed the database client on the Web Server node in the UC2 network. Updated the integration test to query the DB server using the DB client.
- #1816 Added full documentation on the database client/server, and the internal frame processing process
- #1816 Fixed tests. Used node and link added number (id) in observation space.

## Test process
For testing these functionalities, the following steps were taken:

1. **Unit Tests:** Tests have been written to confirm that database queries can be sent over the network successfully.
2. **Integration Tests:** Manually tested the frame processing flow from NIC to Service/Application, ensuring the functionality behaves as expected.
3. **Database Queries** Executed sample SQL queries using the `DatabaseClient` to make sure it interacts correctly with the `DatabaseService`.

## Checklist
- [ ] This PR is linked to a **work item**
- [ ] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [ ] I have update the **change log**
- [ ] I have run **pre-commit** checks for code style

Related work items: #1816
2023-09-12 13:31:08 +00:00
Czar Echavez
8b6bc84321 #1752: simplifying the DNS implementation - switch to TCP + fixing the DNS integration test 2023-09-12 13:37:11 +01:00
Marek Wolan
275115f4dd Updated pull_request_template.md 2023-09-12 12:12:38 +00:00
Czar Echavez
fb96ef18c0 #1752: remove unnecessary changes 2023-09-12 09:32:28 +01:00
Czar Echavez
1a81285b76 #1752: Added send+receive functionality for DNS client and server + tests + added simulation_output to gitignore 2023-09-12 08:46:07 +01:00
Czar Echavez
ee730d4ab0 Merge branch 'feature/1816_Database-Service-(Network-and-User-Interaction)' into feature/1752-dns-server-and-client 2023-09-11 16:22:18 +01:00
Chris McCarthy
695b3ceab4 #1816 - Updated the DataManipulationBot to subclass DatabaseClient. Extended logging. Dropped the Link loading logging as it was clogging up the terminal output. 2023-09-11 16:15:03 +01:00
Czar Echavez
4c67365d4f Merge branch 'feature/1816_Database-Service-(Network-and-User-Interaction)' into feature/1752-dns-server-and-client 2023-09-11 15:23:39 +01:00
Chris McCarthy
f19dc9892b #1816 - Fixed tests. Used node and link added number (id) in observation space. 2023-09-11 11:31:03 +01:00
Czar Echavez
5a101d5426 Merge branch 'feature/1816_Database-Service-(Network-and-User-Interaction)' into feature/1752-dns-server-and-client 2023-09-11 09:50:16 +01:00
Chris McCarthy
388176b8bd #1816 - Added full documentation on the database client/server, and the internal frame processing process 2023-09-11 09:30:40 +01:00
Czar Echavez
5cd1e2edf0 Merge branch 'feature/1816_Database-Service-(Network-and-User-Interaction)' into feature/1752-dns-server-and-client 2023-09-11 08:58:13 +01:00
Chris McCarthy
b1d8666c16 #1816 - Added database client. Installed the database client on the Web Server node in the UC2 network. Updated the integration test to query the DB server using the DB client. 2023-09-08 16:50:49 +01:00
Czar Echavez
97a38efc27 Merge branch 'feature/1816_Database-Service-(Network-and-User-Interaction)' into feature/1752-dns-server-and-client 2023-09-08 10:41:03 +01:00
Chris McCarthy
ceac89e778 #1816 - DatabaseService now uses the send function when responding. 2023-09-08 10:15:26 +01:00
Czar Echavez
6f2f23e04f #1752: update changelog 2023-09-07 15:59:46 +01:00
Czar Echavez
47dd23311b #1752: added more functionality to DNS client and server + tests 2023-09-07 15:45:37 +01:00
Chris McCarthy
2f744af34e #1816 - Added the final pieces of the puzzle to get data up from NIC → session manager → software manager → service.
- Implemented a basic sim DB that matches UC2 data manipulation DB in IY.
- Added a test that confirms DB queries can be sent over the network.
2023-09-06 22:26:23 +01:00
Chris McCarthy
6b41bec32a #1816 - Added the final pieces of the puzzle to get data up from NIC → session manager → software manager → service.
- Implemented a basic sim DB that matches UC2 data manipulation DB in IY.
- Added a test that confirms DB queries can be sent over the network.
2023-09-06 22:01:51 +01:00
Czar Echavez
2cb0c238c9 Merge branch 'dev' into feature/1752-dns-server-and-client 2023-09-06 13:42:07 +01:00
Chris McCarthy
65b027bc06 Merge branch 'dev' into feature/1816_Database-Service-(Network-and-User-Interaction) 2023-09-06 13:37:06 +01:00
Marek Wolan
4f89adb19a Start changing to dict instead of string actions. 2023-09-06 12:51:47 +01:00
Czar Echavez
6b9928c9b9 Merged PR 175: Red Service Data Manipulator Bot
## Summary
Implementation of the Data Manipulation Bot. This service sends a SQL query payload to the database server (or a given machine IP and port)

## Test process
Added a test
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/175?_a=files&path=/tests/unit_tests/_primaite/_simulator/_system/_services/_red_services/test_data_manipulator_service.py

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [X] I have update the **change log**
- [x] I have run **pre-commit** checks for code style

Related work items: #1814
2023-09-06 11:40:29 +00:00
Chris McCarthy
7c157d27d7 #1800 - Simplified a bunch of stuff in the file system in prep for services and applications. Started adding the database logic. Waiting for the software manager/session manager work from another ticket. 2023-09-06 11:35:41 +01:00
Czar Echavez
597c7664bc #1814: update changelog 2023-09-06 11:19:30 +01:00
Czar Echavez
d503e51c2d #1814: Remove hardcoded values + added test + remove unnecessary private parent attribute 2023-09-06 11:12:03 +01:00
Czar Echavez
c349bb4484 #1814: initial implementation of data manipulator service 2023-09-05 17:14:47 +01:00
Marek Wolan
1dccceaf56 Verify that action tree is starting to work! 2023-09-05 15:53:22 +01:00
Marek Wolan
ffe1e92664 Make actions more recursive 2023-09-05 14:51:25 +01:00
Marek Wolan
2b68ed813c Make actions more recursive 2023-09-05 14:51:04 +01:00
Marek Wolan
0c362da789 Merge remote-tracking branch 'origin/dev' into feature/1812-traverse-actions 2023-09-05 13:20:20 +01:00
Marek Wolan
0493c2062c Merged PR 173: Database service (without networking)
## Summary
- add a database service
- change how `SimComponent` adds actions to allow inheritance of actions
- add service-based actions, like start, stop, pause, and compromise

## Test process
New test cases were added.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [ ] I have update the **change log**
- [x] I have run **pre-commit** checks for code style

Related work items: #1801
2023-09-04 19:41:17 +00:00
Chris McCarthy
1385adf3fe Merge remote-tracking branch 'devops/dev' into feature/1801-Database
# Conflicts:
#	src/primaite/simulator/network/container.py
#	src/primaite/simulator/network/hardware/base.py
2023-09-04 19:45:29 +01:00
Christopher McCarthy
0892a976fd Apply suggestions from code review 2023-09-04 18:37:05 +00:00
Christopher McCarthy
c547f12f4e Merged PR 158: Sync with the downstream GitHub repo
DSTL requested some changes to docs.

Related work items: #1711
2023-09-04 18:21:19 +00:00
Christopher McCarthy
482a5fc5e9 Merged PR 174: Router Node
**_*Disclaimer, I used AI to write this PR description for me, you know, for efficiency._**

## Summary
In this pull request, we've made several key enhancements and fixes to improve the routing and network simulation functionalities of our codebase. At the heart of this PR is the introduction of a `Router` class, complete with `ACLRule` and `RouteTableEntry` classes to facilitate easier management of routes and permissions. We've also fixed a lingering issue with the `.ping` functionality, ensuring that it properly checks for replies before returning a boolean value.

To make our `Router` class more inspectable, `.show()` methods have been added which can output information in both plain text and markdown formats. Additionally, we've removed the `gateway` field from the `NIC` class and relocated it to the `Node` class. This move allows each `Node` to have a single default gateway. To further refine the system, we've added `Computer` and `Server` classes, and updated our restructured text formatted docstrings and documentation. Finally, a UC2 network has been added.

Changes have been fully tested to ensure that the existing functionalities remain intact, and new unit tests have been added to verify routing between different subnets. The code has been synced with the dev branch.

## Test process
We've added new unit tests and integration tests to check the routing capabilities when a router is placed between different subnets. These tests specifically focus on the ping functionality to verify that it works as expected after the changes. Existing tests were also run to make sure no existing functionality was broken.

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have written/updated **design docs** if this PR implements new functionality
- [ ] I have update the **change log**
- [X] I have run **pre-commit** checks for code style

Related work items: #1800
2023-09-04 16:56:41 +00:00
Marek Wolan
289f818266 Apply suggestions from code review 2023-09-04 16:11:47 +00:00
Chris McCarthy
dc9601bf30 Merge remote-tracking branch 'devops/dev' into downstream_github_sync 2023-09-04 16:46:14 +01:00
Chris McCarthy
f3f8d02fcb Merge remote-tracking branch 'github/dev' into downstream_github_sync 2023-09-04 16:45:23 +01:00
Chris McCarthy
596ad20cc6 #1800 - Added better logging and error messages to AccessControlList class. Updated usage of extra following pydantic deprecated warning "pydantic.config.Extra is deprecated, use literal values instead (e.g. extra='allow')" 2023-09-04 16:44:29 +01:00
Chris McCarthy
ccad5ba8a3 #1800 - Ran pre-commit 2023-09-04 16:34:55 +01:00
Chris McCarthy
5981bc7255 Merge remote-tracking branch 'devops/feature/1800_model-a-basic-router-subclass-of-node' into feature/1800_model-a-basic-router-subclass-of-node 2023-09-04 14:58:52 +01:00
Chris McCarthy
3075d1985b #1800 - Renamed all ip fields so that they're post-fixed with ip_address 2023-09-04 14:58:34 +01:00
Christopher McCarthy
d9feb67e02 Apply suggestions from code review 2023-09-04 11:20:40 +00:00
Chris McCarthy
05959e5408 #1800 - Moved the Switch code to a dedicated switch.py module.
- Added more switch tests.
- Updated ACL tests to use router acl.
- Updated more docs.
- Moved the Jupyter notebooks to _package_data and fixed up the setup to move all notebooks to ~/primaite/notebooks/example_notebooks.
2023-09-04 12:14:24 +01:00
Marek Wolan
33b4911cb1 Move actions to pydantic 2023-09-04 10:20:06 +01:00
Chris McCarthy
5111affeeb #1800 - Added more docstrings and rst docs.
- Extended the .show functionality to enable markdown format too.
2023-09-01 16:58:21 +01:00
Marek Wolan
d55fd835c7 Merge remote-tracking branch 'origin/dev' into feature/1801-Database 2023-08-31 14:56:31 +01:00
Marek Wolan
61fa83a00d Fix failing test 2023-08-31 14:55:14 +01:00
Chris McCarthy
89ad22aceb #1800 - Synced with dev.
- Added the UC2 network.
- Added a Computer class.
2023-08-31 13:35:56 +01:00
Chris McCarthy
415ee3b3a7 Merge branch 'dev' into feature/1800_model-a-basic-router-subclass-of-node 2023-08-31 11:39:21 +01:00
Marek Wolan
bd5aacaf0c Remove todo comments 2023-08-31 11:32:11 +01:00
Marek Wolan
f60f775f03 Improve logging 2023-08-31 11:27:52 +01:00
Marek Wolan
7759c178bb Add logging and service restarting 2023-08-31 11:20:16 +01:00
Marek Wolan
3368376596 Merged PR 172: Methods for adding, removing, connecting and disconnecting nodes in the network.
## Summary
- Add public API for adding, removing, connecting and disconnecting nodes in the network.
- Introduce parent of simcomponent to keep track of parent as per this diagram ![Component ownership tree - Page 1 (2).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/172/attachments/Component%20ownership%20tree%20-%20Page%201%20%282%29.png)
- Update tutorial notebook with new way of doing things.

## Test process
Unit and integration tests written and passing.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [ ] I have update the **change log**
- [x] I have run **pre-commit** checks for code style

Related work items: #1798
2023-08-31 10:04:11 +00:00
Chris McCarthy
e73d7f49d6 #1800 - Fixed routing and processing of ICMP packets in the Router class 2023-08-31 11:03:38 +01:00
Marek Wolan
62be66205c Fix unit tests 2023-08-31 10:57:45 +01:00
Chris McCarthy
1bf51c7741 #1800 - Added ACL and routing classes.
- Added .show() methods to new router classes to enable inspection of the components as you would a real router.
- Removed gateway from the NIC and added default_gateway to Node so that Node has a single default gateway.
- Added some routing tests to check that ping can be performed when router between subnets.
2023-08-30 21:38:55 +01:00
Marek Wolan
40d3e04e64 Move init action manager function to the top 2023-08-29 14:33:28 +01:00
Marek Wolan
f0b82cbdfb Add ability to uninstall service 2023-08-29 14:15:49 +01:00
Marek Wolan
9c8b7a7b7a Merge remote-tracking branch 'origin/feature/1789-add-convenience-methods-to-network-object' into feature/1801-Database 2023-08-29 13:22:14 +01:00
Marek Wolan
94325d1fde Add Install method to software. 2023-08-29 13:21:34 +01:00
Marek Wolan
7b61322e70 Add service actions 2023-08-29 12:34:41 +01:00
Marek Wolan
1eff41c786 Update docs based on new action options 2023-08-29 11:10:29 +01:00
Marek Wolan
319e87d200 Make changes to the way actions work 2023-08-28 22:34:20 +01:00
Marek Wolan
6e602aa151 Fix unit tests by removing warning checks 2023-08-25 17:56:05 +01:00
Marek Wolan
ae6e835955 Apply suggestions from code review. 2023-08-25 15:58:07 +01:00
Marek Wolan
a9e969aa13 init work on database 2023-08-25 15:29:53 +01:00
Chris McCarthy
c6f71600fc #1800 - Fixed the ping functionality so that it actually checks for replies and returns True if the right number of replies have been received.
- Added the foundations of a Router class along with ACLRule and RouteTableEntry classes.
2023-08-25 09:07:32 +01:00
Marek Wolan
2dd191bf32 Merge branch 'feature/1789-add-convenience-methods-to-network-object' into feature/1801-Database 2023-08-24 14:41:09 +01:00
Marek Wolan
05bb0f295b Update notebook tutorial on creating a simulation 2023-08-24 13:06:45 +01:00
Marek Wolan
fec44aef53 Rename connect_nodes to connect and fix minor bug 2023-08-24 13:03:16 +01:00
Marek Wolan
78008e3c6e Fix container test 2023-08-24 12:52:38 +01:00
Marek Wolan
7058c7e9a8 Rename networkcontainer to network 2023-08-24 12:41:46 +01:00
Marek Wolan
a818de8f01 Add ability to connect nodes via the network. 2023-08-24 12:40:00 +01:00
Marek Wolan
f38b423886 Update comment 2023-08-24 10:27:30 +01:00
Marek Wolan
4077eb3a5c Add tests for network node adding/removal 2023-08-24 10:26:17 +01:00
Marek Wolan
01e8501bc1 Merged PR 169: Connect all components and add describe_state() methods
## Summary
- Add an object that holds the entire simulation, and a container for the network that keeps track of a list of nodes and links.
- Implement `describe_state()` for all existing sim components and take advantage of the inheritance relationships to avoid repetition.
- Fix some minor mistakes like typehints and indentation errors.
- Write a jupyter notebook which uses the python API to create a simulation and verify that it's `describe_state()` method outputs a correct value.
- Currently the notebook creates the simulation in a janky way, because the API for simulation creation is not fleshed out yet. Further tickets have been added to the backlog to address some of these shortcomings. They are:
  - #1790

## Test process
I have tested that the notebook runs and that after populating a simulation, the describe_state function returns a dictionary full of only serialisable data types.

## Checklist
- [y] This PR is linked to a **work item**
- [y] I have performed **self-review** of the code
- [~] I have written **tests** for any new functionality added with this PR
- [n] I have updated the **documentation** if this PR changes or adds functionality
- [na] I have written/updated **design docs** if this PR implements new functionality
- [y] I have update the **change log**
- [y] I have run **pre-commit** checks for code style

Note:
This ticket also makes a small amount of progress against: #1705, it adds a shell of a network class, but only by creating the class, not implementing any functionality.

Related work items: #1787
2023-08-23 15:24:17 +00:00
Marek Wolan
a82ffb9747 Add notebook outputs back into src control 2023-08-23 15:44:23 +01:00
Marek Wolan
72b019287a Add scratch notebook to gitignore. 2023-08-23 14:41:59 +01:00
Marek Wolan
1613bbe27a Add methods for adding/removing nodes form network 2023-08-23 14:41:30 +01:00
SunilSamra
c1ba3b0850 #1752 - Added comments to ticket 2023-08-22 21:43:57 +01:00
SunilSamra
550b62f75d #1752 - Removed unnecessary print statement
- Changed docstring on function check_domain_in_cache
2023-08-21 16:09:17 +01:00
SunilSamra
1a13af2f5e #1752 - Changed DNSReply and DNSResponse to have 1 parameter only 2023-08-21 14:11:53 +01:00
Marek Wolan
7e64acd368 Update container docstrings 2023-08-21 10:04:23 +01:00
Marek Wolan
07b740a81e Update docs and changelog. 2023-08-21 09:49:31 +01:00
SunilSamra
a0b258a597 #1752 - Added a dns_lookup function to dns_server.py 2023-08-21 09:02:04 +01:00
Marek Wolan
7c16a9cdde Update notebook 2023-08-20 18:43:21 +01:00
Marek Wolan
3911010777 update notebook 2023-08-20 18:42:58 +01:00
Marek Wolan
01c912c094 fix type hints and describe state functions 2023-08-20 18:38:02 +01:00
Marek Wolan
6ca53803cd Describe state 2023-08-17 15:32:12 +01:00
SunilSamra
2919be3796 #1752 - Added web_browser.py application for DNS modelling 2023-08-17 14:20:09 +01:00
Marek Wolan
ced45d4275 Connect actions of top-level sim components 2023-08-16 16:45:52 +01:00
SunilSamra
72cd9fd8e2 #1752 - Created dns.py protocol file with DNSPacket and DNSRequest and DNSReply packets
- Added reset_component logic for dns_server.py and dns_client.py
2023-08-16 13:00:16 +01:00
SunilSamra
76d404dc2f #1752 - Added dns_client.py and dns_server.py service files
- Added new get_install method to software.py
2023-08-15 13:56:38 +01:00
Chris McCarthy
18f57d6418 Added PrimAITE_logo_transparent.png file 2023-08-15 13:56:06 +01:00
Chris McCarthy
58048cd0e1 Dropped sphinx-pipeline 2023-08-15 13:28:02 +01:00
ARCD
eb70acf0c6 Create spinx-pipeline 2023-08-15 13:23:25 +01:00
Chris McCarthy
1a1c3c9344 Added sphinx docs build pipeline for GitHub pages on release 2023-08-15 11:26:15 +01:00
Chris McCarthy
01fb9e65fe Added the DSTL MIT license and updated the license in pyproject.toml 2023-08-15 11:14:23 +01:00
Czar Echavez
d972fcc07e Merged PR 164: File System Class setup fixing tests
## Summary
Attempting to fix a test which seems to be broken when integrated with https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/160

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality.
- [x] I have run **pre-commit** checks for code style

#1714: fixing minor error in test + adding a check for existing uuid when adding file

Related work items: #1714
2023-08-14 08:27:09 +00:00
Czar Echavez
c4aacb8c69 #1714: Change file and folder uuid checking to check for file or folder names already existing 2023-08-11 15:33:07 +01:00
Christopher McCarthy
1b84d28c48 Merged PR 161: Working base Node class
## Summary
- Network Hardware - Added base hardware module with NIC, SwitchPort, Node, Switch, and Link. Nodes and Switches have
fundamental services like ARP, ICMP, and PCAP running them by default.
- Network Transmission - Modelled OSI Model layers 1 through to 5 with various classes for creating network frames and
transmitting them from a Service/Application, down through the layers, over the wire, and back up through the layers to
a Service/Application another machine.
- system - Added the core structure of Application, Services, and Components. Also added a SoftwareManager and
SessionManager.

- #1706 - Got the core Node class build and working with ARP and the ability to ping another node. Added some basic tests in. Next job is to create the Node subclasses. Then move ARP and ICMP into a ser
- #1706 - Added some extra logging
- #1706 - Started adding the core node software required by all nodes. Made some tweaks to the Frame to have send and receive timestamp.
- #1706 - Got the code services, application, and process base classes stubbed out. Need them now so that I can leverage them for core node services required.
- #1706 - Tidied up the SysLog ARPCache, and ICMP classes and integrated them into the Node. Tidied up the base implementation of SoftwareManager and SessionManager. Tidies up the public API for Service

## Test process
Tests really asses how components fit together and that it all does work. They tests don't yet check that things like ICMP work, as in the ping is received and responded to.

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have written/updated **design docs** if this PR implements new functionality.
- [X] I have run **pre-commit** checks for code style

Related work items: #1706
2023-08-10 14:30:04 +00:00
Chris McCarthy
49f855c320 #1706 - Synced with Dev 2023-08-10 13:33:32 +01:00
Chris McCarthy
b902d945ee Merge remote-tracking branch 'devops/dev' into feature/1706_node_class_and_node_type_subclasses
# Conflicts:
#	CHANGELOG.md
#	src/primaite/simulator/core.py
2023-08-10 13:29:14 +01:00
Chris McCarthy
9ee0ef2fd6 #1706 - Applied some final changes from PR. Fixed the PCAP log name on SwitchPort so that a pcap file is generated for each port. 2023-08-10 13:26:51 +01:00
Marek Wolan
586f210402 Merged PR 160: Permission system, account skeleton, and group skeleton
## Summary
This PR implements an outline of accounts and domain controller. However, the main contribution is the permissions system and the changes to `SimComponent`. The domain skeleton will probably change after the node/folder/file/app/service classes exist.

The big idea of the permissions is that the simulator itself is built in a way that permits everything, i.e. the methods of each component that make something happen don't have any permissions checking. Therefore, if you can use primaite without any agents and you will essentially have superadmin, any action you perform will go through. The permissions come into play when you try to interact with the components via the actions. Every action has a configurable permission validator attached to it that will either allow or block the action.

For this reason, I've had to modify the way actions work. To keep everything neatly contained, there is a new Action class that holds a reference to both the action function itself but also to a permission validation function.

## Test process
Unit tests and integration tests.
I will write the design documentation for permissions and update the design for SimComponent once others are happy that the design makes sense.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have updated the **changelog**
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #1716
2023-08-10 12:07:38 +00:00
Marek Wolan
e24d4b8890 Fix typo in test 2023-08-10 09:14:45 +01:00
Chris McCarthy
ad81a81949 #1706 - Applied some code suggestions from the PR 2023-08-09 20:38:45 +01:00
Chris McCarthy
b46057841d #1706 - Refactored a bunch of if statements in base.py to improve readability 2023-08-09 20:31:42 +01:00
Marek Wolan
34ff9abd7a Apply changes from code review. 2023-08-09 15:55:28 +01:00
Czar Echavez
cf241366dc #1714: apply suggestions for preventing addition of objects with similar uuid 2023-08-09 15:15:45 +01:00
Marek Wolan
f198a8b94d Fix bad merge 2023-08-09 12:36:09 +01:00
Marek Wolan
51baabb35b Update enums to uppercase in docs 2023-08-09 12:34:56 +01:00
Marek Wolan
596bbaacde Change enum strings to uppercase 2023-08-09 12:06:06 +01:00
Czar Echavez
572f457231 #1714: fixing minor error in test + adding a check for existing uuid when adding file 2023-08-09 11:19:58 +01:00
Marek Wolan
be8c2955ce Change Accountstatus to a bool 2023-08-09 10:26:52 +01:00
Marek Wolan
1de8e0a058 Update tests 2023-08-09 09:19:11 +01:00
Marek Wolan
a3c2ae6c7d Merge dev into feature/1716-accounts-and-groups 2023-08-09 09:18:06 +01:00
Chris McCarthy
a840159460 #1706 - Fixed the "smart" merging of SimComponent that PyCharm performed. Integrated the Filesystem class into the Node. Added prettytable to deps in pyproject.toml 2023-08-08 20:30:37 +01:00
Chris McCarthy
9fbc3c91f7 #1706 - Finished up the Node and Switch MVP. Added full extensive documentation on what's happening at each step. 2023-08-08 20:22:18 +01:00
Chris McCarthy
4e4c2b501a Merge remote-tracking branch 'devops/dev' into feature/1706_node_class_and_node_type_subclasses
# Conflicts:
#	tests/unit_tests/_primaite/_simulator/test_core.py
2023-08-08 20:05:11 +01:00
Czar Echavez
5f097b7c1b Merged PR 157: File System Class setup
## Summary
Skeleton of the FileSystem for the simulation. Does not have all the requirements for the FileSystem yet, since we need to start somewhere

## Test process
Created unit tests for:
- [FileSystem](https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/157?_a=files&path=/tests/unit_tests/_primaite/_simulator/_file_system/test_file_system.py)
- [FileSystemFolder](https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/157?_a=files&path=/tests/unit_tests/_primaite/_simulator/_file_system/test_file_system_folder.py)
- [FileSystemFile](https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/157?_a=files&path=/tests/unit_tests/_primaite/_simulator/_file_system/test_file_system_file.py)

## Design document
https://dev.azure.com/ma-dev-uk/PrimAITE/_wiki/wikis/PrimAITE.wiki/151/FileSystem

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have written/updated **design docs** if this PR implements new functionality.
- [x] I have run **pre-commit** checks for code style

Related work items: #1714
2023-08-08 09:29:46 +00:00
Czar Echavez
2f27e02877 #1714: fix precommit 2023-08-08 09:53:32 +01:00
Czar Echavez
c2b783c858 Apply suggestions from code review 2023-08-08 08:17:40 +00:00
Czar Echavez
f854404ba0 #1714: added file system to changelog 2023-08-08 08:41:50 +01:00
Czar Echavez
c8ee409b3b #1714: run precommit 2023-08-08 08:29:51 +01:00
Chris McCarthy
139d739732 #1706 - Tidies up the sysLog ARPCache, and ICMP classes and integrated them into the Node. Tidied up the base implementation of SoftwareManager and SessionManager. Tidies up the public API for Services and Applications. Added the SwitchPort and Switch classes. Added a basic test in test_frame_transmission.py that tests sending a frame from one node to another across a multi-switch network. 2023-08-07 19:33:52 +01:00
Marek Wolan
7eb0bb428f Update code based on PR comments. 2023-08-07 17:24:14 +01:00
Czar Echavez
700950b856 Apply suggestions from code review 2023-08-07 15:38:15 +00:00
Czar Echavez
a4c193cd34 #1714: apply recommended changes with removing get methods and using the properties directly 2023-08-07 16:20:55 +01:00
Czar Echavez
554619e4b4 #1714: conver file and folder lists to dicts + fixing and adding a few more tests 2023-08-07 14:49:59 +01:00
Czar Echavez
b58a3a3e24 #1714: FileSystemItem is no longer an abstract base class + Added enums and enum sizes + stream lined FileSystemFile init 2023-08-07 11:52:54 +01:00
Marek Wolan
22afdc9134 Updated pull_request_template.md 2023-08-07 10:19:06 +00:00
Marek Wolan
84b6e2206e Updated CHANGELOG.md 2023-08-07 10:18:27 +00:00
Marek Wolan
f0d7e03fd7 Add docs and tests 2023-08-07 10:55:29 +01:00
Czar Echavez
d57c2a936e #1714: remove duplicate method 2023-08-07 10:10:05 +01:00
Czar Echavez
028211d288 #1714: update to use objects instead of uuids + tests 2023-08-07 09:34:59 +01:00
Marek Wolan
ac9b83cc42 Merge remote-tracking branch 'origin/dev' into feature/1716-accounts-and-groups 2023-08-07 09:15:35 +01:00
Czar Echavez
46c70ac084 #1714: refactor private attributes and made them public + serialisation tests 2023-08-03 22:20:14 +01:00
Chris McCarthy
04f1cb0dc6 #1706 - Got the code services, application, and process base classes stubbed out. Need them now so that I can leverage them for core node services required. 2023-08-03 21:30:13 +01:00
Marek Wolan
2a680c1e48 Test my validators 2023-08-03 16:26:33 +01:00
Chris McCarthy
e7e39a8c1d Merge branch 'github_dev' into downstream_github_sync
# Conflicts:
#	docs/index.rst
#	docs/source/primaite_session.rst
2023-08-03 16:07:15 +01:00
Chris McCarthy
fed65db7fc Updated the What is PrimAITE? section in index.rst. Dropped the use of sphinx-code-tabs in the docs as building the docs in pdf (make latexpdf) is suddenly complaining about the tab buttons. 2023-08-03 16:04:23 +01:00
Chris McCarthy
cac4779244 #1706 - Started adding the core node software required by all nodes. Made some tweaks to the Frame to have send and receive timestamp. 2023-08-03 14:37:55 +01:00
Marek Wolan
94617c57a4 Make register and deregister acct private 2023-08-03 13:24:27 +01:00
Marek Wolan
3a2840bed8 Overhaul sim component for permission management. 2023-08-03 13:09:04 +01:00
Czar Echavez
b08683fcd3 #1714: fix tests 2023-08-03 12:42:16 +01:00
Czar Echavez
483fa7d841 Merge branch 'dev' into feature/1714-file-system-file-system-folder-and-file-system-file-class-skeletons 2023-08-03 12:15:08 +01:00
Czar Echavez
a0356a7fbc #1714: updated file system classes 2023-08-03 12:14:11 +01:00
Chris McCarthy
209f934abd #1706 - Added some extra logging 2023-08-02 22:01:15 +01:00
Chris McCarthy
897dbdf10c #1706 - Got the core Node class build and working with ARP and the ability to ping another node. Added some basic tests in. Next job is to create the Node subclasses. Then move ARP and ICMP into a service that is used by all nodes. 2023-08-02 21:54:21 +01:00
Christopher McCarthy
3660e27c15 Merged PR 156: Model a minimal implementation of a network Frame
## Summary
- Added the primaite/simulator/network/transmission sub-package with modules for each layer. They come together to build a minimal but fairly realistic network Frame.
- A custom PrimaiteHeader has been included to hold primaite specific metadata required in transmission for reward function and RL agent downstream.
- Added some basic tests that check the proper configuration of Frames with matching headers for protocols.
- Updated the frame typehints in NIC and Link classes.
- Added documentation for the transport layer down to data link layer

## Test process
Unit tests check the frame has been configured correctly with the right headers for the right protocol.

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have written/updated **design docs** if this PR implements new functionality.
- [X] I have run **pre-commit** checks for code style

Related work items: #1724
2023-08-02 14:25:58 +00:00
Marek Wolan
091b4a801d Make some progress on accounts 2023-08-02 13:43:31 +01:00
Chris McCarthy
95f5515d69 #1724 - Added documentation for the transport layer down to data link layer 2023-08-02 12:12:08 +01:00
Chris McCarthy
9d17a9b0d3 #1724 - Added the primaite/simulator/network/transmission sub-package with modules for each layer. They come together to build a minimal but fairly realistic network Frame. A custom PrimaiteHeader has been included to hold primaite specific metadata required in transmission for reward function and RL agent downstream. Added some basic tests that check the proper configuration of Frames with matching headers for protocols. Updated the frame typehints in NIC and Link classes. 2023-08-01 22:25:00 +01:00
Czar Echavez
841aafd259 Merge branch 'dev' into feature/1714-file-system-file-system-folder-and-file-system-file-class-skeletons 2023-08-01 16:20:08 +01:00
Czar Echavez
ea8c65a17e #1714: set up files 2023-08-01 16:18:49 +01:00
Christopher McCarthy
f41fc241b7 Merged PR 152: Model Link and NIC
## Summary
- #1715 #1715 - Added Link class in physical_layer.py.- Also added NIC class in physical_layer.py for
#1672. Added attributes and public API functions.
- Added test_physical_layer.py with some basic tests ready to house the tests once logic has been implemented.
- Made use of the pydantic model_post_init function for proper ipv4 configuration checking.
- Added NetworkError to exceptions.py.
- Added timestep int as a param to the apply_timestep function in core.py. Also added a reset_component_for_episode function.
- Updated docs with details of Link and NIC.

## Test process
- Added basic unit tests for instantiation that look at proper config and error raising.
- Added an integration test for linking NICs to Link.

## Checklist
- [ ] This PR is linked to a **work item**
- [ ] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have run **pre-commit** checks for code style

Related work items: #1672, #1715
2023-08-01 12:31:42 +00:00
Marek Wolan
dda986fc56 Merge remote-tracking branch 'origin/dev' into feature/1716-accounts-and-groups 2023-08-01 12:52:17 +01:00
Chris McCarthy
0f33b837aa #1715 - Fixed up pr code suggestion flake8 issues 2023-08-01 12:45:36 +01:00
Christopher McCarthy
5ee3eff0e9 Apply suggestions from code review 2023-08-01 11:14:36 +00:00
Christopher McCarthy
2769b1bfb1 Apply suggestions from code review 2023-08-01 11:04:16 +00:00
Chris McCarthy
8785089a1c #1715 - Moved IPv4Address conversions to the NIC init. Mak wake_on_lan not optional. Ignored ANN002 and ANN003 in .flake8 so we don't get silly 'ANN002 Missing type annotation for *args' and 'ANN003 Missing type annotation for **kwargs' flake8 failures 2023-08-01 10:32:16 +01:00
Marek Wolan
5ebbfab0ff Create some files for domain sim 2023-08-01 10:02:13 +01:00
Chris McCarthy
557caeaac4 #1715 - Added suppress-none-returning and suppress-dummy-args to .flake8 as flake8-annotations can get very annoying 2023-08-01 08:19:28 +01:00
Chris McCarthy
c05cb62aa9 Merge branch 'dev' into feature/1715_model_link 2023-08-01 08:12:39 +01:00
Marek Wolan
0f0c61642c Merged PR 151: Check type hints with pre-commit
## Summary
Added `flake8-annotations` to the pre-commit hooks. This ensures that we all write type hints for all new code.

There's also a minor unrelated addition to the pre-commit template.

## Test process
I tried adding a function with a parameter but no typehint. Git did not allow me to commit this.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #1721
2023-07-31 19:34:48 +00:00
Chris McCarthy
e4b6f266e8 #1715 - Added timestep int as a param to the apply_timestep function in core.py. Also added a reset_component_for_episode function. Updated docs with details of Link and NIC. 2023-07-31 20:05:36 +01:00
Marek Wolan
3324a8caae Apply suggestions from code review 2023-07-31 18:54:29 +00:00
Marek Wolan
c1bb6d8b7f Update the PR template 2023-07-31 17:09:38 +01:00
Marek Wolan
9cf5bfa1b2 Fix typehint issues 2023-07-31 17:07:56 +01:00
Marek Wolan
0a079832e9 Add self,cls to flake8-ann ignore list 2023-07-31 17:00:28 +01:00
Chris McCarthy
0532db960a #1715 - Added more tests. MAde use of the pydantic model_post_init function for proper ipv4 cofiguration checking. Added NetworkError to exceptions.py. 2023-07-31 16:55:45 +01:00
Marek Wolan
c4adc2f543 add flake8-annotations to pre-commits 2023-07-31 16:47:13 +01:00
Chris McCarthy
59394c3642 #1715 - Added Link class in physical_layer.py. Also added NIC class in physical_layer.py for #1672. Added attributes and public API functions. test_physical_layer.py ready to house the tests once logic has been implemented. 2023-07-31 15:55:22 +01:00
Marek Wolan
020682f546 Merged PR 149: Base class for Simulation Components
## Summary
This introduces a base class for all simulation components. The idea behind this is to formalise the way in which data is extracted from the simulator and the way actions are applied to the different aspects of the simulator.

The intention is that any class that simulates something will inherit from SimComponent (which inherits from pydantic BaseModel).

Actions enter the simulator as a list of strings that is intended to be peeled back as you go down the layers of the simulation. For example we could have an action of `["network", "nodes", "node3", "network_interface_card", "disable"]` This list is passed to the `apply_action()` function of the overall simulation controller. The simulation controller looks at the first word on the list, `network` and uses this to select a method that can apply the function. It passes the remainder of the list as an argument to that function. In this case it will be `["nodes", "node3", "network_interface_card", "disable"]`.

To the reviewers, please validate that you're happy with the implicit design choices I've made while implementing this. Especially the contract passing actions down the components tree.

(also I changed some mentions of agent to agent_abc in the docs as it was complaining and refusing to build.)

## Test process
I have written basic unit tests to check that the custom functionality added to SimComponent doesn't interfere with basic pydantic functionality.
I also started doc pages that explains these concepts to potential developers, although once there are subclasses of this core class, it will be easier to populate the docs with concrete examples.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style
- [x] I have **type hinted** all the code I changed.

Related work items: #1709
2023-07-31 12:43:07 +00:00
Marek Wolan
954026d3e0 Comment out RLLib support 2023-07-31 12:13:52 +01:00
Marek Wolan
a486780fba Add timestep function 2023-07-31 11:39:33 +01:00
Marek Wolan
fa2cdf853c Drop Ray 2023-07-31 11:27:16 +01:00
Marek Wolan
8e2ef1b695 Apply suggestions from code review 2023-07-31 10:25:29 +00:00
jamesshort1
80ddf511dc Update README.md 2023-07-31 09:17:48 +01:00
jamesshort1
61fe8c2031 Update README.md 2023-07-31 09:16:24 +01:00
Christopher McCarthy
fd28475e83 Merged PR 148: 1711 Fix legacy config loading issues
## Summary
Added the ability to load legacy lay down config files. Added extensive unit testing and end-to-end testing. Also added the ability to set exactly how many num_train_steps, num_eval_steps, num_train_episodes, and num_eval_episode and used when converting a legacy training config.

## Test process
Full unit test and end-to-end test

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

Related work items: #1711
2023-07-28 14:45:58 +00:00
Marek Wolan
3b4a01760b Rework apply_actions to make it more standard 2023-07-28 15:14:43 +01:00
Marek Wolan
c1bcc372b1 Merge remote-tracking branch 'origin/dev' into feature/1709-base-simulation-class 2023-07-28 14:49:56 +01:00
Marek Wolan
b129c4fc97 Add SimComponent core class 2023-07-28 14:49:21 +01:00
Chris McCarthy
0f8d31c72c #1711 - Last minute docs changes 2023-07-28 14:41:39 +01:00
Chris McCarthy
77e7941510 #1711 - Last minute docs changes 2023-07-28 14:39:01 +01:00
Chris McCarthy
e8349a8ca3 Merge branch 'github_dev' into bugfix/1711_Fix_legacy_config_loading_issues 2023-07-28 14:13:37 +01:00
Chris McCarthy
bb8b41a5ec #1711 - Removed the legacy bools from the RLlibAgent constructor in primaite_session.py 2023-07-28 14:02:17 +01:00
Chris McCarthy
0fb9268f44 #1711 - Fully Integrated the legacy training config and lay down config options into the CLI, run PrimaiteSession, and Agent classes. Made the ese test in test_full_legacy_config_session.py use this new integrated option to read the legacy file. 2023-07-28 13:49:26 +01:00
Chris McCarthy
c276281a64 Merge branch 'github_dev' into bugfix/1711_Fix_legacy_config_loading_issues 2023-07-28 12:55:58 +01:00
Chris McCarthy
baed7445c9 Merge remote-tracking branch 'github/dev' into github_dev 2023-07-28 12:54:58 +01:00
Chris McCarthy
7c843d3caa #1711 - Added the ability to load legacy lay down config files. Added extensive unit testing and end-to-end testing. Also added the ability to set exactly how many num_train_steps, num_eval_steps, num_train_episodes, and num_eval_episode and used when converting a legacy training config. 2023-07-28 12:53:49 +01:00
jamesshort1
e62846255f Update README.md 2023-07-28 09:41:29 +01:00
jamesshort1
546c66c542 Update README.md 2023-07-28 09:40:05 +01:00
jamesshort1
74e3dabae9 Update README.md 2023-07-28 09:39:05 +01:00
Christopher McCarthy
2642cc97de Merged PR 146: Final sync with github v2.0.0 release 2023-07-27 16:24:17 +00:00
Chris McCarthy
3f34c76b3c Merge branch 'github_dev' into release/2.0.0 2023-07-27 17:22:17 +01:00
jamesshort1
378001ff68 Update README.md 2023-07-27 14:57:08 +01:00
Chris McCarthy
92671796a1 Added GFX license conditions. Included LICENSE file in build. Fixed a few character issues in README.md 2023-07-27 11:40:29 +01:00
Chris McCarthy
858396f3d6 Dropped MIT license until public release 2023-07-27 11:03:25 +01:00
jamesshort1
fde033b387 Update README.md 2023-07-27 08:59:43 +01:00
jamesshort1
bd30bab096 Update README.md 2023-07-27 08:59:24 +01:00
Christopher McCarthy
4baff171af Merged PR 144: v2.0.0 GitHub release sync
v2.0.0 GitHub release sync

Related work items: #901, #1523, #1574, #1594, #1595, #1597, #1623, #1626, #1629, #1631, #1632, #1635, #1637, #1638, #1639, #1640, #1641, #1647, #1648, #1650
2023-07-27 07:46:59 +00:00
Chris McCarthy
31e2af6db1 Merge branch 'github_dev' into release/2.0.0 2023-07-27 08:43:33 +01:00
Chris McCarthy
c5a23fa035 Added run section with primaite session command in the README.md 2023-07-26 22:10:59 +01:00
Chris McCarthy
6cf18e7808 Merge branch 'github_dev' into release/2.0.0 2023-07-26 22:08:19 +01:00
Chris McCarthy
472e85cffb Added additional install instructions to the README.md 2023-07-26 21:49:36 +01:00
Chris McCarthy
fce4e78933 Synced with the github repo release 2023-07-26 21:40:30 +01:00
Chris McCarthy
499219eb40 Added project urls to pyproject.toml and a setup.cfg file for PyPi to pickup author and url 2023-07-26 21:11:15 +01:00
Chris McCarthy
efbb6ef8df Added a CONTRIBUTING.md and added a URL to the Yawning-Titan reference in index.rst 2023-07-26 20:17:29 +01:00
Chris McCarthy
1c4695d391 Dropped the ADF build files and updated the package name install step in python-package.yml. Added bug_report.md and feature_request.md files for GitHub 2023-07-26 20:05:44 +01:00
Chris McCarthy
5c5528bb94 Updated the README.md with developer install specific instructions 2023-07-26 19:49:24 +01:00
Chris McCarthy
1c35b109b1 Merge remote-tracking branch 'devops/main' into github_dev 2023-07-26 19:43:46 +01:00
Chris McCarthy
c6cbb5ae8d Create python-package.yml CI pipeline 2023-07-26 19:38:28 +01:00
Christopher McCarthy
1f7677270b Merged PR 143: v2.0.0
v2.0.0
2023-07-26 18:21:18 +00:00
Chris McCarthy
7f8666b3d1 Create README.md 2023-07-20 10:55:59 +01:00
549 changed files with 80219 additions and 15335 deletions

View File

@@ -0,0 +1,108 @@
trigger:
- release/*
schedules:
- cron: "0 2 * * 1-5" # Run at 2 AM every weekday
displayName: "Weekday Schedule"
branches:
include:
- 'refs/heads/dev'
variables:
VERSION: ''
MAJOR_VERSION: ''
jobs:
- job: PrimAITE_Benchmark
timeoutInMinutes: 360 # 6-hour maximum
pool:
name: 'Imaginary Yak Pool'
workspace:
clean: all
steps:
- checkout: self
persistCredentials: true
- script: |
python3.10 -m venv venv
displayName: 'Create venv'
- script: |
VERSION=$(cat src/primaite/VERSION | tr -d '\n')
if [[ "$(Build.SourceBranch)" == "refs/heads/dev" ]]; then
DATE=$(date +%Y%m%d)
echo "${VERSION}+dev.${DATE}" > src/primaite/VERSION
fi
displayName: 'Update VERSION file for Dev Benchmark'
- script: |
VERSION=$(cat src/primaite/VERSION | tr -d '\n')
MAJOR_VERSION=$(echo $VERSION | cut -d. -f1)
echo "##vso[task.setvariable variable=VERSION]$VERSION"
echo "##vso[task.setvariable variable=MAJOR_VERSION]$MAJOR_VERSION"
displayName: 'Set Version Variables'
- script: |
source venv/bin/activate
pip install --upgrade pip
pip install -e .[dev,rl]
primaite setup
displayName: 'Install Dependencies'
- script: |
set -e
source venv/bin/activate
cd benchmark
python primaite_benchmark.py
cd ..
displayName: 'Run Benchmarking Script'
- script: |
tar czf primaite_v$(VERSION)_benchmark.tar.gz benchmark/results/v$(MAJOR_VERSION)/v$(VERSION)
displayName: 'Prepare Artifacts for Publishing'
- task: PublishPipelineArtifact@1
inputs:
targetPath: primaite_v$(VERSION)_benchmark.tar.gz
artifactName: 'benchmark-zip-output'
publishLocation: 'pipeline'
displayName: 'Publish Benchmark Output zip as Artifact'
- script: |
git config --global user.email "oss@dstl.gov.uk"
git config --global user.name "Defence Science and Technology Laboratory UK"
workingDirectory: $(System.DefaultWorkingDirectory)
displayName: 'Configure Git'
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/heads/release'))
- script: |
echo "Fetching all branches..."
git fetch --all --prune
echo "Stashing files..."
git stash push -u
echo "Resolving branch name..."
# Extracting just the branch name from the full ref path
branch_name=$(echo "$(Build.SourceBranch)" | sed 's|refs/heads/||')
echo "Branch Name: $branch_name"
echo "Checking out branch $branch_name..."
git checkout $branch_name
echo "Popping stash..."
git stash pop
echo "Adding benchmark results..."
git add benchmark/results/v$(MAJOR_VERSION)/v$(VERSION)/*
echo "Committing changes..."
git commit -m "Automated benchmark output commit for version $(VERSION) [skip ci]"
echo "Pushing to remote..."
git push origin $branch_name
displayName: 'Commit and Push Benchmark Results'
workingDirectory: $(System.DefaultWorkingDirectory)
env:
GIT_CREDENTIALS: $(System.AccessToken)
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/heads/release'))

View File

@@ -26,8 +26,12 @@ jobs:
displayName: 'Install build dependencies'
- script: |
pip install -e .[dev]
displayName: 'Install Yawning-Titan for docs autosummary'
pip install -e .[dev,rl]
displayName: 'Install PrimAITE for docs autosummary'
- script: |
sudo apt-get install pandoc
displayName: 'Install Pandoc'
- script: |
primaite setup

View File

@@ -6,45 +6,55 @@ trigger:
- bugfix/*
- release/*
pr:
autoCancel: true
drafts: false
parameters:
# https://stackoverflow.com/a/70046417
- name: matrix
type: object
default:
- job_name: 'UbuntuPython38'
py: '3.8'
img: 'ubuntu-latest'
every_time: false
- job_name: 'UbuntuPython310'
py: '3.10'
# - job_name: 'UbuntuPython38'
# py: '3.8'
# img: 'ubuntu-latest'
# every_time: false
# publish_coverage: false
- job_name: 'UbuntuPython311'
py: '3.11'
img: 'ubuntu-latest'
every_time: true
- job_name: 'WindowsPython38'
py: '3.8'
publish_coverage: true
# - job_name: 'WindowsPython38'
# py: '3.8'
# img: 'windows-latest'
# every_time: false
# publish_coverage: false
- job_name: 'WindowsPython311'
py: '3.11'
img: 'windows-latest'
every_time: false
- job_name: 'WindowsPython310'
py: '3.10'
img: 'windows-latest'
every_time: false
- job_name: 'MacOSPython38'
py: '3.8'
img: 'macOS-latest'
every_time: false
- job_name: 'MacOSPython310'
py: '3.10'
publish_coverage: false
# - job_name: 'MacOSPython38'
# py: '3.8'
# img: 'macOS-latest'
# every_time: false
# publish_coverage: false
- job_name: 'MacOSPython311'
py: '3.11'
img: 'macOS-latest'
every_time: false
publish_coverage: false
stages:
- stage: Test
jobs:
- ${{ each item in parameters.matrix }}:
- job: ${{ item.job_name }}
timeoutInMinutes: 90
cancelTimeoutInMinutes: 1
pool:
vmImage: ${{ item.img }}
condition: or( eq(variables['Build.Reason'], 'PullRequest'), ${{ item.every_time }} )
condition: and(succeeded(), or( eq(variables['Build.Reason'], 'PullRequest'), ${{ item.every_time }} ))
steps:
- task: UsePythonVersion@0
@@ -72,12 +82,12 @@ stages:
- script: |
PRIMAITE_WHEEL=$(ls ./dist/primaite*.whl)
python -m pip install $PRIMAITE_WHEEL[dev]
python -m pip install $PRIMAITE_WHEEL[dev,rl]
displayName: 'Install PrimAITE'
condition: or(eq( variables['Agent.OS'], 'Linux' ), eq( variables['Agent.OS'], 'Darwin' ))
- script: |
forfiles /p dist\ /m *.whl /c "cmd /c python -m pip install @file[dev]"
forfiles /p dist\ /m *.whl /c "cmd /c python -m pip install @file[dev,rl]"
displayName: 'Install PrimAITE'
condition: eq( variables['Agent.OS'], 'Windows_NT' )
@@ -85,6 +95,34 @@ stages:
primaite setup
displayName: 'Perform PrimAITE Setup'
- task: UseDotNet@2
displayName: 'Install dotnet dependencies'
inputs:
packageType: 'sdk'
version: '2.1.x'
- script: |
pytest -n 4
displayName: 'Run tests'
coverage run -m --source=primaite pytest -v -o junit_family=xunit2 --junitxml=junit/test-results.xml --cov-fail-under=80
coverage xml -o coverage.xml -i
coverage html -d htmlcov -i
displayName: 'Run tests and code coverage'
- task: PublishTestResults@2
condition: succeededOrFailed()
inputs:
testRunner: JUnit
testResultsFiles: 'junit/**.xml'
testRunTitle: 'Publish test results'
failTaskOnFailedTests: true
- publish: $(System.DefaultWorkingDirectory)/htmlcov/
# publish the html report - so we can debug the coverage if needed
condition: ${{ item.publish_coverage }} # should only be run once
artifact: coverage_report
- task: PublishCodeCoverageResults@2
# publish the code coverage so it can be viewed in the run coverage page
condition: ${{ item.publish_coverage }} # should only be run once
inputs:
codeCoverageTool: Cobertura
summaryFileLocation: '$(System.DefaultWorkingDirectory)/**/coverage.xml'

View File

@@ -1,12 +1,16 @@
## Summary
*Replace this text with an explanation of what the changes are and how you implemented them. Can this impact any other parts of the codebase that we should keep in mind?*
## Test process
*How have you tested this (if applicable)?*
## Checklist
- [ ] This PR is linked to a **work item**
- [ ] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have run **pre-commit** checks for code style
## Summary
*Replace this text with an explanation of what the changes are and how you implemented them. Can this impact any other parts of the codebase that we should keep in mind?*
## Test process
*How have you tested this (if applicable)?*
## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

View File

@@ -9,5 +9,12 @@ extend-ignore =
E712
D401
F811
ANN002
ANN003
ANN101
ANN102
exclude =
docs/source/*
tests/*
suppress-none-returning=True
suppress-dummy-args=True

41
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,41 @@
---
name: Bug report
about: Create a report to help us improve
title: "[BUG] - <bug title goes here>"
labels: bug
assignees: ''
---
### Describe the bug:
A clear and concise description of what the bug is.
### To Reproduce:
Steps to reproduce the behaviour:
1. Import '...'
2. Instantiate '....'
3. Pass to '....'
4. Run '....'
5. See error
### Expected behaviour
A clear and concise description of what you expected to happen.
### Screenshots/Outputs
If applicable, add screenshots to help explain your problem.
### Environment (please complete the following information)
- **OS:** [e.g. Ubuntu 22.04]
- **Python:** [e.g. 3.10.11]
- **PrimAITE Version:** [e.g. v2.0.0]
- **Software:** [e.g. cli, Jupyter, PyCharm, VSCode etc.]
### Additional context
Add any other context about the problem here.

View File

@@ -0,0 +1,24 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[REQUEST] - <request title goes here>"
labels: feature_request
assignees: ''
---
### Is your feature request related to a problem?
If so, please give a concise description of what the problem is. Ex. I'm always frustrated when [...]
### Describe the solution you'd like:
A clear and concise description of what you want to happen.
### Describe alternatives you've considered:
A clear and concise description of any alternative solutions or features you've considered.
### Additional context:
Add any other context or screenshots about the feature request here.

60
.github/workflows/build-sphinx.yml vendored Normal file
View File

@@ -0,0 +1,60 @@
name: build-sphinx-to-github-pages
env:
GITHUB_ACTOR: {todo:fill in URL}
GITHUB_REPOSITORY: {todo:fill in URL}/PrimAITE
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN}}
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10"]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install python dev
run: |
set -x
sudo apt-get update
sudo add-apt-repository ppa:deadsnakes/ppa -y
sudo apt install python${{ matrix.python-version}}-dev -y
- name: Install Git
run: |
set -x
sudo apt-get install -y git
shell: bash
- name: Set pip, wheel, setuptools versions
run: |
python -m pip install --upgrade pip==23.0.1
pip install wheel==0.38.4 --upgrade
pip install setuptools==66 --upgrade
pip install build
- name: Install PrimAITE for docs autosummary
run: |
set -x
python -m pip install -e .[dev,rl]
- name: Run build script for Sphinx pages
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -x
bash $PWD/docs/build-sphinx-docs-to-github-pages.sh

57
.github/workflows/python-package.yml vendored Normal file
View File

@@ -0,0 +1,57 @@
name: Python package
on:
push:
branches:
- main
- dev
- 'release/**'
pull_request:
branches:
- main
- dev
- 'release/**'
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.9", "3.10", "3.11"]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install python dev
run: |
sudo apt update
sudo add-apt-repository ppa:deadsnakes/ppa -y
sudo apt install python${{ matrix.python-version}}-dev -y
- name: Install Build Dependencies
run: |
python -m pip install --upgrade pip==23.0.1
pip install wheel==0.38.4 --upgrade
pip install setuptools==66 --upgrade
pip install build
- name: Build PrimAITE
run: |
python -m build
- name: Install PrimAITE
run: |
PRIMAITE_WHEEL=$(ls ./dist/primaite*.whl)
python -m pip install $PRIMAITE_WHEEL[dev,rl]
- name: Perform PrimAITE Setup
run: |
primaite setup
- name: Run tests
run: |
pytest tests/

20
.gitignore vendored
View File

@@ -37,6 +37,7 @@ pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
junit/
htmlcov/
.tox/
.nox/
@@ -81,6 +82,10 @@ target/
# Jupyter Notebook
.ipynb_checkpoints
PPO_UC2/
# ignore everything but the executed notebooks rst in the docs/source/notebooks directory
!docs/source/notebooks/executed_notebooks.rst
docs/source/notebooks/**/*
# IPython
profile_default/
@@ -143,10 +148,23 @@ cython_debug/
# IDE
.idea/
docs/source/primaite-dependencies.rst
.vscode/
# outputs
src/primaite/outputs/
simulation_output/
sessions/
PrimAITE-PPO-example-agent.zip
# benchmark session outputs
benchmark/output
# src/primaite/notebooks/scratch.ipynb
src/primaite/notebooks/scratch.py
sandbox.py
sandbox/
sandbox.ipynb
# benchmarking
**/benchmark/sessions/
**/benchmark/output/

View File

@@ -1,12 +1,21 @@
repos:
- repo: local
hooks:
- id: ensure-copyright-clause
name: ensure copyright clause
entry: python copyright_clause_pre_commit_hook.py
language: python
- repo: http://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: check-yaml
exclude: |
| scenario_with_placeholders/
| mini_scenario_with_simulation_variation/
- id: end-of-file-fixer
- id: trailing-whitespace
- id: check-added-large-files
args: ['--maxkb=1000']
args: ['--maxkb=5000']
- id: mixed-line-ending
- id: requirements-txt-fixer
- repo: http://github.com/psf/black
@@ -27,3 +36,8 @@ repos:
- id: flake8
additional_dependencies:
- flake8-docstrings
- flake8-annotations
- repo: https://github.com/kynan/nbstripout
rev: 0.7.1
hooks:
- id: nbstripout

View File

@@ -5,7 +5,158 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 3.0.0b9
- Removed deprecated `PrimaiteSession` class.
- Added ability to set log levels via configuration.
- Upgraded pydantic to version 2.7.0
- Upgraded Ray to version >= 2.9
- Added ipywidgets to the dependencies
- Added ability to define scenarios that change depending on the episode number.
- Standardised Environment API by renaming the config parameter of `PrimaiteGymEnv` from `game_config` to `env_config`
- Database Connection ID's are now created/issued by DatabaseService and not DatabaseClient
- Updated DatabaseClient so that it can now have a single native DatabaseClientConnection along with a collection of DatabaseClientConnection's.
- Implemented the uninstall functionality for DatabaseClient so that all connections are terminated at the DatabaseService.
- Added the ability for a DatabaseService to terminate a connection.
- Added active_connection to DatabaseClientConnection so that if the connection is terminated active_connection is set to False and the object can no longer be used.
- Added additional show functions to enable connection inspection.
- Updates to agent logging, to include the reward both per step and per episode.
- Introduced Developer CLI tools to assist with developing/debugging PrimAITE
- Can be enabled via `primaite dev-mode enable`
- Activating dev-mode will change the location where the sessions will be output - by default will output where the PrimAITE repository is located
- Refactored all air-space usage to that a new instance of AirSpace is created for each instance of Network. This 1:1 relationship between network and airspace will allow parallelization.
- Added notebook to demonstrate use of SubprocVecEnv from SB3 to vectorise environments to speed up training.
## [Unreleased]
- Made requests fail to reach their target if the node is off
- Added responses to requests
- Made environment reset completely recreate the game object.
- Changed the red agent in the data manipulation scenario to randomly choose client 1 or client 2 to start its attack.
- Changed the data manipulation scenario to include a second green agent on client 1.
- Refactored actions and observations to be configurable via object name, instead of UUID.
- Made database patch correctly take 2 timesteps instead of being immediate
- Made database patch only possible when the software is compromised or good, it's no longer possible when the software is OFF or RESETTING
- Added a notebook which explains Data manipulation scenario, demonstrates the attack, and shows off blue agent's action space, observation space, and reward function.
- Made packet capture and system logging optional (off by default). To turn on, change the io_settings.save_pcap_logs and io_settings.save_sys_logs settings in the config.
- Made observation space flattening optional (on by default). To turn off for an agent, change the `agent_settings.flatten_obs` setting in the config.
- Added support for SQL INSERT command.
- Added ability to log each agent's action choices in each step to a JSON file.
- Removal of Link bandwidth hardcoding. This can now be configured via the network configuraiton yaml. Will default to 100 if not present.
- Added NMAP application to all host and layer-3 network nodes.
### Bug Fixes
- ACL rules were not resetting on episode reset.
- ACLs were not showing up correctly in the observation space.
- Blue agent's ACL actions were being applied against the wrong IP addresses
- Deleted files and folders did not reset correctly on episode reset.
- Service health status was using the actual health state instead of the visible health state
- Database file health status was using the incorrect value for negative rewards
- Preventing file actions from reaching their intended file
- The data manipulation attack was triggered at episode start.
- FTP STOR stored an additional copy on the client machine's filesystem
- The red agent acted to early
- Order of service health state
- Starting a node didn't start the services on it
- Fixed an issue where the services were still able to run even though the node the service is installed on is turned off
- The use of NODE_FILE_CHECKHASH and NODE_FOLDER_CHECKHASH in the current release is marked as 'Not Implemented'.
### Added
- Network Hardware - Added base hardware module with NIC, SwitchPort, Node, and Link. Nodes have
fundamental services like ARP, ICMP, and PCAP running them by default.
- Network Transmission - Modelled OSI Model layers 1 through to 5 with various classes for creating network frames and
transmitting them from a Service/Application, down through the layers, over the wire, and back up through the layers to
a Service/Application another machine.
- Introduced `Router` and `Switch` classes to manage networking routes more effectively.
- Added `ACLRule` and `RouteTableEntry` classes as part of the `Router`.
- New `.show()` methods in all network component classes to inspect the state in either plain text or markdown formats.
- Added `Computer` and `Server` class to better differentiate types of network nodes.
- Integrated a new Use Case 2 network into the system.
- New unit tests to verify routing between different subnets using `.ping()`.
- system - Added the core structure of Application, Services, and Components. Also added a SoftwareManager and
SessionManager.
- Permission System - each action can define criteria that will be used to permit or deny agent actions.
- File System - ability to emulate a node's file system during a simulation
- Example notebooks - There are 5 jupyter notebook which walk through using PrimAITE
1. Training a Stable Baselines 3 agent
2. Training a single agent system using Ray RLLib
3. Training a multi-agent system Ray RLLib
4. Data manipulation end to end demonstration
5. Data manipulation scenario with customised red agents
- Database:
- `DatabaseClient` and `DatabaseService` created to allow emulation of database actions
- Ability for `DatabaseService` to backup its data to another server via FTP and restore data from backup
- Red Agent Services:
- Data Manipulator Bot - A red agent service which sends a payload to a target machine. (By default this payload is a SQL query that breaks a database). The attack runs in stages with a random, configurable probability of succeeding.
- `DataManipulationAgent` runs the Data Manipulator Bot according to a configured start step, frequency and variance.
- DNS Services: `DNSClient` and `DNSServer`
- FTP Services: `FTPClient` and `FTPServer`
- HTTP Services: `WebBrowser` to simulate a web client and `WebServer`
- NTP Services: `NTPClient` and `NTPServer`
- **RouterNIC Class**: Introduced a new class `RouterNIC`, extending the standard `NIC` functionality. This class is specifically designed for router operations, optimizing the processing and routing of network traffic.
- **Custom Layer-3 Processing**: The `RouterNIC` class includes custom handling for network frames, bypassing standard Node NIC's Layer 3 broadcast/unicast checks. This allows for more efficient routing behavior in network scenarios where router-specific frame processing is required.
- **Enhanced Frame Reception**: The `receive_frame` method in `RouterNIC` is tailored to handle frames based on Layer 2 (Ethernet) checks, focusing on MAC address-based routing and broadcast frame acceptance.
- **Subnet-Wide Broadcasting for Services and Applications**: Implemented the ability for services and applications to conduct broadcasts across an entire IPv4 subnet within the network simulation framework.
- Introduced the `NetworkInterface` abstract class to provide a common interface for all network interfaces. Subclasses are divided into two main categories: `WiredNetworkInterface` and `WirelessNetworkInterface`, each serving as an abstract base class (ABC) for more specific interface types. Under `WiredNetworkInterface`, the subclasses `NIC` and `SwitchPort` were added. For wireless interfaces, `WirelessNIC` and `WirelessAccessPoint` are the subclasses under `WirelessNetworkInterface`.
- Added `Layer3Interface` as an abstract base class for networking functionalities at layer 3, including IP addressing and routing capabilities. This class is inherited by `NIC`, `WirelessNIC`, and `WirelessAccessPoint` to provide them with layer 3 capabilities, facilitating their role in both wired and wireless networking contexts with IP-based communication.
- Created the `ARP` and `ICMP` service classes to handle Address Resolution Protocol operations and Internet Control Message Protocol messages, respectively, with `RouterARP` and `RouterICMP` for router-specific implementations.
- Created `HostNode` as a subclass of `Node`, extending its functionality with host-specific services and applications. This class is designed to represent end-user devices like computers or servers that can initiate and respond to network communications.
- Introduced a new `IPV4Address` type in the Pydantic model for enhanced validation and auto-conversion of IPv4 addresses from strings using an `ipv4_validator`.
- Comprehensive documentation for the Node and its network interfaces, detailing the operational workflow from frame reception to application-level processing.
- Detailed descriptions of the Session Manager and Software Manager functionalities, including their roles in managing sessions, software services, and applications within the simulation.
- Documentation for the Packet Capture (PCAP) service and SysLog functionality, highlighting their importance in logging network frames and system events, respectively.
- Expanded documentation on network devices such as Routers, Switches, Computers, and Switch Nodes, explaining their specific processing logic and protocol support.
- **Firewall Node**: Introduced the `Firewall` class extending the functionality of the existing `Router` class. The `Firewall` class incorporates advanced features to scrutinize, direct, and filter traffic between various network zones, guided by predefined security rules and policies. Key functionalities include:
- Access Control Lists (ACLs) for traffic filtering based on IP addresses, protocols, and port numbers.
- Network zone segmentation for managing traffic across external, internal, and DMZ (De-Militarized Zone) networks.
- Interface configuration to establish connectivity and define network parameters for external, internal, and DMZ interfaces.
- Protocol and service management to oversee traffic and enforce security policies.
- Dynamic traffic processing and filtering to ensure network security and integrity.
- `AirSpace` class to simulate wireless communications, managing wireless interfaces and facilitating the transmission of frames within specified frequencies.
- `AirSpaceFrequency` enum for defining standard wireless frequencies, including 2.4 GHz and 5 GHz bands, to support realistic wireless network simulations.
- `WirelessRouter` class, extending the `Router` class, to incorporate wireless networking capabilities alongside traditional wired connections. This class allows the configuration of wireless access points with specific IP settings and operating frequencies.
- Documentation Updates:
- Examples include how to set up PrimAITE session via config
- Examples include how to create nodes and install software via config
- Examples include how to set up PrimAITE session via Python
- Examples include how to create nodes and install software via Python
- Added missing ``DoSBot`` documentation page
- Added diagrams where needed to make understanding some things easier
- Templated parts of the documentation to prevent unnecessary repetition and for easier maintaining of documentation
- Separated documentation pages of some items i.e. client and server software were on the same pages - which may make things confusing
- Configuration section at the bottom of the software pages specifying the configuration options available (and which ones are optional)
- Ability to add ``Firewall`` node via config
- Ability to add ``Router`` routes via config
- Ability to add ``Router``/``Firewall`` ``ACLRule`` via config
- NMNE capturing capabilities to `NetworkInterface` class for detecting and logging Malicious Network Events.
- New `nmne_config` settings in the simulation configuration to enable NMNE capturing and specify keywords such as "DELETE".
- Router-specific SessionManager Implementation: Introduced a specialized version of the SessionManager tailored for router operations. This enhancement enables the SessionManager to determine the routing path by consulting the route table.
### Changed
- Integrated the RouteTable into the Routers frame processing.
- Frames are now dropped when their TTL reaches 0
- **NIC Functionality Update**: Updated the Network Interface Card (`NIC`) functionality to support Layer 3 (L3) broadcasts.
- **Layer 3 Broadcast Handling**: Enhanced the existing `NIC` classes to correctly process and handle Layer 3 broadcasts. This update allows devices using standard NICs to effectively participate in network activities that involve L3 broadcasting.
- **Improved Frame Reception Logic**: The `receive_frame` method of the `NIC` class has been updated to include additional checks and handling for L3 broadcasts, ensuring proper frame processing in a wider range of network scenarios.
- Standardised the way network interfaces are accessed across all `Node` subclasses (`HostNode`, `Router`, `Switch`) by maintaining a comprehensive `network_interface` attribute. This attribute captures all network interfaces by their port number, streamlining the management and interaction with network interfaces across different types of nodes.
- Refactored all tests to utilise new `Node` subclasses (`Computer`, `Server`, `Router`, `Switch`) instead of creating generic `Node` instances and manually adding network interfaces. This change aligns test setups more closely with the intended use cases and hierarchies within the network simulation framework.
- Updated all tests to employ the `Network()` class for managing nodes and their connections, ensuring a consistent and structured approach to setting up network topologies in testing scenarios.
- **ACLRule Wildcard Masking**: Updated the `ACLRule` class to support IP ranges using wildcard masking. This enhancement allows for more flexible and granular control over traffic filtering, enabling the specification of broader or more specific IP address ranges in ACL rules.
- Updated `NetworkInterface` documentation to reflect the new NMNE capturing features and how to use them.
- Integration of NMNE capturing functionality within the `NICObservation` class.
- Changed blue action set to enable applying node scan, reset, start, and shutdown to every host in data manipulation scenario
### Removed
- Removed legacy simulation modules: `acl`, `common`, `environment`, `links`, `nodes`, `pol`
- Removed legacy training modules
- Removed tests for legacy code
### Fixed
- Addressed network transmission issues that previously allowed ARP requests to be incorrectly routed and repeated across different subnets. This fix ensures ARP requests are correctly managed and confined to their appropriate network segments.
- Resolved problems in `Node` and its subclasses where the default gateway configuration was not properly utilized for communications across different subnets. This correction ensures that nodes effectively use their configured default gateways for outbound communications to other network segments, thereby enhancing the network's routing functionality and reliability.
- Network Interface Port name/num being set properly for sys log and PCAP output.
## [2.0.0] - 2023-07-26

39
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,39 @@
# How to contribute to PrimAITE?
### **Did you find a bug?**
* **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/{todo:fill in URL}/PrimAITE/issues).
* If you're unable to find an open issue addressing the problem, [open a new one](https://github.com/{todo:fill in URL}/PrimAITE/issues/new?assignees=&labels=bug&projects=&template=bug_report.md&title=%5BBUG%5D+-+%3Cbug+title+goes+here%3E). Be sure to follow our bug report template with the headers **Describe the bug**, **To Reproduce**, **Expected behaviour**, **Screenshots/Outputs**, **Environment**, and **Additional context**
### **Do you have a solution to fix the bug?**
* [Fork the repository](https://github.com/{todo:fill in URL}/PrimAITE/fork).
* Install the pre-commit hook with `pre-commit install`.
* Implement the bug fix.
* Update documentation where applicable.
* Update the **UNRELEASED** section of the [CHANGELOG.md](CHANGELOG.md) file
* Write a suitable test/tests.
* Commit the bug fix to the dev branch on your fork. If the bug has an open issue under [Issues](https://github.com/{todo:fill in URL}/PrimAITE/issues), reference the issue in the commit message (e.g. #1 references issue 1).
* Submit a pull request from your dev branch to the {todo:fill in URL}/PrimAITE dev branch. Again, if the bug has an open issue under [Issues](https://github.com/{todo:fill in URL}/PrimAITE/issues), reference the issue in the pull request description.
### **Did you fix whitespace, format code, or make a purely cosmetic patch?**
Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability of PrimAITE will generally not be accepted.
### **Do you intend to add a new feature or change an existing one?**
* Submit a [feature request issue](https://github.com/{todo:fill in URL}/PrimAITE/issues/new?assignees=&labels=feature_request&projects=&template=feature_request.md&title=%5BREQUEST%5D+-+%3Crequest+title+goes+here%3E).
* Know how to implement the new feature or change? Follow the same steps in the bug fix section above to fork, build, document, test, commit, and submit a pull request.
### **Do you have questions about the source code?**
Ask any question about how to use PrimAITE in our discussions section.
### **Do you want to contribute to the PrimAITE documentation?**
Please follow the "Do you intend to add a new feature or change an existing one?" section above and tag your feature request issue and pull request with the documentation tag.
Thank you from the PrimAITE dev team! 🙌

22
LICENSE
View File

@@ -1,21 +1,27 @@
MIT License
MIT License License
Copyright (c) 2023 - 2025 Defence Science and Technology Laboratory UK (https://dstl.gov.uk)
MIT License Conditions
Permission is hereby granted, free of charge, to any person obtaining a copy
These MIT License conditions confirm the provision of the following artefacts as MIT License by Defence Science and Technology
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
request to the QQ or FNC mailbox):
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
- Use Case Release Packs
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
Suppliers are required to read and confirm acceptance of the {todo:fill in URL} Foundry SyOPs (https://github.com/{todo:fill in URL}/foundry-syops) before being admitted access to material hosted on the {todo:fill in URL} Foundry GitHub site.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
The material is supplied in confidence to QQ / FNC and their subcontractors under SERAPIS, and is issued to inform only those
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
of DSTL. The material must be stored and protected appropriately. All material must be destroyed at the end of the task.

View File

@@ -1,2 +1,3 @@
include src/primaite/setup/_package_data/primaite_config.yaml
include src/primaite/config/_package_data/*.yaml
include src/primaite/simulator/_package_data/*.ipynb

Binary file not shown.

After

Width:  |  Height:  |  Size: 274 KiB

163
README.md
View File

@@ -1,50 +1,161 @@
# PrimAITE
![image](./PrimAITE_logo_transparent.png)
The ARCD Primary-level AI Training Environment (**PrimAITE**) provides an effective simulation capability for the purposes of training and evaluating AI in a cyber-defensive role. It incorporates the functionality required of a primary-level ARCD environment, which includes:
- The ability to model a relevant platform / system context;
- The ability to model key characteristics of a platform / system by representing connections, IP addresses, ports, traffic loading, operating systems and services;
- Operates at machine-speed to enable fast training cycles.
PrimAITE presents the following features:
- Highly configurable (via YAML files) to provide the means to model a variety of platform / system laydowns and adversarial attack scenarios;
- A Reinforcement Learning (RL) reward function based on (a) the ability to counter the specific modelled adversarial cyber-attack, and (b) the ability to ensure success;
- Provision of logging to support AI evaluation and metrics gathering;
- Realistic network traffic simulation, including address and sending packets via internet protocols like TCP, UDP, ICMP, and others
- Routers with traffic routing and firewall capabilities
- Support for multiple agents, each having their own customisable observation space, action space, and reward function definition, and either deterministic or RL-directed behaviour
## Getting Started with PrimAITE
### Pre-Requisites
In order to get **PrimAITE** installed, you will need to have the following installed:
- `python3.8+`
- `python3-pip`
- `virtualenv`
### 💫 Installation
**PrimAITE** is designed to be OS-agnostic, and thus should work on most variations/distros of Linux, Windows, and MacOS.
Currently, the PrimAITE wheel can only be installed from GitHub. This may change in the future with release to PyPi.
### Installation from source
#### 1. Navigate to the PrimAITE folder and create a new python virtual environment (venv)
#### Windows (PowerShell)
```unix
python3 -m venv <name_of_venv>
**Prerequisites:**
* Manual install of Python >= 3.9 < 3.12
**Install:**
``` powershell
mkdir ~\primaite
cd ~\primaite
python3 -m venv .venv
attrib +h .venv /s /d # Hides the .venv directory
.\.venv\Scripts\activate
pip install primaite-{VERSION}-py3-none-any.whl[rl]
primaite setup
```
#### 2. Activate the venv
#### Unix
**Prerequisites:**
* Manual install of Python >= 3.8 < 3.12
``` bash
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt install python3.10
sudo apt-get install python3-pip
sudo apt-get install python3-venv
```
**Install:**
``` bash
mkdir ~/primaite
cd ~/primaite
python3 -m venv .venv
source .venv/bin/activate
pip install primaite-{VERSION}-py3-none-any.whl[rl]
primaite setup
```
### Developer Install from Source
To make your own changes to PrimAITE, perform the install from source (developer install)
#### 1. Clone the PrimAITE repository
``` unix
git clone git@github.com:{todo:fill in URL}/PrimAITE.git
```
#### 2. CD into the repo directory
``` unix
cd PrimAITE
```
#### 3. Create a new python virtual environment (venv)
```unix
python3 -m venv venv
```
#### 4. Activate the venv
##### Unix
```bash
source <name_of_venv>/bin/activate
source venv/bin/activate
```
##### Windows
##### Windows (Powershell)
```powershell
.\<name_of_venv>\Scripts\activate
.\venv\Scripts\activate
```
#### 3. Install `primaite` into the venv along with all of it's dependencies
#### 5. Install `primaite` with the dev extra into the venv along with all of it's dependencies
```bash
python3 -m pip install -e .
python3 -m pip install -e .[dev,rl]
```
### Development Installation
To install the development dependencies, postfix the command in step 3 above with the `[dev]` extra. Example:
#### 6. Perform the PrimAITE setup:
```bash
python3 -m pip install -e .[dev]
primaite setup
```
## Building documentation
#### Note
*It is possible to install PrimAITE without Ray RLLib, StableBaselines3, or any deep learning libraries by omitting the `rl` flag in the pip install command.*
### Running PrimAITE
Use the provided jupyter notebooks as a starting point to try running PrimAITE. They are automatically copied to your PrimAITE notebook folder when you run `primaite setup`.
#### 1. Activate the virtual environment
##### Windows (Powershell)
```powershell
.\venv\Scripts\activate
```
##### Unix
```bash
source venv/bin/activate
```
#### 2. Open jupyter notebook
```bash
python -m jupyter notebook
```
Then, click the URL provided by the jupyter command to open the jupyter application in your browser. You can also open notebooks in your IDE if supported.
## 📚 Documentation
### Pre requisites
Building the documentation requires the installation of Pandoc
##### Unix
```bash
sudo apt-get install pandoc
```
##### Other operating systems
Follow the steps in https://pandoc.org/installing.html
### Building the documentation
The PrimAITE documentation can be built with the following commands:
##### Unix
@@ -53,12 +164,12 @@ cd docs
make html
```
##### Windows
##### Windows (Powershell)
```powershell
cd docs
.\make.bat html
```
This will build the documentation as a collection of HTML files which uses the Read The Docs sphinx theme. Other build
options are available but may require additional dependencies such as LaTeX and PDF. Please refer to the Sphinx documentation
for your specific output requirements.
## Example notebooks
Check out the example notebooks to learn more about how PrimAITE works and how you can use it to train agents. They are automatically copied to your primaite installation directory when you run `primaite setup`.

22
benchmark/benchmark.py Normal file
View File

@@ -0,0 +1,22 @@
# © Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
from typing import Any, Dict, Optional, Tuple
from gymnasium.core import ObsType
from primaite.session.environment import PrimaiteGymEnv
class BenchmarkPrimaiteGymEnv(PrimaiteGymEnv):
"""
Class that extends the PrimaiteGymEnv.
The reset method is extended so that the average rewards per episode are recorded.
"""
total_time_steps: int = 0
def reset(self, seed: Optional[int] = None) -> Tuple[ObsType, Dict[str, Any]]:
"""Overrides the PrimAITEGymEnv reset so that the total timesteps is saved."""
self.total_time_steps += self.game.step_counter
return super().reset(seed=seed)

View File

@@ -1,206 +1,93 @@
# © Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
# © Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
import json
import platform
import shutil
import sys
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Final, Optional, Tuple, Union
from unittest.mock import patch
from typing import Any, Dict, Final, Tuple
import GPUtil
import plotly.graph_objects as go
import polars as pl
import psutil
import yaml
from plotly.graph_objs import Figure
from pylatex import Command, Document
from pylatex import Figure as LatexFigure
from pylatex import Section, Subsection, Tabular
from pylatex.utils import bold
from report import build_benchmark_md_report
from stable_baselines3 import PPO
import primaite
from primaite.config.lay_down_config import data_manipulation_config_path
from primaite.data_viz.session_plots import get_plotly_config
from primaite.environment.primaite_env import Primaite
from primaite.primaite_session import PrimaiteSession
from benchmark import BenchmarkPrimaiteGymEnv
from primaite.config.load import data_manipulation_config_path
_LOGGER = primaite.getLogger(__name__)
_MAJOR_V = primaite.__version__.split(".")[0]
_BENCHMARK_ROOT = Path(__file__).parent
_RESULTS_ROOT: Final[Path] = _BENCHMARK_ROOT / "results"
_RESULTS_ROOT.mkdir(exist_ok=True, parents=True)
_RESULTS_ROOT: Final[Path] = _BENCHMARK_ROOT / "results" / f"v{_MAJOR_V}"
_VERSION_ROOT: Final[Path] = _RESULTS_ROOT / f"v{primaite.__version__}"
_SESSION_METADATA_ROOT: Final[Path] = _VERSION_ROOT / "session_metadata"
_OUTPUT_ROOT: Final[Path] = _BENCHMARK_ROOT / "output"
# Clear and recreate the output directory
if _OUTPUT_ROOT.exists():
shutil.rmtree(_OUTPUT_ROOT)
_OUTPUT_ROOT.mkdir()
_TRAINING_CONFIG_PATH = _BENCHMARK_ROOT / "config" / "benchmark_training_config.yaml"
_LAY_DOWN_CONFIG_PATH = data_manipulation_config_path()
_SESSION_METADATA_ROOT.mkdir(parents=True, exist_ok=True)
def get_size(size_bytes: int):
"""
Scale bytes to its proper format.
class BenchmarkSession:
"""Benchmark Session class."""
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
gym_env: BenchmarkPrimaiteGymEnv
"""Gym environment used by the session to train."""
:
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if size_bytes < factor:
return f"{size_bytes:.2f}{unit}B"
size_bytes /= factor
num_episodes: int
"""Number of episodes to run the training session."""
episode_len: int
"""The number of steps per episode."""
def _get_system_info() -> Dict:
"""Builds and returns a dict containing system info."""
uname = platform.uname()
cpu_freq = psutil.cpu_freq()
virtual_mem = psutil.virtual_memory()
swap_mem = psutil.swap_memory()
gpus = GPUtil.getGPUs()
return {
"System": {
"OS": uname.system,
"OS Version": uname.version,
"Machine": uname.machine,
"Processor": uname.processor,
},
"CPU": {
"Physical Cores": psutil.cpu_count(logical=False),
"Total Cores": psutil.cpu_count(logical=True),
"Max Frequency": f"{cpu_freq.max:.2f}Mhz",
},
"Memory": {"Total": get_size(virtual_mem.total), "Swap Total": get_size(swap_mem.total)},
"GPU": [{"Name": gpu.name, "Total Memory": f"{gpu.memoryTotal}MB"} for gpu in gpus],
}
total_steps: int
"""Number of steps to run the training session."""
batch_size: int
"""Number of steps for each episode."""
def _build_benchmark_latex_report(
benchmark_metadata_dict: Dict, this_version_plot_path: Path, all_version_plot_path: Path
):
geometry_options = {"tmargin": "2.5cm", "rmargin": "2.5cm", "bmargin": "2.5cm", "lmargin": "2.5cm"}
data = benchmark_metadata_dict
primaite_version = data["primaite_version"]
learning_rate: float
"""Learning rate for the model."""
# Create a new document
doc = Document("report", geometry_options=geometry_options)
# Title
doc.preamble.append(Command("title", f"PrimAITE {primaite_version} Learning Benchmark"))
doc.preamble.append(Command("author", "PrimAITE Dev Team"))
doc.preamble.append(Command("date", datetime.now().date()))
doc.append(Command("maketitle"))
start_time: datetime
"""Start time for the session."""
sessions = data["total_sessions"]
episodes = data["training_config"]["num_train_episodes"]
steps = data["training_config"]["num_train_steps"]
# Body
with doc.create(Section("Introduction")):
doc.append(
f"PrimAITE v{primaite_version} was benchmarked automatically upon release. Learning rate metrics "
f"were captured to be referenced during system-level testing and user acceptance testing (UAT)."
)
doc.append(
f"\nThe benchmarking process consists of running {sessions} training session using the same "
f"training and lay down config files. Each session trains an agent for {episodes} episodes, "
f"with each episode consisting of {steps} steps."
)
doc.append(
f"\nThe mean reward per episode from each session is captured. This is then used to calculate a "
f"combined average reward per episode from the {sessions} individual sessions for smoothing. "
f"Finally, a 25-widow rolling average of the combined average reward per session is calculated for "
f"further smoothing."
)
with doc.create(Section("System Information")):
with doc.create(Subsection("Python")):
with doc.create(Tabular("|l|l|")) as table:
table.add_hline()
table.add_row((bold("Version"), sys.version))
table.add_hline()
for section, section_data in data["system_info"].items():
if section_data:
with doc.create(Subsection(section)):
if isinstance(section_data, dict):
with doc.create(Tabular("|l|l|")) as table:
table.add_hline()
for key, value in section_data.items():
table.add_row((bold(key), value))
table.add_hline()
elif isinstance(section_data, list):
headers = section_data[0].keys()
tabs_str = "|".join(["l" for _ in range(len(headers))])
tabs_str = f"|{tabs_str}|"
with doc.create(Tabular(tabs_str)) as table:
table.add_hline()
table.add_row([bold(h) for h in headers])
table.add_hline()
for item in section_data:
table.add_row(item.values())
table.add_hline()
headers_map = {
"total_sessions": "Total Sessions",
"total_episodes": "Total Episodes",
"total_time_steps": "Total Steps",
"av_s_per_session": "Av Session Duration (s)",
"av_s_per_step": "Av Step Duration (s)",
"av_s_per_100_steps_10_nodes": "Av Duration per 100 Steps per 10 Nodes (s)",
}
with doc.create(Section("Stats")):
with doc.create(Subsection("Benchmark Results")):
with doc.create(Tabular("|l|l|")) as table:
table.add_hline()
for section, header in headers_map.items():
if section.startswith("av_"):
table.add_row((bold(header), f"{data[section]:.4f}"))
else:
table.add_row((bold(header), data[section]))
table.add_hline()
with doc.create(Section("Graphs")):
with doc.create(Subsection(f"PrimAITE {primaite_version} Learning Benchmark Plot")):
with doc.create(LatexFigure(position="h!")) as pic:
pic.add_image(str(this_version_plot_path))
pic.add_caption(f"PrimAITE {primaite_version} Learning Benchmark Plot")
with doc.create(Subsection("PrimAITE All Versions Learning Benchmark Plot")):
with doc.create(LatexFigure(position="h!")) as pic:
pic.add_image(str(all_version_plot_path))
pic.add_caption("PrimAITE All Versions Learning Benchmark Plot")
doc.generate_pdf(str(this_version_plot_path).replace(".png", ""), clean_tex=True)
class BenchmarkPrimaiteSession(PrimaiteSession):
"""A benchmarking primaite session."""
end_time: datetime
"""End time for the session."""
def __init__(
self,
training_config_path: Union[str, Path],
lay_down_config_path: Union[str, Path],
gym_env: BenchmarkPrimaiteGymEnv,
episode_len: int,
num_episodes: int,
n_steps: int,
batch_size: int,
learning_rate: float,
):
super().__init__(training_config_path, lay_down_config_path)
self.setup()
"""Initialise the BenchmarkSession."""
self.gym_env = gym_env
self.episode_len = episode_len
self.n_steps = n_steps
self.num_episodes = num_episodes
self.total_steps = self.num_episodes * self.episode_len
self.batch_size = batch_size
self.learning_rate = learning_rate
@property
def env(self) -> Primaite:
"""Direct access to the env for ease of testing."""
return self._agent_session._env # noqa
def train(self):
"""Run the training session."""
# start timer for session
self.start_time = datetime.now()
model = PPO(
policy="MlpPolicy",
env=self.gym_env,
learning_rate=self.learning_rate,
n_steps=self.n_steps,
batch_size=self.batch_size,
verbose=0,
tensorboard_log="./PPO_UC2/",
)
model.learn(total_timesteps=self.total_steps)
def __enter__(self):
return self
# end timer for session
self.end_time = datetime.now()
def __exit__(self, type, value, tb):
shutil.rmtree(self.session_path)
_LOGGER.debug(f"Deleted benchmark session directory: {self.session_path}")
self.session_metadata = self.generate_learn_metadata_dict()
def _learn_benchmark_durations(self) -> Tuple[float, float, float]:
"""
@@ -214,235 +101,99 @@ class BenchmarkPrimaiteSession(PrimaiteSession):
:return: The learning benchmark durations as a Tuple of three floats:
Tuple[total_s, s_per_step, s_per_100_steps_10_nodes].
"""
data = self.metadata_file_as_dict()
start_dt = datetime.fromisoformat(data["start_datetime"])
end_dt = datetime.fromisoformat(data["end_datetime"])
delta = end_dt - start_dt
delta = self.end_time - self.start_time
total_s = delta.total_seconds()
total_steps = data["learning"]["total_time_steps"]
total_steps = self.batch_size * self.num_episodes
s_per_step = total_s / total_steps
num_nodes = self.env.num_nodes
num_nodes = len(self.gym_env.game.simulation.network.nodes)
num_intervals = total_steps / 100
av_interval_time = total_s / num_intervals
s_per_100_steps_10_nodes = av_interval_time / (num_nodes / 10)
return total_s, s_per_step, s_per_100_steps_10_nodes
def learn_metadata_dict(self) -> Dict[str, Any]:
def generate_learn_metadata_dict(self) -> Dict[str, Any]:
"""Metadata specific to the learning session."""
total_s, s_per_step, s_per_100_steps_10_nodes = self._learn_benchmark_durations()
self.gym_env.total_reward_per_episode.pop(0) # remove episode 0
return {
"total_episodes": self.env.actual_episode_count,
"total_time_steps": self.env.total_step_count,
"total_episodes": self.gym_env.episode_counter,
"total_time_steps": self.gym_env.total_time_steps,
"total_s": total_s,
"s_per_step": s_per_step,
"s_per_100_steps_10_nodes": s_per_100_steps_10_nodes,
"av_reward_per_episode": self.learn_av_reward_per_episode_dict(),
"total_reward_per_episode": self.gym_env.total_reward_per_episode,
}
def _get_benchmark_session_path(session_timestamp: datetime) -> Path:
return _OUTPUT_ROOT / session_timestamp.strftime("%Y-%m-%d_%H-%M-%S")
def _get_benchmark_primaite_session() -> BenchmarkPrimaiteSession:
with patch("primaite.agents.agent_abc.get_session_path", _get_benchmark_session_path) as mck:
mck.session_timestamp = datetime.now()
return BenchmarkPrimaiteSession(_TRAINING_CONFIG_PATH, _LAY_DOWN_CONFIG_PATH)
def _build_benchmark_results_dict(start_datetime: datetime, metadata_dict: Dict) -> dict:
n = len(metadata_dict)
with open(_TRAINING_CONFIG_PATH, "r") as file:
training_config_dict = yaml.safe_load(file)
with open(_LAY_DOWN_CONFIG_PATH, "r") as file:
lay_down_config_dict = yaml.safe_load(file)
averaged_data = {
"start_timestamp": start_datetime.isoformat(),
"end_datetime": datetime.now().isoformat(),
"primaite_version": primaite.__version__,
"system_info": _get_system_info(),
"total_sessions": n,
"total_episodes": sum(d["total_episodes"] for d in metadata_dict.values()),
"total_time_steps": sum(d["total_time_steps"] for d in metadata_dict.values()),
"av_s_per_session": sum(d["total_s"] for d in metadata_dict.values()) / n,
"av_s_per_step": sum(d["s_per_step"] for d in metadata_dict.values()) / n,
"av_s_per_100_steps_10_nodes": sum(d["s_per_100_steps_10_nodes"] for d in metadata_dict.values()) / n,
"combined_av_reward_per_episode": {},
"session_av_reward_per_episode": {k: v["av_reward_per_episode"] for k, v in metadata_dict.items()},
"training_config": training_config_dict,
"lay_down_config": lay_down_config_dict,
}
episodes = metadata_dict[1]["av_reward_per_episode"].keys()
for episode in episodes:
combined_av_reward = sum(metadata_dict[k]["av_reward_per_episode"][episode] for k in metadata_dict.keys()) / n
averaged_data["combined_av_reward_per_episode"][episode] = combined_av_reward
return averaged_data
def _get_df_from_episode_av_reward_dict(data: Dict):
data: Dict = {"episode": data.keys(), "av_reward": data.values()}
return (
pl.from_dict(data)
.with_columns(rolling_mean=pl.col("av_reward").rolling_mean(window_size=25))
.rename({"rolling_mean": "rolling_av_reward"})
)
def _plot_benchmark_metadata(
benchmark_metadata_dict: Dict,
title: Optional[str] = None,
subtitle: Optional[str] = None,
) -> Figure:
if title:
if subtitle:
title = f"{title} <br>{subtitle}</sup>"
else:
if subtitle:
title = subtitle
config = get_plotly_config()
layout = go.Layout(
autosize=config["size"]["auto_size"],
width=config["size"]["width"],
height=config["size"]["height"],
)
# Create the line graph with a colored line
fig = go.Figure(layout=layout)
fig.update_layout(template=config["template"])
for session, av_reward_dict in benchmark_metadata_dict["session_av_reward_per_episode"].items():
df = _get_df_from_episode_av_reward_dict(av_reward_dict)
fig.add_trace(
go.Scatter(
x=df["episode"],
y=df["av_reward"],
mode="lines",
name=f"Session {session}",
opacity=0.25,
line={"color": "#a6a6a6"},
)
)
df = _get_df_from_episode_av_reward_dict(benchmark_metadata_dict["combined_av_reward_per_episode"])
fig.add_trace(
go.Scatter(
x=df["episode"], y=df["av_reward"], mode="lines", name="Combined Session Av", line={"color": "#FF0000"}
)
)
fig.add_trace(
go.Scatter(
x=df["episode"],
y=df["rolling_av_reward"],
mode="lines",
name="Rolling Av (Combined Session Av)",
line={"color": "#4CBB17"},
)
)
# Set the layout of the graph
fig.update_layout(
xaxis={
"title": "Episode",
"type": "linear",
},
yaxis={"title": "Average Reward"},
title=title,
)
return fig
def _plot_all_benchmarks_combined_session_av():
def _get_benchmark_primaite_environment() -> BenchmarkPrimaiteGymEnv:
"""
Plot the Benchmark results for each released version of PrimAITE.
Create an instance of the BenchmarkPrimaiteGymEnv.
Does this by iterating over the ``benchmark/results`` directory and
extracting the benchmark metadata json for each version that has been
benchmarked. The combined_av_reward_per_episode is extracted from each,
converted into a polars dataframe, and plotted as a scatter line in plotly.
This environment will be used to train the agents on.
"""
title = "PrimAITE Versions Learning Benchmark"
subtitle = "Rolling Av (Combined Session Av)"
if title:
if subtitle:
title = f"{title} <br>{subtitle}</sup>"
else:
if subtitle:
title = subtitle
config = get_plotly_config()
layout = go.Layout(
autosize=config["size"]["auto_size"],
width=config["size"]["width"],
height=config["size"]["height"],
)
# Create the line graph with a colored line
fig = go.Figure(layout=layout)
fig.update_layout(template=config["template"])
for dir in _RESULTS_ROOT.iterdir():
if dir.is_dir():
metadata_file = dir / f"{dir.name}_benchmark_metadata.json"
with open(metadata_file, "r") as file:
metadata_dict = json.load(file)
df = _get_df_from_episode_av_reward_dict(metadata_dict["combined_av_reward_per_episode"])
fig.add_trace(go.Scatter(x=df["episode"], y=df["rolling_av_reward"], mode="lines", name=dir.name))
# Set the layout of the graph
fig.update_layout(
xaxis={
"title": "Episode",
"type": "linear",
},
yaxis={"title": "Average Reward"},
title=title,
)
fig["data"][0]["showlegend"] = True
return fig
env = BenchmarkPrimaiteGymEnv(env_config=data_manipulation_config_path())
return env
def run():
def _prepare_session_directory():
"""Prepare the session directory so that it is easier to clean up after the benchmarking is done."""
# override session path
session_path = _BENCHMARK_ROOT / "sessions"
if session_path.is_dir():
shutil.rmtree(session_path)
primaite.PRIMAITE_PATHS.user_sessions_path = session_path
primaite.PRIMAITE_PATHS.user_sessions_path.mkdir(exist_ok=True, parents=True)
def run(
number_of_sessions: int = 5,
num_episodes: int = 1000,
episode_len: int = 128,
n_steps: int = 1280,
batch_size: int = 32,
learning_rate: float = 3e-4,
) -> None:
"""Run the PrimAITE benchmark."""
start_datetime = datetime.now()
av_reward_per_episode_dicts = {}
for i in range(1, 11):
benchmark_start_time = datetime.now()
session_metadata_dict = {}
_prepare_session_directory()
# run training
for i in range(1, number_of_sessions + 1):
print(f"Starting Benchmark Session: {i}")
with _get_benchmark_primaite_session() as session:
session.learn()
av_reward_per_episode_dicts[i] = session.learn_metadata_dict()
benchmark_metadata = _build_benchmark_results_dict(
start_datetime=start_datetime, metadata_dict=av_reward_per_episode_dicts
with _get_benchmark_primaite_environment() as gym_env:
session = BenchmarkSession(
gym_env=gym_env,
num_episodes=num_episodes,
n_steps=n_steps,
episode_len=episode_len,
batch_size=batch_size,
learning_rate=learning_rate,
)
session.train()
# Dump the session metadata so that we're not holding it in memory as it's large
with open(_SESSION_METADATA_ROOT / f"{i}.json", "w") as file:
json.dump(session.session_metadata, file, indent=4)
for i in range(1, number_of_sessions + 1):
with open(_SESSION_METADATA_ROOT / f"{i}.json", "r") as file:
session_metadata_dict[i] = json.load(file)
# generate report
build_benchmark_md_report(
benchmark_start_time=benchmark_start_time,
session_metadata=session_metadata_dict,
config_path=data_manipulation_config_path(),
results_root_path=_RESULTS_ROOT,
)
v_str = f"v{primaite.__version__}"
version_result_dir = _RESULTS_ROOT / v_str
if version_result_dir.exists():
shutil.rmtree(version_result_dir)
version_result_dir.mkdir(exist_ok=True, parents=True)
with open(version_result_dir / f"{v_str}_benchmark_metadata.json", "w") as file:
json.dump(benchmark_metadata, file, indent=4)
title = f"PrimAITE v{primaite.__version__.strip()} Learning Benchmark"
fig = _plot_benchmark_metadata(benchmark_metadata, title=title)
this_version_plot_path = version_result_dir / f"{title}.png"
fig.write_image(this_version_plot_path)
fig = _plot_all_benchmarks_combined_session_av()
all_version_plot_path = _RESULTS_ROOT / "PrimAITE Versions Learning Benchmark.png"
fig.write_image(all_version_plot_path)
_build_benchmark_latex_report(benchmark_metadata, this_version_plot_path, all_version_plot_path)
if __name__ == "__main__":

426
benchmark/report.py Normal file
View File

@@ -0,0 +1,426 @@
# © Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, Optional
import plotly.graph_objects as go
import polars as pl
import yaml
from plotly.graph_objs import Figure
from utils import _get_system_info
import primaite
PLOT_CONFIG = {
"size": {"auto_size": False, "width": 1500, "height": 900},
"template": "plotly_white",
"range_slider": False,
"av_s_per_100_steps_10_nodes_benchmark_threshold": 5,
"benchmark_line_color": "grey",
}
def _build_benchmark_results_dict(start_datetime: datetime, metadata_dict: Dict, config: Dict) -> dict:
"""
Constructs a dictionary aggregating benchmark results from multiple sessions.
:param start_datetime: The datetime when the benchmarking started.
:param metadata_dict: Dictionary containing metadata for each session.
:param config: Configuration settings used during the benchmarking.
:return: A dictionary containing aggregated data and metadata from the benchmarking sessions.
"""
num_sessions = len(metadata_dict) # number of sessions
averaged_data = {
"start_timestamp": start_datetime.isoformat(),
"end_datetime": datetime.now().isoformat(),
"primaite_version": primaite.__version__,
"system_info": _get_system_info(),
"total_sessions": num_sessions,
"total_episodes": sum(d["total_episodes"] for d in metadata_dict.values()),
"total_time_steps": sum(d["total_time_steps"] for d in metadata_dict.values()),
"av_s_per_session": sum(d["total_s"] for d in metadata_dict.values()) / num_sessions,
"av_s_per_step": sum(d["s_per_step"] for d in metadata_dict.values()) / num_sessions,
"av_s_per_100_steps_10_nodes": sum(d["s_per_100_steps_10_nodes"] for d in metadata_dict.values())
/ num_sessions,
"combined_total_reward_per_episode": {},
"session_total_reward_per_episode": {k: v["total_reward_per_episode"] for k, v in metadata_dict.items()},
"config": config,
}
# find the average of each episode across all sessions
episodes = metadata_dict[1]["total_reward_per_episode"].keys()
for episode in episodes:
combined_av_reward = (
sum(metadata_dict[k]["total_reward_per_episode"][episode] for k in metadata_dict.keys()) / num_sessions
)
averaged_data["combined_total_reward_per_episode"][episode] = combined_av_reward
return averaged_data
def _get_df_from_episode_av_reward_dict(data: Dict) -> pl.DataFrame:
"""
Converts a dictionary of episode average rewards into a Polars DataFrame.
:param data: Dictionary with episodes as keys and average rewards as values.
:return: Polars DataFrame with episodes and average rewards, including a rolling average.
"""
data: Dict = {"episode": data.keys(), "av_reward": data.values()}
return (
pl.from_dict(data)
.with_columns(rolling_mean=pl.col("av_reward").rolling_mean(window_size=25))
.rename({"rolling_mean": "rolling_av_reward"})
)
def _plot_benchmark_metadata(
benchmark_metadata_dict: Dict,
title: Optional[str] = None,
subtitle: Optional[str] = None,
) -> Figure:
"""
Plots benchmark metadata as a line graph using Plotly.
:param benchmark_metadata_dict: Dictionary containing the total reward per episode and session.
:param title: Optional title for the graph.
:param subtitle: Optional subtitle for the graph.
:return: Plotly figure object representing the benchmark metadata plot.
"""
if title:
if subtitle:
title = f"{title} <br>{subtitle}</sup>"
else:
if subtitle:
title = subtitle
layout = go.Layout(
autosize=PLOT_CONFIG["size"]["auto_size"],
width=PLOT_CONFIG["size"]["width"],
height=PLOT_CONFIG["size"]["height"],
)
# Create the line graph with a colored line
fig = go.Figure(layout=layout)
fig.update_layout(template=PLOT_CONFIG["template"])
for session, av_reward_dict in benchmark_metadata_dict["session_total_reward_per_episode"].items():
df = _get_df_from_episode_av_reward_dict(av_reward_dict)
fig.add_trace(
go.Scatter(
x=df["episode"],
y=df["av_reward"],
mode="lines",
name=f"Session {session}",
opacity=0.25,
line={"color": "#a6a6a6"},
)
)
df = _get_df_from_episode_av_reward_dict(benchmark_metadata_dict["combined_total_reward_per_episode"])
fig.add_trace(
go.Scatter(
x=df["episode"], y=df["av_reward"], mode="lines", name="Combined Session Av", line={"color": "#FF0000"}
)
)
fig.add_trace(
go.Scatter(
x=df["episode"],
y=df["rolling_av_reward"],
mode="lines",
name="Rolling Av (Combined Session Av)",
line={"color": "#4CBB17"},
)
)
# Set the layout of the graph
fig.update_layout(
xaxis={
"title": "Episode",
"type": "linear",
},
yaxis={"title": "Total Reward"},
title=title,
)
return fig
def _plot_all_benchmarks_combined_session_av(results_directory: Path) -> Figure:
"""
Plot the Benchmark results for each released version of PrimAITE.
Does this by iterating over the ``benchmark/results`` directory and
extracting the benchmark metadata json for each version that has been
benchmarked. The combined_total_reward_per_episode is extracted from each,
converted into a polars dataframe, and plotted as a scatter line in plotly.
"""
major_v = primaite.__version__.split(".")[0]
title = f"Learning Benchmark of Minor and Bugfix Releases for Major Version {major_v}"
subtitle = "Rolling Av (Combined Session Av)"
if title:
if subtitle:
title = f"{title} <br>{subtitle}</sup>"
else:
if subtitle:
title = subtitle
layout = go.Layout(
autosize=PLOT_CONFIG["size"]["auto_size"],
width=PLOT_CONFIG["size"]["width"],
height=PLOT_CONFIG["size"]["height"],
)
# Create the line graph with a colored line
fig = go.Figure(layout=layout)
fig.update_layout(template=PLOT_CONFIG["template"])
for dir in results_directory.iterdir():
if dir.is_dir():
metadata_file = dir / f"{dir.name}_benchmark_metadata.json"
with open(metadata_file, "r") as file:
metadata_dict = json.load(file)
df = _get_df_from_episode_av_reward_dict(metadata_dict["combined_total_reward_per_episode"])
fig.add_trace(go.Scatter(x=df["episode"], y=df["rolling_av_reward"], mode="lines", name=dir.name))
# Set the layout of the graph
fig.update_layout(
xaxis={
"title": "Episode",
"type": "linear",
},
yaxis={"title": "Total Reward"},
title=title,
)
fig["data"][0]["showlegend"] = True
return fig
def _get_performance_benchmark_for_all_version_dict(results_directory: Path) -> Dict[str, float]:
"""
Gathers performance benchmarks for all versions of the software stored in a specified directory.
This function iterates through each directory within the specified results directory,
extracts the av_s_per_100_steps_10_nodes from the benchmark_metadata.json files, and aggregates it into a
dictionary.
:param results_directory: The directory containing subdirectories for each version's benchmark data.
:return: A dictionary with version numbers as keys and their corresponding average performance benchmark
(average time per 100 steps on 10 nodes) as values.
"""
performance_benchmark_dict = {}
for dir in results_directory.iterdir():
if dir.is_dir():
metadata_file = dir / f"{dir.name}_benchmark_metadata.json"
with open(metadata_file, "r") as file:
metadata_dict = json.load(file)
version = metadata_dict["primaite_version"]
performance_benchmark_dict[version] = metadata_dict["av_s_per_100_steps_10_nodes"]
return performance_benchmark_dict
def _plot_av_s_per_100_steps_10_nodes(
version_times_dict: Dict[str, float],
) -> Figure:
"""
Creates a bar chart visualising the performance of each version of PrimAITE.
Performance is based on the average training time per 100 steps on 10 nodes. The function also includes a benchmark
line indicating the target maximum time.
Versions that perform under this time are marked in green, and those over are marked in red.
:param version_times_dict: A dictionary with software versions as keys and average times as values.
:return: A Plotly figure object representing the bar chart of the performance metrics.
"""
major_v = primaite.__version__.split(".")[0]
title = f"Performance of Minor and Bugfix Releases for Major Version {major_v}"
subtitle = (
f"Average Training Time per 100 Steps on 10 Nodes "
f"(target: <= {PLOT_CONFIG['av_s_per_100_steps_10_nodes_benchmark_threshold']} seconds)"
)
title = f"{title} <br><sub>{subtitle}</sub>"
layout = go.Layout(
autosize=PLOT_CONFIG["size"]["auto_size"],
width=PLOT_CONFIG["size"]["width"],
height=PLOT_CONFIG["size"]["height"],
)
fig = go.Figure(layout=layout)
fig.update_layout(template=PLOT_CONFIG["template"])
versions = sorted(list(version_times_dict.keys()))
times = [version_times_dict[version] for version in versions]
av_s_per_100_steps_10_nodes_benchmark_threshold = PLOT_CONFIG["av_s_per_100_steps_10_nodes_benchmark_threshold"]
benchmark_line_color = PLOT_CONFIG["benchmark_line_color"]
# Calculate the appropriate maximum y-axis value
max_y_axis_value = max(max(times), av_s_per_100_steps_10_nodes_benchmark_threshold) + 1
fig.add_trace(
go.Bar(
x=versions,
y=times,
marker_color=[
"green" if time < av_s_per_100_steps_10_nodes_benchmark_threshold else "red" for time in times
],
text=times,
textposition="auto",
)
)
# Add a horizontal line for the benchmark
fig.add_shape(
type="line",
x0=-0.5, # start slightly before the first bar
x1=len(versions) - 0.5, # end slightly after the last bar
y0=av_s_per_100_steps_10_nodes_benchmark_threshold,
y1=av_s_per_100_steps_10_nodes_benchmark_threshold,
line=dict(
color=benchmark_line_color,
width=2,
dash="dot",
),
)
fig.update_layout(
xaxis_title="PrimAITE Version",
yaxis_title="Avg Time per 100 Steps on 10 Nodes (seconds)",
yaxis=dict(range=[0, max_y_axis_value]),
title=title,
)
return fig
def build_benchmark_md_report(
benchmark_start_time: datetime, session_metadata: Dict, config_path: Path, results_root_path: Path
) -> None:
"""
Generates a Markdown report for a benchmarking session, documenting performance metrics and graphs.
This function orchestrates the creation of several graphs depicting various performance benchmarks and aggregates
them into a markdown document that includes comprehensive system and benchmark information.
:param benchmark_start_time: The datetime object representing when the benchmarking process was initiated.
:param session_metadata: A dictionary containing metadata for each benchmarking session.
:param config_path: A pathlib.Path object pointing to the configuration file used for the benchmark sessions.
:param results_root_path: A pathlib.Path object pointing to the directory where the results and graphs should be
saved.
"""
# generate report folder
v_str = f"v{primaite.__version__}"
version_result_dir = results_root_path / v_str
version_result_dir.mkdir(exist_ok=True, parents=True)
# load the config file as dict
with open(config_path, "r") as f:
cfg_data = yaml.safe_load(f)
# generate the benchmark metadata dict
benchmark_metadata_dict = _build_benchmark_results_dict(
start_datetime=benchmark_start_time, metadata_dict=session_metadata, config=cfg_data
)
major_v = primaite.__version__.split(".")[0]
with open(version_result_dir / f"{v_str}_benchmark_metadata.json", "w") as file:
json.dump(benchmark_metadata_dict, file, indent=4)
title = f"PrimAITE v{primaite.__version__.strip()} Learning Benchmark"
fig = _plot_benchmark_metadata(benchmark_metadata_dict, title=title)
this_version_plot_path = version_result_dir / f"{title}.png"
fig.write_image(this_version_plot_path)
fig = _plot_all_benchmarks_combined_session_av(results_directory=results_root_path)
filename = f"PrimAITE Learning Benchmark of Minor and Bugfix Releases for Major Version {major_v}.png"
all_version_plot_path = version_result_dir / filename
fig.write_image(all_version_plot_path)
performance_benchmark_dict = _get_performance_benchmark_for_all_version_dict(results_directory=results_root_path)
fig = _plot_av_s_per_100_steps_10_nodes(performance_benchmark_dict)
filename = f"PrimAITE Performance of Minor and Bugfix Releases for Major Version {major_v}.png"
performance_benchmark_plot_path = version_result_dir / filename
fig.write_image(performance_benchmark_plot_path)
data = benchmark_metadata_dict
primaite_version = data["primaite_version"]
with open(version_result_dir / f"PrimAITE v{primaite_version} Benchmark Report.md", "w") as file:
# Title
file.write(f"# PrimAITE v{primaite_version} Learning Benchmark\n")
file.write("## PrimAITE Dev Team\n")
file.write(f"### {datetime.now().date()}\n")
file.write("\n---\n")
sessions = data["total_sessions"]
episodes = session_metadata[1]["total_episodes"] - 1
steps = data["config"]["game"]["max_episode_length"]
# Body
file.write("## 1 Introduction\n")
file.write(
f"PrimAITE v{primaite_version} was benchmarked automatically upon release. Learning rate metrics "
f"were captured to be referenced during system-level testing and user acceptance testing (UAT).\n"
)
file.write(
f"The benchmarking process consists of running {sessions} training session using the same "
f"config file. Each session trains an agent for {episodes} episodes, "
f"with each episode consisting of {steps} steps.\n"
)
file.write(
f"The total reward per episode from each session is captured. This is then used to calculate an "
f"caverage total reward per episode from the {sessions} individual sessions for smoothing. "
f"Finally, a 25-widow rolling average of the average total reward per session is calculated for "
f"further smoothing.\n"
)
file.write("## 2 System Information\n")
i = 1
file.write(f"### 2.{i} Python\n")
file.write(f"**Version:** {sys.version}\n")
for section, section_data in data["system_info"].items():
i += 1
if section_data:
file.write(f"### 2.{i} {section}\n")
if isinstance(section_data, dict):
for key, value in section_data.items():
file.write(f"- **{key}:** {value}\n")
headers_map = {
"total_sessions": "Total Sessions",
"total_episodes": "Total Episodes",
"total_time_steps": "Total Steps",
"av_s_per_session": "Av Session Duration (s)",
"av_s_per_step": "Av Step Duration (s)",
"av_s_per_100_steps_10_nodes": "Av Duration per 100 Steps per 10 Nodes (s)",
}
file.write("## 3 Stats\n")
for section, header in headers_map.items():
if section.startswith("av_"):
file.write(f"- **{header}:** {data[section]:.4f}\n")
else:
file.write(f"- **{header}:** {data[section]}\n")
file.write("## 4 Graphs\n")
file.write(f"### 4.1 v{primaite_version} Learning Benchmark Plot\n")
file.write(f"![PrimAITE {primaite_version} Learning Benchmark Plot]({this_version_plot_path.name})\n")
file.write(f"### 4.2 Learning Benchmark of Minor and Bugfix Releases for Major Version {major_v}\n")
file.write(
f"![Learning Benchmark of Minor and Bugfix Releases for Major Version {major_v}]"
f"({all_version_plot_path.name})\n"
)
file.write(f"### 4.3 Performance of Minor and Bugfix Releases for Major Version {major_v}\n")
file.write(
f"![Performance of Minor and Bugfix Releases for Major Version {major_v}]"
f"({performance_benchmark_plot_path.name})\n"
)

View File

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 79 KiB

View File

Before

Width:  |  Height:  |  Size: 225 KiB

After

Width:  |  Height:  |  Size: 225 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

View File

@@ -0,0 +1,38 @@
# PrimAITE v3.0.0 Learning Benchmark
## PrimAITE Dev Team
### 2024-07-20
---
## 1 Introduction
PrimAITE v3.0.0 was benchmarked automatically upon release. Learning rate metrics were captured to be referenced during system-level testing and user acceptance testing (UAT).
The benchmarking process consists of running 5 training session using the same config file. Each session trains an agent for 1000 episodes, with each episode consisting of 128 steps.
The total reward per episode from each session is captured. This is then used to calculate an caverage total reward per episode from the 5 individual sessions for smoothing. Finally, a 25-widow rolling average of the average total reward per session is calculated for further smoothing.
## 2 System Information
### 2.1 Python
**Version:** 3.10.14 (main, Apr 6 2024, 18:45:05) [GCC 9.4.0]
### 2.2 System
- **OS:** Linux
- **OS Version:** #76~20.04.1-Ubuntu SMP Thu Jun 13 18:00:23 UTC 2024
- **Machine:** x86_64
- **Processor:** x86_64
### 2.3 CPU
- **Physical Cores:** 2
- **Total Cores:** 4
- **Max Frequency:** 0.00Mhz
### 2.4 Memory
- **Total:** 15.62GB
- **Swap Total:** 0.00B
## 3 Stats
- **Total Sessions:** 5
- **Total Episodes:** 5005
- **Total Steps:** 640000
- **Av Session Duration (s):** 1452.5910
- **Av Step Duration (s):** 0.0454
- **Av Duration per 100 Steps per 10 Nodes (s):** 4.5393
## 4 Graphs
### 4.1 v3.0.0 Learning Benchmark Plot
![PrimAITE 3.0.0 Learning Benchmark Plot](PrimAITE v3.0.0 Learning Benchmark.png)
### 4.2 Learning Benchmark of Minor and Bugfix Releases for Major Version 3
![Learning Benchmark of Minor and Bugfix Releases for Major Version 3](PrimAITE Learning Benchmark of Minor and Bugfix Releases for Major Version 3.png)
### 4.3 Performance of Minor and Bugfix Releases for Major Version 3
![Performance of Minor and Bugfix Releases for Major Version 3](PrimAITE Performance of Minor and Bugfix Releases for Major Version 3.png)

Binary file not shown.

After

Width:  |  Height:  |  Size: 316 KiB

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

View File

@@ -0,0 +1,38 @@
# PrimAITE v3.1.0 Learning Benchmark
## PrimAITE Dev Team
### 2024-07-20
---
## 1 Introduction
PrimAITE v3.1.0 was benchmarked automatically upon release. Learning rate metrics were captured to be referenced during system-level testing and user acceptance testing (UAT).
The benchmarking process consists of running 5 training session using the same config file. Each session trains an agent for 1000 episodes, with each episode consisting of 128 steps.
The total reward per episode from each session is captured. This is then used to calculate an caverage total reward per episode from the 5 individual sessions for smoothing. Finally, a 25-widow rolling average of the average total reward per session is calculated for further smoothing.
## 2 System Information
### 2.1 Python
**Version:** 3.10.14 (main, Apr 6 2024, 18:45:05) [GCC 9.4.0]
### 2.2 System
- **OS:** Linux
- **OS Version:** #76~20.04.1-Ubuntu SMP Thu Jun 13 18:00:23 UTC 2024
- **Machine:** x86_64
- **Processor:** x86_64
### 2.3 CPU
- **Physical Cores:** 2
- **Total Cores:** 4
- **Max Frequency:** 0.00Mhz
### 2.4 Memory
- **Total:** 15.62GB
- **Swap Total:** 0.00B
## 3 Stats
- **Total Sessions:** 5
- **Total Episodes:** 5005
- **Total Steps:** 640000
- **Av Session Duration (s):** 1632.8888
- **Av Step Duration (s):** 0.0510
- **Av Duration per 100 Steps per 10 Nodes (s):** 5.1028
## 4 Graphs
### 4.1 v3.1.0 Learning Benchmark Plot
![PrimAITE 3.1.0 Learning Benchmark Plot](PrimAITE v3.1.0 Learning Benchmark.png)
### 4.2 Learning Benchmark of Minor and Bugfix Releases for Major Version 3
![Learning Benchmark of Minor and Bugfix Releases for Major Version 3](PrimAITE Learning Benchmark of Minor and Bugfix Releases for Major Version 3.png)
### 4.3 Performance of Minor and Bugfix Releases for Major Version 3
![Performance of Minor and Bugfix Releases for Major Version 3](PrimAITE Performance of Minor and Bugfix Releases for Major Version 3.png)

Binary file not shown.

After

Width:  |  Height:  |  Size: 304 KiB

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

47
benchmark/utils.py Normal file
View File

@@ -0,0 +1,47 @@
# © Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
import platform
from typing import Dict
import psutil
from GPUtil import GPUtil
def get_size(size_bytes: int) -> str:
"""
Scale bytes to its proper format.
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
:
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if size_bytes < factor:
return f"{size_bytes:.2f}{unit}B"
size_bytes /= factor
def _get_system_info() -> Dict:
"""Builds and returns a dict containing system info."""
uname = platform.uname()
cpu_freq = psutil.cpu_freq()
virtual_mem = psutil.virtual_memory()
swap_mem = psutil.swap_memory()
gpus = GPUtil.getGPUs()
return {
"System": {
"OS": uname.system,
"OS Version": uname.version,
"Machine": uname.machine,
"Processor": uname.processor,
},
"CPU": {
"Physical Cores": psutil.cpu_count(logical=False),
"Total Cores": psutil.cpu_count(logical=True),
"Max Frequency": f"{cpu_freq.max:.2f}Mhz",
},
"Memory": {"Total": get_size(virtual_mem.total), "Swap Total": get_size(swap_mem.total)},
"GPU": [{"Name": gpu.name, "Total Memory": f"{gpu.memoryTotal}MB"} for gpu in gpus],
}

View File

@@ -0,0 +1,154 @@
# -*- coding: utf-8 -*-
import datetime
import sys
from pathlib import Path
# Constants
CURRENT_YEAR = datetime.date.today().year
COPYRIGHT_PY_STR = f"# © Crown-owned copyright {CURRENT_YEAR}, Defence Science and Technology Laboratory UK"
COPYRIGHT_RST_LINES = [
".. only:: comment",
"",
f" © Crown-owned copyright {CURRENT_YEAR}, Defence Science and Technology Laboratory UK",
]
PATHS = {Path("./src"), Path("./tests"), Path("./docs"), Path("./benchmark")}
EXTENSIONS = {".py", ".rst"}
def _is_copyright_line(line: str) -> bool:
"""
Check if a line is a copyright line.
:param line: The line to check.
:return: True if the line is a copyright line, False otherwise.
"""
return line.startswith("#") and "copyright" in line.lower()
def _is_rst_copyright_lines(lines: list) -> bool:
"""
Check if the lines match the RST copyright format.
:param lines: The lines to check.
:return: True if the lines match the RST copyright format, False otherwise.
"""
return len(lines) >= 3 and lines[0] == ".. only:: comment" and "copyright" in lines[2].lower()
def process_py_file(file_path: Path) -> bool:
"""
Process a Python file to check and add/update the copyright clause.
:param file_path: The path to the file to check and update.
:return: True if the file was modified, False otherwise.
"""
modified = False
try:
content = file_path.read_text(encoding="utf-8")
lines = content.splitlines(keepends=True) # Keep line endings
if lines and _is_copyright_line(lines[0]):
if lines[0].strip() != COPYRIGHT_PY_STR:
lines[0] = COPYRIGHT_PY_STR + "\n"
modified = True
print(f"Updated copyright clause in {file_path}")
else:
lines.insert(0, COPYRIGHT_PY_STR + "\n")
modified = True
print(f"Added copyright clause to {file_path}")
if modified:
file_path.write_text("".join(lines), encoding="utf-8")
except Exception as e:
print(f"Failed to process {file_path}: {e}")
return False
return modified
def process_rst_file(file_path: Path) -> bool:
"""
Process an RST file to check and add/update the copyright clause.
:param file_path: The path to the file to check and update.
:return: True if the file was modified, False otherwise.
"""
modified = False
try:
content = file_path.read_text(encoding="utf-8")
lines = content.splitlines(keepends=True) # Keep line endings
existing_block = any(".. only:: comment" in line for line in lines)
if existing_block:
# Check if the block is correct
for i, line in enumerate(lines):
if line.strip() == ".. only:: comment":
if lines[i : i + 3] != [
COPYRIGHT_RST_LINES[0] + "\n",
COPYRIGHT_RST_LINES[1] + "\n",
COPYRIGHT_RST_LINES[2] + "\n",
]:
# Update the incorrect block
lines[i : i + 3] = [
COPYRIGHT_RST_LINES[0] + "\n",
COPYRIGHT_RST_LINES[1] + "\n",
COPYRIGHT_RST_LINES[2] + "\n",
]
modified = True
print(f"Updated copyright clause in {file_path}")
break
else:
# Insert new copyright block
lines = [line + "\n" for line in COPYRIGHT_RST_LINES] + ["\n"] + lines
modified = True
print(f"Added copyright clause to {file_path}")
if modified:
file_path.write_text("".join(lines), encoding="utf-8")
except Exception as e:
print(f"Failed to process {file_path}: {e}")
return False
return modified
def process_file(file_path: Path) -> bool:
"""
Check if a file has the correct copyright clause and add or update it if necessary.
:param file_path: The path to the file to check and update.
:return: True if the file was modified, False otherwise.
"""
if file_path.suffix == ".py":
return process_py_file(file_path)
elif file_path.suffix == ".rst":
return process_rst_file(file_path)
return False
def main() -> int:
"""
Main function to walk through the root directories, check files, and update the copyright clause.
:return: 1 if any file was modified, 0 otherwise.
"""
files_checked = 0
files_modified = 0
any_file_modified = False
for path in PATHS:
for file_path in path.rglob("*"):
if file_path.suffix in EXTENSIONS:
files_checked += 1
if process_file(file_path):
files_modified += 1
any_file_modified = True
if any_file_modified:
print(f"Files Checked: {files_checked}. Files Modified: {files_modified}")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -48,7 +48,7 @@ class "ActiveNode" as primaite.nodes.active_node.ActiveNode {
file_system_state_actual : GOOD
file_system_state_observed : REPAIRING, RESTORING, GOOD
ip_address : str
patching_count : int
fixing_count : int
software_state
software_state : GOOD
set_file_system_state(file_system_state: FileSystemState) -> None
@@ -353,10 +353,10 @@ class "SB3Agent" as primaite.agents.sb3.SB3Agent {
}
class "Service" as primaite.common.service.Service {
name : str
patching_count : int
fixing_count : int
port : str
software_state : GOOD
reduce_patching_count() -> None
reduce_fixing_count() -> None
}
class "ServiceNode" as primaite.nodes.service_node.ServiceNode {
services : Dict[str, Service]
@@ -455,7 +455,7 @@ class "TrainingConfig" as primaite.config.training_config.TrainingConfig {
sb3_output_verbose_level
scanning : float
seed : Optional[int]
service_patching_duration : int
service_fixing_duration : int
session_type
time_delay : int
from_dict(config_dict: Dict[str, Any]) -> TrainingConfig

View File

@@ -1,3 +1,4 @@
# © Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
# Minimal makefile for Sphinx documentation
# You can set these variables from the command line, and also
# from the environment for the first two.
@@ -6,7 +7,7 @@ SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build
AUTOSUMMARY="source\_autosummary"
AUTOSUMMARY="source/_autosummary"
# Remove command is different depending on OS
ifdef OS
@@ -29,6 +30,5 @@ clean:
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile | clean
pip-licenses --format=rst --with-urls --output-file=source/primaite-dependencies.rst
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

BIN
docs/_static/component_relationship.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

BIN
docs/_static/firewall_acl.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

BIN
docs/_static/notebooks/extensions.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

BIN
docs/_static/primAITE_architecture.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

BIN
docs/_static/switched_p2p_network.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

View File

@@ -1,6 +1,6 @@
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
..
Credit to https://github.com/JamesALeedham/Sphinx-Autosummary-Recursion for the custom templates.

View File

@@ -1,6 +1,6 @@
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
..
Credit to https://github.com/JamesALeedham/Sphinx-Autosummary-Recursion for the custom templates.

View File

@@ -1,6 +1,8 @@
:orphan:
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
..
DO NOT DELETE THIS FILE! It contains the all-important `.. autosummary::` directive with `:recursive:` option, without
@@ -17,4 +19,3 @@
:recursive:
primaite
tests

View File

@@ -0,0 +1,68 @@
# © Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
#!/bin/bash
set -x
apt-get update
apt-get -y install git rsync python3-sphinx
pwd ls -lah
export SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)
##############
# BUILD DOCS #
##############
cd docs
# Python Sphinx, configured with source/conf.py
# See https://www.sphinx-doc.org/
make clean
make html
cd ..
#######################
# Update GitHub Pages #
#######################
git config --global user.name "${GITHUB_ACTOR}"
git config --global user.email "${GITHUB_ACTOR}@users.noreply.github.com"
docroot=`mktemp -d`
rsync -av $PWD/docs/_build/html/ "${docroot}/"
pushd "${docroot}"
git init
git remote add deploy "https://token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git"
git checkout -b sphinx-docs-github-pages
# Adds .nojekyll file to the root to signal to GitHub that
# directories that start with an underscore (_) can remain
touch .nojekyll
# Add README
cat > README.md <<EOF
# README for the Sphinx Docs GitHub Pages Branch
This branch is simply a cache for the website served from https://{todo:fill in URL}.github.io/PrimAITE/,
and is not intended to be viewed on github.com.
For more information on how this site is built using Sphinx, Read the Docs, GitHub Actions/Pages, and demo
implementation from https://github.com/annegentle, see:
* https://www.docslikecode.com/articles/github-pages-python-sphinx/
* https://tech.michaelaltfield.net/2020/07/18/sphinx-rtd-github-pages-1
* https://github.com/annegentle/create-demo
EOF
# Copy the resulting html pages built from Sphinx to the sphinx-docs-github-pages branch
git add .
# Make a commit with changes and any new files
msg="Updating Docs for commit ${GITHUB_SHA} made on `date -d"@${SOURCE_DATE_EPOCH}" --iso-8601=seconds` from ${GITHUB_REF} by ${GITHUB_ACTOR}"
git commit -am "${msg}"
# overwrite the contents of the sphinx-docs-github-pages branch on our github.com repo
git push deploy sphinx-docs-github-pages --force
popd # return to main repo sandbox root
# exit cleanly
exit 0

View File

@@ -1,4 +1,4 @@
# © Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
# © Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
@@ -9,13 +9,15 @@ import datetime
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
import os
import shutil
import sys
from pathlib import Path
from typing import Any, List, Optional
import furo # noqa
sys.path.insert(0, os.path.abspath("../"))
# -- Project information -----------------------------------------------------
year = datetime.datetime.now().year
project = "PrimAITE"
@@ -28,6 +30,11 @@ with open("../src/primaite/VERSION", "r") as file:
# The full version, including alpha/beta/rc tags
release = version
# set global variables
rst_prolog = f"""
.. |VERSION| replace:: {release}
"""
html_title = f"{project} v{release} docs"
# -- General configuration ---------------------------------------------------
@@ -43,16 +50,136 @@ extensions = [
"sphinx.ext.viewcode", # Add a link to the Python source code for classes, functions etc.
"sphinx.ext.todo",
"sphinx_copybutton", # Adds a copy button to code blocks
"sphinx_code_tabs", # Enables tabbed code blocks
"nbsphinx",
]
templates_path = ["_templates"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
exclude_patterns = [
"_build",
"Thumbs.db",
".DS_Store",
]
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = "furo"
html_static_path = ["_static"]
html_theme_options = {"globaltoc_collapse": True, "globaltoc_maxdepth": 2}
html_copy_source = False
nbsphinx_allow_errors = False # set to True to take shortcuts
html_scaled_image_link = False
# make some stuff easier to read
nbsphinx_prolog = """
.. raw:: html
<style>
.stderr {
color: #000 !important
}
</style>
"""
def replace_token(app: Any, docname: Any, source: Any):
"""Replaces a token from the list of tokens."""
result = source[0]
for key in app.config.tokens:
result = result.replace(key, app.config.tokens[key])
source[0] = result
tokens = {
"{VERSION}": release,
} # Token VERSION is replaced by the value of the PrimAITE version in the version file
"""Dict containing the tokens that need to be replaced in documentation."""
def notebook_assets(ignored_files: Optional[List[str]] = [], include_file_types: Optional[List[str]] = []) -> Any:
"""
Creates a function to be used with `shutil.copytree`'s `ignore` parameter.
:param ignored_files: A list of specific file names to ignore. If a file in the directory matches one of these
names, it will be excluded from the copy process.
:type ignored_files: Optional[List[str]]
:param include_file_types: A list of file extensions to include in the copy process. Files that do not match these
extensions will be excluded. If this list is empty, all files will be excluded, effectively copying only
directories.
:type include_file_types: Optional[List[str]]
"""
def ignore_items(directory: List[str], contents: List[str]) -> List[str]:
"""
Determines which files and directories should be ignored during the copy process.
:param directory: The directory being copied.
:type directory: str
:param contents: A list of contents in the directory.
:type contents: List[str]
:return: A list of items to exclude from the copy process.
:rtype: List[str]
"""
exclude_items = []
for item in contents:
if item in ignored_files:
exclude_items.append(item)
continue
if len(include_file_types) > 0:
if not any(item.lower().endswith(ext.lower()) for ext in include_file_types) and os.path.isdir(item):
exclude_items.append(item)
else:
# if we dont specify which files to include, exclude everything
exclude_items.append(item)
# exclude files but not directories
return [path for path in exclude_items if not (Path(directory) / path).is_dir()]
return ignore_items
def copy_notebooks_to_docs() -> Any:
"""
Incredibly over-engineered method that copies the notebooks and its assets to a directory within the docs directory.
This allows developers to create new notebooks without having to worry about updating documentation when
a new notebook is included within PrimAITE.
"""
notebook_asset_types = [".ipynb", ".png", ".svg"]
notebook_directories = []
# find paths where notebooks are contained
for notebook in Path("../src/primaite").rglob("*.ipynb"):
# add parent path to notebook directory if not already added
if notebook.parent not in notebook_directories:
notebook_directories.append(notebook.parent)
# go through the notebook directories and copy the notebooks and extra assets
for notebook_parent in notebook_directories:
shutil.copytree(
src=notebook_parent,
dst=Path("source") / "notebooks" / notebook_parent.name,
ignore=notebook_assets(include_file_types=notebook_asset_types),
dirs_exist_ok=True,
)
def suppress_log_output():
"""Sets the log level while building the documentation."""
from primaite import _FILE_HANDLER, _LOGGER, _STREAM_HANDLER
log_level = "WARN"
_LOGGER.setLevel(log_level)
_STREAM_HANDLER.setLevel(log_level)
_FILE_HANDLER.setLevel(log_level)
def setup(app: Any):
"""Custom setup for sphinx."""
suppress_log_output()
copy_notebooks_to_docs()
app.add_config_value("tokens", {}, True)
app.connect("source-read", replace_token)

View File

@@ -1,27 +1,94 @@
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
Welcome to PrimAITE's documentation
====================================
What is PrimAITE?
------------------------
-----------------
PrimAITE (Primary-level AI Training Environment) is a simulation environment for training AI under the ARCD programme. It incorporates the functionality required of a Primary-level environment, as specified in the Dstl ARCD Training Environment Matrix document:
Overview
^^^^^^^^
* The ability to model a relevant platform / system context;
* The ability to model key characteristics of a platform / system by representing connections, IP addresses, ports, traffic loading, operating systems, file system, services and processes;
* Operates at machine-speed to enable fast training cycles.
The ARCD Primary-level AI Training Environment (**PrimAITE**) provides an effective simulation capability for training and evaluating AI in a cyber-defensive role. It incorporates the functionality required of a primary-level ARCD environment:
PrimAITE aims to evolve into an ARCD environment that could be used as the follow-on from Reception level approaches (e.g. YAWNING TITAN), and help bridge the Sim-to-Real gap into Secondary level environments (e.g. IMAGINARY YAK).
- The ability to model a relevant system context;
- Modelling an adversarial agent that the defensive agent can be trained and evaluated against;
- The ability to model key characteristics of a system by representing hosts, servers, network devices, IP addresses, ports, operating systems, folders / files, applications, services and links;
- Modelling background (green) pattern-of-life;
- Operates at machine-speed to enable fast training cycles via Reinforcement Learning (RL).
This is similar to the approach taken by FVEY international partners (e.g. AUS CyBORG, US NSA FARLAND and CAN CyGil). These environments are referenced by the Dstl ARCD Agent Training Environments Knowledge Transfer document (TR141342).
Features
^^^^^^^^
PrimAITE incorporates the following features:
- Architected with a separate Simulation layer and Game layer. This separation of concerns defines a clear path towards transfer learning with environments of differing fidelity;
- Ability to reconfigure an RL reward function based on (a) the ability to counter the modelled adversarial cyber-attack, and (b) the ability to ensure success for green agents;
- Access Control List (ACL) functions for network devices (routers and firewalls), following standard ACL rule format (e.g., DENY / ALLOW, source / destination IP addresses, protocol and port);
- Application of traffic to the links of the system laydown adheres to the ACL rulesets and routing tables contained within each network device;
- Provides RL environments adherent to the Farama Foundation Gymnasium (Previously OpenAI Gym) API, allowing integration with any compliant RL Agent frameworks;
- Provides RL environments adherent to Ray RLlib environment specifications for single-agent and multi-agent scenarios;
- Assessed for compatibility with Stable-Baselines3 (SB3), Ray RLlib, and bespoke agents;
- Persona-based adversarial (Red) agent behaviour; several out-the-box personas are provided, and more can be developed to suit the needs of the task. Stochastic variations in Red agent behaviour are also included as required;
- A robust system logging tool, automatically enabled at the node level and featuring various log levels and terminal output options, enables PrimAITE users to conduct in-depth network simulations;
- A PCAP service is seamlessly integrated within the simulation, automatically capturing and logging frames for both
inbound and outbound traffic at the network interface level. This automatic functionality, combined with the ability
to separate traffic directions, significantly enhances network analysis and troubleshooting capabilities;
- Agent action logs provide a description of every action taken by each agent during the episode. This includes timestep, action, parameters, request and response, for all Blue agent activity, which is aligned with the Track 2 Common Action / Observation Space (CAOS) format. Action logs also details of all scripted / stochastic red / green agent actions;
- Environment ground truth is provided at every timestep, providing a full description of the environments true state;
- Alignment with CAOS provides the ability to transfer agents between CAOS compliant environments.
Architecture
^^^^^^^^^^^^
PrimAITE is a Python application and will operate on multiple Operating Systems (Windows, Linux and Mac);
a comprehensive installation and user guide is provided with each release to support its usage.
Configuration of PrimAITE is achieved via included YAML files which support full control over the network / system laydown being modelled, background pattern of life, adversarial (red agent) behaviour, and step and episode count.
A Simulation Controller layer manages the overall running of the simulation, keeping track of all low-level objects.
It is agnostic to the number of agents, their action / observation spaces, and the RL library being used.
It presents a public API providing a method for describing the current state of the simulation, a method that accepts action requests and provides responses, and a method that triggers a timestep advancement.
The Game Layer converts the simulation into a playable game for the agent(s).
It translates between simulation state and Gymnasium.Spaces to pass action / observation data between the agent(s) and the simulation. It is responsible for calculating rewards, managing Multi-Agent RL (MARL) action turns, and via a single agent interface can interact with Blue, Red and Green agents.
Agents can either generate their own scripted behaviour or accept input behaviour from an RL agent.
Finally, a Gymnasium / Ray RLlib Environment Layer forwards requests to the Game Layer as the agent sends them. This layer also manages most of the I/O, such as reading in the configuration files and saving agent logs.
.. image:: ../../_static/primAITE_architecture.png
:width: 500
:align: center
Training & Evaluation Capability
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
PrimAITE provides a training and evaluation capability to AI agents in the context of cyber-attack, via its Gymnasium / Ray RLlib compliant interface.
Scenarios can be constructed to reflect network / system laydowns consisting of any configuration of nodes (e.g., PCs, servers etc.) and the networking equipment and links between them.
All nodes can be configured to contain applications, services, folders and files (and their status).
Traffic flows between services and applications as directed by an execution definition, with the traffic flow on the network governed by the network equipment (switches, routers and firewalls) and the ACL rules and routing tables they employ.
Highlights of PrimAITEs training and evaluation capability are:
- The scenario is not bound to a representation of any platform, system, or technology;
- Fully configurable (network / system laydown, green pattern-of-life, red personas, reward function, ACL rules for each device, number of episodes / steps, action / observation space) and repeatable to suit the requirements of AI agents;
- Can integrate with any Gymnasium / Ray RLlib compliant AI agent .
PrimAITE provides a number of use cases (network and red/green action configurations) by default which the user is able to extend and modify as required.
What is PrimAITE built with
--------------------------------------
---------------------------
* `OpenAI's Gym <https://gym.openai.com/>`_ is used as the basis for AI blue agent interaction with the PrimAITE environment
* `Gymnasium <https://gymnasium.farama.org/>`_ is used as the basis for AI blue agent interaction with the PrimAITE environment
* `Networkx <https://github.com/networkx/networkx>`_ is used as the underlying data structure used for the PrimAITE environment
* `Stable Baselines 3 <https://github.com/DLR-RM/stable-baselines3>`_ is used as a default source of RL algorithms (although PrimAITE is not limited to SB3 agents)
* `Ray RLlib <https://github.com/ray-project/ray>`_ is used as an additional source of RL algorithms
@@ -31,35 +98,45 @@ What is PrimAITE built with
* `Plotly <https://github.com/plotly/plotly.py>`_ is used for building high level charts
Where next?
------------
Getting Started with PrimAITE
-----------------------------
Head over to the :ref:`getting-started` page to install and setup PrimAITE!
.. toctree::
:maxdepth: 8
:caption: Contents:
:caption: About PrimAITE:
:hidden:
source/about
source/dependencies
source/glossary
.. toctree::
:caption: Usage:
:hidden:
source/getting_started
source/about
source/simulation
source/game_layer
source/config
source/primaite_session
source/custom_agent
PrimAITE API <source/_autosummary/primaite>
PrimAITE Tests <source/_autosummary/tests>
source/dependencies
source/glossary
source/migration_1.2_-_2.0
.. TODO: Add project links once public repo has been created
source/environment
source/customising_scenarios
source/varying_config_files
.. toctree::
:caption: Project Links:
:caption: Notebooks:
:hidden:
Code <https://github.com/Autonomous-Resilient-Cyber-Defence/PrimAITE>
Issues <https://github.com/Autonomous-Resilient-Cyber-Defence/PrimAITE/issues>
Pull Requests <https://github.com/Autonomous-Resilient-Cyber-Defence/PrimAITE/pulls>
Discussions <https://github.com/Autonomous-Resilient-Cyber-Defence/PrimAITE/discussions>
source/example_notebooks
source/notebooks/executed_notebooks
.. toctree::
:caption: Developer information:
:hidden:
source/developer_tools
source/state_system
source/request_system
PrimAITE API <source/_autosummary/primaite>
PrimAITE Tests <source/_autosummary/tests>

View File

@@ -1,4 +1,5 @@
@ECHO OFF
REM © Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
setlocal EnableDelayedExpansion
@@ -36,11 +37,6 @@ IF EXIST %AUTOSUMMARYDIR% (
RMDIR %AUTOSUMMARYDIR% /s /q
)
REM print the YT licenses
set LICENSEBUILD=pip-licenses --format=rst --with-urls
set DEPS="%cd%\source\primaite-dependencies.rst"
%LICENSEBUILD% --output-file=%DEPS%
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end

View File

@@ -1,414 +1,317 @@
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _about:
About PrimAITE
==============
PrimAITE is a simulation environment for training agents to protect a computer network from cyber attacks.
Features
********
PrimAITE provides the following features:
* A flexible network / system laydown based on the Python networkx framework
* Nodes and links (edges) host Python classes in order to present attributes and methods (and hence, a more representative model of a platform / system)
* A 'green agent' Information Exchange Requirement (IER) function allows the representation of traffic (protocols and loading) on any / all links. Application of IERs is based on the status of node operating systems and services
* A 'green agent' node Pattern-of-Life (PoL) function allows the representation of core behaviours on nodes (e.g. changing the Hardware state, Software State, Service state, or File System state)
* An Access Control List (ACL) function, mimicking the behaviour of a network firewall, is applied across the model, following standard ACL rule format (e.g. DENY/ALLOW, source IP, destination IP, protocol and port). Application of IERs adheres to any ACL restrictions
* Presents an OpenAI Gym interface to the environment, allowing integration with any OpenAI Gym compliant defensive agents
* Red agent activity based on 'red' IERs and 'red' PoL
* Defined reward function for use with RL agents (based on nodes status, and green / red IER success)
* Fully configurable (network / system laydown, IERs, node PoL, ACL, episode step period, episode max steps) and repeatable to suit the training requirements of agents. Therefore, not bound to a representation of any particular platform, system or technology
* Full capture of discrete metrics relating to agent training (full system state, agent actions taken, average reward)
* Networkx provides laydown visualisation capability
Architecture - Nodes and Links
******************************
**Nodes**
An inheritance model has been adopted in order to model nodes. All nodes have the following base attributes (Class: Node):
* ID
* Name
* Type (e.g. computer, switch, RTU - enumeration)
* Priority (P1, P2, P3, P4 or P5 - enumeration)
* Hardware State (ON, OFF, RESETTING, SHUTTING_DOWN, BOOTING - enumeration)
Active Nodes also have the following attributes (Class: Active Node):
* IP Address
* Software State (GOOD, PATCHING, COMPROMISED - enumeration)
* File System State (GOOD, CORRUPT, DESTROYED, REPAIRING, RESTORING - enumeration)
Service Nodes also have the following attributes (Class: Service Node):
* List of Services (where service is composed of service name and port). There is no theoretical limit on the number of services that can be modelled. Services and protocols are currently intrinsically linked (i.e. a service is an application on a node transmitting traffic of this protocol type)
* Service state (GOOD, PATCHING, COMPROMISED, OVERWHELMED - enumeration)
Passive Nodes are currently not used (but may be employed for non IP-based components such as machinery actuators in future releases).
**Links**
Links are modelled both as network edges (networkx) and as Python classes, in order to extend their functionality. Links include the following attributes:
* ID
* Name
* Bandwidth (bits/s)
* Source node ID
* Destination node ID
* Protocol list (containing the loading of protocols currently running on the link)
When the simulation runs, IERs are applied to the links in order to model traffic loading, individually assigned to each protocol. This allows green (background) and red agent behaviour to be modelled, and defensive agents to identify suspicious traffic patterns at a protocol / traffic loading level of fidelity.
Information Exchange Requirements (IERs)
****************************************
PrimAITE adopts the concept of Information Exchange Requirements (IERs) to model both green agent (background) and red agent (adversary) behaviour. IERs are used to initiate modelling of traffic loading on the network, and have the following attributes:
* ID
* Start step (i.e. which step in the training episode should the IER start)
* End step (i.e. which step in the training episode should the IER end)
* Source node ID
* Destination node ID
* Load (bits/s)
* Protocol
* Port
* Running status (i.e. on / off)
The application of green agent IERs between a source and destination follows a number of rules. Specifically:
1. Does the current simulation time step fall between IER start and end step
2. Is the source node operational (both physically and at an O/S level), and is the service (protocol / port) associated with the IER (a) present on this node, and (b) in an operational state (i.e. not PATCHING)
3. Is the destination node operational (both physically and at an O/S level), and is the service (protocol / port) associated with the IER (a) present on this node, and (b) in an operational state (i.e. not PATCHING)
4. Are there any Access Control List rules in place that prevent the application of this IER
5. Are all switches in the (OSPF) path between source and destination operational (both physically and at an O/S level)
For red agent IERs, the application of IERs between a source and destination follows a number of subtly different rules. Specifically:
1. Does the current simulation time step fall between IER start and end step
2. Is the source node operational, and is the service (protocol / port) associated with the IER (a) present on that node and (b) already in a compromised state
3. Is the destination node operational, and is the service (protocol / port) associated with the IER present on that node
4. Are there any Access Control List rules in place that prevent the application of this IER
5. Are all switches in the (OSPF) path between source and destination operational (both physically and at an O/S level)
Assuming the rules pass, the IER is applied to all relevant links (based on use of OSPF) between source and destination.
Node Pattern-of-Life
********************
Every node can be impacted (i.e. have a status change applied to it) by either green agent pattern-of-life or red agent pattern-of-life. This is distinct from IERs, and allows for attacks (and defence) to be modelled purely within the confines of a node.
The status changes that can be made to a node are as follows:
* All Nodes:
* Hardware State:
* ON
* OFF
* RESETTING - when a status of resetting is entered, the node will automatically exit this state after a number of steps (as defined by the nodeResetDuration configuration item) after which it returns to an ON state
* BOOTING
* SHUTTING_DOWN
* Active Nodes and Service Nodes:
* Software State:
* GOOD
* PATCHING - when a status of patching is entered, the node will automatically exit this state after a number of steps (as defined by the osPatchingDuration configuration item) after which it returns to a GOOD state
* COMPROMISED
* File System State:
* GOOD
* CORRUPT (can be resolved by repair or restore)
* DESTROYED (can be resolved by restore only)
* REPAIRING - when a status of repairing is entered, the node will automatically exit this state after a number of steps (as defined by the fileSystemRepairingLimit configuration item) after which it returns to a GOOD state
* RESTORING - when a status of repairing is entered, the node will automatically exit this state after a number of steps (as defined by the fileSystemRestoringLimit configuration item) after which it returns to a GOOD state
* Service Nodes only:
* Service State (for any associated service):
* GOOD
* PATCHING - when a status of patching is entered, the service will automatically exit this state after a number of steps (as defined by the servicePatchingDuration configuration item) after which it returns to a GOOD state
* COMPROMISED
* OVERWHELMED
Red agent pattern-of-life has an additional feature not found in the green pattern-of-life. This is the ability to influence the state of the attributes of a node via a number of different conditions:
* DIRECT:
The pattern-of-life described by the configuration file item will be applied regardless of any other conditions in the network. This is particularly useful for direct red agent entry into the network.
* IER:
The pattern-of-life described by the configuration file item will be applied to the service on the node, only if there is an IER of the same protocol / service type incoming at the specified timestep.
* SERVICE:
The pattern-of-life described by the configuration file item will be applied to the node based on the state of a service. The service can either be on the same node, or a different node within the network.
Access Control List modelling
*****************************
An Access Control List (ACL) is modelled to provide the means to manage traffic flows in the system. This will allow defensive agents the means to turn on / off rules, or potentially create new rules, to counter an attack.
The ACL follows a standard network firewall format. For example:
.. list-table:: ACL example
:widths: 25 25 25 25 25
:header-rows: 1
* - Permission
- Source IP
- Dest IP
- Protocol
- Port
* - DENY
- 192.168.1.2
- 192.168.1.3
- HTTPS
- 443
* - ALLOW
- 192.168.1.4
- ANY
- SMTP
- 25
* - DENY
- ANY
- 192.168.1.5
- ANY
- ANY
All ACL rules are considered when applying an IER. Logic follows the order of rules, so a DENY or ALLOW for the same parameters will override an earlier entry.
Observation Spaces
******************
The observation space provides the blue agent with information about the current status of nodes and links.
PrimAITE builds on top of Gym Spaces to create an observation space that is easily configurable for users. It's made up of components which are managed by the :py:class:`primaite.environment.observations.ObservationsHandler`. Each training scenario can define its own observation space, and the user can choose which information to inlude, and how it should be formatted.
NodeLinkTable component
-----------------------
For example, the :py:class:`primaite.environment.observations.NodeLinkTable` component represents the status of nodes and links as a ``gym.spaces.Box`` with an example format shown below:
An example observation space is provided below:
.. list-table:: Observation Space example
:widths: 25 25 25 25 25 25 25
:header-rows: 1
* -
- ID
- Hardware State
- Software State
- File System State
- Service / Protocol A
- Service / Protocol B
* - Node A
- 1
- 1
- 1
- 1
- 1
- 1
* - Node B
- 2
- 1
- 3
- 1
- 1
- 1
* - Node C
- 3
- 2
- 1
- 1
- 3
- 2
* - Link 1
- 5
- 0
- 0
- 0
- 0
- 10000
* - Link 2
- 6
- 0
- 0
- 0
- 0
- 10000
* - Link 3
- 7
- 0
- 0
- 0
- 5000
- 0
For the nodes, the following values are represented:
.. code-block::
[
ID
Hardware State (1=ON, 2=OFF, 3=RESETTING, 4=SHUTTING_DOWN, 5=BOOTING)
Operating System State (0=none, 1=GOOD, 2=PATCHING, 3=COMPROMISED)
File System State (0=none, 1=GOOD, 2=CORRUPT, 3=DESTROYED, 4=REPAIRING, 5=RESTORING)
Service1/Protocol1 state (0=none, 1=GOOD, 2=PATCHING, 3=COMPROMISED)
Service2/Protocol2 state (0=none, 1=GOOD, 2=PATCHING, 3=COMPROMISED)
]
(Note that each service available in the network is provided as a column, although not all nodes may utilise all services)
For the links, the following statuses are represented:
.. code-block::
[
ID
Hardware State (0=not applicable)
Operating System State (0=not applicable)
File System State (0=not applicable)
Service1/Protocol1 state (Traffic load from this protocol on this link)
Service2/Protocol2 state (Traffic load from this protocol on this link)
]
NodeStatus component
----------------------
This is a MultiDiscrete observation space that can be though of as a one-dimensional vector of discrete states.
The example above would have the following structure:
.. code-block::
[
node1_info
node2_info
node3_info
]
Each ``node_info`` contains the following:
.. code-block::
[
hardware_state (0=none, 1=ON, 2=OFF, 3=RESETTING, 4=SHUTTING_DOWN, 5=BOOTING)
software_state (0=none, 1=GOOD, 2=PATCHING, 3=COMPROMISED)
file_system_state (0=none, 1=GOOD, 2=CORRUPT, 3=DESTROYED, 4=REPAIRING, 5=RESTORING)
service1_state (0=none, 1=GOOD, 2=PATCHING, 3=COMPROMISED)
service2_state (0=none, 1=GOOD, 2=PATCHING, 3=COMPROMISED)
]
In a network with three nodes and two services, the full observation space would have 15 elements. It can be written with ``gym`` notation to indicate the number of discrete options for each of the elements of the observation space. For example:
.. code-block::
gym.spaces.MultiDiscrete([4,5,6,4,4,4,5,6,4,4,4,5,6,4,4])
.. note::
NodeStatus observation component provides information only about nodes. Links are not considered.
LinkTrafficLevels
-----------------
This component is a MultiDiscrete space showing the traffic flow levels on the links in the network, after applying a threshold to convert it from a continuous to a discrete value.
There are two configurable parameters:
* ``quantisation_levels`` determines how many discrete bins to use for converting the continuous traffic value to discrete (default is 5).
* ``combine_service_traffic`` determines whether to separately output traffic use for each network protocol or whether to combine them into an overall value for the link. (default is ``True``)
For example, with default parameters and a network with three links, the structure of this component would be:
.. code-block::
[
link1_status
link2_status
link3_status
]
Each ``link_status`` is a number from 0-4 representing the network load in relation to bandwidth.
.. code-block::
0 = No traffic (0%)
1 = low traffic (1%-33%)
2 = medium traffic (33%-66%)
3 = high traffic (66%-99%)
4 = max traffic/ overwhelmed (100%)
Using ``gym`` notation, the shape of the obs space is: ``gym.spaces.MultiDiscrete([5,5,5])``.
Action Spaces
**************
The action space available to the blue agent comes in two types:
1. Node-based
2. Access Control List
3. Any (Agent can take both node-based and ACL-based actions)
The choice of action space used during a training session is determined in the config_[name].yaml file.
**Node-Based**
The agent is able to influence the status of nodes by switching them off, resetting, or patching operating systems and services. In this instance, the action space is an OpenAI Gym spaces.Discrete type, as follows:
* Dictionary item {... ,1: [x1, x2, x3,x4] ...}
The placeholders inside the list under the key '1' mean the following:
* [0, num nodes] - Node ID (0 = nothing, node ID)
* [0, 4] - What property it's acting on (0 = nothing, 1 = state, 2 = SoftwareState, 3 = service state, 4 = file system state)
* [0, 3] - Action on property (0 = nothing, 1 = on / scan, 2 = off / repair, 3 = reset / patch / restore)
* [0, num services] - Resolves to service ID (0 = nothing, resolves to service)
**Access Control List**
The blue agent is able to influence the configuration of the Access Control List rule set (which implements a system-wide firewall). In this instance, the action space is an OpenAI spaces.Discrete type, as follows:
* Dictionary item {... ,1: [x1, x2, x3, x4, x5, x6] ...}
The placeholders inside the list under the key '1' mean the following:
* [0, 2] - Action (0 = do nothing, 1 = create rule, 2 = delete rule)
* [0, 1] - Permission (0 = DENY, 1 = ALLOW)
* [0, num nodes] - Source IP (0 = any, then 1 -> x resolving to IP addresses)
* [0, num nodes] - Dest IP (0 = any, then 1 -> x resolving to IP addresses)
* [0, num services] - Protocol (0 = any, then 1 -> x resolving to protocol)
* [0, num ports] - Port (0 = any, then 1 -> x resolving to port)
**ANY**
The agent is able to carry out both **Node-Based** and **Access Control List** operations.
This means the dictionary will contain key-value pairs in the format of BOTH Node-Based and Access Control List as seen above.
Rewards
*******
A reward value is presented back to the blue agent on the conclusion of every step. The reward value is calculated via two methods which combine to give the total value:
1. Node and service status
2. IER status
**Node and service status**
On every step, the status of each node is compared against both a reference environment (simulating the situation if the red and blue agents had not impacted the environment)
and the before and after state of the environment. If the comparison against the reference environment shows no difference, then the score provided is "AllOK". If there is a
difference with respect to the reference environment, the before and after states are compared, and a score determined. See :ref:`config` for details of reward values.
**IER status**
On every step, the full IER set is examined to determine whether green and red agent IERs are being permitted to run. Any red agent IERs running incur a penalty; any green agent
IERs not permitted to run also incur a penalty. See :ref:`config` for details of reward values.
Future Enhancements
*******************
The PrimAITE project has an ambition to include the following enhancements in future releases:
* Integration with a suitable standardised framework to allow multi-agent integration
* Integration with external threat emulation tools, either using off-line data, or integrating at runtime
* A flexible system for defining network layouts and host configurations
* Highly configurable network hosts, including definition of software, file system, and network interfaces,
* Realistic network traffic simulation, including address and sending packets via internet protocols like TCP, UDP, ICMP, etc.
* Routers with traffic routing and firewall capabilities
* Simulation of customisable deterministic agents
* Support for multiple agents, each having their own customisable observation space, action space, and reward function definition.
Structure
*********
PrimAITE consists of a simulator and a 'game' layer that allows agents to interact with the simulator. The simulator is built in a modular way where each component such as network hosts, links, networking devices, softwares, etc. are implemented as instances of a base class, meaning they all support the same interface. This allows for standardised configuration using either the Python API or YAML files.
The game layer is built on top of the simulator and it consumes the simulation action/state interface to allow agents to interact with the simulator. The game layer is also responsible for defining the reward function and observation space for the agents.
..
Architecture - Nodes and Links
******************************
**Nodes**
An inheritance model has been adopted in order to model nodes. All nodes have the following base attributes (Class: Node):
* ID
* Name
* Type (e.g. computer, switch, RTU - enumeration)
* Priority (P1, P2, P3, P4 or P5 - enumeration)
* Hardware State (ON, OFF, RESETTING, SHUTTING_DOWN, BOOTING - enumeration)
Active Nodes also have the following attributes (Class: Active Node):
* IP Address
* Software State (GOOD, FIXING, COMPROMISED - enumeration)
* File System State (GOOD, CORRUPT, DESTROYED, REPAIRING, RESTORING - enumeration)
Service Nodes also have the following attributes (Class: Service Node):
* List of Services (where service is composed of service name and port). There is no theoretical limit on the number of services that can be modelled. Services and protocols are currently intrinsically linked (i.e. a service is an application on a node transmitting traffic of this protocol type)
* Service state (GOOD, FIXING, COMPROMISED, OVERWHELMED - enumeration)
Passive Nodes are currently not used (but may be employed for non IP-based components such as machinery actuators in future releases).
**Links**
Links are modelled both as network edges (networkx) and as Python classes, in order to extend their functionality. Links include the following attributes:
* ID
* Name
* Bandwidth (bits/s)
* Source node ID
* Destination node ID
* Protocol list (containing the loading of protocols currently running on the link)
When the simulation runs, IERs are applied to the links in order to model traffic loading, individually assigned to each protocol. This allows green (background) and red agent behaviour to be modelled, and defensive agents to identify suspicious traffic patterns at a protocol / traffic loading level of fidelity.
Information Exchange Requirements (IERs)
****************************************
PrimAITE adopts the concept of Information Exchange Requirements (IERs) to model both green agent (background) and red agent (adversary) behaviour. IERs are used to initiate modelling of traffic loading on the network, and have the following attributes:
* ID
* Start step (i.e. which step in the training episode should the IER start)
* End step (i.e. which step in the training episode should the IER end)
* Source node ID
* Destination node ID
* Load (bits/s)
* Protocol
* Port
* Running status (i.e. on / off)
The application of green agent IERs between a source and destination follows a number of rules. Specifically:
1. Does the current simulation time step fall between IER start and end step
2. Is the source node operational (both physically and at an O/S level), and is the service (protocol / port) associated with the IER (a) present on this node, and (b) in an operational state (i.e. not FIXING)
3. Is the destination node operational (both physically and at an O/S level), and is the service (protocol / port) associated with the IER (a) present on this node, and (b) in an operational state (i.e. not FIXING)
4. Are there any Access Control List rules in place that prevent the application of this IER
5. Are all switches in the (OSPF) path between source and destination operational (both physically and at an O/S level)
For red agent IERs, the application of IERs between a source and destination follows a number of subtly different rules. Specifically:
1. Does the current simulation time step fall between IER start and end step
2. Is the source node operational, and is the service (protocol / port) associated with the IER (a) present on that node and (b) already in a compromised state
3. Is the destination node operational, and is the service (protocol / port) associated with the IER present on that node
4. Are there any Access Control List rules in place that prevent the application of this IER
5. Are all switches in the (OSPF) path between source and destination operational (both physically and at an O/S level)
Assuming the rules pass, the IER is applied to all relevant links (based on use of OSPF) between source and destination.
Node Pattern-of-Life
********************
Every node can be impacted (i.e. have a status change applied to it) by either green agent pattern-of-life or red agent pattern-of-life. This is distinct from IERs, and allows for attacks (and defence) to be modelled purely within the confines of a node.
The status changes that can be made to a node are as follows:
* All Nodes:
* Hardware State:
* ON
* OFF
* RESETTING - when a status of resetting is entered, the node will automatically exit this state after a number of steps (as defined by the nodeResetDuration configuration item) after which it returns to an ON state
* BOOTING
* SHUTTING_DOWN
* Active Nodes and Service Nodes:
* Software State:
* GOOD
* FIXING - when a status of FIXING is entered, the node will automatically exit this state after a number of steps (as defined by the osFIXINGDuration configuration item) after which it returns to a GOOD state
* COMPROMISED
* File System State:
* GOOD
* CORRUPT (can be resolved by repair or restore)
* DESTROYED (can be resolved by restore only)
* REPAIRING - when a status of repairing is entered, the node will automatically exit this state after a number of steps (as defined by the fileSystemRepairingLimit configuration item) after which it returns to a GOOD state
* RESTORING - when a status of repairing is entered, the node will automatically exit this state after a number of steps (as defined by the fileSystemRestoringLimit configuration item) after which it returns to a GOOD state
* Service Nodes only:
* Service State (for any associated service):
* GOOD
* FIXING - when a status of FIXING is entered, the service will automatically exit this state after a number of steps (as defined by the serviceFIXINGDuration configuration item) after which it returns to a GOOD state
* COMPROMISED
* OVERWHELMED
Red agent pattern-of-life has an additional feature not found in the green pattern-of-life. This is the ability to influence the state of the attributes of a node via a number of different conditions:
* DIRECT:
The pattern-of-life described by the configuration file item will be applied regardless of any other conditions in the network. This is particularly useful for direct red agent entry into the network.
* IER:
The pattern-of-life described by the configuration file item will be applied to the service on the node, only if there is an IER of the same protocol / service type incoming at the specified timestep.
* SERVICE:
The pattern-of-life described by the configuration file item will be applied to the node based on the state of a service. The service can either be on the same node, or a different node within the network.
Access Control List modelling
*****************************
An Access Control List (ACL) is modelled to provide the means to manage traffic flows in the system. This will allow defensive agents the means to turn on / off rules, or potentially create new rules, to counter an attack.
The ACL follows a standard network firewall format. For example:
.. list-table:: ACL example
:widths: 25 25 25 25 25
:header-rows: 1
* - Permission
- Source IP
- Dest IP
- Protocol
- Port
* - DENY
- 192.168.1.2
- 192.168.1.3
- HTTPS
- 443
* - ALLOW
- 192.168.1.4
- ANY
- SMTP
- 25
* - DENY
- ANY
- 192.168.1.5
- ANY
- ANY
All ACL rules are considered when applying an IER. Logic follows the order of rules, so a DENY or ALLOW for the same parameters will override an earlier entry.
Observation Spaces
******************
The observation space provides the blue agent with information about the current status of nodes and links.
PrimAITE builds on top of Gymnasium Spaces to create an observation space that is easily configurable for users. It's made up of components which are managed by the :py:class:`primaite.environment.observations.ObservationsHandler`. Each training scenario can define its own observation space, and the user can choose which information to inlude, and how it should be formatted.
NodeLinkTable component
-----------------------
For example, the :py:class:`primaite.environment.observations.NodeLinkTable` component represents the status of nodes and links as a ``gym.spaces.Box`` with an example format shown below:
An example observation space is provided below:
.. list-table:: Observation Space example
:widths: 25 25 25 25 25 25 25
:header-rows: 1
* -
- ID
- Hardware State
- Software State
- File System State
- Service / Protocol A
- Service / Protocol B
* - Node A
- 1
- 1
- 1
- 1
- 1
- 1
* - Node B
- 2
- 1
- 3
- 1
- 1
- 1
* - Node C
- 3
- 2
- 1
- 1
- 3
- 2
* - Link 1
- 5
- 0
- 0
- 0
- 0
- 10000
* - Link 2
- 6
- 0
- 0
- 0
- 0
- 10000
* - Link 3
- 7
- 0
- 0
- 0
- 5000
- 0
For the nodes, the following values are represented:
.. code-block::
[
ID
Hardware State (1=ON, 2=OFF, 3=RESETTING, 4=SHUTTING_DOWN, 5=BOOTING)
Operating System State (0=none, 1=GOOD, 2=PATCHING, 3=COMPROMISED)
File System State (0=none, 1=GOOD, 2=CORRUPT, 3=DESTROYED, 4=REPAIRING, 5=RESTORING)
Service1/Protocol1 state (0=none, 1=GOOD, 2=FIXING, 3=COMPROMISED)
Service2/Protocol2 state (0=none, 1=GOOD, 2=FIXING, 3=COMPROMISED)
]
(Note that each service available in the network is provided as a column, although not all nodes may utilise all services)
For the links, the following statuses are represented:
.. code-block::
[
ID
Hardware State (0=not applicable)
Operating System State (0=not applicable)
File System State (0=not applicable)
Service1/Protocol1 state (Traffic load from this protocol on this link)
Service2/Protocol2 state (Traffic load from this protocol on this link)
]
NodeStatus component
----------------------
This is a MultiDiscrete observation space that can be though of as a one-dimensional vector of discrete states.
The example above would have the following structure:
.. code-block::
[
node1_info
node2_info
node3_info
]
Each ``node_info`` contains the following:
.. code-block::
[
hardware_state (0=none, 1=ON, 2=OFF, 3=RESETTING, 4=SHUTTING_DOWN, 5=BOOTING)
software_state (0=none, 1=GOOD, 2=PATCHING, 3=COMPROMISED)
file_system_state (0=none, 1=GOOD, 2=CORRUPT, 3=DESTROYED, 4=REPAIRING, 5=RESTORING)
service1_state (0=none, 1=GOOD, 2=FIXING, 3=COMPROMISED)
service2_state (0=none, 1=GOOD, 2=FIXING, 3=COMPROMISED)
]
In a network with three nodes and two services, the full observation space would have 15 elements. It can be written with ``gym`` notation to indicate the number of discrete options for each of the elements of the observation space. For example:
.. code-block::
gym.spaces.MultiDiscrete([4,5,6,4,4,4,5,6,4,4,4,5,6,4,4])
.. note::
NodeStatus observation component provides information only about nodes. Links are not considered.
LinkTrafficLevels
-----------------
This component is a MultiDiscrete space showing the traffic flow levels on the links in the network, after applying a threshold to convert it from a continuous to a discrete value.
There are two configurable parameters:
* ``quantisation_levels`` determines how many discrete bins to use for converting the continuous traffic value to discrete (default is 5).
* ``combine_service_traffic`` determines whether to separately output traffic use for each network protocol or whether to combine them into an overall value for the link. (default is ``True``)
For example, with default parameters and a network with three links, the structure of this component would be:
.. code-block::
[
link1_status
link2_status
link3_status
]
Each ``link_status`` is a number from 0-4 representing the network load in relation to bandwidth.
.. code-block::
0 = No traffic (0%)
1 = low traffic (1%-33%)
2 = medium traffic (33%-66%)
3 = high traffic (66%-99%)
4 = max traffic/ overwhelmed (100%)
Using ``gym`` notation, the shape of the obs space is: ``gym.spaces.MultiDiscrete([5,5,5])``.
Action Spaces
**************
The action space available to the blue agent comes in two types:
1. Node-based
2. Access Control List
3. Any (Agent can take both node-based and ACL-based actions)
The choice of action space used during a training session is determined in the config_[name].yaml file.
**Node-Based**
The agent is able to influence the status of nodes by switching them off, resetting, or FIXING operating systems and services. In this instance, the action space is a Gymnasium spaces.Discrete type, as follows:
* Dictionary item {... ,1: [x1, x2, x3,x4] ...}
The placeholders inside the list under the key '1' mean the following:
* [0, num nodes] - Node ID (0 = nothing, node ID)
* [0, 4] - What property it's acting on (0 = nothing, 1 = state, 2 = SoftwareState, 3 = service state, 4 = file system state)
* [0, 3] - Action on property (0 = nothing, 1 = on / scan, 2 = off / repair, 3 = reset / patch / restore)
* [0, num services] - Resolves to service ID (0 = nothing, resolves to service)
**Access Control List**
The blue agent is able to influence the configuration of the Access Control List rule set (which implements a system-wide firewall). In this instance, the action space is an Gymnasium spaces.Discrete type, as follows:
* Dictionary item {... ,1: [x1, x2, x3, x4, x5, x6] ...}
The placeholders inside the list under the key '1' mean the following:
* [0, 2] - Action (0 = do nothing, 1 = create rule, 2 = delete rule)
* [0, 1] - Permission (0 = DENY, 1 = ALLOW)
* [0, num nodes] - Source IP (0 = any, then 1 -> x resolving to IP addresses)
* [0, num nodes] - Dest IP (0 = any, then 1 -> x resolving to IP addresses)
* [0, num services] - Protocol (0 = any, then 1 -> x resolving to protocol)
* [0, num ports] - Port (0 = any, then 1 -> x resolving to port)
**ANY**
The agent is able to carry out both **Node-Based** and **Access Control List** operations.
This means the dictionary will contain key-value pairs in the format of BOTH Node-Based and Access Control List as seen above.
Rewards
*******
A reward value is presented back to the blue agent on the conclusion of every step. The reward value is calculated via two methods which combine to give the total value:
1. Node and service status
2. IER status
**Node and service status**
On every step, the status of each node is compared against both a reference environment (simulating the situation if the red and blue agents had not impacted the environment)
and the before and after state of the environment. If the comparison against the reference environment shows no difference, then the score provided is "AllOK". If there is a
difference with respect to the reference environment, the before and after states are compared, and a score determined. See :ref:`config` for details of reward values.
**IER status**
On every step, the full IER set is examined to determine whether green and red agent IERs are being permitted to run. Any red agent IERs running incur a penalty; any green agent
IERs not permitted to run also incur a penalty. See :ref:`config` for details of reward values.
Future Enhancements
*******************
The PrimAITE project has an ambition to include the following enhancements in future releases:
* Integration with a suitable standardised framework to allow multi-agent integration
* Integration with external threat emulation tools, either using off-line data, or integrating at runtime

View File

@@ -1,489 +1,41 @@
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _config:
PrimAITE |VERSION| Configuration
********************************
The Config Files Explained
==========================
PrimAITE uses YAML configuration files to define everything needed to create the training environment for RL agents, including the network, the scripted agents, and the RL agent's action space, observation space, and reward function.
PrimAITE uses two configuration files for its operation:
Example Configuration Hierarchy
###############################
The top level configuration items in a configuration file is as follows
* **The Training Config**
.. code-block:: yaml
Used to define the top-level settings of the PrimAITE environment, the reward values, and the session that is to be run.
io_settings:
...
game:
...
agents:
...
simulation:
...
* **The Lay Down Config**
These are expanded upon in the Configurable items section below
Used to define the low-level settings of a session, including the network laydown, green / red agent information exchange requirements (IERSs) and Access Control Rules.
Configurable items
##################
Training Config:
*******************
.. toctree::
:maxdepth: 1
The Training Config file consists of the following attributes:
configuration/io_settings.rst
configuration/game.rst
configuration/agents.rst
configuration/simulation.rst
**Generic Config Values**
Varying The Configuration Each Episode
######################################
* **agent_framework** [enum]
This identifies the agent framework to be used to instantiate the agent algorithm. Select from one of the following:
* NONE - Where a user developed agent is to be used
* SB3 - Stable Baselines3
* RLLIB - Ray RLlib.
* **agent_identifier**
This identifies the agent to use for the session. Select from one of the following:
* A2C - Advantage Actor Critic
* PPO - Proximal Policy Optimization
* HARDCODED - A custom built deterministic agent
* RANDOM - A Stochastic random agent
* **random_red_agent** [bool]
Determines if the session should be run with a random red agent
* **action_type** [enum]
Determines whether a NODE, ACL, or ANY (combined NODE & ACL) action space format is adopted for the session
* **OBSERVATION_SPACE** [dict]
Allows for user to configure observation space by combining one or more observation components. List of available
components is in :py:mod:`primaite.environment.observations`.
The observation space config item should have a ``components`` key which is a list of components. Each component
config must have a ``name`` key, and can optionally have an ``options`` key. The ``options`` are passed to the
component while it is being initialised.
This example illustrates the correct format for the observation space config item
.. code-block:: yaml
observation_space:
components:
- name: NODE_LINK_TABLE
- name: NODE_STATUSES
- name: LINK_TRAFFIC_LEVELS
- name: ACCESS_CONTROL_LIST
options:
combine_service_traffic : False
quantisation_levels: 99
Currently available components are:
* :py:mod:`NODE_LINK_TABLE<primaite.environment.observations.NodeLinkTable>` this does not accept any additional options
* :py:mod:`NODE_STATUSES<primaite.environment.observations.NodeStatuses>`, this does not accept any additional options
* :py:mod:`ACCESS_CONTROL_LIST<primaite.environment.observations.AccessControlList>`, this does not accept additional options
* :py:mod:`LINK_TRAFFIC_LEVELS<primaite.environment.observations.LinkTrafficLevels>`, this accepts the following options:
* ``combine_service_traffic`` - whether to consider bandwidth use separately for each network protocol or combine them into a single bandwidth reading (boolean)
* ``quantisation_levels`` - how many discrete bandwidth usage levels to use for encoding. This can be an integer equal to or greater than 3.
The other configurable item is ``flatten`` which is false by default. When set to true, the observation space is flattened (turned into a 1-D vector). You should use this if your RL agent does not natively support observation space types like ``gym.Spaces.Tuple``.
* **num_train_episodes** [int]
This defines the number of episodes that the agent will train for.
* **num_train_steps** [int]
Determines the number of steps to run in each episode of the training session.
* **num_eval_episodes** [int]
This defines the number of episodes that the agent will be evaluated over.
* **num_eval_steps** [int]
Determines the number of steps to run in each episode of the evaluation session.
* **time_delay** [int]
The time delay (in milliseconds) to take between each step when running a GENERIC agent session
* **session_type** [text]
Type of session to be run (TRAINING, EVALUATION, or BOTH)
* **load_agent** [bool]
Determine whether to load an agent from file
* **agent_load_file** [text]
File path and file name of agent if you're loading one in
* **observation_space_high_value** [int]
The high value to use for values in the observation space. This is set to 1000000000 by default, and should not need changing in most cases
* **implicit_acl_rule** [str]
Determines which Explicit rule the ACL list has - two options are: DENY or ALLOW.
* **max_number_acl_rules** [int]
Sets a limit on how many ACL rules there can be in the ACL list throughout the training session.
**Reward-Based Config Values**
Rewards are calculated based on the difference between the current state and reference state (the 'should be' state) of the environment.
* **Generic [all_ok]** [float]
The score to give when the current situation (for a given component) is no different from that expected in the baseline (i.e. as though no blue or red agent actions had been undertaken)
* **Node Hardware State [off_should_be_on]** [float]
The score to give when the node should be on, but is off
* **Node Hardware State [off_should_be_resetting]** [float]
The score to give when the node should be resetting, but is off
* **Node Hardware State [on_should_be_off]** [float]
The score to give when the node should be off, but is on
* **Node Hardware State [on_should_be_resetting]** [float]
The score to give when the node should be resetting, but is on
* **Node Hardware State [resetting_should_be_on]** [float]
The score to give when the node should be on, but is resetting
* **Node Hardware State [resetting_should_be_off]** [float]
The score to give when the node should be off, but is resetting
* **Node Hardware State [resetting]** [float]
The score to give when the node is resetting
* **Node Operating System or Service State [good_should_be_patching]** [float]
The score to give when the state should be patching, but is good
* **Node Operating System or Service State [good_should_be_compromised]** [float]
The score to give when the state should be compromised, but is good
* **Node Operating System or Service State [good_should_be_overwhelmed]** [float]
The score to give when the state should be overwhelmed, but is good
* **Node Operating System or Service State [patching_should_be_good]** [float]
The score to give when the state should be good, but is patching
* **Node Operating System or Service State [patching_should_be_compromised]** [float]
The score to give when the state should be compromised, but is patching
* **Node Operating System or Service State [patching_should_be_overwhelmed]** [float]
The score to give when the state should be overwhelmed, but is patching
* **Node Operating System or Service State [patching]** [float]
The score to give when the state is patching
* **Node Operating System or Service State [compromised_should_be_good]** [float]
The score to give when the state should be good, but is compromised
* **Node Operating System or Service State [compromised_should_be_patching]** [float]
The score to give when the state should be patching, but is compromised
* **Node Operating System or Service State [compromised_should_be_overwhelmed]** [float]
The score to give when the state should be overwhelmed, but is compromised
* **Node Operating System or Service State [compromised]** [float]
The score to give when the state is compromised
* **Node Operating System or Service State [overwhelmed_should_be_good]** [float]
The score to give when the state should be good, but is overwhelmed
* **Node Operating System or Service State [overwhelmed_should_be_patching]** [float]
The score to give when the state should be patching, but is overwhelmed
* **Node Operating System or Service State [overwhelmed_should_be_compromised]** [float]
The score to give when the state should be compromised, but is overwhelmed
* **Node Operating System or Service State [overwhelmed]** [float]
The score to give when the state is overwhelmed
* **Node File System State [good_should_be_repairing]** [float]
The score to give when the state should be repairing, but is good
* **Node File System State [good_should_be_restoring]** [float]
The score to give when the state should be restoring, but is good
* **Node File System State [good_should_be_corrupt]** [float]
The score to give when the state should be corrupt, but is good
* **Node File System State [good_should_be_destroyed]** [float]
The score to give when the state should be destroyed, but is good
* **Node File System State [repairing_should_be_good]** [float]
The score to give when the state should be good, but is repairing
* **Node File System State [repairing_should_be_restoring]** [float]
The score to give when the state should be restoring, but is repairing
* **Node File System State [repairing_should_be_corrupt]** [float]
The score to give when the state should be corrupt, but is repairing
* **Node File System State [repairing_should_be_destroyed]** [float]
The score to give when the state should be destroyed, but is repairing
* **Node File System State [repairing]** [float]
The score to give when the state is repairing
* **Node File System State [restoring_should_be_good]** [float]
The score to give when the state should be good, but is restoring
* **Node File System State [restoring_should_be_repairing]** [float]
The score to give when the state should be repairing, but is restoring
* **Node File System State [restoring_should_be_corrupt]** [float]
The score to give when the state should be corrupt, but is restoring
* **Node File System State [restoring_should_be_destroyed]** [float]
The score to give when the state should be destroyed, but is restoring
* **Node File System State [restoring]** [float]
The score to give when the state is restoring
* **Node File System State [corrupt_should_be_good]** [float]
The score to give when the state should be good, but is corrupt
* **Node File System State [corrupt_should_be_repairing]** [float]
The score to give when the state should be repairing, but is corrupt
* **Node File System State [corrupt_should_be_restoring]** [float]
The score to give when the state should be restoring, but is corrupt
* **Node File System State [corrupt_should_be_destroyed]** [float]
The score to give when the state should be destroyed, but is corrupt
* **Node File System State [corrupt]** [float]
The score to give when the state is corrupt
* **Node File System State [destroyed_should_be_good]** [float]
The score to give when the state should be good, but is destroyed
* **Node File System State [destroyed_should_be_repairing]** [float]
The score to give when the state should be repairing, but is destroyed
* **Node File System State [destroyed_should_be_restoring]** [float]
The score to give when the state should be restoring, but is destroyed
* **Node File System State [destroyed_should_be_corrupt]** [float]
The score to give when the state should be corrupt, but is destroyed
* **Node File System State [destroyed]** [float]
The score to give when the state is destroyed
* **Node File System State [scanning]** [float]
The score to give when the state is scanning
* **IER Status [red_ier_running]** [float]
The score to give when a red agent IER is permitted to run
* **IER Status [green_ier_blocked]** [float]
The score to give when a green agent IER is prevented from running
**Patching / Reset Durations**
* **os_patching_duration** [int]
The number of steps to take when patching an Operating System
* **node_reset_duration** [int]
The number of steps to take when resetting a node's hardware state
* **service_patching_duration** [int]
The number of steps to take when patching a service
* **file_system_repairing_limit** [int]:
The number of steps to take when repairing the file system
* **file_system_restoring_limit** [int]
The number of steps to take when restoring the file system
* **file_system_scanning_limit** [int]
The number of steps to take when scanning the file system
* **deterministic** [bool]
Set to true if the agent evaluation should be deterministic. Default is ``False``
* **seed** [int]
Seed used in the randomisation in agent training. Default is ``None``
The Lay Down Config
*******************
The lay down config file consists of the following attributes:
* **itemType: STEPS** [int]
* **item_type: PORTS** [int]
Provides a list of ports modelled in this session
* **item_type: SERVICES** [freetext]
Provides a list of services modelled in this session
* **item_type: NODE**
Defines a node included in the system laydown being simulated. It should consist of the following attributes:
* **id** [int]: Unique ID for this YAML item
* **name** [freetext]: Human-readable name of the component
* **node_class** [enum]: Relates to the base type of the node. Can be SERVICE, ACTIVE or PASSIVE. PASSIVE nodes do not have an operating system or services. ACTIVE nodes have an operating system, but no services. SERVICE nodes have both an operating system and one or more services
* **node_type** [enum]: Relates to the component type. Can be one of CCTV, SWITCH, COMPUTER, LINK, MONITOR, PRINTER, LOP, RTU, ACTUATOR or SERVER
* **priority** [enum]: Provides a priority for each node. Can be one of P1, P2, P3, P4 or P5 (which P1 being the highest)
* **hardware_state** [enum]: The initial hardware state of the node. Can be one of ON, OFF or RESETTING
* **ip_address** [IP address]: The IP address of the component in format xxx.xxx.xxx.xxx
* **software_state** [enum]: The intial state of the node operating system. Can be GOOD, PATCHING or COMPROMISED
* **file_system_state** [enum]: The initial state of the node file system. Can be GOOD, CORRUPT, DESTROYED, REPAIRING or RESTORING
* **services**: For each service associated with the node:
* **name** [freetext]: Free-text name of the service, but must match one of the services defined for the system in the services list
* **port** [int]: Integer value of the port related to this service, but must match one of the ports defined for the system in the ports list
* **state** [enum]: The initial state of the service. Can be one of GOOD, PATCHING, COMPROMISED or OVERWHELMED
* **item_type: LINK**
Defines a link included in the system laydown being simulated. It should consist of the following attributes:
* **id** [int]: Unique ID for this YAML item
* **name** [freetext]: Human-readable name of the component
* **bandwidth** [int]: The bandwidth (in bits/s) of the link
* **source** [int]: The ID of the source node
* **destination** [int]: The ID of the destination node
* **item_type: GREEN_IER**
Defines a green agent Information Exchange Requirement (IER). It should consist of:
* **id** [int]: Unique ID for this YAML item
* **start_step** [int]: The start step (in the episode) for this IER to begin
* **end_step** [int]: The end step (in the episode) for this IER to finish
* **load** [int]: The load (in bits/s) for this IER to apply to links
* **protocol** [freetext]: The protocol to apply to the links. This must match a value in the services list
* **port** [int]: The port that the protocol is running on. This must match a value in the ports list
* **source** [int]: The ID of the source node
* **destination** [int]: The ID of the destination node
* **mission_criticality** [enum]: The mission criticality of this IER (with 5 being highest, 1 lowest)
* **item_type: RED_IER**
Defines a red agent Information Exchange Requirement (IER). It should consist of:
* **id** [int]: Unique ID for this YAML item
* **start_step** [int]: The start step (in the episode) for this IER to begin
* **end_step** [int]: The end step (in the episode) for this IER to finish
* **load** [int]: The load (in bits/s) for this IER to apply to links
* **protocol** [freetext]: The protocol to apply to the links. This must match a value in the services list
* **port** [int]: The port that the protocol is running on. This must match a value in the ports list
* **source** [int]: The ID of the source node
* **destination** [int]: The ID of the destination node
* **mission_criticality** [enum]: Not currently used. Default to 0
* **item_type: GREEN_POL**
Defines a green agent pattern-of-life instruction. It should consist of:
* **id** [int]: Unique ID for this YAML item
* **start_step** [int]: The start step (in the episode) for this PoL to begin
* **end_step** [int]: Not currently used. Default to same as start step
* **nodeId** [int]: The ID of the node to apply the PoL to
* **type** [enum]: The type of PoL to apply. Can be one of OPERATING, OS or SERVICE
* **protocol** [freetext]: The protocol to be affected if SERVICE type is chosen. Must match a value in the services list
* **state** [enuum]: The state to apply to the node (which represents the PoL change). Can be one of ON, OFF or RESETTING (for node state) or GOOD, PATCHING or COMPROMISED (for Software State) or GOOD, PATCHING, COMPROMISED or OVERWHELMED (for service state)
* **item_type: RED_POL**
Defines a red agent pattern-of-life instruction. It should consist of:
* **id** [int]: Unique ID for this YAML item
* **start_step** [int]: The start step (in the episode) for this PoL to begin
* **end_step** [int]: Not currently used. Default to same as start step
* **targetNodeId** [int]: The ID of the node to apply the PoL to
* **initiator** [enum]: What initiates the PoL. Can be DIRECT, IER or SERVICE
* **type** [enum]: The type of PoL to apply. Can be one of OPERATING, OS or SERVICE
* **protocol** [freetext]: The protocol to be affected if SERVICE type is chosen. Must match a value in the services list
* **state** [enum]: The state to apply to the node (which represents the PoL change). Can be one of ON, OFF or RESETTING (for node state) or GOOD, PATCHING or COMPROMISED (for Software State) or GOOD, PATCHING, COMPROMISED or OVERWHELMED (for service state) or GOOD, CORRUPT, DESTROYED, REPAIRING or RESTORING (for file system state)
* **sourceNodeId** [int] The ID of the source node containing the service to check (used for SERVICE initiator)
* **sourceNodeService** [freetext]: The service on the source node to check (used for SERVICE initiator). Must match a value in the services list for this node
* **sourceNodeServiceState** [enum]: The state of the source node service to check (used for SERVICE initiator). Can be one of GOOD, PATCHING, COMPROMISED or OVERWHELMED
* **item_type: ACL_RULE**
Defines an initial Access Control List (ACL) rule. It should consist of:
* **id** [int]: Unique ID for this YAML item
* **permission** [enum]: Defines either an allow or deny rule. Value must be either DENY or ALLOW
* **source** [IP address]: Defines the source IP address for the rule in xxx.xxx.xxx.xxx format
* **destination** [IP address]: Defines the destination IP address for the rule in xxx.xxx.xxx.xxx format
* **protocol** [freetext]: Defines the protocol for the rule. Must match a value in the services list
* **port** [int]: Defines the port for the rule. Must match a value in the ports list
* **position** [int]: Defines where to place the ACL rule in the list. Lower index or (higher up in the list) means they are checked first. Index starts at 0 (Python indexes).
PrimAITE allows for the configuration to be varied each episode. This is done by specifying a configuration folder instead of a single file. A full explanation is provided in the notebook `Using-Episode-Schedules.ipynb`. Please find the notebook in the user notebooks directory.

View File

@@ -0,0 +1,174 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
``agents``
==========
Agents can be scripted (deterministic and stochastic), or controlled by a reinforcement learning algorithm. Not to be confused with an RL agent, the term agent here is used to refer to an entity that sends requests to the simulated network. In this part of the config, each agent's action space, observation space, and reward function can be defined. All three are defined in a modular way.
``agents`` hierarchy
--------------------
.. code-block:: yaml
agents:
- ref: red_agent_example
...
- ref: blue_agent_example
...
- ref: green_agent_example
team: GREEN
type: ProbabilisticAgent
observation_space:
type: UC2GreenObservation
action_space:
action_list:
- type: DONOTHING
- type: NODE_APPLICATION_EXECUTE
options:
nodes:
- node_name: client_2
applications:
- application_name: WebBrowser
max_folders_per_node: 1
max_files_per_folder: 1
max_services_per_node: 1
max_applications_per_node: 1
reward_function:
reward_components:
- type: DUMMY
agent_settings:
start_settings:
start_step: 5
frequency: 4
variance: 3
flatten_obs: False
``ref``
-------
The reference to be used for the given agent.
``team``
--------
Specifies if the agent is malicious (``RED``), benign (``GREEN``), or defensive (``BLUE``). Currently this value is not used for anything other than for human readability in the configuration file.
``type``
--------
Specifies which class should be used for the agent. ``ProxyAgent`` is used for agents that receive instructions from an RL algorithm. Scripted agents like ``RedDatabaseCorruptingAgent`` and ``ProbabilisticAgent`` generate their own behaviour.
Available agent types:
- ``ProbabilisticAgent``
- ``ProxyAgent``
- ``RedDatabaseCorruptingAgent``
``observation_space``
---------------------
Defines the observation space of the agent.
``type``
^^^^^^^^
selects which python class from the :py:mod:`primaite.game.agent.observation` module is used for the overall observation structure.
``options``
^^^^^^^^^^^
Allows configuration of the chosen observation type. These are optional.
* ``num_services_per_node``, ``num_folders_per_node``, ``num_files_per_folder``, ``num_nics_per_node`` all define the shape of the observation space. The size and shape of the obs space must remain constant, but the number of files, folders, ACL rules, and other components can change within an episode. Therefore padding is performed and these options set the size of the obs space.
* ``nodes``: list of nodes that will be present in this agent's observation space. The ``node_ref`` relates to the human-readable unique reference defined later in the ``simulation`` part of the config. Each node can also be configured with services, and files that should be monitored.
* ``links``: list of links that will be present in this agent's observation space. The ``link_ref`` relates to the human-readable unique reference defined later in the ``simulation`` part of the config.
* ``acl``: configure how the agent reads the access control list on the router in the simulation. ``router_node_ref`` is for selecting which router's ACL table should be used. ``ip_list`` sets the encoding of ip addresses as integers within the observation space.
For more information see :py:mod:`primaite.game.agent.observations`
``action_space``
----------------
The action space is configured to be made up of individual action types. Once configured, the agent can select an action type and some optional action parameters at every step. For example: The ``NODE_SERVICE_SCAN`` action takes the parameters ``node_id`` and ``service_id``.
``action_list``
^^^^^^^^^^^^^^^
A list of action modules. The options are listed in the :py:mod:`primaite.game.agent.actions.ActionManager.act_class_identifiers` module.
``action_map``
^^^^^^^^^^^^^^
Restricts the possible combinations of action type / action parameter values to reduce the overall size of the action space. By default, every possible combination of actions and parameters will be assigned an integer for the agent's ``MultiDiscrete`` action space. Instead, the ``action_map`` allows you to list the actions corresponding to each integer in the ``MultiDiscrete`` space.
This is Optional.
``options``
^^^^^^^^^^^
Options that apply to all action components. These are optional.
* ``nodes``: list the nodes that the agent can act on, the order of this list defines the mapping between nodes and ``node_id`` integers.
* ``max_folders_per_node``, ``max_files_per_folder``, ``max_services_per_node``, ``max_nics_per_node``, ``max_acl_rules`` all are used to define the size of the action space.
For more information see :py:mod:`primaite.game.agent.actions`
``reward_function``
-------------------
Similar to action space, this is defined as a list of components from the :py:mod:`primaite.game.agent.rewards` module.
``reward_components``
^^^^^^^^^^^^^^^^^^^^^
A list of reward types from :py:mod:`primaite.game.agent.rewards.RewardFunction.rew_class_identifiers`
e.g.
.. code-block:: yaml
reward_components:
- type: DUMMY
- type: DATABASE_FILE_INTEGRITY
``agent_settings``
------------------
Settings passed to the agent during initialisation. Determines how the agent will behave during training.
e.g.
.. code-block:: yaml
agent_settings:
start_settings:
start_step: 25
frequency: 20
variance: 5
``start_step``
^^^^^^^^^^^^^^
Optional. Default value is ``5``.
The timestep where the agent begins performing actions.
``frequency``
^^^^^^^^^^^^^
Optional. Default value is ``5``.
The number of timesteps the agent will wait before performing another action.
``variance``
^^^^^^^^^^^^
Optional. Default value is ``0``.
The amount of timesteps that the frequency can randomly change.
``flatten_obs``
---------------
If ``True``, gymnasium flattening will be performed on the observation space before sending to the agent. Set this to ``True`` if your agent does not support nested observation spaces.

View File

@@ -0,0 +1,56 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
``game``
========
This section defines high-level settings that apply across the game, currently it's used to help shape the action and observation spaces by restricting which ports and internet protocols should be considered. Here, users can also set the maximum number of steps in an episode.
``game`` hierarchy
------------------
.. code-block:: yaml
game:
max_episode_length: 256
ports:
- ARP
- DNS
- HTTP
- POSTGRES_SERVER
protocols:
- ICMP
- TCP
- UDP
thresholds:
nmne:
high: 10
medium: 5
low: 0
``max_episode_length``
----------------------
Optional. Default value is ``256``.
The maximum number of episodes a Reinforcement Learning agent(s) can be trained for.
``ports``
---------
A list of ports that the Reinforcement Learning agent(s) are able to see in the observation space.
See :ref:`List of Ports <List of Ports>` for a list of ports.
``protocols``
-------------
A list of protocols that the Reinforcement Learning agent(s) are able to see in the observation space.
See :ref:`List of IPProtocols <List of IPProtocols>` for a list of protocols.
``thresholds``
--------------
These are used to determine the thresholds of high, medium and low categories for counted observation occurrences.

View File

@@ -0,0 +1,90 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
``io_settings``
===============
This section configures how PrimAITE saves data during simulation and training.
``io_settings`` hierarchy
-------------------------
.. code-block:: yaml
io_settings:
# save_logs: True
save_agent_actions: True
save_step_metadata: False
save_pcap_logs: False
save_sys_logs: False
write_sys_log_to_terminal: False
sys_log_level: WARNING
``save_logs``
-------------
*currently unused*.
``save_agent_actions``
----------------------
Optional. Default value is ``True``.
If ``True``, this will create a JSON file each episode detailing every agent's action in each step of that episode, formatted according to the CAOS format. This includes scripted, RL, and red agents.
``save_step_metadata``
----------------------
Optional. Default value is ``False``.
If ``True``, The RL agent(s) actions, environment states and other data will be saved at every single step.
``save_pcap_logs``
------------------
Optional. Default value is ``False``.
If ``True``, then the pcap files which contain all network traffic during the simulation will be saved.
``save_sys_logs``
-----------------
Optional. Default value is ``False``.
If ``True``, then the log files which contain all node actions during the simulation will be saved.
``write_sys_log_to_terminal``
-----------------------------
Optional. Default value is ``False``.
If ``True``, PrimAITE will print sys log to the terminal.
``sys_log_level``
-------------
Optional. Default value is ``WARNING``.
The level of logging that should be visible in the sys logs or the logs output to the terminal.
``save_sys_logs`` or ``write_sys_log_to_terminal`` has to be set to ``True`` for this setting to be used.
Available options are:
- ``DEBUG``: Debug level items and the items below
- ``INFO``: Info level items and the items below
- ``WARNING``: Warning level items and the items below
- ``ERROR``: Error level items and the items below
- ``CRITICAL``: Only critical level logs
See also |logging_levels|
.. |logging_levels| raw:: html
<a href="https://docs.python.org/3/library/logging.html#logging-levels" target="blank">Python logging levels</a>

View File

@@ -0,0 +1,103 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
``simulation``
==============
In this section the network layout is defined. This part of the config follows a hierarchical structure. Almost every component defines a ``ref`` field which acts as a human-readable unique identifier, used by other parts of the config, such as agents.
At the top level of the network are ``nodes`` and ``links``.
e.g.
.. code-block:: yaml
simulation:
network:
nodes:
...
links:
...
``nodes``
---------
This is where the list of nodes are defined. Some items will differ according to the node type, however, there will be common items such as a node's reference (which is used by the agent), the node's ``type`` and ``hostname``
To see the configuration for these nodes, refer to the following:
.. toctree::
:maxdepth: 1
:glob:
simulation/nodes/computer
simulation/nodes/firewall
simulation/nodes/router
simulation/nodes/server
simulation/nodes/switch
simulation/nodes/wireless_router
simulation/nodes/network_examples
``links``
---------
This is where the links between the nodes are formed.
e.g.
In order to recreate the network below, we will need to create 2 links:
- a link from computer_1 to the switch
- a link from computer_2 to the switch
.. image:: ../../_static/switched_p2p_network.png
:width: 500
:align: center
this results in:
.. code-block:: yaml
links:
- endpoint_a_hostname: computer_1
endpoint_a_port: 1 # port 1 on computer_1
endpoint_b_hostname: switch
endpoint_b_port: 1 # port 1 on switch
bandwidth: 100
- endpoint_a_hostname: computer_2
endpoint_a_port: 1 # port 1 on computer_2
endpoint_b_hostname: switch
endpoint_b_port: 2 # port 2 on switch
bandwidth: 100
``ref``
^^^^^^^
The human readable name for the link. Not used in code, however is useful for a human to understand what the link is for.
``endpoint_a_hostname``
^^^^^^^^^^^^^^^^^^^^^^^
The ``hostname`` of the node which must be connected.
``endpoint_a_port``
^^^^^^^^^^^^^^^^^^^
The port on ``endpoint_a_hostname`` which is to be connected to ``endpoint_b_port``.
This accepts an integer value e.g. if port 1 is to be connected, the configuration should be ``endpoint_a_port: 1``
``endpoint_b_hostname``
^^^^^^^^^^^^^^^^^^^^^^^
The ``hostname`` of the node which must be connected.
``endpoint_b_port``
^^^^^^^^^^^^^^^^^^^
The port on ``endpoint_b_hostname`` which is to be connected to ``endpoint_a_port``.
This accepts an integer value e.g. if port 1 is to be connected, the configuration should be ``endpoint_b_port: 1``
``bandwidth``
This is an integer value specifying the allowed bandwidth across the connection. Units are in Mbps.

View File

@@ -0,0 +1,35 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _Node Attributes:
Common Attributes
#################
Node Attributes
===============
Attributes that are shared by all nodes.
.. include:: common_node_attributes.rst
.. _Network Node Attributes:
Network Node Attributes
=======================
Attributes that are shared by nodes that inherit from :py:mod:`primaite.simulator.network.hardware.nodes.network.network_node.NetworkNode`
.. include:: common_host_node_attributes.rst
.. _Host Node Attributes:
Host Node Attributes
====================
Attributes that are shared by nodes that inherit from :py:mod:`primaite.simulator.network.hardware.nodes.host.host_node.HostNode`
.. include:: common_host_node_attributes.rst
.. |NODE| replace:: node

View File

@@ -0,0 +1,26 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _common_host_node_attributes:
``ip_address``
--------------
The IP address of the |NODE| in the network.
``subnet_mask``
---------------
Optional. Default value is ``255.255.255.0``.
The subnet mask for the |NODE| to use.
``default_gateway``
-------------------
The IP address that the |NODE| will use as the default gateway. Typically, this is the IP address of the closest router that the |NODE| is connected to.
.. include:: ../software/applications.rst
.. include:: ../software/services.rst

View File

@@ -0,0 +1,51 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _common_network_node_attributes:
``routes``
----------
A list of routes which tells the |NODE| where to forward the packet to depending on the target IP address.
e.g.
.. code-block:: yaml
nodes:
- ref: node
...
routes:
- address: 192.168.0.10
subnet_mask: 255.255.255.0
next_hop_ip_address: 192.168.1.1
metric: 0
``address``
"""""""""""
The target IP address for the route. If the packet destination IP address matches this, the |NODE| will route the packet according to the ``next_hop_ip_address``.
This must be a valid octet i.e. in the range of ``0.0.0.0`` and ``255.255.255.255``.
``subnet_mask``
"""""""""""""""
Optional. Default value is ``255.255.255.0``.
The subnet mask setting for the route.
``next_hop_ip_address``
"""""""""""""""""""""""
The IP address of the next hop IP address that the packet will follow if the address matches the packet's destination IP address.
This must be a valid octet i.e. in the range of ``0.0.0.0`` and ``255.255.255.255``.
``metric``
""""""""""
Optional. Default value is ``0``. This value accepts floats.
The cost or distance of a route. The higher the value, the more cost or distance is attributed to the route.

View File

@@ -0,0 +1,55 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _common_node_attributes:
``ref``
-------
Human readable name used as reference for the |NODE|. Not used in code.
``hostname``
------------
The hostname of the |NODE|. This will be used to reference the |NODE|.
``operating_state``
-------------------
The initial operating state of the node.
Optional. Default value is ``ON``.
Options available are:
- ``ON``
- ``OFF``
- ``BOOTING``
- ``SHUTTING_DOWN``
Note that YAML may assume non quoted ``ON`` and ``OFF`` as ``True`` and ``False`` respectively. To prevent this, use ``"ON"`` or ``"OFF"``
See :py:mod:`primaite.simulator.network.hardware.node_operating_state.NodeOperatingState`
``dns_server``
--------------
Optional. Default value is ``None``.
The IP address of the node which holds an instance of the :ref:`DNSServer`. Some applications may use a domain name e.g. the :ref:`WebBrowser`
``start_up_duration``
---------------------
Optional. Default value is ``3``.
The number of time steps required to occur in order for the node to cycle from ``OFF`` to ``BOOTING_UP`` and then finally ``ON``.
``shut_down_duration``
----------------------
Optional. Default value is ``3``.
The number of time steps required to occur in order for the node to cycle from ``ON`` to ``SHUTTING_DOWN`` and then finally ``OFF``.

View File

@@ -0,0 +1,18 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
``type``
--------
The type of node to add.
Available options are:
- ``computer``
- ``firewall``
- ``router``
- ``server``
- ``switch``
To create a |NODE|, type must be |NODE_TYPE|.

View File

@@ -0,0 +1,41 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _computer_configuration:
``computer``
============
A basic representation of a computer within the simulation.
See :py:mod:`primaite.simulator.network.hardware.nodes.host.computer.Computer`
example computer
----------------
.. code-block:: yaml
simulation:
network:
nodes:
- ref: client_1
hostname: client_1
type: computer
ip_address: 192.168.0.10
subnet_mask: 255.255.255.0
default_gateway: 192.168.0.1
dns_server: 192.168.1.10
applications:
...
services:
...
.. include:: common/common_node_attributes.rst
.. include:: common/node_type_list.rst
.. include:: common/common_host_node_attributes.rst
.. |NODE| replace:: computer
.. |NODE_TYPE| replace:: ``computer``

View File

@@ -0,0 +1,300 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _firewall_configuration:
``firewall``
============
A basic representation of a network firewall within the simulation.
The firewall is similar to how :ref:`Router <router_configuration>` works, with the difference being how firewall has specific ACL rules for inbound and outbound traffic as well as firewall being limited to 3 ports.
See :py:mod:`primaite.simulator.network.hardware.nodes.network.firewall.Firewall`
example firewall
----------------
.. code-block:: yaml
simulation:
network:
nodes:
- ref: firewall
hostname: firewall
type: firewall
start_up_duration: 0
shut_down_duration: 0
ports:
external_port: # port 1
ip_address: 192.168.20.1
subnet_mask: 255.255.255.0
internal_port: # port 2
ip_address: 192.168.1.2
subnet_mask: 255.255.255.0
dmz_port: # port 3
ip_address: 192.168.10.1
subnet_mask: 255.255.255.0
acl:
internal_inbound_acl:
...
internal_outbound_acl:
...
dmz_inbound_acl:
...
dmz_outbound_acl:
...
external_inbound_acl:
...
external_outbound_acl:
...
routes:
...
.. include:: common/common_node_attributes.rst
.. include:: common/node_type_list.rst
``ports``
---------
The firewall node only has 3 ports. These specifically are:
- ``external_port`` (port 1)
- ``internal_port`` (port 2)
- ``dmz_port`` (port 3) (can be optional)
The ports should be defined with an ip address and subnet mask e.g.
.. code-block:: yaml
nodes:
- ref: firewall
...
ports:
external_port: # port 1
ip_address: 192.168.20.1
subnet_mask: 255.255.255.0
internal_port: # port 2
ip_address: 192.168.1.2
subnet_mask: 255.255.255.0
dmz_port: # port 3
ip_address: 192.168.10.1
subnet_mask: 255.255.255.0
``ip_address``
""""""""""""""
The IP address for the given port. This must be a valid octet i.e. in the range of ``0.0.0.0`` and ``255.255.255.255``.
``subnet_mask``
"""""""""""""""
Optional. Default value is ``255.255.255.0``.
The subnet mask setting for the port.
``acl``
-------
There are 6 ACLs that can be defined for a firewall
- ``internal_inbound_acl`` for traffic going towards the internal network
- ``internal_outbound_acl`` for traffic coming from the internal network
- ``dmz_inbound_acl`` for traffic going towards the dmz network
- ``dmz_outbound_acl`` for traffic coming from the dmz network
- ``external_inbound_acl`` for traffic coming from the external network
- ``external_outbound_acl`` for traffic going towards the external network
.. image:: ../../../../_static/firewall_acl.png
:width: 500
:align: center
By default, ``external_inbound_acl`` and ``external_outbound_acl`` will permit any traffic through.
``internal_inbound_acl``, ``internal_outbound_acl``, ``dmz_inbound_acl`` and ``dmz_outbound_acl`` will deny any traffic by default, so must be configured to allow defined ``src_port`` and ``dst_port`` or ``protocol``.
See :py:mod:`primaite.simulator.network.hardware.nodes.network.router.AccessControlList`
See :ref:`List of Ports <List of Ports>` for a list of ports.
``internal_inbound_acl``
""""""""""""""""""""""""
ACL rules for packets that have a destination IP address in what is considered the internal network.
example:
.. code-block:: yaml
nodes:
- ref: firewall
...
acl:
internal_inbound_acl:
21: # position 21 on ACL list
action: PERMIT # allow packets that
src_port: POSTGRES_SERVER # are emitted from the POSTGRES_SERVER port
dst_port: POSTGRES_SERVER # are going towards an POSTGRES_SERVER port
22: # position 22 on ACL list
action: PERMIT # allow packets that
src_port: ARP # are emitted from the ARP port
dst_port: ARP # are going towards an ARP port
23: # position 23 on ACL list
action: PERMIT # allow packets that
protocol: ICMP # are ICMP
``internal_outbound_acl``
"""""""""""""""""""""""""
ACL rules for packets that have a source IP address in what is considered the internal network and is going towards the DMZ network or the external network.
example:
.. code-block:: yaml
nodes:
- ref: firewall
...
acl:
internal_outbound_acl:
21: # position 21 on ACL list
action: PERMIT # allow packets that
src_port: POSTGRES_SERVER # are emitted from the POSTGRES_SERVER port
dst_port: POSTGRES_SERVER # are going towards an POSTGRES_SERVER port
22: # position 22 on ACL list
action: PERMIT # allow packets that
src_port: ARP # are emitted from the ARP port
dst_port: ARP # are going towards an ARP port
23: # position 23 on ACL list
action: PERMIT # allow packets that
protocol: ICMP # are ICMP
``dmz_inbound_acl``
"""""""""""""""""""
ACL rules for packets that have a destination IP address in what is considered the DMZ network.
example:
.. code-block:: yaml
nodes:
- ref: firewall
...
acl:
dmz_inbound_acl:
19: # position 19 on ACL list
action: PERMIT # allow packets that
src_port: POSTGRES_SERVER # are emitted from the POSTGRES_SERVER port
dst_port: POSTGRES_SERVER # are going towards an POSTGRES_SERVER port
20: # position 20 on ACL list
action: PERMIT # allow packets that
src_port: HTTP # are emitted from the HTTP port
dst_port: HTTP # are going towards an HTTP port
21: # position 21 on ACL list
action: PERMIT # allow packets that
src_port: HTTPS # are emitted from the HTTPS port
dst_port: HTTPS # are going towards an HTTPS port
22: # position 22 on ACL list
action: PERMIT # allow packets that
src_port: ARP # are emitted from the ARP port
dst_port: ARP # are going towards an ARP port
23: # position 23 on ACL list
action: PERMIT # allow packets that
protocol: ICMP # are ICMP
``dmz_outbound_acl``
""""""""""""""""""""
ACL rules for packets that have a source IP address in what is considered the DMZ network and is going towards the internal network or the external network.
example:
.. code-block:: yaml
nodes:
- ref: firewall
...
acl:
dmz_outbound_acl:
19: # position 19 on ACL list
action: PERMIT # allow packets that
src_port: POSTGRES_SERVER # are emitted from the POSTGRES_SERVER port
dst_port: POSTGRES_SERVER # are going towards an POSTGRES_SERVER port
20: # position 20 on ACL list
action: PERMIT # allow packets that
src_port: HTTP # are emitted from the HTTP port
dst_port: HTTP # are going towards an HTTP port
21: # position 21 on ACL list
action: PERMIT # allow packets that
src_port: HTTPS # are emitted from the HTTPS port
dst_port: HTTPS # are going towards an HTTPS port
22: # position 22 on ACL list
action: PERMIT # allow packets that
src_port: ARP # are emitted from the ARP port
dst_port: ARP # are going towards an ARP port
23: # position 23 on ACL list
action: PERMIT # allow packets that
protocol: ICMP # are ICMP
``external_inbound_acl``
""""""""""""""""""""""""
Optional. By default, this will allow any traffic through.
ACL rules for packets that have a destination IP address in what is considered the external network.
example:
.. code-block:: yaml
nodes:
- ref: firewall
...
acl:
external_inbound_acl:
21: # position 19 on ACL list
action: DENY # deny packets that
src_port: POSTGRES_SERVER # are emitted from the POSTGRES_SERVER port
dst_port: POSTGRES_SERVER # are going towards an POSTGRES_SERVER port
22: # position 22 on ACL list
action: PERMIT # allow packets that
src_port: ARP # are emitted from the ARP port
dst_port: ARP # are going towards an ARP port
23: # position 23 on ACL list
action: PERMIT # allow packets that
protocol: ICMP # are ICMP
``external_outbound_acl``
"""""""""""""""""""""""""
Optional. By default, this will allow any traffic through.
ACL rules for packets that have a source IP address in what is considered the external network and is going towards the DMZ network or the internal network.
example:
.. code-block:: yaml
nodes:
- ref: firewall
...
acl:
external_outbound_acl:
22: # position 22 on ACL list
action: PERMIT # allow packets that
src_port: ARP # are emitted from the ARP port
dst_port: ARP # are going towards an ARP port
23: # position 23 on ACL list
action: PERMIT # allow packets that
protocol: ICMP # are ICMP
.. include:: common/common_network_node_attributes.rst
.. |NODE| replace:: firewall
.. |NODE_TYPE| replace:: ``firewall``

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,127 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _router_configuration:
``router``
==========
A basic representation of a network router within the simulation.
See :py:mod:`primaite.simulator.network.hardware.nodes.network.router.Router`
example router
--------------
.. code-block:: yaml
simulation:
network:
nodes:
- ref: router_1
hostname: router_1
type: router
num_ports: 5
ports:
...
acl:
...
.. include:: common/common_node_attributes.rst
.. include:: common/node_type_list.rst
``num_ports``
-------------
Optional. Default value is ``5``.
The number of ports the router will have.
``ports``
---------
Sets up the router's ports with an IP address and a subnet mask.
Example of setting ports for a router with 2 ports:
.. code-block:: yaml
nodes:
- ref: router_1
...
ports:
1:
ip_address: 192.168.1.1
subnet_mask: 255.255.255.0
2:
ip_address: 192.168.10.1
subnet_mask: 255.255.255.0
``ip_address``
""""""""""""""
The IP address for the given port. This must be a valid octet i.e. in the range of ``0.0.0.0`` and ``255.255.255.255``.
``subnet_mask``
"""""""""""""""
Optional. Default value is ``255.255.255.0``.
The subnet mask setting for the port.
``acl``
-------
Sets up the ACL rules for the router.
e.g.
.. code-block:: yaml
nodes:
- ref: router_1
...
acl:
1:
action: PERMIT
src_port: ARP
dst_port: ARP
2:
action: PERMIT
protocol: ICMP
See :py:mod:`primaite.simulator.network.hardware.nodes.network.router.AccessControlList`
See :ref:`List of Ports <List of Ports>` for a list of ports.
``action``
""""""""""
Available options are
- ``PERMIT`` : Allows the specified ``protocol`` or ``src_port`` and ``dst_port`` pairs
- ``DENY`` : Blocks the specified ``protocol`` or ``src_port`` and ``dst_port`` pairs
``src_port``
""""""""""""
Is used alongside ``dst_port``. Specifies the port where a packet originates. Used by the ACL Rule to determine if a packet with a specific source port is allowed to pass through the network node.
``dst_port``
""""""""""""
Is used alongside ``src_port``. Specifies the port where a packet is destined to arrive. Used by the ACL Rule to determine if a packet with a specific destination port is allowed to pass through the network node.
``protocol``
""""""""""""
Specifies which protocols are allowed by the ACL Rule to pass through the network node.
See :ref:`List of IPProtocols <List of IPProtocols>` for a list of protocols.
.. include:: common/common_network_node_attributes.rst
.. |NODE| replace:: router
.. |NODE_TYPE| replace:: ``router``

View File

@@ -0,0 +1,41 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _server_configuration:
``server``
==========
A basic representation of a server within the simulation.
See :py:mod:`primaite.simulator.network.hardware.nodes.host.server.Server`
example server
--------------
.. code-block:: yaml
simulation:
network:
nodes:
- ref: server_1
hostname: server_1
type: server
ip_address: 192.168.10.10
subnet_mask: 255.255.255.0
default_gateway: 192.168.10.1
dns_server: 192.168.1.10
applications:
...
services:
...
.. include:: common/common_node_attributes.rst
.. include:: common/node_type_list.rst
.. include:: common/common_host_node_attributes.rst
.. |NODE| replace:: server
.. |NODE_TYPE| replace:: ``server``

View File

@@ -0,0 +1,39 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _switch_configuration:
``switch``
==========
A basic representation of a network switch within the simulation.
See :py:mod:`primaite.simulator.network.hardware.nodes.network.switch.Switch`
example switch
--------------
.. code-block:: yaml
simulation:
network:
nodes:
- ref: switch_1
hostname: switch_1
type: switch
num_ports: 8
.. include:: common/common_node_attributes.rst
.. include:: common/node_type_list.rst
``num_ports``
-------------
Optional. Default value is ``8``.
The number of ports the switch will have.
.. |NODE| replace:: switch
.. |NODE_TYPE| replace:: ``switch``

View File

@@ -0,0 +1,25 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
``applications``
----------------
List of available applications that can be installed on a |NODE| can be found in :ref:`List of Applications <List of Applications>`
application in configuration
""""""""""""""""""""""""""""
Applications takes a list of applications as shown in the example below.
.. code-block:: yaml
- ref: client_1
hostname: client_1
type: computer
...
applications:
- ref: example_application
type: example_application_type
options:
# this section is different for each application

View File

@@ -0,0 +1,25 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
``services``
------------
List of available services that can be installed on a |NODE| can be found in :ref:`List of Services <List of Services>`
services in configuration
"""""""""""""""""""""""""
Services takes a list of services as shown in the example below.
.. code-block:: yaml
- ref: client_1
hostname: client_1
type: computer
...
applications:
- ref: example_service
type: example_service_type
options:
# this section is different for each service

View File

@@ -1,142 +0,0 @@
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
Custom Agents
=============
Integrating a user defined blue agent
*************************************
.. note::
If you are planning to implement custom RL agents into PrimAITE, you must use the project as a repository. If you install PrimAITE as a python package from wheel, custom agents are not supported.
PrimAITE has integration with Ray RLLib and StableBaselines3 agents. All agents interface with PrimAITE through an :py:class:`primaite.agents.agent.AgentSessionABC<Agent Session>` which provides Input/Output of agent savefiles, as well as capturing and plotting performance metrics during training and evaluation. If you wish to integrate a custom blue agent, it is recommended to create a subclass of the :py:class:`primaite.agents.agent.AgentSessionABC` and implement the ``__init__()``, ``_setup()``, ``_save_checkpoint()``, ``learn()``, ``evaluate()``, ``_get_latest_checkpoint``, ``load()``, and ``save()`` methods.
Below is a barebones example of a custom agent implementation:
.. code:: python
# src/primaite/agents/my_custom_agent.py
from primaite.agents.agent import AgentSessionABC
from primaite.common.enums import AgentFramework, AgentIdentifier
class CustomAgent(AgentSessionABC):
def __init__(self, training_config_path, lay_down_config_path):
super().__init__(training_config_path, lay_down_config_path)
assert self._training_config.agent_framework == AgentFramework.CUSTOM
assert self._training_config.agent_identifier == AgentIdentifier.MY_AGENT
self._setup()
def _setup(self):
super()._setup()
self._env = Primaite(
training_config_path=self._training_config_path,
lay_down_config_path=self._lay_down_config_path,
session_path=self.session_path,
timestamp_str=self.timestamp_str,
)
self._agent = ... # your code to setup agent
def _save_checkpoint(self):
checkpoint_num = self._training_config.checkpoint_every_n_episodes
episode_count = self._env.episode_count
save_checkpoint = False
if checkpoint_num:
save_checkpoint = episode_count % checkpoint_num == 0
# saves checkpoint if the episode count is not 0 and save_checkpoint flag was set to true
if episode_count and save_checkpoint:
...
# your code to save checkpoint goes here.
# The path should start with self.checkpoints_path and include the episode number.
def learn(self):
...
# call your agent's learning function here.
super().learn() # this will finalise learning and output session metadata
self.save()
def evaluate(self):
...
# call your agent's evaluation function here.
self._env.close()
super().evaluate()
def _get_latest_checkpoint(self):
...
# Load an agent from file.
@classmethod
def load(cls, path):
...
# Create a CustomAgent object which loads model weights from file.
def save(self):
...
# Call your agent's function that saves it to a file
You will also need to modify :py:class:`primaite.primaite_session.PrimaiteSession<PrimaiteSession>` and :py:mod:`primaite.common.enums` to capture your new agent identifiers.
.. code-block:: python
:emphasize-lines: 17, 18
# src/primaite/common/enums.py
class AgentIdentifier(Enum):
"""The Red Agent algo/class."""
A2C = 1
"Advantage Actor Critic"
PPO = 2
"Proximal Policy Optimization"
HARDCODED = 3
"The Hardcoded agents"
DO_NOTHING = 4
"The DoNothing agents"
RANDOM = 5
"The RandomAgent"
DUMMY = 6
"The DummyAgent"
CUSTOM_AGENT = 7
"Your custom agent"
.. code-block:: python
:emphasize-lines: 3, 11, 12
# src/primaite_session.py
from primaite.agents.my_custom_agent import CustomAgent
# ...
def setup(self):
"""Performs the session setup."""
if self._training_config.agent_framework == AgentFramework.CUSTOM:
_LOGGER.debug(f"PrimaiteSession Setup: Agent Framework = {AgentFramework.CUSTOM}")
if self._training_config.agent_identifier == AgentIdentifier.CUSTOM_AGENT:
self._agent_session = CustomAgent(self._training_config_path, self._lay_down_config_path)
if self._training_config.agent_identifier == AgentIdentifier.HARDCODED:
_LOGGER.debug(f"PrimaiteSession Setup: Agent Identifier =" f" {AgentIdentifier.HARDCODED}")
if self._training_config.action_type == ActionType.NODE:
# Deterministic Hardcoded Agent with Node Action Space
self._agent_session = HardCodedNodeAgent(self._training_config_path, self._lay_down_config_path)
Finally, specify your agent in your training config.
.. code-block:: yaml
# ~/primaite/2.0.0/config/path/to/your/config_main.yaml
# Training Config File
agent_framework: CUSTOM
agent_identifier: CUSTOM_AGENT
random_red_agent: False
# ...
Now you can :ref:`run a primaite session<run a primaite session>` with your custom agent by passing in the custom ``config_main``.

View File

@@ -0,0 +1,8 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
Customising Agents
******************
For an example of how to customise red agent behaviour in the Data Manipulation scenario, please refer to the notebook ``Data-Manipulation-Customising-Red-Agent.ipynb``.

View File

@@ -1,10 +1,12 @@
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. role:: raw-html(raw)
:format: html
.. _Dependencies:
Dependencies
============

View File

@@ -0,0 +1,210 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _Developer Tools:
Developer Tools
***************
PrimAITE includes developer CLI tools that are intended to be used by developers.
dev-mode
========
The dev-mode contains configuration which override any of the config files during runtime.
This is intended to make debugging easier by removing the need to find the relevant configuration file/settings.
Enabling dev-mode
-----------------
The PrimAITE dev-mode can be enabled via the use of
.. code-block::
primaite dev-mode enable
Disabling dev-mode
------------------
The PrimAITE dev-mode can be disabled via the use of
.. code-block::
primaite dev-mode disable
Show current mode
-----------------
To show if the dev-mode is enabled or not, use
The PrimAITE dev-mode can be disabled via the use of
.. code-block::
primaite dev-mode show
dev-mode configuration
======================
The following configures some specific items that the dev-mode overrides, if enabled.
`--sys-log-level` or `-level`
----------------------------
The level of system logs can be overridden by dev-mode.
By default, this is set to DEBUG
The available options are [DEBUG|INFO|WARNING|ERROR|CRITICAL]
.. code-block::
primaite dev-mode config -level INFO
or
.. code-block::
primaite dev-mode config --sys-log-level INFO
`--output-sys-logs` or `-sys`
-----------------------------
The outputting of system logs can be overridden by dev-mode.
By default, this is set to False
Enabling system logs
""""""""""""""""""""
To enable outputting of system logs
.. code-block::
primaite dev-mode config --output-sys-logs
or
.. code-block::
primaite dev-mode config -sys
Disabling system logs
"""""""""""""""""""""
To disable outputting of system logs
.. code-block::
primaite dev-mode config --no-sys-logs
or
.. code-block::
primaite dev-mode config -nsys
`--output-pcap-logs` or `-pcap`
-------------------------------
The outputting of packet capture logs can be overridden by dev-mode.
By default, this is set to False
Enabling PCAP logs
""""""""""""""""""
To enable outputting of packet capture logs
.. code-block::
primaite dev-mode config --output-pcap-logs
or
.. code-block::
primaite dev-mode config -pcap
Disabling PCAP logs
"""""""""""""""""""
To disable outputting of packet capture logs
.. code-block::
primaite dev-mode config --no-pcap-logs
or
.. code-block::
primaite dev-mode config -npcap
`--output-to-terminal` or `-t`
------------------------------
The outputting of system logs to the terminal can be overridden by dev-mode.
By default, this is set to False
Enabling system log output to terminal
""""""""""""""""""""""""""""""""""""""
To enable outputting of system logs to terminal
.. code-block::
primaite dev-mode config --output-to-terminal
or
.. code-block::
primaite dev-mode config -t
Disabling system log output to terminal
"""""""""""""""""""""""""""""""""""""""
To disable outputting of system logs to terminal
.. code-block::
primaite dev-mode config --no-terminal
or
.. code-block::
primaite dev-mode config -nt
path
----
PrimAITE dev-mode can override where sessions are output.
By default, PrimAITE will output the sessions in USER_HOME/primaite/sessions
With dev-mode enabled, by default, this will be changed to PRIMAITE_REPOSITORY_ROOT/sessions
However, providing a path will let dev-mode output sessions to the given path e.g.
.. code-block:: bash
:caption: Unix
primaite dev-mode config path ~/output/path
.. code-block:: powershell
:caption: Windows (Powershell)
primaite dev-mode config path ~\output\path
default path
""""""""""""
To reset the path to use the PRIMAITE_REPOSITORY_ROOT/sessions, run the command
.. code-block::
primaite dev-mode config path --default

View File

@@ -0,0 +1,14 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
RL Environments
***************
RL environments are the objects that directly interface with RL libraries such as Stable-Baselines3 and Ray RLLib. The PrimAITE simulation is exposed via three different environment APIs:
* Gymnasium API - this is the standard interface that works with many RL libraries like SB3, Ray, Tianshou, etc. ``PrimaiteGymEnv`` adheres to the `Official Gymnasium documentation <https://gymnasium.farama.org/api/env/>`_.
* Ray Single agent API - For training a single Ray RLLib agent
* Ray MARL API - For training multi-agent systems with Ray RLLib. ``PrimaiteRayMARLEnv`` adheres to the `Official Ray documentation <https://docs.ray.io/en/latest/rllib/package_ref/env/multi_agent_env.html>`_.
There are Jupyter notebooks which demonstrate integration with each of these three environments. They are located in ``~/primaite/<VERSION>/notebooks/example_notebooks``.

View File

@@ -0,0 +1,82 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
Example Jupyter Notebooks
=========================
Executed Notebooks
------------------
There are a few example notebooks included which help with the understanding of PrimAITE's capabilities.
The PrimAITE documentation includes a pre executed example of notebooks. See :ref:`Executed Notebooks`.
In order to run the notebooks interactively, :ref:`install PrimAITE <getting-started>` and follow these steps:
Running Jupyter Notebooks
-------------------------
1. Navigate to the PrimAITE directory
.. code-block:: bash
:caption: Unix
cd ~/primaite/{VERSION}
.. code-block:: powershell
:caption: Windows (Powershell)
cd ~\primaite\{VERSION}
2. Run jupyter notebook (the python environment to which you installed PrimAITE must be active)
.. code-block:: bash
:caption: Unix
jupyter notebook
.. code-block:: powershell
:caption: Windows (Powershell)
jupyter notebook
3. Opening the jupyter webpage (optional)
The default web browser may automatically open the webpage. However, if that is not the case, click the link shown in your command prompt output. It should look like this: ``http://localhost:8888/?token=0123456798abc0123456789abc``
4. Navigate to the list of notebooks
The example notebooks are located in ``notebooks/example_notebooks/``. The file system shown in the jupyter webpage is relative to the location in which the ``jupyter notebook`` command was used.
Running Jupyter Notebooks via VSCode
------------------------------------
It is also possible to view the Jupyter notebooks within VSCode.
The best place to start is by opening a notebook file (.ipynb) in VSCode. If using VSCode to view a notebook for the first time, follow the steps below.
Installing extensions
"""""""""""""""""""""
VSCode may need some extensions to be installed if not already done.
To do this, press the "Select Kernel" button on the top right.
This should open a dialog which has the option to install python and jupyter extensions.
.. image:: ../../_static/notebooks/install_extensions.png
:width: 700
:align: center
:alt: :: The top dialog option that appears will automatically install the extensions
The following extensions should now be installed
.. image:: ../../_static/notebooks/extensions.png
:width: 300
:align: center
VSCode will then ask for a Python environment version to use. PrimAITE is compatible with Python versions 3.9 - 3.11
You should now be able to interact with the notebook.

View File

@@ -0,0 +1,90 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
PrimAITE Game layer
*******************
The Primaite codebase consists of two main modules:
* ``simulator``: The simulation logic including the network topology, the network state, and behaviour of various hardware and software classes.
* ``game``: The agent-training infrastructure which helps reinforcement learning agents interface with the simulation. This includes the observation, action, and rewards, for RL agents, but also scripted deterministic agents. The game layer orchestrates all the interactions between modules.
The simulator and game layer communicate using the PrimAITE State API and the PrimAITE Request API.
The game layer is responsible for managing agents and getting them to interface with the simulator correctly. It consists of several components:
Agents
======
All agents inherit from the :py:class:`primaite.game.agent.interface.AbstractAgent` class, which mandates that they have an ObservationManager, ActionManager, and RewardManager. The agent behaviour depends on the type of agent, but there are two main types:
* RL agents action during each step is decided by an appropriate RL algorithm. The agent within PrimAITE just acts to format and forward actions decided by an RL policy.
* Deterministic agents perform all of their decision making within the PrimAITE game layer. They typically have a scripted policy which always performs the same action or a rule-based policy which performs actions based on the current state of the simulation. They can have a stochastic element, and their seed is settable.
Observations
============
An agent's observations are managed by the ``ObservationManager`` class. It generates observations based on the current simulation state dictionary. It also provides the observation space during initial setup. The data is formatted so it's compatible with ``Gymnasium.spaces``. Observation spaces are composed of one or more components which are defined by the ``AbstractObservation`` base class.
Actions
=======
An agent's actions are managed by the ``ActionManager``. It converts actions selected by agents (which are typically integers chosen from a ``gymnasium.spaces.Discrete`` space) into simulation-friendly requests. It also provides the action space during initial setup. Action spaces are composed of one or more components which are defined by the ``AbstractAction`` base class.
Rewards
=======
An agent's reward function is managed by the ``RewardManager``. It calculates rewards based on the simulation state (in a way similar to observations). Rewards can be defined as a weighted sum of small reward components. For example, an agents reward can be based on the uptime of a database service plus the loss rate of packets between clients and a web server.
Reward Components
-----------------
Currently implemented are reward components tailored to the data manipulation scenario. View the full API and description of how they work here: :py:module:`primaite.game.agent.reward`.
Reward Sharing
--------------
An agent's reward can be based on rewards of other agents. This is particularly useful for modelling a situation where the blue agent's job is to protect the ability of green agents to perform their pattern-of-life. This can be configured in the YAML file this way:
```yaml
green_agent_1: # this agent sometimes tries to access the webpage, and sometimes the database
# actions, observations, and agent settings go here
reward_function:
reward_components:
# When the webpage loads, the reward goes up by 0.25 when it fails to load, it goes down to -0.25
- type: WEBPAGE_UNAVAILABLE_PENALTY
weight: 0.25
options:
node_hostname: client_2
# When the database is reachable, the reward goes up by 0.05, when it is unreachable it goes down to -0.05
- type: GREEN_ADMIN_DATABASE_UNREACHABLE_PENALTY
weight: 0.05
options:
node_hostname: client_2
blue_agent:
# actions, observations, and agent settings go here
reward_function:
reward_components:
# When the database file is in a good state, blue's reward is 0.4, when it's in a corrupted state the reward is -0.4
- type: DATABASE_FILE_INTEGRITY
weight: 0.40
options:
node_hostname: database_server
folder_name: database
file_name: database.db
# The green's reward is added onto the blue's reward.
- type: SHARED_REWARD
weight: 1.0
options:
agent_name: client_2_green_user
```
When defining agent reward sharing, users must be careful to avoid circular references, as that would lead to an infinite calculation loop. PrimAITE will prevent circular dependencies and provide a helpful error message if they are detected in the yaml.

View File

@@ -1,6 +1,6 @@
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _getting-started:
@@ -11,100 +11,93 @@ Getting Started
Pre-Requisites
In order to get **PrimAITE** installed, you will need to have a python version between 3.8 and 3.10 installed. If you don't already have it, this is how to install it:
In order to get **PrimAITE** installed, you will need Python, venv, and pip. If you don't already have them, this is how to install it:
.. tabs:: lang
.. code-block:: bash
:caption: Unix
.. code-tab:: bash
:caption: Unix
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt install python3.10
sudo apt-get install python3-pip
sudo apt-get install python3-venv
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt install python3.10
sudo apt-get install python3-pip
sudo apt-get install python3-venv
.. code-tab:: text
:caption: Windows (Powershell)
.. code-block:: text
:caption: Windows (Powershell)
- Manual install from: https://www.python.org/downloads/release/python-31011/
- Manual install from: https://www.python.org/downloads/release/python-31011/
**PrimAITE** is designed to be OS-agnostic, and thus should work on most variations/distros of Linux, Windows, and MacOS.
Installing PrimAITE has been tested with all supported python versions, venv 20.24.1, and pip 23.
Install PrimAITE
****************
1. Create a primaite directory in your home directory:
1. Create a directory for your PrimAITE project:
.. tabs:: lang
.. code-block:: bash
:caption: Unix
.. code-tab:: bash
:caption: Unix
mkdir -p ~/primaite/{VERSION}
mkdir ~/primaite/2.0.0
.. code-block:: powershell
:caption: Windows (Powershell)
.. code-tab:: powershell
:caption: Windows (Powershell)
mkdir ~\primaite\{VERSION}
mkdir ~\primaite\2.0.0
2. Navigate to the primaite directory and create a new python virtual environment (venv)
.. tabs:: lang
.. code-block:: bash
:caption: Unix
.. code-tab:: bash
:caption: Unix
cd ~/primaite/{VERSION}
python3 -m venv .venv
cd ~/primaite/2.0.0
python3 -m venv .venv
.. code-block:: powershell
:caption: Windows (Powershell)
.. code-tab:: powershell
:caption: Windows (Powershell)
cd ~\primaite\2.0.0
cd ~\primaite\{VERSION}
python3 -m venv .venv
attrib +h .venv /s /d # Hides the .venv directory
3. Activate the venv
.. tabs:: lang
.. code-block:: bash
:caption: Unix
.. code-tab:: bash
:caption: Unix
source .venv/bin/activate
source .venv/bin/activate
.. code-block:: powershell
:caption: Windows (Powershell)
.. code-tab:: powershell
:caption: Windows (Powershell)
.\.venv\Scripts\activate
.\.venv\Scripts\activate
4. Install PrimAITE using pip from PyPi
4. Install PrimAITE from your saved wheel file
.. tabs:: lang
.. code-block:: bash
:caption: Unix
.. code-tab:: bash
:caption: Unix
pip install path/to/your/primaite.whl[rl]
pip install primaite
.. code-block:: powershell
:caption: Windows (Powershell)
.. code-tab:: powershell
:caption: Windows (Powershell)
pip install primaite
pip install path\to\your\primaite.whl
5. Perform the PrimAITE setup
.. tabs:: lang
.. code-block:: bash
:caption: Unix
.. code-tab:: bash
:caption: Unix
primaite setup
primaite setup
.. code-tab:: powershell
:caption: Windows (Powershell)
.. code-block:: powershell
:caption: Windows (Powershell)
primaite setup
@@ -114,42 +107,67 @@ Clone & Install PrimAITE for Development
To be able to extend PrimAITE further, or to build wheels manually before install, clone the repository to a location
of your choice:
.. TODO:: Add repo path once we know what it is
1. Clone the repository.
For example:
.. code-block:: bash
git clone <repo path>
git clone https://github.com/{todo:fill in URL}/PrimAITE
cd primaite
Create and activate your Python virtual environment (venv)
2. Create and activate your Python virtual environment (venv)
.. tabs:: lang
.. code-block:: bash
:caption: Unix
.. code-tab:: bash
:caption: Unix
python3 -m venv venv
source venv/bin/activate
python3 -m venv venv
source venv/bin/activate
.. code-block:: powershell
:caption: Windows (Powershell)
.. code-tab:: powershell
:caption: Windows (Powershell)
python3 -m venv venv
.\venv\Scripts\activate
python3 -m venv venv
.\venv\Scripts\activate
3. Install PrimAITE with the dev extra
Install PrimAITE with the dev extra
.. code-block:: bash
:caption: Unix
.. tabs:: lang
pip install -e .[dev,rl]
.. code-tab:: bash
:caption: Unix
pip install -e .[dev]
.. code-tab:: powershell
:caption: Windows (Powershell)
pip install -e .[dev]
.. code-block:: powershell
:caption: Windows (Powershell)
pip install -e .[dev,rl]
To view the complete list of packages installed during PrimAITE installation, go to the dependencies page (:ref:`Dependencies`).
4. Set PrimAITE to run on development mode
Running step 3 should have installed PrimAITE, verify this by running
.. code-block:: bash
:caption: Unix
primaite setup
.. code-block:: powershell
:caption: Windows (Powershell)
primaite setup
To set PrimAITE to run in development mode:
.. code-block:: bash
:caption: Unix
primaite dev-mode enable
.. code-block:: powershell
:caption: Windows (Powershell)
primaite dev-mode enable
More information about :ref:`Developer Tools`

View File

@@ -1,6 +1,6 @@
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
Glossary
=============
@@ -38,14 +38,11 @@ Glossary
Blue Agent
A defensive agent that protects the network from Red Agent attacks to minimise disruption to green agents and protect data.
Information Exchange Requirement (IER)
Simulates network traffic by sending data from one network node to another via links for a specified amount of time. IERs can be part of green agent behaviour or red agent behaviour. PrimAITE can be configured to apply a penalty for green agents' IERs being blocked and a reward for red agents' IERs being blocked.
Pattern-of-Life (PoL)
PoLs allow agents to change the current hardware, OS, file system, or service statuses of nodes during the course of an episode. For example, a green agent may restart a server node to represent scheduled maintainance. A red agent's Pattern-of-Life can be used to attack nodes by changing their states to CORRUPTED or COMPROMISED.
Reward
The reward is a single number used by the blue agent to understand whether it's performing well or poorly. RL agents change their behaviour in an attempt to increase the expected reward each episode. The reward is generated based on the current states of the environment / :term:`reference environment` and is impacted positively by things like green IERS running successfully and negatively by things like nodes being compromised.
The reward is a single number used by the blue agent to understand whether it's performing well or poorly. RL agents change their behaviour in an attempt to increase the expected reward each episode. The reward is generated based on the current states of the environment and is impacted positively by things like green PoL running successfully and negatively by things like nodes being compromised.
Observation
An observation is a representation of the current state of the environment that is given to the learning agent so it can decide on which action to perform. If the environment is 'fully observable', the observation contains information about every possible aspect of the environment. More commonly, the environment is 'partially observable' which means the learning agent has to make decisions without knowing every detail of the current environment state.
@@ -65,17 +62,11 @@ Glossary
Episode
When an episode starts, the network simulation is reset to an initial state. The agents take actions on each step of the episode until it reaches a terminal state, which usually happens after a predetermined number of steps. After the terminal state is reached, a new episode starts and the RL agent has another opportunity to protect the network.
Reference environment
While the network simulation is unfolding, a parallel simulation takes place which is identical to the main one except that blue and red agent actions are not applied. This reference environment essentially shows what would be happening to the network if there had been no cyberattack or defense. The reference environment is used to calculate rewards.
Transaction
PrimAITE records the decisions of the learning agent by saving its observation, action, and reward at every time step. During each session, this data is saved to disk to allow for full inspection.
Laydown
The laydown is a file which defines the training scenario. It contains the network topology, firewall rules, services, protocols, and details about green and red agent behaviours.
Gym
PrimAITE uses the Gym reinforcement learning framework API to create a training environment and interface with RL agents. Gym defines a common way of creating observations, actions, and rewards.
Gymnasium
PrimAITE uses the Gymnasium reinforcement learning framework API to create a training environment and interface with RL agents. Gymnasium defines a common way of creating observations, actions, and rewards.
User app home
PrimAITE supports upgrading software version while retaining user data. The user data directory is where configs, notebooks, and results are stored, this location is `~/primaite<version>` on linux/darwin and `C:\Users\<username>\primaite\<version>` on Windows.
PrimAITE supports upgrading software version while retaining user data. The user data directory is where configs, notebooks, and results are stored, this location is `~/primaite<version>/` on linux/darwin and `C:\\Users\\<username>\\primaite<version>` on Windows.

View File

@@ -1,57 +0,0 @@
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
v1.2 to v2.0 Migration guide
============================
**1. Installing PrimAITE**
Like before, you can install primaite from the repository by running ``pip install -e .``. But, there is now an additional setup step which does several things, like setting up user directories, copy default configs and notebooks, etc. Once you have installed PrimAITE to your virtual environment, run this command to finalise setup.
.. code-block:: bash
primaite setup
**2. Running a training session**
In version 1.2 of PrimAITE, the main entry point for training or evaluating agents was the ``src/primaite/main.py`` file. v2.0.0 introduced managed 'sessions' which are responsible for reading configuration files, performing training, and writing outputs.
``main.py`` file still runs a training session but it now uses the new `PrimaiteSession`, and it now requires you to provide the path to your config files.
.. code-block:: bash
python src/primaite/main.py --tc path/to/training-config.yaml --ldc path/to/laydown-config.yaml
Alternatively, the session can be invoked via the commandline by running:
.. code-block:: bash
primaite session --tc path/to/training-config.yaml --ldc path/to/laydown-config.yaml
**3. Location of configs**
In version 1.2, training configs and laydown configs were all stored in the project repository under ``src/primaite/config``. Version 2.0.0 introduced user data directories, and now when you install and setup PrimAITE, config files are stored in your user data location. On Linux/OSX, this is stored in ``~/primaite/2.0.0/config``. On Windows, this is stored in ``C:\Users\<your username>\primaite\configs``. Upon first setup, the configs folder is populated with some default yaml files. It is recommended that you store all your custom configuration files here.
**4. Contents of configs**
Some things that were previously part of the laydown config are now part of the traning config.
* Actions
If you have custom configs which use these, you will need to adapt them by moving the configuration from the laydown config to the training config.
Also, there are new configurable items in the training config:
* Observations
* Agent framework
* Agent
* Deep learning framework
* random red agents
* seed
* deterministic
* hard coded agent view
Each of these items have default values which are designed so that PrimAITE has the same behaviour as it did in 1.2.0, so you do not have to specify them.
ACL Rules in laydown configs have a new required parameter: ``position``. The lower the position, the higher up in the ACL table the rule will placed. If you have custom laydowns, you will need to go through them and add a position to each ACL_RULE.

Some files were not shown because too many files have changed in this diff Show More