diff --git a/.castor.php b/.castor.php
deleted file mode 100644
index 10a7056..0000000
--- a/.castor.php
+++ /dev/null
@@ -1,99 +0,0 @@
- $projectName,
- 'project_directory' => 'application',
- 'root_domain' => $projectName . '.local',
- 'extra_domains' => [
- 'www.' . $projectName . '.local',
- ],
- 'php_version' => '8.1',
- 'docker_compose_files' => [
- 'docker-compose.yml',
- 'docker-compose.worker.yml',
- 'docker-compose.builder.yml',
- ],
- 'services_to_build_first' => [
- 'php-base',
- 'builder',
- ],
- 'dinghy' => false,
- 'macos' => false,
- 'power_shell' => false,
- 'user_id' => 1000,
- 'root_dir' => __DIR__,
- 'start_workers' => false,
- 'composer_cache_dir' => '~/.composer/cache',
- ]);
-
- if (file_exists($context['root_dir'] . '/infrastructure/docker/docker-compose.override.yml')) {
- $context['docker_compose_files'][] = 'docker-compose.override.yml';
- }
-
-// $composerDirectory = exec('composer global config cache-dir -q')->getOutput();
-//
-// if ($composerDirectory) {
-// $context['composer_cache_dir'] = trim($composerDirectory);
-// }
-
- $platform = php_uname('s');
-
- if (stripos($platform, 'darwin') !== false) {
- $context['macos'] = true;
- }
-
- return $context;
-}
-
-function docker_compose(Context $context, string $command): \Symfony\Component\Process\Process
-{
- $domains = [$context['root_domain'], ...$context['extra_domains']];
- $domains = implode(' ', $domains);
-
- $environment = [
- 'PROJECT_NAME' => $context['project_name'],
- 'PROJECT_DIRECTORY' => $context['project_directory'],
- 'PROJECT_ROOT_DOMAIN' => $context['root_domain'],
- 'PROJECT_DOMAINS' => $domains,
- 'PROJECT_START_WORKERS' => $context['start_workers'],
- 'COMPOSER_CACHE_DIR' => $context['composer_cache_dir'],
- 'PHP_VERSION' => $context['php_version'],
- ];
-
- $dockerComposeFiles = implode(' -f ', array_map(function ($file) use ($context) {
- return $context['root_dir'] . '/infrastructure/docker/' . $file;
- }, $context['docker_compose_files']));
-
- $command = "docker compose -p {$context['project_name']} -f $dockerComposeFiles $command";
-
- return exec($command, environment: $environment);
-}
-
-#[Task(description: 'Build the infrastructure')]
-function build(Context $context) {
- $command = "build --build-arg PROJECT_NAME={$context['project_name']} --build-arg USER_ID={$context['user_id']} --build-arg PHP_VERSION={$context['php_version']}";
-
- foreach ($context['services_to_build_first'] as $service) {
- $serviceCommand = "$command $service";
-
- docker_compose($context, $serviceCommand);
- }
-
- return docker_compose($context, $command);
-}
-
-#[Task(description: 'Build and start the infrastructure')]
-function up(Context $context) {
- build($context);
-
- return docker_compose($context, 'up --remove-orphans --detach');
-}
diff --git a/.castor/infra.php b/.castor/infra.php
new file mode 100644
index 0000000..fe4eb77
--- /dev/null
+++ b/.castor/infra.php
@@ -0,0 +1,223 @@
+error('An error occured while starting the infrastructure.');
+ io()->note('Did you forget to run "castor infra:build"?');
+ io()->note('Or you forget to login to the registry?');
+
+ throw $e;
+ }
+}
+
+#[AsTask(description: 'Stops the infrastructure', aliases: ['stop'])]
+function stop(): void
+{
+ docker_compose(['stop']);
+}
+
+#[AsTask(description: 'Displays infrastructure logs')]
+function logs(): void
+{
+ docker_compose(['logs', '-f', '--tail', '150'], c: get_context()->withTty());
+}
+
+#[AsTask(description: 'Lists containers status')]
+function ps(): void
+{
+ docker_compose(['ps'], withBuilder: false);
+}
+
+#[AsTask(description: 'Cleans the infrastructure (remove container, volume, networks)')]
+function destroy(
+ #[AsOption(description: 'Force the destruction without confirmation', shortcut: 'f')]
+ bool $force = false,
+): void {
+ if (!$force) {
+ io()->warning('This will permanently remove all containers, volumes, networks... created for this project.');
+ io()->note('You can use the --force option to avoid this confirmation.');
+ if (!io()->confirm('Are you sure?', false)) {
+ io()->comment('Aborted.');
+
+ return;
+ }
+ }
+
+ docker_compose(['down', '--remove-orphans', '--volumes', '--rmi=local'], withBuilder: true);
+ $files = finder()
+ ->in(variable('root_dir') . '/infrastructure/docker/services/router/etc/ssl/certs/')
+ ->name('*.pem')
+ ->files()
+ ;
+ fs()->remove($files);
+}
+
+#[AsTask(description: 'Generates SSL certificates (with mkcert if available or self-signed if not)')]
+function generate_certificates(
+ #[AsOption(description: 'Force the certificates re-generation without confirmation', shortcut: 'f')]
+ bool $force = false,
+): void {
+ if (file_exists(variable('root_dir') . '/infrastructure/docker/services/router/etc/ssl/certs/cert.pem') && !$force) {
+ io()->comment('SSL certificates already exists.');
+ io()->note('Run "castor infra:generate-certificates --force" to generate new certificates.');
+
+ return;
+ }
+
+ if ($force) {
+ if (file_exists($f = variable('root_dir') . '/infrastructure/docker/services/router/etc/ssl/certs/cert.pem')) {
+ io()->comment('Removing existing certificates in infrastructure/docker/services/router/etc/ssl/certs/*.pem.');
+ unlink($f);
+ }
+
+ if (file_exists($f = variable('root_dir') . '/infrastructure/docker/services/router/etc/ssl/certs/key.pem')) {
+ unlink($f);
+ }
+ }
+
+ $finder = new ExecutableFinder();
+ $mkcert = $finder->find('mkcert');
+
+ if ($mkcert) {
+ $pathCaRoot = capture(['mkcert', '-CAROOT']);
+
+ if (!is_dir($pathCaRoot)) {
+ io()->warning('You must have mkcert CA Root installed on your host with "mkcert -install" command.');
+
+ return;
+ }
+
+ $rootDomain = variable('root_domain');
+
+ run([
+ 'mkcert',
+ '-cert-file', 'infrastructure/docker/services/router/etc/ssl/certs/cert.pem',
+ '-key-file', 'infrastructure/docker/services/router/etc/ssl/certs/key.pem',
+ $rootDomain,
+ "*.{$rootDomain}",
+ ...variable('extra_domains'),
+ ]);
+
+ io()->success('Successfully generated SSL certificates with mkcert.');
+
+ if ($force) {
+ io()->note('Please restart the infrastructure to use the new certificates with "castor up" or "castor start".');
+ }
+
+ return;
+ }
+
+ run(['infrastructure/docker/services/router/generate-ssl.sh']);
+
+ io()->success('Successfully generated self-signed SSL certificates in infrastructure/docker/services/router/etc/ssl/certs/*.pem.');
+ io()->comment('Consider installing mkcert to generate locally trusted SSL certificates and run "castor infra:generate-certificates --force".');
+
+ if ($force) {
+ io()->note('Please restart the infrastructure to use the new certificates with "castor up" or "castor start".');
+ }
+}
+
+#[AsTask(description: 'Starts the workers', namespace: 'infra:worker', name: 'start')]
+function workers_start(): void
+{
+ $workers = get_workers();
+
+ if (!$workers) {
+ return;
+ }
+
+ run([
+ 'docker',
+ 'update',
+ '--restart=unless-stopped',
+ ...$workers,
+ ], quiet: true);
+
+ run([
+ 'docker',
+ 'start',
+ ...$workers,
+ ], quiet: true);
+}
+
+#[AsTask(description: 'Stops the workers', namespace: 'infra:worker', name: 'stop')]
+function workers_stop(): void
+{
+ $workers = get_workers();
+
+ if (!$workers) {
+ return;
+ }
+
+ run([
+ 'docker',
+ 'update',
+ '--restart=no',
+ ...$workers,
+ ]);
+
+ run([
+ 'docker',
+ 'stop',
+ ...$workers,
+ ]);
+}
+
+/**
+ * Find worker containers for the current project.
+ *
+ * @return array
-Collection of Dockerfile and docker-compose configurations wrapped in an easy-to-use command line, oriented for PHP projects. + Collection of Dockerfile and docker-compose configurations wrapped in an easy-to-use command line, oriented for PHP projects.
## What is Docker Starter Kit -This repository provides a Docker infrastructure for your PHP projects with built-in support for HTTPS, custom domain, databases, workers... -and is used as a foundation for our projects here at [JoliCode](https://jolicode.com/). +This repository provides a Docker infrastructure for your PHP projects with +built-in support for HTTPS, custom domain, databases, workers... and is used as +a foundation for our projects at [JoliCode](https://jolicode.com/). Learn more about it and why we created and open-sourced this starter-kit in our blog posts: [in English 🇬🇧](https://jolicode.com/blog/introducing-our-docker-starter-kit) or [in French 🇫🇷](https://jolicode.com/blog/presentation-de-notre-starter-kit-docker). > **Warning** -> You are reading the README of version 3 that uses [Invoke](https://www.pyinvoke.org/). +> You are reading the README of version 4 that uses [castor](https://github.com/jolicode/castor). +* If you are using [Invoke](https://www.pyinvoke.org/), you can read the [dedicated README](https://github.com/jolicode/docker-starter/tree/v3.0.0); * If you are using [Fabric](https://www.fabfile.org/), you can read the [dedicated README](https://github.com/jolicode/docker-starter/tree/v2.0.0); -* If you want to migrate from docker-starter v2.x to v3.0, you can read the [dedicated guide](./UPGRADE-3.0.md); ## Project configuration Before executing any command, you need to configure a few parameters in the -`invoke.py` file: +`castor.php` file, in the `create_default_parameters()` function: -* `project_name` (**required**): This will be used to prefix all docker -objects (network, images, containers); +* `project_name` (**required**): This will be used to prefix all docker objects +(network, images, containers); -* `root_domain` (optional, default: `project_name + '.test'`): This is the -root domain where the application will be available; +* `root_domain` (optional, default: `project_name + '.test'`): This is the root +domain where the application will be available; -* `extra_domains` (optional): This contains extra domains where the -application will be available; +* `extra_domains` (optional): This contains extra domains where the application +will be available; * `project_directory` (optional, default: `application`): This is the host -directory containing your PHP application. +directory containing your PHP application; -For example: +* `php_version` (optional, default: `8.2`): This is PHP version. -```py -project_name = 'foobar' -root_domain = project_name + '.test' -extra_domains = ['api.' + root_domain] -project_directory = 'application' -``` +For example: -Will give you `https://foobar.test` and `https://api.foobar.test` pointing at your `application/` directory. +```php +function create_default_parameters(): Context +{ + $projectName = 'app'; + $tld = 'test'; + + return [ + 'project_name' => $projectName, + 'root_domain' => "{$projectName}.{$tld}", + 'extra_domains' => [ + "www.{$projectName}.{$tld}", + "admin.{$projectName}.{$tld}", + "api.{$projectName}.{$tld}", + ], + 'php_version' => 8.2, + ]; +) +``` + +Will give you `https://app.test`, `https://www.app.test`, +`https://api.app.test` and `https://admin.app.test` pointing at your +`application/` directory. > **Note** -> Some Invoke tasks have been added for DX purposes. Checkout and adapt +> Some castor tasks have been added for DX purposes. Checkout and adapt the tasks `install`, `migrate` and `cache_clear` to your project. ## Usage documentation -We provide a [README.dist.md](./README.dist.md) to bootstrap your project documentation, with everything you need -to know to start and interact with the infrastructure. +We provide a [README.dist.md](./README.dist.md) to bootstrap your project +documentation, with everything you need to know to start and interact with the +infrastructure. To use this README.dist.md as a base for your project's README.md: @@ -67,21 +85,22 @@ mv README.{dist.md,md} Some files will not be needed for your project and should be deleted: ```bash -rm -rf .github/ CHANGELOG.md CONTRIBUTING.md LICENSE UPGRADE-3.0.md +rm -rf .github/ CHANGELOG.md CONTRIBUTING.md LICENSE UPGRADE-4.0.md ``` -Also, in order to improve your usage of invoke scripts, you can install console autocompletion script. +Also, in order to improve your usage of castor scripts, you can install console +autocompletion script. If you are using bash: ```bash -invoke --print-completion-script=bash > /etc/bash_completion.d/invoke +castor completion | sudo tee /etc/bash_completion.d/castor ``` -If you are using something else, please refer to your shell documentation. -You may need to use `invoke --print-completion-script=zsh > /to/somewhere`. +If you are using something else, please refer to your shell documentation. You +may need to use `castor completion > /to/somewhere`. -Invoke supports completion for `bash`, `zsh` & `fish` shells. +Castor supports completion for `bash`, `zsh` & `fish` shells. ## Cookbooks @@ -866,7 +885,7 @@ services: Note: `172.17.0.1` is the default IP of the `docker0` interface. It can be different on some installations. You can see this IP thanks to the following command `ip address show docker0`. Since `docker-compose.yml` file supports -environment variables you may script this with Invoke. +environment variables you may script this with Castor. diff --git a/UPGRADE-3.0.md b/UPGRADE-3.0.md deleted file mode 100644 index 8dd29c8..0000000 --- a/UPGRADE-3.0.md +++ /dev/null @@ -1,292 +0,0 @@ -How to upgrade from 2.x to 3.0 -============================== - -This guide will cover the migration from Fabric to Invoke. -At anytime, you can refer the final form of the starter kit by looking -at the [main repository](https://github.com/jolicode/docker-starter) - -**WARNING**: Migrating from 2.x to 3.0 can be a fastidious task since a lot of -parts have changed. Moreover, this project is a starter kit. It means you -usually start with it, then you make your own choices and implementations. So if -you are comfortable with your current project **we recommend you to stick on -2.x**. If you want to migrate from 2.x to 3.0, here are the tasks you will have -to perform. - -## Fabric to Invoke - -1. Rename the `fabfile.py` to `tasks.py`: - - ```bash - mv fabfile.py tasks.py - ``` - -1. Extract the configuration to a dedicated file `invoke.py`: - - 1. The variables are not longer prefixed with `env.`: - - * `env.project_name` => `project_name`; - * `env.root_domain` => `root_domain`; - * `env.project_directory` => `project_directory`; - * `env.extra_domains` => `extra_domains`. - - 1. Append the following content to the file: - - ```py - # Usually, you should not edit the file above this point - docker_compose_files = [ - 'docker-compose.yml', - 'docker-compose.worker.yml', - ] - services_to_build_first = [ - 'php-base', - 'builder', - ] - dinghy = False - power_shell = False - user_id = 1000 - root_dir = '.' - start_workers = False - - - def __extract_runtime_configuration(config): - from invoke import run - from sys import platform - import os - import sys - from colorama import init, Fore - init(autoreset=True) - - config['root_dir'] = os.path.dirname(os.path.abspath(__file__)) - - try: - docker_kernel = run('docker version --format "{{.Server.KernelVersion}}"', hide=True).stdout - except: - docker_kernel = '' - - if platform == "darwin" and docker_kernel.find('linuxkit') != -1: - config['dinghy'] = True - elif platform in ["win32", "win64"]: - config['power_shell'] = True - # # Python can't set the vars correctly on PowerShell and local() always calls cmd.exe - shellProjectName = run('echo %PROJECT_NAME%', hide=True).stdout - if (shellProjectName != config['project_name']): - domains = '`' + '`, `'.join([config['root_domain']] + config['extra_domains']) + '`' - print(Fore.RED + 'Env vars not set (Windows detected)') - print(Fore.YELLOW + 'You must manually set environment variables on Windows:') - print('$Env:PROJECT_NAME="%s"' % config['project_name']) - print('$Env:PROJECT_DIRECTORY="%s"' % config['project_directory']) - print('$Env:PROJECT_ROOT_DOMAIN="%s"' % config['root_domain']) - print('$Env:PROJECT_DOMAINS="%s"' % domains) - sys.exit(0) - - if not config['power_shell']: - config['user_id'] = int(run('id -u', hide=True).stdout) - - if config['user_id'] > 256000: - config['user_id'] = 1000 - - return config - - - locals().update(__extract_runtime_configuration(locals())) - ``` - - 1. You can remove the similar part from `tasks.py` because `invoke.py` will be automatically imported. - - Don't forget to remove `set_local_configuration()` function and its function call. - -1. Edit `tasks.py`: - - 1. Fix `import`s: - - Remove all imports (unless you are using specific import) and add the following lines: - - ```py - from invoke import task - from shlex import quote - from colorama import Fore - ``` - - 1. Replace `run_in_docker_or_locally_for_dinghy()`, `docker_compose()` and `docker_composer_run()` functions: - - With the following content: - - ```py - def run_in_docker_or_locally_for_dinghy(c, command, no_deps=False): - """ - Mac users have a lot of problems running Yarn / Webpack on the Docker stack so this func allow them to run these tools on their host - """ - if c.dinghy: - with c.cd(c.project_directory): - c.run(command) - else: - docker_compose_run(c, command, no_deps=no_deps) - - - def docker_compose_run(c, command_name, service="builder", user="app", no_deps=False, workdir=None, port_mapping=False): - args = [ - 'run', - '--rm', - '-u %s' % quote(user), - ] - - if no_deps: - args.append('--no-deps') - - if port_mapping: - args.append('--service-ports') - - if workdir is not None: - args.append('-w %s' % quote(workdir)) - - docker_compose(c, '%s %s /bin/sh -c "exec %s"' % ( - ' '.join(args), - quote(service), - command_name - )) - - - def docker_compose(c, command_name): - domains = '`' + '`, `'.join([c.root_domain] + c.extra_domains) + '`' - - env = { - 'PROJECT_NAME': c.project_name, - 'PROJECT_DIRECTORY': c.project_directory, - 'PROJECT_ROOT_DOMAIN': c.root_domain, - 'PROJECT_DOMAINS': domains, - } - - cmd = 'docker-compose -p %s %s %s' % ( - c.project_name, - ' '.join('-f \'' + c.root_dir + '/infrastructure/docker/' + file + '\'' for file in c.docker_compose_files), - command_name - ) - - c.run(cmd, pty=True, env=env) - ``` - - 1. Use the context in all tasks - - Invoke needs a context (named `c`) in every single task. This context: - - * is configured for each task; - * contains the configuration; - * contains some methods to execute commands. - - You will need to update all tasks signature, and all tasks function call to pass the context: - - Before: - - ```py - @task - def up(): - build() - docker_compose('up --remove-orphans -d') - ``` - - After: - - ```py - @task - def up(c): - build(c) - docker_compose(c, 'up --remove-orphans -d') - ``` - - 1. Do not use `env.` anymore: - - Before: - - ```py - @task - def up(c): - print(env.project_name) - ``` - - After: - - ```py - @task - def up(c): - print(c.project_name) - ``` - - 1. Do not use `local()` anymore: - - Before: - - ```py - @task - def start(c): - machine_running = local('dinghy status', capture=True) - ``` - - After: - - ```py - @task - def start(c): - machine_running = c.local('dinghy status').stdout - ``` - - 1. Add `Builder` class and use it: - - The Builder class is the new `@with_builder` decorator - - ```py - class Builder: - def __init__(self, c): - self.c = c - - def __enter__(self): - self.docker_compose_files = self.c.docker_compose_files - self.c.docker_compose_files = ['docker-compose.builder.yml'] + self.docker_compose_files - - def __exit__(self, type, value, traceback): - self.c.docker_compose_files = self.docker_compose_files - ``` - - Before: - - ```py - @task - @with_builder - def install(): - docker_compose_run('composer install -n --prefer-dist --optimize-autoloader') - ``` - - After: - - ```py - @task - def install(c): - with Builder(c): - docker_compose_run(c, 'composer install -n --prefer-dist --optimize-autoloader') - ``` - - 1. Update colors - - Fabric provided a nice helper for colors. Now we use colorama. - - Before: - - ```py - print green('You can now browse:') - for domain in [c.root_domain] + c.extra_domains: - print yellow("* https://" + domain) - ``` - - After: - - ```py - @task - print(Fore.GREEN + 'You can now browse:') - for domain in [c.root_domain] + c.extra_domains: - print(Fore.YELLOW + "* https://" + domain) - ``` - -## Alpine to Debian - -We have changed PHP base images from Alpine to Debian. The best guide to process -this migration is to replicate what have been done in following pull request: -https://github.com/jolicode/docker-starter/pull/67 diff --git a/application/public/index.php b/application/public/index.php index 8eae0fb..3e18401 100644 --- a/application/public/index.php +++ b/application/public/index.php @@ -1,3 +1,3 @@ + */ +function create_default_variables(): array +{ + $projectName = 'app'; + $tld = 'test'; + + return [ + 'project_name' => $projectName, + 'root_domain' => "{$projectName}.{$tld}", + 'extra_domains' => [ + "www.{$projectName}.{$tld}", + ], + 'php_version' => $_SERVER['DS_PHP_VERSION'] ?? '8.2', + 'project_directory' => 'application', + ]; +} + +#[AsTask(description: 'Builds and starts the infrastructure, then install the application (composer, yarn, ...)')] +function start(): void +{ + infra\workers_stop(); + infra\generate_certificates(false); + infra\build(); + infra\up(); + cache_clear(); + install(); + migrate(); + infra\workers_start(); + + notify('The stack is now up and running.'); + io()->success('The stack is now up and running.'); + + about(); +} + +#[AsTask(description: 'Installs the application (composer, yarn, ...)', namespace: 'app')] +function install(): void +{ + $basePath = sprintf('%s/%s', variable('root_dir'), variable('project_directory')); + + if (is_file("{$basePath}/composer.json")) { + docker_compose_run('composer install -n --prefer-dist --optimize-autoloader'); + } + if (is_file("{$basePath}/yarn.lock")) { + docker_compose_run('yarn'); + } elseif (is_file("{$basePath}/package.json")) { + docker_compose_run('npm install'); + } +} + +#[AsTask(description: 'Clear the application cache', namespace: 'app')] +function cache_clear(): void +{ + // docker_compose_run('rm -rf var/cache/ && bin/console cache:warmup'); +} + +#[AsTask(description: 'Migrates database schema', namespace: 'app:db')] +function migrate(): void +{ + // docker_compose_run('bin/console doctrine:database:create --if-not-exists'); + // docker_compose_run('bin/console doctrine:migration:migrate -n --allow-no-migration'); +} diff --git a/infrastructure/docker/docker-compose.worker.yml b/infrastructure/docker/docker-compose.worker.yml index 6c69081..bc3a2c3 100644 --- a/infrastructure/docker/docker-compose.worker.yml +++ b/infrastructure/docker/docker-compose.worker.yml @@ -12,12 +12,10 @@ x-services-templates: volumes: - "../../${PROJECT_DIRECTORY}:/home/app/application:cached" user: app - environment: - - "PROJECT_START_WORKERS=${PROJECT_START_WORKERS}" labels: - "docker-starter.worker.${PROJECT_NAME}" -#services: +# services: # worker_messenger: # <<: *worker_base # command: php -d memory_limit=1G /home/app/application/bin/console messenger:consume async --memory-limit=128M diff --git a/infrastructure/docker/services/php/Dockerfile b/infrastructure/docker/services/php/Dockerfile index cf822ac..7cebeab 100644 --- a/infrastructure/docker/services/php/Dockerfile +++ b/infrastructure/docker/services/php/Dockerfile @@ -69,10 +69,6 @@ CMD ["runsvdir", "-P", "/etc/service"] FROM php-base as worker -COPY worker/entrypoint.sh /var/lib/entrypoint.sh - -ENTRYPOINT ["/var/lib/entrypoint.sh"] - FROM php-base as builder ARG NODEJS_VERSION=18.x diff --git a/infrastructure/docker/services/php/worker/entrypoint.sh b/infrastructure/docker/services/php/worker/entrypoint.sh deleted file mode 100755 index 4665cae..0000000 --- a/infrastructure/docker/services/php/worker/entrypoint.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/sh -set -e - -if [ "$PROJECT_START_WORKERS" = "False" ]; then - echo "Worker not started" - exit 0 -fi - -exec "$@" diff --git a/invoke.py b/invoke.py deleted file mode 100644 index b63406b..0000000 --- a/invoke.py +++ /dev/null @@ -1,90 +0,0 @@ -# This will be used to prefix all docker objects (network, images, containers) -project_name = 'app' -# This is the root domain where the app will be available -# The "frontend" container will receive all the traffic -root_domain = project_name + '.test' -# This contains extra domains where the app will be available -# The "frontend" container will receive all the traffic -extra_domains = [] -# This is the host directory containing your PHP application -project_directory = 'application' - -# Usually, you should not edit the file below this point -php_version = '8.1' -docker_compose_files = [ - 'docker-compose.yml', - 'docker-compose.worker.yml', -] -dinghy = False -macos = False -power_shell = False -user_id = 1000 -root_dir = '.' -start_workers = False -composer_cache_dir = '~/.composer/cache' - - -def __extract_runtime_configuration(config): - from invoke import run - from sys import platform - import os - import sys - import inspect - from colorama import init, Fore - init(autoreset=True) - - config['root_dir'] = os.path.dirname(inspect.getfile(lambda: None)) - - if os.path.exists(config['root_dir'] + '/infrastructure/docker/docker-compose.override.yml'): - config['docker_compose_files'] += ['docker-compose.override.yml'] - - config['composer_cache_dir'] = composer_cache_dir - composer_cache_dir_from_host = run('composer global config cache-dir -q', warn=True, hide=True).stdout - if composer_cache_dir_from_host: - config['composer_cache_dir'] = composer_cache_dir_from_host.strip() - - if platform == "darwin": - config['macos'] = True - - try: - docker_kernel = run('docker version --format "{{.Server.KernelVersion}}"', hide=True).stdout - except: - docker_kernel = '' - - if docker_kernel.find('boot2docker') != -1: - config['dinghy'] = True - else: - config['docker_compose_files'] += ['docker-compose.docker-for-x.yml'] - elif platform in ["win32", "win64"]: - config['docker_compose_files'] += ['docker-compose.docker-for-x.yml'] - config['power_shell'] = True - # Python can't set the vars correctly on PowerShell and local() always calls cmd.exe - shellProjectName = run('echo %PROJECT_NAME%', hide=True).stdout - - if (shellProjectName.rstrip() != config['project_name']): - domains = '`' + '`, `'.join([config['root_domain']] + config['extra_domains']) + '`' - print(Fore.RED + 'Env vars not set (Windows detected)') - print(Fore.YELLOW + 'You must manually set environment variables on Windows:') - # This list should be in sync with the one in docker_compose.py, docker_compose() function - print('$Env:PROJECT_NAME="%s"' % config['project_name']) - print('$Env:PROJECT_DIRECTORY="%s"' % config['project_directory']) - print('$Env:PROJECT_ROOT_DOMAIN="%s"' % config['root_domain']) - print("$Env:PROJECT_DOMAINS='%s'" % domains) - print('$Env:COMPOSER_CACHE_DIR="%s"' % config['composer_cache_dir']) - print('$Env:PHP_VERSION="%s"' % config['php_version']) - sys.exit(1) - - if not config['power_shell']: - config['user_id'] = int(run('id -u', hide=True).stdout) - - if config['user_id'] > 256000: - config['user_id'] = 1000 - - if config['user_id'] == 0: - print(Fore.YELLOW + 'Running as root? Fallback to fake user id.') - config['user_id'] = 1000 - - return config - - -locals().update(__extract_runtime_configuration(locals())) diff --git a/tasks.py b/tasks.py deleted file mode 100644 index 73588b6..0000000 --- a/tasks.py +++ /dev/null @@ -1,334 +0,0 @@ -from invoke import task -from shlex import quote -from colorama import Fore -from distutils.spawn import find_executable -import json -import os -import re -import requests -import subprocess - - -@task -def build(c): - """ - Build the infrastructure - """ - command = 'build' - command += ' --build-arg PROJECT_NAME=%s' % c.project_name - command += ' --build-arg USER_ID=%s' % c.user_id - command += ' --build-arg PHP_VERSION=%s' % c.php_version - - with Builder(c): - docker_compose(c, command) - - -@task -def up(c): - """ - Build and start the infrastructure - """ - build(c) - - docker_compose(c, 'up --remove-orphans --detach') - - -@task -def start(c): - """ - Build and start the infrastructure, then install the application (composer, yarn, ...) - """ - if c.dinghy: - machine_running = c.run('dinghy status', hide=True).stdout - if machine_running.splitlines()[0].strip() != 'VM: running': - c.run('dinghy up --no-proxy') - c.run('docker-machine ssh dinghy "echo \'nameserver 8.8.8.8\' | sudo tee -a /etc/resolv.conf && sudo /etc/init.d/docker restart"') - - stop_workers(c) - generate_certificates(c) - up(c) - cache_clear(c) - install(c) - migrate(c) - start_workers(c) - - print(Fore.GREEN + 'The stack is now up and running.') - help(c) - - -@task -def install(c): - """ - Install the application (composer, yarn, ...) - """ - with Builder(c): - if os.path.isfile(c.root_dir + '/' + c.project_directory + '/composer.json'): - docker_compose_run(c, 'composer install -n --prefer-dist --optimize-autoloader', no_deps=True) - if os.path.isfile(c.root_dir + '/' + c.project_directory + '/yarn.lock'): - run_in_docker_or_locally_for_mac(c, 'yarn', no_deps=True) - elif os.path.isfile(c.root_dir + '/' + c.project_directory + '/package.json'): - run_in_docker_or_locally_for_mac(c, 'npm install', no_deps=True) - - -@task -def cache_clear(c): - """ - Clear the application cache - """ - # with Builder(c): - # docker_compose_run(c, 'rm -rf var/cache/ && php bin/console cache:warmup', no_deps=True) - - -@task -def migrate(c): - """ - Migrate database schema - """ - # with Builder(c): - # docker_compose_run(c, 'php bin/console doctrine:database:create --if-not-exists') - # docker_compose_run(c, 'php bin/console doctrine:migration:migrate -n --allow-no-migration') - - -@task -def builder(c, user="app"): - """ - Open a shell (bash) into a builder container - """ - with Builder(c): - docker_compose_run(c, 'bash', user=user, bare_run=True) - - -@task -def logs(c): - """ - Display infrastructure logs - """ - docker_compose(c, 'logs -f --tail=150') - - -@task -def ps(c): - """ - List containers status - """ - docker_compose(c, 'ps --all') - - -@task -def stop(c): - """ - Stop the infrastructure - """ - docker_compose(c, 'stop') - - -@task -def start_workers(c): - """ - Start the workers - """ - workers = get_workers(c) - - if (len(workers) == 0): - return - - c.start_workers = True - c.run('docker update --restart=unless-stopped %s' % (' '.join(workers)), hide='both') - docker_compose(c, 'up --remove-orphans --detach') - - -@task -def stop_workers(c): - """ - Stop the workers - """ - workers = get_workers(c) - - if (len(workers) == 0): - return - - c.start_workers = False - c.run('docker update --restart=no %s' % (' '.join(workers)), hide='both') - c.run('docker stop %s' % (' '.join(workers)), hide='both') - - -@task -def destroy(c, force=False): - """ - Clean the infrastructure (remove container, volume, networks) - """ - - if not force: - ok = confirm_choice('Are you sure? This will permanently remove all containers, volumes, networks... created for this project.') - if not ok: - return - - with Builder(c): - docker_compose(c, 'down --remove-orphans --volumes --rmi=local') - c.run('rm -f infrastructure/docker/services/router/etc/ssl/certs/*.pem') - - -@task(default=True) -def help(c): - """ - Display some help and available urls for the current project - """ - - print('Run ' + Fore.GREEN + 'inv help' + Fore.RESET + ' to display this help.') - print('') - - print('Run ' + Fore.GREEN + 'inv --help' + Fore.RESET + ' to display invoke help.') - print('') - - print('Run ' + Fore.GREEN + 'inv -l' + Fore.RESET + ' to list all the available tasks.') - c.run('inv --list') - - print(Fore.GREEN + 'Available URLs for this project:' + Fore.RESET) - for domain in [c.root_domain] + c.extra_domains: - print("* " + Fore.YELLOW + "https://" + domain + Fore.RESET) - - try: - response = json.loads(requests.get('http://%s:8080/api/http/routers' % (c.root_domain)).text) - gen = (router for router in response if re.match("^%s-(.*)@docker$" % (c.project_name), router['name'])) - for router in gen: - if router['service'] != 'frontend-%s' % (c.project_name): - host = re.search('Host\(\`(?P