> ## Documentation Index
> Fetch the complete documentation index at: https://docs.generalrobotics.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Advanced mode

This section provides an overview of the advanced settings available within GRID Enterprise. These settings provide further customization and control over your development setup.

### Docker Commands

While GRID Enterprise's CLI seamlessly handles Docker authentication and basic orchestration, advanced users may seek greater control and customization by interacting directly with Docker. The following Docker commands provide a deeper level of control over containers and their configurations.

#### 1. Monitor Container Logs

Monitoring container logs is crucial for debugging and ensuring that your applications are running smoothly.

**Command:**

```bash theme={null}
docker logs -f <container_name>
```

**Description:**

* `-f`: Follows the log output in real-time, allowing you to monitor logs as they are generated.

**Example:**

```bash theme={null}
docker logs -f grid_core_sdk
```

#### 2. Access Container Shell

Accessing the container's shell allows for in-depth troubleshooting and direct interaction with the container's environment.

**Command:**

```bash theme={null}
docker exec -it <container_name> /bin/bash
```

**Description:**

* `-i`: Interactive mode.
* `-t`: Allocates a pseudo-TTY.
* `/bin/bash`: Specifies the shell to use inside the container.

**Example:**

```bash theme={null}
docker exec -it grid_core_sdk /bin/bash
```

#### 3. Inspect Container Details

Inspecting a container provides detailed information about its configuration, state, and resource usage, aiding in troubleshooting and optimization.

**Command:**

```bash theme={null}
docker inspect <container_name>
```

**Description:**

* Retrieves comprehensive details about the specified container in JSON format.

**Example:**

```bash theme={null}
docker inspect grid_core_sdk
```

#### 4. Monitor Container Resource Usage

Keeping track of a container's resource consumption ensures that it operates efficiently without overusing system resources.

**Command:**

```bash theme={null}
docker stats <container_name>
```

**Description:**

* Provides real-time statistics on CPU, memory, network, and disk usage for the specified container.

**Example:**

```bash theme={null}
docker stats grid_core_sdk
```

#### 5. Update Docker Containers

Updating containers ensures that you have the latest features, security patches, and performance improvements. This process involves pulling the latest image, stopping and removing the existing container, and deploying a new one with the updated image.

**Steps to Update a Container:**

* **Pull the Latest Image:**

```bash theme={null}
docker pull sfgrid.azurecr.io/grid/core/sdk:latest
```

**Example:**

```bash theme={null}
docker pull sfgrid.azurecr.io/grid/core/sdk:latest
```

* **Stop the Running Container:**

```bash theme={null}
docker stop <container_name>
```

**Example:**

```bash theme={null}
docker stop grid_core_sdk
```

* **Remove the Existing Container:**

```bash theme={null}
docker rm <container_name>
```

**Example:**

```bash theme={null}
docker rm grid_core_sdk
```

* **Run the Updated Container:**

```bash theme={null}
docker run -d --name <container_name> sfgrid.azurecr.io/grid/core/sdk:latest
```

**Example:**

```bash theme={null}
docker run -d --name grid_core_sdk sfgrid.azurecr.io/grid/core/sdk:latest
```

### Data Storage

Images generated during sessions are saved inside the Docker container in the `/app/images` directory. To save an image using Python, use the following code snippet:

```python theme={null}
import os
from PIL import Image

# Define the directory inside the container where images are saved
IMAGE_SAVE_DIR = "/app/images"

# Ensure the directory exists
os.makedirs(IMAGE_SAVE_DIR, exist_ok=True)

# Save the image
image.save(os.path.join(IMAGE_SAVE_DIR, "generated_image.png"))
```

To transfer the saved images from the Docker container to a location on your host machine, use the `docker cp` command as shown below:

```bash theme={null}
docker cp <container_name>:/app/images /path/on/host
```

**Example:**

If your container is named `grid_core` and you want to copy images to `/home/user/images`, run:

```bash theme={null}
docker cp grid_core:/app/images /home/user/images
```

This command copies all images from the container's `/app/images` directory to your specified host directory, allowing you to access and manage them outside the Docker environment.

### API Reference

Apart from the CLI, which is meant to be an easy-to-use orchestration module for GRID sessions, the Enterprise also allows you to interact directly with GRID APIs to start/stop sessions. This section provides a detailed reference for the GRID Enterprise's `GRIDSessionManager` class, which manages user sessions, including session creation, management, and termination. Below is a description of the class methods and their usage.

#### `GRIDSessionManager` Class

The `GRIDSessionManager` class handles session management for users, including generating JWT tokens, starting and stopping sessions, listing active sessions, and managing resource configurations.

**Initialization:**

Initializes a `GRIDSessionManager` instance by loading the resource configuration from `~/.grid/resource_config.json`. If the configuration file does not exist, it prompts the user to input the necessary tokens and creates the configuration file.

**Raises:**

* `ValueError`: If the configuration file does not contain `'tokens'`.

```python theme={null}
def __init__(self) -> None:
    ...
```

##### Method: `load_resource_config`

Loads the resource configuration from the default path `~/.grid/resource_config.json`. If the file does not exist, it creates the directory and prompts the user to input the required tokens and resource details.

**Returns:**

* `Dict`: The loaded resource configuration dictionary.

```python theme={null}
def load_resource_config(self):
    ...
```

##### Method: `generate_jwt_token`

Generates a JWT token using the user ID and a predefined secret key.

**Returns:**

* `str`: The generated JWT token.

```python theme={null}
def generate_jwt_token(self) -> str:
    ...
```

##### Method: `create_config`

Creates a session configuration dictionary based on the provided session configuration file.

**Parameters:**

* `session_config_file_path` (str): Path to the session configuration file containing AirGen and GRID settings.
* `session_id` (str): The unique identifier for the session.

**Returns:**

* `Dict`: A dictionary containing the combined session configuration.

**Raises:**

* `ValueError`: If the session configuration file does not contain `'airgen'` or `'grid'` settings.

```python theme={null}
def create_config(self, session_config_file_path: str, session_id: str) -> Dict:
    ...
```

##### Method: `get_ip_for_resource`

Retrieves the IP address for the specified resource name.

**Parameters:**

* `resource_name` (str): The name of the resource.

**Returns:**

* `Optional[str]`: The IP address of the resource if found, otherwise `None`.

```python theme={null}
def get_ip_for_resource(self, resource_name: str) -> Optional[str]:
    ...
```

##### Method: `start_session`

Starts a new session by sending a request to the specified node IP.

**Parameters:**

* `session_id` (str): The unique identifier for the session.
* `session_config_file_path` (str): Path to the session configuration file.
* `node_ip` (str): The IP address of the node where the session will be started.

**Returns:**

* `Optional[bool]`: `True` if the session was started successfully, `False` if it failed, or `None` if a request error occurs.

```python theme={null}
async def start_session(
    self, session_id: str, session_config_file_path: str, node_ip: str
) -> Optional[bool]:
    ...
```

##### Method: `stop_session`

Stops an active session by sending a termination request to the associated node.

**Parameters:**

* `session_id` (str): The unique identifier for the session to be stopped.

**Returns:**

* `bool`: `True` if the session was stopped successfully, `False` otherwise.

```python theme={null}
async def stop_session(self, session_id: str) -> bool:
    ...
```

##### Method: `list_sessions`

Lists all active sessions, providing details such as session ID, node IP, and last active time.

**Returns:**

* `List[Dict]`: A list of dictionaries containing session details, or an empty list if no active sessions are found.

```python theme={null}
async def list_sessions(self) -> List[Dict]:
    ...
```

##### Method: `list_nodes`

Lists all configured nodes with their corresponding IP addresses.

**Returns:**

* `None`: Prints the list of nodes in a tabulated format. If no nodes are found, it notifies the user.

```python theme={null}
def list_nodes(self):
    ...
```

### Usage Examples

Below are examples of how to use the `GRIDSessionManager` class.

#### Creating an Instance

Initializes a `GRIDSessionManager` instance.

```python theme={null}
manager = GRIDSessionManager()
```

#### Starting a Session

Starts a new session by specifying the session ID, session configuration file path, and node IP.

```python theme={null}
await manager.start_session(
    session_id="session_001",
    session_config_file_path="path/to/session_config.json",
    node_ip="192.168.1.10"
)
```

#### Stopping a Session

Stops an active session by providing the session ID.

```python theme={null}
await manager.stop_session(session_id="session_001")
```

#### Listing Active Sessions

Retrieves and displays all active sessions with their details.

```python theme={null}
await manager.list_sessions()
```

#### Listing Configured Nodes

Displays all configured nodes along with their IP addresses.

```python theme={null}
manager.list_nodes()
```
