From 328aa177da2c26c5af8e83c147b8afe5090ee361 Mon Sep 17 00:00:00 2001 From: CY <774239153@qq.com> Date: Tue, 9 Sep 2025 15:53:29 +0800 Subject: [PATCH 1/6] add: display the vm on the map --- tools/InternetMap/backend/src/api/v1/main.ts | 53 +++++++++++++- .../frontend/src/map/datasource.ts | 34 ++++++++- tools/InternetMap/frontend/src/map/ui.ts | 70 +++++++++++++++++-- 3 files changed, 151 insertions(+), 6 deletions(-) diff --git a/tools/InternetMap/backend/src/api/v1/main.ts b/tools/InternetMap/backend/src/api/v1/main.ts index 00dbf1c19..ebd2af101 100644 --- a/tools/InternetMap/backend/src/api/v1/main.ts +++ b/tools/InternetMap/backend/src/api/v1/main.ts @@ -281,6 +281,48 @@ router.post('/container/vis/set', express.json(), async function (req, res, next next(); }); +router.post('/vm', express.json(), async function (req, res, next) { + if (VMSubscriber == null) { + res.json({ + ok: false, + result: 'VMSubscriber is null' + }); + next(); + return; + } + + if (!req.body['networkName'] || !req.body['nodename'] || !req.body['ip']) { + res.json({ + ok: false, + result: 'the [networkName & nodename & ip] parameter must be provided, and neither can be empty' + }); + next(); + return; + } + + if (VMSubscriber.readyState == WebSocket.OPEN) { + let data = { + role: 'Host', + custom: 'custom', + ...req.body + }; + VMSubscriber.send(JSON.stringify(data)); + } else { + res.json({ + ok: false, + result: 'VMSubscriber is close' + }); + next(); + return; + } + + res.json({ + ok: true + }); + + next(); +}); + router.ws('/console/:id', async function (ws, req, next) { try { if (process.env.CONSOLE === 'false') { @@ -299,7 +341,8 @@ router.ws('/console/:id', async function (ws, req, next) { var snifferSubscribers: WebSocket[] = []; var currentSnifferFilter: string = ''; -var visSubscribers: WebSocket[] = []; +let visSubscribers: WebSocket[] = []; +let VMSubscriber: WebSocket = null; router.post('/sniff', express.json(), async function (req, res, next) { sniffer.setListener((nodeId, data) => { @@ -355,6 +398,14 @@ router.ws('/container/vis/set', async function (ws, req, next) { next(); }); +router.ws('/vm', async function (ws, req, next) { + if (VMSubscriber?.readyState === WebSocket.OPEN) { + VMSubscriber.close(); + } + VMSubscriber = ws; + next(); +}); + router.get('/container/:id/bgp', async function (req, res, next) { let id = req.params.id; diff --git a/tools/InternetMap/frontend/src/map/datasource.ts b/tools/InternetMap/frontend/src/map/datasource.ts index 89745a1ab..7c088ea4d 100644 --- a/tools/InternetMap/frontend/src/map/datasource.ts +++ b/tools/InternetMap/frontend/src/map/datasource.ts @@ -4,7 +4,7 @@ import {BgpPeer, EmulatorNetwork, EmulatorNode} from '../common/types'; export const META_CLASS = 'org.seedsecuritylabs.seedemu.meta.class'; -export type DataEvent = 'packet' | 'dead' | 'vis'; +export type DataEvent = 'packet' | 'dead' | 'vis' | 'vm'; export interface Vertex extends NodeOptions { id: string; @@ -52,6 +52,7 @@ export class DataSource { private _errorHandler: (error: any) => void; private _visEventHandler: (params: any) => void; + private _VMEventHandler: (params: any) => void; /** * construct new data provider. @@ -191,6 +192,29 @@ export class DataSource { } }); + // VM ws + this._socketVis = new WebSocket(`${this._wsProtocol}://${location.host}${this._apiBase}/vm`); + this._socketVis.addEventListener('message', (ev) => { + let msg = ev.data.toString(); + + let object = JSON.parse(msg); + if (this._VMEventHandler) { + this._VMEventHandler(object); + } + }); + + this._socketVis.addEventListener('error', (ev) => { + if (this._errorHandler) { + this._errorHandler(ev); + } + }); + + this._socketVis.addEventListener('close', (ev) => { + if (this._errorHandler) { + this._errorHandler(ev); + } + }); + this._connected = true; } @@ -294,6 +318,10 @@ export class DataSource { break case 'vis': this._visEventHandler = callback; + break + case 'vm': + this._VMEventHandler = callback; + break } } @@ -396,4 +424,8 @@ export class DataSource { return groups; } + + get nets(): EmulatorNetwork[] { + return this._nets; + } } \ No newline at end of file diff --git a/tools/InternetMap/frontend/src/map/ui.ts b/tools/InternetMap/frontend/src/map/ui.ts index a5f6404c1..d19629d50 100644 --- a/tools/InternetMap/frontend/src/map/ui.ts +++ b/tools/InternetMap/frontend/src/map/ui.ts @@ -5,7 +5,7 @@ import {bpfCompletionTree} from '../common/bpf'; import {Completion} from '../common/completion'; import {EmulatorNetwork, EmulatorNode} from '../common/types'; import {WindowManager} from '../common/window-manager'; -import {DataSource, NodesType, EdgesType, Vertex, META_CLASS} from './datasource'; +import {DataSource, EdgesType, META_CLASS, NodesType, Vertex} from './datasource'; declare global { interface Window { @@ -84,8 +84,6 @@ interface PlaylistItem { at: number }; -const count = 10; - const staticDefault = {borderWidth: 1} const dynamicDefault = {borderWidth: 4} const arrowStop = { @@ -681,6 +679,49 @@ export class MapUi { }, adjustedDelay) } }); + + this._datasource.on('vm', (data) => { + if (!data || !this._nodes) { + return; + } + + const networkInfo = this._datasource.nets.find((net) => net['Name'] === data['networkName']) as EmulatorNetwork; + const asn = networkInfo.meta.emulatorInfo.scope; + const id = this.generateRandomHash(), + label = `${asn}/${data.nodename}`, + type = 'node', + custom = 'custom', + shape = 'triangle'; + + if (this._nodes.get({ + filter: item => item.label.split('/').pop() === data.nodename + }).length) { + return; + } + this._addNode({ + id, label, type, shape, group: asn, custom, + object: { + Id: id, + meta: { + relation: { + parent: new Set([networkInfo.Id]) + }, + emulatorInfo: { + role: "Host", + asn: parseInt(asn), + name: data.nodename, + nets: [ + { + name: 'net0', + address: data['ip'], + } + ] + } + } + } + } as Vertex); + this._addEdge(id, networkInfo.Id, data['ip']); + }); } /** @@ -1203,7 +1244,6 @@ export class MapUi { if (vertex.type == 'node') { let node = vertex.object as EmulatorNode; - itemDetails = node.meta.emulatorInfo.nets.map(net => net.address).join(', '); itemName = `${node.meta.emulatorInfo.role}: ${itemName}`; } @@ -1966,4 +2006,26 @@ export class MapUi { nodes.update(updates); } + + private _addNode(vertex:Vertex){ + this._nodes.add(vertex) + } + + private _addEdge(from:string, to:string, label:string){ + this._edges.add({ + from, + to, + label, + }) + } + + generateRandomHash(length: number = 12): string { + const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + let result = ''; + for (let i = 0; i < length; i++) { + const randomIndex = Math.floor(Math.random() * characters.length); + result += characters[randomIndex]; + } + return result; + } } From bafe36f45e5a4ac2e512687ee291c54a8027e629 Mon Sep 17 00:00:00 2001 From: CY <774239153@qq.com> Date: Wed, 10 Sep 2025 10:23:29 +0800 Subject: [PATCH 2/6] fix: VMSubscribers --- tools/InternetMap/backend/src/api/v1/main.ts | 49 ++++++++------------ 1 file changed, 20 insertions(+), 29 deletions(-) diff --git a/tools/InternetMap/backend/src/api/v1/main.ts b/tools/InternetMap/backend/src/api/v1/main.ts index ebd2af101..7d6515861 100644 --- a/tools/InternetMap/backend/src/api/v1/main.ts +++ b/tools/InternetMap/backend/src/api/v1/main.ts @@ -282,15 +282,6 @@ router.post('/container/vis/set', express.json(), async function (req, res, next }); router.post('/vm', express.json(), async function (req, res, next) { - if (VMSubscriber == null) { - res.json({ - ok: false, - result: 'VMSubscriber is null' - }); - next(); - return; - } - if (!req.body['networkName'] || !req.body['nodename'] || !req.body['ip']) { res.json({ ok: false, @@ -300,21 +291,24 @@ router.post('/vm', express.json(), async function (req, res, next) { return; } - if (VMSubscriber.readyState == WebSocket.OPEN) { - let data = { - role: 'Host', - custom: 'custom', - ...req.body - }; - VMSubscriber.send(JSON.stringify(data)); - } else { - res.json({ - ok: false, - result: 'VMSubscriber is close' - }); - next(); - return; - } + let deadSockets: WebSocket[] = []; + let data = { + role: 'Host', + custom: 'custom', + ...req.body + }; + + VMSubscribers.forEach(socket => { + if (socket.readyState == 1) { + socket.send(JSON.stringify(data)); + } + + if (socket.readyState > 1) { + deadSockets.push(socket); + } + }); + + deadSockets.forEach(socket => VMSubscribers.splice(VMSubscribers.indexOf(socket), 1)); res.json({ ok: true @@ -342,7 +336,7 @@ router.ws('/console/:id', async function (ws, req, next) { var snifferSubscribers: WebSocket[] = []; var currentSnifferFilter: string = ''; let visSubscribers: WebSocket[] = []; -let VMSubscriber: WebSocket = null; +let VMSubscribers: WebSocket[] = []; router.post('/sniff', express.json(), async function (req, res, next) { sniffer.setListener((nodeId, data) => { @@ -399,10 +393,7 @@ router.ws('/container/vis/set', async function (ws, req, next) { }); router.ws('/vm', async function (ws, req, next) { - if (VMSubscriber?.readyState === WebSocket.OPEN) { - VMSubscriber.close(); - } - VMSubscriber = ws; + VMSubscribers.push(ws); next(); }); From 2ab07a803f149233f564be4c5dff8aed085e26e1 Mon Sep 17 00:00:00 2001 From: cy-gitlab <774239153@qq.com> Date: Wed, 28 Oct 2026 18:00:44 +0800 Subject: [PATCH 3/6] fix: containerBundle md --- docs/designs/container_bundle.md | 307 +++++++++++++++++++-- docs/designs/eth_explorer.md | 132 +++++++++ docs/designs/internet_map.md | 99 +++++++ seedemu/containerBundle/ContainerBundle.py | 213 +++++++++++++- seedemu/containerBundle/EthExplorer.py | 41 ++- seedemu/containerBundle/InternetMap.py | 90 +++--- 6 files changed, 799 insertions(+), 83 deletions(-) create mode 100644 docs/designs/eth_explorer.md create mode 100644 docs/designs/internet_map.md diff --git a/docs/designs/container_bundle.md b/docs/designs/container_bundle.md index 9e33976cf..62dc079e2 100644 --- a/docs/designs/container_bundle.md +++ b/docs/designs/container_bundle.md @@ -2,6 +2,283 @@ Created: October 8, 2026 +## Current implementation: two cooperating classes + +`seedemu/containerBundle/ContainerBundle.py` defines two layers of +responsibility: + +- `ContainerBundle` owns a group of services, shared network configuration, + port allocation, and the Compose fragments returned to the Docker compiler. +- `PreparedContainer` owns one service definition, its network attachments, + staged files, startup commands, and generated Dockerfile context. + +The lifecycle is: + +```mermaid +flowchart TD + A[Create emulator] --> B[Render emulator] + B --> C[Create ContainerBundle] + C --> D[Create PreparedContainer objects] + D --> E[Configure network and ports] + E --> F[docker.addContainerBundle] + F --> G[emu.compile] + G --> H[ContainerBundle.configure] + H --> I[Configure services and attachments] + I --> J[ContainerBundle.install] + J --> K[PreparedContainer.install] + K --> L[Dockerfiles and Compose YAML] +``` + +## `ContainerBundle` design + +Subclasses normally create their containers in `__init__`, configure them in +`configure()`, and rely on the compiler to call `install()`: + +```python +class ExampleBundle(ContainerBundle): + def __init__(self, emulator, suffix=".example"): + super().__init__(emulator=emulator, suffix=suffix) + self._createContainer("backend", suffix) + + def configure(self): + self._required_port_number = 1 + super().configure() + backend = self.getContainer("backend") + backend.setContentAttribute({ + "image": "busybox:latest", + "command": "sleep infinity", + }) +``` + +`_createContainer(local_name, suffix)` registers a `PreparedContainer`. The +logical name is used as the Compose service name; its generated hostname is +`local_name + suffix`. `getContainer()`, `getContainers()`, `getEmulator()`, +and `getSuffix()` provide inspection access. + +### Default network + +`setDefaultNetwork()` defines the isolated Docker network shared by bundle +services: + +```python +bundle.setDefaultNetwork( + name="example_network", + prefix="172.30.0.0/24", + ip_addresses=["172.30.0.10", "172.30.0.11"], + default_router="172.30.0.1", + type="bridge", +) +``` + +`prefix` is an IPv4 subnet in CIDR notation. The method validates the subnet, +gateway, address count, subnet membership, duplicate addresses, and gateway +exclusion. It also creates the Compose IPAM configuration. Addresses are +assigned in container creation order. `getDefaultNetwork()` returns the +stored dictionary, including the generated `network_config`. + +The resulting structure is consumed by `configure()` and `install()`: + +```python +{ + "name": "example_network", + "prefix": "172.30.0.0/24", + "ip_addresses": ["172.30.0.10", "172.30.0.11"], + "default_router": "172.30.0.1", + "type": "bridge", + "network_config": { + "driver": "bridge", + "ipam": {"config": [{"subnet": "172.30.0.0/24", "gateway": "172.30.0.1"}]}, + }, +} +``` + +`setDefaultNetwork()` does not attach containers immediately. A bundle's +`configure()` method selects an address for each container and calls +`joinExternalNetwork()`. Later, `install()` emits the `network_config` as the +Compose network definition. + +```mermaid +flowchart LR + A[setDefaultNetwork] --> B[Validate CIDR, gateway and addresses] + B --> C[Store normalized network dictionary] + C --> D[configure assigns addresses] + D --> E[PreparedContainer.joinExternalNetwork] + E --> F[install emits Compose IPAM network] +``` + +### Ports and lifecycle + +`setPorts()` stores a copy of the host-port pool. A subclass sets +`_required_port_number` before calling `super().configure()`; the base method +then validates that enough ports were supplied. The subclass consumes ports +and fills service attributes during the same `configure()` call. + +`install()` calls `PreparedContainer.install()` for every registered service, +filters emulator-owned networks from the bundle network section, and returns +the generated service and network YAML fragments. + +```mermaid +sequenceDiagram + participant D as Docker compiler + participant B as ContainerBundle + participant C as PreparedContainer + D->>B: configure() + B->>B: validate ports and configure services + D->>B: install() + B->>C: install() for each service + C-->>B: Compose service mapping + B-->>D: services and networks YAML +``` + +`getEmuHostNetworkInfo()` scans rendered emulator hosts and returns the first +usable network, host address, and default router. It is intended to run after +`emu.render()`, because it reads the rendered host and network registries. The +return value is either `None` or the parameter dictionary expected by +`joinInternalNetwork()`: + +```python +{ + "network": "net0.as150", + "hostname": "router150.net0.seed", + "ip_address": "10.150.0.1", + "default_route": "10.150.0.254", +} +``` + +The two methods intentionally share the same field names, so the result can +be passed directly with keyword expansion: + +```python +network_info = bundle.getEmuHostNetworkInfo() +if network_info is None: + raise RuntimeError("No emulator host network is available") + +container.joinInternalNetwork(**network_info) +``` + +This is also the pattern used by bundles that store the result during +construction and later attach selected containers during `configure()`. + +The method skips networks without a usable host address and converts address +and router objects to strings. The bundle decides which network to select and +which containers need it. `getInternalHostnameIpMappings()` +and `getExternalHostnameIpMappings()` expose the collected hostname/IP data. + +## `PreparedContainer` design + +`PreparedContainer` is the mutable build description for one container. It +stores its Compose mapping, internal and external network attachments, staged +files, and startup commands. + +`getName()` returns the logical service name and `getHostname()` returns the +name with the bundle suffix. `setContentAttribute()` merges Compose service +attributes: + +```python +container.setContentAttribute({ + "image": "busybox:latest", + "command": "sleep infinity", +}) +``` + +`joinExternalNetwork(network, hostname, ip_address)` attaches the container to +the bundle Docker network with a static address. `joinInternalNetwork()` +attaches it to an emulator network and records the network, hostname, address, +and optional gateway. When `default_route` is supplied, the container records +the gateway and inserts route setup before the application startup commands: + +```sh +DEFAULT_ROUTE="10.150.0.254" +IFACE=$(ip route get "$DEFAULT_ROUTE" | awk '{for (i=1;i<=NF;i++) if ($i=="dev") print $(i+1); exit}') +echo "gateway=$DEFAULT_ROUTE interface=$IFACE" +ip route del default 2>/dev/null || true +ip route add default via "$DEFAULT_ROUTE" dev "$IFACE" +``` + +The commands are inserted after an existing shebang and `set -eu` prologue +when those lines are present. If startup commands are available, +`install()` writes them to the configured start-script path and wraps the +image entrypoint when the commands do not already form a complete script. +This is required when a bundle service must reach the emulator network through +its gateway. + +The method is normally called by a bundle during `configure()`: + +```python +network = bundle.getEmuHostNetworkInfo() +container.joinInternalNetwork( + network=network["network"], + hostname=network["hostname"], + ip_address=network["ip_address"], + default_route=network.get("default_route", ""), +) +``` + +The internal attachment and the external bundle attachment are independent. +A container may therefore have two Compose network entries. The default route +is optional and should be used only when outbound traffic must leave through +the emulator gateway. A service using `network_mode: host` should not also be +attached through this method. + +`setFile()` stages a file in the generated image context. `setEtcHosts()` +stages content that is appended to `/etc/hosts` during installation. The +`install()` method creates the hostname directory, writes staged files and the +startup script, generates a Dockerfile when needed, and returns the Compose +service mapping. It also performs the final startup integration: `/tmp/etc-hosts` +is appended to `/etc/hosts`, default-route commands are inserted, and a +wrapper entrypoint is selected when generated commands must run before the +image's normal process. `_addFile()` hashes destination paths to create +staging names for Docker `COPY` instructions. + +The installation sequence is: + +```mermaid +flowchart TD + A[PreparedContainer.install] --> B[Create hostname build directory] + B --> C[Stage files and /tmp/etc-hosts] + C --> D[Insert hosts and route commands] + D --> E{Startup commands present?} + E -- no --> F[Keep image entrypoint] + E -- yes --> G{Commands have shebang?} + G -- yes --> H[Write configured start script] + G -- no --> I[Create entrypoint wrapper] + I --> H + H --> J[Generate Dockerfile and return service mapping] + F --> J +``` + +### `_getDefaultRouteCommands()` + +This helper converts a gateway address into shell commands that can run inside +the container. It first asks the kernel which interface reaches the gateway, +then replaces the Docker-provided default route: + +```sh +DEFAULT_ROUTE="10.150.0.254" +IFACE=$(ip route get "$DEFAULT_ROUTE" | awk '{for (i=1;i<=NF;i++) if ($i=="dev") print $(i+1); exit}') +echo "gateway=$DEFAULT_ROUTE interface=$IFACE" +ip route del default 2>/dev/null || true +ip route add default via "$DEFAULT_ROUTE" dev "$IFACE" +``` + +The helper is only used when `joinInternalNetwork(..., default_route=...)` +provides a non-empty gateway. The commands are inserted after an existing +shebang and `set -eu` prologue when present. They are generated at container +startup because Docker assigns the interface name at runtime. + +For images that already have an entrypoint, `setEntrypointWrapper()` can run +preparation commands and then delegate to the original entrypoint: + +```python +container.setEntrypointWrapper( + original_entrypoint="/entrypoint.sh", + commands=["cat /tmp/etc-hosts >> /etc/hosts"], +) +``` + +This avoids assuming that a generated `/start.sh` will be executed by an +image whose `ENTRYPOINT` is fixed. + ### Design Assumptions - Default network: All the containers in the bundle are attached to the isolated external network created for this bundle. This network is not reachable by the nodes in the emulator. @@ -80,27 +357,21 @@ emu.render() # After the rendering # Customize and configure the containers in the entire group bundle = VisualizationSystem(emu, "map.seed") -bundle.setDefaultNetwork("visualization_network", "172.19.0.0/16", [f"172.18.0.{i}" for i in range(5, 11)]) +bundle.setDefaultNetwork( + name="internetMap_network", + prefix="172.30.0.0/24", + ip_addresses=[ + "172.30.0.10", + "172.30.0.11", + "172.30.0.12", + "172.30.0.13", + ], + default_router="172.30.0.1" +) bundle.setPorts(list(range(8090, 8099)) # Docker first invokes bundle.configure() which will configure all the containers; # Docker then invokes bundle.install() to create a folder for each container, and add entries to docker-compose.yml docker.addContainerBundle(bundle) -# Dockerfile of each container image -From baseimage - -COPY {etchosts} /tmp/etc-hosts -RUN cat /tmp/etc-hosts >> /etc/hosts - - - -# Add extra_hosts -services: - frontend: - image: ubuntu:24.04 - extra_hosts: - backend.visual.seed: "10.150.0.10" - database.visual.seed: "10.150.0.11" - -``` \ No newline at end of file +``` diff --git a/docs/designs/eth_explorer.md b/docs/designs/eth_explorer.md new file mode 100644 index 000000000..f1d2dea0c --- /dev/null +++ b/docs/designs/eth_explorer.md @@ -0,0 +1,132 @@ +# EthExplorer design + +`seedemu.containerBundle.EthExplorer` packages the services required to index +an Ethereum Beacon Chain and expose explorer pages inside a SEED Emulator. +It extends `ContainerBundle` and produces one Docker Compose service for each +dependency and application component. + +## Service topology + +| Service | Role | +| --- | --- | +| `clickhouse` | Analytics and indexed execution data | +| `postgres` | Relational explorer metadata | +| `redis` | Cache and session storage | +| `littlebigtable` | Bigtable-compatible storage | +| `rawbigtable` | Raw Bigtable-compatible storage | +| `seedemu-ethexplorer-backend` | Beacon/execution indexers and exporters | +| `seedemu-ethexplorer-web` | Explorer API and web-facing processes | + +All services join the bundle bridge network with deterministic addresses. The +backend and web services also join an emulator network so they can contact the +configured Beacon and Geth boot nodes. + +```mermaid +flowchart LR + P[Postgres] --> L[Little Bigtable] + P --> R[Raw Bigtable] + C[ClickHouse] --> B[Explorer backend] + P --> B + R --> B + L --> B + K[Redis] --> B + B --> W[Explorer web] + ETH[Beacon and Geth boot nodes] --> B + ETH --> W +``` + +## Construction and lifecycle + +```python +explorer = EthExplorer(emu, ".eth.explorer") +explorer.setPorts([8090]) +docker.addContainerBundle(explorer) +``` + +The constructor creates the seven containers and resolves the emulator host +network. `configure()` performs the following work: + +1. Validates that at least one published host port is available. +2. Reads the first blockchain from `EthereumService`. +3. Selects Beacon and Geth boot-node addresses unless explicit overrides were + provided. +4. Assigns the bundle network addresses and service images. +5. Adds health checks and dependency conditions for storage services. +6. Configures backend and web environment variables. +7. Joins backend and web to the selected emulator network. +8. Generates startup scripts that provision and rewrite `config.yml`. + +The Docker compiler then invokes `install()` on every `PreparedContainer` and +publishes the web service port to the host. + +```mermaid +sequenceDiagram + participant D as Docker compiler + participant X as EthExplorer + participant E as EthereumService + participant S as Storage services + participant B as Backend + participant W as Web + D->>X: configure() + X->>E: select blockchain and boot nodes + X->>S: assign images, addresses, health checks + X->>B: configure host variables and dependencies + X->>W: configure host variables and published port + X->>B: joinInternalNetwork(..., default_route) + X->>W: joinInternalNetwork(..., default_route) + D->>X: install() +``` + +## Network and default route + +The default bridge network is `ethExplorer_network` on `172.20.0.0/24`. +`setDefaultNetwork()` can replace it, but the supplied address list must have +at least seven entries because every EthExplorer container receives one +address. + +The backend and web containers call `joinInternalNetwork()` with the selected +emulator network. Their startup scripts use the returned `default_route` to +identify the interface, remove the Docker default route, and add a route via +the emulator gateway. This is necessary when the explorer must reach Beacon +and Geth nodes through the emulator network rather than through the isolated +bundle bridge. + +If the emulator does not expose a usable host network, configuration should +fail clearly instead of producing containers that cannot index the chain. + +## Configuration provisioning + +The backend and web images contain the upstream provisioning script +`provision-explorer-config-custom.sh`. Their generated startup commands run +that script first, then use `sed` to replace service hosts in the generated +`config.yml`: + +```mermaid +flowchart TD + A[Container starts] --> B[Run provision-explorer-config-custom.sh] + B --> C[Create local deployment config.yml] + C --> D[Replace Postgres, ClickHouse, Bigtable and Redis hosts] + D --> E[Start indexers and explorer processes] + E --> F[Keep supervisor shell alive] +``` + +The replacement values are the static addresses assigned on the bundle +network. The Beacon and Geth addresses come from `EthereumService` and are +passed through the `CL_HOST` and `EL_HOST` environment variables. Keeping the +provisioning script inside the image allows the bundle to adapt the generated +configuration without exposing the image's original entrypoint implementation +in the emulator source. + +## Host override APIs + +Use `setBeaconHost()` and `setGethHost()` before `configure()` when the default +boot-node selection is not appropriate: + +```python +explorer.setBeaconHost("10.0.0.10") +explorer.setGethHost("10.0.0.11") +``` + +`getBeaconHost()` and `getGethHost()` expose the values selected for the final +configuration and are useful for diagnostics or tests. + diff --git a/docs/designs/internet_map.md b/docs/designs/internet_map.md new file mode 100644 index 000000000..c22c94a0d --- /dev/null +++ b/docs/designs/internet_map.md @@ -0,0 +1,99 @@ +# InternetMap design + +`seedemu.containerBundle.InternetMap` packages the services used to visualize +an emulator: the emulator API service, topology UI, geographic UI, and traffic +observer. It is a `ContainerBundle`, so Docker compiles the bundle only after +the emulator has been rendered. + +## Responsibilities + +The bundle creates four logical services: + +| Service | Role | Network behavior | +| --- | --- | --- | +| `seedemu_emulator_service_backend` | Exposes emulator REST and WebSocket APIs | Bundle network; optionally emulator network | +| `seedemu_internet_map_toplogy` | Serves the topology frontend | Bundle network | +| `seedemu_internet_map_geographic` | Serves the geographic frontend | Bundle network and `host.docker.internal` | +| `seedemu_traffic_observer_service_backend` | Captures host traffic | Host network mode | + +The traffic observer is deliberately excluded from the bundle bridge network, +because it uses `network_mode: host` and accesses kernel and Docker resources. + +## Construction and configuration + +```python +internet_map = InternetMap(emu, ".map.seed") +internet_map.setPorts(list(range(8081, 8089))) +docker.addContainerBundle(internet_map) +``` + +`InternetMap` creates all four `PreparedContainer` instances in its +constructor. `configure()` requires at least three host ports: one for the +traffic observer and one for each frontend. It assigns static addresses from +the default bridge network, writes the Nginx configuration, and stages +`/etc/hosts` entries for the emulator API hostname. + +The default network can be replaced with `setDefaultNetwork()`. Its address +pool must contain enough addresses for the three bridge-attached containers; +the host-network traffic observer does not consume an address. + +```mermaid +flowchart TD + A[InternetMap constructor] --> B[Create four PreparedContainer objects] + B --> C[setPorts] + C --> D[Docker compiler calls configure] + D --> E[Assign bridge addresses] + E --> F[Configure emulator API and Nginx] + F --> G[Configure traffic observer host networking] + G --> H[Docker compiler calls install] + H --> I[Generate Compose services and container contexts] +``` + +## Optional emulator-network attachment + +The normal configuration only needs the bundle bridge network. Some +deployments also need the emulator API container to reach the emulated host +network. The current opt-in API is: + +```python +internet_map.enableEmulatorNetwork() +``` + +This attaches `seedemu_emulator_service_backend` to the network returned by +`getEmuHostNetworkInfo()`. The network information contains the network name, +the selected emulator host name and address, and, when available, its default +router. `PreparedContainer.joinInternalNetwork()` stores that attachment and +can add startup commands that replace the container's default route. + +The opt-in call should be made after the emulator has been rendered, so a +usable emulator network is available. If the bundle is extended with more +internal-network consumers, each service should be attached explicitly and +the traffic observer should remain on host networking. + +```mermaid +sequenceDiagram + participant E as Emulator + participant I as InternetMap + participant B as API backend + participant N as Emulator network + E->>E: render() + I->>E: getEmuHostNetworkInfo() + I->>B: joinInternalNetwork(network, host, ip, route) + B->>N: attach second network interface + B->>B: optionally replace default route + B->>N: call emulator API / websocket peers +``` + +`enableEmulatorNetwork()` is intentionally opt-in. Existing examples that do +not call it retain the original bridge-only topology. + +## Reverse proxy and generated files + +The topology and geographic containers run Nginx. Their generated upstream +configuration points to the backend service at port `7071`; the geographic +configuration also proxies traffic-observer requests to the host-published +observer port. `setFile()` stages the Nginx configuration, while `setEtcHosts()` +stages the backend hostname mapping. The generated container entrypoint is +preserved through `PreparedContainer` installation rather than requiring the +base image's original script to be copied into the bundle source. + diff --git a/seedemu/containerBundle/ContainerBundle.py b/seedemu/containerBundle/ContainerBundle.py index 46790490c..fe85fc823 100644 --- a/seedemu/containerBundle/ContainerBundle.py +++ b/seedemu/containerBundle/ContainerBundle.py @@ -5,6 +5,7 @@ from hashlib import md5 from os import mkdir, chdir from textwrap import indent +from ipaddress import IPv4Address, IPv4Network from typing import Dict, List, Optional, Tuple, Any from dataclasses import InitVar, dataclass, field @@ -17,11 +18,21 @@ class IndentDumper(yaml.SafeDumper): + """YAML dumper that keeps nested mappings consistently indented.""" + def increase_indent(self, flow=False, indentless=False): return super().increase_indent(flow, False) def safe_dump_pretty(data) -> str: + """Serialize ``data`` as readable YAML without sorting mapping keys. + + Args: + data: Mapping or sequence to serialize. + + Returns: + The generated YAML document. + """ return yaml.dump( data, Dumper=IndentDumper, @@ -33,6 +44,13 @@ def safe_dump_pretty(data) -> str: @dataclass(eq=False) class ContainerBundle: + """Base class for a group of independently built Docker containers. + + Subclasses create containers in ``__init__`` and populate their service + definitions in ``configure``. The Docker compiler calls ``configure`` and + ``install`` to generate Compose services and network definitions. + """ + emulator: InitVar[Optional[Emulator]] = None suffix: InitVar[str] = "" _emulator: Optional[Emulator] = field(default=None, init=False, repr=False) @@ -45,61 +63,142 @@ class ContainerBundle: _required_port_number: int = field(default=0, init=False) def __post_init__(self, emulator: Optional[Emulator], suffix: str) -> None: + """Store the emulator reference and hostname/build-directory suffix.""" self._emulator = emulator self._suffix = suffix def _createContainer(self, local_name: str, suffix: str) -> PreparedContainer: + """Create and register a prepared container. + + Args: + local_name: Logical service name used in Compose. + suffix: Suffix appended to the generated hostname. + + Returns: + The newly registered :class:`PreparedContainer`. + """ container = PreparedContainer(name=local_name, suffix=suffix) self._containers.update({local_name: container}) return container def getContainer(self, local_name: str) -> PreparedContainer: + """Return a registered container by its logical service name.""" return self._containers[local_name] def getContainers(self) -> Dict[str, PreparedContainer]: + """Return a shallow copy of all registered containers.""" return self._containers.copy() def getEmulator(self) -> Optional[Emulator]: + """Return the emulator associated with this bundle, if any.""" return self._emulator def getSuffix(self) -> str: + """Return the suffix used for generated container hostnames.""" return self._suffix def setDefaultNetwork( self, name: str, - prefix: str = "", - ip_addresses: List[str] = None, - network_config: Dict[str, Any] = None, - ) -> None: - assert ip_addresses, 'The "ip_addresses" field cannot be left blank.' - assert len(ip_addresses) >= len( - self._containers - ), 'The "ip_addresses" field must contain at least one address per container.' + prefix: str, + ip_addresses: List[str], + default_router: str, + type: str = "bridge", + ): + """Configure the default Docker network and static container addresses. + + Args: + name: Docker Compose network name. + prefix: IPv4 subnet in CIDR notation, such as ``172.20.0.0/24``. + ip_addresses: Static IPv4 addresses assigned in container order. + default_router: IPv4 gateway address inside ``prefix``. + type: Docker network driver, normally ``"bridge"``. + + Returns: + This bundle, allowing fluent configuration. + + Raises: + ValueError: If the subnet, gateway, or container addresses are + invalid or inconsistent. + """ + subnet = IPv4Network(prefix, strict=True) + gateway = IPv4Address(default_router) + + if not ip_addresses: + raise ValueError('The "ip_addresses" field cannot be left blank.') + + if len(ip_addresses) < len(self._containers): + raise ValueError( + f"The number of IP addresses ({len(ip_addresses)}) " + f"cannot be less than the number of containers " + f"({len(self._containers)})." + ) + + if gateway not in subnet: + raise ValueError(f"default_router {default_router!r} is outside subnet {prefix!r}.") + + normalized_addresses = [] + for address in ip_addresses: + ip = IPv4Address(address) + + if ip not in subnet: + raise ValueError(f"IP address {address!r} is outside subnet {prefix!r}.") + + if ip == gateway: + raise ValueError(f"IP address {address!r} cannot be the default router.") + + normalized_addresses.append(str(ip)) + + if len(set(normalized_addresses)) != len(normalized_addresses): + raise ValueError("Container IP addresses must be unique.") + self._default_network = { "name": name, "prefix": prefix, - "ip_addresses": list(ip_addresses), - "network_config": network_config.copy(), + "ip_addresses": normalized_addresses, + "default_router": str(gateway), + "type": type, + "network_config": { + "driver": type, + "ipam": { + "config": [ + { + "subnet": prefix, + "gateway": str(gateway), + } + ] + }, + }, } + return self + def getDefaultNetwork(self) -> Optional[Dict[str, Any]]: + """Return the configured default network, or ``None`` if unset.""" return self._default_network def setPorts(self, ports: List[int]) -> None: + """Set the host-port pool consumed by the bundle during configuration.""" self._ports = ports.copy() def getPorts(self) -> List[int]: + """Return a copy of the currently configured host-port pool.""" return self._ports.copy() def getInternalHostnameIpMappings(self) -> Dict[str, str]: + """Return mappings for services attached to emulated networks.""" return self._internal_hostname_ip_mappings.copy() def getExternalHostnameIpMappings(self) -> Dict[str, str]: + """Return mappings for services attached to the bundle network.""" return self._external_hostname_ip_mappings.copy() def configure(self) -> None: + """Validate bundle-wide settings before service generation. + + Subclasses should call this method before configuring their services. + """ if len(self._ports) < self._required_port_number: raise ValueError( f"At least {self._required_port_number} ports are required; " @@ -107,6 +206,7 @@ def configure(self) -> None: ) def install(self) -> tuple[str, str]: + """Install containers and return Compose service and network YAML.""" services = {} for name, container in self._containers.items(): services[name] = container.install() @@ -159,7 +259,12 @@ def install(self) -> tuple[str, str]: return compose_services_txt, compose_networks_txt def getEmuHostNetworkInfo(self): - """Return host network information using the Docker Compose network name.""" + """Return the first usable emulated host network and default route. + + Returns: + A dictionary containing ``network``, ``hostname``, ``ip_address`` + and ``default_route``, or ``None`` when no suitable host exists. + """ for (_, node_type, _), node in self._emulator.getRegistry().getAll().items(): if node_type != "hnode": continue @@ -186,6 +291,8 @@ def getEmuHostNetworkInfo(self): @dataclass(eq=False) class PreparedContainer: + """Mutable description of one container before Compose generation.""" + name: InitVar[str] = "" suffix: InitVar[str] = "" _name: str = field(default="", init=False) @@ -199,19 +306,24 @@ class PreparedContainer: _service_ports: List[str] = field(default_factory=list, init=False) _start_commands: List[str] = field(default_factory=list, init=False) _start_script_name: str = field(default="/start.sh", init=False) + _default_route: str = field(default="", init=False) def __post_init__(self, name: str, suffix: str) -> None: + """Initialize the logical service name and Compose service metadata.""" self._name = name self._suffix = suffix self.service["container_name"] = name def getName(self) -> str: + """Return the logical Compose service name.""" return self._name def getHostname(self) -> str: + """Return the generated hostname including the configured suffix.""" return self._name + self._suffix def getInternalHostnameIpMappings(self) -> Dict[str, str]: + """Return the first emulated-network hostname-to-IP mapping.""" if not self._internal_networks: return {} @@ -219,12 +331,41 @@ def getInternalHostnameIpMappings(self) -> Dict[str, str]: return {internal_networks[1]: internal_networks[2]} def getExternalHostnameIpMappings(self) -> Dict[str, str]: + """Return external-network hostname-to-IP mappings.""" return { external_network[1]: external_network[2] for external_network in (self._external_network or []) } + def setEntrypointWrapper( + self, + original_entrypoint: str, + commands: List[str], + ) -> None: + """ + Run preparation commands before delegating to the original entrypoint. + + Args: + original_entrypoint: Entrypoint script from the base image. + commands: Shell commands to run before the original entrypoint. + """ + wrapper_commands = [ + "#!/bin/sh", + "set -eu", + *commands, + f'exec sh "{original_entrypoint}" "$@"', + ] + + self._start_commands = wrapper_commands + self._start_script_name = "/new-entrypoint.sh" + + self.service["entrypoint"] = [ + "sh", + "/new-entrypoint.sh", + ] + def install(self) -> Dict[str, Any]: + """Write build context files and return the Compose service mapping.""" hostname = self.getHostname() mkdir(hostname) chdir(hostname) @@ -232,9 +373,30 @@ def install(self) -> Dict[str, Any]: etchosts_content = self._files.pop("__etchosts_file", "") if etchosts_content: self.setFile("/tmp/etc-hosts", etchosts_content) - self._start_commands.insert(1, "cat /tmp/etc-hosts >> /etc/hosts") + etc_hosts_command = "cat /tmp/etc-hosts >> /etc/hosts" + if etc_hosts_command not in self._start_commands: + insert_index = 0 + if len(self._start_commands) > 1: + if self._start_commands[1] == "set -eu": + insert_index = 2 + else: + insert_index = 1 + self._start_commands.insert(insert_index, etc_hosts_command) + + if self._default_route: + insert_index = 0 + if len(self._start_commands) > 1: + if self._start_commands[1] == "set -eu": + insert_index = 2 + else: + insert_index = 1 + self._start_commands[insert_index:insert_index] = self._getDefaultRouteCommands() if self._start_commands: + if not self._start_commands[0].startswith("#!"): + self.setEntrypointWrapper( + original_entrypoint=self._start_script_name, commands=self._start_commands + ) self.setFile(self._start_script_name, "\n".join(self._start_commands)) dockerfile = self._computeDockerfile() @@ -244,6 +406,17 @@ def install(self) -> Dict[str, Any]: chdir("..") return self.service + def _getDefaultRouteCommands(self) -> List[str]: + """Return shell commands for switching the container default route.""" + return [ + f'DEFAULT_ROUTE="{self._default_route}"', + 'IFACE=$(ip route get "$DEFAULT_ROUTE" | ' + "awk '{for (i=1;i<=NF;i++) if ($i==\"dev\") print $(i+1); exit}')", + 'echo "gateway=$DEFAULT_ROUTE interface=$IFACE"', + "ip route del default 2>/dev/null || true", + 'ip route add default via "$DEFAULT_ROUTE" dev "$IFACE"', + ] + def joinInternalNetwork( self, network: str, @@ -251,6 +424,14 @@ def joinInternalNetwork( ip_address: str = "", default_route: Optional[str] = "", ) -> None: + """Attach the container to an emulated network. + + Args: + network: Compose network name. + hostname: Hostname or node name on that network. + ip_address: Address assigned by the emulator. + default_route: Optional gateway used by startup scripts. + """ internal_network = (network, hostname, ip_address, default_route) if internal_network not in self._internal_networks: self._internal_networks.append(internal_network) @@ -259,8 +440,11 @@ def joinInternalNetwork( if network not in networks: networks.update({network: {}}) + if default_route and not self._default_route: + self._default_route = default_route + def joinExternalNetwork(self, network: str, hostname: str, ip_address: str) -> None: - """Attach to the bundle's single external network, identified by name.""" + """Attach the container to a bundle-managed network with a static IP.""" external_network = (network, hostname, ip_address) if external_network not in self._external_network: self._external_network.append(external_network) @@ -270,12 +454,15 @@ def joinExternalNetwork(self, network: str, hostname: str, ip_address: str) -> N networks.update({network: {"ipv4_address": ip_address}}) def setContentAttribute(self, content: dict) -> None: + """Merge Docker Compose service attributes into this container.""" self.service.update(content) def setEtcHosts(self, content: str) -> None: + """Stage content that will be appended to the container's ``/etc/hosts``.""" self._files["__etchosts_file"] = content def setFile(self, filename: str, content: str) -> None: + """Stage a file to be copied into the generated image.""" self._files.update({filename: content}) def _computeDockerfile(self) -> str: diff --git a/seedemu/containerBundle/EthExplorer.py b/seedemu/containerBundle/EthExplorer.py index e14f290e1..eb4ca762b 100644 --- a/seedemu/containerBundle/EthExplorer.py +++ b/seedemu/containerBundle/EthExplorer.py @@ -16,7 +16,7 @@ DEFAULT_NETWORK = { "name": "ethExplorer_network", - "prefix": ".eth", + "prefix": "172.20.0.0/24", "ip_addresses": [ "172.20.0.10", "172.20.0.11", @@ -26,19 +26,11 @@ "172.20.0.15", "172.20.0.16", ], - "network_config": { - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.20.0.0/24", "gateway": "172.20.0.1"}]}, - }, + "default_router": "172.20.0.1" } BACKEND_START_SH = [ "#!/bin/sh", - 'DEFAULT_ROUTE="{default_route}"', - 'IFACE=$(ip route get "$DEFAULT_ROUTE" | awk \'{for (i=1;i<=NF;i++) if ($i=="dev") print $(i+1); exit}\')', - 'echo "gateway=$DEFAULT_ROUTE interface=$IFACE"', - "ip route del default 2>/dev/null || true", - 'ip route add default via "$DEFAULT_ROUTE" dev "$IFACE"', "stopit() {", ' echo "trapped SIGINT"', " exit 0", @@ -82,11 +74,6 @@ ] FRONTEND_START_SH = [ "#!/bin/bash", - 'DEFAULT_ROUTE="{default_route}"', - 'IFACE=$(ip route get "$DEFAULT_ROUTE" | awk \'{for (i=1;i<=NF;i++) if ($i=="dev") print $(i+1); exit}\')', - 'echo "gateway=$DEFAULT_ROUTE interface=$IFACE"', - "ip route del default 2>/dev/null || true", - 'ip route add default via "$DEFAULT_ROUTE" dev "$IFACE"', "stopit() {", ' echo "trapped SIGINT"', " exit 0", @@ -131,7 +118,20 @@ class EthExplorer(ContainerBundle): + """Container bundle for the Ethereum Beacon Chain explorer stack. + + The bundle includes PostgreSQL, ClickHouse, Redis, two Bigtable emulators, + an indexing backend, and the Web frontend. + """ + def __init__(self, emulator, suffix="eth.explorer"): + """Create an explorer bundle for an Ethereum-enabled emulator. + + Args: + emulator: Emulator containing an ``EthereumService`` and a usable + emulated host network. + suffix: Suffix appended to generated container hostnames. + """ super().__init__(emulator=emulator, suffix=suffix) self._default_network = DEFAULT_NETWORK service_names = [ @@ -149,6 +149,7 @@ def __init__(self, emulator, suffix="eth.explorer"): self._emu_internal_network = self.getEmuHostNetworkInfo() def configure(self) -> None: + """Validate settings and configure explorer services and connections.""" self._required_port_number = 1 super().configure() @@ -271,9 +272,6 @@ def configure(self) -> None: ) seedemu_ethexplorer_backend.joinInternalNetwork(**self._emu_internal_network) backend_start_commands = BACKEND_START_SH.copy() - backend_start_commands[1] = backend_start_commands[1].format( - default_route=self._emu_internal_network["default_route"] - ) backend_start_commands = [ command.format( POSTGRES_HOST=postgres_ip, @@ -309,9 +307,6 @@ def configure(self) -> None: ) seedemu_ethexplorer_web.joinInternalNetwork(**self._emu_internal_network) frontend_start_commands = FRONTEND_START_SH.copy() - frontend_start_commands[1] = frontend_start_commands[1].format( - default_route=self._emu_internal_network["default_route"] - ) frontend_start_commands = [ command.format( POSTGRES_HOST=postgres_ip, @@ -325,13 +320,17 @@ def configure(self) -> None: seedemu_ethexplorer_web._start_commands = frontend_start_commands def getBeaconHost(self) -> str: + """Return the consensus-layer Beacon node host selected for the explorer.""" return self.__beacon_host def getGethHost(self) -> str: + """Return the execution-layer Geth node host selected for the explorer.""" return self.__geth_host def setBeaconHost(self, beacon_host) -> None: + """Override the Beacon node host used by the backend and frontend.""" self.__beacon_host = beacon_host def setGethHost(self, geth_host) -> None: + """Override the Geth node host used by the backend and frontend.""" self.__geth_host = geth_host diff --git a/seedemu/containerBundle/InternetMap.py b/seedemu/containerBundle/InternetMap.py index bf53f99e9..696093ac8 100644 --- a/seedemu/containerBundle/InternetMap.py +++ b/seedemu/containerBundle/InternetMap.py @@ -7,17 +7,14 @@ DEFAULT_NETWORK = { "name": "internetMap_network", - "prefix": ".map", + "prefix": "172.30.0.0/24", "ip_addresses": [ "172.30.0.10", "172.30.0.11", "172.30.0.12", "172.30.0.13", ], - "network_config": { - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.30.0.0/24", "gateway": "172.30.0.1"}]}, - }, + "default_router": "172.30.0.1", } NGINX_CONF_PATH = "/etc/nginx/conf.d/default.conf" @@ -38,7 +35,7 @@ ] START_SCRIPT_NAME = "/entrypoint.sh" SEEDEMU_INTERNET_MAP_TOPLOGY_NGINX_CONF = """ -upstream seedemu_emulator_service {{ +upstream seedemu_emulator_service_backend {{ server {}:{}; }} @@ -51,7 +48,7 @@ client_max_body_size 100m; location ^~ /api/v1 {{ - proxy_pass http://seedemu_emulator_service; + proxy_pass http://seedemu_emulator_service_backend; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; @@ -64,7 +61,7 @@ }} location ^~ /emulator/ {{ - proxy_pass http://seedemu_emulator_service/; + proxy_pass http://seedemu_emulator_service_backend/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; @@ -82,11 +79,11 @@ }} """ SEEDEMU_INTERNET_MAP_GEOGRAPHIC_NGINX_CONF = """ -upstream seedemu_emulator_service {{ +upstream seedemu_emulator_service_backend {{ server {}:{}; }} -upstream seedemu_traffic_observer_service {{ +upstream seedemu_traffic_observer_service_backend {{ server host.docker.internal:{}; }} @@ -99,7 +96,7 @@ client_max_body_size 100m; location ^~ /api/v1 {{ - proxy_pass http://seedemu_emulator_service; + proxy_pass http://seedemu_emulator_service_backend; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; @@ -112,7 +109,7 @@ }} location ^~ /emulator/ {{ - proxy_pass http://seedemu_emulator_service/; + proxy_pass http://seedemu_emulator_service_backend/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; @@ -125,7 +122,7 @@ }} location ^~ /traffic-observer/ {{ - proxy_pass http://seedemu_traffic_observer_service/; + proxy_pass http://seedemu_traffic_observer_service_backend/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; @@ -145,25 +142,46 @@ class InternetMap(ContainerBundle): + """Container bundle for the topology, geographic map, and traffic views.""" + def __init__(self, emulator, suffix="map.seed"): + """Create an Internet Map bundle. + + Args: + emulator: Emulator whose topology will be visualized. + suffix: Suffix appended to generated container hostnames. + """ super().__init__(emulator=emulator, suffix=suffix) self._default_network = DEFAULT_NETWORK service_names = [ - "seedemu_emulator_service", + "seedemu_emulator_service_backend", "seedemu_internet_map_toplogy", "seedemu_internet_map_geographic", - "seedemu_traffic_observer_service", + "seedemu_traffic_observer_service_backend", ] for service_name in service_names: self._createContainer(service_name, suffix) + self._emu_internal_network = self.getEmuHostNetworkInfo() + + def enableEmulatorNetwork(self): + """ + Enable access to an emulator internal network. + """ + seedemu_emulator_service_backend = self._containers["seedemu_emulator_service_backend"] + seedemu_emulator_service_backend.joinInternalNetwork(**self._emu_internal_network) + + return self def configure(self) -> None: + """Validate ports and configure the map, API, and observer services.""" self._required_port_number = 3 super().configure() - seedemu_traffic_observer_service = self._containers["seedemu_traffic_observer_service"] + seedemu_traffic_observer_service_backend = self._containers[ + "seedemu_traffic_observer_service_backend" + ] seedemu_traffic_observer_service_port = self._ports.pop() - seedemu_traffic_observer_service.setContentAttribute( + seedemu_traffic_observer_service_backend.setContentAttribute( { "image": SEEDEMU_TRAFFIC_OBSERVER_SERVICE_IMAGE, "privileged": True, @@ -183,34 +201,38 @@ def configure(self) -> None: ], } ) - seedemu_traffic_observer_service._service_ports = [seedemu_traffic_observer_service_port] + seedemu_traffic_observer_service_backend._service_ports = [ + seedemu_traffic_observer_service_port + ] default_network_name = self._default_network["name"] ip_addresses = self._default_network["ip_addresses"] for index, container in enumerate(self._containers.values()): - if container is seedemu_traffic_observer_service: + if container is seedemu_traffic_observer_service_backend: continue container.joinExternalNetwork( default_network_name, container.getHostname(), ip_addresses[index] ) - seedemu_emulator_service = self._containers["seedemu_emulator_service"] - seedemu_emulator_service.setContentAttribute( + seedemu_emulator_service_backend = self._containers["seedemu_emulator_service_backend"] + seedemu_emulator_service_backend.setContentAttribute( { + "privileged": True, "image": SEEDEMU_EMULATOR_SERVICE_IMAGE, "volumes": ["/var/run/docker.sock:/var/run/docker.sock:ro"], "environment": {"BACKEND_ENV": "production"}, } ) - seedemu_emulator_service_ip = seedemu_emulator_service.service["networks"][ + seedemu_emulator_service_ip = seedemu_emulator_service_backend.service["networks"][ default_network_name ]["ipv4_address"] seedemu_internet_map_toplogy = self._containers["seedemu_internet_map_toplogy"] seedemu_internet_map_toplogy.setContentAttribute( { + "privileged": True, "image": SEEDEMU_INTERNET_MAP_TOPLOGY_IMAGE, - "depends_on": [seedemu_emulator_service.getName()], + "depends_on": [seedemu_emulator_service_backend.getName()], "ports": [f"{self._ports.pop()}:80"], "build": f"./{seedemu_internet_map_toplogy.getHostname()}", } @@ -218,20 +240,24 @@ def configure(self) -> None: seedemu_internet_map_toplogy.setFile( NGINX_CONF_PATH, SEEDEMU_INTERNET_MAP_TOPLOGY_NGINX_CONF.format( - seedemu_emulator_service.getHostname(), SEEDEMU_EMULATOR_SERVICE_INTERNAL_PORT + seedemu_emulator_service_backend.getHostname(), + SEEDEMU_EMULATOR_SERVICE_INTERNAL_PORT, ), ) - seedemu_internet_map_toplogy._start_commands = START_SH + # seedemu_internet_map_toplogy._start_commands = START_SH seedemu_internet_map_toplogy._start_script_name = START_SCRIPT_NAME seedemu_internet_map_toplogy.setEtcHosts( - "\n".join([f"{seedemu_emulator_service_ip} {seedemu_emulator_service.getHostname()}"]) + "\n".join( + [f"{seedemu_emulator_service_ip} {seedemu_emulator_service_backend.getHostname()}"] + ) ) seedemu_internet_map_geographic = self._containers["seedemu_internet_map_geographic"] seedemu_internet_map_geographic.setContentAttribute( { + "privileged": True, "image": SEEDEMU_INTERNET_MAP_GEOGRAPHIC_IMAGE, - "depends_on": [seedemu_emulator_service.getName()], + "depends_on": [seedemu_emulator_service_backend.getName()], "extra_hosts": {"host.docker.internal": "host-gateway"}, "ports": [f"{self._ports.pop()}:80"], "build": f"./{seedemu_internet_map_geographic.getHostname()}", @@ -240,15 +266,17 @@ def configure(self) -> None: seedemu_internet_map_geographic.setFile( NGINX_CONF_PATH, SEEDEMU_INTERNET_MAP_GEOGRAPHIC_NGINX_CONF.format( - seedemu_emulator_service.getHostname(), + seedemu_emulator_service_backend.getHostname(), SEEDEMU_EMULATOR_SERVICE_INTERNAL_PORT, - seedemu_traffic_observer_service.service.get("environment", {}).get( + seedemu_traffic_observer_service_backend.service.get("environment", {}).get( "TRAFFIC_CONTROL_ADDR" )[1:], ), ) - seedemu_internet_map_geographic._start_commands = START_SH + # seedemu_internet_map_geographic._start_commands = START_SH seedemu_internet_map_geographic._start_script_name = START_SCRIPT_NAME seedemu_internet_map_geographic.setEtcHosts( - "\n".join([f"{seedemu_emulator_service_ip} {seedemu_emulator_service.getHostname()}"]) + "\n".join( + [f"{seedemu_emulator_service_ip} {seedemu_emulator_service_backend.getHostname()}"] + ) ) From 3eba10b578e52dc84953c0cf9966aa55d22781c3 Mon Sep 17 00:00:00 2001 From: cy-gitlab <774239153@qq.com> Date: Fri, 30 Oct 2026 17:31:36 +0800 Subject: [PATCH 4/6] update: containerBundle --- docs/designs/container_bundle.md | 248 +++++------- docs/designs/eth_explorer.md | 219 +++++++++- docs/designs/internet_map.md | 156 ++++---- examples/basic/A10b_add_containers/README.md | 230 +++++++++++ .../add_containerBundle.py | 159 ++++++++ .../D01_ethereum_pos/ethereum_pos.py | 34 -- .../blockchain/D10_eth_explorer/README.md | 105 +++-- .../D10_eth_explorer/ethereum_pos.py | 207 ++++++++-- .../B08_internet_map_bundle/README.md | 127 ++++++ .../internet_map_bundle.py | 75 ++++ seedemu/containerBundle/ContainerBundle.py | 376 +++++++++++++----- seedemu/containerBundle/EthExplorer.py | 231 ++++++----- seedemu/containerBundle/InternetMap.py | 115 +++--- 13 files changed, 1685 insertions(+), 597 deletions(-) create mode 100644 examples/basic/A10b_add_containers/README.md create mode 100644 examples/basic/A10b_add_containers/add_containerBundle.py create mode 100644 examples/internet/B08_internet_map_bundle/README.md create mode 100644 examples/internet/B08_internet_map_bundle/internet_map_bundle.py diff --git a/docs/designs/container_bundle.md b/docs/designs/container_bundle.md index 62dc079e2..ab03886d8 100644 --- a/docs/designs/container_bundle.md +++ b/docs/designs/container_bundle.md @@ -16,17 +16,23 @@ The lifecycle is: ```mermaid flowchart TD - A[Create emulator] --> B[Render emulator] - B --> C[Create ContainerBundle] - C --> D[Create PreparedContainer objects] - D --> E[Configure network and ports] - E --> F[docker.addContainerBundle] - F --> G[emu.compile] - G --> H[ContainerBundle.configure] - H --> I[Configure services and attachments] - I --> J[ContainerBundle.install] - J --> K[PreparedContainer.install] - K --> L[Dockerfiles and Compose YAML] + subgraph row1["1. Create"] + direction LR + A[Create emulator] --> B[Render emulator] --> C[Create ContainerBundle] + end + subgraph row2["2. Register"] + direction RL + D[Create PreparedContainer objects] --> E[Configure network and ports] --> F[docker.addContainerBundle] + end + subgraph row3["3. Configure"] + direction LR + G[emu.compile] --> H[ContainerBundle.configure] --> I[Configure services and attachments] + end + subgraph row4["4. Install"] + direction RL + J[ContainerBundle.install] --> K[PreparedContainer.install] --> L[Dockerfiles and Compose YAML] + end + row1 --> row2 --> row3 --> row4 ``` ## `ContainerBundle` design @@ -43,7 +49,7 @@ class ExampleBundle(ContainerBundle): def configure(self): self._required_port_number = 1 super().configure() - backend = self.getContainer("backend") + backend = self.getContainer("backend" + self.getSuffix()) backend.setContentAttribute({ "image": "busybox:latest", "command": "sleep infinity", @@ -51,17 +57,18 @@ class ExampleBundle(ContainerBundle): ``` `_createContainer(local_name, suffix)` registers a `PreparedContainer`. The -logical name is used as the Compose service name; its generated hostname is -`local_name + suffix`. `getContainer()`, `getContainers()`, `getEmulator()`, +registration key, Compose service name, `container_name`, and generated hostname +are all `local_name + suffix`. `getName()` retains the unsuffixed logical name. +Pass the suffixed key to `getContainer()`; `getContainers()`, `getEmulator()`, and `getSuffix()` provide inspection access. ### Default network -`setDefaultNetwork()` defines the isolated Docker network shared by bundle +`setDefaultExternalNetwork()` defines the isolated Docker network shared by bundle services: ```python -bundle.setDefaultNetwork( +bundle.setDefaultExternalNetwork( name="example_network", prefix="172.30.0.0/24", ip_addresses=["172.30.0.10", "172.30.0.11"], @@ -73,8 +80,9 @@ bundle.setDefaultNetwork( `prefix` is an IPv4 subnet in CIDR notation. The method validates the subnet, gateway, address count, subnet membership, duplicate addresses, and gateway exclusion. It also creates the Compose IPAM configuration. Addresses are -assigned in container creation order. `getDefaultNetwork()` returns the -stored dictionary, including the generated `network_config`. +assigned in container creation order. `getDefaultExternalNetwork()` returns the +stored dictionary, including the generated `network_config`, with a copied +`ip_addresses` list. Configure the external network before calling this getter. The resulting structure is consumed by `configure()` and `install()`: @@ -92,18 +100,22 @@ The resulting structure is consumed by `configure()` and `install()`: } ``` -`setDefaultNetwork()` does not attach containers immediately. A bundle's +`setDefaultExternalNetwork()` does not attach containers immediately. A bundle's `configure()` method selects an address for each container and calls `joinExternalNetwork()`. Later, `install()` emits the `network_config` as the Compose network definition. ```mermaid -flowchart LR - A[setDefaultNetwork] --> B[Validate CIDR, gateway and addresses] - B --> C[Store normalized network dictionary] - C --> D[configure assigns addresses] - D --> E[PreparedContainer.joinExternalNetwork] - E --> F[install emits Compose IPAM network] +flowchart TD + subgraph row1["1. Define network"] + direction LR + A[setDefaultExternalNetwork] --> B[Validate CIDR, gateway and addresses] --> C[Store network dictionary] + end + subgraph row2["2. Attach and install"] + direction RL + D[configure assigns addresses] --> E[PreparedContainer.joinExternalNetwork] --> F[install emits Compose IPAM network] + end + row1 --> row2 ``` ### Ports and lifecycle @@ -130,34 +142,53 @@ sequenceDiagram B-->>D: services and networks YAML ``` -`getEmuHostNetworkInfo()` scans rendered emulator hosts and returns the first -usable network, host address, and default router. It is intended to run after -`emu.render()`, because it reads the rendered host and network registries. The -return value is either `None` or the parameter dictionary expected by -`joinInternalNetwork()`: +### Internal emulator network + +`allocateEmuNetworkAddress()` scans rendered host interfaces and selects the +first network with enough free addresses. Each call reserves +`_required_emu_network_address_number` addresses starting at network-address +offset 10 (`10.150.0.10` for `10.150.0.0/24`). It skips all registered host, +router, and border-router addresses, the gateway, network and broadcast +addresses, and earlier bundle reservations. Reservations are stored on the +network as `container_bundle_reserved_addresses`, so bundles share them. +Insufficient candidates receive no partial reservation. + +Call after `emu.render()`. On success the method stores the following internal +network dictionary and returns the bundle itself; it returns `None` when no +network has enough capacity or no emulator is associated. The required count +must be a non-negative integer; booleans and other invalid values raise +`ValueError`. ```python { - "network": "net0.as150", - "hostname": "router150.net0.seed", - "ip_address": "10.150.0.1", + "network": "net_150_net0", + "emu_hostname": "host150", + "ip_addresses": ["10.150.0.10", "10.150.0.11"], "default_route": "10.150.0.254", } ``` -The two methods intentionally share the same field names, so the result can -be passed directly with keyword expansion: +Read the stored dictionary with `getDefaultInternalNetwork()` after successful +allocation. Select one IP and pass the container's own hostname explicitly: ```python -network_info = bundle.getEmuHostNetworkInfo() -if network_info is None: +bundle._required_emu_network_address_number = 2 +if bundle.allocateEmuNetworkAddress() is None: raise RuntimeError("No emulator host network is available") - -container.joinInternalNetwork(**network_info) +network_info = bundle.getDefaultInternalNetwork() +container.joinInternalNetwork( + network=network_info["network"], + hostname=container.getHostname(), + ip_address=network_info["ip_addresses"][0], + default_route=network_info["default_route"], +) ``` -This is also the pattern used by bundles that store the result during -construction and later attach selected containers during `configure()`. +`setDefaultInternalNetwork(name, ip_addresses, default_route)` supplies a manual +selection and returns the bundle. Supply enough addresses for the consuming +services and ensure they are free: this setter does not validate or reserve +them. The getter copies the address list. Prefer explicit allocation before +the getter when no manual network has been set. The method skips networks without a usable host address and converts address and router objects to strings. The bundle decides which network to select and @@ -205,15 +236,19 @@ its gateway. The method is normally called by a bundle during `configure()`: ```python -network = bundle.getEmuHostNetworkInfo() +bundle._required_emu_network_address_number = 1 +if bundle.allocateEmuNetworkAddress() is None: + raise RuntimeError("No emulator host network is available") +network = bundle.getDefaultInternalNetwork() container.joinInternalNetwork( network=network["network"], - hostname=network["hostname"], - ip_address=network["ip_address"], + hostname=container.getHostname(), + ip_address=network["ip_addresses"][0], default_route=network.get("default_route", ""), ) ``` +The internal attachment writes `ipv4_address` into the Compose network entry. The internal attachment and the external bundle attachment are independent. A container may therefore have two Compose network entries. The default route is optional and should be used only when outbound traffic must leave through @@ -234,17 +269,21 @@ The installation sequence is: ```mermaid flowchart TD - A[PreparedContainer.install] --> B[Create hostname build directory] - B --> C[Stage files and /tmp/etc-hosts] - C --> D[Insert hosts and route commands] - D --> E{Startup commands present?} - E -- no --> F[Keep image entrypoint] - E -- yes --> G{Commands have shebang?} - G -- yes --> H[Write configured start script] - G -- no --> I[Create entrypoint wrapper] - I --> H - H --> J[Generate Dockerfile and return service mapping] - F --> J + subgraph row1["1. Stage files"] + direction LR + A[PreparedContainer.install] --> B[Create hostname build directory] --> C[Stage files and /tmp/etc-hosts] + end + subgraph row2["2. Prepare startup"] + direction RL + D[Insert hosts and route commands] --> E{Startup commands present?} + E -- no --> F[Keep image entrypoint] + E -- yes --> G{Commands have shebang?} + G -- yes --> H[Write configured start script] + G -- no --> I[Create entrypoint wrapper] + I --> H + end + row1 --> row2 + row2 --> J[Generate Dockerfile and return service mapping] ``` ### `_getDefaultRouteCommands()` @@ -278,100 +317,5 @@ container.setEntrypointWrapper( This avoids assuming that a generated `/start.sh` will be executed by an image whose `ENTRYPOINT` is fixed. - -### Design Assumptions - -- Default network: All the containers in the bundle are attached to the isolated external network created for this bundle. This network is not reachable by the nodes in the emulator. -- Emulator networks: If a container needs to communicate with the nodes in the emulator, it also needs to attach to a network internal to the emulator. Which network to use is up to the bundle. -- Limited customization needs: Most part of the container’s Dockerfile and compose entries are already prepared, so there is no need to provide many unnecessary customization APIs. -- /etc/hosts: The name-ip mappings are only needed by the containers in this bundle; other containers in the emulator do not need the mappings. -- Compose’s extra_hosts entry: provide name-ip mappings to the containers inside the emulator. - -### ContainerBundle (Similar to Service) - -- init(emulator, suffix): - - Call `_createContainer(local_name, suffix)` to create the containers in this bundle. - - Each container has a local name, which is decided by the bundle. The hostname of a container = local name + suffix -- _createContainer(local_name, suffix): internal method to create Container. -- setDefaultNetwork(name, prefix, [ip address list]): This network is an isolated network reserved for this bundle. All the containers will be attached to this network by default. Containers on this network cannot reach the hosts on the emulator, and vice versa. The host machine can reach these containers. A network entry will be created in the compose file. - - If users do not set this, default values will be used -- setPorts(list): Allocate a list of ports for the containers; they can use these ports for port forwarding. Port selection is up to the bundle -- configure(): Configure the containers in this group. When this is called, all the information needed by a container is already decided, so we can generate the final content for all the files of the container. - - Attach all the containers to the default network: PrepairedContainer :: joinExternalNetwork(network, hostname, ip_address) - - Attach containers to a selected emulator network, if needed. The selection method is implemented here (see the notes below). Set the network information for each container. PrepairedContainer :: joinInternalNetwork(network, hostname, ip_address, default_router) - - Select ports for each container. These ports are for port forwarding. Container’s local ports are decided locally by the bundle. - - Construct the final Dockerfile, compose entry, etchosts file, and other files. Store the final results in the Container object. Construction is based on the prepared format strings defined in this object (or file). -- install(): Call `PreparedContainer::install()`for each container. This API returns the followings: - - The compose entry strings for all the containers in this bundle. -- File templates: the file templates is stored in the same file using a dictionary: key —> content -- Attributes - - __internal_hostname_ip_mappings: record the the hostname-ip mappings for those hosts attached to the internal network. These mappings will be added to the compose entry for all the emulator nodes (using the extra_hosts entry). This is to supplement the /etc/hosts content set by the EtcHosts layer, because we cannot use this layer anymore after the rendering phase. Docker will append these mappings to /etc/hosts when creating containers. - - __external_hostname_ip_mappings: this is for the /etc/hosts file of all the containers in this bundle. -- **Notes**: - - If a container needs to communicate with the nodes inside the emulator, it needs to be attached to a network inside the emulator. The Bundle class can use the Emulator object to select networks, reserve IP addresses (each network object has an IP assignment method), and get the default routes on these networks. The selection can be based on ASN, network name, or hostname. The selection is entirely up to the bundle. - -### PreparedContainer - -Most of the part of this container is already fixed, but a small part of it needs to be decided during the construction time. Eventually, docker compiler creates a folder for each container, and add corresponding entries to docker-compose.yml. - -- init(name, suffix, etchosts_file=”etchosts”): Set the name of the container. -- install(): Create a folder for the container, and set its content. Use the hostname (local name + suffix) as the folder name. Return the followings: - - The docker compose service entry for this container. - - The hostname-ip mappings for the -- joinInternalNetwork(network, hostname, ip_address, default_router): Attach the container to an internal network inside the emulator. - - Typically, a container should join just one internal network (if it needs to communicate with the nodes inside the emulator). If indeed, it is attached to multiple internal networks, only the first network’s following information is used: hostname-ip mapping, default router. - - The IP address should pick from the reserved range, so it does not use the ones that are already allocated. - - The default router information can be obtained from the network object. -- joinExternalNetwork(network, hostname, ip_address): Attach the container to a network external to the emulator. -- setComposeContent(content: str): Set the docker compose entry for this container. Set __compose_content. -- setDockerfile(content: str): Set the content of the Dockerfile, use self.__files[”Dockerfile”] -- setEtcHosts(content: str): Set the content of the /etc/hosts file, use self.__files[_etchosts_file] -- setFile(filename, content): Set the content of the other files. Each file set via this API will appear in the output container folder -- Attributes: - - __emulator: the emulator object - - __name: str, __suffix: str - - __internal_networks: a list of network (network_name, hostname, ip_address, default_router) - - __external_network: only one (network_name, hostname, ip_address) - - __files: Dict[name, content]: each entry will become a file in the final image folder. - - __etchosts_file - - __compose_content - - -### Notes (future work) - -- For each network, reserve a block of IPs for external containers, i.e., for containers added later by the docker compiler. - - -### Code Example - -```python -# VisualizationSystem -class VisualizationSystem(ContainerBundle) - -# Example -docker = Docker() - -... -emu.render() - -# After the rendering -# Customize and configure the containers in the entire group -bundle = VisualizationSystem(emu, "map.seed") -bundle.setDefaultNetwork( - name="internetMap_network", - prefix="172.30.0.0/24", - ip_addresses=[ - "172.30.0.10", - "172.30.0.11", - "172.30.0.12", - "172.30.0.13", - ], - default_router="172.30.0.1" -) -bundle.setPorts(list(range(8090, 8099)) - -# Docker first invokes bundle.configure() which will configure all the containers; -# Docker then invokes bundle.install() to create a folder for each container, and add entries to docker-compose.yml -docker.addContainerBundle(bundle) - -``` +The wrapper's Compose entrypoint is `["sh", self._start_script_name]`, using +the configured script path. diff --git a/docs/designs/eth_explorer.md b/docs/designs/eth_explorer.md index f1d2dea0c..c2db1da48 100644 --- a/docs/designs/eth_explorer.md +++ b/docs/designs/eth_explorer.md @@ -43,8 +43,9 @@ explorer.setPorts([8090]) docker.addContainerBundle(explorer) ``` -The constructor creates the seven containers and resolves the emulator host -network. `configure()` performs the following work: +The constructor creates seven containers, requires one host port, and requests +two internal addresses. Allocation is deferred to `configure()`, which performs +the following work: 1. Validates that at least one published host port is available. 2. Reads the first blockchain from `EthereumService`. @@ -53,7 +54,8 @@ network. `configure()` performs the following work: 4. Assigns the bundle network addresses and service images. 5. Adds health checks and dependency conditions for storage services. 6. Configures backend and web environment variables. -7. Joins backend and web to the selected emulator network. +7. Allocates two internal addresses unless a manual internal network is set, + then attaches the backend at `ip_addresses[0]` and web at `ip_addresses[1]`. 8. Generates startup scripts that provision and rewrite `config.yml`. The Docker compiler then invokes `install()` on every `PreparedContainer` and @@ -80,10 +82,16 @@ sequenceDiagram ## Network and default route The default bridge network is `ethExplorer_network` on `172.20.0.0/24`. -`setDefaultNetwork()` can replace it, but the supplied address list must have +`setDefaultExternalNetwork()` can replace it, but the supplied address list must have at least seven entries because every EthExplorer container receives one address. +Allocation starts at network-address offset 10, skips occupied addresses and +earlier bundle reservations, and reserves both addresses on one host network. +Use `setDefaultInternalNetwork(name, ip_addresses, default_route)` to supply +two free addresses manually before compilation; this setter does not reserve +or validate them. Render the emulator before allocation. + The backend and web containers call `joinInternalNetwork()` with the selected emulator network. Their startup scripts use the returned `default_route` to identify the interface, remove the Docker default route, and add a route via @@ -91,7 +99,7 @@ the emulator gateway. This is necessary when the explorer must reach Beacon and Geth nodes through the emulator network rather than through the isolated bundle bridge. -If the emulator does not expose a usable host network, configuration should +If no host network has two usable addresses, configuration should fail clearly instead of producing containers that cannot index the chain. ## Configuration provisioning @@ -103,11 +111,15 @@ that script first, then use `sed` to replace service hosts in the generated ```mermaid flowchart TD - A[Container starts] --> B[Run provision-explorer-config-custom.sh] - B --> C[Create local deployment config.yml] - C --> D[Replace Postgres, ClickHouse, Bigtable and Redis hosts] - D --> E[Start indexers and explorer processes] - E --> F[Keep supervisor shell alive] + subgraph row1["1. Provision"] + direction LR + A[Container starts] --> B[Run provisioning script] --> C[Create local deployment config.yml] + end + subgraph row2["2. Adapt and run"] + direction RL + D[Replace storage hosts] --> E[Start indexers and explorer processes] --> F[Keep supervisor shell alive] + end + row1 --> row2 ``` The replacement values are the static addresses assigned on the bundle @@ -130,3 +142,190 @@ explorer.setGethHost("10.0.0.11") `getBeaconHost()` and `getGethHost()` expose the values selected for the final configuration and are useful for diagnostics or tests. +## How EthExplorer extends ContainerBundle + +`EthExplorer` inherits from `ContainerBundle`. The base class provides generic +container registration, network settings, address reservation, port pools, +hostname/IP mapping accessors, and Compose installation. EthExplorer supplies +the Ethereum-specific service topology and configuration. It overrides +`__init__()` and `configure()`, adds four node-host accessors, and inherits +`install()` without overriding it. + +| Responsibility | `ContainerBundle` | `EthExplorer` | +| --- | --- | --- | +| Initialization | Stores emulator and suffix through the dataclass initialization and `__post_init__()`; starts with empty containers and unset networks. | Calls `super().__init__()`, supplies an external network, creates seven containers, sets resource requirements, and initializes node hosts. | +| `configure()` | Checks that the supplied port pool meets `_required_port_number`. | Calls the base check, selects Ethereum nodes, configures storage and applications, attaches networks, and prepares startup commands. | +| `install()` | Installs each prepared container and returns service/network YAML, excluding emulator-owned networks from bundle network definitions. | Inherits this behavior; generated startup scripts and files are materialized by `PreparedContainer.install()`. | +| Beacon/Geth selection | Has no Ethereum-specific node selection. | Adds `getBeaconHost()`, `getGethHost()`, `setBeaconHost()`, and `setGethHost()`. | + +### `__init__()`: define the explorer stack + +The constructor performs these operations in order: + +1. Calls `super().__init__(emulator=emulator, suffix=suffix)` so inherited + registration, networking, and compiler integration remain available. +2. Sets `_default_external_network = DEFAULT_NETWORK`, using the seven static + addresses on `172.20.0.0/24`. +3. Calls `_createContainer()` for `clickhouse`, `postgres`, `redis`, + `littlebigtable`, `rawbigtable`, `seedemu-ethexplorer-backend`, and + `seedemu-ethexplorer-web`, in that order. This order determines external + address assignment. +4. Sets `_required_port_number = 1` for the Web UI and + `_required_emu_network_address_number = 2` for backend/Web internal + interfaces. Storage services only need the external bundle network. +5. Initializes `__beacon_host` and `__geth_host` to empty strings. Node + selection, service image attributes, and startup-script preparation happen + later in `configure()`. + +### `configure()`: turn the stack into concrete services + +The Docker compiler invokes this method during compilation: + +1. `super().configure()` checks the one-port minimum and raises `ValueError` + before explorer setup if the pool is too small. +2. Fetches `EthereumService`, selects its first blockchain, and fills each + empty node-host field from the corresponding first bootnode IP. Nonempty + overrides remain unchanged. +3. Attaches all seven containers to the external network in creation order. + Retrieves prepared containers using their logical name plus suffix. +4. Configures ClickHouse, PostgreSQL, Redis, and both Bigtable services, + including database settings, Redis persistence, health checks, and + dependencies. Reads their actual assigned static IPs from the service + network mappings for use in application configuration. +5. Configures backend privileges, host PID, capabilities, logging, build + context, dependency conditions, database-table health check, and the + `CL_HOST`/`EL_HOST` environment variables. +6. Uses a manually supplied internal network or calls + `allocateEmuNetworkAddress()` to reserve two addresses. Backend uses the + first address and Web the second, with the selected default route. +7. Copies `BACKEND_START_SH`, formats its `sed -i` command with storage IPs, + and assigns it to `seedemu_ethexplorer_backend._start_commands`. +8. Configures Web with the same node-host variables and storage dependencies, + additionally waiting for backend health. Publishes the final supplied host + port to container port `5000`, attaches the second internal address, and + assigns a formatted copy of `FRONTEND_START_SH` to + `seedemu_ethexplorer_web._start_commands`. + +`configure()` prepares Python service descriptions; it does not run the +provisioning or application processes. Inherited installation writes build +contexts, and those processes run when Docker starts the containers. + +## Detailed Beacon and Geth host APIs + +These four methods are specific to EthExplorer: + +| Method | Stored value and effect | Return value | +| --- | --- | --- | +| `setBeaconHost(beacon_host)` | Assigns `__beacon_host`; a nonempty value overrides automatic consensus-layer selection and becomes `CL_HOST` in both containers. | `None` | +| `setGethHost(geth_host)` | Assigns `__geth_host`; a nonempty value overrides automatic execution-layer selection and becomes `EL_HOST` in both containers. | `None` | +| `getBeaconHost()` | Reads the current `__beacon_host`; does not query the emulator or trigger selection. | Current value, initially `""` | +| `getGethHost()` | Reads the current `__geth_host`; does not query the emulator or trigger selection. | Current value, initially `""` | + +The setters perform assignment without reachability or address validation. +They are not fluent methods, so call them separately. An empty string allows +the corresponding automatic selection on the next `configure()` call. Set +overrides before compilation: changing these fields after configuration does +not rewrite service environment dictionaries that were already generated. + +```python +explorer = EthExplorer(emu, ".eth.explorer.seed") +assert explorer.getBeaconHost() == "" +assert explorer.getGethHost() == "" +explorer.setBeaconHost("10.150.0.71") +explorer.setGethHost("10.150.0.72") +print(explorer.getBeaconHost(), explorer.getGethHost()) +explorer.setPorts([8090]) +docker.addContainerBundle(explorer) +``` + +For automatic selection, omit the setters and inspect the getters after a +successful `emu.compile()`. These addresses identify the Ethereum nodes; +they are separate from the two internal addresses allocated to the explorer +containers themselves. + +## Adapted backend and Web start scripts + +### Why the scripts change + +The base images already have `/start.sh` entrypoints: +[backend start.sh](../../docker_images/seedemu-ethexplorer/beaconchain/backend/start.sh) +and [Web start.sh](../../docker_images/seedemu-ethexplorer/eth2-beaconchain-explorer/start.sh). +They run the image's provisioning script and then start their respective +processes. EthExplorer supplies adapted startup command lists, preserving +that sequence and adding storage-host rewriting after provisioning. + +The provisioning scripts generate configuration using defaults such as +`postgres` and `redis`. The bundle's actual services have suffixed Compose +names and configurable static addresses. Those short defaults may no longer +identify the intended dependencies. The adapted scripts insert the assigned +external-network IPs so both applications use the same bundle's storage, +including when its external subnet has been overridden. + +Rewriting happens **after** provisioning because provisioning recreates +`config.yml`; edits made beforehand would be overwritten. Keeping the image's +provisioning step also preserves its runtime-derived chain settings, ports, +credentials, and schema initialization instead of maintaining a second full +YAML template in Python. The provisioning scripts must themselves complete +successfully before this rewrite runs; rewriting afterward cannot repair a +connection failure that occurs during provisioning. + +Internal-network routing is another startup adaptation. Docker initially +supplies a default route, while Beacon/Geth nodes may require the emulator +gateway. `joinInternalNetwork()` records the gateway; +`PreparedContainer.install()` inserts commands to discover the interface and +replace the default route before provisioning and application startup. It +then stages the generated `/start.sh` in a derived image. Both base Dockerfiles +already declare `ENTRYPOINT ["/start.sh"]`, so the replacement script runs at +container startup; assigning `_start_commands` alone does not execute it. + +### What the replacement scripts do + +| Detail | `seedemu_ethexplorer_backend` | `seedemu_ethexplorer_web` | +| --- | --- | --- | +| Command-list constant | `BACKEND_START_SH` | `FRONTEND_START_SH` | +| Shell | `/bin/sh` | `/bin/bash` | +| Provisioning directory | `/app/local_deployment` | `/app/local-deployment` | +| Runtime configuration | `/app/local_deployment/config.yml` | `/app/local-deployment/config.yml` | +| Processes launched in background | `bc eth1indexer`, `bc rewards-exporter`, `bc statistics` | `/app/explorer`, `/app/validator-tagger`, `/app/frontend-data-updater` | + +Both scripts install a `SIGINT` handler, run +`provision-explorer-config-custom.sh`, and exit with status 1 if provisioning +fails. After successful provisioning, `sed -i` rewrites storage endpoints; +a failing `sed` command also exits with status 1. Each process is passed the +corresponding runtime configuration path. The final `while true` loop prints +the date and sleeps to keep the container's main shell alive. This loop does +not monitor background-process health or restart a failed indexer. + +The backend's `eth1indexer` retains `-concurrency 1` and +`-blocks.tracemode 'geth'`; its statistics process enables charts, graffiti, +validators, and deposits. The Web script retains scheduled validator tagging +with `-schedule true` and the frontend data updater. + +### Storage endpoint substitutions + +`configure()` formats `{POSTGRES_HOST}`, `{CLICKHOUSE_HOST}`, `{LBT_HOST}`, +`{RBT_HOST}`, and `{REDIS_HOST}` with their external-network static IPs. + +The replacements target these fields rather than replacing every `host` key: + +| Configuration fields | Replacement | +| --- | --- | +| `readerDatabase.host`, `writerDatabase.host`, `alloyReader.host`, `alloyWriter.host` | PostgreSQL static IP | +| `clickhouse.host` | ClickHouse static IP | +| `bigtable.emulatorHost` | Little Bigtable static IP | +| `rawBigtable.emulatorHost` | Raw Bigtable static IP | +| `redisCacheEndpoint`, `redisSessionStoreEndpoint` | Redis static IP, retaining the existing port suffix | + +Only commands beginning with `sed -i ` receive Python `.format()` expansion. +The other shell lines are copied unchanged, including shell-function braces +and runtime expressions. Each service gets its own copied command list; +formatting does not mutate the shared constants. + +## Service identity + +Registration keys, Compose service keys, container names, hostnames, and build +directories include the suffix. For example, `postgres` with suffix +`.eth.explorer` becomes `postgres.eth.explorer`. `getName()` retains the +logical name; pass the suffixed key to `getContainer()`. Separate instances +also require independent external networks, subnets, and published ports. + diff --git a/docs/designs/internet_map.md b/docs/designs/internet_map.md index c22c94a0d..6e031f4ba 100644 --- a/docs/designs/internet_map.md +++ b/docs/designs/internet_map.md @@ -1,99 +1,95 @@ -# InternetMap design +# InternetMap design -`seedemu.containerBundle.InternetMap` packages the services used to visualize -an emulator: the emulator API service, topology UI, geographic UI, and traffic -observer. It is a `ContainerBundle`, so Docker compiles the bundle only after -the emulator has been rendered. +`seedemu.containerBundle.InternetMap` extends `ContainerBundle` to provide +an emulator API, topology UI, geographic UI, and traffic observer. See the +[ContainerBundle design](container_bundle.md) for shared lifecycle behavior. -## Responsibilities +## Services and construction -The bundle creates four logical services: - -| Service | Role | Network behavior | +| Logical service name | Role | Network behavior | | --- | --- | --- | -| `seedemu_emulator_service_backend` | Exposes emulator REST and WebSocket APIs | Bundle network; optionally emulator network | -| `seedemu_internet_map_toplogy` | Serves the topology frontend | Bundle network | -| `seedemu_internet_map_geographic` | Serves the geographic frontend | Bundle network and `host.docker.internal` | -| `seedemu_traffic_observer_service_backend` | Captures host traffic | Host network mode | +| `seedemu_emulator_service_backend` | REST and WebSocket APIs | Bundle network; optionally emulator network | +| `seedemu_internet_map_toplogy` | Topology frontend | Bundle network | +| `seedemu_internet_map_geographic` | Geographic frontend | Bundle network and `host.docker.internal` mapping | +| `seedemu_traffic_observer_service_backend` | Host traffic capture | `network_mode: host` | + +The constructor accepts `emulator` and `suffix="map.seed"`. It creates four +prepared containers, sets `_default_external_network = DEFAULT_NETWORK`, +requires three host ports, and requests one emulator-network address. Internal +network access starts disabled; construction does not allocate an address. + +Registration keys, Compose service keys, container names, hostnames, and build +folders use the logical name plus the suffix. Use distinct suffixes, external +networks, subnets, and host ports for separate instances. -The traffic observer is deliberately excluded from the bundle bridge network, -because it uses `network_mode: host` and accesses kernel and Docker resources. +## Optional internal network -## Construction and configuration +Call `enableInternalNetwork()` before compilation to enable emulator access: ```python internet_map = InternetMap(emu, ".map.seed") -internet_map.setPorts(list(range(8081, 8089))) +internet_map.enableInternalNetwork() +internet_map.setPorts([8081, 8082, 8083]) docker.addContainerBundle(internet_map) ``` -`InternetMap` creates all four `PreparedContainer` instances in its -constructor. `configure()` requires at least three host ports: one for the -traffic observer and one for each frontend. It assigns static addresses from -the default bridge network, writes the Nginx configuration, and stages -`/etc/hosts` entries for the emulator API hostname. - -The default network can be replaced with `setDefaultNetwork()`. Its address -pool must contain enough addresses for the three bridge-attached containers; -the host-network traffic observer does not consume an address. - -```mermaid -flowchart TD - A[InternetMap constructor] --> B[Create four PreparedContainer objects] - B --> C[setPorts] - C --> D[Docker compiler calls configure] - D --> E[Assign bridge addresses] - E --> F[Configure emulator API and Nginx] - F --> G[Configure traffic observer host networking] - G --> H[Docker compiler calls install] - H --> I[Generate Compose services and container contexts] -``` - -## Optional emulator-network attachment +This method sets a flag and returns the bundle. During `configure()`, only the +API backend joins the internal network. If no manual internal network has +been supplied, `allocateEmuNetworkAddress()` reserves one address on a rendered +host network, starting at network-address offset 10. It skips occupied and +reserved addresses and the gateway. The selected `ip_addresses[0]` and +`default_route` are passed explicitly to `joinInternalNetwork()`, together +with the backend's own hostname. A usable network with enough capacity is +required when this option is enabled. -The normal configuration only needs the bundle bridge network. Some -deployments also need the emulator API container to reach the emulated host -network. The current opt-in API is: +To choose the internal attachment explicitly before compilation: ```python -internet_map.enableEmulatorNetwork() +internet_map.setDefaultInternalNetwork( + name="net_150_net0", + ip_addresses=["10.150.0.10"], + default_route="10.150.0.254", +) +internet_map.enableInternalNetwork() ``` -This attaches `seedemu_emulator_service_backend` to the network returned by -`getEmuHostNetworkInfo()`. The network information contains the network name, -the selected emulator host name and address, and, when available, its default -router. `PreparedContainer.joinInternalNetwork()` stores that attachment and -can add startup commands that replace the container's default route. - -The opt-in call should be made after the emulator has been rendered, so a -usable emulator network is available. If the bundle is extended with more -internal-network consumers, each service should be attached explicitly and -the traffic observer should remain on host networking. - -```mermaid -sequenceDiagram - participant E as Emulator - participant I as InternetMap - participant B as API backend - participant N as Emulator network - E->>E: render() - I->>E: getEmuHostNetworkInfo() - I->>B: joinInternalNetwork(network, host, ip, route) - B->>N: attach second network interface - B->>B: optionally replace default route - B->>N: call emulator API / websocket peers -``` - -`enableEmulatorNetwork()` is intentionally opt-in. Existing examples that do -not call it retain the original bridge-only topology. - -## Reverse proxy and generated files +The manual address must be free; the setter does not reserve or validate it. +When a gateway is supplied, generated startup commands replace the backend's +Docker default route. Its build context is enabled for this startup setup. +Both frontends continue to reach the API through the external bundle network. + +## Configuration and compilation + +`configure()` performs these steps: + +1. Calls the base port validation using the constructor's requirement of three + ports. The observer consumes the last supplied port, the topology frontend + the next, and the geographic frontend the next. The API uses internal port + `7071` without a host-published port. +2. Configures the observer with host networking, privileged mode, host PID, + kernel/BPF mounts, and the Docker socket. It skips bridge attachment. +3. Attaches the API and both frontends to the external bundle network with + static addresses in container creation order. +4. Configures the API image, Docker socket, and production environment, and + attaches its optional internal network. +5. Configures frontend dependencies using the suffixed backend service key. + Both Nginx upstreams target the API's external-network static IP on `7071`. + The geographic proxy also targets the configured traffic-observer endpoint. +6. Stages Nginx configuration and `/etc/hosts` mappings for both frontends. + Their configured startup script path is `/entrypoint.sh`; shared + `PreparedContainer` installation handles startup wrapping and staged files. + +The external network can be overridden before compilation: -The topology and geographic containers run Nginx. Their generated upstream -configuration points to the backend service at port `7071`; the geographic -configuration also proxies traffic-observer requests to the host-published -observer port. `setFile()` stages the Nginx configuration, while `setEtcHosts()` -stages the backend hostname mapping. The generated container entrypoint is -preserved through `PreparedContainer` installation rather than requiring the -base image's original script to be copied into the bundle source. +```python +internet_map.setDefaultExternalNetwork( + name="internetMap_network", + prefix="172.30.0.0/24", + ip_addresses=[f"172.30.0.{i}" for i in range(10, 14)], + default_router="172.30.0.1", +) +``` +The address list must cover all four prepared containers, although the +observer's entry remains unused because it uses host networking. The compiler +calls `configure()` and `install()` to generate build contexts and Compose YAML. diff --git a/examples/basic/A10b_add_containers/README.md b/examples/basic/A10b_add_containers/README.md new file mode 100644 index 000000000..54564bb5b --- /dev/null +++ b/examples/basic/A10b_add_containers/README.md @@ -0,0 +1,230 @@ +# A10b: Custom ContainerBundle + +This example demonstrates how to attach a custom group of Docker containers to a SEED Emulator using `ContainerBundle`. + +The example builds three autonomous systems connected through Internet Exchange 100. It then renders the emulator, creates a `DemoContainerBundle`, configures its networks and ports, and registers it with the Docker compiler. + +## Running + +```bash +cd examples/basic/A10b_add_containers +python add_containerBundle.py +``` + +The generated Docker files are written to `output`. Start them with: + +```bash +cd output +docker compose up --build +``` + +The bundle maps host port `8090` to container port `8080`. The demo prints a +message and sleeps; it does not start an HTTP server. Pass `amd` (the default) +or `arm` as the script argument to select the target platform. + +## Bundle lifecycle + +Import the bundle classes from `seedemu.containerBundle`: + +```python +from seedemu.containerBundle import ContainerBundle +``` + +The normal lifecycle is: + +```text +create bundle -> configure bundle -> register bundle -> compile emulator +``` + +`docker.addContainerBundle(bundle)` registers the bundle. During `emu.compile()`, the compiler calls the bundle's `configure()` and `install()` methods to generate Compose services, networks, Dockerfiles, startup scripts, and staged files. + +## ContainerBundle API + +Useful bundle methods include: + +```python +bundle.getContainer("service-name" + bundle.getSuffix()) +bundle.getContainers() +bundle.getEmulator() +bundle.getSuffix() +bundle.getDefaultExternalNetwork() +bundle.setDefaultInternalNetwork("net_151_net0", ["10.151.0.16"], "10.151.0.254") +bundle.getDefaultInternalNetwork() +bundle.setPorts([8090]) +bundle.getPorts() +bundle.getInternalHostnameIpMappings() +bundle.getExternalHostnameIpMappings() +``` + +`getContainer()` returns a `PreparedContainer`. A custom bundle can configure it with: + +```python +container.setContentAttribute({"image": "busybox:latest"}) +container.joinInternalNetwork(network, hostname, ip_address, default_route) +container.joinExternalNetwork(network, hostname, ip_address) +container.setFile("/start.sh", "#!/bin/sh\n...") +container.setEtcHosts("10.0.0.10 example\n") +``` + +`setContentAttribute()` updates the Compose service definition. The network methods add network attachments and static addresses. `setFile()` stages a file for the generated image, and `setEtcHosts()` stages host entries that are appended during startup. + +## Custom bundle pattern + +This example also defines `DemoContainerBundle`, a concrete subclass that is +defined in this example. It creates two `PreparedContainer` +instances and demonstrates the main extension points in one run: + +- `setContentAttribute()` and static external-network attachments +- `getContainer()`, `getContainers()`, `getSuffix()`, and network mapping accessors +- `allocateEmuNetworkAddress()`, `getDefaultInternalNetwork()`, and explicit + `joinInternalNetwork()` arguments +- `setEtcHosts()` and `setFile()` for generated container files +- `setEntrypointWrapper()` for startup commands and a custom entrypoint + +The demo bundle uses a separate `172.31.0.0/24` bridge network and publishes +one host port. The script explicitly attaches `demo-app` to `net_151_net0` at +`10.151.0.16`, with gateway `10.151.0.254`. If this manual selection is removed, +`configure()` attempts automatic allocation. Internal attachment is required +by this demo; it is not skipped on allocation failure. + +```python +class ExampleBundle(ContainerBundle): + def __init__(self, emulator, suffix=".example"): + super().__init__(emulator=emulator, suffix=suffix) + self._createContainer("example-service", suffix) + + def configure(self): + self._required_port_number = 1 + super().configure() + service = self.getContainer("example-service" + self.getSuffix()) + service.setContentAttribute({ + "image": "busybox:latest", + "command": "sleep infinity", + }) +``` + +Subclasses create containers in `__init__`, configure their services in `configure()`, and should call `super().configure()` so port validation is preserved. + +### Detailed `DemoContainerBundle` walkthrough + +`DemoContainerBundle` creates two `PreparedContainer` objects in its +constructor: + +```python +class DemoContainerBundle(ContainerBundle): + def __init__(self, emulator, suffix=".demo.seed"): + super().__init__(emulator=emulator, suffix=suffix) + self._createContainer("demo-app", suffix) + self._createContainer("demo-helper", suffix) + self._required_emu_network_address_number = 1 + self._required_port_number = 1 +``` + +`demo-app` is the main service and publishes a host port. `demo-helper` is a +second service used to demonstrate hostname mappings. The suffix is appended +to registration keys, Compose service keys, container names, hostnames, and +build-context directories. The services are `demo-app.demo.seed` and +`demo-helper.demo.seed`. + +The constructor sets both required counts to `1`. During `configure()`, it calls +`super().configure()` for port validation, obtains its prepared containers, +and assigns Compose attributes. The app consumes one port from the configured +pool and maps it to container port `8080`; the helper stays alive with +`sleep infinity`. + +The complete registration code is: + +```python +demo_bundle = DemoContainerBundle(emu, ".demo.seed") +demo_bundle.setDefaultExternalNetwork( + name="demo_bundle_network", + prefix="172.31.0.0/24", + ip_addresses=["172.31.0.10", "172.31.0.11"], + default_router="172.31.0.1", +) +demo_bundle.setPorts([8090]) +demo_bundle.setDefaultInternalNetwork( + name="net_151_net0", + ip_addresses=["10.151.0.16"], + default_route="10.151.0.254", +) +demo_bundle.getInternalHostnameIpMappings() +demo_bundle.getExternalHostnameIpMappings() +docker.addContainerBundle(demo_bundle) +``` + +The calls perform these steps: + +1. `DemoContainerBundle(emu, ".demo.seed")` creates and registers the two + prepared services. +2. `setDefaultExternalNetwork()` creates the private `172.31.0.0/24` bridge network. + Addresses are assigned in creation order: `demo-app` receives + `172.31.0.10`, and `demo-helper` receives `172.31.0.11`. +3. `setPorts([8090])` supplies the host-port pool. The app consumes `8090`, + producing the mapping `8090:8080`. +4. `setDefaultInternalNetwork()` stores the manual internal attachment. The + network must exist and the address must be free; the setter does not + validate or reserve addresses. +5. The mapping accessors return copies of hostname/IP mappings. These are + empty before compilation because no containers have joined networks yet. +6. `docker.addContainerBundle()` registers the bundle. It does not start + containers; `emu.compile()` later calls `configure()` and `install()`. + +The custom bundle uses its own Docker network (`172.31.0.0/24`) and host port (`8090`). + +Inside `configure()`, both containers join the custom network with static +addresses. The app uses the manual internal selection when supplied; otherwise +it requests one automatically: + +```python +if not self._default_internal_network: + self.allocateEmuNetworkAddress() +app.joinInternalNetwork( + hostname=app.getHostname(), + network=self._default_internal_network["network"], + ip_address=self._default_internal_network["ip_addresses"][0], + default_route=self._default_internal_network["default_route"], +) +``` + +`allocateEmuNetworkAddress()` returns the bundle on success, or `None` when no +network has enough capacity. It stores an internal network dictionary with an +`ip_addresses` list. Allocation starts at network-address offset 10 and skips +occupied and reserved addresses. Select one address for `joinInternalNetwork()`. +The app receives a second network attachment and route setup through the +supplied gateway; the helper remains on the bundle network. The current code +does not check allocation failure before reading the stored dictionary, so +automatic mode requires a rendered host network with enough capacity. + +The example also demonstrates generated files and startup wrapping: + +```python +app.setEtcHosts(f"{helper.getHostname()} {network['ip_addresses'][1]}\n") +app.setFile( + "/usr/local/bin/demo-message.sh", + "#!/bin/sh\necho 'ContainerBundle demo is running'\n", +) +app.setEntrypointWrapper( + original_entrypoint="/bin/sh", + commands=[ + "echo \"service=$0 hostname=$(hostname)\"", + "sleep infinity", + ], +) +``` + +`setEtcHosts()` stages host entries for startup, `setFile()` adds a file to the +generated image context, and `setEntrypointWrapper()` runs preparation commands +before delegating to the base image entrypoint. +The staged `demo-message.sh` is not executed by the wrapper. The wrapper prints +the service/hostname message and runs `sleep infinity`. + +## Troubleshooting + +- Too few ports: call `setPorts()` before registering the bundle. +- Invalid static addresses: check subnet membership, uniqueness, and gateway exclusion. +- Network reachability problems: render the emulator before compilation and verify the emulated host's default route. +- Port conflicts: choose a different host-port range and regenerate `output`. +- Manual attachment failure: verify `net_151_net0`, the availability of + `10.151.0.16`, and gateway `10.151.0.254` in the rendered topology. +- No HTTP response on `8090`: the demo publishes a port but starts no server. diff --git a/examples/basic/A10b_add_containers/add_containerBundle.py b/examples/basic/A10b_add_containers/add_containerBundle.py new file mode 100644 index 000000000..154860d3a --- /dev/null +++ b/examples/basic/A10b_add_containers/add_containerBundle.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +# encoding: utf-8 + +from seedemu.compiler import Docker, Platform +from seedemu.core import Emulator +import sys, os +from examples.internet.B00_mini_internet import mini_internet +from seedemu.containerBundle import ContainerBundle + + +class DemoContainerBundle(ContainerBundle): + """! + @brief Small bundle demonstrating ContainerBundle extension points. + """ + + def __init__(self, emulator, suffix=".demo.seed"): + """! + @brief Create the demonstration bundle and its containers. + + @param emulator emulator to which this bundle is attached. + @param suffix suffix appended to generated container hostnames. + """ + super().__init__(emulator=emulator, suffix=suffix) + self._createContainer("demo-app", suffix) + self._createContainer("demo-helper", suffix) + # Only demo-app needs an internal address and a published host port. + self._required_emu_network_address_number = 1 + self._required_port_number = 1 + + def configure(self): + """! + @brief Configure services, networks, files and startup routing. + + @raises RuntimeError when no default bundle network was configured. + @raises ValueError when the configured host-port pool is too small. + """ + super().configure() + + network = self.getDefaultExternalNetwork() + if network is None: + raise RuntimeError("DemoContainerBundle requires a default network") + + # Registration keys include the suffix; getName() keeps the logical name. + containers = self.getContainers() + app = self.getContainer("demo-app" + self._suffix) + helper = containers["demo-helper" + self._suffix] + app.getName() + app.getHostname() + + app.setContentAttribute( + { + "image": "debian:bookworm-slim", + "environment": {"DEMO_SUFFIX": self.getSuffix()}, + "ports": [f"{self._ports.pop()}:8080"], + "build": f"./{app.getHostname()}", + } + ) + helper.setContentAttribute( + { + "image": "debian:bookworm-slim", + "command": "sleep infinity", + } + ) + + app.joinExternalNetwork(network["name"], app.getHostname(), network["ip_addresses"][0]) + helper.joinExternalNetwork( + network["name"], helper.getHostname(), network["ip_addresses"][1] + ) + + # Prefer the caller's manual internal network. Otherwise reserve one + # free address from a rendered host network, starting at host offset 10. + # Allocation stores the dictionary and returns self, not a dictionary. + # This demo requires allocation to succeed; it has no failure fallback. + if not self._default_internal_network: + self.allocateEmuNetworkAddress() + app.joinInternalNetwork( + hostname=app.getHostname(), + network=self._default_internal_network["network"], + ip_address=self._default_internal_network["ip_addresses"][0], + default_route=self._default_internal_network["default_route"], + ) + + # Inspect mappings after the network attachments have been configured. + app.getInternalHostnameIpMappings() + app.getExternalHostnameIpMappings() + helper.getExternalHostnameIpMappings() + + app.setEtcHosts(f"{helper.getHostname()} {network['ip_addresses'][1]}\n") + # Stage this script in the image; the wrapper does not execute it. + app.setFile( + "/usr/local/bin/demo-message.sh", + "#!/bin/sh\necho 'ContainerBundle demo is running'\n", + ) + # Keep the demo alive after printing a message. No HTTP server is + # started on the published container port 8080. + app.setEntrypointWrapper( + original_entrypoint="/bin/sh", + commands=[ + 'echo "service=$0 hostname=$(hostname)"', + "sleep infinity", + ], + ) + + +# Set the platform information +script_name = os.path.basename(__file__) + +platform = None +if len(sys.argv) == 1: + platform = Platform.AMD64 +elif len(sys.argv) == 2: + if sys.argv[1].lower() == "amd": + platform = Platform.AMD64 + elif sys.argv[1].lower() == "arm": + platform = Platform.ARM64 + else: + print(f"Usage: {script_name} amd|arm") + sys.exit(1) +else: + print(f"Usage: {script_name} amd|arm") + sys.exit(1) + +mini_internet.run(dumpfile="./base_internet.bin") + +emu = Emulator() + +# Load the pre-built component +emu.load("./base_internet.bin") + +# Render the emulation +emu.render() + +docker = Docker(platform=platform) +# Register a custom bundle. The demo bundle shows +# how to configure service attributes, attach containers to external and +# emulator networks, stage files and /etc/hosts entries, and wrap an +# image entrypoint. It uses a separate Docker network and port. +demo_bundle = DemoContainerBundle(emu, ".demo.seed") +demo_bundle.setDefaultExternalNetwork( + name="demo_bundle_network", + prefix="172.31.0.0/24", + ip_addresses=["172.31.0.10", "172.31.0.11"], + default_router="172.31.0.1", +) +demo_bundle.setPorts([8090]) +# Select the application's second interface and emulator gateway explicitly. +# The network must exist and the address must be free: this setter neither +# validates nor reserves it. Remove this call to use automatic allocation. +demo_bundle.setDefaultInternalNetwork( + name="net_151_net0", ip_addresses=["10.151.0.16"], default_route="10.151.0.254" +) +# These mappings are empty before configure() attaches the containers. +# Inspect them after compilation to see the configured hostname/IP mappings. +demo_bundle.getInternalHostnameIpMappings() +demo_bundle.getExternalHostnameIpMappings() +docker.addContainerBundle(demo_bundle) +############################################################################### +# Compilation +emu.compile(docker, "./output", override=True) diff --git a/examples/blockchain/D01_ethereum_pos/ethereum_pos.py b/examples/blockchain/D01_ethereum_pos/ethereum_pos.py index 60b38825e..353b3e692 100755 --- a/examples/blockchain/D01_ethereum_pos/ethereum_pos.py +++ b/examples/blockchain/D01_ethereum_pos/ethereum_pos.py @@ -194,22 +194,6 @@ def run( # Add Internet visualization services: topology, geographic map, and traffic observation. # The second argument is a container name suffix that distinguishes bundle instances. internet_map_bundle = InternetMap(emu, ".map.seed") - # Customize the bundle network; provide at least one IP per container, in creation order. - # All IPs must belong to the configured subnet, which should not overlap other networks. - internet_map_bundle.setDefaultNetwork( - name="internetMap_network", - prefix=".map", - ip_addresses=[ - "172.30.0.10", - "172.30.0.11", - "172.30.0.12", - "172.30.0.13", - ], - network_config={ - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.30.0.0/24", "gateway": "172.30.0.1"}]}, - }, - ) # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. internet_map_bundle.setPorts(list(range(8081, 8089))) # Register the bundle with the Docker compiler to generate its containers during emu.compile(). @@ -217,24 +201,6 @@ def run( # Add an Ethereum explorer with an indexing backend, a Web frontend, and supporting services. eth_explorer_bundle = EthExplorer(emu, ".eth.explorer.seed") - # Configure a separate explorer network with one static IP per container. - eth_explorer_bundle.setDefaultNetwork( - name="ethExplorer_network", - prefix=".eth", - ip_addresses=[ - "172.20.0.10", - "172.20.0.11", - "172.20.0.12", - "172.20.0.13", - "172.20.0.14", - "172.20.0.15", - "172.20.0.16", - ], - network_config={ - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.20.0.0/24", "gateway": "172.20.0.1"}]}, - }, - ) # The explorer Web frontend needs at least 1 host port; ports are taken from the list's end. eth_explorer_bundle.setPorts(list(range(8090, 8099))) # Include the explorer bundle in this Docker compilation. diff --git a/examples/blockchain/D10_eth_explorer/README.md b/examples/blockchain/D10_eth_explorer/README.md index e872f716c..e096e8f5b 100644 --- a/examples/blockchain/D10_eth_explorer/README.md +++ b/examples/blockchain/D10_eth_explorer/README.md @@ -2,7 +2,7 @@ This example builds an Ethereum PoS private network and attaches the explorer implemented by [`EthExplorer`](../../../seedemu/containerBundle/EthExplorer.py). The explorer indexes execution-layer and consensus-layer data and provides a Web UI for blocks, transactions, epochs, slots, and validators. -The D10 entry point, [`ethereum_pos.py`](ethereum_pos.py), delegates network construction and bundle registration to [D01](../D01_ethereum_pos/ethereum_pos.py). D01 creates Geth/Beacon node pairs, validator clients, a Beacon setup node, and an Internet topology. It registers both `InternetMap` and `EthExplorer` with the Docker compiler. +The D10 entry point, [`ethereum_pos.py`](ethereum_pos.py), contains the complete example. It creates the Geth/Beacon node pairs, validator clients, Beacon setup node, Internet topology, and both container bundles. D01 is not required to run this example. ## Run this example @@ -17,24 +17,31 @@ docker compose up --build The legacy invocation `python ethereum_pos.py 3 amd` is also supported. `--platform arm` selects ARM64 output; the explorer images must also support the target architecture. `--output` changes the generated directory. `--dumpfile` saves the emulator and returns before rendering or compiling bundles. -With the current D01 port configuration, open the explorer at **http://127.0.0.1:8098**. D01 supplies `list(range(8090, 8099))`, and EthExplorer takes the last port, `8098`. The container listens on port `5000` internally. Startup and initial indexing can take time. +The example supplies `list(range(8090, 8099))` to `EthExplorer`, which takes the last port, `8098`. Open the explorer at **http://127.0.0.1:8098**. The container listens on port `5000` internally. Startup and initial indexing can take time. ## Attach EthExplorer to an existing emulator -Import the bundle from `seedemu.containerBundle`. Create it after rendering the emulator, register it with the Docker compiler, and compile: +The example creates the emulator locally and then configures the bundle: ```python -from seedemu import Platform -from seedemu.compiler import Docker -from seedemu.containerBundle import EthExplorer +from seedemu import * -# emu is an existing emulator with a configured EthereumService PoS chain. -# Render first so host interfaces and Ethereum bootnode IPs are available. -emu.render() - -docker = Docker(platform=Platform.AMD64) +emu = build_emulator(total_beacon_nodes=3, vc_per_beacon=3) explorer = EthExplorer(emu, ".eth.explorer.seed") + +explorer.setDefaultExternalNetwork( + name="ethExplorer_network", + prefix="172.20.0.0/24", + ip_addresses=[ + "172.20.0.10", "172.20.0.11", "172.20.0.12", + "172.20.0.13", "172.20.0.14", "172.20.0.15", + "172.20.0.16", + ], + default_router="172.20.0.1", +) explorer.setPorts([8090]) + +docker = Docker(platform=Platform.AMD64) docker.addContainerBundle(explorer) emu.compile(docker, "./output", override=True) ``` @@ -43,7 +50,7 @@ Then run `docker compose up --build` inside `output` and open `http://127.0.0.1: `Docker.addContainerBundle()` registers the bundle. During compilation, the compiler calls `configure()` and then `install()` to produce the Compose services, network definitions, build directories, startup scripts, and configuration files. Application code normally does not call these lifecycle methods directly. Configure and compile a fresh bundle for each build: configuration consumes ports and modifies startup scripts. -The current integration uses `addContainerBundle()`. The older `Docker(etherViewEnabled=True, etherViewPort=...)` examples do not describe this bundle API. +The current integration uses `addContainerBundle()`. The `--ether-view` and `--no-ether-view` switches remain accepted for compatibility with existing scripts; this example always registers `EthExplorer` in its `run()` function. ## Constructor and prerequisites @@ -58,18 +65,30 @@ explorer = EthExplorer(emulator=emu, suffix=".eth.explorer.seed") The emulator must contain an `EthereumService` with at least one blockchain. Automatic node selection requires that blockchain to expose Beacon and Geth bootnode IPs. Geth HTTP RPC and the Beacon API must be enabled and reachable from the explorer containers. -The constructor also finds the first registered host interface with an IP address and records its network and default router. The backend and Web containers later join this emulated network and route through that router to reach the chain nodes. Provide a rendered topology with a usable host interface and gateway; setting RPC host addresses alone does not create network connectivity. +The constructor records the requirement for two internal addresses; it does +not scan interfaces or allocate them. `configure()` later selects a rendered +host network unless a manual internal network is already set. The backend +and Web containers join that network and use its gateway to reach chain nodes. +Setting RPC host addresses alone does not create network connectivity. + +The suffix applies to Compose service keys, `container_name` values, hostnames, +and build directories. D10 uses `.eth.explorer.seed`, producing names such as +`postgres.eth.explorer.seed`. Multiple explorer bundles also need distinct +external networks, subnets, and host ports. -The suffix changes generated hostnames/build directories. Compose service keys and `container_name` values remain fixed names such as `postgres` and `seedemu-ethexplorer-web`; a different suffix alone does not isolate multiple explorer bundles in one Compose project. +For the differences between `EthExplorer` and `ContainerBundle`, detailed +`__init__()` and `configure()` behavior, the four Beacon/Geth host APIs, and +the backend/Web start-script changes and their reasons, see the +[EthExplorer design document](../../../docs/designs/eth_explorer.md). ## Configure the bundle network -EthExplorer already provides a default bridge network, so `setDefaultNetwork()` is optional. The current default is: +EthExplorer already provides a default bridge network, so `setDefaultExternalNetwork()` is optional. The current default is: ```python network = { "name": "ethExplorer_network", - "prefix": ".eth", + "prefix": "172.20.0.0/24", "ip_addresses": [ "172.20.0.10", "172.20.0.11", @@ -79,28 +98,28 @@ network = { "172.20.0.15", "172.20.0.16", ], - "network_config": { - "driver": "bridge", - "ipam": { - "config": [{"subnet": "172.20.0.0/24", "gateway": "172.20.0.1"}] - }, - }, + "default_router": "172.20.0.1", } # Optional: override the default before compilation. -explorer.setDefaultNetwork(**network) +explorer.setDefaultExternalNetwork(**network) ``` -The dictionary is expanded into keyword arguments. The equivalent call is `explorer.setDefaultNetwork(name=..., prefix=..., ip_addresses=..., network_config=...)`. +The dictionary is expanded into keyword arguments. The equivalent call is `explorer.setDefaultExternalNetwork(name=..., prefix=..., ip_addresses=..., default_router=...)`. | Field | Meaning | | --- | --- | | `name` | Compose network key used by all seven bundle services. | -| `prefix` | Stored network metadata; the current EthExplorer implementation does not use it to generate hostnames or allocate addresses. It is separate from the constructor's `suffix`. | +| `prefix` | IPv4 subnet in CIDR notation. It is used as the Docker network subnet. | | `ip_addresses` | Static IPv4 addresses assigned in container creation order. | -| `network_config` | Compose network configuration, including bridge driver, subnet, and gateway. Pass a dictionary; the setter calls `.copy()` on it. | +| `default_router` | IPv4 gateway address for the Docker network. | -`ip_addresses` must be nonempty and contain at least as many entries as `explorer.getContainers()`. The current bundle contains **seven containers**, so fewer than seven addresses trigger an assertion in `setDefaultNetwork()`. Extra addresses are unused. Supply unique addresses within the configured subnet, exclude the gateway, and avoid overlap with the emulated topology or other Docker networks. The assertions check presence and count; they do not validate subnet membership or uniqueness. +`ip_addresses` must be nonempty and contain at least as many entries as +`explorer.getContainers()`. The bundle contains **seven containers**. Invalid +subnets, gateways, insufficient addresses, duplicate addresses, addresses +outside the subnet, or addresses equal to the gateway, network, or broadcast +address raise `ValueError`. Extra addresses are unused. Avoid overlap with +the emulated topology and other Docker networks. Default address assignment: @@ -114,7 +133,15 @@ Default address assignment: | 6 | `seedemu-ethexplorer-backend` | `172.20.0.15` | Indexing, rewards, and statistics | | 7 | `seedemu-ethexplorer-web` | `172.20.0.16` | Explorer UI and frontend update tasks | -All services join the bundle bridge network. The backend and Web service additionally join the selected emulated host network. When serializing Compose, the bundle uses `network_config` for its network and avoids redeclaring emulator-owned networks. +All services join the bundle bridge network. The backend and Web service additionally join the selected emulated host network. The bundle derives the Compose network configuration from `prefix` and `default_router`. + +During `configure()`, the bundle reserves two free internal addresses on one +rendered host network, starting at network-address offset 10. The backend uses +`ip_addresses[0]` and the Web service uses `ip_addresses[1]`. Allocation skips +occupied addresses, the gateway, and reservations shared with other bundles. +To choose the network manually, call +`explorer.setDefaultInternalNetwork(name, ip_addresses, default_route)` with +two free addresses before compilation. This setter does not reserve them. ## Select Beacon and Geth nodes @@ -154,7 +181,9 @@ Only one port is used by EthExplorer. Additional ports in the list do not publis ## Configuration templates and startup -`BACKEND_CONFIG_YML` and `FRONTEND_CONFIG_YML` are defined in `EthExplorer.py`. During `configure()`, Python `.format()` replaces these five placeholders with the corresponding service's static IP: +`BACKEND_START_SH` and `FRONTEND_START_SH` are defined in `EthExplorer.py`. +During `configure()`, Python `.format()` replaces these five placeholders in +their `sed` commands with the corresponding service's static IP: | Placeholder | Service | | --- | --- | @@ -164,11 +193,11 @@ Only one port is used by EthExplorer. Additional ports in the list do not publis | `{LBT_HOST}` | `littlebigtable` | | `{RBT_HOST}` | `rawbigtable` | -Other placeholders, such as `$EL_HOST`, `$CL_HOST`, `$POSTGRES_DB`, `$GENESIS_TIMESTAMP`, and `$SERVER_PORT`, remain in shell-style form after Python formatting. The formatted templates are written into each container at `/tmp/config.yml`. - -The backend uses `/app/local_deployment`; the Web service uses `/app/local-deployment`. Each startup script configures its route and runs `provision-explorer-config-custom.sh`, then copies `/tmp/config.yml` over the runtime `config.yml` in its deployment directory. The backend starts `eth1indexer`, `rewards-exporter`, and `statistics`; the Web container starts `explorer`, `validator-tagger`, and `frontend-data-updater`. +Runtime configuration is generated by the image's provisioning script. Python +formats only the host-replacement commands; it does not stage configuration +templates at `/tmp/config.yml`. -**Current implementation detail:** the copy of `/tmp/config.yml` is a plain `cat`, with no explicit shell substitution at that step. Therefore, the remaining `$...` placeholders are preserved in the copied file. If startup reports invalid configuration values, inspect the generated file and the image's configuration-loading behavior rather than assuming that Python formatting or the copy expanded those variables. +The backend uses `/app/local_deployment`; the Web service uses `/app/local-deployment`. Each startup script configures its route and runs `provision-explorer-config-custom.sh`, then replaces the database, cache, Bigtable, and ClickHouse host entries in the generated runtime `config.yml` with the static IPs assigned by `EthExplorer`. The backend starts `eth1indexer`, `rewards-exporter`, and `statistics`; the Web container starts `explorer`, `validator-tagger`, and `frontend-data-updater`. Compose health checks gate startup on ClickHouse, Postgres, and Redis. The Bigtable services must be started. The Web service also waits for the backend health check, which checks for the Postgres `blocks` table; this does not guarantee that chain indexing has caught up. @@ -181,24 +210,24 @@ From the generated output directory: ```bash docker compose config docker compose ps -docker compose logs -f seedemu-ethexplorer-backend seedemu-ethexplorer-web +docker compose logs -f seedemu-ethexplorer-backend.eth.explorer.seed seedemu-ethexplorer-web.eth.explorer.seed ``` | Symptom | What to check | | --- | --- | -| IP assertion during `setDefaultNetwork()` | Supply a nonempty list with at least seven IP addresses. | +| Address validation error during `setDefaultExternalNetwork()` | Supply at least seven unique usable addresses in the subnet, excluding the gateway. | | Missing port error during compilation | Call `setPorts([host_port])` before compiling. | | Missing blockchain or bootnode lookup failure | Render the emulator, configure the Ethereum service and bootnodes, or set explicit node hosts. | | Network or route setup failure | Check the selected emulated host interface, its gateway, subnet overlap, and reachability of the chain nodes. | | Cannot open the Web UI | Check the last supplied host port, port conflicts, Compose status, and backend health. D10 currently uses `8098`, not `5000`. | | UI has no chain data | Wait for chain genesis and indexing, then inspect Geth RPC, Beacon API, database health, and explorer logs. | -| Invalid YAML values or literal `$...` in configuration | Inspect `/tmp/config.yml` and the copied runtime config; confirm how the image resolves the remaining placeholders. | +| Invalid YAML values or host connection failures | Inspect the generated runtime configuration and verify the assigned bundle-network IPs. | To inspect the effective runtime configuration: ```bash -docker compose exec seedemu-ethexplorer-backend cat /app/local_deployment/config.yml -docker compose exec seedemu-ethexplorer-web cat /app/local-deployment/config.yml +docker compose exec seedemu-ethexplorer-backend.eth.explorer.seed cat /app/local_deployment/config.yml +docker compose exec seedemu-ethexplorer-web.eth.explorer.seed cat /app/local-deployment/config.yml ``` InternetMap complements the explorer by showing network topology and connectivity; EthExplorer shows chain state and indexing results. Register and configure each bundle separately, with nonoverlapping networks and host ports. diff --git a/examples/blockchain/D10_eth_explorer/ethereum_pos.py b/examples/blockchain/D10_eth_explorer/ethereum_pos.py index 8d373f7ea..26213141b 100644 --- a/examples/blockchain/D10_eth_explorer/ethereum_pos.py +++ b/examples/blockchain/D10_eth_explorer/ethereum_pos.py @@ -7,23 +7,19 @@ from pathlib import Path import sys - SCRIPT_DIR = Path(__file__).resolve().parent REPO_ROOT = SCRIPT_DIR.parents[2] if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) -from seedemu import Platform -from examples.blockchain.D01_ethereum_pos import ethereum_pos as d01_ethereum_pos +from seedemu import * + +DOMAIN = ".net" def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser(description="Build the D10 Ethereum PoS EthExplorer example.") - parser.add_argument( - "legacy_args", - nargs="*", - help="legacy form: [amd|arm]", - ) + parser = argparse.ArgumentParser(description="Build the D01 Ethereum PoS example.") + parser.add_argument("legacy_platform", nargs="?", choices=["amd", "arm"]) parser.add_argument("--platform", choices=["amd", "arm"]) parser.add_argument("--output", default=str(SCRIPT_DIR / "output")) parser.add_argument("--dumpfile") @@ -39,31 +35,24 @@ def parse_args() -> argparse.Namespace: default=3, help="validator clients per beacon node", ) + parser.add_argument( + "--ether-view", + dest="ether_view_enabled", + action="store_true", + default=True, + help="enable Eth Explorer output in generated Docker files (default)", + ) + parser.add_argument( + "--no-ether-view", + dest="ether_view_enabled", + action="store_false", + help="disable Eth Explorer output; useful for CI builds", + ) parser.add_argument("--override", dest="override", action="store_true", default=True) parser.add_argument("--no-override", dest="override", action="store_false") parser.add_argument("--skip-render", dest="render", action="store_false", default=True) args = parser.parse_args() - - if len(args.legacy_args) > 2: - parser.error("legacy arguments must be: [amd|arm]") - - legacy_platform = None - if args.legacy_args: - first = args.legacy_args[0].lower() - if first in ("amd", "arm"): - legacy_platform = first - else: - try: - args.beacon_nodes = int(first) - except ValueError: - parser.error("legacy beacon node count must be an integer") - - if len(args.legacy_args) == 2: - legacy_platform = args.legacy_args[1].lower() - if legacy_platform not in ("amd", "arm"): - parser.error("legacy platform must be amd or arm") - - args.platform = args.platform or legacy_platform or "amd" + args.platform = args.platform or args.legacy_platform or "amd" if args.beacon_nodes < 1: parser.error("--beacon-nodes must be >= 1") if args.validators_per_beacon < 1: @@ -75,6 +64,111 @@ def resolve_platform(name: str) -> Platform: return Platform.AMD64 if name == "amd" else Platform.ARM64 +def build_emulator(total_beacon_nodes: int = 3, vc_per_beacon: int = 3) -> Emulator: + ############################################################################### + # Configure the number of nodes + geth_node_number = total_beacon_nodes + beacon_node_number = total_beacon_nodes + vc_node_number = vc_per_beacon * beacon_node_number + # Create Emulator Base with 10 Stub AS (150-154, 160-164) using Makers utility method. + # hosts_per_stub_as=3 : create 3 hosts per one stub AS. + # It will create hosts(physical node) named `host_{}`.format(counter), counter starts from 0. + hosts_per_stub_as = 3 + emu = Makers.makeEmulatorBaseWith10StubASAndHosts(hosts_per_stub_as=hosts_per_stub_as) + + # Create the Ethereum layer + eth = EthereumService() + # Create the Blockchain layer which is a sub-layer of Ethereum layer. + # chainName="pos": set the blockchain name as "pos" + # consensus="ConsensusMechnaism.POS" : set the consensus of the blockchain as "ConsensusMechanism.POS". + # supported consensus option: ConsensusMechanism.POA, ConsensusMechanism.POW, ConsensusMechanism.POS + blockchain = eth.createBlockchain(chainName="pos", consensus=ConsensusMechanism.POS) + # Generate a list of wallet-compatible local accounts and prefund them. + accounts_total = 10 + pre_funded_amount = 1000000 + mnemonic = "gentle always fun glass foster produce north tail security list example gain" + blockchain.addLocalAccountsFromMnemonic( + mnemonic=mnemonic, + total=accounts_total, + balance=pre_funded_amount, + ) + asns = [150, 151, 152, 153, 154, 160, 161, 162, 163, 164] + geth_nodes: List[PoSGethServer] = [] + beacon_nodes: List[PoSBeaconServer] = [] + vc_nodes: List[PoSVcServer] = [] + # Create the BeaconSetupNode + beaconsetupServer: PoSBeaconSetupServer = blockchain.createBeaconSetupNode(f"BeaconSetupNode") + emu.getVirtualNode(f"BeaconSetupNode").setDisplayName("Ethereum-POS-BeaconSetup") + for i in range(geth_node_number): + gethServer: PoSGethServer = blockchain.createGethNode(f"gethnode{i}") + gethServer.enableGethHttp() + gethServer.appendClassName(f"Ethereum-POS-Geth-{i+1}") + gethServer.addHostName(f"gethnode{i}" + DOMAIN) + geth_nodes.append(gethServer) + emu.getVirtualNode(f"gethnode{i}").setDisplayName(f"Ethereum-POS-Geth-{i+1}") + + # Create Beacon nodes and connect to Geth nodes + for i in range(beacon_node_number): + beaconServer: PoSBeaconServer = blockchain.createBeaconNode(f"beaconnode{i}") + beaconServer.appendClassName(f"Ethereum-POS-Beacon-{i+1}") + beaconServer.connectToGethNode(f"gethnode{(i+1)%len(geth_nodes)}") + beacon_nodes.append(beaconServer) + emu.getVirtualNode(f"beaconnode{i}").setDisplayName(f"Ethereum-POS-Beacon-{i+1}") + + # Set boot nodes + geth_nodes[0].setBootNode(True) + beacon_nodes[0].setBootNode(True) + + # Create Validator nodes and connect to Beacon nodes + for i in range(vc_node_number): + VcServer: PoSVcServer = blockchain.createVcNode(f"vcnode{i}") + VcServer.appendClassName(f"Ethereum-POS-Validator-{i+1}") + VcServer.connectToBeaconNode(f"beaconnode{(i+1)%len(beacon_nodes)}") + VcServer.enablePOSValidatorAtGenesis() + vc_nodes.append(VcServer) + emu.getVirtualNode(f"vcnode{i}").setDisplayName(f"Ethereum-POS-Validator-{i+1}") + + faucet_geth_node = "gethnode{}".format(1 if geth_node_number > 1 else 0) + utility_geth_node = "gethnode{}".format(2 if geth_node_number > 2 else geth_node_number - 1) + + # Create the Faucet server + faucet: FaucetServer = blockchain.createFaucetServer( + vnode="faucet", + port=80, + linked_eth_node=faucet_geth_node, + balance=10000, + max_fund_amount=10, + ) + faucet.setDisplayName("Faucet") + faucet.addHostName("faucet" + DOMAIN) + # Create the Utility server + util_server: EthUtilityServer = blockchain.createEthUtilityServer( + vnode="utility", port=5000, linked_eth_node=utility_geth_node, linked_faucet_node="faucet" + ) + util_server.setDisplayName("UtilityServer") + util_server.addHostName("utility" + DOMAIN) + + # Add Ethereum service to the emulator + emu.addLayer(eth) + + # Bind all virtual servers (including faucet/utility) to physical hosts + for _, servers in blockchain.getAllServerNames().items(): + for server in servers: + emu.addBinding(Binding(server, filter=Filter(nodeName="host_*"), action=Action.FIRST)) + + # Add /etc/hosts layer + emu.addLayer(EtcHosts()) + + # Configure IP range for each AS + base_layer = emu.getLayer("Base") + for asn in asns: + as_obj = base_layer.getAutonomousSystem(asn) + net = as_obj.getNetwork("net0") + net.setHostIpRange(hostStart=71, hostEnd=199, hostStep=1) + + return emu + + def run( dumpfile=None, total_beacon_nodes: int = 3, @@ -83,17 +177,51 @@ def run( platform=Platform.AMD64, override: bool = True, render: bool = True, + ether_view_enabled: bool = True, ): - d01_ethereum_pos.run( - dumpfile=dumpfile, - total_beacon_nodes=total_beacon_nodes, - vc_per_beacon=vc_per_beacon, - output=output, - platform=platform, - override=override, - render=render, - ether_view_enabled=True, + emu = build_emulator(total_beacon_nodes=total_beacon_nodes, vc_per_beacon=vc_per_beacon) + if dumpfile is not None: + emu.dump(dumpfile) + return + + if render: + emu.render() + + output_dir = Path(output or SCRIPT_DIR / "output").resolve() + output_dir.parent.mkdir(parents=True, exist_ok=True) + docker = Docker(platform=platform) + + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + + # Add an Ethereum explorer with an indexing backend, a Web frontend, and supporting services. + eth_explorer_bundle = EthExplorer(emu, ".eth.explorer.seed") + # Configure a separate explorer network with one static IP per container. + eth_explorer_bundle.setDefaultExternalNetwork( + name="ethExplorer_network", + prefix="172.20.0.0/24", + ip_addresses=[f"172.20.0.{i}" for i in range(10, 17)], + default_router="172.20.0.1" ) + # The explorer Web frontend needs at least 1 host port; ports are taken from the list's end. + eth_explorer_bundle.setPorts(list(range(8090, 8099))) + # Set Beacon node ip + eth_explorer_bundle.setBeaconHost("10.151.0.72") + # Set Geth node ip + eth_explorer_bundle.setGethHost("10.150.0.72") + # Get Beacon node ip + eth_explorer_bundle.getBeaconHost() + # Get Geth node ip + eth_explorer_bundle.getGethHost() + # Include the explorer bundle in this Docker compilation. + docker.addContainerBundle(eth_explorer_bundle) + + emu.compile(docker, str(output_dir), override=override) def main() -> int: @@ -106,6 +234,7 @@ def main() -> int: platform=resolve_platform(args.platform), override=args.override, render=args.render, + ether_view_enabled=args.ether_view_enabled, ) return 0 diff --git a/examples/internet/B08_internet_map_bundle/README.md b/examples/internet/B08_internet_map_bundle/README.md new file mode 100644 index 000000000..5813be1b9 --- /dev/null +++ b/examples/internet/B08_internet_map_bundle/README.md @@ -0,0 +1,127 @@ +# B08: Two InternetMap bundles + +This example demonstrates how to register two independent `InternetMap` +bundles in one SEED Emulator compilation. Both bundles provide topology, +geographic, and traffic visualization services, but they use different +container suffixes, Docker networks, and host-port ranges. + +## Running the example + +```bash +cd examples/internet/B08_internet_map_bundle +python internet_map_bundle.py +``` + +The script defaults to AMD64. Use `python internet_map_bundle.py amd` or +`python internet_map_bundle.py arm` to select the target platform explicitly. + +It calls `mini_internet.run(dumpfile="./base_internet.bin")`, loads that +component into an `Emulator`, and renders it before creating the bundles. +It then registers both bundles with `Docker(platform=platform)` and writes +the generated Compose project to `output` with `override=True`: + +```bash +cd output +docker compose up --build +``` + +The port pools are consumed from the end of each list. Only three ports per +bundle are used: + +| Instance | Topology UI | Geographic UI | Traffic observer | +| --- | --- | --- | --- | +| `.map.seed` | `http://localhost:8087` | `http://localhost:8086` | `8088` | +| `.map.seed.emu` | `http://localhost:8097` | `http://localhost:8096` | `8098` | + +The API backend uses port `7071` on the bundle network and does not publish +a separate host port. The observer uses host networking; both instances +capture traffic from the same Docker host. + +## The two bundle instances + +The first instance is the baseline configuration: + +```python +bundle = InternetMap(emu, ".map.seed") +bundle.setDefaultExternalNetwork( + name="internetMap_network", + prefix="172.30.0.0/24", + ip_addresses=[f"172.30.0.{i}" for i in range(10, 14)], + default_router="172.30.0.1", +) +bundle.setPorts(list(range(8081, 8089))) +docker.addContainerBundle(bundle) +``` + +This bundle uses the `172.30.0.0/24` bridge network and the `8081`–`8088` +host-port pool. Its services communicate through the bundle network. The +emulator-service backend is not attached to an emulator network by this +instance. + +The second instance uses independent names and addresses: + +```python +bundle_join_emu_network = InternetMap(emu, ".map.seed.emu") +bundle_join_emu_network.setDefaultExternalNetwork( + name="internetMap_network_emu", + prefix="172.40.0.0/24", + ip_addresses=[f"172.40.0.{i}" for i in range(10, 14)], + default_router="172.40.0.1", +) +bundle_join_emu_network.enableInternalNetwork() +bundle_join_emu_network.setPorts(list(range(8091, 8099))) +docker.addContainerBundle(bundle_join_emu_network) +``` + +The suffix `.map.seed.emu` prevents Compose service and hostname collisions. +Registration keys, `container_name` values, and build directories also include +the suffix. For example, the second API service is named +`seedemu_emulator_service_backend.map.seed.emu`. +The `172.40.0.0/24` network and `8091`–`8098` port pool prevent address and +host-port conflicts with the first instance. + +`enableInternalNetwork()` is the functional difference between the two +instances. It sets a flag; during `configure()`, the bundle reserves one free +address starting at network-address offset 10 and passes the stored network, +first `ip_addresses` entry, backend hostname, and optional gateway to +`seedemu_emulator_service_backend.joinInternalNetwork(...)`. The backend then +has two network attachments: + +1. The bundle bridge network, used by the visualization frontends and other + InternetMap services. +2. A selected emulator network, used to communicate with the emulated network + and its emulator service API. If a default route is available, the startup + script also installs the route through the emulator gateway. + +The first bundle remains bridge-only, so it is useful as a comparison showing +the default InternetMap connectivity model. + +The second bundle does not call `setDefaultInternalNetwork()`, so its internal +address is selected automatically during compilation. The `.10` starting +point is relative to the selected network address; occupied addresses, the +gateway, and earlier bundle reservations are skipped. A rendered host network +with at least one free eligible address is required. The frontends retain +their external-network attachments and proxy to the backend's static IP on +that network. The traffic observer remains on host networking. + +## Registration lifecycle + +Both bundles are registered independently: + +```python +docker.addContainerBundle(bundle) +docker.addContainerBundle(bundle_join_emu_network) +emu.compile(docker, "./output", override=True) +``` + +During compilation, each bundle validates its port pool, assigns static +addresses, configures its prepared services, and emits its own network definition. The +different suffixes, network names, subnets, and host-port ranges allow both +bundles to coexist in the generated Compose project. + +## InternetMap design + +This README focuses on the differences demonstrated by this example. For the +complete `InternetMap` service topology, lifecycle, reverse-proxy setup, +network attachments, optional emulator-network integration, and generated +startup files, see the [InternetMap design document](../../../docs/designs/internet_map.md). diff --git a/examples/internet/B08_internet_map_bundle/internet_map_bundle.py b/examples/internet/B08_internet_map_bundle/internet_map_bundle.py new file mode 100644 index 000000000..1c036787b --- /dev/null +++ b/examples/internet/B08_internet_map_bundle/internet_map_bundle.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +# encoding: utf-8 + +from seedemu import * +from examples.internet.B00_mini_internet import mini_internet +import os, sys + +############################################################################### +# Set the platform information +script_name = os.path.basename(__file__) + +platform = None +if len(sys.argv) == 1: + platform = Platform.AMD64 +elif len(sys.argv) == 2: + if sys.argv[1].lower() == 'amd': + platform = Platform.AMD64 + elif sys.argv[1].lower() == 'arm': + platform = Platform.ARM64 + else: + print(f"Usage: {script_name} amd|arm") + sys.exit(1) +else: + print(f"Usage: {script_name} amd|arm") + sys.exit(1) + +mini_internet.run(dumpfile='./base_internet.bin') + +emu = Emulator() + +# Load the pre-built component +emu.load('./base_internet.bin') + +# Render the emulation +emu.render() + +docker = Docker(platform=platform) + +# Create the first InternetMap bundle with an isolated Docker bridge network. +# Its emulator-service backend can communicate with the other visualization +# containers on this bundle network, but it is not attached to an emulator +# network. The suffix keeps its generated container names unique. +bundle = InternetMap(emu, ".map.seed") +# Customize the bundle network; provide at least one IP per container, in creation order. +# All IPs must belong to the configured subnet, which should not overlap other networks. +bundle.setDefaultExternalNetwork( + name="internetMap_network", + prefix="172.30.0.0/24", + ip_addresses=[f"172.30.0.{i}" for i in range(10, 14)], + default_router="172.30.0.1" +) +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +bundle.setPorts(list(range(8081, 8089))) +# Register the isolated bundle; Docker will configure and install it during +docker.addContainerBundle(bundle) + +# Create a second InternetMap instance. Its suffix, bridge network, and host +# port range are different from the first instance. +bundle_join_emu_network = InternetMap(emu, ".map.seed.emu") +bundle_join_emu_network.setDefaultExternalNetwork( + name="internetMap_network_emu", + prefix="172.40.0.0/24", + ip_addresses=[f"172.40.0.{i}" for i in range(10, 14)], + default_router="172.40.0.1" +) +# Attach seedemu_emulator_service_backend to the selected emulator network. +# This adds a second network interface to that container, allowing the +# emulator service API to communicate with containers on the emulated network. +# The first bundle does not make this attachment and remains bridge-only. +bundle_join_emu_network.enableInternalNetwork() +bundle_join_emu_network.setPorts(list(range(8091, 8099))) +docker.addContainerBundle(bundle_join_emu_network) + +# Compile the emulation and generate both InternetMap deployments. +emu.compile(docker, './output', override=True) diff --git a/seedemu/containerBundle/ContainerBundle.py b/seedemu/containerBundle/ContainerBundle.py index fe85fc823..584356985 100644 --- a/seedemu/containerBundle/ContainerBundle.py +++ b/seedemu/containerBundle/ContainerBundle.py @@ -18,20 +18,20 @@ class IndentDumper(yaml.SafeDumper): - """YAML dumper that keeps nested mappings consistently indented.""" + """! + @brief YAML dumper that keeps nested mappings consistently indented. + """ def increase_indent(self, flow=False, indentless=False): return super().increase_indent(flow, False) def safe_dump_pretty(data) -> str: - """Serialize ``data`` as readable YAML without sorting mapping keys. - - Args: - data: Mapping or sequence to serialize. + """! + @brief Serialize data as readable YAML without sorting keys. - Returns: - The generated YAML document. + @param data mapping or sequence to serialize. + @returns the generated YAML document. """ return yaml.dump( data, @@ -44,11 +44,12 @@ def safe_dump_pretty(data) -> str: @dataclass(eq=False) class ContainerBundle: - """Base class for a group of independently built Docker containers. + """ + ! + @brief Base class for a group of independently built Docker containers. - Subclasses create containers in ``__init__`` and populate their service - definitions in ``configure``. The Docker compiler calls ``configure`` and - ``install`` to generate Compose services and network definitions. + Subclasses create containers in ``__init__`` and configure their services + before the Docker compiler calls ``configure`` and ``install``. """ emulator: InitVar[Optional[Emulator]] = None @@ -56,49 +57,88 @@ class ContainerBundle: _emulator: Optional[Emulator] = field(default=None, init=False, repr=False) _suffix: str = field(default="", init=False) _containers: Dict[str, PreparedContainer] = field(default_factory=dict, init=False) - _default_network: Optional[Dict[str, Any]] = field(default=None, init=False) + _default_external_network: Optional[Dict[str, Any]] = field(default=None, init=False) + _default_internal_network: Optional[Dict[str, Any]] = field(default=None, init=False) _ports: List[int] = field(default_factory=list, init=False) _internal_hostname_ip_mappings: Dict[str, str] = field(default_factory=dict, init=False) _external_hostname_ip_mappings: Dict[str, str] = field(default_factory=dict, init=False) _required_port_number: int = field(default=0, init=False) + _required_emu_network_address_number: int = field(default=0, init=False) def __post_init__(self, emulator: Optional[Emulator], suffix: str) -> None: - """Store the emulator reference and hostname/build-directory suffix.""" + """! + @brief Store the emulator reference and hostname suffix. + + @param emulator emulator associated with this bundle. + @param suffix suffix appended to generated container hostnames. + """ self._emulator = emulator self._suffix = suffix def _createContainer(self, local_name: str, suffix: str) -> PreparedContainer: - """Create and register a prepared container. + """! + @brief Create and register a prepared container. - Args: - local_name: Logical service name used in Compose. - suffix: Suffix appended to the generated hostname. - - Returns: - The newly registered :class:`PreparedContainer`. + @param local_name logical Compose service name. + @param suffix suffix appended to the generated hostname. + @returns the newly registered ``PreparedContainer``. """ container = PreparedContainer(name=local_name, suffix=suffix) - self._containers.update({local_name: container}) + self._containers.update({local_name + suffix: container}) return container def getContainer(self, local_name: str) -> PreparedContainer: - """Return a registered container by its logical service name.""" + """! + @brief Return a registered container by logical service name. + + @param local_name logical service name. + @returns the matching ``PreparedContainer``. + """ return self._containers[local_name] def getContainers(self) -> Dict[str, PreparedContainer]: - """Return a shallow copy of all registered containers.""" + """! + @brief Return a shallow copy of all registered containers. + + @returns mapping from logical service names to prepared containers. + """ return self._containers.copy() def getEmulator(self) -> Optional[Emulator]: - """Return the emulator associated with this bundle, if any.""" + """! + @brief Return the emulator associated with this bundle. + + @returns the associated emulator, or ``None``. + """ return self._emulator def getSuffix(self) -> str: - """Return the suffix used for generated container hostnames.""" + """! + @brief Return the suffix used for generated hostnames. + + @returns the configured hostname and build-directory suffix. + """ return self._suffix - def setDefaultNetwork( + def setDefaultInternalNetwork(self, name, ip_addresses: List, default_route: str): + self._default_internal_network = { + "network": name, + "ip_addresses": ip_addresses, + "default_route": default_route, + } + return self + + def getDefaultInternalNetwork(self): + if not self._default_internal_network: + self._default_internal_network = self.allocateEmuNetworkAddress() + + return { + **self._default_internal_network, + "ip_addresses": self._default_internal_network["ip_addresses"][:], + } + + def setDefaultExternalNetwork( self, name: str, prefix: str, @@ -106,21 +146,16 @@ def setDefaultNetwork( default_router: str, type: str = "bridge", ): - """Configure the default Docker network and static container addresses. - - Args: - name: Docker Compose network name. - prefix: IPv4 subnet in CIDR notation, such as ``172.20.0.0/24``. - ip_addresses: Static IPv4 addresses assigned in container order. - default_router: IPv4 gateway address inside ``prefix``. - type: Docker network driver, normally ``"bridge"``. - - Returns: - This bundle, allowing fluent configuration. - - Raises: - ValueError: If the subnet, gateway, or container addresses are - invalid or inconsistent. + """! + @brief Configure the default Docker network and static addresses. + + @param name Docker Compose network name. + @param prefix IPv4 subnet in CIDR notation. + @param ip_addresses static IPv4 addresses in container order. + @param default_router IPv4 gateway inside ``prefix``. + @param type Docker network driver, normally ``"bridge"``. + @returns this bundle for fluent configuration. + @raises ValueError if network or address values are invalid. """ subnet = IPv4Network(prefix, strict=True) gateway = IPv4Address(default_router) @@ -153,7 +188,7 @@ def setDefaultNetwork( if len(set(normalized_addresses)) != len(normalized_addresses): raise ValueError("Container IP addresses must be unique.") - self._default_network = { + self._default_external_network = { "name": name, "prefix": prefix, "ip_addresses": normalized_addresses, @@ -174,30 +209,59 @@ def setDefaultNetwork( return self - def getDefaultNetwork(self) -> Optional[Dict[str, Any]]: - """Return the configured default network, or ``None`` if unset.""" - return self._default_network + def getDefaultExternalNetwork(self) -> Optional[Dict[str, Any]]: + """! + @brief Return the configured default network. + + @returns the network dictionary, or ``None`` when unset. + """ + return { + **self._default_external_network, + "ip_addresses": self._default_external_network["ip_addresses"][:] + } def setPorts(self, ports: List[int]) -> None: - """Set the host-port pool consumed by the bundle during configuration.""" + """! + @brief Set the host-port pool consumed during configuration. + + @param ports host ports available to the bundle. + """ self._ports = ports.copy() def getPorts(self) -> List[int]: - """Return a copy of the currently configured host-port pool.""" + """! + @brief Return a copy of the configured host-port pool. + + @returns available host ports. + """ return self._ports.copy() def getInternalHostnameIpMappings(self) -> Dict[str, str]: - """Return mappings for services attached to emulated networks.""" + """! + @brief Return hostname/IP mappings for emulated networks. + + @returns a copy of internal hostname-to-address mappings. + """ + for _, container in self._containers.items(): + self._internal_hostname_ip_mappings.update(container.getInternalHostnameIpMappings()) return self._internal_hostname_ip_mappings.copy() def getExternalHostnameIpMappings(self) -> Dict[str, str]: - """Return mappings for services attached to the bundle network.""" + """! + @brief Return hostname/IP mappings for the bundle network. + + @returns a copy of external hostname-to-address mappings. + """ + for _, container in self._containers.items(): + self._external_hostname_ip_mappings.update(container.getExternalHostnameIpMappings()) return self._external_hostname_ip_mappings.copy() def configure(self) -> None: - """Validate bundle-wide settings before service generation. + """! + @brief Validate bundle-wide settings before service generation. Subclasses should call this method before configuring their services. + @raises ValueError when fewer than the required ports are configured. """ if len(self._ports) < self._required_port_number: raise ValueError( @@ -206,7 +270,11 @@ def configure(self) -> None: ) def install(self) -> tuple[str, str]: - """Install containers and return Compose service and network YAML.""" + """! + @brief Install containers and generate Compose YAML fragments. + + @returns a tuple containing service YAML and network YAML. + """ services = {} for name, container in self._containers.items(): services[name] = container.install() @@ -231,8 +299,9 @@ def install(self) -> tuple[str, str]: networks = { network: ( - self._default_network["network_config"] - if self._default_network is not None and network == self._default_network["name"] + self._default_external_network["network_config"] + if self._default_external_network is not None + and network == self._default_external_network["name"] else {} ) for service in services.values() @@ -258,40 +327,85 @@ def install(self) -> tuple[str, str]: ) return compose_services_txt, compose_networks_txt - def getEmuHostNetworkInfo(self): - """Return the first usable emulated host network and default route. + def allocateEmuNetworkAddress(self): + """! + @brief Reserve addresses starting at host offset 10 on one host network. - Returns: - A dictionary containing ``network``, ``hostname``, ``ip_address`` - and ``default_route``, or ``None`` when no suitable host exists. + @returns a network dictionary whose ``ip_address`` is a list of + ``_required_emu_network_address_number`` IPv4 strings, or ``None`` + when no host network has enough capacity. Select one address + before passing the dictionary to ``joinInternalNetwork``. + Call after rendering. Reservations are shared across bundles and + committed only when the full requested count is available. """ + count = self._required_emu_network_address_number + if isinstance(count, bool) or not isinstance(count, int) or count < 0: + raise ValueError( + "Required emulator network address count must be a non-negative integer." + ) + if self._emulator is None: + return None + + occupied = set() + candidates = {} for (_, node_type, _), node in self._emulator.getRegistry().getAll().items(): - if node_type != "hnode": + if node_type not in ("hnode", "rnode", "brdnode"): continue - for interface in node.getInterfaces(): address = interface.getAddress() if address is None: continue - - network = interface.getNet() - router = network.getDefaultRouter() - scope, _, _ = network.getRegistryInfo() - network_name = network.getName() - if network.getType() != NetworkType.Bridge: - network_name = f"net_{scope}_{network_name}" - - return { - "network": network_name, - "hostname": node.getName(), - "ip_address": str(address), - "default_route": str(router) if router is not None else None, - } + occupied.add(IPv4Address(address)) + if node_type == "hnode": + network = interface.getNet() + candidates.setdefault(id(network), (network, node.getName())) + + # All node addresses must be known before selecting a free address. + # Preserve host order, but inspect each candidate network only once. + for network, hostname in candidates.values(): + router = network.getDefaultRouter() + reserved = set(network.getAttribute("container_bundle_reserved_addresses", set())) + gateway = IPv4Address(router) if router is not None else None + prefix = network.getPrefix() + first_address = int(prefix.network_address) + 10 + addresses = [] + if count: + for ip in prefix.hosts(): + if ( + int(ip) < first_address + or ip in occupied + or ip in reserved + or ip == gateway + or ip == prefix.network_address + or ip == prefix.broadcast_address + ): + continue + addresses.append(str(ip)) + if len(addresses) == count: + break + if len(addresses) < count: + continue + reserved.update(IPv4Address(address) for address in addresses) + network.setAttribute("container_bundle_reserved_addresses", reserved) + scope, _, _ = network.getRegistryInfo() + network_name = network.getName() + if network.getType() != NetworkType.Bridge: + network_name = f"net_{scope}_{network_name}" + + self._default_internal_network = { + "network": network_name, + "emu_hostname": hostname, + "ip_addresses": addresses, + "default_route": str(router) if router is not None else None, + } + return self @dataclass(eq=False) class PreparedContainer: - """Mutable description of one container before Compose generation.""" + """! + @brief Mutable description of one container before Compose generation. + """ name: InitVar[str] = "" suffix: InitVar[str] = "" @@ -309,21 +423,38 @@ class PreparedContainer: _default_route: str = field(default="", init=False) def __post_init__(self, name: str, suffix: str) -> None: - """Initialize the logical service name and Compose service metadata.""" + """! + @brief Initialize service identity and Compose metadata. + + @param name logical Compose service name. + @param suffix suffix appended to the generated hostname. + """ self._name = name self._suffix = suffix - self.service["container_name"] = name + self.service["container_name"] = name + suffix def getName(self) -> str: - """Return the logical Compose service name.""" + """! + @brief Return the logical Compose service name. + + @returns the service name. + """ return self._name def getHostname(self) -> str: - """Return the generated hostname including the configured suffix.""" + """! + @brief Return the generated hostname. + + @returns the logical name followed by the configured suffix. + """ return self._name + self._suffix def getInternalHostnameIpMappings(self) -> Dict[str, str]: - """Return the first emulated-network hostname-to-IP mapping.""" + """! + @brief Return the first emulated-network hostname mapping. + + @returns a hostname-to-IP mapping, or an empty dictionary. + """ if not self._internal_networks: return {} @@ -331,7 +462,11 @@ def getInternalHostnameIpMappings(self) -> Dict[str, str]: return {internal_networks[1]: internal_networks[2]} def getExternalHostnameIpMappings(self) -> Dict[str, str]: - """Return external-network hostname-to-IP mappings.""" + """! + @brief Return external-network hostname/IP mappings. + + @returns all configured external hostname-to-address mappings. + """ return { external_network[1]: external_network[2] for external_network in (self._external_network or []) @@ -342,12 +477,11 @@ def setEntrypointWrapper( original_entrypoint: str, commands: List[str], ) -> None: - """ - Run preparation commands before delegating to the original entrypoint. + """! + @brief Run preparation commands before the original entrypoint. - Args: - original_entrypoint: Entrypoint script from the base image. - commands: Shell commands to run before the original entrypoint. + @param original_entrypoint entrypoint script from the base image. + @param commands shell commands to execute before that entrypoint. """ wrapper_commands = [ "#!/bin/sh", @@ -361,11 +495,15 @@ def setEntrypointWrapper( self.service["entrypoint"] = [ "sh", - "/new-entrypoint.sh", + self._start_script_name, ] def install(self) -> Dict[str, Any]: - """Write build context files and return the Compose service mapping.""" + """! + @brief Write build-context files and return the Compose service. + + @returns the generated Compose service mapping. + """ hostname = self.getHostname() mkdir(hostname) chdir(hostname) @@ -407,7 +545,11 @@ def install(self) -> Dict[str, Any]: return self.service def _getDefaultRouteCommands(self) -> List[str]: - """Return shell commands for switching the container default route.""" + """! + @brief Generate commands that replace the container default route. + + @returns shell commands that route traffic through ``_default_route``. + """ return [ f'DEFAULT_ROUTE="{self._default_route}"', 'IFACE=$(ip route get "$DEFAULT_ROUTE" | ' @@ -424,27 +566,33 @@ def joinInternalNetwork( ip_address: str = "", default_route: Optional[str] = "", ) -> None: - """Attach the container to an emulated network. + """! + @brief Attach the container to an emulated network. - Args: - network: Compose network name. - hostname: Hostname or node name on that network. - ip_address: Address assigned by the emulator. - default_route: Optional gateway used by startup scripts. + @param network Compose network name. + @param hostname hostname or node name on that network. + @param ip_address address assigned by the emulator. + @param default_route optional gateway used by startup scripts. """ internal_network = (network, hostname, ip_address, default_route) if internal_network not in self._internal_networks: self._internal_networks.append(internal_network) - networks = self.service.setdefault("networks", []) + networks = self.service.setdefault("networks", {}) if network not in networks: - networks.update({network: {}}) + networks.update({network: {"ipv4_address": ip_address}}) if default_route and not self._default_route: self._default_route = default_route def joinExternalNetwork(self, network: str, hostname: str, ip_address: str) -> None: - """Attach the container to a bundle-managed network with a static IP.""" + """! + @brief Attach the container to a bundle network with a static IP. + + @param network Compose network name. + @param hostname hostname represented by the static address. + @param ip_address static IPv4 address. + """ external_network = (network, hostname, ip_address) if external_network not in self._external_network: self._external_network.append(external_network) @@ -454,34 +602,56 @@ def joinExternalNetwork(self, network: str, hostname: str, ip_address: str) -> N networks.update({network: {"ipv4_address": ip_address}}) def setContentAttribute(self, content: dict) -> None: - """Merge Docker Compose service attributes into this container.""" + """! + @brief Merge attributes into the Compose service definition. + + @param content service attributes such as image, ports, or environment. + """ self.service.update(content) def setEtcHosts(self, content: str) -> None: - """Stage content that will be appended to the container's ``/etc/hosts``.""" + """! + @brief Stage content to append to the container ``/etc/hosts``. + + @param content newline-separated host entries. + """ self._files["__etchosts_file"] = content def setFile(self, filename: str, content: str) -> None: - """Stage a file to be copied into the generated image.""" + """! + @brief Stage a file for the generated image. + + @param filename destination path inside the image. + @param content file contents. + """ self._files.update({filename: content}) def _computeDockerfile(self) -> str: if not self._files: return "" - + + self.service.update({"privileged": True}) dockerfile_lines = [ "FROM {}".format(self.service.pop("image", "")), "ARG DEBIAN_FRONTEND=noninteractive", - "RUN apt-get update && apt-get install -y --no-install-recommends iproute2 && rm -rf /var/lib/apt/lists/*", + "RUN apt-get update && apt-get install -y --no-install-recommends iproute2 iputils-ping && rm -rf /var/lib/apt/lists/*", ] for filename, content in self._files.items(): dockerfile_lines.append(self._addFile(filename, content)) dockerfile = "\n".join(dockerfile_lines) + "\n" + return dockerfile def _addFile(self, path: str, content: str) -> str: + """! + @brief Write a staged file and return its Docker COPY command. + + @param path destination path inside the image. + @param content file contents. + @returns a Dockerfile ``COPY`` instruction. + """ staged_path = md5(path.encode("utf-8")).hexdigest() print(content, file=open(staged_path, "w")) if path.endswith(".sh"): diff --git a/seedemu/containerBundle/EthExplorer.py b/seedemu/containerBundle/EthExplorer.py index eb4ca762b..e5425d6b7 100644 --- a/seedemu/containerBundle/EthExplorer.py +++ b/seedemu/containerBundle/EthExplorer.py @@ -14,19 +14,23 @@ "options": {"max-size": "200m", "max-file": 1}, } -DEFAULT_NETWORK = { +DEFAULT_EXTERNAL_NETWORK = { "name": "ethExplorer_network", "prefix": "172.20.0.0/24", - "ip_addresses": [ - "172.20.0.10", - "172.20.0.11", - "172.20.0.12", - "172.20.0.13", - "172.20.0.14", - "172.20.0.15", - "172.20.0.16", - ], - "default_router": "172.20.0.1" + "ip_addresses": [f"172.20.0.{i}" for i in range(10, 17)], + "default_router": "172.20.0.1", + "type": "bridge", + "network_config": { + "driver": "bridge", + "ipam": { + "config": [ + { + "subnet": "172.20.0.0/24", + "gateway": "172.20.0.1", + } + ] + }, + }, } BACKEND_START_SH = [ @@ -38,6 +42,14 @@ "trap stopit SIGINT", 'echo "run provision-explorer-config-custom.sh ..."', "cd /app/local_deployment", + # Replace service hosts while preserving values resolved by provisioning. + "sed -i " + "-e '/^clickhouse:/,/^[^[:space:]#]/ s|^\\([[:space:]]*host:\\).*|\\1 {CLICKHOUSE_HOST}|' " + "-e '/^bigtable:/,/^[[:space:]]*emulatorHost:/ s|^\\([[:space:]]*emulatorHost:\\).*|\\1 {LBT_HOST}|' " + "-e '/^rawBigtable:/,/^[[:space:]]*emulatorHost:/ s|^\\([[:space:]]*emulatorHost:\\).*|\\1 {RBT_HOST}|' " + "-e \"s|^redisCacheEndpoint: '.*:|redisCacheEndpoint: '{REDIS_HOST}:|\" " + "-e \"s|^redisSessionStoreEndpoint: '.*:|redisSessionStoreEndpoint: '{REDIS_HOST}:|\" " + "/app/local_deployment/provision-explorer-config-custom.sh || exit 1", "chmod +x provision-explorer-config-custom.sh", "./provision-explorer-config-custom.sh", "if [ $? -eq 0 ]; then", @@ -46,18 +58,6 @@ ' echo "ERROR: script failed"', " exit 1", "fi", - # Replace service hosts while preserving values resolved by provisioning. - "sed -i " - "-e '/^[[:space:]]*readerDatabase:/,/^[[:space:]]*host:/ s|^\\([[:space:]]*host:\\).*|\\1 {POSTGRES_HOST}|' " - "-e '/^[[:space:]]*writerDatabase:/,/^[[:space:]]*host:/ s|^\\([[:space:]]*host:\\).*|\\1 {POSTGRES_HOST}|' " - "-e '/^alloyReader:/,/^[[:space:]]*host:/ s|^\\([[:space:]]*host:\\).*|\\1 {POSTGRES_HOST}|' " - "-e '/^alloyWriter:/,/^[[:space:]]*host:/ s|^\\([[:space:]]*host:\\).*|\\1 {POSTGRES_HOST}|' " - "-e '/^clickhouse:/,/^[^[:space:]#]/ s|^\\([[:space:]]*host:\\).*|\\1 {CLICKHOUSE_HOST}|' " - "-e '/^bigtable:/,/^[[:space:]]*emulatorHost:/ s|^\\([[:space:]]*emulatorHost:\\).*|\\1 {LBT_HOST}|' " - "-e '/^rawBigtable:/,/^[[:space:]]*emulatorHost:/ s|^\\([[:space:]]*emulatorHost:\\).*|\\1 {RBT_HOST}|' " - "-e \"s|^redisCacheEndpoint: '.*:|redisCacheEndpoint: '{REDIS_HOST}:|\" " - "-e \"s|^redisSessionStoreEndpoint: '.*:|redisSessionStoreEndpoint: '{REDIS_HOST}:|\" " - "/app/local_deployment/config.yml || exit 1", "cd /app", 'echo "start ..."', 'echo "run eth1indexer"', @@ -81,6 +81,14 @@ "trap stopit SIGINT", 'echo "run provision-explorer-config-custom.sh ..."', "cd /app/local-deployment", + # Replace service hosts while preserving values resolved by provisioning. + "sed -i " + "-e '/^clickhouse:/,/^[^[:space:]#]/ s|^\\([[:space:]]*host:\\).*|\\1 {CLICKHOUSE_HOST}|' " + "-e '/^bigtable:/,/^[[:space:]]*emulatorHost:/ s|^\\([[:space:]]*emulatorHost:\\).*|\\1 {LBT_HOST}|' " + "-e '/^rawBigtable:/,/^[[:space:]]*emulatorHost:/ s|^\\([[:space:]]*emulatorHost:\\).*|\\1 {RBT_HOST}|' " + "-e \"s|^redisCacheEndpoint: '.*:|redisCacheEndpoint: '{REDIS_HOST}:|\" " + "-e \"s|^redisSessionStoreEndpoint: '.*:|redisSessionStoreEndpoint: '{REDIS_HOST}:|\" " + "/app/local-deployment/provision-explorer-config-custom.sh || exit 1", "chmod +x provision-explorer-config-custom.sh", "./provision-explorer-config-custom.sh", "if [ $? -eq 0 ]; then", @@ -89,18 +97,6 @@ ' echo "ERROR: script failed"', " exit 1", "fi", - # Replace service hosts while preserving values resolved by provisioning. - "sed -i " - "-e '/^[[:space:]]*readerDatabase:/,/^[[:space:]]*host:/ s|^\\([[:space:]]*host:\\).*|\\1 {POSTGRES_HOST}|' " - "-e '/^[[:space:]]*writerDatabase:/,/^[[:space:]]*host:/ s|^\\([[:space:]]*host:\\).*|\\1 {POSTGRES_HOST}|' " - "-e '/^alloyReader:/,/^[[:space:]]*host:/ s|^\\([[:space:]]*host:\\).*|\\1 {POSTGRES_HOST}|' " - "-e '/^alloyWriter:/,/^[[:space:]]*host:/ s|^\\([[:space:]]*host:\\).*|\\1 {POSTGRES_HOST}|' " - "-e '/^clickhouse:/,/^[^[:space:]#]/ s|^\\([[:space:]]*host:\\).*|\\1 {CLICKHOUSE_HOST}|' " - "-e '/^bigtable:/,/^[[:space:]]*emulatorHost:/ s|^\\([[:space:]]*emulatorHost:\\).*|\\1 {LBT_HOST}|' " - "-e '/^rawBigtable:/,/^[[:space:]]*emulatorHost:/ s|^\\([[:space:]]*emulatorHost:\\).*|\\1 {RBT_HOST}|' " - "-e \"s|^redisCacheEndpoint: '.*:|redisCacheEndpoint: '{REDIS_HOST}:|\" " - "-e \"s|^redisSessionStoreEndpoint: '.*:|redisSessionStoreEndpoint: '{REDIS_HOST}:|\" " - "/app/local-deployment/config.yml || exit 1", "cd /app", 'echo "start ..."', 'echo "run explorer"', @@ -118,22 +114,23 @@ class EthExplorer(ContainerBundle): - """Container bundle for the Ethereum Beacon Chain explorer stack. + """! + @brief Bundle for the Ethereum Beacon Chain explorer stack. - The bundle includes PostgreSQL, ClickHouse, Redis, two Bigtable emulators, - an indexing backend, and the Web frontend. + Includes PostgreSQL, ClickHouse, Redis, two Bigtable emulators, an indexing + backend, and the Web frontend. """ def __init__(self, emulator, suffix="eth.explorer"): - """Create an explorer bundle for an Ethereum-enabled emulator. + """! + @brief Create an explorer bundle for an Ethereum emulator. - Args: - emulator: Emulator containing an ``EthereumService`` and a usable - emulated host network. - suffix: Suffix appended to generated container hostnames. + @param emulator emulator containing ``EthereumService`` and a usable + emulated host network. + @param suffix suffix appended to generated container hostnames. """ super().__init__(emulator=emulator, suffix=suffix) - self._default_network = DEFAULT_NETWORK + self._default_external_network = DEFAULT_EXTERNAL_NETWORK service_names = [ "clickhouse", "postgres", @@ -145,12 +142,16 @@ def __init__(self, emulator, suffix="eth.explorer"): ] for service_name in service_names: self._createContainer(service_name, suffix) + self._required_port_number = 1 + self._required_emu_network_address_number = 2 self.__beacon_host = self.__geth_host = "" - self._emu_internal_network = self.getEmuHostNetworkInfo() def configure(self) -> None: - """Validate settings and configure explorer services and connections.""" - self._required_port_number = 1 + """! + @brief Validate settings and configure explorer services. + + @raises ValueError when the required host port is unavailable. + """ super().configure() eth = self._emulator.getLayer("EthereumService") @@ -160,14 +161,14 @@ def configure(self) -> None: if not self.__geth_host: self.__geth_host = blockchain.getGethBootNodeIP()[0] - default_network_name = self._default_network["name"] - ip_addresses = self._default_network["ip_addresses"] + default_network_name = self._default_external_network["name"] + ip_addresses = self._default_external_network["ip_addresses"] for index, container in enumerate(self._containers.values()): container.joinExternalNetwork( default_network_name, container.getHostname(), ip_addresses[index] ) - clickhouse = self._containers["clickhouse"] + clickhouse = self._containers["clickhouse" + self._suffix] clickhouse.setContentAttribute( { "image": CLICKHOUSE_IMAGE, @@ -185,7 +186,7 @@ def configure(self) -> None: } ) - postgres = self._containers["postgres"] + postgres = self._containers["postgres" + self._suffix] postgres.setContentAttribute( { "image": POSTGRES_IMAGE, @@ -203,7 +204,7 @@ def configure(self) -> None: } ) - redis = self._containers["redis"] + redis = self._containers["redis" + self._suffix] redis.setContentAttribute( { "image": REDIS_IMAGE, @@ -217,19 +218,19 @@ def configure(self) -> None: } ) - littlebigtable = self._containers["littlebigtable"] + littlebigtable = self._containers["littlebigtable" + self._suffix] littlebigtable.setContentAttribute( { "image": LITTLE_BIGTABLE_IMAGE, - "depends_on": [postgres.getName()], + "depends_on": [postgres.getHostname()], } ) - rawbigtable = self._containers["rawbigtable"] + rawbigtable = self._containers["rawbigtable" + self._suffix] rawbigtable.setContentAttribute( { "image": LITTLE_BIGTABLE_IMAGE, - "depends_on": [postgres.getName()], + "depends_on": [postgres.getHostname()], } ) @@ -241,7 +242,9 @@ def configure(self) -> None: ] rawbigtable_ip = rawbigtable.service["networks"][default_network_name]["ipv4_address"] - seedemu_ethexplorer_backend = self._containers["seedemu-ethexplorer-backend"] + seedemu_ethexplorer_backend = self._containers[ + "seedemu-ethexplorer-backend" + self._suffix + ] seedemu_ethexplorer_backend.setContentAttribute( { "image": SEEDEMU_ETH_EXPLORER_BACKEND_IMAGE, @@ -251,40 +254,54 @@ def configure(self) -> None: "healthcheck": { "test": [ "CMD-SHELL", - """PGPASSWORD=pass psql -h postgres -U postgres -d db -tAc "SELECT 1 FROM information_schema.tables WHERE table_name='blocks';" | grep -q 1""", + f"""PGPASSWORD=pass psql -h {postgres.getHostname()} -U postgres -d db -tAc "SELECT 1 FROM information_schema.tables WHERE table_name='blocks';" | grep -q 1""", ], "interval": "5s", "timeout": "3s", - "retries": 60, + "retries": 20, "start_period": "10s", }, "depends_on": { - "clickhouse": {"condition": "service_healthy"}, - "postgres": {"condition": "service_healthy"}, - "redis": {"condition": "service_healthy"}, - "littlebigtable": {"condition": "service_started"}, - "rawbigtable": {"condition": "service_started"}, + clickhouse.getHostname(): {"condition": "service_healthy"}, + postgres.getHostname(): {"condition": "service_healthy"}, + redis.getHostname(): {"condition": "service_healthy"}, + littlebigtable.getHostname(): {"condition": "service_started"}, + rawbigtable.getHostname(): {"condition": "service_started"}, + }, + "environment": { + "CL_HOST": self.__beacon_host, + "EL_HOST": self.__geth_host, + "POSTGRES_HOST": postgres_ip, }, - "environment": {"CL_HOST": self.__beacon_host, "EL_HOST": self.__geth_host}, "build": f"./{seedemu_ethexplorer_backend.getHostname()}", "logging": DOCKER_LOGGOING_SET, } ) - seedemu_ethexplorer_backend.joinInternalNetwork(**self._emu_internal_network) + if not self._default_internal_network: + self.allocateEmuNetworkAddress() + seedemu_ethexplorer_backend.joinInternalNetwork( + hostname=seedemu_ethexplorer_backend.getHostname(), + network=self._default_internal_network["network"], + ip_address=self._default_internal_network["ip_addresses"][0], + default_route=self._default_internal_network["default_route"], + ) backend_start_commands = BACKEND_START_SH.copy() backend_start_commands = [ - command.format( - POSTGRES_HOST=postgres_ip, - CLICKHOUSE_HOST=clickhouse_ip, - LBT_HOST=littlebigtable_ip, - RBT_HOST=rawbigtable_ip, - REDIS_HOST=redis_ip, - ) if command.startswith("sed -i ") else command + ( + command.format( + CLICKHOUSE_HOST=clickhouse_ip, + LBT_HOST=littlebigtable_ip, + RBT_HOST=rawbigtable_ip, + REDIS_HOST=redis_ip, + ) + if command.startswith("sed -i ") + else command + ) for command in backend_start_commands ] seedemu_ethexplorer_backend._start_commands = backend_start_commands - seedemu_ethexplorer_web = self._containers["seedemu-ethexplorer-web"] + seedemu_ethexplorer_web = self._containers["seedemu-ethexplorer-web" + self._suffix] seedemu_ethexplorer_web.setContentAttribute( { "image": SEEDEMU_ETH_EXPLORER_WEB_IMAGE, @@ -292,45 +309,73 @@ def configure(self) -> None: "pid": "host", "cap_add": ["ALL"], "depends_on": { - "clickhouse": {"condition": "service_healthy"}, - "postgres": {"condition": "service_healthy"}, - "redis": {"condition": "service_healthy"}, - "littlebigtable": {"condition": "service_started"}, - "rawbigtable": {"condition": "service_started"}, - seedemu_ethexplorer_backend.getName(): {"condition": "service_healthy"}, + clickhouse.getHostname(): {"condition": "service_healthy"}, + postgres.getHostname(): {"condition": "service_healthy"}, + redis.getHostname(): {"condition": "service_healthy"}, + littlebigtable.getHostname(): {"condition": "service_started"}, + rawbigtable.getHostname(): {"condition": "service_started"}, + seedemu_ethexplorer_backend.getHostname(): {"condition": "service_healthy"}, + }, + "environment": { + "CL_HOST": self.__beacon_host, + "EL_HOST": self.__geth_host, + "POSTGRES_HOST": postgres_ip, }, - "environment": {"CL_HOST": self.__beacon_host, "EL_HOST": self.__geth_host}, "ports": [f"{self._ports.pop()}:{SEEDEMU_ETH_EXPLORER_WEB_INTERNAL_PORT}"], "build": f"./{seedemu_ethexplorer_web.getHostname()}", "logging": DOCKER_LOGGOING_SET, } ) - seedemu_ethexplorer_web.joinInternalNetwork(**self._emu_internal_network) + seedemu_ethexplorer_web.joinInternalNetwork( + hostname=seedemu_ethexplorer_web.getHostname(), + network=self._default_internal_network["network"], + ip_address=self._default_internal_network["ip_addresses"][1], + default_route=self._default_internal_network["default_route"], + ) frontend_start_commands = FRONTEND_START_SH.copy() frontend_start_commands = [ - command.format( - POSTGRES_HOST=postgres_ip, - CLICKHOUSE_HOST=clickhouse_ip, - LBT_HOST=littlebigtable_ip, - RBT_HOST=rawbigtable_ip, - REDIS_HOST=redis_ip, - ) if command.startswith("sed -i ") else command + ( + command.format( + CLICKHOUSE_HOST=clickhouse_ip, + LBT_HOST=littlebigtable_ip, + RBT_HOST=rawbigtable_ip, + REDIS_HOST=redis_ip, + ) + if command.startswith("sed -i ") + else command + ) for command in frontend_start_commands ] seedemu_ethexplorer_web._start_commands = frontend_start_commands def getBeaconHost(self) -> str: - """Return the consensus-layer Beacon node host selected for the explorer.""" + """! + @brief Return the selected consensus-layer Beacon host. + + @returns Beacon node hostname or IP address. + """ return self.__beacon_host def getGethHost(self) -> str: - """Return the execution-layer Geth node host selected for the explorer.""" + """! + @brief Return the selected execution-layer Geth host. + + @returns Geth node hostname or IP address. + """ return self.__geth_host def setBeaconHost(self, beacon_host) -> None: - """Override the Beacon node host used by the backend and frontend.""" + """! + @brief Override the Beacon host used by backend and frontend. + + @param beacon_host Beacon node hostname or IP address. + """ self.__beacon_host = beacon_host def setGethHost(self, geth_host) -> None: - """Override the Geth node host used by the backend and frontend.""" + """! + @brief Override the Geth host used by backend and frontend. + + @param geth_host Geth node hostname or IP address. + """ self.__geth_host = geth_host diff --git a/seedemu/containerBundle/InternetMap.py b/seedemu/containerBundle/InternetMap.py index 696093ac8..b8e330355 100644 --- a/seedemu/containerBundle/InternetMap.py +++ b/seedemu/containerBundle/InternetMap.py @@ -5,34 +5,27 @@ SEEDEMU_INTERNET_MAP_GEOGRAPHIC_IMAGE = "handsonsecurity/seedemu-internet-map-geographic:1.0" SEEDEMU_TRAFFIC_OBSERVER_SERVICE_IMAGE = "handsonsecurity/seedemu-traffic-observer-service:1.0" -DEFAULT_NETWORK = { +DEFAULT_EXTERNAL_NETWORK = { "name": "internetMap_network", "prefix": "172.30.0.0/24", - "ip_addresses": [ - "172.30.0.10", - "172.30.0.11", - "172.30.0.12", - "172.30.0.13", - ], + "ip_addresses": [f"172.30.0.{i}" for i in range(10, 14)], "default_router": "172.30.0.1", + "type": "bridge", + "network_config": { + "driver": "bridge", + "ipam": { + "config": [ + { + "subnet": "172.30.0.0/24", + "gateway": "172.30.0.1", + } + ] + }, + }, } NGINX_CONF_PATH = "/etc/nginx/conf.d/default.conf" SEEDEMU_EMULATOR_SERVICE_INTERNAL_PORT = 7071 -START_SH = [ - "#!/bin/sh", - "set -eu", - "nginx -g 'daemon off;' &", - "nginx_pid=$!", - "trap 'kill \"$nginx_pid\" 2> /dev/null || true' INT TERM", - "while true; do", - ' if ! kill -0 "$nginx_pid" 2> /dev/null; then', - ' wait "$nginx_pid"', - " exit $?", - " fi", - " sleep 2", - "done", -] START_SCRIPT_NAME = "/entrypoint.sh" SEEDEMU_INTERNET_MAP_TOPLOGY_NGINX_CONF = """ upstream seedemu_emulator_service_backend {{ @@ -142,17 +135,18 @@ class InternetMap(ContainerBundle): - """Container bundle for the topology, geographic map, and traffic views.""" + """! + @brief Bundle for topology, geographic map, and traffic views.""" def __init__(self, emulator, suffix="map.seed"): - """Create an Internet Map bundle. + """! + @brief Create an Internet Map bundle. - Args: - emulator: Emulator whose topology will be visualized. - suffix: Suffix appended to generated container hostnames. + @param emulator emulator whose topology will be visualized. + @param suffix suffix appended to generated container hostnames. """ super().__init__(emulator=emulator, suffix=suffix) - self._default_network = DEFAULT_NETWORK + self._default_external_network = DEFAULT_EXTERNAL_NETWORK service_names = [ "seedemu_emulator_service_backend", "seedemu_internet_map_toplogy", @@ -161,24 +155,30 @@ def __init__(self, emulator, suffix="map.seed"): ] for service_name in service_names: self._createContainer(service_name, suffix) - self._emu_internal_network = self.getEmuHostNetworkInfo() + self._required_port_number = 3 + self._required_emu_network_address_number = 1 + self._enableInternalNetwork = False - def enableEmulatorNetwork(self): - """ - Enable access to an emulator internal network. + def enableInternalNetwork(self): + """! + @brief Attach the API backend to the emulator network. + + @returns this bundle for fluent configuration. """ - seedemu_emulator_service_backend = self._containers["seedemu_emulator_service_backend"] - seedemu_emulator_service_backend.joinInternalNetwork(**self._emu_internal_network) - + self._enableInternalNetwork = True + return self def configure(self) -> None: - """Validate ports and configure the map, API, and observer services.""" - self._required_port_number = 3 + """! + @brief Validate ports and configure all InternetMap services. + + @raises ValueError when fewer than three host ports are configured. + """ super().configure() seedemu_traffic_observer_service_backend = self._containers[ - "seedemu_traffic_observer_service_backend" + "seedemu_traffic_observer_service_backend" + self._suffix ] seedemu_traffic_observer_service_port = self._ports.pop() seedemu_traffic_observer_service_backend.setContentAttribute( @@ -205,8 +205,8 @@ def configure(self) -> None: seedemu_traffic_observer_service_port ] - default_network_name = self._default_network["name"] - ip_addresses = self._default_network["ip_addresses"] + default_network_name = self._default_external_network["name"] + ip_addresses = self._default_external_network["ip_addresses"] for index, container in enumerate(self._containers.values()): if container is seedemu_traffic_observer_service_backend: continue @@ -214,7 +214,9 @@ def configure(self) -> None: default_network_name, container.getHostname(), ip_addresses[index] ) - seedemu_emulator_service_backend = self._containers["seedemu_emulator_service_backend"] + seedemu_emulator_service_backend = self._containers[ + "seedemu_emulator_service_backend" + self._suffix + ] seedemu_emulator_service_backend.setContentAttribute( { "privileged": True, @@ -227,12 +229,29 @@ def configure(self) -> None: default_network_name ]["ipv4_address"] - seedemu_internet_map_toplogy = self._containers["seedemu_internet_map_toplogy"] + if self._enableInternalNetwork: + if not self._default_internal_network: + self.allocateEmuNetworkAddress() + seedemu_emulator_service_backend.joinInternalNetwork( + hostname=seedemu_emulator_service_backend.getHostname(), + network=self._default_internal_network["network"], + ip_address=self._default_internal_network["ip_addresses"][0], + default_route=self._default_internal_network["default_route"], + ) + seedemu_emulator_service_backend.setContentAttribute( + { + "build": f"./{seedemu_emulator_service_backend.getHostname()}", + } + ) + + seedemu_internet_map_toplogy = self._containers[ + "seedemu_internet_map_toplogy" + self._suffix + ] seedemu_internet_map_toplogy.setContentAttribute( { "privileged": True, "image": SEEDEMU_INTERNET_MAP_TOPLOGY_IMAGE, - "depends_on": [seedemu_emulator_service_backend.getName()], + "depends_on": [seedemu_emulator_service_backend.getHostname()], "ports": [f"{self._ports.pop()}:80"], "build": f"./{seedemu_internet_map_toplogy.getHostname()}", } @@ -240,11 +259,10 @@ def configure(self) -> None: seedemu_internet_map_toplogy.setFile( NGINX_CONF_PATH, SEEDEMU_INTERNET_MAP_TOPLOGY_NGINX_CONF.format( - seedemu_emulator_service_backend.getHostname(), + seedemu_emulator_service_ip, SEEDEMU_EMULATOR_SERVICE_INTERNAL_PORT, ), ) - # seedemu_internet_map_toplogy._start_commands = START_SH seedemu_internet_map_toplogy._start_script_name = START_SCRIPT_NAME seedemu_internet_map_toplogy.setEtcHosts( "\n".join( @@ -252,12 +270,14 @@ def configure(self) -> None: ) ) - seedemu_internet_map_geographic = self._containers["seedemu_internet_map_geographic"] + seedemu_internet_map_geographic = self._containers[ + "seedemu_internet_map_geographic" + self._suffix + ] seedemu_internet_map_geographic.setContentAttribute( { "privileged": True, "image": SEEDEMU_INTERNET_MAP_GEOGRAPHIC_IMAGE, - "depends_on": [seedemu_emulator_service_backend.getName()], + "depends_on": [seedemu_emulator_service_backend.getHostname()], "extra_hosts": {"host.docker.internal": "host-gateway"}, "ports": [f"{self._ports.pop()}:80"], "build": f"./{seedemu_internet_map_geographic.getHostname()}", @@ -266,14 +286,13 @@ def configure(self) -> None: seedemu_internet_map_geographic.setFile( NGINX_CONF_PATH, SEEDEMU_INTERNET_MAP_GEOGRAPHIC_NGINX_CONF.format( - seedemu_emulator_service_backend.getHostname(), + seedemu_emulator_service_ip, SEEDEMU_EMULATOR_SERVICE_INTERNAL_PORT, seedemu_traffic_observer_service_backend.service.get("environment", {}).get( "TRAFFIC_CONTROL_ADDR" )[1:], ), ) - # seedemu_internet_map_geographic._start_commands = START_SH seedemu_internet_map_geographic._start_script_name = START_SCRIPT_NAME seedemu_internet_map_geographic.setEtcHosts( "\n".join( From f1e3a00e14691b8f6a5ab6e43ed0c1b3934a77f3 Mon Sep 17 00:00:00 2001 From: cy-gitlab <774239153@qq.com> Date: Fri, 30 Oct 2026 17:39:29 +0800 Subject: [PATCH 5/6] update: examples matches containerBundle --- examples/basic/A00_simple_as/simple_as.py | 15 +- examples/basic/A01_transit_as/transit_as.py | 9 +- .../A02a_transit_as_mpls/transit_as_mpls.py | 13 +- .../basic/A02b_manual_mpls/manual_mpls.py | 13 +- .../out_to_real_world.py | 13 +- .../A03b_from_real_world/from_real_world.py | 13 +- .../basic/A04_visualization/visualization.py | 11 +- examples/basic/A05_components/components.py | 13 +- .../A06_merge_emulation/merge_emulation.py | 11 +- examples/basic/A07_compilers/compilers.py | 13 +- .../node_customization.py | 12 +- .../A10_add_containers/add_containers.py | 1 - .../method_1/add_container.py | 2 +- .../basic/A11_add_containers_new/method_3 | 1 + .../bgp_mixed_backend.py | 13 +- examples/basic/A13_exabgp/exabgp.py | 13 +- .../topology_generator.py | 13 +- .../basic/A20_nano_internet/nano_internet.py | 8 +- .../A21_shadow_internet/shadow_internet.py | 11 +- .../A62_route_reflector/route_reflector.py | 13 +- .../control_plane_regression.py | 13 +- examples/blockchain/D20_faucet/faucet.py | 34 - .../D21_deploy_contract/deploy_contract.py | 34 - .../blockchain/D22_oracle/simple_oracle.py | 34 - .../blockchain/D23_validator/validator.py | 34 - .../R00_ethereum_pos_test/ethereum_pos.py | 34 - .../B00_mini_internet/mini_internet.py | 10 +- .../mini_internet_with_dns.py | 13 +- .../B03_hybrid_internet/hybrid_internet.py | 13 +- .../hybrid_internet_with_dns.py | 13 +- .../topology_with_locations.py | 1066 ++++++++--------- examples/internet/B20_dhcp/dhcp.py | 13 +- examples/internet/B21_etc_hosts/etc_hosts.py | 13 +- examples/internet/B22_botnet/botnet_basic.py | 13 +- .../B22_botnet/not_ready/botnet-with-dga.py | 11 +- .../internet/B23_darknet_tor/darknet_tor.py | 11 +- .../internet/B24_ip_anycast/ip_anycast.py | 8 + examples/internet/B25_pki/base_internet.py | 13 +- .../B25_pki/base_internet_with_dns.py | 13 +- examples/internet/B25_pki/pki.py | 13 +- examples/internet/B25_pki/pki_with_dns.py | 11 +- .../internet/B26_ipfs_kubo/base_component.py | 10 +- examples/internet/B26_ipfs_kubo/kubo.py | 9 +- .../B27_ipfs_kubo_dapp/base_component.py | 10 +- .../internet/B27_ipfs_kubo_dapp/kubo-eth.py | 8 + .../iperf-traffic-generator.py | 13 +- .../ditg-traffic-generator.py | 13 +- .../scapy-traffic-generator.py | 12 +- .../multi-traffic-generator.py | 22 +- .../internet/B29_email_dns/email_realistic.py | 11 +- examples/internet/B30_CDN/cdn.py | 12 +- .../mini_internet_mpls.py | 8 + .../mini_internet_exabgp.py | 13 +- .../bring_your_own_internet.py | 10 +- .../bring_your_own_internet_client.py | 11 +- .../b62_protocol_parama/protocol_parama.py | 8 + .../R01_routing_matrix/routing_matrix.py | 13 +- .../bgp_free_core_mpls.py | 13 +- .../complex_generated_routing.py | 13 +- examples/sample/sample_example.py | 13 +- examples/scion/S01_scion/scion.py | 12 +- .../S02_scion_bgp_mixed/scion_bgp_mixed.py | 14 +- .../S03_bandwidth_tester/bandwidth_tester.py | 12 +- examples/scion/S04_docker_api/docker_api.py | 14 +- .../scion/S05_scion_internet/bgp_internet.py | 11 +- .../S05_scion_internet/scion_internet.py | 11 +- .../scion-link-properties.py | 12 +- .../scion-bwtest-client.py | 12 +- .../S08_dev_service/scion_dev_service.py | 14 +- 69 files changed, 1143 insertions(+), 819 deletions(-) create mode 100644 examples/basic/A11_add_containers_new/method_3 diff --git a/examples/basic/A00_simple_as/simple_as.py b/examples/basic/A00_simple_as/simple_as.py index d19daea37..0688b3acd 100755 --- a/examples/basic/A00_simple_as/simple_as.py +++ b/examples/basic/A00_simple_as/simple_as.py @@ -17,6 +17,7 @@ from seedemu.core import Binding, Emulator, Filter from seedemu.layers import Base, Ebgp, Routing from seedemu.services import WebService +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -87,7 +88,17 @@ def run( output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=platform), str(output_dir), override=override) + docker = Docker(platform=platform) + + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + + emu.compile(docker, str(output_dir), override=override) def main() -> int: @@ -103,4 +114,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/basic/A01_transit_as/transit_as.py b/examples/basic/A01_transit_as/transit_as.py index 9c9af1beb..9222a4885 100755 --- a/examples/basic/A01_transit_as/transit_as.py +++ b/examples/basic/A01_transit_as/transit_as.py @@ -134,6 +134,13 @@ def run( ############################################################################### # Final step: Generate the docker files docker = Docker(internetMapEnabled=True, platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) emu.compile(docker, output or './output', override=override) @@ -150,4 +157,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/basic/A02a_transit_as_mpls/transit_as_mpls.py b/examples/basic/A02a_transit_as_mpls/transit_as_mpls.py index 35698e7ea..1e29aa0c0 100644 --- a/examples/basic/A02a_transit_as_mpls/transit_as_mpls.py +++ b/examples/basic/A02a_transit_as_mpls/transit_as_mpls.py @@ -17,6 +17,7 @@ from seedemu.core import Binding, Emulator, Filter from seedemu.layers import Base, Ebgp, Ibgp, Mpls, Ospf, PeerRelationship, Routing from seedemu.services import WebService +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -130,7 +131,15 @@ def run( # Generate the Docker files. output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=platform), str(output_dir), override=override) + docker = Docker(platform=platform), str(output_dir) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, override=override) def main() -> int: @@ -146,4 +155,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/basic/A02b_manual_mpls/manual_mpls.py b/examples/basic/A02b_manual_mpls/manual_mpls.py index 510652673..45b3c9b9f 100755 --- a/examples/basic/A02b_manual_mpls/manual_mpls.py +++ b/examples/basic/A02b_manual_mpls/manual_mpls.py @@ -17,6 +17,7 @@ from seedemu.core import Binding, Emulator, Filter from seedemu.layers import Base, Ebgp, Ibgp, Ospf, PeerRelationship, Routing from seedemu.services import WebService +from seedemu.containerBundle import InternetMap MANUAL_MPLS = { @@ -196,7 +197,15 @@ def run( output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=platform), str(output_dir), override=override) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=override) def main() -> int: @@ -212,4 +221,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/basic/A03a_out_to_real_world/out_to_real_world.py b/examples/basic/A03a_out_to_real_world/out_to_real_world.py index 6ed3a9cc3..ebde83b3f 100755 --- a/examples/basic/A03a_out_to_real_world/out_to_real_world.py +++ b/examples/basic/A03a_out_to_real_world/out_to_real_world.py @@ -17,6 +17,7 @@ from seedemu.core import Binding, Emulator, Filter from seedemu.layers import Base, Ebgp, Ibgp, Ospf, PeerRelationship, Routing from seedemu.services import WebService +from seedemu.containerBundle import InternetMap AKAMAI_ASN = 20940 @@ -113,7 +114,15 @@ def run( output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=platform), str(output_dir), override=override) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=override) def main() -> int: @@ -130,4 +139,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/basic/A03b_from_real_world/from_real_world.py b/examples/basic/A03b_from_real_world/from_real_world.py index 085bcb2c6..89176cbce 100755 --- a/examples/basic/A03b_from_real_world/from_real_world.py +++ b/examples/basic/A03b_from_real_world/from_real_world.py @@ -18,6 +18,7 @@ from seedemu.layers import Base, Ebgp, Ibgp, Ospf, PeerRelationship, Routing from seedemu.raps import OpenVpnRemoteAccessProvider from seedemu.services import WebService +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -100,7 +101,15 @@ def run( output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=platform), str(output_dir), override=override) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=override) def main() -> int: @@ -116,4 +125,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/basic/A04_visualization/visualization.py b/examples/basic/A04_visualization/visualization.py index 686605d2f..8533b0b52 100755 --- a/examples/basic/A04_visualization/visualization.py +++ b/examples/basic/A04_visualization/visualization.py @@ -6,6 +6,7 @@ from seedemu.compiler import Docker, Platform from examples.basic.A01_transit_as import transit_as import sys, os +from seedemu.containerBundle import InternetMap ############################################################################### # Set the platform information @@ -55,4 +56,12 @@ # Render and compile emu.render() -emu.compile(Docker(platform=platform), './output', override=True) +docker = Docker(platform=platform) +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, './output', override=True) \ No newline at end of file diff --git a/examples/basic/A05_components/components.py b/examples/basic/A05_components/components.py index a08c76464..6e63e053b 100755 --- a/examples/basic/A05_components/components.py +++ b/examples/basic/A05_components/components.py @@ -17,6 +17,7 @@ from seedemu.services import WebService from seedemu.compiler import Docker, Platform from examples.basic.A01_transit_as import transit_as +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -116,7 +117,15 @@ def run( output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=platform), str(output_dir), override=override) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=override) def main() -> int: @@ -133,4 +142,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/basic/A06_merge_emulation/merge_emulation.py b/examples/basic/A06_merge_emulation/merge_emulation.py index 59f39ad5d..57b7e5068 100755 --- a/examples/basic/A06_merge_emulation/merge_emulation.py +++ b/examples/basic/A06_merge_emulation/merge_emulation.py @@ -10,6 +10,7 @@ from seedemu.mergers import DEFAULT_MERGERS from seedemu.layers import Base, Routing, Ebgp from seedemu.compiler import Docker, Platform +from seedemu.containerBundle import InternetMap SCRIPT_DIR = Path(__file__).resolve().parent @@ -99,7 +100,15 @@ def run( output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu_merged.compile(Docker(platform=platform), str(output_dir), override=override) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu_merged, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu_merged.compile(docker, str(output_dir), override=override) def main() -> int: diff --git a/examples/basic/A07_compilers/compilers.py b/examples/basic/A07_compilers/compilers.py index fc7c21651..63b89bcad 100755 --- a/examples/basic/A07_compilers/compilers.py +++ b/examples/basic/A07_compilers/compilers.py @@ -5,6 +5,7 @@ from seedemu.core import Emulator import os, sys from examples.basic.A01_transit_as import transit_as +from seedemu.containerBundle import InternetMap ############################################################################### # Set the platform information @@ -49,7 +50,15 @@ script_dir = os.path.dirname(os.path.abspath(__file__)) output_dir = os.path.join(script_dir, 'output') os.makedirs(output_dir, exist_ok=True) -emu.compile(Docker(platform=platform), './output/regular-docker', override=True) +docker = Docker(platform=platform) +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, './output/regular-docker', override=True) emu.compile(Graphviz(), './output/graphs', override=True) emu.compile(DistributedDocker(), './output/distributed-docker', override=True) -emu.compile(GcpDistributedDocker(), './output/gcp-distributed-docker', override=True) +emu.compile(GcpDistributedDocker(), './output/gcp-distributed-docker', override=True) \ No newline at end of file diff --git a/examples/basic/A09_node_customization/node_customization.py b/examples/basic/A09_node_customization/node_customization.py index faed5609f..4b8d08c24 100755 --- a/examples/basic/A09_node_customization/node_customization.py +++ b/examples/basic/A09_node_customization/node_customization.py @@ -60,8 +60,16 @@ def main() -> None: node.appendStartCommand("python3 /myprog.py", fork=True) emu.render() - emu.compile(Docker(platform=platform), str(output), override=True) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output), override=True) if __name__ == "__main__": - main() + main() \ No newline at end of file diff --git a/examples/basic/A10_add_containers/add_containers.py b/examples/basic/A10_add_containers/add_containers.py index 7daf6cc4f..177276ede 100755 --- a/examples/basic/A10_add_containers/add_containers.py +++ b/examples/basic/A10_add_containers/add_containers.py @@ -38,4 +38,3 @@ emu.render() emu.compile(Docker(platform=platform), './output', override=True) - diff --git a/examples/basic/A11_add_containers_new/method_1/add_container.py b/examples/basic/A11_add_containers_new/method_1/add_container.py index 71cce7ce8..22415f2d3 100755 --- a/examples/basic/A11_add_containers_new/method_1/add_container.py +++ b/examples/basic/A11_add_containers_new/method_1/add_container.py @@ -149,4 +149,4 @@ def run(dumpfile = None): emu.compile(docker, './output', override=True) if __name__ == '__main__': - run() + run() \ No newline at end of file diff --git a/examples/basic/A11_add_containers_new/method_3 b/examples/basic/A11_add_containers_new/method_3 new file mode 100644 index 000000000..6aeabd3f4 --- /dev/null +++ b/examples/basic/A11_add_containers_new/method_3 @@ -0,0 +1 @@ +../A10b_add_containers \ No newline at end of file diff --git a/examples/basic/A12_bgp_mixed_backend/bgp_mixed_backend.py b/examples/basic/A12_bgp_mixed_backend/bgp_mixed_backend.py index c7b7e673d..734bc63f8 100644 --- a/examples/basic/A12_bgp_mixed_backend/bgp_mixed_backend.py +++ b/examples/basic/A12_bgp_mixed_backend/bgp_mixed_backend.py @@ -17,6 +17,7 @@ from seedemu.core import Binding, Emulator, Filter from seedemu.layers import Base, Ebgp, Ibgp, Ospf, PeerRelationship, Routing from seedemu.services import WebService +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -96,10 +97,18 @@ def main() -> int: output_dir = Path(args.output).resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=resolve_platform(args.platform)), str(output_dir), override=args.override) + docker = Docker(platform=resolve_platform(args.platform)) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=args.override) print("Generated A12 Docker output in {}".format(output_dir)) return 0 if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/basic/A13_exabgp/exabgp.py b/examples/basic/A13_exabgp/exabgp.py index 0b9dc381e..fe7a88cd5 100755 --- a/examples/basic/A13_exabgp/exabgp.py +++ b/examples/basic/A13_exabgp/exabgp.py @@ -17,6 +17,7 @@ from seedemu.core import Binding, Emulator, Filter from seedemu.layers import Base, Routing from seedemu.services import ExaBgpService +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -81,10 +82,18 @@ def main() -> int: output_dir = Path(args.output).resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=resolve_platform(args.platform)), str(output_dir), override=args.override) + docker = Docker(platform=resolve_platform(args.platform)) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=args.override) print("Generated A13 Docker output in {}".format(output_dir)) return 0 if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/basic/A15_toplogy_generator/topology_generator.py b/examples/basic/A15_toplogy_generator/topology_generator.py index 8b6d5fff4..3d38f2934 100755 --- a/examples/basic/A15_toplogy_generator/topology_generator.py +++ b/examples/basic/A15_toplogy_generator/topology_generator.py @@ -19,6 +19,7 @@ from seedemu.core import Emulator from seedemu.layers import Base, Ebgp, Ibgp, Ospf, PeerRelationship, Routing from seedemu.utilities import Makers, AutonomousSystemLocationGenerator, AutonomousSystemTopologyGenerator +from seedemu.containerBundle import InternetMap DEFAULT_IXES = [100, 101, 102] @@ -391,7 +392,15 @@ def main() -> int: # location labels have all been attached to the emulator objects. output_dir = Path(args.output).resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=resolve_platform(args.platform)), str(output_dir), override=args.override) + docker = Docker(platform=resolve_platform(args.platform)) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=args.override) write_topology_artifacts(topology, output_dir, internal_routing, locations) print(topology.summary()) print("Internal routing mode: {}".format(internal_routing["mode"])) @@ -407,4 +416,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/basic/A20_nano_internet/nano_internet.py b/examples/basic/A20_nano_internet/nano_internet.py index 672fba289..da16866eb 100755 --- a/examples/basic/A20_nano_internet/nano_internet.py +++ b/examples/basic/A20_nano_internet/nano_internet.py @@ -175,7 +175,13 @@ # Use the "seedemu-multiarch" custom image from local docker.addImage(DockerImage('seedemu-multiarch', [], local = True), priority=-1) docker.setImageOverride(as152.getHost('host2'), 'seedemu-multiarch') - +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) # Generate the Docker files emu.compile(docker, './output', override=True) diff --git a/examples/basic/A21_shadow_internet/shadow_internet.py b/examples/basic/A21_shadow_internet/shadow_internet.py index 10713e2e1..4ddd8623d 100755 --- a/examples/basic/A21_shadow_internet/shadow_internet.py +++ b/examples/basic/A21_shadow_internet/shadow_internet.py @@ -103,6 +103,13 @@ emu.render() #emu.dump('base_component.bin') +docker = Docker(platform=platform) +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) # Generate the Docker files -emu.compile(Docker(platform=platform), './output', override=True) - +emu.compile(docker, './output', override=True) diff --git a/examples/basic/A62_route_reflector/route_reflector.py b/examples/basic/A62_route_reflector/route_reflector.py index 0ea87c310..07d1ba9a6 100644 --- a/examples/basic/A62_route_reflector/route_reflector.py +++ b/examples/basic/A62_route_reflector/route_reflector.py @@ -21,6 +21,7 @@ from seedemu.core import Emulator from seedemu.layers import Base, Ebgp, Ibgp, Ospf, PeerRelationship, Routing from seedemu.utilities import Makers +from seedemu.containerBundle import InternetMap AS12_CLUSTER_ID = "10.12.0.1" @@ -211,7 +212,15 @@ def run( if render: emu.render() - emu.compile(Docker(platform=platform), output or "./output", override=override) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, output or "./output", override=override) def main() -> int: @@ -231,4 +240,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/basic/A63_control_plane_regression/control_plane_regression.py b/examples/basic/A63_control_plane_regression/control_plane_regression.py index c9ab0a55d..872884ffd 100644 --- a/examples/basic/A63_control_plane_regression/control_plane_regression.py +++ b/examples/basic/A63_control_plane_regression/control_plane_regression.py @@ -17,6 +17,7 @@ from seedemu.core import Binding, Emulator, Filter from seedemu.layers import Base, Ebgp, Ibgp, Mpls, Ospf, PeerRelationship, Routing from seedemu.services import ExaBgpService, WebService +from seedemu.containerBundle import InternetMap AS3_CLUSTER_ID = "10.3.0.1" @@ -216,10 +217,18 @@ def main() -> int: output_dir = Path(args.output).resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=resolve_platform(args.platform)), str(output_dir), override=args.override) + docker = Docker(platform=resolve_platform(args.platform)) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=args.override) print("Generated A63 Docker output in {}".format(output_dir)) return 0 if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/blockchain/D20_faucet/faucet.py b/examples/blockchain/D20_faucet/faucet.py index dfe7a0225..f9431b63c 100755 --- a/examples/blockchain/D20_faucet/faucet.py +++ b/examples/blockchain/D20_faucet/faucet.py @@ -142,22 +142,6 @@ def run( # Add Internet visualization services: topology, geographic map, and traffic observation. # The second argument is a container name suffix that distinguishes bundle instances. internet_map_bundle = InternetMap(emu, ".map.seed") - # Customize the bundle network; provide at least one IP per container, in creation order. - # All IPs must belong to the configured subnet, which should not overlap other networks. - internet_map_bundle.setDefaultNetwork( - name="internetMap_network", - prefix=".map", - ip_addresses=[ - "172.30.0.10", - "172.30.0.11", - "172.30.0.12", - "172.30.0.13", - ], - network_config={ - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.30.0.0/24", "gateway": "172.30.0.1"}]}, - }, - ) # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. internet_map_bundle.setPorts(list(range(8081, 8089))) # Register the bundle with the Docker compiler to generate its containers during emu.compile(). @@ -165,24 +149,6 @@ def run( # Add an Ethereum explorer with an indexing backend, a Web frontend, and supporting services. eth_explorer_bundle = EthExplorer(emu, ".eth.explorer.seed") - # Configure a separate explorer network with one static IP per container. - eth_explorer_bundle.setDefaultNetwork( - name="ethExplorer_network", - prefix=".eth", - ip_addresses=[ - "172.20.0.10", - "172.20.0.11", - "172.20.0.12", - "172.20.0.13", - "172.20.0.14", - "172.20.0.15", - "172.20.0.16", - ], - network_config={ - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.20.0.0/24", "gateway": "172.20.0.1"}]}, - }, - ) # The explorer Web frontend needs at least 1 host port; ports are taken from the list's end. eth_explorer_bundle.setPorts(list(range(8090, 8099))) # Include the explorer bundle in this Docker compilation. diff --git a/examples/blockchain/D21_deploy_contract/deploy_contract.py b/examples/blockchain/D21_deploy_contract/deploy_contract.py index bcaa33a94..57f9bc674 100755 --- a/examples/blockchain/D21_deploy_contract/deploy_contract.py +++ b/examples/blockchain/D21_deploy_contract/deploy_contract.py @@ -141,22 +141,6 @@ def run( # Add Internet visualization services: topology, geographic map, and traffic observation. # The second argument is a container name suffix that distinguishes bundle instances. internet_map_bundle = InternetMap(emu, ".map.seed") - # Customize the bundle network; provide at least one IP per container, in creation order. - # All IPs must belong to the configured subnet, which should not overlap other networks. - internet_map_bundle.setDefaultNetwork( - name="internetMap_network", - prefix=".map", - ip_addresses=[ - "172.30.0.10", - "172.30.0.11", - "172.30.0.12", - "172.30.0.13", - ], - network_config={ - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.30.0.0/24", "gateway": "172.30.0.1"}]}, - }, - ) # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. internet_map_bundle.setPorts(list(range(8081, 8089))) # Register the bundle with the Docker compiler to generate its containers during emu.compile(). @@ -164,24 +148,6 @@ def run( # Add an Ethereum explorer with an indexing backend, a Web frontend, and supporting services. eth_explorer_bundle = EthExplorer(emu, ".eth.explorer.seed") - # Configure a separate explorer network with one static IP per container. - eth_explorer_bundle.setDefaultNetwork( - name="ethExplorer_network", - prefix=".eth", - ip_addresses=[ - "172.20.0.10", - "172.20.0.11", - "172.20.0.12", - "172.20.0.13", - "172.20.0.14", - "172.20.0.15", - "172.20.0.16", - ], - network_config={ - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.20.0.0/24", "gateway": "172.20.0.1"}]}, - }, - ) # The explorer Web frontend needs at least 1 host port; ports are taken from the list's end. eth_explorer_bundle.setPorts(list(range(8090, 8099))) # Include the explorer bundle in this Docker compilation. diff --git a/examples/blockchain/D22_oracle/simple_oracle.py b/examples/blockchain/D22_oracle/simple_oracle.py index 74618c215..c78a64b9e 100755 --- a/examples/blockchain/D22_oracle/simple_oracle.py +++ b/examples/blockchain/D22_oracle/simple_oracle.py @@ -222,22 +222,6 @@ def run( # Add Internet visualization services: topology, geographic map, and traffic observation. # The second argument is a container name suffix that distinguishes bundle instances. internet_map_bundle = InternetMap(emu, ".map.seed") - # Customize the bundle network; provide at least one IP per container, in creation order. - # All IPs must belong to the configured subnet, which should not overlap other networks. - internet_map_bundle.setDefaultNetwork( - name="internetMap_network", - prefix=".map", - ip_addresses=[ - "172.30.0.10", - "172.30.0.11", - "172.30.0.12", - "172.30.0.13", - ], - network_config={ - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.30.0.0/24", "gateway": "172.30.0.1"}]}, - }, - ) # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. internet_map_bundle.setPorts(list(range(8081, 8089))) # Register the bundle with the Docker compiler to generate its containers during emu.compile(). @@ -245,24 +229,6 @@ def run( # Add an Ethereum explorer with an indexing backend, a Web frontend, and supporting services. eth_explorer_bundle = EthExplorer(emu, ".eth.explorer.seed") - # Configure a separate explorer network with one static IP per container. - eth_explorer_bundle.setDefaultNetwork( - name="ethExplorer_network", - prefix=".eth", - ip_addresses=[ - "172.20.0.10", - "172.20.0.11", - "172.20.0.12", - "172.20.0.13", - "172.20.0.14", - "172.20.0.15", - "172.20.0.16", - ], - network_config={ - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.20.0.0/24", "gateway": "172.20.0.1"}]}, - }, - ) # The explorer Web frontend needs at least 1 host port; ports are taken from the list's end. eth_explorer_bundle.setPorts(list(range(8090, 8099))) # Include the explorer bundle in this Docker compilation. diff --git a/examples/blockchain/D23_validator/validator.py b/examples/blockchain/D23_validator/validator.py index 1fe44f37d..980be6cd6 100755 --- a/examples/blockchain/D23_validator/validator.py +++ b/examples/blockchain/D23_validator/validator.py @@ -152,22 +152,6 @@ def run( # Add Internet visualization services: topology, geographic map, and traffic observation. # The second argument is a container name suffix that distinguishes bundle instances. internet_map_bundle = InternetMap(emu, ".map.seed") - # Customize the bundle network; provide at least one IP per container, in creation order. - # All IPs must belong to the configured subnet, which should not overlap other networks. - internet_map_bundle.setDefaultNetwork( - name="internetMap_network", - prefix=".map", - ip_addresses=[ - "172.30.0.10", - "172.30.0.11", - "172.30.0.12", - "172.30.0.13", - ], - network_config={ - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.30.0.0/24", "gateway": "172.30.0.1"}]}, - }, - ) # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. internet_map_bundle.setPorts(list(range(8081, 8089))) # Register the bundle with the Docker compiler to generate its containers during emu.compile(). @@ -175,24 +159,6 @@ def run( # Add an Ethereum explorer with an indexing backend, a Web frontend, and supporting services. eth_explorer_bundle = EthExplorer(emu, ".eth.explorer.seed") - # Configure a separate explorer network with one static IP per container. - eth_explorer_bundle.setDefaultNetwork( - name="ethExplorer_network", - prefix=".eth", - ip_addresses=[ - "172.20.0.10", - "172.20.0.11", - "172.20.0.12", - "172.20.0.13", - "172.20.0.14", - "172.20.0.15", - "172.20.0.16", - ], - network_config={ - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.20.0.0/24", "gateway": "172.20.0.1"}]}, - }, - ) # The explorer Web frontend needs at least 1 host port; ports are taken from the list's end. eth_explorer_bundle.setPorts(list(range(8090, 8099))) # Include the explorer bundle in this Docker compilation. diff --git a/examples/blockchain/R00_ethereum_pos_test/ethereum_pos.py b/examples/blockchain/R00_ethereum_pos_test/ethereum_pos.py index 6e3359780..afd9495f8 100644 --- a/examples/blockchain/R00_ethereum_pos_test/ethereum_pos.py +++ b/examples/blockchain/R00_ethereum_pos_test/ethereum_pos.py @@ -165,22 +165,6 @@ # Add Internet visualization services: topology, geographic map, and traffic observation. # The second argument is a container name suffix that distinguishes bundle instances. internet_map_bundle = InternetMap(emu, ".map.seed") -# Customize the bundle network; provide at least one IP per container, in creation order. -# All IPs must belong to the configured subnet, which should not overlap other networks. -internet_map_bundle.setDefaultNetwork( - name="internetMap_network", - prefix=".map", - ip_addresses=[ - "172.30.0.10", - "172.30.0.11", - "172.30.0.12", - "172.30.0.13", - ], - network_config={ - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.30.0.0/24", "gateway": "172.30.0.1"}]}, - }, -) # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. internet_map_bundle.setPorts(list(range(8081, 8089))) # Register the bundle with the Docker compiler to generate its containers during emu.compile(). @@ -188,24 +172,6 @@ # Add an Ethereum explorer with an indexing backend, a Web frontend, and supporting services. eth_explorer_bundle = EthExplorer(emu, ".eth.explorer.seed") -# Configure a separate explorer network with one static IP per container. -eth_explorer_bundle.setDefaultNetwork( - name="ethExplorer_network", - prefix=".eth", - ip_addresses=[ - "172.20.0.10", - "172.20.0.11", - "172.20.0.12", - "172.20.0.13", - "172.20.0.14", - "172.20.0.15", - "172.20.0.16", - ], - network_config={ - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.20.0.0/24", "gateway": "172.20.0.1"}]}, - }, -) # The explorer Web frontend needs at least 1 host port; ports are taken from the list's end. eth_explorer_bundle.setPorts(list(range(8090, 8099))) # Include the explorer bundle in this Docker compilation. diff --git a/examples/internet/B00_mini_internet/mini_internet.py b/examples/internet/B00_mini_internet/mini_internet.py index d4d67a996..705fd49a1 100755 --- a/examples/internet/B00_mini_internet/mini_internet.py +++ b/examples/internet/B00_mini_internet/mini_internet.py @@ -17,6 +17,7 @@ from seedemu.core import Emulator from seedemu.layers import Base, Ebgp, Ibgp, Ospf, PeerRelationship, Routing from seedemu.utilities import Makers +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -173,6 +174,13 @@ def run( emu.render() docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) emu.compile(docker, output or "./output", override=override) @@ -192,4 +200,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/internet/B02_mini_internet_with_dns/mini_internet_with_dns.py b/examples/internet/B02_mini_internet_with_dns/mini_internet_with_dns.py index f8797ec1d..bf121be4f 100755 --- a/examples/internet/B02_mini_internet_with_dns/mini_internet_with_dns.py +++ b/examples/internet/B02_mini_internet_with_dns/mini_internet_with_dns.py @@ -21,6 +21,7 @@ from seedemu.layers import Base from examples.internet.B00_mini_internet import mini_internet from examples.internet.B01_dns_component import dns_component +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -123,7 +124,15 @@ def run( emu.render() output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=platform), str(output_dir), override=override) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=override) def main() -> int: @@ -139,4 +148,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/internet/B03_hybrid_internet/hybrid_internet.py b/examples/internet/B03_hybrid_internet/hybrid_internet.py index 03f2ba782..2a3d03bb5 100755 --- a/examples/internet/B03_hybrid_internet/hybrid_internet.py +++ b/examples/internet/B03_hybrid_internet/hybrid_internet.py @@ -21,6 +21,7 @@ from seedemu.core import Emulator from seedemu.layers import Base, Ebgp, PeerRelationship from seedemu.raps import OpenVpnRemoteAccessProvider +from seedemu.containerBundle import InternetMap SYRACUSE_ASN = 11872 @@ -105,7 +106,15 @@ def run( output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=platform), str(output_dir), override=override) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=override) def main() -> int: @@ -123,4 +132,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/internet/B05_hybrid_internet_with_dns/hybrid_internet_with_dns.py b/examples/internet/B05_hybrid_internet_with_dns/hybrid_internet_with_dns.py index 4558cc237..9211964c1 100755 --- a/examples/internet/B05_hybrid_internet_with_dns/hybrid_internet_with_dns.py +++ b/examples/internet/B05_hybrid_internet_with_dns/hybrid_internet_with_dns.py @@ -9,6 +9,7 @@ from examples.internet.B03_hybrid_internet import hybrid_internet from examples.internet.B04_hybrid_dns_component import hybrid_dns_component import os, sys +from seedemu.containerBundle import InternetMap def run(dumpfile = None): ############################################################################### @@ -78,7 +79,15 @@ def run(dumpfile = None): emu.dump(dumpfile) else: emu.render() - emu.compile(Docker(platform=platform), './output', override=True) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, './output', override=True) if __name__ == "__main__": - run() + run() \ No newline at end of file diff --git a/examples/internet/B07_topology_with_locations/topology_with_locations.py b/examples/internet/B07_topology_with_locations/topology_with_locations.py index c2d3cb7c8..b96e2780e 100644 --- a/examples/internet/B07_topology_with_locations/topology_with_locations.py +++ b/examples/internet/B07_topology_with_locations/topology_with_locations.py @@ -1,541 +1,525 @@ -#!/usr/bin/env python3 -"""Generate transit and stub ASes with two hosts per IX (500 total nodes).""" - -from __future__ import annotations - -import argparse -from collections import Counter -from ipaddress import IPv4Network -from math import asin, cos, radians, sin, sqrt -from pathlib import Path -import random -import sys -from typing import List - -SCRIPT_DIR = Path(__file__).resolve().parent -REPO_ROOT = SCRIPT_DIR.parents[2] -sys.path.insert(0, str(REPO_ROOT)) -sys.path.insert(0, str(SCRIPT_DIR)) - -from seedemu.compiler import Docker, Platform -from seedemu.core import Emulator -from seedemu.layers import Base, Ebgp, Ibgp, Ospf, PeerRelationship, Routing -from seedemu.utilities import Makers -from geopy.distance import geodesic -from seedemu.containerBundle import InternetMap, ContainerBundle - -# The supplied catalogue is named cityies.py, not cities.py. -from cities import IX_LOCATIONS - -META = "org.seedsecuritylabs.seedemu.meta." -HOSTS_PER_STUB = 2 -STUB_ASNS = {ix: 150 + ix - 100 for ix in range(100, 120)} -STUB_NODE_COUNT = len(STUB_ASNS) * (1 + HOSTS_PER_STUB) -MIN_NODE_COUNT = 58 + STUB_NODE_COUNT -# Conservative core exclusions; populated peripheral cities remain eligible. -# south, north, west, east -DESERT_CORES = [ - (19, 29, -12, 32), - (19, 24, 44, 55), - (37, 41, 77, 89), - (42, 46, 95, 110), - (39, 44, 54, 64), - (-26, -19, 13, 16), - (-27, -20, 19, 24), - (-26, -20, -70, -67), - (-30, -20, 120, 140), -] - - -def distance(a, b): - lat1, lon1, lat2, lon2 = map(radians, (a[3], a[4], b[3], b[4])) - h = sin((lat2 - lat1) / 2) ** 2 + cos(lat1) * cos(lat2) * sin((lon2 - lon1) / 2) ** 2 - return 12742 * asin(sqrt(min(1.0, max(0.0, h)))) - - -def valid_land(lat, lon): - try: - from global_land_mask import globe - except ImportError as exc: - raise RuntimeError("Install requirements.txt in this example directory first.") from exc - return ( - -60 < lat < 66 - and -180 <= lon <= 180 - and not any(s <= lat <= n and w <= lon <= e for s, n, w, e in DESERT_CORES) - and bool(globe.is_land(lat, lon)) - ) - - -def load_cities(): - unique = {} - for city in IX_LOCATIONS: - lat, lon = city[3:5] - if not valid_land(lat, lon): - continue - unique.setdefault((lat, lon), city) - return list(unique.values()) - - -def ix_display_locations(anchors, plans): - """Keep IX semantics at the anchor; choose a small, land-checked display offset.""" - occupied = {tuple(round(v, 6) for v in c[3:5]) for c in anchors.values()} - occupied.update(tuple(round(v, 6) for v in c[3:5]) for p in plans for _, c in p) - result = {} - for ix, city in anchors.items(): - nearest = min(distance(city, c) for p in plans for i, c in p if i == ix) - maximum = min(2.0, nearest * 0.09) - for scale in (1, 0.5, 0.25, 0.125, 0.0625, 0.03125): - radius = maximum * scale - for step in range(72): - bearing = (ix * 137.508 + step * 5) % 360 - point = geodesic(kilometers=radius).destination(city[3:5], bearing) - coord = (round(point.latitude, 6), round(point.longitude, 6)) - if coord in occupied or not valid_land(*coord): - continue - # Sample every <=100 m to avoid hopping across coastal water. - samples = max(2, int(radius / 0.1) + 1) - path = [ - geodesic(kilometers=radius * k / samples).destination(city[3:5], bearing) - for k in range(1, samples + 1) - ] - if not all(valid_land(p.latitude, p.longitude) for p in path): - continue - result[ix] = (*city[:3], *coord, city[5]) - occupied.add(coord) - break - if ix in result: - break - if ix not in result: - raise ValueError(f"Cannot find a safe local display offset for IX{ix} ({city[2]}).") - return result - - -def select_anchors(cities): - """Spread 20 IXes over six continents using farthest-point sampling.""" - quotas = { - "North America": 3, - "South America": 3, - "Europe": 4, - "Africa": 3, - "Asia": 4, - "Oceania": 3, - } - anchors = {} - for region, count in quotas.items(): - pool = [c for c in cities if c[0] == region] - chosen = [pool[0]] - while len(chosen) < count: - chosen.append( - max( - (c for c in pool if c not in chosen), - key=lambda c: min(distance(c, p) for p in chosen), - ) - ) - for city in chosen: - anchors[100 + len(anchors)] = city - return anchors - - -def backbone(anchors): - """A spanning tree: exhaust same-continent edges before intercontinental ones.""" - reached = {next(iter(anchors))} - edges = [] - while len(reached) < len(anchors): - a, b = min( - ((a, b) for a in reached for b in anchors if b not in reached), - key=lambda pair: ( - anchors[pair[0]][0] != anchors[pair[1]][0], - distance(anchors[pair[0]], anchors[pair[1]]), - pair, - ), - ) - edges.append([a, b]) - reached.add(b) - return edges - - -def plan_topology(node_count, cities, seed): - if node_count < 58: - raise ValueError("At least 58 nodes are needed for 20 connected IXes and transit routers.") - if node_count > len(cities): - raise ValueError( - f"Requested {node_count} nodes; only {len(cities)} unique validated cities available." - ) - anchors = select_anchors(cities) - available = { - c: min( - (ix for ix in anchors if anchors[ix][0] == c[0]), - key=lambda ix: distance(c, anchors[ix]), - ) - for c in cities - if c not in anchors.values() - } - region_capacity = Counter(c[0] for c in available) - rng = random.Random(seed) - # Cache nearest selected-point distances for efficient global dispersion. - separation = {c: min(distance(c, a) for a in anchors.values()) for c in available} - used = Counter() - - def take(ix): - pool = [c for c in available if available[c] == ix] - if not pool: - pool = [c for c in available if c[0] == anchors[ix][0]] - if not pool: - raise ValueError(f"No unused land cities remain for IX{ix}. Reduce --nodes.") - # Alternate medium and far rings where the catalogue supports them. - medium = used[ix] % 2 == 0 - ring = [ - c - for c in pool - if ( - 300 <= distance(c, anchors[ix]) <= 900 - if medium - else distance(c, anchors[ix]) > 900 - ) - ] - pool = ring or pool - rng.shuffle(pool) - city = max(pool, key=lambda c: separation[c]) - del available[city] - used[ix] += 1 - for c in available: - separation[c] = min(separation[c], distance(c, city)) - return (ix, city) - - plans = [[take(ix) for ix in edge] for edge in backbone(anchors)] - remaining = node_count - 20 - 38 - # Add regional transit ASes; explicit LAN prefixes support ASNs above 255. - while remaining: - counts = Counter(available.values()) - region_remaining = Counter(c[0] for c in available) - region_used = Counter() - for ix, count in used.items(): - region_used[anchors[ix][0]] += count - eligible = [ix for ix in anchors if region_remaining[anchors[ix][0]]] - if remaining == 1: - # Makers creates exactly one r per AS/IX: never repeat an IX. - candidates = [ - (ix, p) - for ix in eligible - for p in plans - if all(j != ix and anchors[j][0] == anchors[ix][0] for j, _ in p) - ] - if not candidates: - raise ValueError( - "No regional Transit AS can accept another distinct IX; reduce --nodes." - ) - ix, plan = min( - candidates, - key=lambda item: ( - used[item[0]] / max(1, counts[item[0]] + used[item[0]]), - len(item[1]), - item[0], - ), - ) - plan.append(take(ix)) - remaining -= 1 - continue - pairs = [ - (a, b) - for a in eligible - for b in eligible - if a < b and anchors[a][0] == anchors[b][0] and region_remaining[anchors[a][0]] >= 2 - ] - if not pairs: - raise ValueError("Insufficient regional city pairs remain; reduce --nodes.") - a, b = min( - pairs, - key=lambda p: ( - region_used[anchors[p[0]][0]] - / min(region_capacity[anchors[p[0]][0]], node_count / 6), - sum(used[i] / max(1, counts[i] + used[i]) for i in p), - distance(anchors[p[0]], anchors[p[1]]), - p, - ), - ) - plans.append([take(a), take(b)]) - remaining -= 2 - return anchors, plans - - -def set_geo(node, city, role): - region, country, name, lat, lon, _ = city - node.setGeo(lat, lon, name) - for key, value in { - "geo.lat": f"{lat:.6f}", - "geo.lon": f"{lon:.6f}", - "geo.city": name, - "geo.country": country, - "geo.region": region, - "geo.source": "cityies-land-mask-validated", - "topology.role": role, - }.items(): - node.setLabel(key, value) - - -def plan_stubs(cities, anchors): - """Reserve a router and two nearby, distinct land cities for each stub.""" - available = set(cities) - set(anchors.values()) - stubs = {} - for ix, anchor in anchors.items(): - candidates = sorted( - (c for c in available if c[0] == anchor[0]), key=lambda c: (distance(anchor, c), c) - ) - for router in candidates: - nearby = [ - c for c in candidates if c[1] == router[1] and 20 <= distance(router, c) <= 300 - ] - if len(nearby) < HOSTS_PER_STUB: - continue - first = max(nearby, key=lambda c: (distance(router, c), c)) - others = [c for c in nearby if distance(first, c) >= 20] - if not others: - continue - second = max(others, key=lambda c: (min(distance(router, c), distance(first, c)), c)) - stubs[ix] = [router, first, second] - available.difference_update(stubs[ix]) - break - else: - raise ValueError(f"No unused regional city cluster for IX{ix} stub and hosts") - return stubs - - -def transit_peerings(records): - """Build a rooted provider/customer tree over existing shared IX LANs. - - RS peers export only local/customer routes, so a chain of RS peers cannot - provide transit. Like B00, explicit Provider sessions carry full routes - downstream and customer prefixes upstream. The first AS is the root; - backbone records introduce every IX before regional records are attached. - """ - root = records[0]["asn"] - owners = {ix: root for ix in records[0]["ixes"]} - depths = {root: 0} - peerings = [] - for record in records[1:]: - candidates = [ - (depths[owners[ix]], ix, owners[ix]) for ix in set(record["ixes"]) if ix in owners - ] - if not candidates: - raise ValueError(f"AS{record['asn']} has no shared IX with the transit backbone") - depth, ix, provider = min(candidates) - customer = record["asn"] - peerings.append((ix, provider, customer)) - depths[customer] = depth + 1 - for joined_ix in record["ixes"]: - owners.setdefault(joined_ix, customer) - return peerings - - -class TransitMakerBase: - """Adapt the original four-argument Maker without changing SeedEMU APIs. - - The Maker only calls createAutonomousSystem, createRouter and createNetwork. - Store the real AS in Base and supply explicit LAN prefixes through this - small factory adapter, including for ASNs above 255. - """ - - def __init__(self, base, prefixes): - self.base = base - self.prefixes = prefixes - - def createAutonomousSystem(self, asn): - return TransitMakerAs(self.base.createAutonomousSystem(asn), self.prefixes) - - -class TransitMakerAs: - def __init__(self, system, prefixes): - self.system = system - self.prefixes = prefixes - - def createRouter(self, name): - return self.system.createRouter(name) - - def createNetwork(self, name): - return self.system.createNetwork(name, prefix=self.prefixes[name]) - - -def build_emulator(seed=42, node_count=200): - if node_count < MIN_NODE_COUNT: - raise ValueError( - f"At least {MIN_NODE_COUNT} nodes are needed, including 20 stubs and 40 hosts." - ) - cities = load_cities() - anchors = select_anchors(cities) - stubs = plan_stubs(cities, anchors) - reserved_cities = {c for cluster in stubs.values() for c in cluster} - anchors, plans = plan_topology( - node_count - STUB_NODE_COUNT, [c for c in cities if c not in reserved_cities], seed - ) - displays = ix_display_locations( - anchors, plans + [[(ix, c) for c in cluster] for ix, cluster in stubs.items()] - ) - emu, base, ebgp = Emulator(), Base(), Ebgp() - members = {ix: [] for ix in anchors} - for ix, city in anchors.items(): - exchange = base.createInternetExchange(ix, rsAddress=f"10.{ix}.0.254") - exchange.getPeeringLan().setDisplayName(f"{city[2]}-IX{ix}") - server = exchange.getRouteServerNode() - set_geo(server, displays[ix], "ix-route-server") - server.setLabel("geo.source", "ix-display-offset-land-validated") - server.setLabel("geo.anchor_ix", str(ix)) - server.setLabel("geo.anchor_lat", f"{city[3]:.6f}") - server.setLabel("geo.anchor_lon", f"{city[4]:.6f}") - server.setLabel("geo.display_offset_km", f"{distance(city, displays[ix]):.6f}") - asns = iter(a for a in range(2, 65535) if a not in anchors and a not in STUB_ASNS.values()) - # Avoid 172.17.0.0/16 (Docker's usual default bridge). IX LANs occupy - # 10.100..119.0.0/24 and Routing loopbacks occupy 10.0.0.0/16. - internal_prefixes = ( - p - for p in IPv4Network("10.128.0.0/9").subnets(new_prefix=24) - if int(str(p.network_address).split(".")[1]) not in STUB_ASNS.values() - ) - records = [] - for plan in plans: - asn = next(asns) - joined_ixes = [ix for ix, _ in plan] - # Short local tree rather than a full mesh. - reached = {0} - links = [] - while len(reached) < len(plan): - a, b = min( - ((a, b) for a in reached for b in range(len(plan)) if b not in reached), - key=lambda p: distance(plan[p[0]][1], plan[p[1]][1]), - ) - links.append((joined_ixes[a], joined_ixes[b])) - reached.add(b) - addresses = {} - for ix in joined_ixes: - # .253 is reserved for the stub router and .254 for the route server. - if len(members[ix]) >= 251: - raise ValueError(f"IX{ix} exceeds its /24 address capacity; reduce --nodes.") - addresses[ix] = f"10.{ix}.0.{2 + len(members[ix])}" - maker_base = TransitMakerBase( - base, {f"net_{a}_{b}": str(next(internal_prefixes)) for a, b in links} - ) - Makers.makeTransitAs(maker_base, asn, joined_ixes, links) - system = base.getAutonomousSystem(asn) - for ix, city in plan: - router = system.getRouter(f"r{ix}") - # Replace the Maker's pending auto address before Base configures it. - router.updateNetwork(f"ix{ix}", addresses[ix]) - members[ix].append(asn) - set_geo(router, city, "transit-router") - router.setLabel("geo.anchor_ix", str(ix)) - router.setLabel("geo.radius_km", f"{distance(city, anchors[ix]):.3f}") - records.append({"asn": asn, "ixes": joined_ixes, "links": links, "kind": "transit"}) - for ix, peers in members.items(): - ebgp.addRsPeers(ix, list(dict.fromkeys(peers))) - for ix, asn in STUB_ASNS.items(): - Makers.makeStubAsWithHosts(emu, base, asn, ix, HOSTS_PER_STUB) - stub = base.getAutonomousSystem(asn) - router = stub.getRouter("router0") - router.updateNetwork(f"ix{ix}", f"10.{ix}.0.253") - set_geo(router, stubs[ix][0], "stub-router") - router.setLabel("geo.anchor_ix", str(ix)) - for index in range(HOSTS_PER_STUB): - host = stub.getHost(f"host_{index}") - set_geo(host, stubs[ix][index + 1], "stub-host") - host.setLabel("geo.anchor_ix", str(ix)) - host.setLabel("geo.anchor_router", f"as{asn}/router0") - records.append({"asn": asn, "ixes": [ix], "links": [], "kind": "stub"}) - for ix, provider, customer in transit_peerings(records): - # Same orientation as B00: provider exports ALL routes to its customer. - ebgp.addPrivatePeerings(ix, [provider], [customer], PeerRelationship.Provider) - for layer in (base, Routing(), ebgp, Ibgp(), Ospf()): - emu.addLayer(layer) - return emu, records, members - - -class GeoDocker(Docker): - __containerBundles: List[ContainerBundle] = [] - - def __init__(self, **kwargs): - super().__init__(**kwargs) - self.anchors = select_anchors(load_cities()) - - def _getNetMeta(self, net): - labels = super()._getNetMeta(net) - scope, _, name = net.getRegistryInfo() - if scope == "ix": - city = self.anchors[int(name.removeprefix("ix"))] - for key, value in zip(("geo.lat", "geo.lon"), city[3:5]): - labels += f' {META}{key}: "{value:.6f}"\n' - return labels - - -def parse_args(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("legacy_platform", nargs="?", choices=["amd", "arm"]) - parser.add_argument("--platform", choices=["amd", "arm"]) - parser.add_argument( - "--nodes", - "--node-count", - type=int, - default=500, - help=f"Total routers + IX route servers + hosts (default: 500; minimum: {MIN_NODE_COUNT}).", - ) - parser.add_argument("--output", default=str(SCRIPT_DIR / "output")) - parser.add_argument("--dumpfile") - parser.add_argument("--seed", type=int, default=42) - parser.add_argument("--override", dest="override", action="store_true", default=True) - parser.add_argument("--no-override", dest="override", action="store_false") - parser.add_argument("--skip-render", dest="render", action="store_false", default=True) - args = parser.parse_args() - args.platform = args.platform or args.legacy_platform or "amd" - if args.nodes < MIN_NODE_COUNT: - parser.error(f"--nodes must be at least {MIN_NODE_COUNT}") - return args - - -def main(): - args = parse_args() - emu, records, members = build_emulator(args.seed, args.nodes) - if args.dumpfile: - emu.dump(args.dumpfile) - return 0 - if args.render: - emu.render() - output = Path(args.output).resolve() - output.parent.mkdir(parents=True, exist_ok=True) - geoDocker = GeoDocker( - internetMapEnabled=False, - platform=Platform.AMD64 if args.platform == "amd" else Platform.ARM64, - ) - - # Add Internet visualization services: topology, geographic map, and traffic observation. - # The second argument is a container name suffix that distinguishes bundle instances. - bundle = InternetMap(emu, ".map.seed") - # Customize the bundle network; provide at least one IP per container, in creation order. - # All IPs must belong to the configured subnet, which should not overlap other networks. - bundle.setDefaultNetwork( - name="internetMap_network", - prefix=".map", - ip_addresses=[ - "172.30.0.10", - "172.30.0.11", - "172.30.0.12", - "172.30.0.13", - ], - network_config={ - "driver": "bridge", - "ipam": {"config": [{"subnet": "172.30.0.0/24", "gateway": "172.30.0.1"}]}, - }, - ) - # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. - bundle.setPorts(list(range(8081, 8089))) - # Register the bundle with the Docker compiler to generate its containers during emu.compile(). - geoDocker.addContainerBundle(bundle) - - emu.compile(geoDocker, str(output), override=args.override) - - print( - f"Generated {args.nodes} nodes: 20 IX route servers + {args.nodes-80} transit routers" - f" + 20 stub routers + 40 hosts, {len(records)} ASes." - ) - print(f"Docker output: {output}") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) +"""Generate transit and stub ASes with two hosts per IX (500 total nodes).""" + +from __future__ import annotations +from seedemu.containerBundle import InternetMap + +import argparse +from collections import Counter +from ipaddress import IPv4Network +from math import asin, cos, radians, sin, sqrt +from pathlib import Path +import random +import sys +from typing import List + +SCRIPT_DIR = Path(__file__).resolve().parent +REPO_ROOT = SCRIPT_DIR.parents[2] +sys.path.insert(0, str(REPO_ROOT)) +sys.path.insert(0, str(SCRIPT_DIR)) + +from seedemu.compiler import Docker, Platform +from seedemu.core import Emulator +from seedemu.layers import Base, Ebgp, Ibgp, Ospf, PeerRelationship, Routing +from seedemu.utilities import Makers +from geopy.distance import geodesic +from seedemu.containerBundle import InternetMap, ContainerBundle + +# The supplied catalogue is named cityies.py, not cities.py. +from cities import IX_LOCATIONS + +META = "org.seedsecuritylabs.seedemu.meta." +HOSTS_PER_STUB = 2 +STUB_ASNS = {ix: 150 + ix - 100 for ix in range(100, 120)} +STUB_NODE_COUNT = len(STUB_ASNS) * (1 + HOSTS_PER_STUB) +MIN_NODE_COUNT = 58 + STUB_NODE_COUNT +# Conservative core exclusions; populated peripheral cities remain eligible. +# south, north, west, east +DESERT_CORES = [ + (19, 29, -12, 32), + (19, 24, 44, 55), + (37, 41, 77, 89), + (42, 46, 95, 110), + (39, 44, 54, 64), + (-26, -19, 13, 16), + (-27, -20, 19, 24), + (-26, -20, -70, -67), + (-30, -20, 120, 140), +] + + +def distance(a, b): + lat1, lon1, lat2, lon2 = map(radians, (a[3], a[4], b[3], b[4])) + h = sin((lat2 - lat1) / 2) ** 2 + cos(lat1) * cos(lat2) * sin((lon2 - lon1) / 2) ** 2 + return 12742 * asin(sqrt(min(1.0, max(0.0, h)))) + + +def valid_land(lat, lon): + try: + from global_land_mask import globe + except ImportError as exc: + raise RuntimeError("Install requirements.txt in this example directory first.") from exc + return ( + -60 < lat < 66 + and -180 <= lon <= 180 + and not any(s <= lat <= n and w <= lon <= e for s, n, w, e in DESERT_CORES) + and bool(globe.is_land(lat, lon)) + ) + + +def load_cities(): + unique = {} + for city in IX_LOCATIONS: + lat, lon = city[3:5] + if not valid_land(lat, lon): + continue + unique.setdefault((lat, lon), city) + return list(unique.values()) + + +def ix_display_locations(anchors, plans): + """Keep IX semantics at the anchor; choose a small, land-checked display offset.""" + occupied = {tuple(round(v, 6) for v in c[3:5]) for c in anchors.values()} + occupied.update(tuple(round(v, 6) for v in c[3:5]) for p in plans for _, c in p) + result = {} + for ix, city in anchors.items(): + nearest = min(distance(city, c) for p in plans for i, c in p if i == ix) + maximum = min(2.0, nearest * 0.09) + for scale in (1, 0.5, 0.25, 0.125, 0.0625, 0.03125): + radius = maximum * scale + for step in range(72): + bearing = (ix * 137.508 + step * 5) % 360 + point = geodesic(kilometers=radius).destination(city[3:5], bearing) + coord = (round(point.latitude, 6), round(point.longitude, 6)) + if coord in occupied or not valid_land(*coord): + continue + # Sample every <=100 m to avoid hopping across coastal water. + samples = max(2, int(radius / 0.1) + 1) + path = [ + geodesic(kilometers=radius * k / samples).destination(city[3:5], bearing) + for k in range(1, samples + 1) + ] + if not all(valid_land(p.latitude, p.longitude) for p in path): + continue + result[ix] = (*city[:3], *coord, city[5]) + occupied.add(coord) + break + if ix in result: + break + if ix not in result: + raise ValueError(f"Cannot find a safe local display offset for IX{ix} ({city[2]}).") + return result + + +def select_anchors(cities): + """Spread 20 IXes over six continents using farthest-point sampling.""" + quotas = { + "North America": 3, + "South America": 3, + "Europe": 4, + "Africa": 3, + "Asia": 4, + "Oceania": 3, + } + anchors = {} + for region, count in quotas.items(): + pool = [c for c in cities if c[0] == region] + chosen = [pool[0]] + while len(chosen) < count: + chosen.append( + max( + (c for c in pool if c not in chosen), + key=lambda c: min(distance(c, p) for p in chosen), + ) + ) + for city in chosen: + anchors[100 + len(anchors)] = city + return anchors + + +def backbone(anchors): + """A spanning tree: exhaust same-continent edges before intercontinental ones.""" + reached = {next(iter(anchors))} + edges = [] + while len(reached) < len(anchors): + a, b = min( + ((a, b) for a in reached for b in anchors if b not in reached), + key=lambda pair: ( + anchors[pair[0]][0] != anchors[pair[1]][0], + distance(anchors[pair[0]], anchors[pair[1]]), + pair, + ), + ) + edges.append([a, b]) + reached.add(b) + return edges + + +def plan_topology(node_count, cities, seed): + if node_count < 58: + raise ValueError("At least 58 nodes are needed for 20 connected IXes and transit routers.") + if node_count > len(cities): + raise ValueError( + f"Requested {node_count} nodes; only {len(cities)} unique validated cities available." + ) + anchors = select_anchors(cities) + available = { + c: min( + (ix for ix in anchors if anchors[ix][0] == c[0]), + key=lambda ix: distance(c, anchors[ix]), + ) + for c in cities + if c not in anchors.values() + } + region_capacity = Counter(c[0] for c in available) + rng = random.Random(seed) + # Cache nearest selected-point distances for efficient global dispersion. + separation = {c: min(distance(c, a) for a in anchors.values()) for c in available} + used = Counter() + + def take(ix): + pool = [c for c in available if available[c] == ix] + if not pool: + pool = [c for c in available if c[0] == anchors[ix][0]] + if not pool: + raise ValueError(f"No unused land cities remain for IX{ix}. Reduce --nodes.") + # Alternate medium and far rings where the catalogue supports them. + medium = used[ix] % 2 == 0 + ring = [ + c + for c in pool + if ( + 300 <= distance(c, anchors[ix]) <= 900 + if medium + else distance(c, anchors[ix]) > 900 + ) + ] + pool = ring or pool + rng.shuffle(pool) + city = max(pool, key=lambda c: separation[c]) + del available[city] + used[ix] += 1 + for c in available: + separation[c] = min(separation[c], distance(c, city)) + return (ix, city) + + plans = [[take(ix) for ix in edge] for edge in backbone(anchors)] + remaining = node_count - 20 - 38 + # Add regional transit ASes; explicit LAN prefixes support ASNs above 255. + while remaining: + counts = Counter(available.values()) + region_remaining = Counter(c[0] for c in available) + region_used = Counter() + for ix, count in used.items(): + region_used[anchors[ix][0]] += count + eligible = [ix for ix in anchors if region_remaining[anchors[ix][0]]] + if remaining == 1: + # Makers creates exactly one r per AS/IX: never repeat an IX. + candidates = [ + (ix, p) + for ix in eligible + for p in plans + if all(j != ix and anchors[j][0] == anchors[ix][0] for j, _ in p) + ] + if not candidates: + raise ValueError( + "No regional Transit AS can accept another distinct IX; reduce --nodes." + ) + ix, plan = min( + candidates, + key=lambda item: ( + used[item[0]] / max(1, counts[item[0]] + used[item[0]]), + len(item[1]), + item[0], + ), + ) + plan.append(take(ix)) + remaining -= 1 + continue + pairs = [ + (a, b) + for a in eligible + for b in eligible + if a < b and anchors[a][0] == anchors[b][0] and region_remaining[anchors[a][0]] >= 2 + ] + if not pairs: + raise ValueError("Insufficient regional city pairs remain; reduce --nodes.") + a, b = min( + pairs, + key=lambda p: ( + region_used[anchors[p[0]][0]] + / min(region_capacity[anchors[p[0]][0]], node_count / 6), + sum(used[i] / max(1, counts[i] + used[i]) for i in p), + distance(anchors[p[0]], anchors[p[1]]), + p, + ), + ) + plans.append([take(a), take(b)]) + remaining -= 2 + return anchors, plans + + +def set_geo(node, city, role): + region, country, name, lat, lon, _ = city + node.setGeo(lat, lon, name) + for key, value in { + "geo.lat": f"{lat:.6f}", + "geo.lon": f"{lon:.6f}", + "geo.city": name, + "geo.country": country, + "geo.region": region, + "geo.source": "cityies-land-mask-validated", + "topology.role": role, + }.items(): + node.setLabel(key, value) + + +def plan_stubs(cities, anchors): + """Reserve a router and two nearby, distinct land cities for each stub.""" + available = set(cities) - set(anchors.values()) + stubs = {} + for ix, anchor in anchors.items(): + candidates = sorted( + (c for c in available if c[0] == anchor[0]), key=lambda c: (distance(anchor, c), c) + ) + for router in candidates: + nearby = [ + c for c in candidates if c[1] == router[1] and 20 <= distance(router, c) <= 300 + ] + if len(nearby) < HOSTS_PER_STUB: + continue + first = max(nearby, key=lambda c: (distance(router, c), c)) + others = [c for c in nearby if distance(first, c) >= 20] + if not others: + continue + second = max(others, key=lambda c: (min(distance(router, c), distance(first, c)), c)) + stubs[ix] = [router, first, second] + available.difference_update(stubs[ix]) + break + else: + raise ValueError(f"No unused regional city cluster for IX{ix} stub and hosts") + return stubs + + +def transit_peerings(records): + """Build a rooted provider/customer tree over existing shared IX LANs. + + RS peers export only local/customer routes, so a chain of RS peers cannot + provide transit. Like B00, explicit Provider sessions carry full routes + downstream and customer prefixes upstream. The first AS is the root; + backbone records introduce every IX before regional records are attached. + """ + root = records[0]["asn"] + owners = {ix: root for ix in records[0]["ixes"]} + depths = {root: 0} + peerings = [] + for record in records[1:]: + candidates = [ + (depths[owners[ix]], ix, owners[ix]) for ix in set(record["ixes"]) if ix in owners + ] + if not candidates: + raise ValueError(f"AS{record['asn']} has no shared IX with the transit backbone") + depth, ix, provider = min(candidates) + customer = record["asn"] + peerings.append((ix, provider, customer)) + depths[customer] = depth + 1 + for joined_ix in record["ixes"]: + owners.setdefault(joined_ix, customer) + return peerings + + +class TransitMakerBase: + """Adapt the original four-argument Maker without changing SeedEMU APIs. + + The Maker only calls createAutonomousSystem, createRouter and createNetwork. + Store the real AS in Base and supply explicit LAN prefixes through this + small factory adapter, including for ASNs above 255. + """ + + def __init__(self, base, prefixes): + self.base = base + self.prefixes = prefixes + + def createAutonomousSystem(self, asn): + return TransitMakerAs(self.base.createAutonomousSystem(asn), self.prefixes) + + +class TransitMakerAs: + def __init__(self, system, prefixes): + self.system = system + self.prefixes = prefixes + + def createRouter(self, name): + return self.system.createRouter(name) + + def createNetwork(self, name): + return self.system.createNetwork(name, prefix=self.prefixes[name]) + + +def build_emulator(seed=42, node_count=200): + if node_count < MIN_NODE_COUNT: + raise ValueError( + f"At least {MIN_NODE_COUNT} nodes are needed, including 20 stubs and 40 hosts." + ) + cities = load_cities() + anchors = select_anchors(cities) + stubs = plan_stubs(cities, anchors) + reserved_cities = {c for cluster in stubs.values() for c in cluster} + anchors, plans = plan_topology( + node_count - STUB_NODE_COUNT, [c for c in cities if c not in reserved_cities], seed + ) + displays = ix_display_locations( + anchors, plans + [[(ix, c) for c in cluster] for ix, cluster in stubs.items()] + ) + emu, base, ebgp = Emulator(), Base(), Ebgp() + members = {ix: [] for ix in anchors} + for ix, city in anchors.items(): + exchange = base.createInternetExchange(ix, rsAddress=f"10.{ix}.0.254") + exchange.getPeeringLan().setDisplayName(f"{city[2]}-IX{ix}") + server = exchange.getRouteServerNode() + set_geo(server, displays[ix], "ix-route-server") + server.setLabel("geo.source", "ix-display-offset-land-validated") + server.setLabel("geo.anchor_ix", str(ix)) + server.setLabel("geo.anchor_lat", f"{city[3]:.6f}") + server.setLabel("geo.anchor_lon", f"{city[4]:.6f}") + server.setLabel("geo.display_offset_km", f"{distance(city, displays[ix]):.6f}") + asns = iter(a for a in range(2, 65535) if a not in anchors and a not in STUB_ASNS.values()) + # Avoid 172.17.0.0/16 (Docker's usual default bridge). IX LANs occupy + # 10.100..119.0.0/24 and Routing loopbacks occupy 10.0.0.0/16. + internal_prefixes = ( + p + for p in IPv4Network("10.128.0.0/9").subnets(new_prefix=24) + if int(str(p.network_address).split(".")[1]) not in STUB_ASNS.values() + ) + records = [] + for plan in plans: + asn = next(asns) + joined_ixes = [ix for ix, _ in plan] + # Short local tree rather than a full mesh. + reached = {0} + links = [] + while len(reached) < len(plan): + a, b = min( + ((a, b) for a in reached for b in range(len(plan)) if b not in reached), + key=lambda p: distance(plan[p[0]][1], plan[p[1]][1]), + ) + links.append((joined_ixes[a], joined_ixes[b])) + reached.add(b) + addresses = {} + for ix in joined_ixes: + # .253 is reserved for the stub router and .254 for the route server. + if len(members[ix]) >= 251: + raise ValueError(f"IX{ix} exceeds its /24 address capacity; reduce --nodes.") + addresses[ix] = f"10.{ix}.0.{2 + len(members[ix])}" + maker_base = TransitMakerBase( + base, {f"net_{a}_{b}": str(next(internal_prefixes)) for a, b in links} + ) + Makers.makeTransitAs(maker_base, asn, joined_ixes, links) + system = base.getAutonomousSystem(asn) + for ix, city in plan: + router = system.getRouter(f"r{ix}") + # Replace the Maker's pending auto address before Base configures it. + router.updateNetwork(f"ix{ix}", addresses[ix]) + members[ix].append(asn) + set_geo(router, city, "transit-router") + router.setLabel("geo.anchor_ix", str(ix)) + router.setLabel("geo.radius_km", f"{distance(city, anchors[ix]):.3f}") + records.append({"asn": asn, "ixes": joined_ixes, "links": links, "kind": "transit"}) + for ix, peers in members.items(): + ebgp.addRsPeers(ix, list(dict.fromkeys(peers))) + for ix, asn in STUB_ASNS.items(): + Makers.makeStubAsWithHosts(emu, base, asn, ix, HOSTS_PER_STUB) + stub = base.getAutonomousSystem(asn) + router = stub.getRouter("router0") + router.updateNetwork(f"ix{ix}", f"10.{ix}.0.253") + set_geo(router, stubs[ix][0], "stub-router") + router.setLabel("geo.anchor_ix", str(ix)) + for index in range(HOSTS_PER_STUB): + host = stub.getHost(f"host_{index}") + set_geo(host, stubs[ix][index + 1], "stub-host") + host.setLabel("geo.anchor_ix", str(ix)) + host.setLabel("geo.anchor_router", f"as{asn}/router0") + records.append({"asn": asn, "ixes": [ix], "links": [], "kind": "stub"}) + for ix, provider, customer in transit_peerings(records): + # Same orientation as B00: provider exports ALL routes to its customer. + ebgp.addPrivatePeerings(ix, [provider], [customer], PeerRelationship.Provider) + for layer in (base, Routing(), ebgp, Ibgp(), Ospf()): + emu.addLayer(layer) + return emu, records, members + + +class GeoDocker(Docker): + __containerBundles: List[ContainerBundle] = [] + + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.anchors = select_anchors(load_cities()) + + def _getNetMeta(self, net): + labels = super()._getNetMeta(net) + scope, _, name = net.getRegistryInfo() + if scope == "ix": + city = self.anchors[int(name.removeprefix("ix"))] + for key, value in zip(("geo.lat", "geo.lon"), city[3:5]): + labels += f' {META}{key}: "{value:.6f}"\n' + return labels + + +def parse_args(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("legacy_platform", nargs="?", choices=["amd", "arm"]) + parser.add_argument("--platform", choices=["amd", "arm"]) + parser.add_argument( + "--nodes", + "--node-count", + type=int, + default=500, + help=f"Total routers + IX route servers + hosts (default: 500; minimum: {MIN_NODE_COUNT}).", + ) + parser.add_argument("--output", default=str(SCRIPT_DIR / "output")) + parser.add_argument("--dumpfile") + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--override", dest="override", action="store_true", default=True) + parser.add_argument("--no-override", dest="override", action="store_false") + parser.add_argument("--skip-render", dest="render", action="store_false", default=True) + args = parser.parse_args() + args.platform = args.platform or args.legacy_platform or "amd" + if args.nodes < MIN_NODE_COUNT: + parser.error(f"--nodes must be at least {MIN_NODE_COUNT}") + return args + + +def main(): + args = parse_args() + emu, records, members = build_emulator(args.seed, args.nodes) + if args.dumpfile: + emu.dump(args.dumpfile) + return 0 + if args.render: + emu.render() + output = Path(args.output).resolve() + output.parent.mkdir(parents=True, exist_ok=True) + geoDocker = GeoDocker( + internetMapEnabled=False, + platform=Platform.AMD64 if args.platform == "amd" else Platform.ARM64, + ) + + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + geoDocker.addContainerBundle(bundle) + + emu.compile(geoDocker, str(output), override=args.override) + + print( + f"Generated {args.nodes} nodes: 20 IX route servers + {args.nodes-80} transit routers" + f" + 20 stub routers + 40 hosts, {len(records)} ASes." + ) + print(f"Docker output: {output}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/internet/B20_dhcp/dhcp.py b/examples/internet/B20_dhcp/dhcp.py index b5c8793fb..66febf764 100755 --- a/examples/internet/B20_dhcp/dhcp.py +++ b/examples/internet/B20_dhcp/dhcp.py @@ -18,6 +18,7 @@ from seedemu.layers import Base from seedemu.services import DHCPService from examples.internet.B00_mini_internet import mini_internet +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -96,7 +97,15 @@ def run( output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=platform), str(output_dir), override=override) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=override) def main() -> int: @@ -112,4 +121,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/internet/B21_etc_hosts/etc_hosts.py b/examples/internet/B21_etc_hosts/etc_hosts.py index 3657fc34b..ea87b6708 100755 --- a/examples/internet/B21_etc_hosts/etc_hosts.py +++ b/examples/internet/B21_etc_hosts/etc_hosts.py @@ -17,6 +17,7 @@ from seedemu.core import Emulator from seedemu.layers import Base, EtcHosts from examples.internet.B00_mini_internet import mini_internet +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -69,7 +70,15 @@ def run( output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=platform), str(output_dir), override=override) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=override) def main() -> int: @@ -85,4 +94,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/internet/B22_botnet/botnet_basic.py b/examples/internet/B22_botnet/botnet_basic.py index f9f59f717..b9916d0fd 100755 --- a/examples/internet/B22_botnet/botnet_basic.py +++ b/examples/internet/B22_botnet/botnet_basic.py @@ -21,6 +21,7 @@ from seedemu.compiler import Docker, Platform from seedemu.core import Action, Binding, Emulator, Filter from seedemu.services import BotnetClientService, BotnetService +from seedemu.containerBundle import InternetMap BOT_CONTROLLER_IP = "10.150.0.66" @@ -113,7 +114,15 @@ def run( if render: emu.render() - emu.compile(Docker(platform=platform), output or str(SCRIPT_DIR / "output"), override=override) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, output or str(SCRIPT_DIR / "output"), override=override) def main() -> int: @@ -135,4 +144,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/internet/B22_botnet/not_ready/botnet-with-dga.py b/examples/internet/B22_botnet/not_ready/botnet-with-dga.py index 768a8d14f..9e96fc6e1 100755 --- a/examples/internet/B22_botnet/not_ready/botnet-with-dga.py +++ b/examples/internet/B22_botnet/not_ready/botnet-with-dga.py @@ -4,6 +4,7 @@ from seedemu.core import Emulator, Binding, Filter, Action from seedemu.services import BotnetService, BotnetClientService, DomainNameService, DomainNameCachingService from seedemu.compiler import Docker +from seedemu.containerBundle import InternetMap emu = Emulator() @@ -64,4 +65,12 @@ emu.addLayer(ldns) emu.render() -emu.compile(Docker(), './output2') +docker = Docker() +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, './output2') \ No newline at end of file diff --git a/examples/internet/B23_darknet_tor/darknet_tor.py b/examples/internet/B23_darknet_tor/darknet_tor.py index 61fa01afa..2ae438895 100755 --- a/examples/internet/B23_darknet_tor/darknet_tor.py +++ b/examples/internet/B23_darknet_tor/darknet_tor.py @@ -5,6 +5,7 @@ import random from examples.internet.B00_mini_internet import mini_internet import os, sys +from seedemu.containerBundle import InternetMap ############################################################################### script_name = os.path.basename(__file__) @@ -101,4 +102,12 @@ emu.addLayer(web) emu.addLayer(tor) emu.render() -emu.compile(Docker(platform=platform), './output', override=True) +docker = Docker(platform=platform) +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, './output', override=True) \ No newline at end of file diff --git a/examples/internet/B24_ip_anycast/ip_anycast.py b/examples/internet/B24_ip_anycast/ip_anycast.py index 925cfc3d7..8345b23e2 100755 --- a/examples/internet/B24_ip_anycast/ip_anycast.py +++ b/examples/internet/B24_ip_anycast/ip_anycast.py @@ -21,6 +21,7 @@ from seedemu.core import Binding, Emulator, Filter from seedemu.layers import Base, Ebgp, PeerRelationship from seedemu.services import WebService +from seedemu.containerBundle import InternetMap ANYCAST_ADDRESS = "10.180.0.100" @@ -98,6 +99,13 @@ def run( # selfManagedNetwork is required because AS180 intentionally has two Docker # networks with the same IP prefix. docker = Docker(selfManagedNetwork=True, platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) emu.compile(docker, output or str(SCRIPT_DIR / "output"), override=override) diff --git a/examples/internet/B25_pki/base_internet.py b/examples/internet/B25_pki/base_internet.py index e453f8f34..590e2ba3a 100644 --- a/examples/internet/B25_pki/base_internet.py +++ b/examples/internet/B25_pki/base_internet.py @@ -2,6 +2,7 @@ from seedemu.core import Emulator from seedemu.layers import Base, Ebgp, Ibgp, Ospf, Routing, PeerRelationship, EtcHosts import os, sys +from seedemu.containerBundle import InternetMap def run(dumpfile = None): ############################################################################### @@ -76,7 +77,15 @@ def run(dumpfile = None): emu.dump(dumpfile) else: emu.render() - emu.compile(Docker(platform=platform), './output', override=True) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, './output', override=True) if __name__ == "__main__": - run() + run() \ No newline at end of file diff --git a/examples/internet/B25_pki/base_internet_with_dns.py b/examples/internet/B25_pki/base_internet_with_dns.py index d355851f1..4a00b46ad 100644 --- a/examples/internet/B25_pki/base_internet_with_dns.py +++ b/examples/internet/B25_pki/base_internet_with_dns.py @@ -3,6 +3,7 @@ from seedemu.layers import Base, Ebgp, Ibgp, Ospf, Routing, PeerRelationship from seedemu.services import DomainNameCachingService, DomainNameService import os, sys +from seedemu.containerBundle import InternetMap def run(dumpfile = None): ############################################################################### @@ -123,7 +124,15 @@ def run(dumpfile = None): emu.dump(dumpfile) else: emu.render() - emu.compile(Docker(platform=platform), './output', override=True) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, './output', override=True) if __name__ == "__main__": - run() + run() \ No newline at end of file diff --git a/examples/internet/B25_pki/pki.py b/examples/internet/B25_pki/pki.py index 8c9bec585..ed4aa481c 100755 --- a/examples/internet/B25_pki/pki.py +++ b/examples/internet/B25_pki/pki.py @@ -20,6 +20,7 @@ from seedemu.layers import Base from seedemu.services import CAService, CAServer, WebService, WebServer, RootCAStore import base_internet +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -115,7 +116,15 @@ def run( output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=platform), str(output_dir), override=override) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=override) def main() -> int: @@ -131,4 +140,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/internet/B25_pki/pki_with_dns.py b/examples/internet/B25_pki/pki_with_dns.py index ea4233b49..9c9e71759 100755 --- a/examples/internet/B25_pki/pki_with_dns.py +++ b/examples/internet/B25_pki/pki_with_dns.py @@ -7,6 +7,7 @@ from seedemu.services import DomainNameService, CAService, CAServer, WebService, WebServer, RootCAStore import base_internet_with_dns import os, sys +from seedemu.containerBundle import InternetMap ############################################################################### # Set the platform information @@ -83,4 +84,12 @@ emu.addLayer(web) emu.render() -emu.compile(Docker(platform=platform), './output', override=True) +docker = Docker(platform=platform) +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, './output', override=True) \ No newline at end of file diff --git a/examples/internet/B26_ipfs_kubo/base_component.py b/examples/internet/B26_ipfs_kubo/base_component.py index f6dd854f5..db877d485 100755 --- a/examples/internet/B26_ipfs_kubo/base_component.py +++ b/examples/internet/B26_ipfs_kubo/base_component.py @@ -151,7 +151,15 @@ def run(hosts_total = 3, dumpfile = None): emu.dump(dumpfile) else: emu.render() - emu.compile(Docker(), './output', override=True) + docker = Docker() + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, './output', override=True) if __name__ == "__main__": run() \ No newline at end of file diff --git a/examples/internet/B26_ipfs_kubo/kubo.py b/examples/internet/B26_ipfs_kubo/kubo.py index 56c05d0a2..efb082221 100755 --- a/examples/internet/B26_ipfs_kubo/kubo.py +++ b/examples/internet/B26_ipfs_kubo/kubo.py @@ -77,4 +77,11 @@ # Render and compile docker = Docker(internetMapEnabled=True, platform=platform) # Initialize the desired compiler emu.render() -emu.compile(docker, OUTPUTDIR, override = True) +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, OUTPUTDIR, override = True) \ No newline at end of file diff --git a/examples/internet/B27_ipfs_kubo_dapp/base_component.py b/examples/internet/B27_ipfs_kubo_dapp/base_component.py index 6107d4640..2bb58ee87 100755 --- a/examples/internet/B27_ipfs_kubo_dapp/base_component.py +++ b/examples/internet/B27_ipfs_kubo_dapp/base_component.py @@ -122,7 +122,15 @@ def run(host_total = 1, dumpfile = None): emu.dump(dumpfile) else: emu.render() - emu.compile(Docker(), './output', override=True) + docker = Docker() + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, './output', override=True) if __name__ == "__main__": run() \ No newline at end of file diff --git a/examples/internet/B27_ipfs_kubo_dapp/kubo-eth.py b/examples/internet/B27_ipfs_kubo_dapp/kubo-eth.py index 1da2c9164..8edad2971 100755 --- a/examples/internet/B27_ipfs_kubo_dapp/kubo-eth.py +++ b/examples/internet/B27_ipfs_kubo_dapp/kubo-eth.py @@ -151,6 +151,14 @@ docker.addImage(DockerImage('kubo-webhost-image', [], local = True), priority=-1) docker.setImageOverride(webHost, 'kubo-webhost-image') +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, OUTPUTDIR, override = True) # Copy the base container image to the output folder diff --git a/examples/internet/B28_traffic_generator/0-iperf-traffic-generator/iperf-traffic-generator.py b/examples/internet/B28_traffic_generator/0-iperf-traffic-generator/iperf-traffic-generator.py index 3fb72cb66..f3050d55a 100755 --- a/examples/internet/B28_traffic_generator/0-iperf-traffic-generator/iperf-traffic-generator.py +++ b/examples/internet/B28_traffic_generator/0-iperf-traffic-generator/iperf-traffic-generator.py @@ -7,6 +7,7 @@ from seedemu.layers import EtcHosts from examples.internet.B00_mini_internet import mini_internet import os, sys +from seedemu.containerBundle import InternetMap def run(dumpfile=None): ############################################################################### @@ -86,7 +87,15 @@ def run(dumpfile=None): else: # Rendering compilation emu.render() - emu.compile(Docker(platform=platform), './output', override=True) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, './output', override=True) if __name__ == "__main__": - run() + run() \ No newline at end of file diff --git a/examples/internet/B28_traffic_generator/1-ditg-traffic-generator/ditg-traffic-generator.py b/examples/internet/B28_traffic_generator/1-ditg-traffic-generator/ditg-traffic-generator.py index 04431c63e..5ba287e35 100755 --- a/examples/internet/B28_traffic_generator/1-ditg-traffic-generator/ditg-traffic-generator.py +++ b/examples/internet/B28_traffic_generator/1-ditg-traffic-generator/ditg-traffic-generator.py @@ -7,6 +7,7 @@ from seedemu.layers import EtcHosts from examples.internet.B00_mini_internet import mini_internet import os, sys +from seedemu.containerBundle import InternetMap def run(dumpfile=None): ############################################################################### @@ -85,7 +86,15 @@ def run(dumpfile=None): else: # Rendering compilation emu.render() - emu.compile(Docker(platform=platform), './output', override=True) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, './output', override=True) if __name__ == "__main__": - run() + run() \ No newline at end of file diff --git a/examples/internet/B28_traffic_generator/2-scapy-traffic-generator/scapy-traffic-generator.py b/examples/internet/B28_traffic_generator/2-scapy-traffic-generator/scapy-traffic-generator.py index d44d844b7..16d89b142 100755 --- a/examples/internet/B28_traffic_generator/2-scapy-traffic-generator/scapy-traffic-generator.py +++ b/examples/internet/B28_traffic_generator/2-scapy-traffic-generator/scapy-traffic-generator.py @@ -7,6 +7,7 @@ from seedemu.layers import EtcHosts from examples.internet.B00_mini_internet import mini_internet import os, sys +from seedemu.containerBundle import InternetMap def run(dumpfile=None): ############################################################################### @@ -61,8 +62,15 @@ def run(dumpfile=None): else: # Rendering compilation emu.render() - emu.compile(Docker(platform=platform), './output', override=True) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker,'./output', override=True) if __name__ == "__main__": run() - diff --git a/examples/internet/B28_traffic_generator/3-multi-traffic-generator/multi-traffic-generator.py b/examples/internet/B28_traffic_generator/3-multi-traffic-generator/multi-traffic-generator.py index f42b440e9..188bbf08f 100755 --- a/examples/internet/B28_traffic_generator/3-multi-traffic-generator/multi-traffic-generator.py +++ b/examples/internet/B28_traffic_generator/3-multi-traffic-generator/multi-traffic-generator.py @@ -7,6 +7,8 @@ from seedemu.layers import EtcHosts from examples.internet.B00_mini_internet import mini_internet import os, sys +from seedemu.containerBundle import InternetMap + def run(dumpfile=None): ############################################################################### # Set the platform information @@ -81,12 +83,20 @@ def run(dumpfile=None): emu.addLayer(etc_hosts) if dumpfile is not None: - # Save it to a file, so it can be used by other emulators - emu.dump(dumpfile) + # Save it to a file, so it can be used by other emulators + emu.dump(dumpfile) else: - # Rendering compilation - emu.render() - emu.compile(Docker(platform=platform), './output', override=True) + # Rendering compilation + emu.render() + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker,'./output', override=True) if __name__ == "__main__": - run() + run() \ No newline at end of file diff --git a/examples/internet/B29_email_dns/email_realistic.py b/examples/internet/B29_email_dns/email_realistic.py index 60b9d9c07..80d19a79c 100644 --- a/examples/internet/B29_email_dns/email_realistic.py +++ b/examples/internet/B29_email_dns/email_realistic.py @@ -12,6 +12,7 @@ from seedemu.compiler import Docker, Platform from seedemu.core import Emulator, Binding, Filter, Action from seedemu.utilities import Makers +from seedemu.containerBundle import InternetMap def create_realistic_network(emu): """创建更真实的网络拓扑""" @@ -445,7 +446,13 @@ def run(platform="auto"): dns=f"10.{mail['asn']}.0.53", ) email_svc.attach_to_docker(docker) - + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) emu.compile(docker, "./output", override=True) emu.updateOutputDirectory(docker, email_svc.get_output_callbacks()) @@ -507,7 +514,7 @@ def run(platform="auto"): Internet Map: http://localhost:8080/pro/map ====================================================================== - "") + """) if __name__ == "__main__": platform = sys.argv[1] if len(sys.argv) > 1 else "auto" diff --git a/examples/internet/B30_CDN/cdn.py b/examples/internet/B30_CDN/cdn.py index 86a66ee5d..fec5fabf2 100644 --- a/examples/internet/B30_CDN/cdn.py +++ b/examples/internet/B30_CDN/cdn.py @@ -15,7 +15,7 @@ from seedemu.core import Action, Binding, Emulator, Filter from seedemu.layers import Ebgp, PeerRelationship from seedemu.services import CDNService, DomainNameService - +from seedemu.containerBundle import InternetMap from examples.internet.B00_mini_internet import mini_internet @@ -213,8 +213,16 @@ def run(): emu = build_emulator() emu.render() + docker = Docker(selfManagedNetwork=True, platform=resolve_platform(args.platform)) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) emu.compile( - Docker(selfManagedNetwork=True, platform=resolve_platform(args.platform)), + docker, str(output_dir), override=True, ) diff --git a/examples/internet/B31_mini_internet_mpls/mini_internet_mpls.py b/examples/internet/B31_mini_internet_mpls/mini_internet_mpls.py index ae55d25cf..ba480f788 100644 --- a/examples/internet/B31_mini_internet_mpls/mini_internet_mpls.py +++ b/examples/internet/B31_mini_internet_mpls/mini_internet_mpls.py @@ -17,6 +17,7 @@ from seedemu.core import Emulator from seedemu.layers import Base, Ebgp, Ibgp, Mpls, Ospf, PeerRelationship, Routing from seedemu.utilities import Makers +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -194,6 +195,13 @@ def run( emu.render() docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) emu.compile(docker, output or "./output", override=override) diff --git a/examples/internet/B32_mini_internet_exabgp/mini_internet_exabgp.py b/examples/internet/B32_mini_internet_exabgp/mini_internet_exabgp.py index 9d70b3600..9b531cf76 100755 --- a/examples/internet/B32_mini_internet_exabgp/mini_internet_exabgp.py +++ b/examples/internet/B32_mini_internet_exabgp/mini_internet_exabgp.py @@ -18,6 +18,7 @@ from seedemu.core import Binding, Emulator, Filter from seedemu.layers import Base from seedemu.services import ExaBgpService +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -80,7 +81,15 @@ def run( output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=platform), str(output_dir), override=override) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=override) def main() -> int: @@ -97,4 +106,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/internet/B50_bring_your_own_internet/bring_your_own_internet.py b/examples/internet/B50_bring_your_own_internet/bring_your_own_internet.py index c98c3c8ed..d16d5cd46 100755 --- a/examples/internet/B50_bring_your_own_internet/bring_your_own_internet.py +++ b/examples/internet/B50_bring_your_own_internet/bring_your_own_internet.py @@ -72,5 +72,13 @@ # Render the emulation emu.render() +docker = Docker(platform=platform) +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) # Compile the emulation -emu.compile(Docker(internetMapEnabled = True, platform=platform), './output', override=True) +emu.compile(docker, './output', override=True) \ No newline at end of file diff --git a/examples/internet/B50_bring_your_own_internet/bring_your_own_internet_client.py b/examples/internet/B50_bring_your_own_internet/bring_your_own_internet_client.py index 09a156da0..3393df266 100755 --- a/examples/internet/B50_bring_your_own_internet/bring_your_own_internet_client.py +++ b/examples/internet/B50_bring_your_own_internet/bring_your_own_internet_client.py @@ -135,5 +135,12 @@ # Uncomment the following if you want to generate the final emulation files emu.render() #print(dns.getZone('.').getRecords()) - emu.compile(Docker(platform=platform), './output_'+str(i), override=True) - + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, './output_'+str(i), override=True) diff --git a/examples/internet/b62_protocol_parama/protocol_parama.py b/examples/internet/b62_protocol_parama/protocol_parama.py index c8f9ca016..7c78de7fd 100755 --- a/examples/internet/b62_protocol_parama/protocol_parama.py +++ b/examples/internet/b62_protocol_parama/protocol_parama.py @@ -17,6 +17,7 @@ from seedemu.core import Emulator from seedemu.layers import Base, Ebgp, Ibgp, Ospf, PeerRelationship, Routing from seedemu.utilities import Makers +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -177,6 +178,13 @@ def run( emu.render() docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) emu.compile(docker, output or "./output", override=override) diff --git a/examples/routing/R01_routing_matrix/routing_matrix.py b/examples/routing/R01_routing_matrix/routing_matrix.py index f9db9b294..cc9c5a016 100644 --- a/examples/routing/R01_routing_matrix/routing_matrix.py +++ b/examples/routing/R01_routing_matrix/routing_matrix.py @@ -18,6 +18,7 @@ from seedemu.core import Emulator from seedemu.layers import Base, Ebgp, Ibgp, Ospf, PeerRelationship, Routing from seedemu.utilities import Makers +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -287,11 +288,19 @@ def main() -> int: output_dir = Path(args.output).resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=resolve_platform(args.platform)), str(output_dir), override=args.override) + docker = Docker(platform=resolve_platform(args.platform)) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=args.override) print_route_reflector_summaries(rr_summaries) print("Generated routing matrix Docker output in {}".format(output_dir)) return 0 if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/routing/R02_bgp_free_core_mpls/bgp_free_core_mpls.py b/examples/routing/R02_bgp_free_core_mpls/bgp_free_core_mpls.py index 2d6ce72ce..7652e53fa 100644 --- a/examples/routing/R02_bgp_free_core_mpls/bgp_free_core_mpls.py +++ b/examples/routing/R02_bgp_free_core_mpls/bgp_free_core_mpls.py @@ -18,6 +18,7 @@ from seedemu.core import Emulator from seedemu.layers import Base, Ebgp, Ibgp, Mpls, Ospf, PeerRelationship, Routing from seedemu.utilities import Makers +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -147,10 +148,18 @@ def main() -> int: output_dir = Path(args.output).resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=resolve_platform(args.platform)), str(output_dir), override=args.override) + docker = Docker(platform=resolve_platform(args.platform)) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=args.override) print("Generated BGP-free core MPLS Docker output in {}".format(output_dir)) return 0 if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/routing/R03_complex_generated_routing/complex_generated_routing.py b/examples/routing/R03_complex_generated_routing/complex_generated_routing.py index 14cb23658..69126a566 100644 --- a/examples/routing/R03_complex_generated_routing/complex_generated_routing.py +++ b/examples/routing/R03_complex_generated_routing/complex_generated_routing.py @@ -19,6 +19,7 @@ from seedemu.core import Emulator from seedemu.layers import Base, Ebgp, Ibgp, Ospf, PeerRelationship, Routing from seedemu.utilities import AutonomousSystemTopologyGenerator, Makers +from seedemu.containerBundle import InternetMap DEFAULT_IXES = [120, 121, 122, 123] @@ -309,7 +310,15 @@ def main() -> int: output_dir = Path(args.output).resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=resolve_platform(args.platform)), str(output_dir), override=args.override) + docker = Docker(platform=resolve_platform(args.platform)) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=args.override) write_artifacts(topology, output_dir, internal_routing, stub_assignments) print(topology.summary()) @@ -330,4 +339,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/sample/sample_example.py b/examples/sample/sample_example.py index 2c932dfc8..6464a2675 100644 --- a/examples/sample/sample_example.py +++ b/examples/sample/sample_example.py @@ -17,6 +17,7 @@ from seedemu.core import Binding, Emulator, Filter from seedemu.layers import Base, Ebgp, Routing from seedemu.services import WebService +from seedemu.containerBundle import InternetMap def parse_args() -> argparse.Namespace: @@ -81,10 +82,18 @@ def main() -> int: output_dir = Path(args.output).resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - emu.compile(Docker(platform=resolve_platform(args.platform)), str(output_dir), override=args.override) + docker = Docker(platform=resolve_platform(args.platform)) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, str(output_dir), override=args.override) print("Generated sample SEED Emulator Docker output in {}".format(output_dir)) return 0 if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/examples/scion/S01_scion/scion.py b/examples/scion/S01_scion/scion.py index 42e96952a..d66682b20 100755 --- a/examples/scion/S01_scion/scion.py +++ b/examples/scion/S01_scion/scion.py @@ -4,6 +4,7 @@ from seedemu.core import Emulator from seedemu.layers import ScionBase, ScionRouting, ScionIsd, Scion from seedemu.layers.Scion import LinkType as ScLinkType +from seedemu.containerBundle import InternetMap # Initialize emu = Emulator() @@ -65,5 +66,12 @@ emu.render() -# Compilation -emu.compile(Docker(), './output') +docker = Docker() +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, './output') \ No newline at end of file diff --git a/examples/scion/S02_scion_bgp_mixed/scion_bgp_mixed.py b/examples/scion/S02_scion_bgp_mixed/scion_bgp_mixed.py index bfe8489c7..304ee3253 100755 --- a/examples/scion/S02_scion_bgp_mixed/scion_bgp_mixed.py +++ b/examples/scion/S02_scion_bgp_mixed/scion_bgp_mixed.py @@ -6,6 +6,7 @@ ScionBase, ScionRouting, ScionIsd, Scion, Ospf, Ibgp, Ebgp, PeerRelationship, SetupSpecification, CheckoutSpecification) from seedemu.layers.Scion import LinkType as ScLinkType, ScionConfigMode +from seedemu.containerBundle import InternetMap # Initialize emu = Emulator() @@ -127,6 +128,13 @@ emu.render() -# Compilation -emu.compile(Docker(), './output') -emu.compile(Graphviz(), "./output/graphs") +docker = Docker() +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, './output') +emu.compile(Graphviz(), "./output/graphs") \ No newline at end of file diff --git a/examples/scion/S03_bandwidth_tester/bandwidth_tester.py b/examples/scion/S03_bandwidth_tester/bandwidth_tester.py index 500b5fc8d..b6fb5e5f8 100755 --- a/examples/scion/S03_bandwidth_tester/bandwidth_tester.py +++ b/examples/scion/S03_bandwidth_tester/bandwidth_tester.py @@ -5,6 +5,7 @@ from seedemu.layers import ScionBase, ScionRouting, ScionIsd, Scion from seedemu.layers.Scion import LinkType as ScLinkType from seedemu.services import ScionBwtestService +from seedemu.containerBundle import InternetMap # Initialize emu = Emulator() @@ -85,5 +86,12 @@ emu.render() -# Compilation -emu.compile(Docker(), './output') +docker = Docker() +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, './output') \ No newline at end of file diff --git a/examples/scion/S04_docker_api/docker_api.py b/examples/scion/S04_docker_api/docker_api.py index 10a61e32b..fba445277 100755 --- a/examples/scion/S04_docker_api/docker_api.py +++ b/examples/scion/S04_docker_api/docker_api.py @@ -10,6 +10,7 @@ from seedemu.layers import ScionBase, ScionRouting, ScionIsd, Scion from seedemu.layers.Scion import LinkType as ScLinkType from seedemu.services import ScionBwtestService +from seedemu.containerBundle import InternetMap # Initialize @@ -91,8 +92,15 @@ emu.render() -# Compilation -emu.compile(Docker(), './output') +docker = Docker() +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, './output') # Build Docker containers and run the network whales = python_on_whales.DockerClient(compose_files=["./output/docker-compose.yml"]) @@ -113,4 +121,4 @@ print(" " + line) # Shut the network down -whales.compose.down() +whales.compose.down() \ No newline at end of file diff --git a/examples/scion/S05_scion_internet/bgp_internet.py b/examples/scion/S05_scion_internet/bgp_internet.py index b23ef7a1c..9188beffd 100755 --- a/examples/scion/S05_scion_internet/bgp_internet.py +++ b/examples/scion/S05_scion_internet/bgp_internet.py @@ -7,6 +7,7 @@ from seedemu.layers import ScionBase, ScionRouting, ScionIsd, Scion, Ebgp from seedemu.layers import PeerRelationship as PeerRel from seedemu.layers.Scion import LinkType as ScLinkType +from seedemu.containerBundle import InternetMap def create_as(isd, asn, is_core=False, issuer=None): @@ -175,4 +176,12 @@ def next_addr(self, net): # Compilation os.makedirs('./output', exist_ok=True) -emu.compile(Docker(), './output/bgp') +docker = Docker() +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, './output/bgp') \ No newline at end of file diff --git a/examples/scion/S05_scion_internet/scion_internet.py b/examples/scion/S05_scion_internet/scion_internet.py index 39babe4d9..8b7d9d6a5 100755 --- a/examples/scion/S05_scion_internet/scion_internet.py +++ b/examples/scion/S05_scion_internet/scion_internet.py @@ -6,6 +6,7 @@ from seedemu.core import Emulator from seedemu.layers import ScionBase, ScionRouting, ScionIsd, Scion from seedemu.layers.Scion import LinkType as ScLinkType +from seedemu.containerBundle import InternetMap def create_as(isd, asn, is_core=False, issuer=None): @@ -298,4 +299,12 @@ def next_addr(self, net): # Compilation os.makedirs('./output', exist_ok=True) -emu.compile(Docker(), './output/scion') +docker = Docker() +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, './output/scion') \ No newline at end of file diff --git a/examples/scion/S06-scion-link-properties/scion-link-properties.py b/examples/scion/S06-scion-link-properties/scion-link-properties.py index e9ccba7f5..fc07cf32a 100644 --- a/examples/scion/S06-scion-link-properties/scion-link-properties.py +++ b/examples/scion/S06-scion-link-properties/scion-link-properties.py @@ -3,6 +3,7 @@ from seedemu.core import Emulator from seedemu.layers import ScionBase, ScionRouting, ScionIsd, Scion from seedemu.layers.Scion import LinkType as ScLinkType +from seedemu.containerBundle import InternetMap # Initialize emu = Emulator() @@ -63,5 +64,12 @@ emu.render() -# Compilation -emu.compile(Docker(), './output') +docker = Docker() +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, './output') \ No newline at end of file diff --git a/examples/scion/S07-scion-bwtest-client/scion-bwtest-client.py b/examples/scion/S07-scion-bwtest-client/scion-bwtest-client.py index 94ddbe1cf..c39f3f6a9 100644 --- a/examples/scion/S07-scion-bwtest-client/scion-bwtest-client.py +++ b/examples/scion/S07-scion-bwtest-client/scion-bwtest-client.py @@ -5,6 +5,7 @@ from seedemu.layers import ScionBase, ScionRouting, ScionIsd, Scion from seedemu.layers.Scion import LinkType as ScLinkType from seedemu.services import ScionBwtestService, ScionBwtestClientService +from seedemu.containerBundle import InternetMap # Initialize emu = Emulator() @@ -94,5 +95,12 @@ emu.render() -# Compilation -emu.compile(Docker(internetMapEnabled=True), './output') +docker = Docker() +# Add Internet visualization services: topology, geographic map, and traffic observation. +# The second argument is a container name suffix that distinguishes bundle instances. +internet_map_bundle = InternetMap(emu, ".map.seed") +# Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. +internet_map_bundle.setPorts(list(range(8081, 8089))) +# Register the bundle with the Docker compiler to generate its containers during emu.compile(). +docker.addContainerBundle(internet_map_bundle) +emu.compile(docker, './output') \ No newline at end of file diff --git a/examples/scion/S08_dev_service/scion_dev_service.py b/examples/scion/S08_dev_service/scion_dev_service.py index a5c1387a9..322acae87 100755 --- a/examples/scion/S08_dev_service/scion_dev_service.py +++ b/examples/scion/S08_dev_service/scion_dev_service.py @@ -9,7 +9,7 @@ from seedemu.core import Emulator, OptionRegistry from seedemu.layers import ScionBase, ScionRouting, ScionIsd, Scion, CheckoutSpecification, SetupSpecification from seedemu.layers.Scion import LinkType as ScLinkType - +from seedemu.containerBundle import InternetMap from seedemu.compiler import Docker, Platform import os, sys @@ -123,9 +123,15 @@ def run(dumpfile = None): emu.render() ############################################################################### - # Compilation - - emu.compile(Docker(platform=platform), './output', override=True) + docker = Docker(platform=platform) + # Add Internet visualization services: topology, geographic map, and traffic observation. + # The second argument is a container name suffix that distinguishes bundle instances. + internet_map_bundle = InternetMap(emu, ".map.seed") + # Provide a host port pool (range excludes the stop value); InternetMap needs at least 3 ports. + internet_map_bundle.setPorts(list(range(8081, 8089))) + # Register the bundle with the Docker compiler to generate its containers during emu.compile(). + docker.addContainerBundle(internet_map_bundle) + emu.compile(docker, './output', override=True) if __name__ == "__main__": run() \ No newline at end of file From 9dc4ed77b73828a153022cc4055cabc31521265f Mon Sep 17 00:00:00 2001 From: Kevin Du Date: Sat, 31 Oct 2026 15:06:37 +0800 Subject: [PATCH 6/6] fixed a typo --- examples/basic/A02a_transit_as_mpls/transit_as_mpls.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/basic/A02a_transit_as_mpls/transit_as_mpls.py b/examples/basic/A02a_transit_as_mpls/transit_as_mpls.py index 1e29aa0c0..034eedb73 100644 --- a/examples/basic/A02a_transit_as_mpls/transit_as_mpls.py +++ b/examples/basic/A02a_transit_as_mpls/transit_as_mpls.py @@ -131,7 +131,7 @@ def run( # Generate the Docker files. output_dir = Path(output or SCRIPT_DIR / "output").resolve() output_dir.parent.mkdir(parents=True, exist_ok=True) - docker = Docker(platform=platform), str(output_dir) + docker = Docker(platform=platform) # Add Internet visualization services: topology, geographic map, and traffic observation. # The second argument is a container name suffix that distinguishes bundle instances. internet_map_bundle = InternetMap(emu, ".map.seed") @@ -139,7 +139,7 @@ def run( internet_map_bundle.setPorts(list(range(8081, 8089))) # Register the bundle with the Docker compiler to generate its containers during emu.compile(). docker.addContainerBundle(internet_map_bundle) - emu.compile(docker, override=override) + emu.compile(docker, str(output_dir), override=override) def main() -> int: @@ -155,4 +155,4 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) \ No newline at end of file + raise SystemExit(main())