WSL2 based Dockerを使用したGitlabの構築

## 旧バージョン

```yaml:docker-compose.yaml
#docker-composeのバージョン
#https://matsuand.github.io/docs.docker.jp.onthefly/compose/compose-file/
version: '3.8'
services:
  gitlab:
    #インストール時点の最新版にすることを推奨
    image: 'gitlab/gitlab-ce:13.8.0-ce.0'
    container_name: gitlab
    restart: always
    environment:
      GITLAB_OMNIBUS_CONFIG: |
        #公式ドキュメントを参照してください
        # https://docs.gitlab.com/omnibus/docker/README.html
        # https://docs.gitlab.com/omnibus/docker/README.html#install-gitlab-using-docker-compose
        # https://docs.gitlab.com/omnibus/docker/README.html#pre-configure-docker-container
        external_url 'http://localhost:10080'
        #gitlab_rails['gitlab_host'] = 'http://localhost:10022'
        gitlab_rails['gitlab_shell_ssh_port'] = 10022
        nginx['listen_addresses'] = ['0.0.0.0', '[::]']
        # 以降、カスタマイズ
        # https://github.com/gitlabhq/omnibus-gitlab/blob/master/files/gitlab-config-template/gitlab.rb.template
        # Maven(Gradle)パッケージレジストリの有効化
        gitlab_rails['packages_enabled'] = true
        gitlab_rails['packages_storage_path'] = "/var/opt/gitlab/gitlab-rails/shared/packages"
        # grafana監視を使用
        grafana['disable_login_form'] = false
        grafana['allow_user_sign_up'] = true
        grafana['admin_password'] = 'grafana'
        grafana['metrics_enabled'] = true
        grafana['metrics_basic_auth_username'] = 'grafana_metrics'
        grafana['metrics_basic_auth_password'] = 'grafana'
    ports:
      - '10080:10080'
      - '443:443'
      - '10022:22'
    volumes:
      - type: volume
        source: gitlab-config
        target: /etc/gitlab
        volume:
          nocopy: true
      - type: volume
        source: gitlab-log
        target: /var/log/gitlab
        volume:
          nocopy: true
      - type: volume
        source: gitlab-data
        target: /var/opt/gitlab
        volume:
          nocopy: true
  runner:
    build:
      context: .
      dockerfile: gitlab-runner.Dockerfile
    container_name: gitlab-runner
    environment:
      http_proxy: ***
      https_proxy: ***
    restart: always
    volumes:
      - gitlab-runner-volume:/etc/gitlab-runner
      - /var/run/docker.sock:/var/run/docker.sock
volumes:
  gitlab-config:
  gitlab-log:
  gitlab-data:
  gitlab-runner-volume:

```

```dockerfile:gitlab-runner.Dockerfile
#インストール時点の最新版にすることを推奨。うまく動作しない場合はubuntuにすること。
#https://hub.docker.com/r/gitlab/gitlab-runner/tags?page=1&ordering=last_updated
FROM gitlab/gitlab-runner:ubuntu-v13.8.0

ENV http_proxy=***
ENV https_proxy=***

RUN ["/bin/bash", "-c", "apt update"]
RUN ["/bin/bash", "-c", "apt -y install sshpass"]
RUN ["/bin/bash", "-c", "apt -y install openjdk-8-jdk"]

```

```shell:main.tf
terraform {
  # 本体のバージョン指定
  required_version = "~> 0.14"

  required_providers {
    gitlab = {
      source  = "gitlabhq/gitlab"
      version = "3.4.0"
    }
  }
}

provider "gitlab" {
  # Configuration options
  token    = ***
  base_url = "http://localhost:10080/api/v4/"
}


locals {
  #管理者一覧
  admininfo = {
    #ここの下に全員分足してください。左は社員番号、右はメールアドレスの@から左
    "user" = "prefix"
  }
  #一般ユーザ一覧
  userinfo = {
    "user" = "prefix"
  }
}

resource "gitlab_user" "admin" {

  for_each = local.admininfo

  name             = each.value
  username         = each.key
  email            = "${each.value}@foo.co.jp"
  is_admin         = true
  projects_limit   = 4
  can_create_group = true
  is_external      = false
  reset_password   = true
}

resource "gitlab_user" "user" {

  for_each = local.userinfo

  name             = each.value
  username         = each.key
  email            = "${each.value}@foo.co.jp"
  is_admin         = false
  projects_limit   = 2
  can_create_group = true
  is_external      = false
  reset_password   = true
}

resource "gitlab_group" "cicd_test" {
  name        = "cicd_test"
  path        = "cicd_test"
  description = "An example group"

  visibility_level = "internal"
}

// Create a project in the example group
resource "gitlab_project" "example" {
  name         = "example"
  description  = "example"
  namespace_id = gitlab_group.cicd_test.id

  visibility_level = gitlab_group.cicd_test.visibility_level
}

resource "gitlab_group_membership" "admin" {
  for_each = gitlab_user.admin

  group_id     = gitlab_group.cicd_test.id
  user_id      = each.value.id
  access_level = "maintainer"
}

resource "gitlab_group_membership" "user" {
  for_each = gitlab_user.user

  group_id     = gitlab_group.cicd_test.id
  user_id      = each.value.id
  access_level = "guest"
}

output "web_url" {
  value = gitlab_project.example.web_url
}

output "runners_token" {
  value = gitlab_project.example.runners_token
}


```


## 14.0 & oracleあり
```yaml:docker-compose.yaml
#docker-composeのバージョン
#https://matsuand.github.io/docs.docker.jp.onthefly/compose/compose-file/
version: '3.8'
services:
  gitlab:
    #インストール時点の最新版にすることを推奨
    image: "gitlab/gitlab-ce:${GITLAB_TAG_VERSION:-14.0.0-ce.0}"
    container_name: gitlab
    restart: always
    environment:
      GITLAB_OMNIBUS_CONFIG: |
        #公式ドキュメントを参照してください
        # https://docs.gitlab.com/omnibus/docker/README.html
        # https://docs.gitlab.com/omnibus/docker/README.html#install-gitlab-using-docker-compose
        # https://docs.gitlab.com/omnibus/docker/README.html#pre-configure-docker-container
        # = をつけてはいけない。正しいhostが参照できない場合がある
        external_url 'http://${GITLAB_HOST?err}:18080'
        #gitlab_rails['gitlab_host'] = 'http://${GITLAB_HOST?err}:18080'
        gitlab_rails['gitlab_shell_ssh_port'] = 10022
        #タイムゾーン設定
        gitlab_rails['time_zone'] = 'Asia/Tokyo'
        nginx['listen_addresses'] = ['0.0.0.0', '[::]']
        #nginx['listen_port'] = 18080
        #ChromeでsecureでないcookieがブロックされることによるInvalidAuthenticityToken(status code 422)対策。
        #https://gitlab.com/gitlab-org/gitlab-foss/-/issues/50393
        nginx['proxy_set_headers'] = {
          "X-Forwarded-Proto" => "http"
        }
        nginx['redirect_http_to_https'] = false
        nginx['redirect_http_to_https_port'] = 18080
        nginx['real_ip_trusted_addresses'] = ['${GITLAB_HOST?err}','127.0.0.1']
        # 以降、カスタマイズ
        # https://github.com/gitlabhq/omnibus-gitlab/blob/master/files/gitlab-config-template/gitlab.rb.template
        # [OPTION]Maven(Gradle)パッケージレジストリの有効化
        gitlab_rails['packages_enabled'] = true
        gitlab_rails['packages_storage_path'] = "/var/opt/gitlab/gitlab-rails/shared/packages"
        # [OPTION]grafana監視を使用
        grafana['disable_login_form'] = false
        grafana['allow_user_sign_up'] = true
        grafana['admin_password'] = 'grafana'
        grafana['metrics_enabled'] = true
        grafana['metrics_basic_auth_username'] = 'grafana_metrics'
        grafana['metrics_basic_auth_password'] = 'grafana'
        prometheus['scrape_configs'] = [
          {
          'job_name': 'example',
          'static_configs' => [ 'targets' => ['${GITLAB_HOST?err}:9252'], ],
          },
        ]
        #https://gitlab.com/gitlab-org/gitlab-foss/-/issues/35300
        prometheus['monitor_kubernetes'] = false
        pages_external_url 'http://${GITLAB_HOST?err}:18080'
        gitlab_pages['enable'] = true
        gitlab_pages['dir'] = "/var/opt/gitlab/gitlab-pages"
        gitlab_pages['log_directory'] = "/var/log/gitlab/gitlab-pages"
        gitlab_pages['access_control'] = true
        gitlab_pages['inplace_chroot'] = true
    ports:
      - '18080:18080'
      - '443:443'
      - '10022:22'
    volumes:
      - type: volume
        source: gitlab-config
        target: /etc/gitlab
        volume:
          nocopy: true
      - type: volume
        source: gitlab-log
        target: /var/log/gitlab
        volume:
          nocopy: true
      - type: volume
        source: gitlab-data
        target: /var/opt/gitlab
        volume:
          nocopy: true
  runner:
    build:
      context: .
      dockerfile: gitlab-runner.Dockerfile
      args:
        IMAGE_VERSION: ubuntu-v${RUNNER_TAG_VERSION:-14.0.0}
        PROXY_URL: ${PROXY_URL}
    image: koyama/jdk-runner:ubuntu-v${RUNNER_TAG_VERSION:-14.0.0}
    container_name: gitlab-runner
    restart: always
    ports:
      #9252=Prometheus
      - '9252:9252'
    volumes:
      - gitlab-runner-config:/etc/gitlab-runner
      - gitlab-runner-home:/home/gitlab-runner
      - /var/run/docker.sock:/var/run/docker.sock
  database:
   build:
     context: .
     dockerfile: oracle.Dockerfile
   container_name: oracle11
   shm_size: 2g # 共有メモリは1GB以上にしないとコンテナ起動時にエラー発生
   environment:
     - TZ=Asia/Tokyo
     - LANGUAGE=ja_JP.ja
     - LANG=ja_JP.UTF-8
     - NLS_LANG=Japanese_Japan.AL32UTF8 # sqlplusの日本語化用
     - ORACLE_PWD=oracle # sys,systemのパスワード
     - ORACLE_SID=XE
     - ORACLE_PDB=pdb1
   ports:
     - 1521:1521
   volumes:
     - /oradata:/opt/oracle/oradata # データの永続化
volumes:
  gitlab-config:
  gitlab-log:
  gitlab-data:
  gitlab-runner-config:
  gitlab-runner-home:

```

### runner-dockerfile

```
#インストール時点の最新版にすることを推奨。うまく動作しない場合はubuntuにすること。
#https://hub.docker.com/r/gitlab/gitlab-runner/tags?page=1&ordering=last_updated

ARG IMAGE_VERSION=ubuntu-v13.10.0
ARG PROXY_URL

FROM gitlab/gitlab-runner:${IMAGE_VERSION}

ENV http_proxy=${PROXY_URL} https_proxy=${PROXY_URL}

#いちいち/bin/bashを入れなくても済むようにする
SHELL ["/bin/bash", "-o", "pipefail", "-c"]

#鍵認証がない検証環境と接続するためのパッケージ：sshpass
#ビルド用java：openjdk-8-jdk

RUN apt update && apt install -y \
    openjdk-8-jdk \
    && apt clean \
    && rm -rf /var/lib/apt/lists/*
```

### oracle-dockerfile
```
FROM oracle/database:11.2.0.2-xe 

RUN yum -y install vi
RUN echo 'TZ="Asia/Tokyo"' > /etc/sysconfig/clock
RUN cp /usr/share/zoneinfo/Asia/Tokyo /etc/localtime
RUN echo 'LANG="ja_JP.UTF-8"' > /etc/sysconfig/i18n
RUN echo 'LC_CTYPE="ja_JP.utf8"' >> /etc/sysconfig/i18n
RUN yum reinstall -y glibc-common
RUN yum reinstall -y glibc
RUN localedef -f UTF-8 -i ja_JP ja_JP.UTF-8

# ポート番号1521で起動
EXPOSE 1521

```

## oracleビルド方法

https://www.oracle.com/jp/database/technologies/xe-prior-releases.html

※git bash　を利用

```
git clone https://github.com/oracle/docker-images.git
cd oracle/docker-images/OracleDatabase/SingleInstance/dockerfiles
# ここで、oracle-xe-11.2.0-1.0.x86_64.rpm.zipを移動先フォルダに配置
./buildContainerImage.sh -v 11.2.0.2 -x -i
```


### テストサンプル
```gradle:build.gradle
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    implementation "com.oracle.database.jdbc:ojdbc6:11.2.0.4"
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
}

test {
    useJUnitPlatform()
}
```

```yaml:.gitlab-ci.yaml
image: openjdk:8u282-jdk-slim

default:
  tags:
    - shell
variables:
  GRADLE_OPTS: "-Dorg.gradle.daemon=false"

before_script:
  - export GRADLE_USER_HOME=`pwd`/.gradle

build:
  stage: build
  script: ./gradlew --build-cache assemble
  cache:
    key: "$CI_COMMIT_REF_NAME"
    policy: push
    paths:
      - build
      - .gradle

test:
  stage: test
  script: ./gradlew test
  cache:
    key: "$CI_COMMIT_REF_NAME"
    policy: pull
    paths:
      - build
      - .gradle
  artifacts:
    paths:
      - ./build/reports/
    reports:
      junit: ./build/test-results/test/TEST-MainTest.xml
```

```java:main.java
import oracle.ucp.jdbc.PoolDataSource;
import oracle.ucp.jdbc.PoolDataSourceFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static List<Integer> getList() throws SQLException {
        final String URL = "jdbc:oracle:thin:@192.168.1.4:1521:XE";
        final String USER = "system";
        final String PASS = "oracle";
        final String CONN_FACTORY_CLASS_NAME = "oracle.jdbc.pool.OracleDataSource";

        PoolDataSource pds = PoolDataSourceFactory.getPoolDataSource();

        pds.setConnectionFactoryClassName(CONN_FACTORY_CLASS_NAME);
        pds.setURL(URL);
        pds.setUser(USER);
        pds.setPassword(PASS);
        pds.setConnectionPoolName("JDBC_UCP_POOL");

        // Default is 0. Set the initial number of connections to be created
        // when UCP is started.
        pds.setInitialPoolSize(5);
        pds.setMinPoolSize(5);
        pds.setMaxPoolSize(20);
        pds.setTimeoutCheckInterval(5);
        pds.setInactiveConnectionTimeout(10);

        List<Integer> list = new ArrayList<>();
        final String SQL = "select * from HR.EMPLOYEES";
        try (Connection conn = pds.getConnection();
             PreparedStatement ps = conn.prepareStatement(SQL);
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                list.add(rs.getInt("EMPLOYEE_ID"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            System.out.println("finished");
        }
        return list;
    }

    public static void main(String[] args) throws SQLException {
        System.out.println(getList().stream().collect(Collectors.summarizingInt(e->e)));
    }
}

```

```java:test.java
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.sql.SQLException;
import java.util.stream.Collectors;

import static org.junit.jupiter.api.Assertions.*;

class MainTest {

    @Test
    void getList() throws SQLException {
        Assertions.assertEquals(Main.getList().stream().count(),107);
        System.out.println(Main.getList().stream().collect(Collectors.summarizingInt(e->e)));
    }
}

```

### 結果画像

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/161516/712262ff-eec1-0323-313a-746e004b7891.png)

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/161516/fd313963-f956-d358-1d9b-ffa453ba90ed.png)

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/161516/03a788de-6f72-655d-be46-5f9f3390d830.png)