# Task System

## Tasks for remote command execution

Our platform uses a task system to communicate with the Host Agents installed on all your hosts (BM and VM). A Task as such is a wrapper for one or more commands sent to a Host Agent. This wrapper keeps track of which command is currently being executed and its execution status. A Task can also contain a schedule time, allowing Tasks to be performed somewhere in the future. You can find an API example below.

### Task Actions

Tasks are made up of TaskAction elements, each describing a single command to be executed by a host agent. A Task consists of one or more TaskActions. Each TaskAction has a status field to inform you about the result of command execution.

### Task Action Examples

Here are some examples of TaskAction types, to give you an idea:

* Download a build archive (e.g. your game server build, or a sidecar build)
* Extract a build archive
* Stop an instance
* Deploy a build \[to an instance]
* Start an instance

These are the most frequently used actions and are also basic building blocks with which we can can deploy / update / control your instances. These actions also exactly describe an instance deployment task. So whenever any type of instance is deployed for you, we create a task containing the actions described above. These 6 actions are combined into 1 Task.

Here is a more thorough example of the actions of an instance deployment Task. These also contain the parameters that each action requires in order to operate properly:

```
[
    {
        "idx": 0,
        "actionType": "Download software build",
        "requiredParams": {
            "buildId": "The ID of the applicationBuild. Its build archive will be downloaded."
        }
    },
    {
        "idx": 1,
        "actionType": "Extract software build",
        "requiredParams": {
            "buildId": "The ID of the applicationBuild. This action will extract the build archive that has been downloaded."
        }
    },
    {
        "idx": 2,
        "actionType": "Stop instance",
        "requiredParams": {
            "methodId": "The ID of the stop-method, indicating how you want to stop the application instance.",
            "timeout": "If the stop-method is graceful, you can indicate a maximum time to wait here, before the application instance is forcefully terminated."
        }
    },
    {
        "idx": 3,
        "actionType": "Deploy software build to instance",
        "requiredParams": {
            "buildId": "The ID of the applicationBuild. This action expects the build archive to already have been downloaded and extracted onto the host."
        }
    },
    {
        "idx": 4,
        "actionType": "Start instance",
        "requiredParams": null
    }
]
```

## Task Status (API example)

When you create a Task, you will be given a Task ID. With this ID you can at any time check the status of the task. when doing that via the API you will get something like this:

#### HTTP request

[`GET /v3/applicationInstance/task/12278257`](/api/api_one.md#v3-applicationinstance-task-taskid)

#### Request body

```
none
```

#### Response body

```
[
    {
        "id": 12278257,
        "batchId": 0,
        "categoryId": 2,
        "entityId": 2897954287466354361,
        "currentActionIdx": 6,
        "executeAt": 1563469175,
        "lastActivityAt": 1563469176,
        "finishedAt": 1563469176,
        "resultCode": 127,
        "resultText": "Done"
    }
]
```

| Property         | Description                                                                                                                                 |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| id               | The Task ID                                                                                                                                 |
| batchId          | The TaskBatch ID, in case this Task was part of a larger batch                                                                              |
| categoryId       | Task category. Normally 2, meaning ApplicationInstance                                                                                      |
| entityId         | The ID of the entity (application instance) this Task was performed on                                                                      |
| currentActionIdx | Index of the TaskAction currently being executed. If the Task itself is yet to be performed, this will be -1                                |
| executeAt        | If 0, the Task will be executed as soon as possible. Otherwise it contains the unix timestamp of when the Task has been or will be executed |
| lastActivityAt   | Unix timestamp of when the system received a sign of life for this Task                                                                     |
| finishedAt       | Unix timestamp of when this task finished processing                                                                                        |
| resultCode       | The result of the Task in numerical form                                                                                                    |
| resultText       | The result of the Task in human readable form                                                                                               |

Table 1: Task element structure

### Task Result Codes

A Task will reflect its status through the `resultCode` property. It will be one of the following values:

* **0**: Pending Task execution
* **1**: In progress
* **2**: Paused
* **124**: Cancelled
* **125**: Timed out
* **126**: Done, with error (the error can be found in the `resultText` field
* **127**: Done

## Task Batch

When executing the same command for multiple application instances, we create a task per instance and collect them all within a TaskBatch. When a TaskBatch is submitted, you will be given a TaskBatch ID. This allows you to easily track the execution result of all tasks within a batch.

#### HTTP request

[`GET /v3/applicationInstance/taskBatch/9`](/api/api_one.md#v3-applicationinstance-task-taskid)

#### Request body

```
none
```

#### Response body

```
[
    {
        "id": 9,
        "createdAt": 1559829929,
        "executeAt": 1559829929,
        "finishedAt": 1559829934,
        "numTasks": 8,
        "numTasksOk": 8,
        "numTasksFailed": 0,
        "numTasksCancelled": 0,
        "taskIds": {
            "11238257": 127,
            "11238258": 127,
            "11238259": 127,
            "11238260": 127,
            "11238261": 127,
            "11238262": 127,
            "11238263": 127,
            "11238264": 127
        }
    }
]
```

| Property          | Value type | Description                                                     |
| ----------------- | ---------- | --------------------------------------------------------------- |
| id                | int        | A unique TaskBatch identifier                                   |
| createdAt         | int        | Unix timestamp of creation time                                 |
| executeAt         | int        | Unix timestamp of execution time                                |
| finishedAt        | int        | Unix timestamp of when the last Tasks was finished executing    |
| numTasks          | int        | Total number of Tasks in this TaskBatch                         |
| numTasksOk        | int        | Number of successfully executed Tasks                           |
| numTasksFailed    | int        | Number of failed Tasks                                          |
| numTasksCancelled | int        | Number of cancelled Tasks                                       |
| taskIds           | \[int]     | Array of key-value pairs indicating Task ID vs Task Result Code |

Table 2: TaskBatch element structure

## Cancelling a Task

You can cancel a (scheduled) Task by calling [`DELETE /v3/applicationInstance/task/{taskId}`](/api/api_one.md#v3-applicationinstance-task-taskid).

The Task's result code will then be set to 124 (Cancelled).

{% hint style="info" %}
At this time, there is no roll-back mechanism for already performed actions.
{% endhint %}

## Pausing a Task

You can pause a (running) task by calling [`PUT /v3/applicationInstance/task/{taskId}`](/api/api_one.md#v3-applicationinstance-task-taskid).

To un-pause a paused Task, call the same endpoint.

Note that when a Task is paused, no other Tasks for the same ApplicationInstance can be run, until the paused Task is un-paused and finished again.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.i3d.net/game-hosting/features/task-system.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
