diff --git a/docs/designs/container_bundle.md b/docs/designs/container_bundle.md index 9e33976cf..ab03886d8 100644 --- a/docs/designs/container_bundle.md +++ b/docs/designs/container_bundle.md @@ -2,105 +2,320 @@ Created: October 8, 2026 -### 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 +## Current implementation: two cooperating classes -```python -# VisualizationSystem -class VisualizationSystem(ContainerBundle) +`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. -# Example -docker = Docker() +The lifecycle is: -... -emu.render() +```mermaid +flowchart TD + 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 +``` -# 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.setPorts(list(range(8090, 8099)) +## `ContainerBundle` design -# 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) +Subclasses normally create their containers in `__init__`, configure them in +`configure()`, and rely on the compiler to call `install()`: -# Dockerfile of each container image -From baseimage +```python +class ExampleBundle(ContainerBundle): + def __init__(self, emulator, suffix=".example"): + super().__init__(emulator=emulator, suffix=suffix) + self._createContainer("backend", suffix) -COPY {etchosts} /tmp/etc-hosts -RUN cat /tmp/etc-hosts >> /etc/hosts + def configure(self): + self._required_port_number = 1 + super().configure() + backend = self.getContainer("backend" + self.getSuffix()) + backend.setContentAttribute({ + "image": "busybox:latest", + "command": "sleep infinity", + }) +``` +`_createContainer(local_name, suffix)` registers a `PreparedContainer`. The +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 -# Add extra_hosts +`setDefaultExternalNetwork()` defines the isolated Docker network shared by bundle 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 +```python +bundle.setDefaultExternalNetwork( + 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. `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()`: + +```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"}]}, + }, +} +``` + +`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 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 + +`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 +``` + +### 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": "net_150_net0", + "emu_hostname": "host150", + "ip_addresses": ["10.150.0.10", "10.150.0.11"], + "default_route": "10.150.0.254", +} +``` + +Read the stored dictionary with `getDefaultInternalNetwork()` after successful +allocation. Select one IP and pass the container's own hostname explicitly: + +```python +bundle._required_emu_network_address_number = 2 +if bundle.allocateEmuNetworkAddress() is None: + raise RuntimeError("No emulator host network is available") +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"], +) +``` + +`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 +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 +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=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 +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 + 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()` + +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. +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 new file mode 100644 index 000000000..c2db1da48 --- /dev/null +++ b/docs/designs/eth_explorer.md @@ -0,0 +1,331 @@ +# 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 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`. +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. 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 +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`. +`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 +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 no host network has two usable addresses, 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 + 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 +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. + +## 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 new file mode 100644 index 000000000..6e031f4ba --- /dev/null +++ b/docs/designs/internet_map.md @@ -0,0 +1,95 @@ +# InternetMap design + +`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. + +## Services and construction + +| Logical service name | Role | Network behavior | +| --- | --- | --- | +| `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. + +## Optional internal network + +Call `enableInternalNetwork()` before compilation to enable emulator access: + +```python +internet_map = InternetMap(emu, ".map.seed") +internet_map.enableInternalNetwork() +internet_map.setPorts([8081, 8082, 8083]) +docker.addContainerBundle(internet_map) +``` + +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. + +To choose the internal attachment explicitly before compilation: + +```python +internet_map.setDefaultInternalNetwork( + name="net_150_net0", + ip_addresses=["10.150.0.10"], + default_route="10.150.0.254", +) +internet_map.enableInternalNetwork() +``` + +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: + +```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/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..034eedb73 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) + # 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: 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/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/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/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/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/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 diff --git a/seedemu/containerBundle/ContainerBundle.py b/seedemu/containerBundle/ContainerBundle.py index 46790490c..584356985 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): + """! + @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: + """! + @brief Serialize data as readable YAML without sorting keys. + + @param data mapping or sequence to serialize. + @returns the generated YAML document. + """ return yaml.dump( data, Dumper=IndentDumper, @@ -33,73 +44,225 @@ def safe_dump_pretty(data) -> str: @dataclass(eq=False) class ContainerBundle: + """ + ! + @brief Base class for a group of independently built Docker containers. + + Subclasses create containers in ``__init__`` and configure their services + before the Docker compiler calls ``configure`` and ``install``. + """ + emulator: InitVar[Optional[Emulator]] = None suffix: InitVar[str] = "" _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: + """! + @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: + """! + @brief Create and register a prepared container. + + @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: + """! + @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]: + """! + @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]: + """! + @brief Return the emulator associated with this bundle. + + @returns the associated emulator, or ``None``. + """ return self._emulator def getSuffix(self) -> str: + """! + @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 = "", - 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.' - self._default_network = { + prefix: str, + ip_addresses: List[str], + default_router: str, + type: str = "bridge", + ): + """! + @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) + + 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_external_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), + } + ] + }, + }, } - def getDefaultNetwork(self) -> Optional[Dict[str, Any]]: - return self._default_network + return self + + 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: + """! + @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]: + """! + @brief Return a copy of the configured host-port pool. + + @returns available host ports. + """ return self._ports.copy() def getInternalHostnameIpMappings(self) -> Dict[str, str]: + """! + @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]: + """! + @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: + """! + @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( f"At least {self._required_port_number} ports are required; " @@ -107,6 +270,11 @@ def configure(self) -> None: ) def install(self) -> tuple[str, str]: + """! + @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() @@ -131,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() @@ -158,34 +327,86 @@ 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.""" + def allocateEmuNetworkAddress(self): + """! + @brief Reserve addresses starting at host offset 10 on one host network. + + @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: + """! + @brief Mutable description of one container before Compose generation. + """ + name: InitVar[str] = "" suffix: InitVar[str] = "" _name: str = field(default="", init=False) @@ -199,19 +420,41 @@ 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: + """! + @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: + """! + @brief Return the logical Compose service name. + + @returns the service name. + """ return self._name def getHostname(self) -> str: + """! + @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]: + """! + @brief Return the first emulated-network hostname mapping. + + @returns a hostname-to-IP mapping, or an empty dictionary. + """ if not self._internal_networks: return {} @@ -219,12 +462,48 @@ def getInternalHostnameIpMappings(self) -> Dict[str, str]: return {internal_networks[1]: internal_networks[2]} def getExternalHostnameIpMappings(self) -> Dict[str, str]: + """! + @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 []) } + def setEntrypointWrapper( + self, + original_entrypoint: str, + commands: List[str], + ) -> None: + """! + @brief Run preparation commands 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", + "set -eu", + *commands, + f'exec sh "{original_entrypoint}" "$@"', + ] + + self._start_commands = wrapper_commands + self._start_script_name = "/new-entrypoint.sh" + + self.service["entrypoint"] = [ + "sh", + self._start_script_name, + ] + def install(self) -> Dict[str, Any]: + """! + @brief Write build-context files and return the Compose service. + + @returns the generated Compose service mapping. + """ hostname = self.getHostname() mkdir(hostname) chdir(hostname) @@ -232,9 +511,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 +544,21 @@ def install(self) -> Dict[str, Any]: chdir("..") return self.service + def _getDefaultRouteCommands(self) -> List[str]: + """! + @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" | ' + "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,16 +566,33 @@ def joinInternalNetwork( ip_address: str = "", default_route: Optional[str] = "", ) -> None: + """! + @brief Attach the container to an emulated network. + + @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 to the bundle's single external network, identified by name.""" + """! + @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) @@ -270,31 +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: + """! + @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: + """! + @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: + """! + @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 e14f290e1..e5425d6b7 100644 --- a/seedemu/containerBundle/EthExplorer.py +++ b/seedemu/containerBundle/EthExplorer.py @@ -14,31 +14,27 @@ "options": {"max-size": "200m", "max-file": 1}, } -DEFAULT_NETWORK = { +DEFAULT_EXTERNAL_NETWORK = { "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", - ], + "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", + "type": "bridge", "network_config": { "driver": "bridge", - "ipam": {"config": [{"subnet": "172.20.0.0/24", "gateway": "172.20.0.1"}]}, + "ipam": { + "config": [ + { + "subnet": "172.20.0.0/24", + "gateway": "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", @@ -46,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", @@ -54,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"', @@ -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", @@ -94,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", @@ -102,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"', @@ -131,9 +114,23 @@ class EthExplorer(ContainerBundle): + """! + @brief Bundle for the Ethereum Beacon Chain explorer stack. + + Includes PostgreSQL, ClickHouse, Redis, two Bigtable emulators, an indexing + backend, and the Web frontend. + """ + def __init__(self, emulator, suffix="eth.explorer"): + """! + @brief Create an explorer bundle for an Ethereum emulator. + + @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,11 +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: - 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") @@ -159,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, @@ -184,7 +186,7 @@ def configure(self) -> None: } ) - postgres = self._containers["postgres"] + postgres = self._containers["postgres" + self._suffix] postgres.setContentAttribute( { "image": POSTGRES_IMAGE, @@ -202,7 +204,7 @@ def configure(self) -> None: } ) - redis = self._containers["redis"] + redis = self._containers["redis" + self._suffix] redis.setContentAttribute( { "image": REDIS_IMAGE, @@ -216,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()], } ) @@ -240,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, @@ -250,43 +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) - backend_start_commands = BACKEND_START_SH.copy() - backend_start_commands[1] = backend_start_commands[1].format( - default_route=self._emu_internal_network["default_route"] + 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, @@ -294,44 +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) - frontend_start_commands = FRONTEND_START_SH.copy() - frontend_start_commands[1] = frontend_start_commands[1].format( - default_route=self._emu_internal_network["default_route"] + 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: + """! + @brief Return the selected consensus-layer Beacon host. + + @returns Beacon node hostname or IP address. + """ return self.__beacon_host def getGethHost(self) -> str: + """! + @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: + """! + @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: + """! + @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 bf53f99e9..b8e330355 100644 --- a/seedemu/containerBundle/InternetMap.py +++ b/seedemu/containerBundle/InternetMap.py @@ -5,40 +5,30 @@ 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": ".map", - "ip_addresses": [ - "172.30.0.10", - "172.30.0.11", - "172.30.0.12", - "172.30.0.13", - ], + "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", + "type": "bridge", "network_config": { "driver": "bridge", - "ipam": {"config": [{"subnet": "172.30.0.0/24", "gateway": "172.30.0.1"}]}, + "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 {{ +upstream seedemu_emulator_service_backend {{ server {}:{}; }} @@ -51,7 +41,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 +54,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 +72,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 +89,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 +102,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 +115,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 +135,53 @@ class InternetMap(ContainerBundle): + """! + @brief Bundle for topology, geographic map, and traffic views.""" + def __init__(self, emulator, suffix="map.seed"): + """! + @brief Create an Internet Map bundle. + + @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", + "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._required_port_number = 3 + self._required_emu_network_address_number = 1 + self._enableInternalNetwork = False + + def enableInternalNetwork(self): + """! + @brief Attach the API backend to the emulator network. + + @returns this bundle for fluent configuration. + """ + self._enableInternalNetwork = True + + return self def configure(self) -> None: - 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 = self._containers["seedemu_traffic_observer_service"] + seedemu_traffic_observer_service_backend = self._containers[ + "seedemu_traffic_observer_service_backend" + self._suffix + ] 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,57 @@ 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"] + 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: + 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" + self._suffix + ] + 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"] + 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.getName()], + "depends_on": [seedemu_emulator_service_backend.getHostname()], "ports": [f"{self._ports.pop()}:80"], "build": f"./{seedemu_internet_map_toplogy.getHostname()}", } @@ -218,20 +259,25 @@ 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_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([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 = 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.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()}", @@ -240,15 +286,16 @@ 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_ip, 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_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()}"] + ) ) diff --git a/tools/InternetMap/backend/src/api/v1/main.ts b/tools/InternetMap/backend/src/api/v1/main.ts index 00dbf1c19..7d6515861 100644 --- a/tools/InternetMap/backend/src/api/v1/main.ts +++ b/tools/InternetMap/backend/src/api/v1/main.ts @@ -281,6 +281,42 @@ router.post('/container/vis/set', express.json(), async function (req, res, next next(); }); +router.post('/vm', express.json(), async function (req, res, next) { + 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; + } + + 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 + }); + + next(); +}); + router.ws('/console/:id', async function (ws, req, next) { try { if (process.env.CONSOLE === 'false') { @@ -299,7 +335,8 @@ router.ws('/console/:id', async function (ws, req, next) { var snifferSubscribers: WebSocket[] = []; var currentSnifferFilter: string = ''; -var visSubscribers: WebSocket[] = []; +let visSubscribers: WebSocket[] = []; +let VMSubscribers: WebSocket[] = []; router.post('/sniff', express.json(), async function (req, res, next) { sniffer.setListener((nodeId, data) => { @@ -355,6 +392,11 @@ router.ws('/container/vis/set', async function (ws, req, next) { next(); }); +router.ws('/vm', async function (ws, req, next) { + VMSubscribers.push(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; + } }