# Advanced Implementation

> The advanced template entrypoint: runners, containers, volumes and streaming between steps.

Web page: https://docs.cadence.ci/en/from-template/advanced-implementation

Here is an explanation of the advanced implementation of CI/CD, using more detailed treatments and tooling.
`main` acts the same as in root, `build` and `test` treatments are from `advanced.mel` file and contains CI/CD implementation.

## CI/CD implementation

The `build` and `test` treatments are implemented the same way: they require to setup a runner, on which steps are distributed.
Their basic implementation is given as naive working example.

Both takes the [`CicdDispatchEngine`](https://doc.melodium.tech/latest/en/cicd/runners/index.html) model, and an input `trigger` signal. [`CicdDispatchEngine`](https://doc.melodium.tech/latest/en/cicd/runners/index.html) and input `trigger` are used to require a new distributed runner [`CicdRunnerEngine`](https://doc.melodium.tech/latest/en/cicd/runners/index.html) through [`setupRunner`](https://doc.melodium.tech/latest/en/cicd/runners/setupRunner.html) as soon as it is useful to get one ready.

```mel
treatment build[cicd: CicdDispatchEngine](repository_clone_url: string, repository_clone_ref: string)
  model runner: CicdRunnerEngine()
  input trigger: Block<void>
  output data:   Stream<byte>
{
    setupRunner[
        dispatcher=cicd,
        runner=runner
    ](
        name="build",
        cpu=10,
        memory=500,
        storage=1000,
        volumes=[|volume("build-result", 30)],
        containers=[|container("ubuntu", 1000, 10, 8000, |wrap<Arch>(|amd64()), [|mount("build-result", "/mounted/result")], "ubuntu:noble", _)]
    )
    gitClone: stepOn[runner=runner](
        name="git",
        executor_name="ubuntu",
        environment=|wrap<Environment>(|environment(|map([]), "/root", false, false)),
        commands=[
            |command("apt-get", ["update"]),
            |command("apt-get", ["install", "-y", "git"]),
            |command("git", ["config", "--global", "url.https://.insteadOf", "git://"]),
            |command("git", ["clone", "--branch", repository_clone_ref, "--depth", "1", repository_clone_url, "project"])
        ]
    )
    makeList: stepOn[runner=runner](
        name="list",
        executor_name="ubuntu",
        environment=|wrap<Environment>(|environment(|map([]), "/root/project", false, false)),
        commands=|raw_commands([
            "sh -c \"ls -l --almost-all | tee files-list.txt\"",
            "mv files-list.txt /mounted/result/"
        ]),
        out_filesystem="build-result",
        out_file="files-list.txt"
    )
    stopRunner[runner=runner]()

    Self.trigger -> setupRunner.trigger,ready -> gitClone.trigger,completed -> makeList.trigger,finished -> stopRunner.trigger
                                                                               makeList.data -------------> Self.data
}
```

<img src="/img/main_advanced_light.png" className="dark:hidden rounded shadow"/>
<img src="/img/main_advanced_dark.png" className="hidden dark:block rounded shadow"/>

## Setup runner

[`setupRunner`](https://doc.melodium.tech/latest/en/cicd/runners/setupRunner.html) takes different parameters, the main ones are:
- `name`, a string with which all logs will be marked;
- `cpu`, amount of CPU (in millicores, `1000` being one full CPU) the Mélodium engine must have;
- `memory`, memory (in megabytes) dedicated to the Mélodium engine;
- `storage`, disk space (in megabytes) the Mélodium engine has at disposal;
- `volumes`, array of volumes the Mélodium engine and containers can share on the runner;
- `containers`, list of containers that are available to run steps on the runner.

Volumes are basically labels associated with size (in megabytes), and can be mounted inside containers to share data with them.
Containers are defined by the following:
```mel
|container(name, memory, cpu, storage, arch, mounts, image, pull_secret)
```
- `name` being the designated name with which the container can be adressed as executor;
- `memory` (in megabytes), `cpu` (in millicores) and `storage` (in megabytes), in that order, having the same meaning as for the Mélodium engine;
- `arch` designating the hardware architecture on which the container must run, as an `Option<Arch>`: `_` takes the architecture of the worker, `|wrap<Arch>(|amd64())` requires a specific one;
- `mounts` being an array of mounting points for defined volumes within the container filesystem;
- `image` the container image to use as base for the container;
- `pull_secret` the (optional) registry credentials to pull the container image, a `Secret<string>` holding a Docker configuration JSON. The container starts before the engine of the runner, so the secret has to travel with the request: give it with [`|locate`](https://doc.melodium.tech/latest/en/std/secret/|locate.html) and the transmission `value`, such as `|locate<string>("env:MELODIUM_SECRET_REGISTRY", "registry", "value", false)`, or `reference` for a secret [stored on Cadence.CI](https://docs.cadence.ci/en/pipelines/secrets.md#secrets-for-containers), given by name. A plain locator stays on the machine that resolves it, and is refused.

> The Mélodium engine itself can be quite frugal in resources as work in CI/CD is usually done within containers, leaving only the orchestration and data streaming work: the template gives it 10 millicores and 500 megabytes.

> Currently the AMD64/x86_64 `|amd64()` and ARM64/aarch64 `|arm64()` architectures are supported, and all the containers in the same runner that give one must use the same architecture.

> All volumes together must fit within the Mélodium engine storage, and each container's storage must be at least the sum of the volumes mounted in it. While CPU and memory values are cumulative among the main engine and containers, requiring the runner to have the sum of all the required capacities, the storage space corresponding to volumes is shared and not duplicated between containers.

## Run steps

On every runner an arbitrary number of steps can be applied using the [`stepOn`](https://doc.melodium.tech/latest/en/cicd/steps/stepOn.html) and [`stepOnWithInput`](https://doc.melodium.tech/latest/en/cicd/steps/stepOnWithInput.html) treatments.
These treatments takes a [`CicdRunnerEngine`](https://doc.melodium.tech/latest/en/cicd/runners/index.html), on which work will be done, according to the following logic:
1. inputting data file (for [`stepOnWithInput`](https://doc.melodium.tech/latest/en/cicd/steps/stepOnWithInput.html)),
1. processing commands,
1. outputting data file.

### Inputting data

[`stepOnWithInput`](https://doc.melodium.tech/latest/en/cicd/steps/stepOnWithInput.html) have two parameters setting up what data file is wrote: `in_filesystem` and `in_file` respectively tells what volume and what file name are filled with data coming from `data` input.

Here the file `"list.txt"` is wrote on filesystem volume `"tested-data"` and accessible on the mounting point `"/mounted/data/"` of executor `"alpine"`:
```mel
makeTest: stepOnWithInput[runner=runner](
    name="test",
    executor_name="alpine",
    in_filesystem="tested-data",
    in_file="list.txt",
    commands=[
        |command("test", ["-s", "/mounted/data/list.txt"]),
        |command("cat", ["/mounted/data/list.txt"])
    ]
)
```

### Processing commands

The `commands` parameter is a list of commands run on executor designated by `executor_name` within optionally-defined `environment`.

Commands can be specified in multiple ways:
- [`|command()`](https://doc.melodium.tech/latest/en/process/command/|command.html) function, for a finely-detailed command and list of arguments;
- [`|raw_command()`](https://doc.melodium.tech/latest/en/process/command/|raw_command.html) function, for a raw string command;
- [`|raw_commands()`](https://doc.melodium.tech/latest/en/process/command/|raw_commands.html) function, for full list of string commands.

`environment` can also be given, to specify additionnal environment variables or working directory.
The environemnt is applied on all commands of a given step.

```mel
gitClone: stepOn[runner=runner](
    name="git",
    executor_name="ubuntu",
    environment=|wrap<Environment>(|environment(|map([]), "/root", false, false)),
    commands=[
        |command("apt-get", ["update"]),
        |command("apt-get", ["install", "-y", "git"]),
        |command("git", ["config", "--global", "url.https://.insteadOf", "git://"]),
        |command("git", ["clone", "--branch", repository_clone_ref, "--depth", "1", repository_clone_url, "project"])
    ]
)
```

### Outputting data

[`stepOn`](https://doc.melodium.tech/latest/en/cicd/steps/stepOn.html) and [`stepOnWithInput`](https://doc.melodium.tech/latest/en/cicd/steps/stepOnWithInput.html) treatments both allows to output any data. `out_filesystem` and `out_file` specify what volume and file is streamed after step commands.

Here the file `"files-list.txt"` is streamed from volume `"build-result"` after commands are run:
```mel
makeList: stepOn[runner=runner](
    name="list",
    executor_name="ubuntu",
    environment=|wrap<Environment>(|environment(|map([]), "/root/project", false, false)),
    commands=|raw_commands([
        "sh -c \"ls -l --almost-all | tee files-list.txt\"",
        "mv files-list.txt /mounted/result/"
    ]),
    out_filesystem="build-result",
    out_file="files-list.txt"
)
```

## Execute CI/CD Locally

In order to run the CI/CD program, invoke Mélodium with program parameters.
```sh
export MELODIUM_API_TOKEN=<YOUR_RUN_TOKEN>
melodium run --api-report .melodium-ci/Compo.toml advanced --repository_clone_url <FULL_CLONE_URL>.git --repository_clone_ref <BRANCH_OR_TAG>
```

Where `YOUR_RUN_TOKEN` is a Cadence.CI run token. This executes the CI/CD "main engine" from your computer, and runs the `build` and `test` runners on machines Cadence.CI starts in your connected cloud account. Add `--work_location compose` to run them as local containers instead.

All the CI/CD logs are also shown in the terminal.
