# CI/CD Components

> CI/CD components to run Mélodium in GitLab CI and report pipeline statuses.

Web page: https://docs.cadence.ci/en/gitlab/run-on-gitlab

Make sure you previously read [CI/CD with Mélodium](https://docs.cadence.ci/en/from-template/cicd.md).

> [!TIP]
>
> Open-source project? The [open-source plan](https://cadence.ci/en/open-source) is free, and makes your runs public, ready to link from merge requests and your README.

## CI/CD Component

GitLab CI/CD Components are available to run Mélodium within GitLab runners: [Mélodium GitLab Components](https://gitlab.com/melodium/gitlab-ci). Each component version matches a Mélodium version: use `@v0.11.0` for Mélodium 0.11.

The examples below expect two CI/CD variables, set up as described in [Setup Variables](#setup-variables):

- `CADENCE_RUN_TOKEN`: your Cadence.CI run token, given to the component's `melodium_api_token` input, for `--api-report` and for starting machines in your cloud account;
- `MELODIUM_SECRET_GITLAB_TOKEN`: a GitLab token, read by the status reporting below.

### Mélodium on GitLab CI

The configuration to add in GitLab YAML is:
```yaml
include:
  - component: gitlab.com/melodium/gitlab-ci/melodium@v0.11.0
    inputs:
      job_name: melodium-ci
      melodium_api_token: $CADENCE_RUN_TOKEN
      command: run --api-report --logs logs/melodium.log .melodium-ci/Compo.toml --repository_clone_url "$CI_PROJECT_URL.git" --repository_clone_ref "$CI_COMMIT_REF_NAME" --on_gitlab true --ci_service_project "$CI_PROJECT_ID" --ci_service_sha "$CI_COMMIT_SHA" --ci_service_ref "$CI_COMMIT_REF_NAME" --ci_service_pipeline "$CI_PIPELINE_ID"

melodium-ci:
  artifacts:
    when: always
    paths:
      - logs
```

Use `$CI_PROJECT_URL.git` rather than `$CI_REPOSITORY_URL` as clone URL: the latter embeds the job token, which would then appear in the run's parameters.

Refer to [melodium.yml](https://gitlab.com/melodium/gitlab-ci/-/blob/master/templates/melodium.yml) for the full list of input parameters.

### Dispatch Work Within GitLab Runner

A GitLab Component to run Mélodium with local distribution is available. Steps then run as containers on the GitLab runner itself, instead of machines in your cloud account:
```yaml
include:
  - component: gitlab.com/melodium/gitlab-ci/melodium-local-distrib@v0.11.0
    inputs:
      job_name: melodium-ci
      melodium_api_token: $CADENCE_RUN_TOKEN
      command: run --api-report --logs logs/melodium.log .melodium-ci/Compo.toml --work_location compose --repository_clone_url "$CI_PROJECT_URL.git" --repository_clone_ref "$CI_COMMIT_REF_NAME" --on_gitlab true --ci_service_project "$CI_PROJECT_ID" --ci_service_sha "$CI_COMMIT_SHA" --ci_service_ref "$CI_COMMIT_REF_NAME" --ci_service_pipeline "$CI_PIPELINE_ID"

melodium-ci:
  artifacts:
    when: always
    paths:
      - logs
```

The run is still reported to Cadence.CI; drop `--api-report` and the `melodium_api_token` input to run without it. A bigger runner can be used by applying some tags (see [GitLab Runners](https://docs.gitlab.com/ci/runners/hosted_runners/linux/)):
```yaml
melodium-ci:
  tags:
    - saas-linux-medium-amd64
  artifacts:
    when: always
    paths:
      - logs
```

Refer to [melodium-local-distrib.yml](https://gitlab.com/melodium/gitlab-ci/-/blob/master/templates/melodium-local-distrib.yml) for the full list of input parameters.

### Windows Runner

A GitLab Component to run Mélodium on a Windows runner is available:
```yaml
include:
  - component: gitlab.com/melodium/gitlab-ci/melodium-windows@v0.11.0
    inputs:
      job_name: melodium-ci
      melodium_api_token: $CADENCE_RUN_TOKEN
      command: run --api-report --logs logs/melodium.log .melodium-ci/Compo.toml --repository_clone_url "${env:CI_PROJECT_URL}.git" --repository_clone_ref "${env:CI_COMMIT_REF_NAME}" --on_gitlab true --ci_service_project "${env:CI_PROJECT_ID}" --ci_service_sha "${env:CI_COMMIT_SHA}" --ci_service_ref "${env:CI_COMMIT_REF_NAME}" --ci_service_pipeline "${env:CI_PIPELINE_ID}"

melodium-ci:
  artifacts:
    when: always
    paths:
      - logs
```

On Windows the command runs in PowerShell, which reads environment variables as `${env:CI_PROJECT_URL}` rather than `$CI_PROJECT_URL`. Inputs such as `$CADENCE_RUN_TOKEN` are expanded by GitLab and keep the usual form.

Refer to [melodium-windows.yml](https://gitlab.com/melodium/gitlab-ci/-/blob/master/templates/melodium-windows.yml) for the full list of input parameters.

### Mac OS Runner

A GitLab Component to run Mélodium on a Mac OS runner is available:
```yaml
include:
  - component: gitlab.com/melodium/gitlab-ci/melodium-macos@v0.11.0
    inputs:
      job_name: melodium-ci
      melodium_api_token: $CADENCE_RUN_TOKEN
      command: run --api-report --logs logs/melodium.log .melodium-ci/Compo.toml --repository_clone_url "$CI_PROJECT_URL.git" --repository_clone_ref "$CI_COMMIT_REF_NAME" --on_gitlab true --ci_service_project "$CI_PROJECT_ID" --ci_service_sha "$CI_COMMIT_SHA" --ci_service_ref "$CI_COMMIT_REF_NAME" --ci_service_pipeline "$CI_PIPELINE_ID"

melodium-ci:
  artifacts:
    when: always
    paths:
      - logs
```

Refer to [melodium-macos.yml](https://gitlab.com/melodium/gitlab-ci/-/blob/master/templates/melodium-macos.yml) for the full list of input parameters.

## Report Status to GitLab

To report [commit pipeline status](https://docs.gitlab.com/api/commits/#set-commit-pipeline-status) to GitLab, different methods are available. They all take the GitLab token as a `Secret`, read by default from `env:MELODIUM_SECRET_GITLAB_TOKEN`: the token never appears in logs, debug events or what Cadence.CI receives.

### Using `simpleStep`

In a [`simpleStep`](https://doc.melodium.tech/latest/en/cicd/naive/simpleStep.html) treatment, add the parameters as follows.
```mel
simpleStep[dispatcher=cicd](
  /* … */
  gitlab=true,
  gitlab_project_id=/* GitLab project identifier */,
  gitlab_sha=/* Commit SHA related to the step */,
  gitlab_ref=/* Git reference related to the step */,
  gitlab_pipeline_id=/* GitLab pipeline ID where the step should be reported */
)
```

The token comes from `gitlab_token`, which defaults to `"env:MELODIUM_SECRET_GITLAB_TOKEN"`; set it only to read the token from somewhere else. On a self-managed instance, also set `gitlab_root_url` (`"https://gitlab.com/api/v4"` by default) to your instance's API URL.

The CI/CD template receives these values in its `main` treatment parameters but does not pass them to its steps: to report statuses, add them to `build` and `test` in `main`:
```mel
build: simpleStep[dispatcher=cicd](
  /* … */
  gitlab=on_gitlab,
  gitlab_project_id=ci_service_project,
  gitlab_sha=ci_service_sha,
  gitlab_ref=ci_service_ref,
  gitlab_pipeline_id=ci_service_pipeline
)
/*
  …
*/
test: simpleStepWithInput[dispatcher=cicd](
  /* … */
  gitlab=on_gitlab,
  gitlab_project_id=ci_service_project,
  gitlab_sha=ci_service_sha,
  gitlab_ref=ci_service_ref,
  gitlab_pipeline_id=ci_service_pipeline
)
```

### Using `postGitlabState`

Within the appropriate treatment, add the [`postGitlabState`](https://doc.melodium.tech/latest/en/cicd/services/gitlab/postGitlabState.html) treatment.
```mel
use cicd/services/gitlab::|success
use cicd/services/gitlab::postGitlabState

/*
    …
*/

treatment someStuff[cicd: CicdDispatchEngine](
  // Add the following parameters
  gitlab_project_id: string,
  gitlab_sha: string,
  gitlab_ref: string,
  gitlab_pipeline_id: string
)
// …
{
    /*
        …
    */
    postSuccess: postGitlabState(
        name="Doing a treatment",
        description="Treatment accomplishing some stuff",
        state=|success(),
        root_url="https://gitlab.com/api/v4",
        project=gitlab_project_id,
        sha=gitlab_sha,
        ref=gitlab_ref,
        pipeline=gitlab_pipeline_id,
        token="env:MELODIUM_SECRET_GITLAB_TOKEN"
    )
    theTreatment.completed -> postSuccess.trigger
}
```

There also exists a more generic [`setServiceState`](https://doc.melodium.tech/latest/en/cicd/services/setServiceState.html) treatment with prepared triggers for each state. All its inputs must be connected; a step that is never canceled can feed `canceled` with a `closeBlock`, which closes without sending anything:
```mel
use cicd/services::setServiceState
use std/flow::closeBlock

/*
    …
*/

treatment someStuff[cicd: CicdDispatchEngine](
  // Add the following parameters
  gitlab_project_id: string,
  gitlab_sha: string,
  gitlab_ref: string,
  gitlab_pipeline_id: string
)
// …
{
    /*
        …
    */
    setServiceState(
        name="Doing a treatment",
        description="Treatment accomplishing some stuff",
        gitlab=true,
        gitlab_project_id=gitlab_project_id,
        gitlab_sha=gitlab_sha,
        gitlab_ref=gitlab_ref,
        gitlab_pipeline_id=gitlab_pipeline_id
    )
    noCancel: closeBlock<void>()

    Self.trigger -----------> setServiceState.pending
    theTreatment.started ---> setServiceState.running
    theTreatment.success ---> setServiceState.success
    theTreatment.error -----> setServiceState.error
    theTreatment.failed ----> setServiceState.failed
    Self.trigger -> noCancel.trigger,closed -> setServiceState.canceled
}
```

## Setup Variables

In GitLab, within _Settings_ > _CI/CD_ > _Variables_, add:

- `CADENCE_RUN_TOKEN`, masked, with a run token created in the Cadence.CI console;
- `MELODIUM_SECRET_GITLAB_TOKEN`, masked, with a [project access token](https://docs.gitlab.com/user/project/settings/project_access_tokens/) having the `api` scope and at least the Developer role, if the pipeline reports statuses.

To give other secrets to the pipeline, add them as variables whose name starts with `MELODIUM_SECRET_`: the engine reads them through locators such as `env:MELODIUM_SECRET_DEPLOY_KEY`. Secrets stored on Cadence.CI are read by the steps the pipeline dispatches, given to them [by reference](https://docs.cadence.ci/en/pipelines/secrets.md#from-github-and-gitlab-runners).

> [!NOTE]
>
> GitLab's `CI_JOB_TOKEN` is not allowed to update commit or pipeline statuses: a token with the `api` scope must be used to report them.
