diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index bd98d3f2a..25e97c31a 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -8,7 +8,7 @@ // Append -bullseye or -buster to pin to an OS version. // Use -bullseye variants on local arm64/Apple Silicon. "args": { - "VARIANT": "16-bullseye" + "VARIANT": "18-bullseye" } }, // Set *default* container specific settings.json values on container create. @@ -19,12 +19,14 @@ "dbaeumer.vscode-eslint", "svelte.svelte-vscode", "ardenivanov.svelte-intellisense", - "Prisma.prisma" + "Prisma.prisma", + "bradlc.vscode-tailwindcss", + "waderyan.gitblame" ], // Use 'forwardPorts' to make a list of ports inside the container available locally. - "forwardPorts": [3000], + "forwardPorts": [3000, 3001], // Use 'postCreateCommand' to run commands after the container is created. - "postCreateCommand": "cp .env.template .env && pnpm install && pnpm db:push && pnpm db:seed", + "postCreateCommand": "cp apps/api/.env.example pps/api/.env && pnpm install && pnpm db:push && pnpm db:seed", // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. "remoteUser": "node", "features": { diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index ddd313869..f96d5b45c 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1 +1,2 @@ open_collective: coollabsio +github: coollabsio \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 3338ead6a..4642a8549 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -5,4 +5,4 @@ contact_links: about: Reach out to us on discord or our github discussions page. - name: 🙋‍♂️ Service request url: https://feedback.coolify.io/ - about: want to request a new service? for e.g wordpress, hasura, appwrite etc... + about: Want to request a new service or build pack? For example Wordpress, Hasura, Appwrite, Angular etc... diff --git a/.github/workflows/production-release.yml b/.github/workflows/production-release.yml index 2076895b4..e3e6a0750 100644 --- a/.github/workflows/production-release.yml +++ b/.github/workflows/production-release.yml @@ -2,14 +2,14 @@ name: production-release on: release: - types: [published] + types: [released] jobs: - making-something-cool: - runs-on: ubuntu-latest + arm64-build: + runs-on: [self-hosted, arm64] steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Set up QEMU uses: docker/setup-qemu-action@v1 - name: Set up Docker Buildx @@ -26,12 +26,60 @@ jobs: uses: docker/build-push-action@v2 with: context: . - platforms: linux/amd64,linux/arm64 + platforms: linux/arm64 push: true - tags: coollabsio/coolify:latest,coollabsio/coolify:${{steps.package-version.outputs.current-version}} - cache-from: type=registry,ref=coollabsio/coolify:buildcache - cache-to: type=registry,ref=coollabsio/coolify:buildcache,mode=max + tags: coollabsio/coolify:${{steps.package-version.outputs.current-version}}-arm64 + cache-from: type=registry,ref=coollabsio/coolify:buildcache-arm64 + cache-to: type=registry,ref=coollabsio/coolify:buildcache-arm64,mode=max + amd64-build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - name: Get current package version + uses: martinbeentjes/npm-get-version-action@v1.2.3 + id: package-version + - name: Build and push + uses: docker/build-push-action@v3 + with: + context: . + platforms: linux/amd64 + push: true + tags: coollabsio/coolify:${{steps.package-version.outputs.current-version}}-amd64 + cache-from: type=registry,ref=coollabsio/coolify:buildcache-amd64 + cache-to: type=registry,ref=coollabsio/coolify:buildcache-amd64,mode=max + merge-manifest: + runs-on: ubuntu-latest + needs: [amd64-build, arm64-build] + steps: + - name: Checkout + uses: actions/checkout@v3 + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - name: Get current package version + uses: martinbeentjes/npm-get-version-action@v1.2.3 + id: package-version + - name: Create & publish manifest + run: | + docker manifest create coollabsio/coolify:${{steps.package-version.outputs.current-version}} --amend coollabsio/coolify:${{steps.package-version.outputs.current-version}}-amd64 --amend coollabsio/coolify:${{steps.package-version.outputs.current-version}}-arm64 + docker manifest push coollabsio/coolify:${{steps.package-version.outputs.current-version}} - uses: sarisia/actions-status-discord@v1 if: always() with: - webhook: ${{ secrets.DISCORD_WEBHOOK_DEV_CHANNEL }} + webhook: ${{ secrets.DISCORD_WEBHOOK_PROD_RELEASE_CHANNEL }} diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.yml new file mode 100644 index 000000000..305ea3ad9 --- /dev/null +++ b/.github/workflows/release-candidate.yml @@ -0,0 +1,90 @@ +name: release-candidate +on: + release: + types: [prereleased] + +jobs: + arm64-making-something-cool: + runs-on: [self-hosted, arm64] + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + ref: "next" + - name: Set up QEMU + uses: docker/setup-qemu-action@v1 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v1 + - name: Login to DockerHub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - name: Get current package version + uses: martinbeentjes/npm-get-version-action@v1.2.3 + id: package-version + - name: Build and push + uses: docker/build-push-action@v2 + with: + context: . + platforms: linux/arm64 + push: true + tags: coollabsio/coolify:${{github.event.release.name}}-arm64 + cache-from: type=registry,ref=coollabsio/coolify:buildcache-rc-arm64 + cache-to: type=registry,ref=coollabsio/coolify:buildcache-rc-arm64,mode=max + - uses: sarisia/actions-status-discord@v1 + if: always() + with: + webhook: ${{ secrets.DISCORD_WEBHOOK_DEV_RELEASE_CHANNEL }} + amd64-making-something-cool: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + ref: "next" + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - name: Get current package version + uses: martinbeentjes/npm-get-version-action@v1.2.3 + id: package-version + - name: Build and push + uses: docker/build-push-action@v3 + with: + context: . + platforms: linux/amd64 + push: true + tags: coollabsio/coolify:${{github.event.release.name}}-amd64 + cache-from: type=registry,ref=coollabsio/coolify:buildcache-rc-amd64 + cache-to: type=registry,ref=coollabsio/coolify:buildcache-rc-amd64,mode=max + - uses: sarisia/actions-status-discord@v1 + if: always() + with: + webhook: ${{ secrets.DISCORD_WEBHOOK_DEV_RELEASE_CHANNEL }} + merge-manifest-to-be-cool: + runs-on: ubuntu-latest + needs: [arm64-making-something-cool, amd64-making-something-cool] + steps: + - name: Checkout + uses: actions/checkout@v3 + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - name: Create & publish manifest + run: | + docker manifest create coollabsio/coolify:${{github.event.release.name}} --amend coollabsio/coolify:${{github.event.release.name}}-amd64 --amend coollabsio/coolify:${{github.event.release.name}}-arm64 + docker manifest push coollabsio/coolify:${{github.event.release.name}} + diff --git a/.github/workflows/staging-release.yml b/.github/workflows/staging-release.yml index dda360f8a..7a5e5474f 100644 --- a/.github/workflows/staging-release.yml +++ b/.github/workflows/staging-release.yml @@ -6,11 +6,13 @@ on: - next jobs: - staging-release: - runs-on: ubuntu-latest + arm64-making-something-cool: + runs-on: [self-hosted, arm64] steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 + with: + ref: "next" - name: Set up QEMU uses: docker/setup-qemu-action@v1 - name: Set up Docker Buildx @@ -20,16 +22,66 @@ jobs: with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} + - name: Get current package version + uses: martinbeentjes/npm-get-version-action@v1.2.3 + id: package-version - name: Build and push uses: docker/build-push-action@v2 + with: + context: . + platforms: linux/arm64 + push: true + tags: coollabsio/coolify:next-arm64 + cache-from: type=registry,ref=coollabsio/coolify:buildcache-next-arm64 + cache-to: type=registry,ref=coollabsio/coolify:buildcache-next-arm64,mode=max + amd64-making-something-cool: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + ref: "next" + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - name: Get current package version + uses: martinbeentjes/npm-get-version-action@v1.2.3 + id: package-version + - name: Build and push + uses: docker/build-push-action@v3 with: context: . platforms: linux/amd64 push: true - tags: coollabsio/coolify:next - cache-from: type=registry,ref=coollabsio/coolify:buildcache-next - cache-to: type=registry,ref=coollabsio/coolify:buildcache-next,mode=max + tags: coollabsio/coolify:next-amd64,coollabsio/coolify:next-test + cache-from: type=registry,ref=coollabsio/coolify:buildcache-next-amd64 + cache-to: type=registry,ref=coollabsio/coolify:buildcache-next-amd64,mode=max + merge-manifest-to-be-cool: + runs-on: ubuntu-latest + needs: [arm64-making-something-cool, amd64-making-something-cool] + steps: + - name: Checkout + uses: actions/checkout@v3 + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - name: Create & publish manifest + run: | + docker manifest create coollabsio/coolify:next --amend coollabsio/coolify:next-amd64 --amend coollabsio/coolify:next-arm64 + docker manifest push coollabsio/coolify:next - uses: sarisia/actions-status-discord@v1 if: always() with: - webhook: ${{ secrets.DISCORD_WEBHOOK_DEV_CHANNEL }} + webhook: ${{ secrets.DISCORD_WEBHOOK_DEV_RELEASE_CHANNEL }} diff --git a/.gitignore b/.gitignore index 9e73cbebf..500cd6776 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .DS_Store node_modules +.pnpm-store build .svelte-kit package @@ -10,4 +11,5 @@ dist client apps/api/db/*.db local-serve -apps/api/db/migration.db-journal \ No newline at end of file +apps/api/db/migration.db-journal +apps/api/core* \ No newline at end of file diff --git a/.gitpod.Dockerfile b/.gitpod.Dockerfile new file mode 100644 index 000000000..e365fb489 --- /dev/null +++ b/.gitpod.Dockerfile @@ -0,0 +1,2 @@ +FROM gitpod/workspace-full:2022-08-17-18-37-55 +RUN brew install buildpacks/tap/pack \ No newline at end of file diff --git a/.gitpod.yml b/.gitpod.yml index d46244e67..940733ac9 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -1,10 +1,11 @@ # This configuration file was automatically generated by Gitpod. # Please adjust to your needs (see https://www.gitpod.io/docs/config-gitpod-file) # and commit this file to your remote git repository to share the goodness with others. -image: gitpod/workspace-node:2022-06-20-19-54-55 -tasks: - - init: pnpm install && pnpm db:push && pnpm db:seed - command: pnpm dev +#image: +# file: .gitpod.Dockerfile +#tasks: +# - init: pnpm install && pnpm db:push && pnpm db:seed +# command: pnpm dev ports: - port: 3001 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..246e0dae5 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,94 @@ +# Citizen Code of Conduct + +## 1. Purpose + +A primary goal of Coolify is to be inclusive to the largest number of contributors, with the most varied and diverse backgrounds possible. As such, we are committed to providing a friendly, safe and welcoming environment for all, regardless of gender, sexual orientation, ability, ethnicity, socioeconomic status, and religion (or lack thereof). + +This code of conduct outlines our expectations for all those who participate in our community, as well as the consequences for unacceptable behavior. + +We invite all those who participate in Coolify to help us create safe and positive experiences for everyone. + +## 2. Open [Source/Culture/Tech] Citizenship + +A supplemental goal of this Code of Conduct is to increase open [source/culture/tech] citizenship by encouraging participants to recognize and strengthen the relationships between our actions and their effects on our community. + +Communities mirror the societies in which they exist and positive action is essential to counteract the many forms of inequality and abuses of power that exist in society. + +If you see someone who is making an extra effort to ensure our community is welcoming, friendly, and encourages all participants to contribute to the fullest extent, we want to know. + +## 3. Expected Behavior + +The following behaviors are expected and requested of all community members: + + * Participate in an authentic and active way. In doing so, you contribute to the health and longevity of this community. + * Exercise consideration and respect in your speech and actions. + * Attempt collaboration before conflict. + * Refrain from demeaning, discriminatory, or harassing behavior and speech. + * Be mindful of your surroundings and of your fellow participants. Alert community leaders if you notice a dangerous situation, someone in distress, or violations of this Code of Conduct, even if they seem inconsequential. + * Remember that community event venues may be shared with members of the public; please be respectful to all patrons of these locations. + +## 4. Unacceptable Behavior + +The following behaviors are considered harassment and are unacceptable within our community: + + * Violence, threats of violence or violent language directed against another person. + * Sexist, racist, homophobic, transphobic, ableist or otherwise discriminatory jokes and language. + * Posting or displaying sexually explicit or violent material. + * Posting or threatening to post other people's personally identifying information ("doxing"). + * Personal insults, particularly those related to gender, sexual orientation, race, religion, or disability. + * Inappropriate photography or recording. + * Inappropriate physical contact. You should have someone's consent before touching them. + * Unwelcome sexual attention. This includes, sexualized comments or jokes; inappropriate touching, groping, and unwelcomed sexual advances. + * Deliberate intimidation, stalking or following (online or in person). + * Advocating for, or encouraging, any of the above behavior. + * Sustained disruption of community events, including talks and presentations. + +## 5. Weapons Policy + +No weapons will be allowed at Coolify events, community spaces, or in other spaces covered by the scope of this Code of Conduct. Weapons include but are not limited to guns, explosives (including fireworks), and large knives such as those used for hunting or display, as well as any other item used for the purpose of causing injury or harm to others. Anyone seen in possession of one of these items will be asked to leave immediately, and will only be allowed to return without the weapon. Community members are further expected to comply with all state and local laws on this matter. + +## 6. Consequences of Unacceptable Behavior + +Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated. + +Anyone asked to stop unacceptable behavior is expected to comply immediately. + +If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event). + +## 7. Reporting Guidelines + +If you are subject to or witness unacceptable behavior, or have any other concerns, please notify a community organizer as soon as possible. hi@coollabs.io. + + + +Additionally, community organizers are available to help community members engage with local law enforcement or to otherwise help those experiencing unacceptable behavior feel safe. In the context of in-person events, organizers will also provide escorts as desired by the person experiencing distress. + +## 8. Addressing Grievances + +If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify coollabsio with a concise description of your grievance. Your grievance will be handled in accordance with our existing governing policies. + + + +## 9. Scope + +We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues--online and in-person--as well as in all one-on-one communications pertaining to community business. + +This code of conduct and its related procedures also applies to unacceptable behavior occurring outside the scope of community activities when such behavior has the potential to adversely affect the safety and well-being of community members. + +## 10. Contact info + +hi@coollabs.io + +## 11. License and attribution + +The Citizen Code of Conduct is distributed by [Stumptown Syndicate](http://stumptownsyndicate.org) under a [Creative Commons Attribution-ShareAlike license](http://creativecommons.org/licenses/by-sa/3.0/). + +Portions of text derived from the [Django Code of Conduct](https://www.djangoproject.com/conduct/) and the [Geek Feminism Anti-Harassment Policy](http://geekfeminism.wikia.com/wiki/Conference_anti-harassment/Policy). + +_Revision 2.3. Posted 6 March 2017._ + +_Revision 2.2. Posted 4 February 2016._ + +_Revision 2.1. Posted 23 June 2014._ + +_Revision 2.0, adopted by the [Stumptown Syndicate](http://stumptownsyndicate.org) board on 10 January 2013. Posted 17 March 2013._ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 99c5433bf..958b6512f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,6 @@ First of all, thank you for considering contributing to my project! It means a lot 💜. -Contribution guide is for v2, not applicable for v3 ## 🙋 Want to help? @@ -17,13 +16,17 @@ This is a little list of what you can do to help the project: ## 👋 Introduction -### Setup with github codespaces +### Setup with Github codespaces If you have github codespaces enabled then you can just create a codespace and run `pnpm dev` to run your the dev environment. All the required dependencies and packages has been configured for you already. +### Setup with Gitpod + +If you have a [Gitpod](https://gitpod.io), you can just create a workspace from this repository, run `pnpm install && pnpm db:push && pnpm db:seed` and then `pnpm dev`. All the required dependencies and packages has been configured for you already. + ### Setup locally in your machine -> 🔴 At the moment, Coolify **doesn't support Windows**. You must use Linux or MacOS. 💡 Although windows users can use github codespaces for development +> 🔴 At the moment, Coolify **doesn't support Windows**. You must use Linux or MacOS. Consider using Gitpod or Github Codespaces. #### Recommended Pull Request Guideline @@ -31,21 +34,38 @@ If you have github codespaces enabled then you can just create a codespace and r - Clone your fork repo to local - Create a new branch - Push to your fork repo -- Create a pull request: https://github.com/coollabsio/compare +- Create a pull request: https://github.com/coollabsio/coolify/compare - Write a proper description - Open the pull request to review against `next` branch --- -# How to start after you set up your local fork? +# 🧑‍💻 Developer contribution +## Technical skills required -Due to the lock file, this repository is best with [pnpm](https://pnpm.io). I recommend you try and use `pnpm` because it is cool and efficient! +- **Languages**: Node.js / Javascript / Typescript +- **Framework JS/TS**: [SvelteKit](https://kit.svelte.dev/) & [Fastify](https://www.fastify.io/) +- **Database ORM**: [Prisma.io](https://www.prisma.io/) +- **Docker Engine API** -You need to have [Docker Engine](https://docs.docker.com/engine/install/) installed locally. +--- -#### Steps for local setup +## How to start after you set up your local fork? -1. Copy `.env.template` to `.env` and set the `COOLIFY_APP_ID` environment variable to something cool. +### Prerequisites +1. Due to the lock file, this repository is best with [pnpm](https://pnpm.io). I recommend you try and use `pnpm` because it is cool and efficient! + +2. You need to have [Docker Engine](https://docs.docker.com/engine/install/) installed locally. +3. You need to have [Docker Compose Plugin](https://docs.docker.com/compose/install/compose-plugin/) installed locally. +4. You need to have [GIT LFS Support](https://git-lfs.github.com/) installed locally. + +Optional: + +4. To test Heroku buildpacks, you need [pack](https://github.com/buildpacks/pack) binary installed locally. + +### Steps for local setup + +1. Copy `apps/api/.env.template` to `apps/api/.env.template` and set the `COOLIFY_APP_ID` environment variable to something cool. 2. Install dependencies with `pnpm install`. 3. Need to create a local SQlite database with `pnpm db:push`. @@ -54,28 +74,17 @@ You need to have [Docker Engine](https://docs.docker.com/engine/install/) instal 4. Seed the database with base entities with `pnpm db:seed` 5. You can start coding after starting `pnpm dev`. -## 🧑‍💻 Developer contribution +--- -### Technical skills required - -- **Languages**: Node.js / Javascript / Typescript -- **Framework JS/TS**: Svelte / SvelteKit -- **Database ORM**: Prisma.io -- **Docker Engine** - -### Database migrations +## Database migrations During development, if you change the database layout, you need to run `pnpm db:push` to migrate the database and create types for Prisma. You also need to restart the development process. If the schema is finalized, you need to create a migration file with `pnpm db:migrate ` where `nameOfMigration` is given by you. Make it sense. :) -### Tricky parts - -- BullMQ, the queue system Coolify uses, cannot be hot reloaded. So if you change anything in the files related to it, you need to restart the development process. I'm actively looking for a different queue/scheduler library. I'm open to discussion! - --- -# How to add new services +## How to add new services You can add any open-source and self-hostable software (service/application) to Coolify if the following statements are true: @@ -95,14 +104,14 @@ There are 5 steps you should make on the backend side. > I will use [Umami](https://umami.is/) as an example service. -### Create Prisma / database schema for the new service. +### Create Prisma / Database schema for the new service. You only need to do this if you store passwords or any persistent configuration. Mostly it is required by all services, but there are some exceptions, like NocoDB. Update Prisma schema in [prisma/schema.prisma](prisma/schema.prisma). - Add new model with the new service name. -- Make a relationshup with `Service` model. +- Make a relationship with `Service` model. - In the `Service` model, the name of the new field should be with low-capital. - If the service needs a database, define a `publicPort` field to be able to make it's database public, example field name in case of PostgreSQL: `postgresqlPublicPort`. It should be a optional field. @@ -110,13 +119,13 @@ If you are finished with the Prisma schema, you should update the database schem > You must restart the running development environment to be able to use the new model -> If you use VSCode, you probably need to restart the `Typescript Language Server` to get the new types loaded in the running VSCode. +> If you use VSCode/TLS, you probably need to restart the `Typescript Language Server` to get the new types loaded in the running environment. ### Add supported versions Supported versions are hardcoded into Coolify (for now). -You need to update `supportedServiceTypesAndVersions` function at [src/lib/components/common.ts](src/lib/components/common.ts). Example JSON: +You need to update `supportedServiceTypesAndVersions` function at [apps/api/src/lib/services/supportedVersions.ts](apps/api/src/lib/services/supportedVersions.ts). Example JSON: ```js { @@ -139,12 +148,12 @@ You need to update `supportedServiceTypesAndVersions` function at [src/lib/compo } ``` -### Update global functions +### Add required functions/properties -1. Add the new service to the `include` variable in [src/lib/database/services.ts](src/lib/database/services.ts), so it will be included in all places in the database queries where it is required. +1. Add the new service to the `includeServices` variable in [apps/api/src/lib/services/common.ts](apps/api/src/lib/services/common.ts), so it will be included in all places in the database queries where it is required. ```js -const include: Prisma.ServiceInclude = { +const include: any = { destinationDocker: true, persistentStorage: true, serviceSecret: true, @@ -158,7 +167,7 @@ const include: Prisma.ServiceInclude = { }; ``` -2. Update the database update query with the new service type to `configureServiceType` function in [src/lib/database/services.ts](src/lib/database/services.ts). This function defines the automatically generated variables (passwords, users, etc.) and it's encryption process (if applicable). +2. Update the database update query with the new service type to `configureServiceType` function in [apps/api/src/lib/services/common.ts](apps/api/src/lib/services/common.ts). This function defines the automatically generated variables (passwords, users, etc.) and it's encryption process (if applicable). ```js [...] @@ -184,80 +193,46 @@ else if (type === 'umami') { } ``` -3. Add decryption process for configurations and passwords to `getService` function in [src/lib/database/services.ts](src/lib/database/services.ts) +3. Add field details to [apps/api/src/lib/services/serviceFields.ts](apps/api/src/lib/services/serviceFields.ts), so every component will know what to do with the values (decrypt/show it by default/readonly) ```js -if (body.umami?.postgresqlPassword) - body.umami.postgresqlPassword = decrypt(body.umami.postgresqlPassword); - -if (body.umami?.hashSalt) body.umami.hashSalt = decrypt(body.umami.hashSalt); +export const umami = [{ + name: 'postgresqlUser', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}] ``` -4. Add service deletion query to `removeService` function in [src/lib/database/services.ts](src/lib/database/services.ts) +4. Add service deletion query to `removeService` function in [apps/api/src/lib/services/common.ts](apps/api/src/lib/services/common.ts) -### Create API endpoints. +5. Add start process for the new service in [apps/api/src/lib/services/handlers.ts](apps/api/src/lib/services/handlers.ts) -You need to add a new folder under [src/routes/services/[id]](src/routes/services/[id]) with the low-capital name of the service. You need 3 default files in that folder. +> See startUmamiService() function as example. -#### `index.json.ts`: +6. Add the newly added start process to `startService` in [apps/api/src/routes/api/v1/services/handlers.ts](apps/api/src/routes/api/v1/services/handlers.ts) -It has a POST endpoint that updates the service details in Coolify's database, such as name, url, other configurations, like passwords. It should look something like this: - -```js -import { getUserDetails } from '$lib/common'; -import * as db from '$lib/database'; -import { ErrorHandler } from '$lib/database'; -import type { RequestHandler } from '@sveltejs/kit'; - -export const post: RequestHandler = async (event) => { - const { status, body } = await getUserDetails(event); - if (status === 401) return { status, body }; - - const { id } = event.params; - - let { name, fqdn } = await event.request.json(); - if (fqdn) fqdn = fqdn.toLowerCase(); - - try { - await db.updateService({ id, fqdn, name }); - return { status: 201 }; - } catch (error) { - return ErrorHandler(error); - } -}; -``` - -If it's necessary, you can create your own database update function, specifically for the new service. - -#### `start.json.ts` - -It has a POST endpoint that sets all the required secrets, persistent volumes, `docker-compose.yaml` file and sends a request to the specified docker engine. - -You could also define an `HTTP` or `TCP` proxy for every other port that should be proxied to your server. (See `startHttpProxy` and `startTcpProxy` functions in [src/lib/haproxy/index.ts](src/lib/haproxy/index.ts)) - -#### `stop.json.ts` - -It has a POST endpoint that stops the service and all dependent (TCP/HTTP proxies) containers. If publicPort is specified it also needs to cleanup it from the database. - -## Frontend - -1. You need to add a custom logo at [src/lib/components/svg/services/](src/lib/components/svg/services/) as a svelte component. +7. You need to add a custom logo at [apps/ui/src/lib/components/svg/services](apps/ui/src/lib/components/svg/services) as a svelte component and export it in [apps/ui/src/lib/components/svg/services/index.ts](apps/ui/src/lib/components/svg/services/index.ts) SVG is recommended, but you can use PNG as well. It should have the `isAbsolute` variable with the suitable CSS classes, primarily for sizing and positioning. -2. You need to include it the logo at +8. You need to include it the logo at: -- [src/routes/services/index.svelte](src/routes/services/index.svelte) with `isAbsolute` in two places, -- [src/lib/components/ServiceLinks.svelte](src/lib/components/ServiceLinks.svelte) with `isAbsolute` and a link to the docs/main site of the service -- [src/routes/services/[id]/configuration/type.svelte](src/routes/services/[id]/configuration/type.svelte) with `isAbsolute`. +- [apps/ui/src/lib/components/svg/services/ServiceIcons.svelte](apps/ui/src/lib/components/svg/services/ServiceIcons.svelte) with `isAbsolute`. +- [apps/ui/src/routes/services/[id]/_ServiceLinks.svelte](apps/ui/src/routes/services/[id]/_ServiceLinks.svelte) with the link to the docs/main site of the service -3. By default the URL and the name frontend forms are included in [src/routes/services/[id]/\_Services/\_Services.svelte](src/routes/services/[id]/_Services/_Services.svelte). +9. By default the URL and the name frontend forms are included in [apps/ui/src/routes/services/[id]/_Services/_Services.svelte](apps/ui/src/routes/services/[id]/_Services/_Services.svelte). - If you need to show more details on the frontend, such as users/passwords, you need to add Svelte component to [src/routes/services/[id]/\_Services](src/routes/services/[id]/_Services) with an underscore. For example, see other files in that folder. + If you need to show more details on the frontend, such as users/passwords, you need to add Svelte component to [apps/ui/src/routes/services/[id]/_Services](apps/ui/src/routes/services/[id]/_Services) with an underscore. + + > For example, see other [here](apps/ui/src/routes/services/[id]/_Services/_Umami.svelte). - You also need to add the new inputs to the `index.json.ts` file of the specific service, like for MinIO here: [src/routes/services/[id]/minio/index.json.ts](src/routes/services/[id]/minio/index.json.ts) -## 🌐 Translate the project +Good job! 👏 + + diff --git a/CONTRIBUTION_NEW.md b/CONTRIBUTION_NEW.md new file mode 100644 index 000000000..a9ed208ed --- /dev/null +++ b/CONTRIBUTION_NEW.md @@ -0,0 +1,108 @@ +--- +head: + - - meta + - name: description + content: Coolify - Databases + - - meta + - name: keywords + content: databases coollabs coolify + - - meta + - name: twitter:card + content: summary_large_image + - - meta + - name: twitter:site + content: '@andrasbacsai' + - - meta + - name: twitter:title + content: Coolify + - - meta + - name: twitter:description + content: An open-source & self-hostable Heroku / Netlify alternative. + - - meta + - name: twitter:image + content: https://cdn.coollabs.io/assets/coollabs/og-image-databases.png + - - meta + - property: og:type + content: website + - - meta + - property: og:url + content: https://coolify.io + - - meta + - property: og:title + content: Coolify + - - meta + - property: og:description + content: An open-source & self-hostable Heroku / Netlify alternative. + - - meta + - property: og:site_name + content: Coolify + - - meta + - property: og:image + content: https://cdn.coollabs.io/assets/coollabs/og-image-databases.png +--- +# Contribution + +First, thanks for considering to contribute to my project. It really means a lot! :) + +You can ask for guidance anytime on our Discord server in the #contribution channel. + +## Setup your development environment +### Github codespaces + +If you have github codespaces enabled then you can just create a codespace and run `pnpm dev` to run your the dev environment. All the required dependencies and packages has been configured for you already. + +### Gitpod + +If you have a [Gitpod](https://gitpod.io), you can just create a workspace from this repository, run `pnpm install && pnpm db:push && pnpm db:seed` and then `pnpm dev`. All the required dependencies and packages has been configured for you already. + +### Local Machine +> At the moment, Coolify `doesn't support Windows`. You must use `Linux` or `MacOS` or consider using Gitpod or Github Codespaces. + +- Due to the lock file, this repository is best with [pnpm](https://pnpm.io). I recommend you try and use `pnpm` because it is cool and efficient! + +- You need to have [Docker Engine](https://docs.docker.com/engine/install/) installed locally. +- You need to have [Docker Compose Plugin](https://docs.docker.com/compose/install/compose-plugin/) installed locally. +- You need to have [GIT LFS Support](https://git-lfs.github.com/) installed locally. + +Optional: +- To test Heroku buildpacks, you need [pack](https://github.com/buildpacks/pack) binary installed locally. + +### Inside a Docker container +`WIP` + +## Setup Coolify +- Copy `apps/api/.env.template` to `apps/api/.env.template` and set the `COOLIFY_APP_ID` environment variable to something cool. +- `pnpm install` to install dependencies. +- `pnpm db:push` to o create a local SQlite database. + + This will apply all migrations at `db/dev.db`. + +- `pnpm db:seed` seed the database. +- `pnpm dev` start coding. + +## Technical skills required + +- **Languages**: Node.js / Javascript / Typescript +- **Framework JS/TS**: [SvelteKit](https://kit.svelte.dev/) & [Fastify](https://www.fastify.io/) +- **Database ORM**: [Prisma.io](https://www.prisma.io/) +- **Docker Engine API** + +## Add a new service +### Which service is eligable to add to Coolify? +The following statements needs to be true: + +- Self-hostable +- Open-source +- Maintained (I do not want to add software full of bugs) + +### Create Prisma / Database schema for the new service. +All data that needs to be persist for a service should be saved to the database in `cleartext` or `encrypted`. + +very password/api key/passphrase needs to be encrypted. If you are not sure, whether it should be encrypted or not, just encrypt it. + +Update Prisma schema in [src/api/prisma/schema.prisma](https://github.com/coollabsio/coolify/blob/main/apps/api/prisma/schema.prisma). + +- Add new model with the new service name. +- Make a relationship with `Service` model. +- In the `Service` model, the name of the new field should be with low-capital. +- If the service needs a database, define a `publicPort` field to be able to make it's database public, example field name in case of PostgreSQL: `postgresqlPublicPort`. It should be a optional field. diff --git a/Dockerfile b/Dockerfile index 00c29b5f0..675fe5b5b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,38 +1,37 @@ -FROM node:18-alpine3.16 as build +ARG PNPM_VERSION=7.11.0 +ARG NPM_VERSION=8.19.1 + +FROM node:18-slim as build WORKDIR /app -RUN apk add --no-cache curl -RUN curl -sL https://unpkg.com/@pnpm/self-installer | node +RUN apt update && apt -y install curl +RUN npm --no-update-notifier --no-fund --global install pnpm@${PNPM_VERSION} COPY . . RUN pnpm install RUN pnpm build # Production build -FROM node:18-alpine3.16 +FROM node:18-slim WORKDIR /app ENV NODE_ENV production ARG TARGETPLATFORM -ENV PRISMA_QUERY_ENGINE_BINARY=/app/prisma-engines/query-engine \ - PRISMA_MIGRATION_ENGINE_BINARY=/app/prisma-engines/migration-engine \ - PRISMA_INTROSPECTION_ENGINE_BINARY=/app/prisma-engines/introspection-engine \ - PRISMA_FMT_BINARY=/app/prisma-engines/prisma-fmt \ - PRISMA_CLI_QUERY_ENGINE_TYPE=binary \ - PRISMA_CLIENT_ENGINE_TYPE=binary - -COPY --from=coollabsio/prisma-engine:3.15 /prisma-engines/query-engine /prisma-engines/migration-engine /prisma-engines/introspection-engine /prisma-engines/prisma-fmt /app/prisma-engines/ - -RUN apk add --no-cache git git-lfs openssh-client curl jq cmake sqlite openssl -RUN curl -sL https://unpkg.com/@pnpm/self-installer | node +RUN apt update && apt -y install --no-install-recommends ca-certificates git git-lfs openssh-client curl jq cmake sqlite3 openssl psmisc python3 +RUN apt-get clean autoclean && apt-get autoremove --yes && rm -rf /var/lib/{apt,dpkg,cache,log}/ +RUN npm --no-update-notifier --no-fund --global install pnpm@${PNPM_VERSION} +RUN npm install -g npm@${PNPM_VERSION} RUN mkdir -p ~/.docker/cli-plugins/ # https://download.docker.com/linux/static/stable/ RUN curl -SL https://cdn.coollabs.io/bin/$TARGETPLATFORM/docker-20.10.9 -o /usr/bin/docker # https://github.com/docker/compose/releases -RUN curl -SL https://cdn.coollabs.io/bin/$TARGETPLATFORM/docker-compose-linux-2.7.0 -o ~/.docker/cli-plugins/docker-compose +# Reverted to 2.6.1 because of this https://github.com/docker/compose/issues/9704. 2.9.0 still has a bug. +RUN curl -SL https://cdn.coollabs.io/bin/$TARGETPLATFORM/docker-compose-linux-2.6.1 -o ~/.docker/cli-plugins/docker-compose RUN chmod +x ~/.docker/cli-plugins/docker-compose /usr/bin/docker +RUN (curl -sSL "https://github.com/buildpacks/pack/releases/download/v0.27.0/pack-v0.27.0-linux.tgz" | tar -C /usr/local/bin/ --no-same-owner -xzv pack) + COPY --from=build /app/apps/api/build/ . COPY --from=build /app/apps/ui/build/ ./public COPY --from=build /app/apps/api/prisma/ ./prisma @@ -42,4 +41,5 @@ COPY --from=build /app/docker-compose.yaml . RUN pnpm install -p EXPOSE 3000 +ENV CHECKPOINT_DISABLE=1 CMD pnpm start \ No newline at end of file diff --git a/LICENSE b/LICENSE index 29ebfa545..86c87eba2 100644 --- a/LICENSE +++ b/LICENSE @@ -1,661 +1,201 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. \ No newline at end of file + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2022] [Andras Bacsai] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md index 40d7ac2dc..2c106d047 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,109 @@ # Coolify -An open-source & self-hostable Heroku / Netlify alternative -(ARM support is in beta). +An open-source & self-hostable Heroku / Netlify alternative. + +## Live Demo + +https://demo.coolify.io/ + +(If it is unresponsive, that means someone overloaded the server. 😄) + +## Feedback + +If you have a new service / build pack you would like to add, raise an idea [here](https://feedback.coolify.io/) to get feedback from the community! + +--- + +## How to install + +For more details goto the [docs](https://docs.coollabs.io/coolify/installation). + +Installation is automated with the following command: + +```bash +wget -q https://get.coollabs.io/coolify/install.sh -O install.sh; sudo bash ./install.sh +``` + +If you would like no questions during installation: + +```bash +wget -q https://get.coollabs.io/coolify/install.sh -O install.sh; sudo bash ./install.sh -f +``` + +--- + +## Features + +### Git Sources + +Self-hosted versions also! + + + + +### Destinations + +Deploy your resource to: + +- Local Docker Engine +- Remote Docker Engine + +### Applications + + + + + + + + + + + + + + + + + + +### Databases + + + + + + + + +### Services +- [Appwrite](https://appwrite.io) +- [WordPress](https://docs.coollabs.io/coolify/services/wordpress) +- [Ghost](https://ghost.org) +- [Plausible Analytics](https://docs.coollabs.io/coolify/services/plausible-analytics) +- [NocoDB](https://nocodb.com) +- [VSCode Server](https://github.com/cdr/code-server) +- [MinIO](https://min.io) +- [VaultWarden](https://github.com/dani-garcia/vaultwarden) +- [LanguageTool](https://languagetool.org) +- [n8n](https://n8n.io) +- [Uptime Kuma](https://github.com/louislam/uptime-kuma) +- [MeiliSearch](https://github.com/meilisearch/meilisearch) +- [Umami](https://github.com/mikecao/umami) +- [Fider](https://fider.io) +- [Hasura](https://hasura.io) +- [GlitchTip](https://glitchtip.com) + +## Migration from v1 + +A fresh installation is necessary. v2 and v3 are not compatible with v1. + +## Support + +- Twitter: [@andrasbacsai](https://twitter.com/andrasbacsai) +- Telegram: [@andrasbacsai](https://t.me/andrasbacsai) +- Email: [andras@coollabs.io](mailto:andras@coollabs.io) +- Discord: [Invitation](https://coollabs.io/discord) ## Financial Contributors @@ -24,127 +126,4 @@ Support this project with your organization. Your logo will show up here with a - - ---- - -## Live Demo - -https://demo.coolify.io/ - -(If it is unresponsive, that means someone overloaded the server. 😄) - -## Feedback - -If you have a new service / build pack you would like to add, raise an idea [here](https://feedback.coolify.io/) to get feedback from the community! - ---- - -## How to install - -Installation is automated with the following command: - -```bash -wget -q https://get.coollabs.io/coolify/install.sh -O install.sh; sudo bash ./install.sh -``` - -If you would like no questions during installation: - -```bash -wget -q https://get.coollabs.io/coolify/install.sh -O install.sh; sudo bash ./install.sh -f -``` - -For more details goto the [docs](https://docs.coollabs.io/coolify/installation). - ---- - -## Features - -### Git Sources - -You can use the following Git Sources to be auto-deployed to your Coolify instance! (Self-hosted versions are also supported.) - - - - -### Destinations - -You can deploy your applications to the following destinations: - -- Local Docker Engine -- Remote Docker Engine - -### Applications - -Predefined build packs to cover the basic needs to deploy applications. - -If you have an advanced use case, you can use the Docker build pack that allows you to deploy your application based on your custom Dockerfile. - - - - - - - - - - - - - - - - - -If you have a new build pack you would like to add, raise an idea [here](https://feedback.coolify.io/) to get feedback from the community! - -### Databases - -One-click database is ready to be used internally or shared over the internet: - - - - - - - - -If you have a new database you would like to add, raise an idea [here](https://feedback.coolify.io/) to get feedback from the community! - - -### Services - -You quickly need to host a self-hostable, open-source service? You can do it with a few clicks! -- [WordPress](https://docs.coollabs.io/coolify/services/wordpress) -- [Ghost](https://ghost.org) -- [Plausible Analytics](https://docs.coollabs.io/coolify/services/plausible-analytics) -- [NocoDB](https://nocodb.com) -- [VSCode Server](https://github.com/cdr/code-server) -- [MinIO](https://min.io) -- [VaultWarden](https://github.com/dani-garcia/vaultwarden) -- [LanguageTool](https://languagetool.org) -- [n8n](https://n8n.io) -- [Uptime Kuma](https://github.com/louislam/uptime-kuma) -- [MeiliSearch](https://github.com/meilisearch/meilisearch) -- [Umami](https://github.com/mikecao/umami) -- [Fider](https://fider.io) -- [Hasura](https://hasura.io) - - -If you have a new service you would like to add, raise an idea [here](https://feedback.coolify.io/) to get feedback from the community! - -## Migration from v1 - -A fresh installation is necessary. v2 and v3 are not compatible with v1. - -## Support - -- Twitter: [@andrasbacsai](https://twitter.com/andrasbacsai) -- Telegram: [@andrasbacsai](https://t.me/andrasbacsai) -- Email: [andras@coollabs.io](mailto:andras@coollabs.io) -- Discord: [Invitation](https://discord.gg/xhBCC7eGKw) - - -## License - -This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Please see the [LICENSE](/LICENSE) file in our repository for the full text. + diff --git a/TODO.md b/TODO.md deleted file mode 100644 index be0d3d48f..000000000 --- a/TODO.md +++ /dev/null @@ -1,6 +0,0 @@ -- RDE Application DNS check not working -- Check DNS configurations for app/service/coolify with RDE and local engines - - -# Low -- Create previews model in Coolify DB \ No newline at end of file diff --git a/apps/api/.env.example b/apps/api/.env.example new file mode 100644 index 000000000..800c40929 --- /dev/null +++ b/apps/api/.env.example @@ -0,0 +1,10 @@ +COOLIFY_APP_ID=local-dev +# 32 bits long secret key +COOLIFY_SECRET_KEY=12341234123412341234123412341234 +COOLIFY_DATABASE_URL=file:../db/dev.db +COOLIFY_SENTRY_DSN= + +COOLIFY_IS_ON=docker +COOLIFY_WHITE_LABELED=false +COOLIFY_WHITE_LABELED_ICON= +COOLIFY_AUTO_UPDATE= \ No newline at end of file diff --git a/apps/api/package.json b/apps/api/package.json index 32a012685..f436482c8 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -1,7 +1,7 @@ { - "name": "coolify-api", + "name": "api", "description": "Coolify's Fastify API", - "license": "AGPL-3.0", + "license": "Apache-2.0", "scripts": { "db:push": "prisma db push && prisma generate", "db:seed": "prisma db seed", @@ -15,55 +15,57 @@ }, "dependencies": { "@breejs/ts-worker": "2.0.0", - "@fastify/autoload": "5.1.0", - "@fastify/cookie": "7.3.1", - "@fastify/cors": "8.0.0", - "@fastify/env": "4.0.0", - "@fastify/jwt": "6.3.1", - "@fastify/static": "6.4.1", + "@fastify/autoload": "5.3.1", + "@fastify/cookie": "8.1.0", + "@fastify/cors": "8.1.0", + "@fastify/env": "4.1.0", + "@fastify/jwt": "6.3.2", + "@fastify/static": "6.5.0", "@iarna/toml": "2.2.5", - "@prisma/client": "3.15.2", + "@ladjs/graceful": "3.0.2", + "@prisma/client": "4.3.1", "axios": "0.27.2", "bcryptjs": "2.4.3", - "bree": "9.1.1", + "bree": "9.1.2", "cabin": "9.1.2", - "compare-versions": "4.1.3", + "compare-versions": "5.0.1", "cuid": "2.1.8", - "dayjs": "1.11.4", - "dockerode": "3.3.2", + "dayjs": "1.11.5", + "dockerode": "3.3.4", "dotenv-extended": "2.9.0", - "fastify": "4.3.0", - "fastify-plugin": "4.0.0", + "execa": "6.1.0", + "fastify": "4.5.3", + "fastify-plugin": "4.2.1", "generate-password": "1.7.0", - "get-port": "6.1.2", - "got": "12.2.0", + "got": "12.4.1", "is-ip": "5.0.0", "is-port-reachable": "4.0.0", "js-yaml": "4.1.0", "jsonwebtoken": "8.5.1", "node-forge": "1.3.1", "node-os-utils": "1.3.7", - "p-queue": "7.2.0", + "p-all": "4.0.0", + "p-throttle": "5.0.0", "public-ip": "6.0.1", "ssh-config": "4.1.6", "strip-ansi": "7.0.1", "unique-names-generator": "4.7.1" }, "devDependencies": { - "@types/node": "18.6.1", + "@types/node": "18.7.15", "@types/node-os-utils": "1.3.0", - "@typescript-eslint/eslint-plugin": "5.31.0", - "@typescript-eslint/parser": "5.31.0", - "esbuild": "0.14.50", - "eslint": "8.20.0", + "@typescript-eslint/eslint-plugin": "5.36.2", + "@typescript-eslint/parser": "5.36.2", + "esbuild": "0.15.7", + "eslint": "8.23.0", "eslint-config-prettier": "8.5.0", "eslint-plugin-prettier": "4.2.1", "nodemon": "2.0.19", "prettier": "2.7.1", - "prisma": "3.15.2", + "prisma": "4.3.1", "rimraf": "3.0.2", - "tsconfig-paths": "4.0.0", - "typescript": "4.7.4" + "tsconfig-paths": "4.1.0", + "typescript": "4.8.2" }, "prisma": { "seed": "node prisma/seed.js" diff --git a/apps/api/prisma/migrations/20220806090621_fqdn_not_unique_anymore/migration.sql b/apps/api/prisma/migrations/20220806090621_fqdn_not_unique_anymore/migration.sql new file mode 100644 index 000000000..f1eab666b --- /dev/null +++ b/apps/api/prisma/migrations/20220806090621_fqdn_not_unique_anymore/migration.sql @@ -0,0 +1,2 @@ +-- DropIndex +DROP INDEX "Application_fqdn_key"; diff --git a/apps/api/prisma/migrations/20220806102340_rde_ssh_local_port/migration.sql b/apps/api/prisma/migrations/20220806102340_rde_ssh_local_port/migration.sql new file mode 100644 index 000000000..ae4c39846 --- /dev/null +++ b/apps/api/prisma/migrations/20220806102340_rde_ssh_local_port/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "DestinationDocker" ADD COLUMN "sshLocalPort" INTEGER; diff --git a/apps/api/prisma/migrations/20220815092230_glitchtip/migration.sql b/apps/api/prisma/migrations/20220815092230_glitchtip/migration.sql new file mode 100644 index 000000000..dba98ab82 --- /dev/null +++ b/apps/api/prisma/migrations/20220815092230_glitchtip/migration.sql @@ -0,0 +1,30 @@ +-- CreateTable +CREATE TABLE "GlitchTip" ( + "id" TEXT NOT NULL PRIMARY KEY, + "postgresqlUser" TEXT NOT NULL, + "postgresqlPassword" TEXT NOT NULL, + "postgresqlDatabase" TEXT NOT NULL, + "postgresqlPublicPort" INTEGER, + "secretKeyBase" TEXT, + "defaultEmail" TEXT NOT NULL, + "defaultUsername" TEXT NOT NULL, + "defaultPassword" TEXT NOT NULL, + "defaultEmailFrom" TEXT NOT NULL DEFAULT 'glitchtip@domain.tdl', + "emailSmtpHost" TEXT DEFAULT 'domain.tdl', + "emailSmtpPort" INTEGER DEFAULT 25, + "emailSmtpUser" TEXT, + "emailSmtpPassword" TEXT, + "emailSmtpUseTls" BOOLEAN DEFAULT false, + "emailSmtpUseSsl" BOOLEAN DEFAULT false, + "emailBackend" TEXT, + "mailgunApiKey" TEXT, + "sendgridApiKey" TEXT, + "enableOpenUserRegistration" BOOLEAN NOT NULL DEFAULT true, + "serviceId" TEXT NOT NULL, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" DATETIME NOT NULL, + CONSTRAINT "GlitchTip_serviceId_fkey" FOREIGN KEY ("serviceId") REFERENCES "Service" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- CreateIndex +CREATE UNIQUE INDEX "GlitchTip_serviceId_key" ON "GlitchTip"("serviceId"); diff --git a/apps/api/prisma/migrations/20220815133844_appwrite/migration.sql b/apps/api/prisma/migrations/20220815133844_appwrite/migration.sql new file mode 100644 index 000000000..ec61dc434 --- /dev/null +++ b/apps/api/prisma/migrations/20220815133844_appwrite/migration.sql @@ -0,0 +1,22 @@ +-- CreateTable +CREATE TABLE "Appwrite" ( + "id" TEXT NOT NULL PRIMARY KEY, + "serviceId" TEXT NOT NULL, + "opensslKeyV1" TEXT NOT NULL, + "executorSecret" TEXT NOT NULL, + "redisPassword" TEXT NOT NULL, + "mariadbHost" TEXT, + "mariadbPort" INTEGER NOT NULL DEFAULT 3306, + "mariadbUser" TEXT NOT NULL, + "mariadbPassword" TEXT NOT NULL, + "mariadbRootUser" TEXT NOT NULL, + "mariadbRootUserPassword" TEXT NOT NULL, + "mariadbDatabase" TEXT NOT NULL, + "mariadbPublicPort" INTEGER, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" DATETIME NOT NULL, + CONSTRAINT "Appwrite_serviceId_fkey" FOREIGN KEY ("serviceId") REFERENCES "Service" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- CreateIndex +CREATE UNIQUE INDEX "Appwrite_serviceId_key" ON "Appwrite"("serviceId"); diff --git a/apps/api/prisma/migrations/20220816133447_bot_deployments/migration.sql b/apps/api/prisma/migrations/20220816133447_bot_deployments/migration.sql new file mode 100644 index 000000000..3d6d92d0e --- /dev/null +++ b/apps/api/prisma/migrations/20220816133447_bot_deployments/migration.sql @@ -0,0 +1,20 @@ +-- RedefineTables +PRAGMA foreign_keys=OFF; +CREATE TABLE "new_ApplicationSettings" ( + "id" TEXT NOT NULL PRIMARY KEY, + "applicationId" TEXT NOT NULL, + "dualCerts" BOOLEAN NOT NULL DEFAULT false, + "debug" BOOLEAN NOT NULL DEFAULT false, + "previews" BOOLEAN NOT NULL DEFAULT false, + "autodeploy" BOOLEAN NOT NULL DEFAULT true, + "isBot" BOOLEAN NOT NULL DEFAULT false, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" DATETIME NOT NULL, + CONSTRAINT "ApplicationSettings_applicationId_fkey" FOREIGN KEY ("applicationId") REFERENCES "Application" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); +INSERT INTO "new_ApplicationSettings" ("applicationId", "autodeploy", "createdAt", "debug", "dualCerts", "id", "previews", "updatedAt") SELECT "applicationId", "autodeploy", "createdAt", "debug", "dualCerts", "id", "previews", "updatedAt" FROM "ApplicationSettings"; +DROP TABLE "ApplicationSettings"; +ALTER TABLE "new_ApplicationSettings" RENAME TO "ApplicationSettings"; +CREATE UNIQUE INDEX "ApplicationSettings_applicationId_key" ON "ApplicationSettings"("applicationId"); +PRAGMA foreign_key_check; +PRAGMA foreign_keys=ON; diff --git a/apps/api/prisma/migrations/20220817082342_custom_dns_servers/migration.sql b/apps/api/prisma/migrations/20220817082342_custom_dns_servers/migration.sql new file mode 100644 index 000000000..03588b549 --- /dev/null +++ b/apps/api/prisma/migrations/20220817082342_custom_dns_servers/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Setting" ADD COLUMN "DNSServers" TEXT; diff --git a/apps/api/prisma/migrations/20220818093615_public_repositories/migration.sql b/apps/api/prisma/migrations/20220818093615_public_repositories/migration.sql new file mode 100644 index 000000000..7f08c29fd --- /dev/null +++ b/apps/api/prisma/migrations/20220818093615_public_repositories/migration.sql @@ -0,0 +1,42 @@ +-- RedefineTables +PRAGMA foreign_keys=OFF; +CREATE TABLE "new_GitSource" ( + "id" TEXT NOT NULL PRIMARY KEY, + "name" TEXT NOT NULL, + "forPublic" BOOLEAN NOT NULL DEFAULT false, + "type" TEXT, + "apiUrl" TEXT, + "htmlUrl" TEXT, + "customPort" INTEGER NOT NULL DEFAULT 22, + "organization" TEXT, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" DATETIME NOT NULL, + "githubAppId" TEXT, + "gitlabAppId" TEXT, + CONSTRAINT "GitSource_githubAppId_fkey" FOREIGN KEY ("githubAppId") REFERENCES "GithubApp" ("id") ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT "GitSource_gitlabAppId_fkey" FOREIGN KEY ("gitlabAppId") REFERENCES "GitlabApp" ("id") ON DELETE SET NULL ON UPDATE CASCADE +); +INSERT INTO "new_GitSource" ("apiUrl", "createdAt", "customPort", "githubAppId", "gitlabAppId", "htmlUrl", "id", "name", "organization", "type", "updatedAt") SELECT "apiUrl", "createdAt", "customPort", "githubAppId", "gitlabAppId", "htmlUrl", "id", "name", "organization", "type", "updatedAt" FROM "GitSource"; +DROP TABLE "GitSource"; +ALTER TABLE "new_GitSource" RENAME TO "GitSource"; +CREATE UNIQUE INDEX "GitSource_githubAppId_key" ON "GitSource"("githubAppId"); +CREATE UNIQUE INDEX "GitSource_gitlabAppId_key" ON "GitSource"("gitlabAppId"); +CREATE TABLE "new_ApplicationSettings" ( + "id" TEXT NOT NULL PRIMARY KEY, + "applicationId" TEXT NOT NULL, + "dualCerts" BOOLEAN NOT NULL DEFAULT false, + "debug" BOOLEAN NOT NULL DEFAULT false, + "previews" BOOLEAN NOT NULL DEFAULT false, + "autodeploy" BOOLEAN NOT NULL DEFAULT true, + "isBot" BOOLEAN NOT NULL DEFAULT false, + "isPublicRepository" BOOLEAN NOT NULL DEFAULT false, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" DATETIME NOT NULL, + CONSTRAINT "ApplicationSettings_applicationId_fkey" FOREIGN KEY ("applicationId") REFERENCES "Application" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); +INSERT INTO "new_ApplicationSettings" ("applicationId", "autodeploy", "createdAt", "debug", "dualCerts", "id", "isBot", "previews", "updatedAt") SELECT "applicationId", "autodeploy", "createdAt", "debug", "dualCerts", "id", "isBot", "previews", "updatedAt" FROM "ApplicationSettings"; +DROP TABLE "ApplicationSettings"; +ALTER TABLE "new_ApplicationSettings" RENAME TO "ApplicationSettings"; +CREATE UNIQUE INDEX "ApplicationSettings_applicationId_key" ON "ApplicationSettings"("applicationId"); +PRAGMA foreign_key_check; +PRAGMA foreign_keys=ON; diff --git a/apps/api/prisma/migrations/20220823070532_service_searxng/migration.sql b/apps/api/prisma/migrations/20220823070532_service_searxng/migration.sql new file mode 100644 index 000000000..81ecc81c8 --- /dev/null +++ b/apps/api/prisma/migrations/20220823070532_service_searxng/migration.sql @@ -0,0 +1,13 @@ +-- CreateTable +CREATE TABLE "Searxng" ( + "id" TEXT NOT NULL PRIMARY KEY, + "secretKey" TEXT NOT NULL, + "redisPassword" TEXT NOT NULL, + "serviceId" TEXT NOT NULL, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" DATETIME NOT NULL, + CONSTRAINT "Searxng_serviceId_fkey" FOREIGN KEY ("serviceId") REFERENCES "Service" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- CreateIndex +CREATE UNIQUE INDEX "Searxng_serviceId_key" ON "Searxng"("serviceId"); diff --git a/apps/api/prisma/migrations/20220825064811_concurrent_build_settings/migration.sql b/apps/api/prisma/migrations/20220825064811_concurrent_build_settings/migration.sql new file mode 100644 index 000000000..1535c2bf7 --- /dev/null +++ b/apps/api/prisma/migrations/20220825064811_concurrent_build_settings/migration.sql @@ -0,0 +1,29 @@ +-- RedefineTables +PRAGMA foreign_keys=OFF; +CREATE TABLE "new_Setting" ( + "id" TEXT NOT NULL PRIMARY KEY, + "fqdn" TEXT, + "isRegistrationEnabled" BOOLEAN NOT NULL DEFAULT false, + "dualCerts" BOOLEAN NOT NULL DEFAULT false, + "minPort" INTEGER NOT NULL DEFAULT 9000, + "maxPort" INTEGER NOT NULL DEFAULT 9100, + "proxyPassword" TEXT NOT NULL, + "proxyUser" TEXT NOT NULL, + "proxyHash" TEXT, + "isAutoUpdateEnabled" BOOLEAN NOT NULL DEFAULT false, + "isDNSCheckEnabled" BOOLEAN NOT NULL DEFAULT true, + "DNSServers" TEXT, + "isTraefikUsed" BOOLEAN NOT NULL DEFAULT true, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" DATETIME NOT NULL, + "ipv4" TEXT, + "ipv6" TEXT, + "arch" TEXT, + "concurrentBuilds" INTEGER NOT NULL DEFAULT 1 +); +INSERT INTO "new_Setting" ("DNSServers", "arch", "createdAt", "dualCerts", "fqdn", "id", "ipv4", "ipv6", "isAutoUpdateEnabled", "isDNSCheckEnabled", "isRegistrationEnabled", "isTraefikUsed", "maxPort", "minPort", "proxyHash", "proxyPassword", "proxyUser", "updatedAt") SELECT "DNSServers", "arch", "createdAt", "dualCerts", "fqdn", "id", "ipv4", "ipv6", "isAutoUpdateEnabled", "isDNSCheckEnabled", "isRegistrationEnabled", "isTraefikUsed", "maxPort", "minPort", "proxyHash", "proxyPassword", "proxyUser", "updatedAt" FROM "Setting"; +DROP TABLE "Setting"; +ALTER TABLE "new_Setting" RENAME TO "Setting"; +CREATE UNIQUE INDEX "Setting_fqdn_key" ON "Setting"("fqdn"); +PRAGMA foreign_key_check; +PRAGMA foreign_keys=ON; diff --git a/apps/api/prisma/migrations/20220825072007_build_queue_improvements/migration.sql b/apps/api/prisma/migrations/20220825072007_build_queue_improvements/migration.sql new file mode 100644 index 000000000..78c51fc15 --- /dev/null +++ b/apps/api/prisma/migrations/20220825072007_build_queue_improvements/migration.sql @@ -0,0 +1,24 @@ +-- RedefineTables +PRAGMA foreign_keys=OFF; +CREATE TABLE "new_Build" ( + "id" TEXT NOT NULL PRIMARY KEY, + "type" TEXT NOT NULL, + "applicationId" TEXT, + "destinationDockerId" TEXT, + "gitSourceId" TEXT, + "githubAppId" TEXT, + "gitlabAppId" TEXT, + "commit" TEXT, + "pullmergeRequestId" TEXT, + "forceRebuild" BOOLEAN NOT NULL DEFAULT false, + "sourceBranch" TEXT, + "branch" TEXT, + "status" TEXT DEFAULT 'queued', + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" DATETIME NOT NULL +); +INSERT INTO "new_Build" ("applicationId", "branch", "commit", "createdAt", "destinationDockerId", "gitSourceId", "githubAppId", "gitlabAppId", "id", "status", "type", "updatedAt") SELECT "applicationId", "branch", "commit", "createdAt", "destinationDockerId", "gitSourceId", "githubAppId", "gitlabAppId", "id", "status", "type", "updatedAt" FROM "Build"; +DROP TABLE "Build"; +ALTER TABLE "new_Build" RENAME TO "Build"; +PRAGMA foreign_key_check; +PRAGMA foreign_keys=ON; diff --git a/apps/api/prisma/migrations/20220831095714_service_weblate/migration.sql b/apps/api/prisma/migrations/20220831095714_service_weblate/migration.sql new file mode 100644 index 000000000..c985b4ae2 --- /dev/null +++ b/apps/api/prisma/migrations/20220831095714_service_weblate/migration.sql @@ -0,0 +1,18 @@ +-- CreateTable +CREATE TABLE "Weblate" ( + "id" TEXT NOT NULL PRIMARY KEY, + "adminPassword" TEXT NOT NULL, + "postgresqlHost" TEXT NOT NULL, + "postgresqlPort" INTEGER NOT NULL, + "postgresqlUser" TEXT NOT NULL, + "postgresqlPassword" TEXT NOT NULL, + "postgresqlDatabase" TEXT NOT NULL, + "postgresqlPublicPort" INTEGER, + "serviceId" TEXT NOT NULL, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" DATETIME NOT NULL, + CONSTRAINT "Weblate_serviceId_fkey" FOREIGN KEY ("serviceId") REFERENCES "Service" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- CreateIndex +CREATE UNIQUE INDEX "Weblate_serviceId_key" ON "Weblate"("serviceId"); diff --git a/apps/api/prisma/migrations/20220902115640_service_taiga/migration.sql b/apps/api/prisma/migrations/20220902115640_service_taiga/migration.sql new file mode 100644 index 000000000..3035dd8ef --- /dev/null +++ b/apps/api/prisma/migrations/20220902115640_service_taiga/migration.sql @@ -0,0 +1,23 @@ +-- CreateTable +CREATE TABLE "Taiga" ( + "id" TEXT NOT NULL PRIMARY KEY, + "secretKey" TEXT NOT NULL, + "erlangSecret" TEXT NOT NULL, + "djangoAdminPassword" TEXT NOT NULL, + "djangoAdminUser" TEXT NOT NULL, + "rabbitMQUser" TEXT NOT NULL, + "rabbitMQPassword" TEXT NOT NULL, + "postgresqlHost" TEXT NOT NULL, + "postgresqlPort" INTEGER NOT NULL, + "postgresqlUser" TEXT NOT NULL, + "postgresqlPassword" TEXT NOT NULL, + "postgresqlDatabase" TEXT NOT NULL, + "postgresqlPublicPort" INTEGER, + "serviceId" TEXT NOT NULL, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" DATETIME NOT NULL, + CONSTRAINT "Taiga_serviceId_fkey" FOREIGN KEY ("serviceId") REFERENCES "Service" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- CreateIndex +CREATE UNIQUE INDEX "Taiga_serviceId_key" ON "Taiga"("serviceId"); diff --git a/apps/api/prisma/migrations/20220905062318_database_branching/migration.sql b/apps/api/prisma/migrations/20220905062318_database_branching/migration.sql new file mode 100644 index 000000000..d828a4c66 --- /dev/null +++ b/apps/api/prisma/migrations/20220905062318_database_branching/migration.sql @@ -0,0 +1,22 @@ +-- RedefineTables +PRAGMA foreign_keys=OFF; +CREATE TABLE "new_ApplicationSettings" ( + "id" TEXT NOT NULL PRIMARY KEY, + "applicationId" TEXT NOT NULL, + "dualCerts" BOOLEAN NOT NULL DEFAULT false, + "debug" BOOLEAN NOT NULL DEFAULT false, + "previews" BOOLEAN NOT NULL DEFAULT false, + "autodeploy" BOOLEAN NOT NULL DEFAULT true, + "isBot" BOOLEAN NOT NULL DEFAULT false, + "isPublicRepository" BOOLEAN NOT NULL DEFAULT false, + "isDBBranching" BOOLEAN NOT NULL DEFAULT false, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" DATETIME NOT NULL, + CONSTRAINT "ApplicationSettings_applicationId_fkey" FOREIGN KEY ("applicationId") REFERENCES "Application" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); +INSERT INTO "new_ApplicationSettings" ("applicationId", "autodeploy", "createdAt", "debug", "dualCerts", "id", "isBot", "isPublicRepository", "previews", "updatedAt") SELECT "applicationId", "autodeploy", "createdAt", "debug", "dualCerts", "id", "isBot", "isPublicRepository", "previews", "updatedAt" FROM "ApplicationSettings"; +DROP TABLE "ApplicationSettings"; +ALTER TABLE "new_ApplicationSettings" RENAME TO "ApplicationSettings"; +CREATE UNIQUE INDEX "ApplicationSettings_applicationId_key" ON "ApplicationSettings"("applicationId"); +PRAGMA foreign_key_check; +PRAGMA foreign_keys=ON; diff --git a/apps/api/prisma/migrations/20220905113241_prisma_migration/migration.sql b/apps/api/prisma/migrations/20220905113241_prisma_migration/migration.sql new file mode 100644 index 000000000..324bcfff0 --- /dev/null +++ b/apps/api/prisma/migrations/20220905113241_prisma_migration/migration.sql @@ -0,0 +1,20 @@ +/* + Warnings: + + - You are about to alter the column `time` on the `BuildLog` table. The data in that column could be lost. The data in that column will be cast from `Int` to `BigInt`. + +*/ +-- RedefineTables +PRAGMA foreign_keys=OFF; +CREATE TABLE "new_BuildLog" ( + "id" TEXT NOT NULL PRIMARY KEY, + "applicationId" TEXT, + "buildId" TEXT NOT NULL, + "line" TEXT NOT NULL, + "time" BIGINT NOT NULL +); +INSERT INTO "new_BuildLog" ("applicationId", "buildId", "id", "line", "time") SELECT "applicationId", "buildId", "id", "line", "time" FROM "BuildLog"; +DROP TABLE "BuildLog"; +ALTER TABLE "new_BuildLog" RENAME TO "BuildLog"; +PRAGMA foreign_key_check; +PRAGMA foreign_keys=ON; diff --git a/apps/api/prisma/migrations/20220905115321_application_connected_database/migration.sql b/apps/api/prisma/migrations/20220905115321_application_connected_database/migration.sql new file mode 100644 index 000000000..576c23bdf --- /dev/null +++ b/apps/api/prisma/migrations/20220905115321_application_connected_database/migration.sql @@ -0,0 +1,20 @@ +-- CreateTable +CREATE TABLE "ApplicationConnectedDatabase" ( + "id" TEXT NOT NULL PRIMARY KEY, + "applicationId" TEXT NOT NULL, + "databaseId" TEXT, + "hostedDatabaseType" TEXT, + "hostedDatabaseHost" TEXT, + "hostedDatabasePort" INTEGER, + "hostedDatabaseName" TEXT, + "hostedDatabaseUser" TEXT, + "hostedDatabasePassword" TEXT, + "hostedDatabaseDBName" TEXT, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" DATETIME NOT NULL, + CONSTRAINT "ApplicationConnectedDatabase_databaseId_fkey" FOREIGN KEY ("databaseId") REFERENCES "Database" ("id") ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT "ApplicationConnectedDatabase_applicationId_fkey" FOREIGN KEY ("applicationId") REFERENCES "Application" ("id") ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- CreateIndex +CREATE UNIQUE INDEX "ApplicationConnectedDatabase_applicationId_key" ON "ApplicationConnectedDatabase"("applicationId"); diff --git a/apps/api/prisma/migrations/20220906120112_enable_api_debug_logging/migration.sql b/apps/api/prisma/migrations/20220906120112_enable_api_debug_logging/migration.sql new file mode 100644 index 000000000..05fb3e285 --- /dev/null +++ b/apps/api/prisma/migrations/20220906120112_enable_api_debug_logging/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Setting" ADD COLUMN "isAPIDebuggingEnabled" BOOLEAN DEFAULT false; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 3b68829e3..681293b53 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -1,6 +1,6 @@ generator client { provider = "prisma-client-js" - binaryTargets = ["native", "linux-musl"] + binaryTargets = ["native"] } datasource db { @@ -11,6 +11,7 @@ datasource db { model Setting { id String @id @default(cuid()) fqdn String? @unique + isAPIDebuggingEnabled Boolean? @default(false) isRegistrationEnabled Boolean @default(false) dualCerts Boolean @default(false) minPort Int @default(9000) @@ -20,12 +21,14 @@ model Setting { proxyHash String? isAutoUpdateEnabled Boolean @default(false) isDNSCheckEnabled Boolean @default(true) + DNSServers String? isTraefikUsed Boolean @default(true) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt ipv4 String? ipv6 String? arch String? + concurrentBuilds Int @default(1) } model User { @@ -82,7 +85,7 @@ model TeamInvitation { model Application { id String @id @default(cuid()) name String - fqdn String? @unique + fqdn String? repository String? configHash String? branch String? @@ -115,18 +118,39 @@ model Application { settings ApplicationSettings? secrets Secret[] teams Team[] + connectedDatabase ApplicationConnectedDatabase? +} + +model ApplicationConnectedDatabase { + id String @id @default(cuid()) + applicationId String @unique + databaseId String? + hostedDatabaseType String? + hostedDatabaseHost String? + hostedDatabasePort Int? + hostedDatabaseName String? + hostedDatabaseUser String? + hostedDatabasePassword String? + hostedDatabaseDBName String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + database Database? @relation(fields: [databaseId], references: [id]) + application Application @relation(fields: [applicationId], references: [id]) } model ApplicationSettings { - id String @id @default(cuid()) - applicationId String @unique - dualCerts Boolean @default(false) - debug Boolean @default(false) - previews Boolean @default(false) - autodeploy Boolean @default(true) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - application Application @relation(fields: [applicationId], references: [id]) + id String @id @default(cuid()) + applicationId String @unique + dualCerts Boolean @default(false) + debug Boolean @default(false) + previews Boolean @default(false) + autodeploy Boolean @default(true) + isBot Boolean @default(false) + isPublicRepository Boolean @default(false) + isDBBranching Boolean @default(false) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + application Application @relation(fields: [applicationId], references: [id]) } model ApplicationPersistentStorage { @@ -182,7 +206,7 @@ model BuildLog { applicationId String? buildId String line String - time Int + time BigInt } model Build { @@ -194,6 +218,9 @@ model Build { githubAppId String? gitlabAppId String? commit String? + pullmergeRequestId String? + forceRebuild Boolean @default(false) + sourceBranch String? branch String? status String? @default("queued") createdAt DateTime @default(now()) @@ -215,6 +242,7 @@ model DestinationDocker { updatedAt DateTime @updatedAt sshKeyId String? sshKey SshKey? @relation(fields: [sshKeyId], references: [id]) + sshLocalPort Int? application Application[] database Database[] service Service[] @@ -235,6 +263,7 @@ model SshKey { model GitSource { id String @id @default(cuid()) name String + forPublic Boolean @default(false) type String? apiUrl String? htmlUrl String? @@ -282,22 +311,23 @@ model GitlabApp { } model Database { - id String @id @default(cuid()) - name String - publicPort Int? - defaultDatabase String? - type String? - version String? - dbUser String? - dbUserPassword String? - rootUser String? - rootUserPassword String? - destinationDockerId String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - destinationDocker DestinationDocker? @relation(fields: [destinationDockerId], references: [id]) - settings DatabaseSettings? - teams Team[] + id String @id @default(cuid()) + name String + publicPort Int? + defaultDatabase String? + type String? + version String? + dbUser String? + dbUserPassword String? + rootUser String? + rootUserPassword String? + destinationDockerId String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + destinationDocker DestinationDocker? @relation(fields: [destinationDockerId], references: [id]) + settings DatabaseSettings? + teams Team[] + applicationConnectedDatabase ApplicationConnectedDatabase[] } model DatabaseSettings { @@ -322,19 +352,25 @@ model Service { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt destinationDocker DestinationDocker? @relation(fields: [destinationDockerId], references: [id]) - fider Fider? - ghost Ghost? - hasura Hasura? - meiliSearch MeiliSearch? - minio Minio? - moodle Moodle? - plausibleAnalytics PlausibleAnalytics? persistentStorage ServicePersistentStorage[] serviceSecret ServiceSecret[] - umami Umami? - vscodeserver Vscodeserver? - wordpress Wordpress? teams Team[] + + fider Fider? + ghost Ghost? + glitchTip GlitchTip? + hasura Hasura? + meiliSearch MeiliSearch? + minio Minio? + moodle Moodle? + plausibleAnalytics PlausibleAnalytics? + umami Umami? + vscodeserver Vscodeserver? + wordpress Wordpress? + appwrite Appwrite? + searxng Searxng? + weblate Weblate? + taiga Taiga? } model PlausibleAnalytics { @@ -490,3 +526,94 @@ model Moodle { updatedAt DateTime @updatedAt service Service @relation(fields: [serviceId], references: [id]) } + +model Appwrite { + id String @id @default(cuid()) + serviceId String @unique + opensslKeyV1 String + executorSecret String + redisPassword String + mariadbHost String? + mariadbPort Int @default(3306) + mariadbUser String + mariadbPassword String + mariadbRootUser String + mariadbRootUserPassword String + mariadbDatabase String + mariadbPublicPort Int? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + service Service @relation(fields: [serviceId], references: [id]) +} + +model GlitchTip { + id String @id @default(cuid()) + postgresqlUser String + postgresqlPassword String + postgresqlDatabase String + postgresqlPublicPort Int? + secretKeyBase String? + defaultEmail String + defaultUsername String + defaultPassword String + defaultEmailFrom String @default("glitchtip@domain.tdl") + emailSmtpHost String? @default("domain.tdl") + emailSmtpPort Int? @default(25) + emailSmtpUser String? + emailSmtpPassword String? + emailSmtpUseTls Boolean? @default(false) + emailSmtpUseSsl Boolean? @default(false) + emailBackend String? + mailgunApiKey String? + sendgridApiKey String? + enableOpenUserRegistration Boolean @default(true) + serviceId String @unique + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + service Service @relation(fields: [serviceId], references: [id]) +} + +model Searxng { + id String @id @default(cuid()) + secretKey String + redisPassword String + serviceId String @unique + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + service Service @relation(fields: [serviceId], references: [id]) +} + +model Weblate { + id String @id @default(cuid()) + adminPassword String + postgresqlHost String + postgresqlPort Int + postgresqlUser String + postgresqlPassword String + postgresqlDatabase String + postgresqlPublicPort Int? + serviceId String @unique + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + service Service @relation(fields: [serviceId], references: [id]) +} + +model Taiga { + id String @id @default(cuid()) + secretKey String + erlangSecret String + djangoAdminPassword String + djangoAdminUser String + rabbitMQUser String + rabbitMQPassword String + postgresqlHost String + postgresqlPort Int + postgresqlUser String + postgresqlPassword String + postgresqlDatabase String + postgresqlPublicPort Int? + serviceId String @unique + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + service Service @relation(fields: [serviceId], references: [id]) +} diff --git a/apps/api/prisma/seed.js b/apps/api/prisma/seed.js index 96b55b105..eeb41b253 100644 --- a/apps/api/prisma/seed.js +++ b/apps/api/prisma/seed.js @@ -17,7 +17,6 @@ const algorithm = 'aes-256-ctr'; async function main() { // Enable registration for the first user - // Set initial HAProxy password const settingsFound = await prisma.setting.findFirst({}); if (!settingsFound) { await prisma.setting.create({ @@ -25,7 +24,8 @@ async function main() { isRegistrationEnabled: true, proxyPassword: encrypt(generatePassword()), proxyUser: cuid(), - arch: process.arch + arch: process.arch, + DNSServers: '1.1.1.1,8.8.8.8' } }); } else { @@ -66,6 +66,34 @@ async function main() { } }); } + const github = await prisma.gitSource.findFirst({ + where: { htmlUrl: 'https://github.com', forPublic: true } + }); + const gitlab = await prisma.gitSource.findFirst({ + where: { htmlUrl: 'https://gitlab.com', forPublic: true } + }); + if (!github) { + await prisma.gitSource.create({ + data: { + apiUrl: 'https://api.github.com', + htmlUrl: 'https://github.com', + forPublic: true, + name: 'Github Public', + type: 'github' + } + }); + } + if (!gitlab) { + await prisma.gitSource.create({ + data: { + apiUrl: 'https://gitlab.com/api/v4', + htmlUrl: 'https://gitlab.com', + forPublic: true, + name: 'Gitlab Public', + type: 'gitlab' + } + }); + } } main() .catch((e) => { diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 60f83a50f..902596459 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -5,9 +5,10 @@ import env from '@fastify/env'; import cookie from '@fastify/cookie'; import path, { join } from 'path'; import autoLoad from '@fastify/autoload'; -import { asyncExecShell, isDev, listSettings, prisma } from './lib/common'; +import { asyncExecShell, createRemoteEngineConfiguration, getDomain, isDev, listSettings, prisma, version } from './lib/common'; import { scheduler } from './lib/scheduler'; - +import { compareVersions } from 'compare-versions'; +import Graceful from '@ladjs/graceful' declare module 'fastify' { interface FastifyInstance { config: { @@ -16,123 +17,152 @@ declare module 'fastify' { COOLIFY_DATABASE_URL: string, COOLIFY_SENTRY_DSN: string, COOLIFY_IS_ON: string, - COOLIFY_WHITE_LABELED: boolean, + COOLIFY_WHITE_LABELED: string, COOLIFY_WHITE_LABELED_ICON: string | null, - COOLIFY_AUTO_UPDATE: boolean, + COOLIFY_AUTO_UPDATE: string, }; } } const port = isDev ? 3001 : 3000; const host = '0.0.0.0'; -const fastify = Fastify({ - logger: false, - trustProxy: true -}); -const schema = { - type: 'object', - required: ['COOLIFY_SECRET_KEY', 'COOLIFY_DATABASE_URL', 'COOLIFY_IS_ON'], - properties: { - COOLIFY_APP_ID: { - type: 'string', - }, - COOLIFY_SECRET_KEY: { - type: 'string', - }, - COOLIFY_DATABASE_URL: { - type: 'string', - default: 'file:../db/dev.db' - }, - COOLIFY_SENTRY_DSN: { - type: 'string', - default: null - }, - COOLIFY_IS_ON: { - type: 'string', - default: 'docker' - }, - COOLIFY_WHITE_LABELED: { - type: 'boolean', - default: false - }, - COOLIFY_WHITE_LABELED_ICON: { - type: 'string', - default: null - }, - COOLIFY_AUTO_UPDATE: { - type: 'boolean', - default: false - }, - - } -}; - -const options = { - schema, - dotenv: true -}; -fastify.register(env, options); -if (!isDev) { - fastify.register(serve, { - root: path.join(__dirname, './public'), - preCompressed: true +prisma.setting.findFirst().then(async (settings) => { + const fastify = Fastify({ + logger: settings?.isAPIDebuggingEnabled || false, + trustProxy: true }); - fastify.setNotFoundHandler(async function (request, reply) { - if (request.raw.url && request.raw.url.startsWith('/api')) { - return reply.status(404).send({ - success: false - }); + const schema = { + type: 'object', + required: ['COOLIFY_SECRET_KEY', 'COOLIFY_DATABASE_URL', 'COOLIFY_IS_ON'], + properties: { + COOLIFY_APP_ID: { + type: 'string', + }, + COOLIFY_SECRET_KEY: { + type: 'string', + }, + COOLIFY_DATABASE_URL: { + type: 'string', + default: 'file:../db/dev.db' + }, + COOLIFY_SENTRY_DSN: { + type: 'string', + default: null + }, + COOLIFY_IS_ON: { + type: 'string', + default: 'docker' + }, + COOLIFY_WHITE_LABELED: { + type: 'string', + default: 'false' + }, + COOLIFY_WHITE_LABELED_ICON: { + type: 'string', + default: null + }, + COOLIFY_AUTO_UPDATE: { + type: 'string', + default: 'false' + }, + } - return reply.status(200).sendFile('index.html'); - }); -} -fastify.register(autoLoad, { - dir: join(__dirname, 'plugins') -}); -fastify.register(autoLoad, { - dir: join(__dirname, 'routes') -}); + }; -fastify.register(cookie) -fastify.register(cors); -fastify.listen({ port, host }, async (err: any, address: any) => { - if (err) { - console.error(err); - process.exit(1); - } - console.log(`Coolify's API is listening on ${host}:${port}`); - await initServer(); - await scheduler.start('deployApplication'); - await scheduler.start('cleanupStorage'); - await scheduler.start('checkProxies'); - - // Check if no build is running - - // Check for update - setInterval(async () => { - const { isAutoUpdateEnabled } = await prisma.setting.findFirst(); - if (isAutoUpdateEnabled) { - if (scheduler.workers.has('deployApplication')) { - scheduler.workers.get('deployApplication').postMessage("status:autoUpdater"); + const options = { + schema, + dotenv: true + }; + fastify.register(env, options); + if (!isDev) { + fastify.register(serve, { + root: path.join(__dirname, './public'), + preCompressed: true + }); + fastify.setNotFoundHandler(async function (request, reply) { + if (request.raw.url && request.raw.url.startsWith('/api')) { + return reply.status(404).send({ + success: false + }); } - } - }, 60000 * 15) - - // Cleanup storage - setInterval(async () => { - if (scheduler.workers.has('deployApplication')) { - scheduler.workers.get('deployApplication').postMessage("status:cleanupStorage"); - } - }, 60000 * 10) - - scheduler.on('worker deleted', async (name) => { - if (name === 'autoUpdater' || name === 'cleanupStorage') { - if (!scheduler.workers.has('deployApplication')) await scheduler.start('deployApplication'); - } + return reply.status(200).sendFile('index.html'); + }); + } + fastify.register(autoLoad, { + dir: join(__dirname, 'plugins') }); - await getArch(); - await getIPAddress(); -}); + fastify.register(autoLoad, { + dir: join(__dirname, 'routes') + }); + + fastify.register(cookie) + fastify.register(cors); + fastify.addHook('onRequest', async (request, reply) => { + let allowedList = ['coolify:3000']; + const { ipv4, ipv6, fqdn } = await prisma.setting.findFirst({}) + + ipv4 && allowedList.push(`${ipv4}:3000`); + ipv6 && allowedList.push(ipv6); + fqdn && allowedList.push(getDomain(fqdn)); + isDev && allowedList.push('localhost:3000') && allowedList.push('localhost:3001') && allowedList.push('host.docker.internal:3001'); + const remotes = await prisma.destinationDocker.findMany({ where: { remoteEngine: true, remoteVerified: true } }) + if (remotes.length > 0) { + remotes.forEach(remote => { + allowedList.push(`${remote.remoteIpAddress}:3000`); + }) + } + if (!allowedList.includes(request.headers.host)) { + // console.log('not allowed', request.headers.host) + } + }) + fastify.listen({ port, host }, async (err: any, address: any) => { + if (err) { + console.error(err); + process.exit(1); + } + console.log(`Coolify's API is listening on ${host}:${port}`); + await initServer(); + + const graceful = new Graceful({ brees: [scheduler] }); + graceful.listen(); + + setInterval(async () => { + if (!scheduler.workers.has('deployApplication')) { + scheduler.run('deployApplication'); + } + if (!scheduler.workers.has('infrastructure')) { + scheduler.run('infrastructure'); + } + }, 2000) + + // autoUpdater + setInterval(async () => { + scheduler.workers.has('infrastructure') && scheduler.workers.get('infrastructure').postMessage("action:autoUpdater") + }, isDev ? 5000 : 60000 * 15) + + // cleanupStorage + setInterval(async () => { + scheduler.workers.has('infrastructure') && scheduler.workers.get('infrastructure').postMessage("action:cleanupStorage") + }, isDev ? 6000 : 60000 * 10) + + // checkProxies + setInterval(async () => { + scheduler.workers.has('infrastructure') && scheduler.workers.get('infrastructure').postMessage("action:checkProxies") + }, 10000) + + // cleanupPrismaEngines + // setInterval(async () => { + // scheduler.workers.has('infrastructure') && scheduler.workers.get('infrastructure').postMessage("action:cleanupPrismaEngines") + // }, 60000) + + await Promise.all([ + getArch(), + getIPAddress(), + configureRemoteDockers(), + ]) + }); +}) + async function getIPAddress() { const { publicIpv4, publicIpv6 } = await import('public-ip') try { @@ -153,6 +183,12 @@ async function initServer() { try { await asyncExecShell(`docker network create --attachable coolify`); } catch (error) { } + try { + const isOlder = compareVersions('3.8.1', version); + if (isOlder === 1) { + await prisma.build.updateMany({ where: { status: { in: ['running', 'queued'] } }, data: { status: 'failed' } }); + } + } catch (error) { } } async function getArch() { try { @@ -163,4 +199,15 @@ async function getArch() { } catch (error) { } } - +async function configureRemoteDockers() { + try { + const remoteDocker = await prisma.destinationDocker.findMany({ + where: { remoteVerified: true, remoteEngine: true } + }); + if (remoteDocker.length > 0) { + for (const docker of remoteDocker) { + await createRemoteEngineConfiguration(docker.id) + } + } + } catch (error) { } +} diff --git a/apps/api/src/jobs/autoUpdater.ts b/apps/api/src/jobs/autoUpdater.ts deleted file mode 100644 index 566ffea29..000000000 --- a/apps/api/src/jobs/autoUpdater.ts +++ /dev/null @@ -1,43 +0,0 @@ -import axios from 'axios'; -import compareVersions from 'compare-versions'; -import { parentPort } from 'node:worker_threads'; -import { asyncExecShell, asyncSleep, isDev, prisma, version } from '../lib/common'; - -(async () => { - if (parentPort) { - try { - const currentVersion = version; - const { data: versions } = await axios - .get( - `https://get.coollabs.io/versions.json` - , { - params: { - appId: process.env['COOLIFY_APP_ID'] || undefined, - version: currentVersion - } - }) - const latestVersion = versions['coolify'].main.version; - const isUpdateAvailable = compareVersions(latestVersion, currentVersion); - if (isUpdateAvailable === 1) { - const activeCount = 0 - if (activeCount === 0) { - if (!isDev) { - console.log(`Updating Coolify to ${latestVersion}.`); - await asyncExecShell(`docker pull coollabsio/coolify:${latestVersion}`); - await asyncExecShell(`env | grep COOLIFY > .env`); - await asyncExecShell( - `docker run --rm -tid --env-file .env -v /var/run/docker.sock:/var/run/docker.sock -v coolify-db coollabsio/coolify:${latestVersion} /bin/sh -c "env | grep COOLIFY > .env && echo 'TAG=${latestVersion}' >> .env && docker stop -t 0 coolify && docker rm coolify && docker compose up -d --force-recreate"` - ); - } else { - console.log('Updating (not really in dev mode).'); - } - } - } - } catch (error) { - console.log(error); - } finally { - await prisma.$disconnect(); - } - - } else process.exit(0); -})(); diff --git a/apps/api/src/jobs/checkProxies.ts b/apps/api/src/jobs/checkProxies.ts deleted file mode 100644 index 761554061..000000000 --- a/apps/api/src/jobs/checkProxies.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { parentPort } from 'node:worker_threads'; -import { prisma, startTraefikTCPProxy, generateDatabaseConfiguration, startTraefikProxy, executeDockerCmd } from '../lib/common'; -import { checkContainer } from '../lib/docker'; - -(async () => { - if (parentPort) { - // Coolify Proxy local - const engine = '/var/run/docker.sock'; - const localDocker = await prisma.destinationDocker.findFirst({ - where: { engine, network: 'coolify' } - }); - if (localDocker && localDocker.isCoolifyProxyUsed) { - // Remove HAProxy - const found = await checkContainer({ dockerId: localDocker.id, container: 'coolify-haproxy' }); - if (found) { - await executeDockerCmd({ - dockerId: localDocker.id, - command: `docker stop -t 0 coolify-haproxy && docker rm coolify-haproxy` - }) - } - await startTraefikProxy(localDocker.id); - - } - - // TCP Proxies - const databasesWithPublicPort = await prisma.database.findMany({ - where: { publicPort: { not: null } }, - include: { settings: true, destinationDocker: true } - }); - for (const database of databasesWithPublicPort) { - const { destinationDockerId, destinationDocker, publicPort, id } = database; - if (destinationDockerId && destinationDocker.isCoolifyProxyUsed) { - const { privatePort } = generateDatabaseConfiguration(database); - // Remove HAProxy - const found = await checkContainer({ - dockerId: localDocker.id, container: `haproxy-for-${publicPort}` - }); - if (found) { - await executeDockerCmd({ - dockerId: localDocker.id, - command: `docker stop -t 0 haproxy-for-${publicPort} && docker rm haproxy-for-${publicPort}` - }) - } - await startTraefikTCPProxy(destinationDocker, id, publicPort, privatePort); - - } - } - const wordpressWithFtp = await prisma.wordpress.findMany({ - where: { ftpPublicPort: { not: null } }, - include: { service: { include: { destinationDocker: true } } } - }); - for (const ftp of wordpressWithFtp) { - const { service, ftpPublicPort } = ftp; - const { destinationDockerId, destinationDocker, id } = service; - if (destinationDockerId && destinationDocker.isCoolifyProxyUsed) { - // Remove HAProxy - const found = await checkContainer({ dockerId: localDocker.id, container: `haproxy-for-${ftpPublicPort}` }); - if (found) { - await executeDockerCmd({ - dockerId: localDocker.id, - command: `docker stop -t 0 haproxy -for-${ftpPublicPort} && docker rm haproxy-for-${ftpPublicPort}` - }) - } - await startTraefikTCPProxy(destinationDocker, id, ftpPublicPort, 22, 'wordpressftp'); - } - } - - // HTTP Proxies - const minioInstances = await prisma.minio.findMany({ - where: { publicPort: { not: null } }, - include: { service: { include: { destinationDocker: true } } } - }); - for (const minio of minioInstances) { - const { service, publicPort } = minio; - const { destinationDockerId, destinationDocker, id } = service; - if (destinationDockerId && destinationDocker.isCoolifyProxyUsed) { - // Remove HAProxy - const found = await checkContainer({ dockerId: localDocker.id, container: `${id}-${publicPort}` }); - if (found) { - await executeDockerCmd({ - dockerId: localDocker.id, - command: `docker stop -t 0 ${id}-${publicPort} && docker rm ${id}-${publicPort} ` - }) - } - await startTraefikTCPProxy(destinationDocker, id, publicPort, 9000); - } - } - await prisma.$disconnect(); - } else process.exit(0); -})(); diff --git a/apps/api/src/jobs/cleanupStorage.ts b/apps/api/src/jobs/cleanupStorage.ts deleted file mode 100644 index 97683ac2d..000000000 --- a/apps/api/src/jobs/cleanupStorage.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { parentPort } from 'node:worker_threads'; -import { asyncExecShell, cleanupDockerStorage, executeDockerCmd, isDev, prisma, version } from '../lib/common'; - -(async () => { - if (parentPort) { - const destinationDockers = await prisma.destinationDocker.findMany(); - let enginesDone = new Set() - for (const destination of destinationDockers) { - if (enginesDone.has(destination.engine) || enginesDone.has(destination.remoteIpAddress)) return - if (destination.engine) enginesDone.add(destination.engine) - if (destination.remoteIpAddress) enginesDone.add(destination.remoteIpAddress) - - let lowDiskSpace = false; - try { - let stdout = null - if (!isDev) { - const output = await executeDockerCmd({ dockerId: destination.id, command: `CONTAINER=$(docker ps -lq | head -1) && docker exec $CONTAINER sh -c 'df -kPT /'` }) - stdout = output.stdout; - } else { - const output = await asyncExecShell( - `df -kPT /` - ); - stdout = output.stdout; - } - let lines = stdout.trim().split('\n'); - let header = lines[0]; - let regex = - /^Filesystem\s+|Type\s+|1024-blocks|\s+Used|\s+Available|\s+Capacity|\s+Mounted on\s*$/g; - const boundaries = []; - let match; - - while ((match = regex.exec(header))) { - boundaries.push(match[0].length); - } - - boundaries[boundaries.length - 1] = -1; - const data = lines.slice(1).map((line) => { - const cl = boundaries.map((boundary) => { - const column = boundary > 0 ? line.slice(0, boundary) : line; - line = line.slice(boundary); - return column.trim(); - }); - return { - capacity: Number.parseInt(cl[5], 10) / 100 - }; - }); - if (data.length > 0) { - const { capacity } = data[0]; - if (capacity > 0.8) { - lowDiskSpace = true; - } - } - } catch (error) { - console.log(error); - } - await cleanupDockerStorage(destination.id, lowDiskSpace, false) - } - await prisma.$disconnect(); - } else process.exit(0); -})(); diff --git a/apps/api/src/jobs/deployApplication.ts b/apps/api/src/jobs/deployApplication.ts index e31ccf149..945883bb2 100644 --- a/apps/api/src/jobs/deployApplication.ts +++ b/apps/api/src/jobs/deployApplication.ts @@ -4,154 +4,92 @@ import fs from 'fs/promises'; import yaml from 'js-yaml'; import { copyBaseConfigurationFiles, makeLabelForStandaloneApplication, saveBuildLog, setDefaultConfiguration } from '../lib/buildPacks/common'; -import { createDirectories, decrypt, executeDockerCmd, getDomain, prisma } from '../lib/common'; +import { createDirectories, decrypt, defaultComposeConfiguration, executeDockerCmd, getDomain, prisma, decryptApplication } from '../lib/common'; import * as importers from '../lib/importers'; import * as buildpacks from '../lib/buildPacks'; (async () => { if (parentPort) { - const concurrency = 1 - const PQueue = await import('p-queue'); - const queue = new PQueue.default({ concurrency }); parentPort.on('message', async (message) => { - if (parentPort) { - if (message === 'error') throw new Error('oops'); - if (message === 'cancel') { - parentPort.postMessage('cancelled'); - return; - } - if (message === 'status:autoUpdater') { - parentPort.postMessage({ size: queue.size, pending: queue.pending, caller: 'autoUpdater' }); - return; - } - if (message === 'status:cleanupStorage') { - parentPort.postMessage({ size: queue.size, pending: queue.pending, caller: 'cleanupStorage' }); - return; - } + if (message === 'error') throw new Error('oops'); + if (message === 'cancel') { + parentPort.postMessage('cancelled'); + await prisma.$disconnect() + process.exit(0); + } + }); + const pThrottle = await import('p-throttle') + const throttle = pThrottle.default({ + limit: 1, + interval: 2000 + }); - await queue.add(async () => { - const { - id: applicationId, - repository, - name, - destinationDocker, - destinationDockerId, - gitSource, - build_id: buildId, - configHash, - fqdn, - projectId, - secrets, - phpModules, - type, - pullmergeRequestId = null, - sourceBranch = null, - settings, - persistentStorage, - pythonWSGI, - pythonModule, - pythonVariable, - denoOptions, - exposePort, - baseImage, - baseBuildImage, - deploymentType, - } = message - let { - branch, - buildPack, - port, - installCommand, - buildCommand, - startCommand, - baseDirectory, - publishDirectory, - dockerFileLocation, - denoMainFile - } = message - try { - const { debug } = settings; - if (concurrency === 1) { - await prisma.build.updateMany({ - where: { - status: { in: ['queued', 'running'] }, - id: { not: buildId }, - applicationId, - createdAt: { lt: new Date(new Date().getTime() - 10 * 1000) } - }, - data: { status: 'failed' } - }); - } - let imageId = applicationId; - let domain = getDomain(fqdn); - const volumes = - persistentStorage?.map((storage) => { - return `${applicationId}${storage.path.replace(/\//gi, '-')}:${buildPack !== 'docker' ? '/app' : '' - }${storage.path}`; - }) || []; - // Previews, we need to get the source branch and set subdomain - if (pullmergeRequestId) { - branch = sourceBranch; - domain = `${pullmergeRequestId}.${domain}`; - imageId = `${applicationId}-${pullmergeRequestId}`; - } - let deployNeeded = true; - let destinationType; - - if (destinationDockerId) { - destinationType = 'docker'; - } - if (destinationType === 'docker') { - await prisma.build.update({ where: { id: buildId }, data: { status: 'running' } }); - const { workdir, repodir } = await createDirectories({ repository, buildId }); - const configuration = await setDefaultConfiguration(message); - - buildPack = configuration.buildPack; - port = configuration.port; - installCommand = configuration.installCommand; - startCommand = configuration.startCommand; - buildCommand = configuration.buildCommand; - publishDirectory = configuration.publishDirectory; - baseDirectory = configuration.baseDirectory; - dockerFileLocation = configuration.dockerFileLocation; - denoMainFile = configuration.denoMainFile; - const commit = await importers[gitSource.type]({ - applicationId, - debug, - workdir, - repodir, - githubAppId: gitSource.githubApp?.id, - gitlabAppId: gitSource.gitlabApp?.id, - customPort: gitSource.customPort, - repository, - branch, - buildId, - apiUrl: gitSource.apiUrl, - htmlUrl: gitSource.htmlUrl, - projectId, - deployKeyId: gitSource.gitlabApp?.deployKeyId || null, - privateSshKey: decrypt(gitSource.gitlabApp?.privateSshKey) || null - }); - if (!commit) { - throw new Error('No commit found?'); - } - let tag = commit.slice(0, 7); - if (pullmergeRequestId) { - tag = `${commit.slice(0, 7)}-${pullmergeRequestId}`; - } + const th = throttle(async () => { + try { + const queuedBuilds = await prisma.build.findMany({ where: { status: { in: ['queued', 'running'] } }, orderBy: { createdAt: 'asc' } }); + const { concurrentBuilds } = await prisma.setting.findFirst({}) + if (queuedBuilds.length > 0) { + parentPort.postMessage({ deploying: true }); + const concurrency = concurrentBuilds; + const pAll = await import('p-all'); + const actions = [] + for (const queueBuild of queuedBuilds) { + actions.push(async () => { + let application = await prisma.application.findUnique({ where: { id: queueBuild.applicationId }, include: { destinationDocker: true, gitSource: { include: { githubApp: true, gitlabApp: true } }, persistentStorage: true, secrets: true, settings: true, teams: true } }) + let { id: buildId, type, sourceBranch = null, pullmergeRequestId = null, forceRebuild } = queueBuild + application = decryptApplication(application) try { - await prisma.build.update({ where: { id: buildId }, data: { commit } }); - } catch (err) { - console.log(err); - } - if (!pullmergeRequestId) { + if (queueBuild.status === 'running') { + await saveBuildLog({ line: 'Building halted, restarting...', buildId, applicationId: application.id }); + } + const { + id: applicationId, + repository, + name, + destinationDocker, + destinationDockerId, + gitSource, + configHash, + fqdn, + projectId, + secrets, + phpModules, + settings, + persistentStorage, + pythonWSGI, + pythonModule, + pythonVariable, + denoOptions, + exposePort, + baseImage, + baseBuildImage, + deploymentType, + } = application + let { + branch, + buildPack, + port, + installCommand, + buildCommand, + startCommand, + baseDirectory, + publishDirectory, + dockerFileLocation, + denoMainFile + } = application const currentHash = crypto - //@ts-ignore .createHash('sha256') .update( JSON.stringify({ + pythonWSGI, + pythonModule, + pythonVariable, + deploymentType, + denoOptions, + baseImage, + baseBuildImage, buildPack, port, exposePort, @@ -165,42 +103,178 @@ import * as buildpacks from '../lib/buildPacks'; }) ) .digest('hex'); - - if (configHash !== currentHash) { - await prisma.application.update({ - where: { id: applicationId }, - data: { configHash: currentHash } + const { debug } = settings; + if (concurrency === 1) { + await prisma.build.updateMany({ + where: { + status: { in: ['queued', 'running'] }, + id: { not: buildId }, + applicationId, + createdAt: { lt: new Date(new Date().getTime() - 10 * 1000) } + }, + data: { status: 'failed' } }); - deployNeeded = true; - if (configHash) { - await saveBuildLog({ line: 'Configuration changed.', buildId, applicationId }); - } - } else { - deployNeeded = false; } - } else { - deployNeeded = true; - } + let imageId = applicationId; + let domain = getDomain(fqdn); + const volumes = + persistentStorage?.map((storage) => { + return `${applicationId}${storage.path.replace(/\//gi, '-')}:${buildPack !== 'docker' ? '/app' : '' + }${storage.path}`; + }) || []; + // Previews, we need to get the source branch and set subdomain + if (pullmergeRequestId) { + branch = sourceBranch; + domain = `${pullmergeRequestId}.${domain}`; + imageId = `${applicationId}-${pullmergeRequestId}`; + } - let imageFound = false; - try { - await executeDockerCmd({ - dockerId: destinationDocker.id, - command: `docker image inspect ${applicationId}:${tag}` - }) - imageFound = true; - } catch (error) { - // - } - // if (!imageFound || deployNeeded) { - if (true) { - await copyBaseConfigurationFiles(buildPack, workdir, buildId, applicationId, baseImage); - if (buildpacks[buildPack]) - await buildpacks[buildPack]({ - dockerId: destinationDocker.id, - buildId, + let deployNeeded = true; + let destinationType; + + if (destinationDockerId) { + destinationType = 'docker'; + } + if (destinationType === 'docker') { + await prisma.build.update({ where: { id: buildId }, data: { status: 'running' } }); + const { workdir, repodir } = await createDirectories({ repository, buildId }); + const configuration = await setDefaultConfiguration(application); + + buildPack = configuration.buildPack; + port = configuration.port; + installCommand = configuration.installCommand; + startCommand = configuration.startCommand; + buildCommand = configuration.buildCommand; + publishDirectory = configuration.publishDirectory; + baseDirectory = configuration.baseDirectory; + dockerFileLocation = configuration.dockerFileLocation; + denoMainFile = configuration.denoMainFile; + const commit = await importers[gitSource.type]({ applicationId, - domain, + debug, + workdir, + repodir, + githubAppId: gitSource.githubApp?.id, + gitlabAppId: gitSource.gitlabApp?.id, + customPort: gitSource.customPort, + repository, + branch, + buildId, + apiUrl: gitSource.apiUrl, + htmlUrl: gitSource.htmlUrl, + projectId, + deployKeyId: gitSource.gitlabApp?.deployKeyId || null, + privateSshKey: decrypt(gitSource.gitlabApp?.privateSshKey) || null, + forPublic: gitSource.forPublic + }); + if (!commit) { + throw new Error('No commit found?'); + } + let tag = commit.slice(0, 7); + if (pullmergeRequestId) { + tag = `${commit.slice(0, 7)}-${pullmergeRequestId}`; + } + + try { + await prisma.build.update({ where: { id: buildId }, data: { commit } }); + } catch (err) { } + + if (!pullmergeRequestId) { + if (configHash !== currentHash) { + deployNeeded = true; + if (configHash) { + await saveBuildLog({ line: 'Configuration changed.', buildId, applicationId }); + } + } else { + deployNeeded = false; + } + } else { + deployNeeded = true; + } + + let imageFound = false; + try { + await executeDockerCmd({ + dockerId: destinationDocker.id, + command: `docker image inspect ${applicationId}:${tag}` + }) + imageFound = true; + } catch (error) { + // + } + await copyBaseConfigurationFiles(buildPack, workdir, buildId, applicationId, baseImage); + + if (forceRebuild) deployNeeded = true + if (!imageFound || deployNeeded) { + // if (true) { + if (buildpacks[buildPack]) + await buildpacks[buildPack]({ + dockerId: destinationDocker.id, + buildId, + applicationId, + domain, + name, + type, + pullmergeRequestId, + buildPack, + repository, + branch, + projectId, + publishDirectory, + debug, + commit, + tag, + workdir, + port: exposePort ? `${exposePort}:${port}` : port, + installCommand, + buildCommand, + startCommand, + baseDirectory, + secrets, + phpModules, + pythonWSGI, + pythonModule, + pythonVariable, + dockerFileLocation, + denoMainFile, + denoOptions, + baseImage, + baseBuildImage, + deploymentType + }); + else { + await saveBuildLog({ line: `Build pack ${buildPack} not found`, buildId, applicationId }); + throw new Error(`Build pack ${buildPack} not found.`); + } + } else { + await saveBuildLog({ line: 'Build image already available - no rebuild required.', buildId, applicationId }); + } + try { + await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker stop -t 0 ${imageId}` }) + await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker rm ${imageId}` }) + } catch (error) { + // + } + const envs = [ + `PORT=${port}` + ]; + if (secrets.length > 0) { + secrets.forEach((secret) => { + if (pullmergeRequestId) { + if (secret.isPRMRSecret) { + envs.push(`${secret.name}=${secret.value}`); + } + } else { + if (!secret.isPRMRSecret) { + envs.push(`${secret.name}=${secret.value}`); + } + } + }); + } + await fs.writeFile(`${workdir}/.env`, envs.join('\n')); + const labels = makeLabelForStandaloneApplication({ + applicationId, + fqdn, name, type, pullmergeRequestId, @@ -208,150 +282,90 @@ import * as buildpacks from '../lib/buildPacks'; repository, branch, projectId, - publishDirectory, - debug, - commit, - tag, - workdir, port: exposePort ? `${exposePort}:${port}` : port, + commit, installCommand, buildCommand, startCommand, baseDirectory, - secrets, - phpModules, - pythonWSGI, - pythonModule, - pythonVariable, - dockerFileLocation, - denoMainFile, - denoOptions, - baseImage, - baseBuildImage, - deploymentType + publishDirectory }); - else { - await saveBuildLog({ line: `Build pack ${buildPack} not found`, buildId, applicationId }); - throw new Error(`Build pack ${buildPack} not found.`); - } - } else { - await saveBuildLog({ line: 'Build image already available - no rebuild required.', buildId, applicationId }); - } - try { - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker stop -t 0 ${imageId}` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker rm ${imageId}` }) - } catch (error) { - // - } - const envs = []; - if (secrets.length > 0) { - secrets.forEach((secret) => { - if (pullmergeRequestId) { - if (secret.isPRMRSecret) { - envs.push(`${secret.name}=${secret.value}`); - } - } else { - if (!secret.isPRMRSecret) { - envs.push(`${secret.name}=${secret.value}`); - } + let envFound = false; + try { + envFound = !!(await fs.stat(`${workdir}/.env`)); + } catch (error) { + // } - }); - } - await fs.writeFile(`${workdir}/.env`, envs.join('\n')); - const labels = makeLabelForStandaloneApplication({ - applicationId, - fqdn, - name, - type, - pullmergeRequestId, - buildPack, - repository, - branch, - projectId, - port: exposePort ? `${exposePort}:${port}` : port, - commit, - installCommand, - buildCommand, - startCommand, - baseDirectory, - publishDirectory - }); - let envFound = false; - try { - envFound = !!(await fs.stat(`${workdir}/.env`)); - } catch (error) { - // - } - try { - await saveBuildLog({ line: 'Deployment started.', buildId, applicationId }); - const composeVolumes = volumes.map((volume) => { - return { - [`${volume.split(':')[0]}`]: { - name: volume.split(':')[0] - } - }; - }); - const composeFile = { - version: '3.8', - services: { - [imageId]: { - image: `${applicationId}:${tag}`, - container_name: imageId, - volumes, - env_file: envFound ? [`${workdir}/.env`] : [], - networks: [destinationDocker.network], - labels, - depends_on: [], - restart: 'always', - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - // logging: { - // driver: 'fluentd', - // }, - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' + try { + await saveBuildLog({ line: 'Deployment started.', buildId, applicationId }); + const composeVolumes = volumes.map((volume) => { + return { + [`${volume.split(':')[0]}`]: { + name: volume.split(':')[0] } - } - } - }, - networks: { - [destinationDocker.network]: { - external: true - } - }, - volumes: Object.assign({}, ...composeVolumes) - }; - await fs.writeFile(`${workdir}/docker-compose.yml`, yaml.dump(composeFile)); - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose --project-directory ${workdir} up -d` }) - await saveBuildLog({ line: 'Deployment successful!', buildId, applicationId }); - } catch (error) { - await saveBuildLog({ line: error, buildId, applicationId }); - await prisma.build.update({ - where: { id: message.build_id }, + }; + }); + const composeFile = { + version: '3.8', + services: { + [imageId]: { + image: `${applicationId}:${tag}`, + container_name: imageId, + volumes, + env_file: envFound ? [`${workdir}/.env`] : [], + labels, + depends_on: [], + expose: [port], + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + // logging: { + // driver: 'fluentd', + // }, + ...defaultComposeConfiguration(destinationDocker.network), + } + }, + networks: { + [destinationDocker.network]: { + external: true + } + }, + volumes: Object.assign({}, ...composeVolumes) + }; + await fs.writeFile(`${workdir}/docker-compose.yml`, yaml.dump(composeFile)); + await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose --project-directory ${workdir} up -d` }) + await saveBuildLog({ line: 'Deployment successful!', buildId, applicationId }); + } catch (error) { + await saveBuildLog({ line: error, buildId, applicationId }); + await prisma.build.updateMany({ + where: { id: buildId, status: { in: ['queued', 'running'] } }, + data: { status: 'failed' } + }); + throw new Error(error); + } + await saveBuildLog({ line: 'Proxy will be updated shortly.', buildId, applicationId }); + await prisma.build.update({ where: { id: buildId }, data: { status: 'success' } }); + if (!pullmergeRequestId) await prisma.application.update({ + where: { id: applicationId }, + data: { configHash: currentHash } + }); + } + } + catch (error) { + await prisma.build.updateMany({ + where: { id: buildId, status: { in: ['queued', 'running'] } }, data: { status: 'failed' } }); - throw new Error(error); + await saveBuildLog({ line: error, buildId, applicationId: application.id }); } - await saveBuildLog({ line: 'Proxy will be updated shortly.', buildId, applicationId }); - await prisma.build.update({ where: { id: message.build_id }, data: { status: 'success' } }); - } - - } - catch (error) { - await prisma.build.update({ - where: { id: message.build_id }, - data: { status: 'failed' } }); - await saveBuildLog({ line: error, buildId, applicationId }); - } finally { - await prisma.$disconnect(); } - }); - await prisma.$disconnect(); + await pAll.default(actions, { concurrency }) + } + } catch (error) { + console.log(error) } - }); + }) + while (true) { + await th() + } } else process.exit(0); })(); diff --git a/apps/api/src/jobs/infrastructure.ts b/apps/api/src/jobs/infrastructure.ts new file mode 100644 index 000000000..fbcb07616 --- /dev/null +++ b/apps/api/src/jobs/infrastructure.ts @@ -0,0 +1,226 @@ +import { parentPort } from 'node:worker_threads'; +import axios from 'axios'; +import { compareVersions } from 'compare-versions'; +import { asyncExecShell, cleanupDockerStorage, executeDockerCmd, isDev, prisma, startTraefikTCPProxy, generateDatabaseConfiguration, startTraefikProxy, listSettings, version, createRemoteEngineConfiguration } from '../lib/common'; + +async function autoUpdater() { + try { + const currentVersion = version; + const { data: versions } = await axios + .get( + `https://get.coollabs.io/versions.json` + , { + params: { + appId: process.env['COOLIFY_APP_ID'] || undefined, + version: currentVersion + } + }) + const latestVersion = versions['coolify'].main.version; + const isUpdateAvailable = compareVersions(latestVersion, currentVersion); + if (isUpdateAvailable === 1) { + const activeCount = 0 + if (activeCount === 0) { + if (!isDev) { + await asyncExecShell(`docker pull coollabsio/coolify:${latestVersion}`); + await asyncExecShell(`env | grep COOLIFY > .env`); + await asyncExecShell( + `sed -i '/COOLIFY_AUTO_UPDATE=/cCOOLIFY_AUTO_UPDATE=true' .env` + ); + await asyncExecShell( + `docker run --rm -tid --env-file .env -v /var/run/docker.sock:/var/run/docker.sock -v coolify-db coollabsio/coolify:${latestVersion} /bin/sh -c "env | grep COOLIFY > .env && echo 'TAG=${latestVersion}' >> .env && docker stop -t 0 coolify && docker rm coolify && docker compose up -d --force-recreate"` + ); + } else { + console.log('Updating (not really in dev mode).'); + } + } + } + } catch (error) { } +} +async function checkProxies() { + try { + const { default: isReachable } = await import('is-port-reachable'); + let portReachable; + + const { arch, ipv4, ipv6 } = await listSettings(); + + // Coolify Proxy local + const engine = '/var/run/docker.sock'; + const localDocker = await prisma.destinationDocker.findFirst({ + where: { engine, network: 'coolify', isCoolifyProxyUsed: true } + }); + if (localDocker) { + portReachable = await isReachable(80, { host: ipv4 || ipv6 }) + if (!portReachable) { + await startTraefikProxy(localDocker.id); + } + } + // Coolify Proxy remote + const remoteDocker = await prisma.destinationDocker.findMany({ + where: { remoteEngine: true, remoteVerified: true } + }); + if (remoteDocker.length > 0) { + for (const docker of remoteDocker) { + if (docker.isCoolifyProxyUsed) { + portReachable = await isReachable(80, { host: docker.remoteIpAddress }) + if (!portReachable) { + await startTraefikProxy(docker.id); + } + } + try { + await createRemoteEngineConfiguration(docker.id) + } catch (error) { } + } + } + // TCP Proxies + const databasesWithPublicPort = await prisma.database.findMany({ + where: { publicPort: { not: null } }, + include: { settings: true, destinationDocker: true } + }); + for (const database of databasesWithPublicPort) { + const { destinationDockerId, destinationDocker, publicPort, id } = database; + if (destinationDockerId && destinationDocker.isCoolifyProxyUsed) { + const { privatePort } = generateDatabaseConfiguration(database, arch); + portReachable = await isReachable(publicPort, { host: destinationDocker.remoteIpAddress || ipv4 || ipv6 }) + if (!portReachable) { + await startTraefikTCPProxy(destinationDocker, id, publicPort, privatePort); + } + } + } + const wordpressWithFtp = await prisma.wordpress.findMany({ + where: { ftpPublicPort: { not: null } }, + include: { service: { include: { destinationDocker: true } } } + }); + for (const ftp of wordpressWithFtp) { + const { service, ftpPublicPort } = ftp; + const { destinationDockerId, destinationDocker, id } = service; + if (destinationDockerId && destinationDocker.isCoolifyProxyUsed) { + portReachable = await isReachable(ftpPublicPort, { host: destinationDocker.remoteIpAddress || ipv4 || ipv6 }) + if (!portReachable) { + await startTraefikTCPProxy(destinationDocker, id, ftpPublicPort, 22, 'wordpressftp'); + } + } + } + + // HTTP Proxies + const minioInstances = await prisma.minio.findMany({ + where: { publicPort: { not: null } }, + include: { service: { include: { destinationDocker: true } } } + }); + for (const minio of minioInstances) { + const { service, publicPort } = minio; + const { destinationDockerId, destinationDocker, id } = service; + if (destinationDockerId && destinationDocker.isCoolifyProxyUsed) { + portReachable = await isReachable(publicPort, { host: destinationDocker.remoteIpAddress || ipv4 || ipv6 }) + if (!portReachable) { + await startTraefikTCPProxy(destinationDocker, id, publicPort, 9000); + } + } + } + } catch (error) { + + } +} +async function cleanupPrismaEngines() { + if (!isDev) { + try { + const { stdout } = await asyncExecShell(`ps -ef | grep /app/prisma-engines/query-engine | grep -v grep | wc -l | xargs`) + if (stdout.trim() != null && stdout.trim() != '' && Number(stdout.trim()) > 1) { + await asyncExecShell(`killall -q -e /app/prisma-engines/query-engine -o 1m`) + } + } catch (error) { } + } +} +async function cleanupStorage() { + const destinationDockers = await prisma.destinationDocker.findMany(); + let enginesDone = new Set() + for (const destination of destinationDockers) { + if (enginesDone.has(destination.engine) || enginesDone.has(destination.remoteIpAddress)) return + if (destination.engine) enginesDone.add(destination.engine) + if (destination.remoteIpAddress) enginesDone.add(destination.remoteIpAddress) + + let lowDiskSpace = false; + try { + let stdout = null + if (!isDev) { + const output = await executeDockerCmd({ dockerId: destination.id, command: `CONTAINER=$(docker ps -lq | head -1) && docker exec $CONTAINER sh -c 'df -kPT /'` }) + stdout = output.stdout; + } else { + const output = await asyncExecShell( + `df -kPT /` + ); + stdout = output.stdout; + } + let lines = stdout.trim().split('\n'); + let header = lines[0]; + let regex = + /^Filesystem\s+|Type\s+|1024-blocks|\s+Used|\s+Available|\s+Capacity|\s+Mounted on\s*$/g; + const boundaries = []; + let match; + + while ((match = regex.exec(header))) { + boundaries.push(match[0].length); + } + + boundaries[boundaries.length - 1] = -1; + const data = lines.slice(1).map((line) => { + const cl = boundaries.map((boundary) => { + const column = boundary > 0 ? line.slice(0, boundary) : line; + line = line.slice(boundary); + return column.trim(); + }); + return { + capacity: Number.parseInt(cl[5], 10) / 100 + }; + }); + if (data.length > 0) { + const { capacity } = data[0]; + if (capacity > 0.8) { + lowDiskSpace = true; + } + } + } catch (error) { } + await cleanupDockerStorage(destination.id, lowDiskSpace, false) + } +} + +(async () => { + let status = { + cleanupStorage: false, + autoUpdater: false + } + if (parentPort) { + parentPort.on('message', async (message) => { + if (parentPort) { + if (message === 'error') throw new Error('oops'); + if (message === 'cancel') { + parentPort.postMessage('cancelled'); + process.exit(1); + } + if (message === 'action:cleanupStorage') { + if (!status.autoUpdater) { + status.cleanupStorage = true + await cleanupStorage(); + status.cleanupStorage = false + } + return; + } + if (message === 'action:cleanupPrismaEngines') { + await cleanupPrismaEngines(); + return; + } + if (message === 'action:checkProxies') { + await checkProxies(); + return; + } + if (message === 'action:autoUpdater') { + if (!status.cleanupStorage) { + status.autoUpdater = true + await autoUpdater(); + status.autoUpdater = false + } + return; + } + } + }); + } else process.exit(0); +})(); diff --git a/apps/api/src/lib/buildPacks/common.ts b/apps/api/src/lib/buildPacks/common.ts index 3c34c5f31..93b8ca076 100644 --- a/apps/api/src/lib/buildPacks/common.ts +++ b/apps/api/src/lib/buildPacks/common.ts @@ -89,6 +89,22 @@ export function setDefaultBaseImage(buildPack: string | null, deploymentType: st } ]; const phpVersions = [ + { + value: 'webdevops/php-apache:8.2', + label: 'webdevops/php-apache:8.2' + }, + { + value: 'webdevops/php-nginx:8.2', + label: 'webdevops/php-nginx:8.2' + }, + { + value: 'webdevops/php-apache:8.1', + label: 'webdevops/php-apache:8.1' + }, + { + value: 'webdevops/php-nginx:8.1', + label: 'webdevops/php-nginx:8.1' + }, { value: 'webdevops/php-apache:8.0', label: 'webdevops/php-apache:8.0' @@ -145,6 +161,22 @@ export function setDefaultBaseImage(buildPack: string | null, deploymentType: st value: 'webdevops/php-nginx:5.6', label: 'webdevops/php-nginx:5.6' }, + { + value: 'webdevops/php-apache:8.2-alpine', + label: 'webdevops/php-apache:8.2-alpine' + }, + { + value: 'webdevops/php-nginx:8.2-alpine', + label: 'webdevops/php-nginx:8.2-alpine' + }, + { + value: 'webdevops/php-apache:8.1-alpine', + label: 'webdevops/php-apache:8.1-alpine' + }, + { + value: 'webdevops/php-nginx:8.1-alpine', + label: 'webdevops/php-nginx:8.1-alpine' + }, { value: 'webdevops/php-apache:8.0-alpine', label: 'webdevops/php-apache:8.0-alpine' @@ -252,6 +284,20 @@ export function setDefaultBaseImage(buildPack: string | null, deploymentType: st label: 'python:3.7-slim-bullseye' } ]; + const herokuVersions = [ + { + value: 'heroku/builder:22', + label: 'heroku/builder:22' + }, + { + value: 'heroku/buildpacks:20', + label: 'heroku/buildpacks:20' + }, + { + value: 'heroku/builder-classic:22', + label: 'heroku/builder-classic:22' + }, + ] let payload: any = { baseImage: null, baseBuildImage: null, @@ -291,14 +337,19 @@ export function setDefaultBaseImage(buildPack: string | null, deploymentType: st payload.baseImage = 'denoland/deno:latest'; } if (buildPack === 'php') { - payload.baseImage = 'webdevops/php-apache:8.0-alpine'; + payload.baseImage = 'webdevops/php-apache:8.2-alpine'; payload.baseImages = phpVersions; } if (buildPack === 'laravel') { - payload.baseImage = 'webdevops/php-apache:8.0-alpine'; + payload.baseImage = 'webdevops/php-apache:8.2-alpine'; payload.baseBuildImage = 'node:18'; payload.baseBuildImages = nodeVersions; } + if (buildPack === 'heroku') { + payload.baseImage = 'heroku/buildpacks:20'; + payload.baseImages = herokuVersions; + + } return payload; } @@ -493,7 +544,6 @@ export async function copyBaseConfigurationFiles( ); } } catch (error) { - console.log(error); throw new Error(error); } } @@ -522,9 +572,6 @@ export async function buildImage({ } else { await saveBuildLog({ line: `Building image started.`, buildId, applicationId }); } - if (debug) { - await saveBuildLog({ line: `\n###############\nIMPORTANT: Due to some issues during implementing Remote Docker Engine, the builds logs are not streamed at the moment. You will see the full build log when the build is finished!\n###############`, buildId, applicationId }); - } if (!debug && isCache) { await saveBuildLog({ line: `Debug turned off. To see more details, allow it in the configuration.`, @@ -534,54 +581,11 @@ export async function buildImage({ } const dockerFile = isCache ? `${dockerFileLocation}-cache` : `${dockerFileLocation}` const cache = `${applicationId}:${tag}${isCache ? '-cache' : ''}` - const { stderr } = await executeDockerCmd({ dockerId, command: `docker build --progress plain -f ${workdir}/${dockerFile} -t ${cache} ${workdir}` }) - if (debug) { - const array = stderr.split('\n') - for (const line of array) { - if (line !== '\n') { - await saveBuildLog({ - line: `${line.replace('\n', '')}`, - buildId, - applicationId - }); - } - } + await executeDockerCmd({ debug, buildId, applicationId, dockerId, command: `docker build --progress plain -f ${workdir}/${dockerFile} -t ${cache} ${workdir}` }) + const { status } = await prisma.build.findUnique({ where: { id: buildId } }) + if (status === 'canceled') { + throw new Error('Deployment canceled.') } - - - // await new Promise((resolve, reject) => { - // const command = spawn(`docker`, ['build', '-f', `${workdir}${dockerFile}`, '-t', `${cache}`,`${workdir}`], { - // env: { - // DOCKER_HOST: 'ssh://root@95.217.178.202', - // DOCKER_BUILDKIT: '1' - // } - // }); - // command.stdout.on('data', function (data) { - // console.log('stdout: ' + data); - // }); - // command.stderr.on('data', function (data) { - // console.log('stderr: ' + data); - // }); - // command.on('error', function (error) { - // console.log(error) - // reject(error) - // }) - // command.on('exit', function (code) { - // console.log('exit code: ' + code); - // resolve(code) - // }); - // }) - - - // console.log({ stdout, stderr }) - // const stream = await docker.engine.buildImage( - // { src: ['.'], context: workdir }, - // { - // dockerfile: isCache ? `${dockerFileLocation}-cache` : dockerFileLocation, - // t: `${applicationId}:${tag}${isCache ? '-cache' : ''}` - // } - // ); - // await streamEvents({ stream, docker, buildId, applicationId, debug }); if (isCache) { await saveBuildLog({ line: `Building cache image successful.`, buildId, applicationId }); } else { @@ -698,11 +702,10 @@ export async function buildCacheImageWithNode(data, imageForBuild) { if (isPnpm) { Dockerfile.push('RUN curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm@7'); } + Dockerfile.push(`COPY .${baseDirectory || ''} ./`); if (installCommand) { - Dockerfile.push(`COPY .${baseDirectory || ''}/package.json ./`); Dockerfile.push(`RUN ${installCommand}`); } - Dockerfile.push(`COPY .${baseDirectory || ''} ./`); Dockerfile.push(`RUN ${buildCommand}`); await fs.writeFile(`${workdir}/Dockerfile-cache`, Dockerfile.join('\n')); await buildImage({ ...data, isCache: true }); diff --git a/apps/api/src/lib/buildPacks/heroku.ts b/apps/api/src/lib/buildPacks/heroku.ts new file mode 100644 index 000000000..3efdeaf6a --- /dev/null +++ b/apps/api/src/lib/buildPacks/heroku.ts @@ -0,0 +1,39 @@ +import { executeDockerCmd, prisma } from "../common" +import { saveBuildLog } from "./common"; + +export default async function (data: any): Promise { + const { buildId, applicationId, tag, dockerId, debug, workdir } = data + try { + + await saveBuildLog({ line: `Building image started.`, buildId, applicationId }); + const { stdout } = await executeDockerCmd({ + dockerId, + command: `pack build -p ${workdir} ${applicationId}:${tag} --builder heroku/buildpacks:20` + }) + if (debug) { + const array = stdout.split('\n') + for (const line of array) { + if (line !== '\n') { + await saveBuildLog({ + line: `${line.replace('\n', '')}`, + buildId, + applicationId + }); + } + } + } + await saveBuildLog({ line: `Building image successful.`, buildId, applicationId }); + } catch (error) { + const array = error.stdout.split('\n') + for (const line of array) { + if (line !== '\n') { + await saveBuildLog({ + line: `${line.replace('\n', '')}`, + buildId, + applicationId + }); + } + } + throw error; + } +} diff --git a/apps/api/src/lib/buildPacks/index.ts b/apps/api/src/lib/buildPacks/index.ts index 163aa3a7d..b8eb4d609 100644 --- a/apps/api/src/lib/buildPacks/index.ts +++ b/apps/api/src/lib/buildPacks/index.ts @@ -15,6 +15,7 @@ import eleventy from './static'; import python from './python'; import deno from './deno'; import laravel from './laravel'; +import heroku from './heroku'; export { node, @@ -33,5 +34,6 @@ export { eleventy, python, deno, - laravel + laravel, + heroku }; diff --git a/apps/api/src/lib/common.ts b/apps/api/src/lib/common.ts index b698fc12c..febb08374 100644 --- a/apps/api/src/lib/common.ts +++ b/apps/api/src/lib/common.ts @@ -1,4 +1,4 @@ -import child from 'child_process'; +import { exec } from 'node:child_process' import util from 'util'; import fs from 'fs/promises'; import yaml from 'js-yaml'; @@ -15,9 +15,13 @@ import sshConfig from 'ssh-config' import { checkContainer, removeContainer } from './docker'; import { day } from './dayjs'; -import * as serviceFields from './serviceFields' +import * as serviceFields from './services/serviceFields' +import { saveBuildLog } from './buildPacks/common'; +import { scheduler } from './scheduler'; +import { supportedServiceTypesAndVersions } from './services/supportedVersions'; +import { includeServices } from './services/common'; -export const version = '3.2.0'; +export const version = '3.9.2'; export const isDev = process.env.NODE_ENV === 'development'; const algorithm = 'aes-256-ctr'; @@ -38,14 +42,21 @@ export function getAPIUrl() { const newURL = href.replace('https://', 'https://3001-').replace(/\/$/, '') return newURL } + if (process.env.CODESANDBOX_HOST) { + return `https://${process.env.CODESANDBOX_HOST.replace(/\$PORT/, '3001')}` + } return isDev ? 'http://localhost:3001' : 'http://localhost:3000'; } + export function getUIUrl() { if (process.env.GITPOD_WORKSPACE_URL) { const { href } = new URL(process.env.GITPOD_WORKSPACE_URL) const newURL = href.replace('https://', 'https://3000-').replace(/\/$/, '') return newURL } + if (process.env.CODESANDBOX_HOST) { + return `https://${process.env.CODESANDBOX_HOST.replace(/\$PORT/, '3000')}` + } return 'http://localhost:3000'; } @@ -58,29 +69,81 @@ const otherTraefikEndpoint = isDev : 'http://coolify:3000/webhooks/traefik/other.json'; -export const include: any = { - destinationDocker: true, - persistentStorage: true, - serviceSecret: true, - minio: true, - plausibleAnalytics: true, - vscodeserver: true, - wordpress: true, - ghost: true, - meiliSearch: true, - umami: true, - hasura: true, - fider: true, -}; - export const uniqueName = (): string => uniqueNamesGenerator(customConfig); -export const asyncExecShell = util.promisify(child.exec); +export const asyncExecShell = util.promisify(exec); +export const asyncExecShellStream = async ({ debug, buildId, applicationId, command, engine }: { debug: boolean, buildId: string, applicationId: string, command: string, engine: string }) => { + return await new Promise(async (resolve, reject) => { + const { execaCommand } = await import('execa') + const subprocess = execaCommand(command, { env: { DOCKER_BUILDKIT: "1", DOCKER_HOST: engine } }) + if (debug) { + subprocess.stdout.on('data', async (data) => { + const stdout = data.toString(); + const array = stdout.split('\n') + for (const line of array) { + if (line !== '\n' && line !== '') { + await saveBuildLog({ + line: `${line.replace('\n', '')}`, + buildId, + applicationId + }); + } + } + }) + subprocess.stderr.on('data', async (data) => { + const stderr = data.toString(); + const array = stderr.split('\n') + for (const line of array) { + if (line !== '\n' && line !== '') { + await saveBuildLog({ + line: `${line.replace('\n', '')}`, + buildId, + applicationId + }); + } + } + }) + } + subprocess.on('exit', async (code) => { + await asyncSleep(1000); + if (code === 0) { + resolve(code) + } else { + reject(code) + } + }) + }) +} + export const asyncSleep = (delay: number): Promise => new Promise((resolve) => setTimeout(resolve, delay)); export const prisma = new PrismaClient({ - errorFormat: 'minimal' + errorFormat: 'minimal', + // log: [ + // { + // emit: 'event', + // level: 'query', + // }, + // { + // emit: 'stdout', + // level: 'error', + // }, + // { + // emit: 'stdout', + // level: 'info', + // }, + // { + // emit: 'stdout', + // level: 'warn', + // }, + // ], }); +// prisma.$on('query', (e) => { +// console.log({e}) +// console.log('Query: ' + e.query) +// console.log('Params: ' + e.params) +// console.log('Duration: ' + e.duration + 'ms') +// }) export const base64Encode = (text: string): string => { return Buffer.from(text).toString('base64'); }; @@ -89,17 +152,23 @@ export const base64Decode = (text: string): string => { }; export const decrypt = (hashString: string) => { if (hashString) { - const hash = JSON.parse(hashString); - const decipher = crypto.createDecipheriv( - algorithm, - process.env['COOLIFY_SECRET_KEY'], - Buffer.from(hash.iv, 'hex') - ); - const decrpyted = Buffer.concat([ - decipher.update(Buffer.from(hash.content, 'hex')), - decipher.final() - ]); - return decrpyted.toString(); + try { + const hash = JSON.parse(hashString); + const decipher = crypto.createDecipheriv( + algorithm, + process.env['COOLIFY_SECRET_KEY'], + Buffer.from(hash.iv, 'hex') + ); + const decrpyted = Buffer.concat([ + decipher.update(Buffer.from(hash.content, 'hex')), + decipher.final() + ]); + return decrpyted.toString(); + } catch (error) { + console.log({ decryptionError: error.message }) + return hashString + } + } }; export const encrypt = (text: string) => { @@ -114,166 +183,7 @@ export const encrypt = (text: string) => { } }; -export const supportedServiceTypesAndVersions = [ - { - name: 'plausibleanalytics', - fancyName: 'Plausible Analytics', - baseImage: 'plausible/analytics', - images: ['bitnami/postgresql:13.2.0', 'yandex/clickhouse-server:21.3.2.5'], - versions: ['latest', 'stable'], - recommendedVersion: 'stable', - ports: { - main: 8000 - } - }, - { - name: 'nocodb', - fancyName: 'NocoDB', - baseImage: 'nocodb/nocodb', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 8080 - } - }, - { - name: 'minio', - fancyName: 'MinIO', - baseImage: 'minio/minio', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 9001 - } - }, - { - name: 'vscodeserver', - fancyName: 'VSCode Server', - baseImage: 'codercom/code-server', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 8080 - } - }, - { - name: 'wordpress', - fancyName: 'Wordpress', - baseImage: 'wordpress', - images: ['bitnami/mysql:5.7'], - versions: ['latest', 'php8.1', 'php8.0', 'php7.4', 'php7.3'], - recommendedVersion: 'latest', - ports: { - main: 80 - } - }, - { - name: 'vaultwarden', - fancyName: 'Vaultwarden', - baseImage: 'vaultwarden/server', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 80 - } - }, - { - name: 'languagetool', - fancyName: 'LanguageTool', - baseImage: 'silviof/docker-languagetool', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 8010 - } - }, - { - name: 'n8n', - fancyName: 'n8n', - baseImage: 'n8nio/n8n', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 5678 - } - }, - { - name: 'uptimekuma', - fancyName: 'Uptime Kuma', - baseImage: 'louislam/uptime-kuma', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 3001 - } - }, - { - name: 'ghost', - fancyName: 'Ghost', - baseImage: 'bitnami/ghost', - images: ['bitnami/mariadb'], - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 2368 - } - }, - { - name: 'meilisearch', - fancyName: 'Meilisearch', - baseImage: 'getmeili/meilisearch', - images: [], - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 7700 - } - }, - { - name: 'umami', - fancyName: 'Umami', - baseImage: 'ghcr.io/mikecao/umami', - images: ['postgres:12-alpine'], - versions: ['postgresql-latest'], - recommendedVersion: 'postgresql-latest', - ports: { - main: 3000 - } - }, - { - name: 'hasura', - fancyName: 'Hasura', - baseImage: 'hasura/graphql-engine', - images: ['postgres:12-alpine'], - versions: ['latest', 'v2.8.4', 'v2.5.1'], - recommendedVersion: 'v2.8.4', - ports: { - main: 8080 - } - }, - { - name: 'fider', - fancyName: 'Fider', - baseImage: 'getfider/fider', - images: ['postgres:12-alpine'], - versions: ['stable'], - recommendedVersion: 'stable', - ports: { - main: 3000 - } - }, - // { - // name: 'moodle', - // fancyName: 'Moodle', - // baseImage: 'bitnami/moodle', - // images: [], - // versions: ['latest', 'v4.0.2'], - // recommendedVersion: 'latest', - // ports: { - // main: 8080 - // } - // } -]; + export async function checkDoubleBranch(branch: string, projectId: number): Promise { const applications = await prisma.application.findMany({ where: { branch, projectId } }); @@ -281,6 +191,10 @@ export async function checkDoubleBranch(branch: string, projectId: number): Prom } export async function isDNSValid(hostname: any, domain: string): Promise { const { isIP } = await import('is-ip'); + const { DNSServers } = await listSettings(); + if (DNSServers) { + dns.setServers([DNSServers]); + } let resolves = []; try { if (isIP(hostname)) { @@ -294,7 +208,6 @@ export async function isDNSValid(hostname: any, domain: string): Promise { try { let ipDomainFound = false; - dns.setServers(['1.1.1.1', '8.8.8.8']); const dnsResolve = await dns.resolve4(domain); if (dnsResolve.length > 0) { for (const ip of dnsResolve) { @@ -318,12 +231,12 @@ export async function isDomainConfigured({ id, fqdn, checkOwn = false, - dockerId = undefined + remoteIpAddress = undefined }: { id: string; fqdn: string; checkOwn?: boolean; - dockerId?: string; + remoteIpAddress?: string; }): Promise { const domain = getDomain(fqdn); const nakedDomain = domain.replace('www.', ''); @@ -335,7 +248,7 @@ export async function isDomainConfigured({ ], id: { not: id }, destinationDocker: { - id: dockerId + remoteIpAddress, } }, select: { fqdn: true } @@ -350,7 +263,7 @@ export async function isDomainConfigured({ ], id: { not: checkOwn ? undefined : id }, destinationDocker: { - id: dockerId + remoteIpAddress } }, select: { fqdn: true } @@ -386,7 +299,12 @@ export async function checkDomainsIsValidInDNS({ hostname, fqdn, dualCerts }): P const { isIP } = await import('is-ip'); const domain = getDomain(fqdn); const domainDualCert = domain.includes('www.') ? domain.replace('www.', '') : `www.${domain}`; - dns.setServers(['1.1.1.1', '8.8.8.8']); + + const { DNSServers } = await listSettings(); + if (DNSServers) { + dns.setServers([DNSServers]); + } + let resolves = []; try { if (isIP(hostname)) { @@ -443,7 +361,7 @@ export function generateTimestamp(): string { export async function listServicesWithIncludes(): Promise { return await prisma.service.findMany({ - include, + include: includeServices, orderBy: { createdAt: 'desc' } }); } @@ -453,67 +371,122 @@ export const supportedDatabaseTypesAndVersions = [ name: 'mongodb', fancyName: 'MongoDB', baseImage: 'bitnami/mongodb', - versions: ['5.0', '4.4', '4.2'] + baseImageARM: 'mongo', + versions: ['5.0', '4.4', '4.2'], + versionsARM: ['5.0', '4.4', '4.2'] + }, + { + name: 'mysql', + fancyName: 'MySQL', + baseImage: 'bitnami/mysql', + baseImageARM: 'mysql', + versions: ['8.0', '5.7'], + versionsARM: ['8.0', '5.7'] }, - { name: 'mysql', fancyName: 'MySQL', baseImage: 'bitnami/mysql', versions: ['8.0', '5.7'] }, { name: 'mariadb', fancyName: 'MariaDB', baseImage: 'bitnami/mariadb', - versions: ['10.8', '10.7', '10.6', '10.5', '10.4', '10.3', '10.2'] + baseImageARM: 'mariadb', + versions: ['10.8', '10.7', '10.6', '10.5', '10.4', '10.3', '10.2'], + versionsARM: ['10.8', '10.7', '10.6', '10.5', '10.4', '10.3', '10.2'] }, { name: 'postgresql', fancyName: 'PostgreSQL', baseImage: 'bitnami/postgresql', - versions: ['14.4.0', '13.6.0', '12.10.0', '11.15.0', '10.20.0'] + baseImageARM: 'postgres', + versions: ['14.5.0', '13.8.0', '12.12.0', '11.17.0', '10.22.0'], + versionsARM: ['14.5', '13.8', '12.12', '11.17', '10.22'] }, { name: 'redis', fancyName: 'Redis', baseImage: 'bitnami/redis', - versions: ['7.0', '6.2', '6.0', '5.0'] + baseImageARM: 'redis', + versions: ['7.0', '6.2', '6.0', '5.0'], + versionsARM: ['7.0', '6.2', '6.0', '5.0'] }, - { name: 'couchdb', fancyName: 'CouchDB', baseImage: 'bitnami/couchdb', versions: ['3.2.1'] }, { + name: 'couchdb', + fancyName: 'CouchDB', + baseImage: 'bitnami/couchdb', + baseImageARM: 'couchdb', + versions: ['3.2.2', '3.1.2', '2.3.1'], + versionsARM: ['3.2.2', '3.1.2', '2.3.1'] + }, + { name: 'edgedb', fancyName: 'EdgeDB', baseImage: 'edgedb/edgedb', versions: ['2.0', '1.4'] - } + } ]; + +export async function getFreeSSHLocalPort(id: string): Promise { + const { default: isReachable } = await import('is-port-reachable'); + const { remoteIpAddress, sshLocalPort } = await prisma.destinationDocker.findUnique({ where: { id } }) + if (sshLocalPort) { + return Number(sshLocalPort) + } + + const data = await prisma.setting.findFirst(); + const { minPort, maxPort } = data; + + const ports = await prisma.destinationDocker.findMany({ where: { sshLocalPort: { not: null }, remoteIpAddress: { not: remoteIpAddress } } }) + + const alreadyConfigured = await prisma.destinationDocker.findFirst({ + where: { + remoteIpAddress, id: { not: id }, sshLocalPort: { not: null } + } + }) + if (alreadyConfigured?.sshLocalPort) { + await prisma.destinationDocker.update({ where: { id }, data: { sshLocalPort: alreadyConfigured.sshLocalPort } }) + return Number(alreadyConfigured.sshLocalPort) + } + const range = generateRangeArray(minPort, maxPort) + const availablePorts = range.filter(port => !ports.map(p => p.sshLocalPort).includes(port)) + for (const port of availablePorts) { + const found = await isReachable(port, { host: 'localhost' }) + if (!found) { + await prisma.destinationDocker.update({ where: { id }, data: { sshLocalPort: Number(port) } }) + return Number(port) + } + } + return false +} + export async function createRemoteEngineConfiguration(id: string) { const homedir = os.homedir(); const sshKeyFile = `/tmp/id_rsa-${id}` + const localPort = await getFreeSSHLocalPort(id); const { sshKey: { privateKey }, remoteIpAddress, remotePort, remoteUser } = await prisma.destinationDocker.findFirst({ where: { id }, include: { sshKey: true } }) await fs.writeFile(sshKeyFile, decrypt(privateKey) + '\n', { encoding: 'utf8', mode: 400 }) // Needed for remote docker compose - const { stdout: numberOfSSHAgentsRunning } = await asyncExecShell(`ps ax | grep [s]sh-agent | grep ssh-agent.pid | grep -v grep | wc -l`) + const { stdout: numberOfSSHAgentsRunning } = await asyncExecShell(`ps ax | grep [s]sh-agent | grep coolify-ssh-agent.pid | grep -v grep | wc -l`) if (numberOfSSHAgentsRunning !== '' && Number(numberOfSSHAgentsRunning.trim()) == 0) { - await asyncExecShell(`eval $(ssh-agent -sa /tmp/ssh-agent.pid)`) + try { + await fs.stat(`/tmp/coolify-ssh-agent.pid`) + await fs.rm(`/tmp/coolify-ssh-agent.pid`) + } catch (error) { } + await asyncExecShell(`eval $(ssh-agent -sa /tmp/coolify-ssh-agent.pid)`) } - await asyncExecShell(`SSH_AUTH_SOCK=/tmp/ssh-agent.pid ssh-add -q ${sshKeyFile}`) + await asyncExecShell(`SSH_AUTH_SOCK=/tmp/coolify-ssh-agent.pid ssh-add -q ${sshKeyFile}`) - const { stdout: numberOfSSHTunnelsRunning } = await asyncExecShell(`ps ax | grep 'ssh -fNL 11122:localhost:22' | grep -v grep | wc -l`) - console.log(numberOfSSHTunnelsRunning) + const { stdout: numberOfSSHTunnelsRunning } = await asyncExecShell(`ps ax | grep 'ssh -F /dev/null -o StrictHostKeyChecking no -fNL ${localPort}:localhost:${remotePort}' | grep -v grep | wc -l`) if (numberOfSSHTunnelsRunning !== '' && Number(numberOfSSHTunnelsRunning.trim()) == 0) { try { - await asyncExecShell(`SSH_AUTH_SOCK=/tmp/ssh-agent.pid ssh -fNL 11122:localhost:22 ${remoteIpAddress}`) - - } catch(error){ - console.log(error) - } + await asyncExecShell(`SSH_AUTH_SOCK=/tmp/coolify-ssh-agent.pid ssh -F /dev/null -o "StrictHostKeyChecking no" -fNL ${localPort}:localhost:${remotePort} ${remoteUser}@${remoteIpAddress}`) + } catch (error) { } } - - const config = sshConfig.parse('') const found = config.find({ Host: remoteIpAddress }) if (!found) { config.append({ Host: remoteIpAddress, Hostname: 'localhost', - Port: '11122', + Port: localPort.toString(), User: remoteUser, IdentityFile: sshKeyFile, StrictHostKeyChecking: 'no' @@ -524,13 +497,9 @@ export async function createRemoteEngineConfiguration(id: string) { } catch (error) { await fs.mkdir(`${homedir}/.ssh/`) } - - await fs.writeFile(`${homedir}/.ssh/config`, sshConfig.stringify(config)) - - return - + return await fs.writeFile(`${homedir}/.ssh/config`, sshConfig.stringify(config)) } -export async function executeDockerCmd({ dockerId, command }: { dockerId: string, command: string }) { +export async function executeDockerCmd({ debug, buildId, applicationId, dockerId, command }: { debug?: boolean, buildId?: string, applicationId?: string, dockerId: string, command: string }): Promise { let { remoteEngine, remoteIpAddress, engine } = await prisma.destinationDocker.findUnique({ where: { id: dockerId } }) if (remoteEngine) { await createRemoteEngineConfiguration(dockerId) @@ -538,6 +507,14 @@ export async function executeDockerCmd({ dockerId, command }: { dockerId: string } else { engine = 'unix:///var/run/docker.sock' } + if (process.env.CODESANDBOX_HOST) { + if (command.startsWith('docker compose')) { + command = command.replace(/docker compose/gi, 'docker-compose') + } + } + if (command.startsWith(`docker build --progress plain`)) { + return await asyncExecShellStream({ debug, buildId, applicationId, command, engine }); + } return await asyncExecShell( `DOCKER_BUILDKIT=1 DOCKER_HOST="${engine}" ${command}` ); @@ -549,6 +526,11 @@ export async function startTraefikProxy(id: string): Promise { const { id: settingsId, ipv4, ipv6 } = await listSettings(); if (!found) { + const { stdout: coolifyNetwork } = await executeDockerCmd({ dockerId: id, command: `docker network ls --filter 'name=coolify-infra' --no-trunc --format "{{json .}}"` }) + + if (!coolifyNetwork) { + await executeDockerCmd({ dockerId: id, command: `docker network create --attachable coolify-infra` }) + } const { stdout: Config } = await executeDockerCmd({ dockerId: id, command: `docker network inspect ${network} --format '{{json .IPAM.Config }}'` }) const ip = JSON.parse(Config)[0].Gateway; let traefikUrl = mainTraefikEndpoint @@ -652,19 +634,25 @@ export async function listSettings(): Promise { } -export function generatePassword(length = 24, symbols = false): string { - return generator.generate({ +export function generatePassword({ length = 24, symbols = false, isHex = false }: { length?: number, symbols?: boolean, isHex?: boolean } | null): string { + if (isHex) { + return crypto.randomBytes(length).toString("hex"); + } + const password = generator.generate({ length, numbers: true, strict: true, symbols }); + + return password; } -export function generateDatabaseConfiguration(database: any): +export function generateDatabaseConfiguration(database: any, arch: string): | { volume: string; image: string; + command?: string; ulimits: Record; privatePort: number; environmentVariables: { @@ -678,16 +666,20 @@ export function generateDatabaseConfiguration(database: any): | { volume: string; image: string; + command?: string; ulimits: Record; privatePort: number; environmentVariables: { - MONGODB_ROOT_USER: string; - MONGODB_ROOT_PASSWORD: string; + MONGO_INITDB_ROOT_USERNAME?: string; + MONGO_INITDB_ROOT_PASSWORD?: string; + MONGODB_ROOT_USER?: string; + MONGODB_ROOT_PASSWORD?: string; }; } | { volume: string; image: string; + command?: string; ulimits: Record; privatePort: number; environmentVariables: { @@ -701,6 +693,7 @@ export function generateDatabaseConfiguration(database: any): | { volume: string; image: string; + command?: string; ulimits: Record; privatePort: number; environmentVariables: { @@ -713,6 +706,19 @@ export function generateDatabaseConfiguration(database: any): | { volume: string; image: string; + command?: string; + ulimits: Record; + privatePort: number; + environmentVariables: { + POSTGRES_USER: string; + POSTGRES_PASSWORD: string; + POSTGRES_DB: string; + }; + } + | { + volume: string; + image: string; + command?: string; ulimits: Record; privatePort: number; environmentVariables: { @@ -723,6 +729,7 @@ export function generateDatabaseConfiguration(database: any): | { volume: string; image: string; + command?: string; ulimits: Record; privatePort: number; environmentVariables: { @@ -753,9 +760,9 @@ export function generateDatabaseConfiguration(database: any): type, settings: { appendOnly } } = database; - const baseImage = getDatabaseImage(type); + const baseImage = getDatabaseImage(type, arch); if (type === 'mysql') { - return { + const configuration = { privatePort: 3306, environmentVariables: { MYSQL_USER: dbUser, @@ -767,9 +774,13 @@ export function generateDatabaseConfiguration(database: any): image: `${baseImage}:${version}`, volume: `${id}-${type}-data:/bitnami/mysql/data`, ulimits: {} - }; + } + if (isARM(arch)) { + configuration.volume = `${id}-${type}-data:/var/lib/mysql`; + } + return configuration } else if (type === 'mariadb') { - return { + const configuration = { privatePort: 3306, environmentVariables: { MARIADB_ROOT_USER: rootUser, @@ -782,8 +793,12 @@ export function generateDatabaseConfiguration(database: any): volume: `${id}-${type}-data:/bitnami/mariadb`, ulimits: {} }; + if (isARM(arch)) { + configuration.volume = `${id}-${type}-data:/var/lib/mysql`; + } + return configuration } else if (type === 'mongodb') { - return { + const configuration = { privatePort: 27017, environmentVariables: { MONGODB_ROOT_USER: rootUser, @@ -793,8 +808,16 @@ export function generateDatabaseConfiguration(database: any): volume: `${id}-${type}-data:/bitnami/mongodb`, ulimits: {} }; + if (isARM(arch)) { + configuration.environmentVariables = { + MONGO_INITDB_ROOT_USERNAME: rootUser, + MONGO_INITDB_ROOT_PASSWORD: rootUserPassword + } + configuration.volume = `${id}-${type}-data:/data/db`; + } + return configuration } else if (type === 'postgresql') { - return { + const configuration = { privatePort: 5432, environmentVariables: { POSTGRESQL_POSTGRES_PASSWORD: rootUserPassword, @@ -805,10 +828,20 @@ export function generateDatabaseConfiguration(database: any): image: `${baseImage}:${version}`, volume: `${id}-${type}-data:/bitnami/postgresql`, ulimits: {} - }; + } + if (isARM(arch)) { + configuration.volume = `${id}-${type}-data:/var/lib/postgresql`; + configuration.environmentVariables = { + POSTGRES_PASSWORD: dbUserPassword, + POSTGRES_USER: dbUser, + POSTGRES_DB: defaultDatabase + } + } + return configuration } else if (type === 'redis') { - return { + const configuration = { privatePort: 6379, + command: undefined, environmentVariables: { REDIS_PASSWORD: dbUserPassword, REDIS_AOF_ENABLED: appendOnly ? 'yes' : 'no' @@ -817,8 +850,13 @@ export function generateDatabaseConfiguration(database: any): volume: `${id}-${type}-data:/bitnami/redis/data`, ulimits: {} }; + if (isARM(arch)) { + configuration.volume = `${id}-${type}-data:/data`; + configuration.command = `/usr/local/bin/redis-server --appendonly ${appendOnly ? 'yes' : 'no'} --requirepass ${dbUserPassword}`; + } + return configuration } else if (type === 'couchdb') { - return { + const configuration = { privatePort: 5984, environmentVariables: { COUCHDB_PASSWORD: dbUserPassword, @@ -828,14 +866,18 @@ export function generateDatabaseConfiguration(database: any): volume: `${id}-${type}-data:/bitnami/couchdb`, ulimits: {} }; + if (isARM(arch)) { + configuration.volume = `${id}-${type}-data:/opt/couchdb/data`; + } + return configuration } else if (type === 'edgedb') { return { privatePort: 5656, environmentVariables: { - EDGEDB_SERVER_PASSWORD: rootUserPassword, - EDGEDB_SERVER_USER: rootUser, - EDGEDB_SERVER_DATABASE: defaultDatabase, - EDGEDB_SERVER_SECURITY: 'insecure_dev_mode' + EDGEDB_SERVER_PASSWORD: rootUserPassword, + EDGEDB_SERVER_USER: rootUser, + EDGEDB_SERVER_DATABASE: defaultDatabase, + EDGEDB_SERVER_SECURITY: 'insecure_dev_mode' }, image: `${baseImage}:${version}`, volume: `${id}-${type}-data:/edgedb/edgedb`, @@ -843,18 +885,29 @@ export function generateDatabaseConfiguration(database: any): }; } } - -export function getDatabaseImage(type: string): string { +export function isARM(arch: string) { + if (arch === 'arm' || arch === 'arm64') { + return true + } + return false +} +export function getDatabaseImage(type: string, arch: string): string { const found = supportedDatabaseTypesAndVersions.find((t) => t.name === type); if (found) { + if (isARM(arch)) { + return found.baseImageARM || found.baseImage + } return found.baseImage; } return ''; } -export function getDatabaseVersions(type: string): string[] { +export function getDatabaseVersions(type: string, arch: string): string[] { const found = supportedDatabaseTypesAndVersions.find((t) => t.name === type); if (found) { + if (isARM(arch)) { + return found.versionsARM || found.versions + } return found.versions; } return []; @@ -952,9 +1005,14 @@ export const createDirectories = async ({ }): Promise<{ workdir: string; repodir: string }> => { const repodir = `/tmp/build-sources/${repository}/`; const workdir = `/tmp/build-sources/${repository}/${buildId}`; - + let workdirFound = false; + try { + workdirFound = !!(await fs.stat(workdir)); + } catch (error) { } + if (workdirFound) { + await asyncExecShell(`rm -fr ${workdir}`); + } await asyncExecShell(`mkdir -p ${workdir}`); - return { workdir, repodir @@ -1063,8 +1121,26 @@ export async function updatePasswordInDb(database, user, newPassword, isRoot) { } } } +export async function checkExposedPort({ id, configuredPort, exposePort, dockerId, remoteIpAddress }: { id: string, configuredPort?: number, exposePort: number, dockerId: string, remoteIpAddress?: string }) { + if (exposePort < 1024 || exposePort > 65535) { + throw { status: 500, message: `Exposed Port needs to be between 1024 and 65535.` } + } + if (configuredPort) { + if (configuredPort !== exposePort) { + const availablePort = await getFreeExposedPort(id, exposePort, dockerId, remoteIpAddress); + if (availablePort.toString() !== exposePort.toString()) { + throw { status: 500, message: `Port ${exposePort} is already in use.` } + } + } + } else { + const availablePort = await getFreeExposedPort(id, exposePort, dockerId, remoteIpAddress); + if (availablePort.toString() !== exposePort.toString()) { + throw { status: 500, message: `Port ${exposePort} is already in use.` } + } + } +} export async function getFreeExposedPort(id, exposePort, dockerId, remoteIpAddress) { - const { default: getPort } = await import('get-port'); + const { default: checkPort } = await import('is-port-reachable'); const applicationUsed = await ( await prisma.application.findMany({ where: { exposePort: { not: null }, id: { not: id }, destinationDockerId: dockerId }, @@ -1078,22 +1154,23 @@ export async function getFreeExposedPort(id, exposePort, dockerId, remoteIpAddre }) ).map((a) => a.exposePort); const usedPorts = [...applicationUsed, ...serviceUsed]; - if (remoteIpAddress) { - const { default: checkPort } = await import('is-port-reachable'); - const found = await checkPort(exposePort, { host: remoteIpAddress }); - if (!found) { - return exposePort - } + if (usedPorts.includes(exposePort)) { return false } - return await getPort({ port: Number(exposePort), exclude: usedPorts }); + const found = await checkPort(exposePort, { host: remoteIpAddress || 'localhost' }); + if (!found) { + return exposePort + } + return false } +export function generateRangeArray(start, end) { + return Array.from({ length: (end - start) }, (v, k) => k + start); +} export async function getFreePublicPort(id, dockerId) { - const { default: getPort, portNumbers } = await import('get-port'); + const { default: isReachable } = await import('is-port-reachable'); const data = await prisma.setting.findFirst(); const { minPort, maxPort } = data; - const dbUsed = await ( await prisma.database.findMany({ where: { publicPort: { not: null }, id: { not: id }, destinationDockerId: dockerId }, @@ -1119,7 +1196,15 @@ export async function getFreePublicPort(id, dockerId) { }) ).map((a) => a.publicPort); const usedPorts = [...dbUsed, ...wpFtpUsed, ...wpUsed, ...minioUsed]; - return await getPort({ port: portNumbers(minPort, maxPort), exclude: usedPorts }); + const range = generateRangeArray(minPort, maxPort) + const availablePorts = range.filter(port => !usedPorts.includes(port)) + for (const port of availablePorts) { + const found = await isReachable(port, { host: 'localhost' }) + if (!found) { + return port + } + } + return false } export async function startTraefikTCPProxy( @@ -1155,7 +1240,6 @@ export async function startTraefikTCPProxy( } traefikUrl = `${ip}/webhooks/traefik/other.json` } - console.log(traefikUrl) const tcpProxy = { version: '3.8', services: { @@ -1200,7 +1284,6 @@ export async function startTraefikTCPProxy( }) } } catch (error) { - console.log(error); return error; } } @@ -1209,7 +1292,7 @@ export async function getServiceFromDB({ id, teamId }: { id: string; teamId: str const settings = await prisma.setting.findFirst(); const body = await prisma.service.findFirst({ where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } }, - include + include: includeServices }); let { type } = body type = fixType(type) @@ -1220,6 +1303,7 @@ export async function getServiceFromDB({ id, teamId }: { id: string; teamId: str return s; }); } + body[type] = { ...body[type], ...getUpdateableFields(type, body[type]) } return { ...body, settings }; } @@ -1240,240 +1324,8 @@ export function getServiceImages(type: string): string[] { return []; } -export async function configureServiceType({ - id, - type -}: { - id: string; - type: string; -}): Promise { - if (type === 'plausibleanalytics') { - const password = encrypt(generatePassword()); - const postgresqlUser = cuid(); - const postgresqlPassword = encrypt(generatePassword()); - const postgresqlDatabase = 'plausibleanalytics'; - const secretKeyBase = encrypt(generatePassword(64)); - - await prisma.service.update({ - where: { id }, - data: { - type, - plausibleAnalytics: { - create: { - postgresqlDatabase, - postgresqlUser, - postgresqlPassword, - password, - secretKeyBase - } - } - } - }); - } else if (type === 'nocodb') { - await prisma.service.update({ - where: { id }, - data: { type } - }); - } else if (type === 'minio') { - const rootUser = cuid(); - const rootUserPassword = encrypt(generatePassword()); - await prisma.service.update({ - where: { id }, - data: { type, minio: { create: { rootUser, rootUserPassword } } } - }); - } else if (type === 'vscodeserver') { - const password = encrypt(generatePassword()); - await prisma.service.update({ - where: { id }, - data: { type, vscodeserver: { create: { password } } } - }); - } else if (type === 'wordpress') { - const mysqlUser = cuid(); - const mysqlPassword = encrypt(generatePassword()); - const mysqlRootUser = cuid(); - const mysqlRootUserPassword = encrypt(generatePassword()); - await prisma.service.update({ - where: { id }, - data: { - type, - wordpress: { create: { mysqlPassword, mysqlRootUserPassword, mysqlRootUser, mysqlUser } } - } - }); - } else if (type === 'vaultwarden') { - await prisma.service.update({ - where: { id }, - data: { - type - } - }); - } else if (type === 'languagetool') { - await prisma.service.update({ - where: { id }, - data: { - type - } - }); - } else if (type === 'n8n') { - await prisma.service.update({ - where: { id }, - data: { - type - } - }); - } else if (type === 'uptimekuma') { - await prisma.service.update({ - where: { id }, - data: { - type - } - }); - } else if (type === 'ghost') { - const defaultEmail = `${cuid()}@example.com`; - const defaultPassword = encrypt(generatePassword()); - const mariadbUser = cuid(); - const mariadbPassword = encrypt(generatePassword()); - const mariadbRootUser = cuid(); - const mariadbRootUserPassword = encrypt(generatePassword()); - - await prisma.service.update({ - where: { id }, - data: { - type, - ghost: { - create: { - defaultEmail, - defaultPassword, - mariadbUser, - mariadbPassword, - mariadbRootUser, - mariadbRootUserPassword - } - } - } - }); - } else if (type === 'meilisearch') { - const masterKey = encrypt(generatePassword(32)); - await prisma.service.update({ - where: { id }, - data: { - type, - meiliSearch: { create: { masterKey } } - } - }); - } else if (type === 'umami') { - const umamiAdminPassword = encrypt(generatePassword()); - const postgresqlUser = cuid(); - const postgresqlPassword = encrypt(generatePassword()); - const postgresqlDatabase = 'umami'; - const hashSalt = encrypt(generatePassword(64)); - await prisma.service.update({ - where: { id }, - data: { - type, - umami: { - create: { - umamiAdminPassword, - postgresqlDatabase, - postgresqlPassword, - postgresqlUser, - hashSalt - } - } - } - }); - } else if (type === 'hasura') { - const postgresqlUser = cuid(); - const postgresqlPassword = encrypt(generatePassword()); - const postgresqlDatabase = 'hasura'; - const graphQLAdminPassword = encrypt(generatePassword()); - await prisma.service.update({ - where: { id }, - data: { - type, - hasura: { - create: { - postgresqlDatabase, - postgresqlPassword, - postgresqlUser, - graphQLAdminPassword - } - } - } - }); - } else if (type === 'fider') { - const postgresqlUser = cuid(); - const postgresqlPassword = encrypt(generatePassword()); - const postgresqlDatabase = 'fider'; - const jwtSecret = encrypt(generatePassword(64, true)); - await prisma.service.update({ - where: { id }, - data: { - type, - fider: { - create: { - postgresqlDatabase, - postgresqlPassword, - postgresqlUser, - jwtSecret - } - } - } - }); - } else if (type === 'moodle') { - const defaultUsername = cuid(); - const defaultPassword = encrypt(generatePassword()); - const defaultEmail = `${cuid()} @example.com`; - const mariadbUser = cuid(); - const mariadbPassword = encrypt(generatePassword()); - const mariadbDatabase = 'moodle_db'; - const mariadbRootUser = cuid(); - const mariadbRootUserPassword = encrypt(generatePassword()); - await prisma.service.update({ - where: { id }, - data: { - type, - moodle: { - create: { - defaultUsername, - defaultPassword, - defaultEmail, - mariadbUser, - mariadbPassword, - mariadbDatabase, - mariadbRootUser, - mariadbRootUserPassword - } - } - } - }); - } else { - await prisma.service.update({ - where: { id }, - data: { - type - } - }); - } -} - -export async function removeService({ id }: { id: string }): Promise { - await prisma.servicePersistentStorage.deleteMany({ where: { serviceId: id } }); - await prisma.meiliSearch.deleteMany({ where: { serviceId: id } }); - await prisma.fider.deleteMany({ where: { serviceId: id } }); - await prisma.ghost.deleteMany({ where: { serviceId: id } }); - await prisma.umami.deleteMany({ where: { serviceId: id } }); - await prisma.hasura.deleteMany({ where: { serviceId: id } }); - await prisma.plausibleAnalytics.deleteMany({ where: { serviceId: id } }); - await prisma.minio.deleteMany({ where: { serviceId: id } }); - await prisma.vscodeserver.deleteMany({ where: { serviceId: id } }); - await prisma.wordpress.deleteMany({ where: { serviceId: id } }); - await prisma.serviceSecret.deleteMany({ where: { serviceId: id } }); - - await prisma.service.delete({ where: { id } }); -} - export function saveUpdateableFields(type: string, data: any) { - let update = {}; + const update = {}; if (type && serviceFields[type]) { serviceFields[type].map((k) => { let temp = data[k.name] @@ -1491,6 +1343,9 @@ export function saveUpdateableFields(type: string, data: any) { temp = Boolean(temp) } } + if (k.isNumber && temp === '') { + temp = null + } update[k.name] = temp }); } @@ -1498,7 +1353,7 @@ export function saveUpdateableFields(type: string, data: any) { } export function getUpdateableFields(type: string, data: any) { - let update = {}; + const update = {}; if (type && serviceFields[type]) { serviceFields[type].map((k) => { let temp = data[k.name] @@ -1533,9 +1388,9 @@ export const getServiceMainPort = (service: string) => { export function makeLabelForServices(type) { return [ 'coolify.managed=true', - `coolify.version = ${version} `, - `coolify.type = service`, - `coolify.service.type = ${type} ` + `coolify.version=${version}`, + `coolify.type=service`, + `coolify.service.type=${type}` ]; } export function errorHandler({ status = 500, message = 'Unknown error.' }: { status: number, message: string | any }) { @@ -1561,18 +1416,22 @@ export async function stopBuild(buildId, applicationId) { let count = 0; await new Promise(async (resolve, reject) => { const { destinationDockerId, status } = await prisma.build.findFirst({ where: { id: buildId } }); - const { engine, id: dockerId } = await prisma.destinationDocker.findFirst({ where: { id: destinationDockerId } }); - let interval = setInterval(async () => { + const { id: dockerId } = await prisma.destinationDocker.findFirst({ where: { id: destinationDockerId } }); + const interval = setInterval(async () => { try { - if (status === 'failed') { + if (status === 'failed' || status === 'canceled') { clearInterval(interval); return resolve(); } - if (count > 100) { + if (count > 15) { clearInterval(interval); - return reject(new Error('Build canceled')); + if (scheduler.workers.has('deployApplication')) { + scheduler.workers.get('deployApplication').postMessage('cancel') + } + await cleanupDB(buildId, applicationId); + return reject(new Error('Deployment canceled.')); } - const { stdout: buildContainers } = await executeDockerCmd({ dockerId, command: `docker container ls--filter "label=coolify.buildId=${buildId}" --format '{{json .}}'` }) + const { stdout: buildContainers } = await executeDockerCmd({ dockerId, command: `docker container ls --filter "label=coolify.buildId=${buildId}" --format '{{json .}}'` }) if (buildContainers) { const containersArray = buildContainers.trim().split('\n'); for (const container of containersArray) { @@ -1580,8 +1439,11 @@ export async function stopBuild(buildId, applicationId) { const id = containerObj.ID; if (!containerObj.Names.startsWith(`${applicationId} `)) { await removeContainer({ id, dockerId }); - await cleanupDB(buildId); clearInterval(interval); + if (scheduler.workers.has('deployApplication')) { + scheduler.workers.get('deployApplication').postMessage('cancel') + } + await cleanupDB(buildId, applicationId); return resolve(); } } @@ -1592,11 +1454,12 @@ export async function stopBuild(buildId, applicationId) { }); } -async function cleanupDB(buildId: string) { +async function cleanupDB(buildId: string, applicationId: string) { const data = await prisma.build.findUnique({ where: { id: buildId } }); if (data?.status === 'queued' || data?.status === 'running') { - await prisma.build.update({ where: { id: buildId }, data: { status: 'failed' } }); + await prisma.build.update({ where: { id: buildId }, data: { status: 'canceled' } }); } + await saveBuildLog({ line: 'Deployment canceled.', buildId, applicationId }); } export function convertTolOldVolumeNames(type) { @@ -1604,41 +1467,107 @@ export function convertTolOldVolumeNames(type) { return 'nc' } } -// export async function getAvailableServices(): Promise { -// const { data } = await axios.get(`https://gist.githubusercontent.com/andrasbacsai/4aac36d8d6214dbfc34fa78110554a50/raw/5b27e6c37d78aaeedc1148d797112c827a2f43cf/availableServices.json`) -// return data -// + export async function cleanupDockerStorage(dockerId, lowDiskSpace, force) { // Cleanup old coolify images try { - let { stdout: images } = await executeDockerCmd({ dockerId, command: `docker images coollabsio/coolify --filter before="coollabsio/coolify:${version}" -q | xargs` }) + let { stdout: images } = await executeDockerCmd({ dockerId, command: `docker images coollabsio/coolify --filter before="coollabsio/coolify:${version}" -q | xargs -r` }) images = images.trim(); if (images) { - await executeDockerCmd({ dockerId, command: `docker rmi -f ${images}" -q | xargs` }) + await executeDockerCmd({ dockerId, command: `docker rmi -f ${images}" -q | xargs -r` }) } - } catch (error) { - //console.log(error); - } + } catch (error) { } if (lowDiskSpace || force) { if (isDev) { if (!force) console.log(`[DEV MODE] Low disk space: ${lowDiskSpace}`); return } try { - await executeDockerCmd({ dockerId, command: `docker container prune -f` }) - } catch (error) { - //console.log(error); - } + await executeDockerCmd({ dockerId, command: `docker container prune -f --filter "label=coolify.managed=true"` }) + } catch (error) { } try { await executeDockerCmd({ dockerId, command: `docker image prune -f` }) - } catch (error) { - //console.log(error); - } + } catch (error) { } try { await executeDockerCmd({ dockerId, command: `docker image prune -a -f` }) - } catch (error) { - //console.log(error); + } catch (error) { } + // Cleanup build caches + try { + await executeDockerCmd({ dockerId, command: `docker builder prune -a -f` }) + } catch (error) { } + } +} + +export function persistentVolumes(id, persistentStorage, config) { + let volumeSet = new Set(); + if (Object.keys(config).length > 0) { + for (const [key, value] of Object.entries(config)) { + if (value.volumes) { + for (const volume of value.volumes) { + volumeSet.add(volume); + } + } + } } -} \ No newline at end of file + const volumesArray = Array.from(volumeSet); + const persistentVolume = + persistentStorage?.map((storage) => { + return `${id}${storage.path.replace(/\//gi, '-')}:${storage.path}`; + }) || []; + + let volumes = [...persistentVolume] + if (volumesArray) volumes = [...volumesArray, ...volumes] + const composeVolumes = volumes.length > 0 && volumes.map((volume) => { + return { + [`${volume.split(':')[0]}`]: { + name: volume.split(':')[0] + } + }; + }) || [] + + const volumeMounts = Object.assign( + {}, + ...composeVolumes + ) || {} + return { volumeMounts } +} +export function defaultComposeConfiguration(network: string): any { + return { + networks: [network], + restart: 'on-failure', + deploy: { + restart_policy: { + condition: 'on-failure', + delay: '5s', + max_attempts: 10, + window: '120s' + } + } + } +} +export function decryptApplication(application: any) { + if (application) { + if (application?.gitSource?.githubApp?.clientSecret) { + application.gitSource.githubApp.clientSecret = decrypt(application.gitSource.githubApp.clientSecret) || null; + } + if (application?.gitSource?.githubApp?.webhookSecret) { + application.gitSource.githubApp.webhookSecret = decrypt(application.gitSource.githubApp.webhookSecret) || null; + } + if (application?.gitSource?.githubApp?.privateKey) { + application.gitSource.githubApp.privateKey = decrypt(application.gitSource.githubApp.privateKey) || null; + } + if (application?.gitSource?.gitlabApp?.appSecret) { + application.gitSource.gitlabApp.appSecret = decrypt(application.gitSource.gitlabApp.appSecret) || null; + } + if (application?.secrets.length > 0) { + application.secrets = application.secrets.map((s: any) => { + s.value = decrypt(s.value) || null + return s; + }); + } + + return application; + } +} diff --git a/apps/api/src/lib/docker.ts b/apps/api/src/lib/docker.ts index db2dbc3e7..f0b13d5f1 100644 --- a/apps/api/src/lib/docker.ts +++ b/apps/api/src/lib/docker.ts @@ -71,13 +71,11 @@ export async function removeContainer({ }): Promise { try { const { stdout } = await executeDockerCmd({ dockerId, command: `docker inspect --format '{{json .State}}' ${id}` }) - if (JSON.parse(stdout).Running) { await executeDockerCmd({ dockerId, command: `docker stop -t 0 ${id}` }) await executeDockerCmd({ dockerId, command: `docker rm ${id}` }) } } catch (error) { - console.log(error); throw error; } } diff --git a/apps/api/src/lib/importers/github.ts b/apps/api/src/lib/importers/github.ts index bac460eca..798931d7a 100644 --- a/apps/api/src/lib/importers/github.ts +++ b/apps/api/src/lib/importers/github.ts @@ -12,7 +12,8 @@ export default async function ({ htmlUrl, branch, buildId, - customPort + customPort, + forPublic }: { applicationId: string; workdir: string; @@ -23,41 +24,55 @@ export default async function ({ branch: string; buildId: string; customPort: number; + forPublic?: boolean; }): Promise { const { default: got } = await import('got') const url = htmlUrl.replace('https://', '').replace('http://', ''); await saveBuildLog({ line: 'GitHub importer started.', buildId, applicationId }); + if (forPublic) { + await saveBuildLog({ + line: `Cloning ${repository}:${branch} branch.`, + buildId, + applicationId + }); + await asyncExecShell( + `git clone -q -b ${branch} https://${url}/${repository}.git ${workdir}/ && cd ${workdir} && git submodule update --init --recursive && git lfs pull && cd .. ` + ); - const body = await prisma.githubApp.findUnique({ where: { id: githubAppId } }); - if (body.privateKey) body.privateKey = decrypt(body.privateKey); - const { privateKey, appId, installationId } = body + } else { + const body = await prisma.githubApp.findUnique({ where: { id: githubAppId } }); + if (body.privateKey) body.privateKey = decrypt(body.privateKey); + const { privateKey, appId, installationId } = body + const githubPrivateKey = privateKey.replace(/\\n/g, '\n').replace(/"/g, ''); - const githubPrivateKey = privateKey.replace(/\\n/g, '\n').replace(/"/g, ''); - - const payload = { - iat: Math.round(new Date().getTime() / 1000), - exp: Math.round(new Date().getTime() / 1000 + 60), - iss: appId - }; - const jwtToken = jsonwebtoken.sign(payload, githubPrivateKey, { - algorithm: 'RS256' - }); - const { token } = await got - .post(`${apiUrl}/app/installations/${installationId}/access_tokens`, { - headers: { - Authorization: `Bearer ${jwtToken}`, - Accept: 'application/vnd.github.machine-man-preview+json' - } - }) - .json(); - await saveBuildLog({ - line: `Cloning ${repository}:${branch} branch.`, - buildId, - applicationId - }); - await asyncExecShell( - `git clone -q -b ${branch} https://x-access-token:${token}@${url}/${repository}.git --config core.sshCommand="ssh -p ${customPort}" ${workdir}/ && cd ${workdir} && git submodule update --init --recursive && git lfs pull && cd .. ` - ); + const payload = { + iat: Math.round(new Date().getTime() / 1000), + exp: Math.round(new Date().getTime() / 1000 + 60), + iss: appId + }; + const jwtToken = jsonwebtoken.sign(payload, githubPrivateKey, { + algorithm: 'RS256' + }); + const { token } = await got + .post(`${apiUrl}/app/installations/${installationId}/access_tokens`, { + headers: { + Authorization: `Bearer ${jwtToken}`, + Accept: 'application/vnd.github.machine-man-preview+json' + } + }) + .json(); + await saveBuildLog({ + line: `Cloning ${repository}:${branch} branch.`, + buildId, + applicationId + }); + await asyncExecShell( + `git clone -q -b ${branch} https://x-access-token:${token}@${url}/${repository}.git --config core.sshCommand="ssh -p ${customPort}" ${workdir}/ && cd ${workdir} && git submodule update --init --recursive && git lfs pull && cd .. ` + ); + } const { stdout: commit } = await asyncExecShell(`cd ${workdir}/ && git rev-parse HEAD`); + return commit.replace('\n', ''); + + } diff --git a/apps/api/src/lib/scheduler.ts b/apps/api/src/lib/scheduler.ts index c32226bc9..ebff53e12 100644 --- a/apps/api/src/lib/scheduler.ts +++ b/apps/api/src/lib/scheduler.ts @@ -2,51 +2,29 @@ import Bree from 'bree'; import path from 'path'; import Cabin from 'cabin'; import TSBree from '@breejs/ts-worker'; -import { isDev } from './common'; + +export const isDev = process.env.NODE_ENV === 'development'; Bree.extend(TSBree); const options: any = { defaultExtension: 'js', + // logger: new Cabin(), logger: false, workerMessageHandler: async ({ name, message }) => { - if (name === 'deployApplication') { - if (message.pending === 0 && message.size === 0) { - if (message.caller === 'autoUpdater') { - if (!scheduler.workers.has('autoUpdater')) { - await scheduler.stop('deployApplication'); - await scheduler.run('autoUpdater') - } - } - if (message.caller === 'cleanupStorage') { - if (!scheduler.workers.has('cleanupStorage')) { - await scheduler.stop('deployApplication'); - await scheduler.run('cleanupStorage') - } - } - + if (name === 'deployApplication' && message?.deploying) { + if (scheduler.workers.has('autoUpdater') || scheduler.workers.has('cleanupStorage')) { + scheduler.workers.get('deployApplication').postMessage('cancel') } } }, jobs: [ - { - name: 'deployApplication' - }, - { - name: 'cleanupStorage', - }, - { - name: 'checkProxies', - interval: '10s' - }, - { - name: 'autoUpdater', - } + { name: 'infrastructure' }, + { name: 'deployApplication' }, ], }; if (isDev) options.root = path.join(__dirname, '../jobs'); - export const scheduler = new Bree(options); diff --git a/apps/api/src/lib/services.ts b/apps/api/src/lib/services.ts new file mode 100644 index 000000000..d7f0fd75e --- /dev/null +++ b/apps/api/src/lib/services.ts @@ -0,0 +1,20 @@ +import { createDirectories, getServiceFromDB, getServiceImage, getServiceMainPort, makeLabelForServices } from "./common"; + +export async function defaultServiceConfigurations({ id, teamId }) { + const service = await getServiceFromDB({ id, teamId }); + const { destinationDockerId, destinationDocker, type, serviceSecret } = service; + + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort(type); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + + const image = getServiceImage(type); + let secrets = []; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + secrets.push(`${secret.name}=${secret.value}`); + }); + } + return { ...service, network, port, workdir, image, secrets } +} \ No newline at end of file diff --git a/apps/api/src/lib/services/common.ts b/apps/api/src/lib/services/common.ts new file mode 100644 index 000000000..f6174ca69 --- /dev/null +++ b/apps/api/src/lib/services/common.ts @@ -0,0 +1,383 @@ + +import cuid from 'cuid'; +import { encrypt, generatePassword, prisma } from '../common'; + +export const includeServices: any = { + destinationDocker: true, + persistentStorage: true, + serviceSecret: true, + minio: true, + plausibleAnalytics: true, + vscodeserver: true, + wordpress: true, + ghost: true, + meiliSearch: true, + umami: true, + hasura: true, + fider: true, + moodle: true, + appwrite: true, + glitchTip: true, + searxng: true, + weblate: true, + taiga: true +}; +export async function configureServiceType({ + id, + type +}: { + id: string; + type: string; +}): Promise { + if (type === 'plausibleanalytics') { + const password = encrypt(generatePassword({})); + const postgresqlUser = cuid(); + const postgresqlPassword = encrypt(generatePassword({})); + const postgresqlDatabase = 'plausibleanalytics'; + const secretKeyBase = encrypt(generatePassword({ length: 64 })); + + await prisma.service.update({ + where: { id }, + data: { + type, + plausibleAnalytics: { + create: { + postgresqlDatabase, + postgresqlUser, + postgresqlPassword, + password, + secretKeyBase + } + } + } + }); + } else if (type === 'nocodb') { + await prisma.service.update({ + where: { id }, + data: { type } + }); + } else if (type === 'minio') { + const rootUser = cuid(); + const rootUserPassword = encrypt(generatePassword({})); + await prisma.service.update({ + where: { id }, + data: { type, minio: { create: { rootUser, rootUserPassword } } } + }); + } else if (type === 'vscodeserver') { + const password = encrypt(generatePassword({})); + await prisma.service.update({ + where: { id }, + data: { type, vscodeserver: { create: { password } } } + }); + } else if (type === 'wordpress') { + const mysqlUser = cuid(); + const mysqlPassword = encrypt(generatePassword({})); + const mysqlRootUser = cuid(); + const mysqlRootUserPassword = encrypt(generatePassword({})); + await prisma.service.update({ + where: { id }, + data: { + type, + wordpress: { create: { mysqlPassword, mysqlRootUserPassword, mysqlRootUser, mysqlUser } } + } + }); + } else if (type === 'vaultwarden') { + await prisma.service.update({ + where: { id }, + data: { + type + } + }); + } else if (type === 'languagetool') { + await prisma.service.update({ + where: { id }, + data: { + type + } + }); + } else if (type === 'n8n') { + await prisma.service.update({ + where: { id }, + data: { + type + } + }); + } else if (type === 'uptimekuma') { + await prisma.service.update({ + where: { id }, + data: { + type + } + }); + } else if (type === 'ghost') { + const defaultEmail = `${cuid()}@example.com`; + const defaultPassword = encrypt(generatePassword({})); + const mariadbUser = cuid(); + const mariadbPassword = encrypt(generatePassword({})); + const mariadbRootUser = cuid(); + const mariadbRootUserPassword = encrypt(generatePassword({})); + + await prisma.service.update({ + where: { id }, + data: { + type, + ghost: { + create: { + defaultEmail, + defaultPassword, + mariadbUser, + mariadbPassword, + mariadbRootUser, + mariadbRootUserPassword + } + } + } + }); + } else if (type === 'meilisearch') { + const masterKey = encrypt(generatePassword({ length: 32 })); + await prisma.service.update({ + where: { id }, + data: { + type, + meiliSearch: { create: { masterKey } } + } + }); + } else if (type === 'umami') { + const umamiAdminPassword = encrypt(generatePassword({})); + const postgresqlUser = cuid(); + const postgresqlPassword = encrypt(generatePassword({})); + const postgresqlDatabase = 'umami'; + const hashSalt = encrypt(generatePassword({ length: 64 })); + await prisma.service.update({ + where: { id }, + data: { + type, + umami: { + create: { + umamiAdminPassword, + postgresqlDatabase, + postgresqlPassword, + postgresqlUser, + hashSalt + } + } + } + }); + } else if (type === 'hasura') { + const postgresqlUser = cuid(); + const postgresqlPassword = encrypt(generatePassword({})); + const postgresqlDatabase = 'hasura'; + const graphQLAdminPassword = encrypt(generatePassword({})); + await prisma.service.update({ + where: { id }, + data: { + type, + hasura: { + create: { + postgresqlDatabase, + postgresqlPassword, + postgresqlUser, + graphQLAdminPassword + } + } + } + }); + } else if (type === 'fider') { + const postgresqlUser = cuid(); + const postgresqlPassword = encrypt(generatePassword({})); + const postgresqlDatabase = 'fider'; + const jwtSecret = encrypt(generatePassword({ length: 64, symbols: true })); + await prisma.service.update({ + where: { id }, + data: { + type, + fider: { + create: { + postgresqlDatabase, + postgresqlPassword, + postgresqlUser, + jwtSecret + } + } + } + }); + } else if (type === 'moodle') { + const defaultUsername = cuid(); + const defaultPassword = encrypt(generatePassword({})); + const defaultEmail = `${cuid()} @example.com`; + const mariadbUser = cuid(); + const mariadbPassword = encrypt(generatePassword({})); + const mariadbDatabase = 'moodle_db'; + const mariadbRootUser = cuid(); + const mariadbRootUserPassword = encrypt(generatePassword({})); + await prisma.service.update({ + where: { id }, + data: { + type, + moodle: { + create: { + defaultUsername, + defaultPassword, + defaultEmail, + mariadbUser, + mariadbPassword, + mariadbDatabase, + mariadbRootUser, + mariadbRootUserPassword + } + } + } + }); + } else if (type === 'appwrite') { + const opensslKeyV1 = encrypt(generatePassword({})); + const executorSecret = encrypt(generatePassword({})); + const redisPassword = encrypt(generatePassword({})); + const mariadbHost = `${id}-mariadb` + const mariadbUser = cuid(); + const mariadbPassword = encrypt(generatePassword({})); + const mariadbDatabase = 'appwrite'; + const mariadbRootUser = cuid(); + const mariadbRootUserPassword = encrypt(generatePassword({})); + await prisma.service.update({ + where: { id }, + data: { + type, + appwrite: { + create: { + opensslKeyV1, + executorSecret, + redisPassword, + mariadbHost, + mariadbUser, + mariadbPassword, + mariadbDatabase, + mariadbRootUser, + mariadbRootUserPassword + } + } + } + }); + } else if (type === 'glitchTip') { + const defaultUsername = cuid(); + const defaultEmail = `${defaultUsername}@example.com`; + const defaultPassword = encrypt(generatePassword({})); + const postgresqlUser = cuid(); + const postgresqlPassword = encrypt(generatePassword({})); + const postgresqlDatabase = 'glitchTip'; + const secretKeyBase = encrypt(generatePassword({ length: 64 })); + + await prisma.service.update({ + where: { id }, + data: { + type, + glitchTip: { + create: { + postgresqlDatabase, + postgresqlUser, + postgresqlPassword, + secretKeyBase, + defaultEmail, + defaultUsername, + defaultPassword, + } + } + } + }); + } else if (type === 'searxng') { + const secretKey = encrypt(generatePassword({ length: 32, isHex: true })) + const redisPassword = encrypt(generatePassword({})); + await prisma.service.update({ + where: { id }, + data: { + type, + searxng: { + create: { + secretKey, + redisPassword, + } + } + } + }); + } else if (type === 'weblate') { + const adminPassword = encrypt(generatePassword({})) + const postgresqlUser = cuid(); + const postgresqlPassword = encrypt(generatePassword({})); + const postgresqlDatabase = 'weblate'; + await prisma.service.update({ + where: { id }, + data: { + type, + weblate: { + create: { + adminPassword, + postgresqlHost: `${id}-postgresql`, + postgresqlPort: 5432, + postgresqlUser, + postgresqlPassword, + postgresqlDatabase, + } + } + } + }); + } else if (type === 'taiga') { + const secretKey = encrypt(generatePassword({})) + const erlangSecret = encrypt(generatePassword({})) + const rabbitMQUser = cuid(); + const djangoAdminUser = cuid(); + const djangoAdminPassword = encrypt(generatePassword({})) + const rabbitMQPassword = encrypt(generatePassword({})) + const postgresqlUser = cuid(); + const postgresqlPassword = encrypt(generatePassword({})); + const postgresqlDatabase = 'taiga'; + await prisma.service.update({ + where: { id }, + data: { + type, + taiga: { + create: { + secretKey, + erlangSecret, + djangoAdminUser, + djangoAdminPassword, + rabbitMQUser, + rabbitMQPassword, + postgresqlHost: `${id}-postgresql`, + postgresqlPort: 5432, + postgresqlUser, + postgresqlPassword, + postgresqlDatabase, + } + } + } + }); + } else { + await prisma.service.update({ + where: { id }, + data: { + type + } + }); + } +} + +export async function removeService({ id }: { id: string }): Promise { + await prisma.serviceSecret.deleteMany({ where: { serviceId: id } }); + await prisma.servicePersistentStorage.deleteMany({ where: { serviceId: id } }); + await prisma.meiliSearch.deleteMany({ where: { serviceId: id } }); + await prisma.fider.deleteMany({ where: { serviceId: id } }); + await prisma.ghost.deleteMany({ where: { serviceId: id } }); + await prisma.umami.deleteMany({ where: { serviceId: id } }); + await prisma.hasura.deleteMany({ where: { serviceId: id } }); + await prisma.plausibleAnalytics.deleteMany({ where: { serviceId: id } }); + await prisma.minio.deleteMany({ where: { serviceId: id } }); + await prisma.vscodeserver.deleteMany({ where: { serviceId: id } }); + await prisma.wordpress.deleteMany({ where: { serviceId: id } }); + await prisma.glitchTip.deleteMany({ where: { serviceId: id } }); + await prisma.moodle.deleteMany({ where: { serviceId: id } }); + await prisma.appwrite.deleteMany({ where: { serviceId: id } }); + await prisma.searxng.deleteMany({ where: { serviceId: id } }); + await prisma.weblate.deleteMany({ where: { serviceId: id } }); + await prisma.taiga.deleteMany({ where: { serviceId: id } }); + + await prisma.service.delete({ where: { id } }); +} \ No newline at end of file diff --git a/apps/api/src/lib/services/handlers.ts b/apps/api/src/lib/services/handlers.ts new file mode 100644 index 000000000..f56657ce7 --- /dev/null +++ b/apps/api/src/lib/services/handlers.ts @@ -0,0 +1,2592 @@ +import type { FastifyReply, FastifyRequest } from 'fastify'; +import fs from 'fs/promises'; +import yaml from 'js-yaml'; +import bcrypt from 'bcryptjs'; +import { ServiceStartStop } from '../../routes/api/v1/services/types'; +import { asyncSleep, ComposeFile, createDirectories, defaultComposeConfiguration, errorHandler, executeDockerCmd, getDomain, getFreePublicPort, getServiceFromDB, getServiceImage, getServiceMainPort, isARM, isDev, makeLabelForServices, persistentVolumes, prisma } from '../common'; +import { defaultServiceConfigurations } from '../services'; + +export async function startService(request: FastifyRequest) { + try { + const { type } = request.params + if (type === 'plausibleanalytics') { + return await startPlausibleAnalyticsService(request) + } + if (type === 'nocodb') { + return await startNocodbService(request) + } + if (type === 'minio') { + return await startMinioService(request) + } + if (type === 'vscodeserver') { + return await startVscodeService(request) + } + if (type === 'wordpress') { + return await startWordpressService(request) + } + if (type === 'vaultwarden') { + return await startVaultwardenService(request) + } + if (type === 'languagetool') { + return await startLanguageToolService(request) + } + if (type === 'n8n') { + return await startN8nService(request) + } + if (type === 'uptimekuma') { + return await startUptimekumaService(request) + } + if (type === 'ghost') { + return await startGhostService(request) + } + if (type === 'meilisearch') { + return await startMeilisearchService(request) + } + if (type === 'umami') { + return await startUmamiService(request) + } + if (type === 'hasura') { + return await startHasuraService(request) + } + if (type === 'fider') { + return await startFiderService(request) + } + if (type === 'moodle') { + return await startMoodleService(request) + } + if (type === 'appwrite') { + return await startAppWriteService(request) + } + if (type === 'glitchTip') { + return await startGlitchTipService(request) + } + if (type === 'searxng') { + return await startSearXNGService(request) + } + if (type === 'weblate') { + return await startWeblateService(request) + } + if (type === 'taiga') { + return await startTaigaService(request) + } + throw `Service type ${type} not supported.` + } catch (error) { + throw { status: 500, message: error?.message || error } + } +} +export async function stopService(request: FastifyRequest) { + try { + return await stopServiceContainers(request) + } catch (error) { + throw { status: 500, message: error?.message || error } + } +} + +async function startPlausibleAnalyticsService(request: FastifyRequest) { + try { + const { id } = request.params + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { + type, + version, + fqdn, + destinationDockerId, + destinationDocker, + serviceSecret, + persistentStorage, + exposePort, + plausibleAnalytics: { + id: plausibleDbId, + username, + email, + password, + postgresqlDatabase, + postgresqlPassword, + postgresqlUser, + secretKeyBase + } + } = service; + const image = getServiceImage(type); + + const config = { + plausibleAnalytics: { + image: `${image}:${version}`, + environmentVariables: { + ADMIN_USER_EMAIL: email, + ADMIN_USER_NAME: username, + ADMIN_USER_PWD: password, + BASE_URL: fqdn, + SECRET_KEY_BASE: secretKeyBase, + DISABLE_AUTH: 'false', + DISABLE_REGISTRATION: 'true', + DATABASE_URL: `postgresql://${postgresqlUser}:${postgresqlPassword}@${id}-postgresql:5432/${postgresqlDatabase}`, + CLICKHOUSE_DATABASE_URL: `http://${id}-clickhouse:8123/plausible` + } + }, + postgresql: { + volumes: [`${plausibleDbId}-postgresql-data:/bitnami/postgresql/`], + image: 'bitnami/postgresql:13.2.0', + environmentVariables: { + POSTGRESQL_PASSWORD: postgresqlPassword, + POSTGRESQL_USERNAME: postgresqlUser, + POSTGRESQL_DATABASE: postgresqlDatabase + } + }, + clickhouse: { + volumes: [`${plausibleDbId}-clickhouse-data:/var/lib/clickhouse`], + image: 'yandex/clickhouse-server:21.3.2.5', + environmentVariables: {}, + ulimits: { + nofile: { + soft: 262144, + hard: 262144 + } + } + } + }; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.plausibleAnalytics.environmentVariables[secret.name] = secret.value; + }); + } + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('plausibleanalytics'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + + const clickhouseConfigXml = ` + + + warning + true + + + + + + + + + + + + `; + const clickhouseUserConfigXml = ` + + + + 0 + 0 + + + `; + + const initQuery = 'CREATE DATABASE IF NOT EXISTS plausible;'; + const initScript = 'clickhouse client --queries-file /docker-entrypoint-initdb.d/init.query'; + await fs.writeFile(`${workdir}/clickhouse-config.xml`, clickhouseConfigXml); + await fs.writeFile(`${workdir}/clickhouse-user-config.xml`, clickhouseUserConfigXml); + await fs.writeFile(`${workdir}/init.query`, initQuery); + await fs.writeFile(`${workdir}/init-db.sh`, initScript); + + const Dockerfile = ` +FROM ${config.clickhouse.image} +COPY ./clickhouse-config.xml /etc/clickhouse-server/users.d/logging.xml +COPY ./clickhouse-user-config.xml /etc/clickhouse-server/config.d/logging.xml +COPY ./init.query /docker-entrypoint-initdb.d/init.query +COPY ./init-db.sh /docker-entrypoint-initdb.d/init-db.sh`; + + await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile); + + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.plausibleAnalytics.image, + command: + 'sh -c "sleep 10 && /entrypoint.sh db createdb && /entrypoint.sh db migrate && /entrypoint.sh db init-admin && /entrypoint.sh run"', + environment: config.plausibleAnalytics.environmentVariables, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + depends_on: [`${id}-postgresql`, `${id}-clickhouse`], + labels: makeLabelForServices('plausibleAnalytics'), + ...defaultComposeConfiguration(network), + }, + [`${id}-postgresql`]: { + container_name: `${id}-postgresql`, + image: config.postgresql.image, + environment: config.postgresql.environmentVariables, + volumes: config.postgresql.volumes, + ...defaultComposeConfiguration(network), + }, + [`${id}-clickhouse`]: { + build: workdir, + container_name: `${id}-clickhouse`, + environment: config.clickhouse.environmentVariables, + volumes: config.clickhouse.volumes, + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startNocodbService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort, persistentStorage } = + service; + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('nocodb'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const config = { + nocodb: { + image: `${image}:${version}`, + volumes: [`${id}-nc:/usr/app/data`], + environmentVariables: {} + } + + }; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.nocodb.environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.nocodb.image, + volumes: config.nocodb.volumes, + environment: config.nocodb.environmentVariables, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + labels: makeLabelForServices('nocodb'), + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startMinioService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { + type, + version, + fqdn, + destinationDockerId, + destinationDocker, + persistentStorage, + exposePort, + minio: { rootUser, rootUserPassword }, + serviceSecret + } = service; + + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('minio'); + + const { service: { destinationDocker: { id: dockerId } } } = await prisma.minio.findUnique({ where: { serviceId: id }, include: { service: { include: { destinationDocker: true } } } }) + const publicPort = await getFreePublicPort(id, dockerId); + + const consolePort = 9001; + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const config = { + minio: { + image: `${image}:${version}`, + volumes: [`${id}-minio-data:/data`], + environmentVariables: { + MINIO_SERVER_URL: fqdn, + MINIO_DOMAIN: getDomain(fqdn), + MINIO_ROOT_USER: rootUser, + MINIO_ROOT_PASSWORD: rootUserPassword, + MINIO_BROWSER_REDIRECT_URL: fqdn + } + } + + }; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.minio.environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.minio.image, + command: `server /data --console-address ":${consolePort}"`, + environment: config.minio.environmentVariables, + volumes: config.minio.volumes, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + labels: makeLabelForServices('minio'), + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + await prisma.minio.update({ where: { serviceId: id }, data: { publicPort } }); + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startVscodeService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { + type, + version, + destinationDockerId, + destinationDocker, + serviceSecret, + persistentStorage, + exposePort, + vscodeserver: { password } + } = service; + + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('vscodeserver'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const config = { + vscodeserver: { + image: `${image}:${version}`, + volumes: [`${id}-vscodeserver-data:/home/coder`], + environmentVariables: { + PASSWORD: password + } + } + + }; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.vscodeserver.environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.vscodeserver.image, + environment: config.vscodeserver.environmentVariables, + volumes: config.vscodeserver.volumes, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + labels: makeLabelForServices('vscodeServer'), + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + + const changePermissionOn = persistentStorage.map((p) => p.path); + if (changePermissionOn.length > 0) { + await executeDockerCmd({ + dockerId: destinationDocker.id, command: `docker exec -u root ${id} chown -R 1000:1000 ${changePermissionOn.join( + ' ' + )}` + }) + } + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startWordpressService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { + arch, + type, + version, + destinationDockerId, + serviceSecret, + destinationDocker, + persistentStorage, + exposePort, + wordpress: { + mysqlDatabase, + mysqlHost, + mysqlPort, + mysqlUser, + mysqlPassword, + extraConfig, + mysqlRootUser, + mysqlRootUserPassword, + ownMysql + } + } = service; + + const network = destinationDockerId && destinationDocker.network; + const image = getServiceImage(type); + const port = getServiceMainPort('wordpress'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const config = { + wordpress: { + image: `${image}:${version}`, + volumes: [`${id}-wordpress-data:/var/www/html`], + environmentVariables: { + WORDPRESS_DB_HOST: ownMysql ? `${mysqlHost}:${mysqlPort}` : `${id}-mysql`, + WORDPRESS_DB_USER: mysqlUser, + WORDPRESS_DB_PASSWORD: mysqlPassword, + WORDPRESS_DB_NAME: mysqlDatabase, + WORDPRESS_CONFIG_EXTRA: extraConfig + } + }, + mysql: { + image: `bitnami/mysql:5.7`, + volumes: [`${id}-mysql-data:/bitnami/mysql/data`], + environmentVariables: { + MYSQL_ROOT_PASSWORD: mysqlRootUserPassword, + MYSQL_ROOT_USER: mysqlRootUser, + MYSQL_USER: mysqlUser, + MYSQL_PASSWORD: mysqlPassword, + MYSQL_DATABASE: mysqlDatabase + } + } + }; + if (isARM(arch)) { + config.mysql.image = 'mysql:5.7' + config.mysql.volumes = [`${id}-mysql-data:/var/lib/mysql`] + } + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.wordpress.environmentVariables[secret.name] = secret.value; + }); + } + + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.wordpress.image, + environment: config.wordpress.environmentVariables, + volumes: config.wordpress.volumes, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + labels: makeLabelForServices('wordpress'), + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + if (!ownMysql) { + composeFile.services[id].depends_on = [`${id}-mysql`]; + composeFile.services[`${id}-mysql`] = { + container_name: `${id}-mysql`, + image: config.mysql.image, + volumes: config.mysql.volumes, + environment: config.mysql.environmentVariables, + ...defaultComposeConfiguration(network), + }; + } + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startVaultwardenService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort, persistentStorage } = + service; + + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('vaultwarden'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const config = { + vaultwarden: { + image: `${image}:${version}`, + volumes: [`${id}-vaultwarden-data:/data/`], + environmentVariables: {} + } + + }; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.vaultwarden.environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.vaultwarden.image, + environment: config.vaultwarden.environmentVariables, + volumes: config.vaultwarden.volumes, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + labels: makeLabelForServices('vaultWarden'), + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startLanguageToolService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort, persistentStorage } = + service; + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('languagetool'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const config = { + languagetool: { + image: `${image}:${version}`, + volumes: [`${id}-ngrams:/ngrams`], + environmentVariables: {} + } + }; + + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.languagetool.environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.languagetool.image, + environment: config.languagetool.environmentVariables, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + volumes: config.languagetool, + labels: makeLabelForServices('languagetool'), + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startN8nService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort, persistentStorage } = + service; + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('n8n'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const config = { + n8n: { + image: `${image}:${version}`, + volumes: [`${id}-n8n:/root/.n8n`], + environmentVariables: { + WEBHOOK_URL: `${service.fqdn}` + } + } + }; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.n8n.environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.n8n.image, + volumes: config.n8n, + environment: config.n8n.environmentVariables, + labels: makeLabelForServices('n8n'), + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startUptimekumaService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort, persistentStorage } = + service; + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('uptimekuma'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const config = { + uptimekuma: { + image: `${image}:${version}`, + volumes: [`${id}-uptimekuma:/app/data`], + environmentVariables: {} + } + }; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.uptimekuma.environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.uptimekuma.image, + volumes: config.uptimekuma.volumes, + environment: config.uptimekuma.environmentVariables, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + labels: makeLabelForServices('uptimekuma'), + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startGhostService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { + type, + version, + destinationDockerId, + destinationDocker, + serviceSecret, + persistentStorage, + exposePort, + fqdn, + ghost: { + defaultEmail, + defaultPassword, + mariadbRootUser, + mariadbRootUserPassword, + mariadbDatabase, + mariadbPassword, + mariadbUser + } + } = service; + const network = destinationDockerId && destinationDocker.network; + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + const domain = getDomain(fqdn); + const port = getServiceMainPort('ghost'); + const isHttps = fqdn.startsWith('https://'); + const config = { + ghost: { + image: `${image}:${version}`, + volumes: [`${id}-ghost:/bitnami/ghost`], + environmentVariables: { + url: fqdn, + GHOST_HOST: domain, + GHOST_ENABLE_HTTPS: isHttps ? 'yes' : 'no', + GHOST_EMAIL: defaultEmail, + GHOST_PASSWORD: defaultPassword, + GHOST_DATABASE_HOST: `${id}-mariadb`, + GHOST_DATABASE_USER: mariadbUser, + GHOST_DATABASE_PASSWORD: mariadbPassword, + GHOST_DATABASE_NAME: mariadbDatabase, + GHOST_DATABASE_PORT_NUMBER: 3306 + } + }, + mariadb: { + image: `bitnami/mariadb:latest`, + volumes: [`${id}-mariadb:/bitnami/mariadb`], + environmentVariables: { + MARIADB_USER: mariadbUser, + MARIADB_PASSWORD: mariadbPassword, + MARIADB_DATABASE: mariadbDatabase, + MARIADB_ROOT_USER: mariadbRootUser, + MARIADB_ROOT_PASSWORD: mariadbRootUserPassword + } + } + }; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.ghost.environmentVariables[secret.name] = secret.value; + }); + } + + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.ghost.image, + volumes: config.ghost.volumes, + environment: config.ghost.environmentVariables, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + labels: makeLabelForServices('ghost'), + depends_on: [`${id}-mariadb`], + ...defaultComposeConfiguration(network), + }, + [`${id}-mariadb`]: { + container_name: `${id}-mariadb`, + image: config.mariadb.image, + volumes: config.mariadb.volumes, + environment: config.mariadb.environmentVariables, + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startMeilisearchService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { + meiliSearch: { masterKey } + } = service; + const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort, persistentStorage } = + service; + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('meilisearch'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const config = { + meilisearch: { + image: `${image}:${version}`, + volumes: [`${id}-datams:/data.ms`], + environmentVariables: { + MEILI_MASTER_KEY: masterKey + } + } + }; + + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.meilisearch.environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.meilisearch.image, + environment: config.meilisearch.environmentVariables, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + volumes: config.meilisearch.volumes, + labels: makeLabelForServices('meilisearch'), + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startUmamiService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { + type, + version, + destinationDockerId, + destinationDocker, + serviceSecret, + persistentStorage, + exposePort, + umami: { + umamiAdminPassword, + postgresqlUser, + postgresqlPassword, + postgresqlDatabase, + hashSalt + } + } = service; + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('umami'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const config = { + umami: { + image: `${image}:${version}`, + environmentVariables: { + DATABASE_URL: `postgresql://${postgresqlUser}:${postgresqlPassword}@${id}-postgresql:5432/${postgresqlDatabase}`, + DATABASE_TYPE: 'postgresql', + HASH_SALT: hashSalt + } + }, + postgresql: { + image: 'postgres:12-alpine', + volumes: [`${id}-postgresql-data:/var/lib/postgresql/data`], + environmentVariables: { + POSTGRES_USER: postgresqlUser, + POSTGRES_PASSWORD: postgresqlPassword, + POSTGRES_DB: postgresqlDatabase + } + } + }; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.umami.environmentVariables[secret.name] = secret.value; + }); + } + + const initDbSQL = ` + drop table if exists event; + drop table if exists pageview; + drop table if exists session; + drop table if exists website; + drop table if exists account; + + create table account ( + user_id serial primary key, + username varchar(255) unique not null, + password varchar(60) not null, + is_admin bool not null default false, + created_at timestamp with time zone default current_timestamp, + updated_at timestamp with time zone default current_timestamp + ); + + create table website ( + website_id serial primary key, + website_uuid uuid unique not null, + user_id int not null references account(user_id) on delete cascade, + name varchar(100) not null, + domain varchar(500), + share_id varchar(64) unique, + created_at timestamp with time zone default current_timestamp + ); + + create table session ( + session_id serial primary key, + session_uuid uuid unique not null, + website_id int not null references website(website_id) on delete cascade, + created_at timestamp with time zone default current_timestamp, + hostname varchar(100), + browser varchar(20), + os varchar(20), + device varchar(20), + screen varchar(11), + language varchar(35), + country char(2) + ); + + create table pageview ( + view_id serial primary key, + website_id int not null references website(website_id) on delete cascade, + session_id int not null references session(session_id) on delete cascade, + created_at timestamp with time zone default current_timestamp, + url varchar(500) not null, + referrer varchar(500) + ); + + create table event ( + event_id serial primary key, + website_id int not null references website(website_id) on delete cascade, + session_id int not null references session(session_id) on delete cascade, + created_at timestamp with time zone default current_timestamp, + url varchar(500) not null, + event_type varchar(50) not null, + event_value varchar(50) not null + ); + + create index website_user_id_idx on website(user_id); + + create index session_created_at_idx on session(created_at); + create index session_website_id_idx on session(website_id); + + create index pageview_created_at_idx on pageview(created_at); + create index pageview_website_id_idx on pageview(website_id); + create index pageview_session_id_idx on pageview(session_id); + create index pageview_website_id_created_at_idx on pageview(website_id, created_at); + create index pageview_website_id_session_id_created_at_idx on pageview(website_id, session_id, created_at); + + create index event_created_at_idx on event(created_at); + create index event_website_id_idx on event(website_id); + create index event_session_id_idx on event(session_id); + + insert into account (username, password, is_admin) values ('admin', '${bcrypt.hashSync( + umamiAdminPassword, + 10 + )}', true);`; + await fs.writeFile(`${workdir}/schema.postgresql.sql`, initDbSQL); + const Dockerfile = ` + FROM ${config.postgresql.image} + COPY ./schema.postgresql.sql /docker-entrypoint-initdb.d/schema.postgresql.sql`; + await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile); + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.umami.image, + environment: config.umami.environmentVariables, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + labels: makeLabelForServices('umami'), + depends_on: [`${id}-postgresql`], + ...defaultComposeConfiguration(network), + }, + [`${id}-postgresql`]: { + build: workdir, + container_name: `${id}-postgresql`, + environment: config.postgresql.environmentVariables, + volumes: config.postgresql.volumes, + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + console.log(composeFile) + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startHasuraService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { + type, + version, + destinationDockerId, + destinationDocker, + persistentStorage, + serviceSecret, + exposePort, + hasura: { postgresqlUser, postgresqlPassword, postgresqlDatabase } + } = service; + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('hasura'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const config = { + hasura: { + image: `${image}:${version}`, + environmentVariables: { + HASURA_GRAPHQL_METADATA_DATABASE_URL: `postgresql://${postgresqlUser}:${postgresqlPassword}@${id}-postgresql:5432/${postgresqlDatabase}` + } + }, + postgresql: { + image: 'postgres:12-alpine', + volumes: [`${id}-postgresql-data:/var/lib/postgresql/data`], + environmentVariables: { + POSTGRES_USER: postgresqlUser, + POSTGRES_PASSWORD: postgresqlPassword, + POSTGRES_DB: postgresqlDatabase + } + } + }; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.hasura.environmentVariables[secret.name] = secret.value; + }); + } + + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.hasura.image, + environment: config.hasura.environmentVariables, + labels: makeLabelForServices('hasura'), + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + depends_on: [`${id}-postgresql`], + ...defaultComposeConfiguration(network), + }, + [`${id}-postgresql`]: { + image: config.postgresql.image, + container_name: `${id}-postgresql`, + environment: config.postgresql.environmentVariables, + volumes: config.postgresql.volumes, + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startFiderService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { + type, + version, + fqdn, + destinationDockerId, + destinationDocker, + serviceSecret, + persistentStorage, + exposePort, + fider: { + postgresqlUser, + postgresqlPassword, + postgresqlDatabase, + jwtSecret, + emailNoreply, + emailMailgunApiKey, + emailMailgunDomain, + emailMailgunRegion, + emailSmtpHost, + emailSmtpPort, + emailSmtpUser, + emailSmtpPassword, + emailSmtpEnableStartTls + } + } = service; + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('fider'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + const config = { + fider: { + image: `${image}:${version}`, + environmentVariables: { + BASE_URL: fqdn, + DATABASE_URL: `postgresql://${postgresqlUser}:${postgresqlPassword}@${id}-postgresql:5432/${postgresqlDatabase}?sslmode=disable`, + JWT_SECRET: `${jwtSecret.replace(/\$/g, '$$$')}`, + EMAIL_NOREPLY: emailNoreply, + EMAIL_MAILGUN_API: emailMailgunApiKey, + EMAIL_MAILGUN_REGION: emailMailgunRegion, + EMAIL_MAILGUN_DOMAIN: emailMailgunDomain, + EMAIL_SMTP_HOST: emailSmtpHost, + EMAIL_SMTP_PORT: emailSmtpPort, + EMAIL_SMTP_USER: emailSmtpUser, + EMAIL_SMTP_PASSWORD: emailSmtpPassword, + EMAIL_SMTP_ENABLE_STARTTLS: emailSmtpEnableStartTls + } + }, + postgresql: { + image: 'postgres:12-alpine', + volumes: [`${id}-postgresql-data:/var/lib/postgresql/data`], + environmentVariables: { + POSTGRES_USER: postgresqlUser, + POSTGRES_PASSWORD: postgresqlPassword, + POSTGRES_DB: postgresqlDatabase + } + } + }; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.fider.environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.fider.image, + environment: config.fider.environmentVariables, + labels: makeLabelForServices('fider'), + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + depends_on: [`${id}-postgresql`], + ...defaultComposeConfiguration(network), + }, + [`${id}-postgresql`]: { + image: config.postgresql.image, + container_name: `${id}-postgresql`, + environment: config.postgresql.environmentVariables, + volumes: config.postgresql.volumes, + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startAppWriteService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const { version, fqdn, destinationDocker, secrets, exposePort, network, port, workdir, image, appwrite } = await defaultServiceConfigurations({ id, teamId }) + + let isStatsEnabled = false + if (secrets.find(s => s === '_APP_USAGE_STATS=enabled')) { + isStatsEnabled = true + } + const { + opensslKeyV1, + executorSecret, + mariadbHost, + mariadbPort, + mariadbUser, + mariadbPassword, + mariadbRootUser, + mariadbRootUserPassword, + mariadbDatabase + } = appwrite; + + const dockerCompose = { + [id]: { + image: `${image}:${version}`, + container_name: id, + labels: makeLabelForServices('appwrite'), + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + volumes: [ + `${id}-uploads:/storage/uploads:rw`, + `${id}-cache:/storage/cache:rw`, + `${id}-config:/storage/config:rw`, + `${id}-certificates:/storage/certificates:rw`, + `${id}-functions:/storage/functions:rw` + ], + depends_on: [ + `${id}-mariadb`, + `${id}-redis`, + ], + environment: [ + "_APP_ENV=production", + "_APP_LOCALE=en", + `_APP_OPENSSL_KEY_V1=${opensslKeyV1}`, + `_APP_DOMAIN=${fqdn}`, + `_APP_DOMAIN_TARGET=${fqdn}`, + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + `_APP_DB_HOST=${mariadbHost}`, + `_APP_DB_PORT=${mariadbPort}`, + `_APP_DB_SCHEMA=${mariadbDatabase}`, + `_APP_DB_USER=${mariadbUser}`, + `_APP_DB_PASS=${mariadbPassword}`, + `_APP_INFLUXDB_HOST=${id}-influxdb`, + "_APP_INFLUXDB_PORT=8086", + `_APP_EXECUTOR_SECRET=${executorSecret}`, + `_APP_EXECUTOR_HOST=http://${id}-executor/v1`, + `_APP_STATSD_HOST=${id}-telegraf`, + "_APP_STATSD_PORT=8125", + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-realtime`]: { + image: `${image}:${version}`, + container_name: `${id}-realtime`, + entrypoint: "realtime", + labels: makeLabelForServices('appwrite'), + depends_on: [ + `${id}-mariadb`, + `${id}-redis`, + ], + environment: [ + "_APP_ENV=production", + `_APP_OPENSSL_KEY_V1=${opensslKeyV1}`, + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + `_APP_DB_HOST=${mariadbHost}`, + `_APP_DB_PORT=${mariadbPort}`, + `_APP_DB_SCHEMA=${mariadbDatabase}`, + `_APP_DB_USER=${mariadbUser}`, + `_APP_DB_PASS=${mariadbPassword}`, + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-worker-audits`]: { + image: `${image}:${version}`, + container_name: `${id}-worker-audits`, + labels: makeLabelForServices('appwrite'), + entrypoint: "worker-audits", + depends_on: [ + `${id}-mariadb`, + `${id}-redis`, + ], + environment: [ + "_APP_ENV=production", + `_APP_OPENSSL_KEY_V1=${opensslKeyV1}`, + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + `_APP_DB_HOST=${mariadbHost}`, + `_APP_DB_PORT=${mariadbPort}`, + `_APP_DB_SCHEMA=${mariadbDatabase}`, + `_APP_DB_USER=${mariadbUser}`, + `_APP_DB_PASS=${mariadbPassword}`, + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-worker-webhooks`]: { + image: `${image}:${version}`, + container_name: `${id}-worker-webhooks`, + labels: makeLabelForServices('appwrite'), + entrypoint: "worker-webhooks", + depends_on: [ + `${id}-mariadb`, + `${id}-redis`, + ], + environment: [ + "_APP_ENV=production", + `_APP_OPENSSL_KEY_V1=${opensslKeyV1}`, + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-worker-deletes`]: { + image: `${image}:${version}`, + container_name: `${id}-worker-deletes`, + labels: makeLabelForServices('appwrite'), + entrypoint: "worker-deletes", + depends_on: [ + `${id}-mariadb`, + `${id}-redis`, + ], + volumes: [ + `${id}-uploads:/storage/uploads:rw`, + `${id}-cache:/storage/cache:rw`, + `${id}-config:/storage/config:rw`, + `${id}-certificates:/storage/certificates:rw`, + `${id}-functions:/storage/functions:rw`, + `${id}-builds:/storage/builds:rw`, + ], + "environment": [ + "_APP_ENV=production", + `_APP_OPENSSL_KEY_V1=${opensslKeyV1}`, + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + `_APP_DB_HOST=${mariadbHost}`, + `_APP_DB_PORT=${mariadbPort}`, + `_APP_DB_SCHEMA=${mariadbDatabase}`, + `_APP_DB_USER=${mariadbUser}`, + `_APP_DB_PASS=${mariadbPassword}`, + `_APP_EXECUTOR_SECRET=${executorSecret}`, + `_APP_EXECUTOR_HOST=http://${id}-executor/v1`, + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-worker-databases`]: { + image: `${image}:${version}`, + container_name: `${id}-worker-databases`, + labels: makeLabelForServices('appwrite'), + entrypoint: "worker-databases", + depends_on: [ + `${id}-mariadb`, + `${id}-redis`, + ], + environment: [ + "_APP_ENV=production", + `_APP_OPENSSL_KEY_V1=${opensslKeyV1}`, + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + `_APP_DB_HOST=${mariadbHost}`, + `_APP_DB_PORT=${mariadbPort}`, + `_APP_DB_SCHEMA=${mariadbDatabase}`, + `_APP_DB_USER=${mariadbUser}`, + `_APP_DB_PASS=${mariadbPassword}`, + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-worker-builds`]: { + image: `${image}:${version}`, + container_name: `${id}-worker-builds`, + labels: makeLabelForServices('appwrite'), + entrypoint: "worker-builds", + depends_on: [ + `${id}-mariadb`, + `${id}-redis`, + ], + environment: [ + "_APP_ENV=production", + `_APP_OPENSSL_KEY_V1=${opensslKeyV1}`, + `_APP_EXECUTOR_SECRET=${executorSecret}`, + `_APP_EXECUTOR_HOST=http://${id}-executor/v1`, + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + `_APP_DB_HOST=${mariadbHost}`, + `_APP_DB_PORT=${mariadbPort}`, + `_APP_DB_SCHEMA=${mariadbDatabase}`, + `_APP_DB_USER=${mariadbUser}`, + `_APP_DB_PASS=${mariadbPassword}`, + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-worker-certificates`]: { + image: `${image}:${version}`, + container_name: `${id}-worker-certificates`, + labels: makeLabelForServices('appwrite'), + entrypoint: "worker-certificates", + depends_on: [ + `${id}-mariadb`, + `${id}-redis`, + ], + volumes: [ + `${id}-config:/storage/config:rw`, + `${id}-certificates:/storage/certificates:rw`, + ], + environment: [ + "_APP_ENV=production", + `_APP_OPENSSL_KEY_V1=${opensslKeyV1}`, + `_APP_DOMAIN=${fqdn}`, + `_APP_DOMAIN_TARGET=${fqdn}`, + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + `_APP_DB_HOST=${mariadbHost}`, + `_APP_DB_PORT=${mariadbPort}`, + `_APP_DB_SCHEMA=${mariadbDatabase}`, + `_APP_DB_USER=${mariadbUser}`, + `_APP_DB_PASS=${mariadbPassword}`, + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-worker-functions`]: { + image: `${image}:${version}`, + container_name: `${id}-worker-functions`, + labels: makeLabelForServices('appwrite'), + entrypoint: "worker-functions", + depends_on: [ + `${id}-mariadb`, + `${id}-redis`, + `${id}-executor` + ], + environment: [ + "_APP_ENV=production", + `_APP_OPENSSL_KEY_V1=${opensslKeyV1}`, + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + `_APP_DB_HOST=${mariadbHost}`, + `_APP_DB_PORT=${mariadbPort}`, + `_APP_DB_SCHEMA=${mariadbDatabase}`, + `_APP_DB_USER=${mariadbUser}`, + `_APP_DB_PASS=${mariadbPassword}`, + `_APP_EXECUTOR_SECRET=${executorSecret}`, + `_APP_EXECUTOR_HOST=http://${id}-executor/v1`, + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-executor`]: { + image: `${image}:${version}`, + container_name: `${id}-executor`, + labels: makeLabelForServices('appwrite'), + entrypoint: "executor", + stop_signal: "SIGINT", + volumes: [ + `${id}-functions:/storage/functions:rw`, + `${id}-builds:/storage/builds:rw`, + "/var/run/docker.sock:/var/run/docker.sock", + "/tmp:/tmp:rw" + ], + depends_on: [ + `${id}-mariadb`, + `${id}-redis`, + `${id}` + ], + environment: [ + "_APP_ENV=production", + `_APP_EXECUTOR_SECRET=${executorSecret}`, + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-worker-mails`]: { + image: `${image}:${version}`, + container_name: `${id}-worker-mails`, + labels: makeLabelForServices('appwrite'), + entrypoint: "worker-mails", + depends_on: [ + `${id}-redis`, + ], + environment: [ + "_APP_ENV=production", + `_APP_OPENSSL_KEY_V1=${opensslKeyV1}`, + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-worker-messaging`]: { + image: `${image}:${version}`, + container_name: `${id}-worker-messaging`, + labels: makeLabelForServices('appwrite'), + entrypoint: "worker-messaging", + depends_on: [ + `${id}-redis`, + ], + environment: [ + "_APP_ENV=production", + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-maintenance`]: { + image: `${image}:${version}`, + container_name: `${id}-maintenance`, + labels: makeLabelForServices('appwrite'), + entrypoint: "maintenance", + depends_on: [ + `${id}-redis`, + ], + environment: [ + "_APP_ENV=production", + `_APP_OPENSSL_KEY_V1=${opensslKeyV1}`, + `_APP_DOMAIN=${fqdn}`, + `_APP_DOMAIN_TARGET=${fqdn}`, + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + `_APP_DB_HOST=${mariadbHost}`, + `_APP_DB_PORT=${mariadbPort}`, + `_APP_DB_SCHEMA=${mariadbDatabase}`, + `_APP_DB_USER=${mariadbUser}`, + `_APP_DB_PASS=${mariadbPassword}`, + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-schedule`]: { + image: `${image}:${version}`, + container_name: `${id}-schedule`, + labels: makeLabelForServices('appwrite'), + entrypoint: "schedule", + depends_on: [ + `${id}-redis`, + ], + environment: [ + "_APP_ENV=production", + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + ...secrets + ], + ...defaultComposeConfiguration(network), + }, + [`${id}-mariadb`]: { + image: "mariadb:10.7", + container_name: `${id}-mariadb`, + labels: makeLabelForServices('appwrite'), + volumes: [ + `${id}-mariadb:/var/lib/mysql:rw` + ], + environment: [ + `MYSQL_ROOT_USER=${mariadbRootUser}`, + `MYSQL_ROOT_PASSWORD=${mariadbRootUserPassword}`, + `MYSQL_USER=${mariadbUser}`, + `MYSQL_PASSWORD=${mariadbPassword}`, + `MYSQL_DATABASE=${mariadbDatabase}` + ], + command: "mysqld --innodb-flush-method=fsync", + ...defaultComposeConfiguration(network), + }, + [`${id}-redis`]: { + image: "redis:6.2-alpine", + container_name: `${id}-redis`, + command: `redis-server --maxmemory 512mb --maxmemory-policy allkeys-lru --maxmemory-samples 5\n`, + volumes: [ + `${id}-redis:/data:rw` + ], + ...defaultComposeConfiguration(network), + }, + + }; + if (isStatsEnabled) { + dockerCompose[id].depends_on.push(`${id}-influxdb`); + dockerCompose[`${id}-usage`] = { + image: `${image}:${version}`, + container_name: `${id}-usage`, + labels: makeLabelForServices('appwrite'), + entrypoint: "usage", + depends_on: [ + `${id}-mariadb`, + `${id}-influxdb`, + ], + environment: [ + "_APP_ENV=production", + `_APP_OPENSSL_KEY_V1=${opensslKeyV1}`, + `_APP_DB_HOST=${mariadbHost}`, + `_APP_DB_PORT=${mariadbPort}`, + `_APP_DB_SCHEMA=${mariadbDatabase}`, + `_APP_DB_USER=${mariadbUser}`, + `_APP_DB_PASS=${mariadbPassword}`, + `_APP_INFLUXDB_HOST=${id}-influxdb`, + "_APP_INFLUXDB_PORT=8086", + `_APP_REDIS_HOST=${id}-redis`, + "_APP_REDIS_PORT=6379", + ...secrets + ], + ...defaultComposeConfiguration(network), + } + dockerCompose[`${id}-influxdb`] = { + image: "appwrite/influxdb:1.5.0", + container_name: `${id}-influxdb`, + volumes: [ + `${id}-influxdb:/var/lib/influxdb:rw` + ], + ...defaultComposeConfiguration(network), + } + dockerCompose[`${id}-telegraf`] = { + image: "appwrite/telegraf:1.4.0", + container_name: `${id}-telegraf`, + environment: [ + `_APP_INFLUXDB_HOST=${id}-influxdb`, + "_APP_INFLUXDB_PORT=8086", + ], + ...defaultComposeConfiguration(network), + } + } + + const composeFile: any = { + version: '3.8', + services: dockerCompose, + networks: { + [network]: { + external: true + } + }, + volumes: { + [`${id}-uploads`]: { + name: `${id}-uploads` + }, + [`${id}-cache`]: { + name: `${id}-cache` + }, + [`${id}-config`]: { + name: `${id}-config` + }, + [`${id}-certificates`]: { + name: `${id}-certificates` + }, + [`${id}-functions`]: { + name: `${id}-functions` + }, + [`${id}-builds`]: { + name: `${id}-builds` + }, + [`${id}-mariadb`]: { + name: `${id}-mariadb` + }, + [`${id}-redis`]: { + name: `${id}-redis` + }, + [`${id}-influxdb`]: { + name: `${id}-influxdb` + } + } + + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} +async function startServiceContainers(dockerId, composeFileDestination) { + await executeDockerCmd({ dockerId, command: `docker compose -f ${composeFileDestination} pull` }) + await executeDockerCmd({ dockerId, command: `docker compose -f ${composeFileDestination} build --no-cache` }) + await executeDockerCmd({ dockerId, command: `docker compose -f ${composeFileDestination} create` }) + await executeDockerCmd({ dockerId, command: `docker compose -f ${composeFileDestination} start` }) + await asyncSleep(1000); + await executeDockerCmd({ dockerId, command: `docker compose -f ${composeFileDestination} up -d` }) +} +async function stopServiceContainers(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const { destinationDockerId } = await getServiceFromDB({ id, teamId }); + if (destinationDockerId) { + await executeDockerCmd({ + dockerId: destinationDockerId, + command: `docker ps -a --filter 'label=com.docker.compose.project=${id}' --format {{.ID}}|xargs -n 1 docker stop -t 0` + }) + await executeDockerCmd({ + dockerId: destinationDockerId, + command: `docker ps -a --filter 'label=com.docker.compose.project=${id}' --format {{.ID}}|xargs -n 1 docker rm --force` + }) + return {} + } + throw { status: 500, message: 'Could not stop containers.' } + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} +async function startMoodleService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { + type, + version, + fqdn, + destinationDockerId, + destinationDocker, + serviceSecret, + persistentStorage, + exposePort, + moodle: { + defaultUsername, + defaultPassword, + defaultEmail, + mariadbRootUser, + mariadbRootUserPassword, + mariadbDatabase, + mariadbPassword, + mariadbUser + } + } = service; + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('moodle'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + const config = { + moodle: { + image: `${image}:${version}`, + volumes: [`${id}-data:/bitnami/moodle`], + environmentVariables: { + MOODLE_USERNAME: defaultUsername, + MOODLE_PASSWORD: defaultPassword, + MOODLE_EMAIL: defaultEmail, + MOODLE_DATABASE_HOST: `${id}-mariadb`, + MOODLE_DATABASE_USER: mariadbUser, + MOODLE_DATABASE_PASSWORD: mariadbPassword, + MOODLE_DATABASE_NAME: mariadbDatabase, + MOODLE_REVERSEPROXY: 'yes' + } + }, + mariadb: { + image: 'bitnami/mariadb:latest', + volumes: [`${id}-mariadb-data:/bitnami/mariadb`], + environmentVariables: { + MARIADB_USER: mariadbUser, + MARIADB_PASSWORD: mariadbPassword, + MARIADB_DATABASE: mariadbDatabase, + MARIADB_ROOT_USER: mariadbRootUser, + MARIADB_ROOT_PASSWORD: mariadbRootUserPassword + } + } + }; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.moodle.environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.moodle.image, + environment: config.moodle.environmentVariables, + volumes: config.moodle.volumes, + labels: makeLabelForServices('moodle'), + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + depends_on: [`${id}-mariadb`], + ...defaultComposeConfiguration(network), + }, + [`${id}-mariadb`]: { + container_name: `${id}-mariadb`, + image: config.mariadb.image, + environment: config.mariadb.environmentVariables, + volumes: config.mariadb.volumes, + ...defaultComposeConfiguration(network), + depends_on: [] + } + + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startGlitchTipService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { + type, + version, + fqdn, + destinationDockerId, + destinationDocker, + serviceSecret, + persistentStorage, + exposePort, + glitchTip: { + postgresqlDatabase, + postgresqlPassword, + postgresqlUser, + secretKeyBase, + defaultEmail, + defaultUsername, + defaultPassword, + defaultFromEmail, + emailSmtpHost, + emailSmtpPort, + emailSmtpUser, + emailSmtpPassword, + emailSmtpUseTls, + emailSmtpUseSsl, + emailBackend, + mailgunApiKey, + sendgridApiKey, + enableOpenUserRegistration, + } + } = service; + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('glitchTip'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const config = { + glitchTip: { + image: `${image}:${version}`, + environmentVariables: { + PORT: port, + GLITCHTIP_DOMAIN: fqdn, + SECRET_KEY: secretKeyBase, + DATABASE_URL: `postgresql://${postgresqlUser}:${postgresqlPassword}@${id}-postgresql:5432/${postgresqlDatabase}`, + REDIS_URL: `redis://${id}-redis:6379/0`, + DEFAULT_FROM_EMAIL: defaultFromEmail, + EMAIL_HOST: emailSmtpHost, + EMAIL_PORT: emailSmtpPort, + EMAIL_HOST_USER: emailSmtpUser, + EMAIL_HOST_PASSWORD: emailSmtpPassword, + EMAIL_USE_TLS: emailSmtpUseTls, + EMAIL_USE_SSL: emailSmtpUseSsl, + EMAIL_BACKEND: emailBackend, + MAILGUN_API_KEY: mailgunApiKey, + SENDGRID_API_KEY: sendgridApiKey, + ENABLE_OPEN_USER_REGISTRATION: enableOpenUserRegistration, + DJANGO_SUPERUSER_EMAIL: defaultEmail, + DJANGO_SUPERUSER_USERNAME: defaultUsername, + DJANGO_SUPERUSER_PASSWORD: defaultPassword, + } + }, + postgresql: { + image: 'postgres:14-alpine', + volumes: [`${id}-postgresql-data:/var/lib/postgresql/data`], + environmentVariables: { + POSTGRES_USER: postgresqlUser, + POSTGRES_PASSWORD: postgresqlPassword, + POSTGRES_DB: postgresqlDatabase + } + }, + redis: { + image: 'redis:7-alpine', + volumes: [`${id}-redis-data:/data`], + } + }; + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.glitchTip.environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.glitchTip.image, + environment: config.glitchTip.environmentVariables, + labels: makeLabelForServices('glitchTip'), + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + depends_on: [`${id}-postgresql`, `${id}-redis`], + ...defaultComposeConfiguration(network), + }, + [`${id}-worker`]: { + container_name: `${id}-worker`, + image: config.glitchTip.image, + command: './bin/run-celery-with-beat.sh', + environment: config.glitchTip.environmentVariables, + depends_on: [`${id}-postgresql`, `${id}-redis`], + ...defaultComposeConfiguration(network), + }, + [`${id}-setup`]: { + container_name: `${id}-setup`, + image: config.glitchTip.image, + command: 'sh -c "(./manage.py migrate || true) && (./manage.py createsuperuser --noinput || true)"', + environment: config.glitchTip.environmentVariables, + networks: [network], + restart: "no", + depends_on: [`${id}-postgresql`, `${id}-redis`] + }, + [`${id}-postgresql`]: { + image: config.postgresql.image, + container_name: `${id}-postgresql`, + environment: config.postgresql.environmentVariables, + volumes: config.postgresql.volumes, + ...defaultComposeConfiguration(network), + }, + [`${id}-redis`]: { + image: config.redis.image, + container_name: `${id}-redis`, + volumes: config.redis.volumes, + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) + await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startSearXNGService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort, persistentStorage, fqdn, searxng: { secretKey, redisPassword } } = + service; + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('searxng'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const config = { + searxng: { + image: `${image}:${version}`, + volumes: [`${id}-searxng:/etc/searxng`], + environmentVariables: { + SEARXNG_BASE_URL: `${fqdn}` + }, + }, + redis: { + image: 'redis:7-alpine', + } + }; + + const settingsYml = ` + # see https://docs.searxng.org/admin/engines/settings.html#use-default-settings + use_default_settings: true + server: + secret_key: ${secretKey} + limiter: true + image_proxy: true + ui: + static_use_hash: true + redis: + url: redis://:${redisPassword}@${id}-redis:6379/0` + + const Dockerfile = ` + FROM ${config.searxng.image} + COPY ./settings.yml /etc/searxng/settings.yml`; + + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.searxng.environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + build: workdir, + container_name: id, + volumes: config.searxng.volumes, + environment: config.searxng.environmentVariables, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + labels: makeLabelForServices('searxng'), + cap_drop: ['ALL'], + cap_add: ['CHOWN', 'SETGID', 'SETUID', 'DAC_OVERRIDE'], + depends_on: [`${id}-redis`], + ...defaultComposeConfiguration(network), + }, + [`${id}-redis`]: { + container_name: `${id}-redis`, + image: config.redis.image, + command: `redis-server --requirepass ${redisPassword} --save "" --appendonly "no"`, + labels: makeLabelForServices('searxng'), + cap_drop: ['ALL'], + cap_add: ['SETGID', 'SETUID', 'DAC_OVERRIDE'], + ...defaultComposeConfiguration(network), + }, + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile); + await fs.writeFile(`${workdir}/settings.yml`, settingsYml); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + + +async function startWeblateService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { + weblate: { adminPassword, postgresqlHost, postgresqlPort, postgresqlUser, postgresqlPassword, postgresqlDatabase } + } = service; + const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort, persistentStorage, fqdn } = + service; + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('weblate'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const config = { + weblate: { + image: `${image}:${version}`, + volumes: [`${id}-data:/app/data`], + environmentVariables: { + WEBLATE_SITE_DOMAIN: getDomain(fqdn), + WEBLATE_ADMIN_PASSWORD: adminPassword, + POSTGRES_PASSWORD: postgresqlPassword, + POSTGRES_USER: postgresqlUser, + POSTGRES_DATABASE: postgresqlDatabase, + POSTGRES_HOST: postgresqlHost, + POSTGRES_PORT: postgresqlPort, + REDIS_HOST: `${id}-redis`, + } + }, + postgresql: { + image: `postgres:14-alpine`, + volumes: [`${id}-postgresql-data:/var/lib/postgresql/data`], + environmentVariables: { + POSTGRES_PASSWORD: postgresqlPassword, + POSTGRES_USER: postgresqlUser, + POSTGRES_DB: postgresqlDatabase, + POSTGRES_HOST: postgresqlHost, + POSTGRES_PORT: postgresqlPort, + } + }, + redis: { + image: `redis:6-alpine`, + volumes: [`${id}-redis-data:/data`], + } + + }; + + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config.weblate.environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + container_name: id, + image: config.weblate.image, + environment: config.weblate.environmentVariables, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + volumes: config.weblate.volumes, + labels: makeLabelForServices('weblate'), + ...defaultComposeConfiguration(network), + }, + [`${id}-postgresql`]: { + container_name: `${id}-postgresql`, + image: config.postgresql.image, + environment: config.postgresql.environmentVariables, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + volumes: config.postgresql.volumes, + labels: makeLabelForServices('weblate'), + ...defaultComposeConfiguration(network), + }, + [`${id}-redis`]: { + container_name: `${id}-redis`, + image: config.redis.image, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + volumes: config.redis.volumes, + labels: makeLabelForServices('weblate'), + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + +async function startTaigaService(request: FastifyRequest) { + try { + const { id } = request.params; + const teamId = request.user.teamId; + const service = await getServiceFromDB({ id, teamId }); + const { + taiga: { secretKey, djangoAdminUser, djangoAdminPassword, erlangSecret, rabbitMQUser, rabbitMQPassword, postgresqlHost, postgresqlPort, postgresqlUser, postgresqlPassword, postgresqlDatabase } + } = service; + const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort, persistentStorage, fqdn } = + service; + const network = destinationDockerId && destinationDocker.network; + const port = getServiceMainPort('taiga'); + + const { workdir } = await createDirectories({ repository: type, buildId: id }); + const image = getServiceImage(type); + + const isHttps = fqdn.startsWith('https://'); + const superUserEntrypoint = `#!/bin/sh + set -e + python manage.py makemigrations + python manage.py migrate + + if [ "$DJANGO_SUPERUSER_USERNAME" ] + then + python manage.py createsuperuser \ + --noinput \ + --username $DJANGO_SUPERUSER_USERNAME \ + --email $DJANGO_SUPERUSER_EMAIL + fi + exec "$@"`; + const entrypoint = `#!/bin/sh + set -e + + /taiga-back/docker/entrypoint_superuser.sh || echo "Superuser creation failed, but continue" + /taiga-back/docker/entrypoint.sh + + exec "$@"`; + + const DockerfileBack = ` + FROM taigaio/taiga-back:latest + COPY ./entrypoint_superuser.sh /taiga-back/docker/entrypoint_superuser.sh + COPY ./entrypoint_coolify.sh /taiga-back/docker/entrypoint_coolify.sh + RUN ["chmod", "+x", "/taiga-back/docker/entrypoint_superuser.sh"] + RUN ["chmod", "+x", "/taiga-back/docker/entrypoint_coolify.sh"] + RUN ["chmod", "+x", "/taiga-back/docker/entrypoint.sh"]`; + + const DockerfileGateway = ` + FROM nginx:1.19-alpine + COPY ./nginx.conf /etc/nginx/conf.d/default.conf`; + + const nginxConf = `server { + listen 80 default_server; + + client_max_body_size 100M; + charset utf-8; + + # Frontend + location / { + proxy_pass http://${id}-taiga-front/; + proxy_pass_header Server; + proxy_set_header Host $http_host; + proxy_redirect off; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Scheme $scheme; + } + + # API + location /api/ { + proxy_pass http://${id}-taiga-back:8000/api/; + proxy_pass_header Server; + proxy_set_header Host $http_host; + proxy_redirect off; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Scheme $scheme; + } + + # Admin + location /admin/ { + proxy_pass http://${id}-taiga-back:8000/admin/; + proxy_pass_header Server; + proxy_set_header Host $http_host; + proxy_redirect off; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Scheme $scheme; + } + + # Static + location /static/ { + alias /taiga/static/; + } + + # Media + location /_protected/ { + internal; + alias /taiga/media/; + add_header Content-disposition "attachment"; + } + + # Unprotected section + location /media/exports/ { + alias /taiga/media/exports/; + add_header Content-disposition "attachment"; + } + + location /media/ { + proxy_set_header Host $http_host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Scheme $scheme; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_pass http://${id}-taiga-protected:8003/; + proxy_redirect off; + } + + # Events + location /events { + proxy_pass http://${id}-taiga-events:8888/events; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_connect_timeout 7d; + proxy_send_timeout 7d; + proxy_read_timeout 7d; + } + }` + await fs.writeFile(`${workdir}/entrypoint_superuser.sh`, superUserEntrypoint); + await fs.writeFile(`${workdir}/entrypoint_coolify.sh`, entrypoint); + await fs.writeFile(`${workdir}/DockerfileBack`, DockerfileBack); + await fs.writeFile(`${workdir}/DockerfileGateway`, DockerfileGateway); + await fs.writeFile(`${workdir}/nginx.conf`, nginxConf); + + const config = { + ['taiga-gateway']: { + volumes: [`${id}-static-data:/taiga-back/static`, `${id}-media-data:/taiga-back/media`], + }, + ['taiga-front']: { + image: `${image}:${version}`, + environmentVariables: { + TAIGA_URL: fqdn, + TAIGA_WEBSOCKETS_URL: isHttps ? `wss://${getDomain(fqdn)}` : `ws://${getDomain(fqdn)}`, + TAIGA_SUBPATH: "", + PUBLIC_REGISTER_ENABLED: isDev ? "true" : "false", + } + }, + ['taiga-back']: { + volumes: [`${id}-static-data:/taiga-back/static`, `${id}-media-data:/taiga-back/media`], + environmentVariables: { + POSTGRES_DB: postgresqlDatabase, + POSTGRES_HOST: postgresqlHost, + POSTGRES_PORT: postgresqlPort, + POSTGRES_USER: postgresqlUser, + POSTGRES_PASSWORD: postgresqlPassword, + TAIGA_SECRET_KEY: secretKey, + TAIGA_SITES_SCHEME: isHttps ? 'https' : 'http', + TAIGA_SITES_DOMAIN: getDomain(fqdn), + TAIGA_SUBPATH: "", + EVENTS_PUSH_BACKEND_URL: `amqp://${rabbitMQUser}:${rabbitMQPassword}@${id}-taiga-rabbitmq:5672/taiga`, + CELERY_BROKER_URL: `amqp://${rabbitMQUser}:${rabbitMQPassword}@${id}-taiga-rabbitmq:5672/taiga`, + RABBITMQ_USER: rabbitMQUser, + RABBITMQ_PASS: rabbitMQPassword, + ENABLE_TELEMETRY: "False", + DJANGO_SUPERUSER_EMAIL: `admin@${getDomain(fqdn)}`, + DJANGO_SUPERUSER_PASSWORD: djangoAdminPassword, + DJANGO_SUPERUSER_USERNAME: djangoAdminUser, + PUBLIC_REGISTER_ENABLED: isDev ? "True" : "False", + SESSION_COOKIE_SECURE: isDev ? "False" : "True", + CSRF_COOKIE_SECURE: isDev ? "False" : "True", + + } + }, + ['taiga-async']: { + image: `taigaio/taiga-back:latest`, + volumes: [`${id}-static-data:/taiga-back/static`, `${id}-media-data:/taiga-back/media`], + environmentVariables: { + POSTGRES_DB: postgresqlDatabase, + POSTGRES_HOST: postgresqlHost, + POSTGRES_PORT: postgresqlPort, + POSTGRES_USER: postgresqlUser, + POSTGRES_PASSWORD: postgresqlPassword, + TAIGA_SECRET_KEY: secretKey, + TAIGA_SITES_SCHEME: isHttps ? 'https' : 'http', + TAIGA_SITES_DOMAIN: getDomain(fqdn), + TAIGA_SUBPATH: "", + RABBITMQ_USER: rabbitMQUser, + RABBITMQ_PASS: rabbitMQPassword, + ENABLE_TELEMETRY: "False", + } + }, + ['taiga-rabbitmq']: { + image: `rabbitmq:3.8-management-alpine`, + volumes: [`${id}-events:/var/lib/rabbitmq`], + environmentVariables: { + RABBITMQ_ERLANG_COOKIE: erlangSecret, + RABBITMQ_DEFAULT_USER: rabbitMQUser, + RABBITMQ_DEFAULT_PASS: rabbitMQPassword, + RABBITMQ_DEFAULT_VHOST: 'taiga' + } + }, + ['taiga-protected']: { + image: `taigaio/taiga-protected:latest`, + environmentVariables: { + MAX_AGE: 360, + SECRET_KEY: secretKey, + TAIGA_URL: fqdn + } + }, + ['taiga-events']: { + image: `taigaio/taiga-events:latest`, + environmentVariables: { + RABBITMQ_URL: `amqp://${rabbitMQUser}:${rabbitMQPassword}@${id}-taiga-rabbitmq:5672/taiga`, + RABBITMQ_USER: rabbitMQUser, + RABBITMQ_PASS: rabbitMQPassword, + TAIGA_SECRET_KEY: secretKey, + } + }, + + postgresql: { + image: `postgres:12.3`, + volumes: [`${id}-postgresql-data:/var/lib/postgresql/data`], + environmentVariables: { + POSTGRES_PASSWORD: postgresqlPassword, + POSTGRES_USER: postgresqlUser, + POSTGRES_DB: postgresqlDatabase + } + } + }; + + if (serviceSecret.length > 0) { + serviceSecret.forEach((secret) => { + config['taiga-back'].environmentVariables[secret.name] = secret.value; + }); + } + const { volumeMounts } = persistentVolumes(id, persistentStorage, config) + + const composeFile: ComposeFile = { + version: '3.8', + services: { + [id]: { + build: { + context: '.', + dockerfile: 'DockerfileGateway', + }, + container_name: id, + volumes: config['taiga-gateway'].volumes, + labels: makeLabelForServices('taiga'), + ...defaultComposeConfiguration(network), + }, + [`${id}-taiga-front`]: { + container_name: `${id}-taiga-front`, + image: config['taiga-front'].image, + environment: config['taiga-front'].environmentVariables, + labels: makeLabelForServices('taiga'), + ...defaultComposeConfiguration(network), + }, + [`${id}-taiga-back`]: { + build: { + context: '.', + dockerfile: 'DockerfileBack', + }, + entrypoint: '/taiga-back/docker/entrypoint_coolify.sh', + container_name: `${id}-taiga-back`, + environment: config['taiga-back'].environmentVariables, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + volumes: config['taiga-back'].volumes, + labels: makeLabelForServices('taiga'), + ...defaultComposeConfiguration(network), + }, + + [`${id}-async`]: { + container_name: `${id}-taiga-async`, + image: config['taiga-async'].image, + entrypoint: ["/taiga-back/docker/async_entrypoint.sh"], + environment: config['taiga-async'].environmentVariables, + volumes: config['taiga-async'].volumes, + labels: makeLabelForServices('taiga'), + ...defaultComposeConfiguration(network), + }, + [`${id}-taiga-rabbitmq`]: { + container_name: `${id}-taiga-rabbitmq`, + image: config['taiga-rabbitmq'].image, + volumes: config['taiga-rabbitmq'].volumes, + environment: config['taiga-rabbitmq'].environmentVariables, + labels: makeLabelForServices('taiga'), + ...defaultComposeConfiguration(network), + }, + [`${id}-taiga-protected`]: { + container_name: `${id}-taiga-protected`, + image: config['taiga-protected'].image, + environment: config['taiga-protected'].environmentVariables, + labels: makeLabelForServices('taiga'), + ...defaultComposeConfiguration(network), + }, + [`${id}-taiga-events`]: { + container_name: `${id}-taiga-events`, + image: config['taiga-events'].image, + environment: config['taiga-events'].environmentVariables, + labels: makeLabelForServices('taiga'), + ...defaultComposeConfiguration(network), + }, + [`${id}-postgresql`]: { + container_name: `${id}-postgresql`, + image: config.postgresql.image, + environment: config.postgresql.environmentVariables, + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + volumes: config.postgresql.volumes, + labels: makeLabelForServices('taiga'), + ...defaultComposeConfiguration(network), + }, + + }, + networks: { + [network]: { + external: true + } + }, + volumes: volumeMounts + }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; + await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); + + await startServiceContainers(destinationDocker.id, composeFileDestination) + return {} + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} + diff --git a/apps/api/src/lib/serviceFields.ts b/apps/api/src/lib/services/serviceFields.ts similarity index 55% rename from apps/api/src/lib/serviceFields.ts rename to apps/api/src/lib/services/serviceFields.ts index 7a6b00a85..22549e9a5 100644 --- a/apps/api/src/lib/serviceFields.ts +++ b/apps/api/src/lib/services/serviceFields.ts @@ -326,7 +326,7 @@ export const fider = [{ isBoolean: false, isEncrypted: true }, { - name: 'postgreslUser', + name: 'postgresqlUser', isEditable: false, isLowerCase: false, isNumber: false, @@ -344,7 +344,7 @@ export const fider = [{ { name: 'emailNoreply', isEditable: true, - isLowerCase: true, + isLowerCase: false, isNumber: false, isBoolean: false, isEncrypted: false @@ -352,7 +352,7 @@ export const fider = [{ { name: 'emailSmtpHost', isEditable: true, - isLowerCase: true, + isLowerCase: false, isNumber: false, isBoolean: false, isEncrypted: false @@ -376,7 +376,7 @@ export const fider = [{ { name: 'emailSmtpUser', isEditable: true, - isLowerCase: true, + isLowerCase: false, isNumber: false, isBoolean: false, isEncrypted: false @@ -476,4 +476,392 @@ export const moodle = [{ isNumber: false, isBoolean: false, isEncrypted: false +}] + +export const appwrite = [{ + name: 'opensslKeyV1', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'executorSecret', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'redisPassword', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'mariadbHost', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'mariadbPort', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'mariadbUser', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'mariadbPassword', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'mariadbRootUser', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'mariadbRootUserPassword', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'mariadbDatabase', + isEditable: true, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}] + +export const glitchTip = [{ + name: 'postgresqlUser', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'postgresqlPassword', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'postgresqlDatabase', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'postgresqlPublicPort', + isEditable: false, + isLowerCase: false, + isNumber: true, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'secretKeyBase', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'emailSmtpHost', + isEditable: true, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'emailSmtpPassword', + isEditable: true, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'emailSmtpUseSsl', + isEditable: true, + isLowerCase: false, + isNumber: false, + isBoolean: true, + isEncrypted: false +}, +{ + name: 'emailSmtpUseSsl', + isEditable: true, + isLowerCase: false, + isNumber: false, + isBoolean: true, + isEncrypted: false +}, +{ + name: 'emailSmtpPort', + isEditable: true, + isLowerCase: false, + isNumber: true, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'emailSmtpUser', + isEditable: true, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'defaultEmail', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'defaultUsername', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'defaultPassword', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'defaultEmailFrom', + isEditable: true, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'emailUrl', + isEditable: true, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'emailBackend', + isEditable: true, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'mailgunApiKey', + isEditable: true, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'sendgridApiKey', + isEditable: true, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'enableOpenUserRegistration', + isEditable: true, + isLowerCase: false, + isNumber: false, + isBoolean: true, + isEncrypted: false +}] + +export const searxng = [{ + name: 'secretKey', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'redisPassword', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}] + +export const weblate = [{ + name: 'adminPassword', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'postgresqlHost', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'postgresqlPort', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'postgresqlUser', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'postgresqlPassword', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'postgresqlDatabase', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}] +export const taiga = [{ + name: 'secretKey', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'djangoAdminUser', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'djangoAdminPassword', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'rabbitMQUser', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'rabbitMQPassword', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'postgresqlHost', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'postgresqlPort', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'postgresqlUser', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false +}, +{ + name: 'postgresqlPassword', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: true +}, +{ + name: 'postgresqlDatabase', + isEditable: false, + isLowerCase: false, + isNumber: false, + isBoolean: false, + isEncrypted: false }] \ No newline at end of file diff --git a/apps/api/src/lib/services/supportedVersions.ts b/apps/api/src/lib/services/supportedVersions.ts new file mode 100644 index 000000000..145d7395b --- /dev/null +++ b/apps/api/src/lib/services/supportedVersions.ts @@ -0,0 +1,215 @@ +export const supportedServiceTypesAndVersions = [ + { + name: 'plausibleanalytics', + fancyName: 'Plausible Analytics', + baseImage: 'plausible/analytics', + images: ['bitnami/postgresql:13.2.0', 'yandex/clickhouse-server:21.3.2.5'], + versions: ['latest', 'stable'], + recommendedVersion: 'stable', + ports: { + main: 8000 + } + }, + { + name: 'nocodb', + fancyName: 'NocoDB', + baseImage: 'nocodb/nocodb', + versions: ['latest'], + recommendedVersion: 'latest', + ports: { + main: 8080 + } + }, + { + name: 'minio', + fancyName: 'MinIO', + baseImage: 'minio/minio', + versions: ['latest'], + recommendedVersion: 'latest', + ports: { + main: 9001 + } + }, + { + name: 'vscodeserver', + fancyName: 'VSCode Server', + baseImage: 'codercom/code-server', + versions: ['latest'], + recommendedVersion: 'latest', + ports: { + main: 8080 + } + }, + { + name: 'wordpress', + fancyName: 'Wordpress', + baseImage: 'wordpress', + images: ['bitnami/mysql:5.7'], + versions: ['latest', 'php8.1', 'php8.0', 'php7.4', 'php7.3'], + recommendedVersion: 'latest', + ports: { + main: 80 + } + }, + { + name: 'vaultwarden', + fancyName: 'Vaultwarden', + baseImage: 'vaultwarden/server', + versions: ['latest'], + recommendedVersion: 'latest', + ports: { + main: 80 + } + }, + { + name: 'languagetool', + fancyName: 'LanguageTool', + baseImage: 'silviof/docker-languagetool', + versions: ['latest'], + recommendedVersion: 'latest', + ports: { + main: 8010 + } + }, + { + name: 'n8n', + fancyName: 'n8n', + baseImage: 'n8nio/n8n', + versions: ['latest'], + recommendedVersion: 'latest', + ports: { + main: 5678 + } + }, + { + name: 'uptimekuma', + fancyName: 'Uptime Kuma', + baseImage: 'louislam/uptime-kuma', + versions: ['latest'], + recommendedVersion: 'latest', + ports: { + main: 3001 + } + }, + { + name: 'ghost', + fancyName: 'Ghost', + baseImage: 'bitnami/ghost', + images: ['bitnami/mariadb'], + versions: ['latest'], + recommendedVersion: 'latest', + ports: { + main: 2368 + } + }, + { + name: 'meilisearch', + fancyName: 'Meilisearch', + baseImage: 'getmeili/meilisearch', + images: [], + versions: ['latest'], + recommendedVersion: 'latest', + ports: { + main: 7700 + } + }, + { + name: 'umami', + fancyName: 'Umami', + baseImage: 'ghcr.io/mikecao/umami', + images: ['postgres:12-alpine'], + versions: ['postgresql-latest'], + recommendedVersion: 'postgresql-latest', + ports: { + main: 3000 + } + }, + { + name: 'hasura', + fancyName: 'Hasura', + baseImage: 'hasura/graphql-engine', + images: ['postgres:12-alpine'], + versions: ['latest', 'v2.10.0', 'v2.5.1'], + recommendedVersion: 'v2.10.0', + ports: { + main: 8080 + } + }, + { + name: 'fider', + fancyName: 'Fider', + baseImage: 'getfider/fider', + images: ['postgres:12-alpine'], + versions: ['stable'], + recommendedVersion: 'stable', + ports: { + main: 3000 + } + }, + { + name: 'appwrite', + fancyName: 'Appwrite', + baseImage: 'appwrite/appwrite', + images: ['mariadb:10.7', 'redis:6.2-alpine', 'appwrite/telegraf:1.4.0'], + versions: ['latest', '0.15.3'], + recommendedVersion: '0.15.3', + ports: { + main: 80 + } + }, + // { + // name: 'moodle', + // fancyName: 'Moodle', + // baseImage: 'bitnami/moodle', + // images: [], + // versions: ['latest', 'v4.0.2'], + // recommendedVersion: 'latest', + // ports: { + // main: 8080 + // } + // } + { + name: 'glitchTip', + fancyName: 'GlitchTip', + baseImage: 'glitchtip/glitchtip', + images: ['postgres:14-alpine', 'redis:7-alpine'], + versions: ['latest'], + recommendedVersion: 'latest', + ports: { + main: 8000 + } + }, + { + name: 'searxng', + fancyName: 'SearXNG', + baseImage: 'searxng/searxng', + images: [], + versions: ['latest'], + recommendedVersion: 'latest', + ports: { + main: 8080 + } + }, + { + name: 'weblate', + fancyName: 'Weblate', + baseImage: 'weblate/weblate', + images: ['postgres:14-alpine', 'redis:6-alpine'], + versions: ['latest'], + recommendedVersion: 'latest', + ports: { + main: 8080 + } + }, + // { + // name: 'taiga', + // fancyName: 'Taiga', + // baseImage: 'taigaio/taiga-front', + // images: ['postgres:12.3', 'rabbitmq:3.8-management-alpine', 'taigaio/taiga-back', 'taigaio/taiga-events', 'taigaio/taiga-protected'], + // versions: ['latest'], + // recommendedVersion: 'latest', + // ports: { + // main: 80 + // } + // }, +]; \ No newline at end of file diff --git a/apps/api/src/plugins/jwt.ts b/apps/api/src/plugins/jwt.ts index 54dd1b72d..029aecd94 100644 --- a/apps/api/src/plugins/jwt.ts +++ b/apps/api/src/plugins/jwt.ts @@ -21,7 +21,6 @@ export default fp(async (fastify, opts) => { try { await request.jwtVerify() } catch (err) { - console.log(err) reply.send(err) } }) diff --git a/apps/api/src/routes/api/v1/applications/handlers.ts b/apps/api/src/routes/api/v1/applications/handlers.ts index 838f7f9b4..1d00e94d1 100644 --- a/apps/api/src/routes/api/v1/applications/handlers.ts +++ b/apps/api/src/routes/api/v1/applications/handlers.ts @@ -3,22 +3,29 @@ import crypto from 'node:crypto' import jsonwebtoken from 'jsonwebtoken'; import axios from 'axios'; import { FastifyReply } from 'fastify'; +import fs from 'fs/promises'; +import yaml from 'js-yaml'; + import { day } from '../../../../lib/dayjs'; -import { setDefaultBaseImage, setDefaultConfiguration } from '../../../../lib/buildPacks/common'; -import { checkDomainsIsValidInDNS, checkDoubleBranch, decrypt, encrypt, errorHandler, executeDockerCmd, generateSshKeyPair, getContainerUsage, getDomain, getFreeExposedPort, isDev, isDomainConfigured, prisma, stopBuild, uniqueName } from '../../../../lib/common'; +import { makeLabelForStandaloneApplication, setDefaultBaseImage, setDefaultConfiguration } from '../../../../lib/buildPacks/common'; +import { checkDomainsIsValidInDNS, checkDoubleBranch, checkExposedPort, createDirectories, decrypt, defaultComposeConfiguration, encrypt, errorHandler, executeDockerCmd, generateSshKeyPair, getContainerUsage, getDomain, isDev, isDomainConfigured, listSettings, prisma, stopBuild, uniqueName } from '../../../../lib/common'; import { checkContainer, formatLabelsOnDocker, isContainerExited, removeContainer } from '../../../../lib/docker'; -import { scheduler } from '../../../../lib/scheduler'; import type { FastifyRequest } from 'fastify'; import type { GetImages, CancelDeployment, CheckDNS, CheckRepository, DeleteApplication, DeleteSecret, DeleteStorage, GetApplicationLogs, GetBuildIdLogs, GetBuildLogs, SaveApplication, SaveApplicationSettings, SaveApplicationSource, SaveDeployKey, SaveDestination, SaveSecret, SaveStorage, DeployApplication, CheckDomain, StopPreviewApplication } from './types'; import { OnlyId } from '../../../../types'; +function filterObject(obj, callback) { + return Object.fromEntries(Object.entries(obj). + filter(([key, val]) => callback(val, key))); +} + export async function listApplications(request: FastifyRequest) { try { const { teamId } = request.user const applications = await prisma.application.findMany({ where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } }, - include: { teams: true, destinationDocker: true } + include: { teams: true, destinationDocker: true, settings: true } }); const settings = await prisma.setting.findFirst() return { @@ -34,7 +41,7 @@ export async function getImages(request: FastifyRequest) { const { buildPack, deploymentType } = request.body let publishDirectory = undefined; let port = undefined - const { baseImage, baseBuildImage, baseBuildImages, baseImages, } = setDefaultBaseImage( + const { baseImage, baseBuildImage, baseBuildImages, baseImages } = setDefaultBaseImage( buildPack, deploymentType ); if (buildPack === 'nextjs') { @@ -56,8 +63,7 @@ export async function getImages(request: FastifyRequest) { } } - - return { baseBuildImage, baseBuildImages, publishDirectory, port } + return { baseImage, baseImages, baseBuildImage, baseBuildImages, publishDirectory, port } } catch ({ status, message }) { return errorHandler({ status, message }) } @@ -75,7 +81,6 @@ export async function getApplicationStatus(request: FastifyRequest) { isExited = await isContainerExited(application.destinationDocker.id, id); } return { - isQueueActive: scheduler.workers.has('deployApplication'), isRunning, isExited, }; @@ -90,10 +95,11 @@ export async function getApplication(request: FastifyRequest) { const { teamId } = request.user const appId = process.env['COOLIFY_APP_ID']; const application: any = await getApplicationFromDB(id, teamId); - + const settings = await listSettings(); return { application, - appId + appId, + settings }; } catch ({ status, message }) { @@ -150,7 +156,8 @@ export async function getApplicationFromDB(id: string, teamId: string) { settings: true, gitSource: { include: { githubApp: true, gitlabApp: true } }, secrets: true, - persistentStorage: true + persistentStorage: true, + connectedDatabase: true } }); if (!application) { @@ -177,32 +184,39 @@ export async function getApplicationFromDB(id: string, teamId: string) { } export async function getApplicationFromDBWebhook(projectId: number, branch: string) { try { - let application = await prisma.application.findFirst({ + let applications = await prisma.application.findMany({ where: { projectId, branch, settings: { autodeploy: true } }, include: { destinationDocker: true, settings: true, gitSource: { include: { githubApp: true, gitlabApp: true } }, secrets: true, - persistentStorage: true + persistentStorage: true, + connectedDatabase: true } }); - if (!application) { + if (applications.length === 0) { throw { status: 500, message: 'Application not configured.' } } - application = decryptApplication(application); - const { baseImage, baseBuildImage, baseBuildImages, baseImages } = setDefaultBaseImage( - application.buildPack - ); + applications = applications.map((application: any) => { + application = decryptApplication(application); + const { baseImage, baseBuildImage, baseBuildImages, baseImages } = setDefaultBaseImage( + application.buildPack + ); - // Set default build images - if (!application.baseImage) { - application.baseImage = baseImage; - } - if (!application.baseBuildImage) { - application.baseBuildImage = baseBuildImage; - } - return { ...application, baseBuildImages, baseImages }; + // Set default build images + if (!application.baseImage) { + application.baseImage = baseImage; + } + if (!application.baseBuildImage) { + application.baseBuildImage = baseBuildImage; + } + application.baseBuildImages = baseBuildImages; + application.baseImages = baseImages; + return application + }) + + return applications; } catch ({ status, message }) { return errorHandler({ status, message }) @@ -230,13 +244,16 @@ export async function saveApplication(request: FastifyRequest, denoOptions, baseImage, baseBuildImage, - deploymentType + deploymentType, + baseDatabaseBranch } = request.body - if (port) port = Number(port); if (exposePort) { exposePort = Number(exposePort); } + + const { destinationDocker: { id: dockerId, remoteIpAddress }, exposePort: configuredPort } = await prisma.application.findUnique({ where: { id }, include: { destinationDocker: true } }) + if (exposePort) await checkExposedPort({ id, configuredPort, exposePort, dockerId, remoteIpAddress }) if (denoOptions) denoOptions = denoOptions.trim(); const defaultConfiguration = await setDefaultConfiguration({ buildPack, @@ -249,22 +266,43 @@ export async function saveApplication(request: FastifyRequest, dockerFileLocation, denoMainFile }); - await prisma.application.update({ - where: { id }, - data: { - name, - fqdn, - exposePort, - pythonWSGI, - pythonModule, - pythonVariable, - denoOptions, - baseImage, - baseBuildImage, - deploymentType, - ...defaultConfiguration - } - }); + if (baseDatabaseBranch) { + await prisma.application.update({ + where: { id }, + data: { + name, + fqdn, + exposePort, + pythonWSGI, + pythonModule, + pythonVariable, + denoOptions, + baseImage, + baseBuildImage, + deploymentType, + ...defaultConfiguration, + connectedDatabase: { update: { hostedDatabaseDBName: baseDatabaseBranch } } + } + }); + } else { + await prisma.application.update({ + where: { id }, + data: { + name, + fqdn, + exposePort, + pythonWSGI, + pythonModule, + pythonVariable, + denoOptions, + baseImage, + baseBuildImage, + deploymentType, + ...defaultConfiguration + } + }); + } + return reply.code(201).send(); } catch ({ status, message }) { return errorHandler({ status, message }) @@ -275,15 +313,15 @@ export async function saveApplication(request: FastifyRequest, export async function saveApplicationSettings(request: FastifyRequest, reply: FastifyReply) { try { const { id } = request.params - const { debug, previews, dualCerts, autodeploy, branch, projectId } = request.body - const isDouble = await checkDoubleBranch(branch, projectId); - if (isDouble && autodeploy) { - await prisma.applicationSettings.updateMany({ where: { application: { branch, projectId } }, data: { autodeploy: false } }) - throw { status: 500, message: 'Cannot activate automatic deployments until only one application is defined for this repository / branch.' } - } + const { debug, previews, dualCerts, autodeploy, branch, projectId, isBot, isDBBranching } = request.body + // const isDouble = await checkDoubleBranch(branch, projectId); + // if (isDouble && autodeploy) { + // await prisma.applicationSettings.updateMany({ where: { application: { branch, projectId } }, data: { autodeploy: false } }) + // throw { status: 500, message: 'Cannot activate automatic deployments until only one application is defined for this repository / branch.' } + // } await prisma.application.update({ where: { id }, - data: { settings: { update: { debug, previews, dualCerts, autodeploy } } }, + data: { fqdn: isBot ? null : undefined, settings: { update: { debug, previews, dualCerts, autodeploy, isBot, isDBBranching } } }, include: { destinationDocker: true } }); return reply.code(201).send(); @@ -311,6 +349,113 @@ export async function stopPreviewApplication(request: FastifyRequest, reply: FastifyReply) { + try { + const { id } = request.params + const { teamId } = request.user + let application: any = await getApplicationFromDB(id, teamId); + if (application?.destinationDockerId) { + const buildId = cuid(); + const { id: dockerId, network } = application.destinationDocker; + const { secrets, pullmergeRequestId, port, repository, persistentStorage, id: applicationId, buildPack, exposePort } = application; + + const envs = [ + `PORT=${port}` + ]; + if (secrets.length > 0) { + secrets.forEach((secret) => { + if (pullmergeRequestId) { + if (secret.isPRMRSecret) { + envs.push(`${secret.name}=${secret.value}`); + } + } else { + if (!secret.isPRMRSecret) { + envs.push(`${secret.name}=${secret.value}`); + } + } + }); + } + const { workdir } = await createDirectories({ repository, buildId }); + const labels = [] + let image = null + const { stdout: container } = await executeDockerCmd({ dockerId, command: `docker container ls --filter 'label=com.docker.compose.service=${id}' --format '{{json .}}'` }) + const containersArray = container.trim().split('\n'); + for (const container of containersArray) { + const containerObj = formatLabelsOnDocker(container); + image = containerObj[0].Image + Object.keys(containerObj[0].Labels).forEach(function (key) { + if (key.startsWith('coolify')) { + labels.push(`${key}=${containerObj[0].Labels[key]}`) + } + }) + } + let imageFound = false; + try { + await executeDockerCmd({ + dockerId, + command: `docker image inspect ${image}` + }) + imageFound = true; + } catch (error) { + // + } + if (!imageFound) { + throw { status: 500, message: 'Image not found, cannot restart application.' } + } + await fs.writeFile(`${workdir}/.env`, envs.join('\n')); + + let envFound = false; + try { + envFound = !!(await fs.stat(`${workdir}/.env`)); + } catch (error) { + // + } + const volumes = + persistentStorage?.map((storage) => { + return `${applicationId}${storage.path.replace(/\//gi, '-')}:${buildPack !== 'docker' ? '/app' : '' + }${storage.path}`; + }) || []; + const composeVolumes = volumes.map((volume) => { + return { + [`${volume.split(':')[0]}`]: { + name: volume.split(':')[0] + } + }; + }); + const composeFile = { + version: '3.8', + services: { + [applicationId]: { + image, + container_name: applicationId, + volumes, + env_file: envFound ? [`${workdir}/.env`] : [], + labels, + depends_on: [], + expose: [port], + ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), + ...defaultComposeConfiguration(network), + } + }, + networks: { + [network]: { + external: true + } + }, + volumes: Object.assign({}, ...composeVolumes) + }; + await fs.writeFile(`${workdir}/docker-compose.yml`, yaml.dump(composeFile)); + await executeDockerCmd({ dockerId, command: `docker stop -t 0 ${id}` }) + await executeDockerCmd({ dockerId, command: `docker rm ${id}` }) + await executeDockerCmd({ dockerId, command: `docker compose --project-directory ${workdir} up -d` }) + return reply.code(201).send(); + } + throw { status: 500, message: 'Application cannot be restarted.' } + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} export async function stopApplication(request: FastifyRequest, reply: FastifyReply) { try { const { id } = request.params @@ -331,12 +476,14 @@ export async function stopApplication(request: FastifyRequest, reply: Fa export async function deleteApplication(request: FastifyRequest, reply: FastifyReply) { try { const { id } = request.params + const { force } = request.body + const { teamId } = request.user const application = await prisma.application.findUnique({ where: { id }, include: { destinationDocker: true } }); - if (application?.destinationDockerId && application.destinationDocker?.network) { + if (!force && application?.destinationDockerId && application.destinationDocker?.network) { const { stdout: containers } = await executeDockerCmd({ dockerId: application.destinationDocker.id, command: `docker ps -a --filter network=${application.destinationDocker.network} --filter name=${id} --format '{{json .}}'` @@ -355,6 +502,7 @@ export async function deleteApplication(request: FastifyRequest) { export async function checkDNS(request: FastifyRequest) { try { const { id } = request.params - let { exposePort, fqdn, forceSave, dualCerts } = request.body - - if (fqdn) fqdn = fqdn.toLowerCase(); + if (!fqdn) { + return {} + } else { + fqdn = fqdn.toLowerCase(); + } if (exposePort) exposePort = Number(exposePort); const { destinationDocker: { id: dockerId, remoteIpAddress, remoteEngine }, exposePort: configuredPort } = await prisma.application.findUnique({ where: { id }, include: { destinationDocker: true } }) const { isDNSCheckEnabled } = await prisma.setting.findFirst({}); - const found = await isDomainConfigured({ id, fqdn, dockerId }); + const found = await isDomainConfigured({ id, fqdn, remoteIpAddress }); if (found) { throw { status: 500, message: `Domain ${getDomain(fqdn).replace('www.', '')} is already in use!` } } - if (exposePort) { - if (exposePort < 1024 || exposePort > 65535) { - throw { status: 500, message: `Exposed Port needs to be between 1024 and 65535.` } - } - - if (configuredPort !== exposePort) { - const availablePort = await getFreeExposedPort(id, exposePort, dockerId, remoteIpAddress); - if (availablePort.toString() !== exposePort.toString()) { - throw { status: 500, message: `Port ${exposePort} is already in use.` } - } - } - } + if (exposePort) await checkExposedPort({ id, configuredPort, exposePort, dockerId, remoteIpAddress }) if (isDNSCheckEnabled && !isDev && !forceSave) { let hostname = request.hostname.split(':')[0]; if (remoteEngine) hostname = remoteIpAddress; @@ -435,7 +574,7 @@ export async function deployApplication(request: FastifyRequest, reply: FastifyReply) { try { const { id } = request.params - const { gitSourceId } = request.body - await prisma.application.update({ - where: { id }, - data: { gitSource: { connect: { id: gitSourceId } } } - }); + const { gitSourceId, forPublic, type } = request.body + if (forPublic) { + const publicGit = await prisma.gitSource.findFirst({ where: { type, forPublic } }); + await prisma.application.update({ + where: { id }, + data: { gitSource: { connect: { id: publicGit.id } } } + }); + } else { + await prisma.application.update({ + where: { id }, + data: { gitSource: { connect: { id: gitSourceId } } } + }); + } + return reply.code(201).send() } catch ({ status, message }) { return errorHandler({ status, message }) @@ -556,7 +691,7 @@ export async function checkRepository(request: FastifyRequest) export async function saveRepository(request, reply) { try { const { id } = request.params - let { repository, branch, projectId, autodeploy, webhookToken } = request.body + let { repository, branch, projectId, autodeploy, webhookToken, isPublicRepository = false } = request.body repository = repository.toLowerCase(); branch = branch.toLowerCase(); @@ -564,18 +699,20 @@ export async function saveRepository(request, reply) { if (webhookToken) { await prisma.application.update({ where: { id }, - data: { repository, branch, projectId, gitSource: { update: { gitlabApp: { update: { webhookToken: webhookToken ? webhookToken : undefined } } } }, settings: { update: { autodeploy } } } + data: { repository, branch, projectId, gitSource: { update: { gitlabApp: { update: { webhookToken: webhookToken ? webhookToken : undefined } } } }, settings: { update: { autodeploy, isPublicRepository } } } }); } else { await prisma.application.update({ where: { id }, - data: { repository, branch, projectId, settings: { update: { autodeploy } } } + data: { repository, branch, projectId, settings: { update: { autodeploy, isPublicRepository } } } }); } - const isDouble = await checkDoubleBranch(branch, projectId); - if (isDouble) { - await prisma.applicationSettings.updateMany({ where: { application: { branch, projectId } }, data: { autodeploy: false } }) - } + // if (!isPublicRepository) { + // const isDouble = await checkDoubleBranch(branch, projectId); + // if (isDouble) { + // await prisma.applicationSettings.updateMany({ where: { application: { branch, projectId } }, data: { autodeploy: false, isPublicRepository } }) + // } + // } return reply.code(201).send() } catch ({ status, message }) { return errorHandler({ status, message }) @@ -606,7 +743,8 @@ export async function getBuildPack(request) { projectId: application.projectId, repository: application.repository, branch: application.branch, - apiUrl: application.gitSource.apiUrl + apiUrl: application.gitSource.apiUrl, + isPublicRepository: application.settings.isPublicRepository } } catch ({ status, message }) { return errorHandler({ status, message }) @@ -623,6 +761,16 @@ export async function saveBuildPack(request, reply) { return errorHandler({ status, message }) } } +export async function saveConnectedDatabase(request, reply) { + try { + const { id } = request.params + const { databaseId, type } = request.body + await prisma.application.update({ where: { id }, data: { connectedDatabase: { upsert: { create: { database: { connect: { id: databaseId } }, hostedDatabaseType: type }, update: { database: { connect: { id: databaseId } }, hostedDatabaseType: type } } } } }) + return reply.code(201).send() + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} export async function getSecrets(request: FastifyRequest) { try { @@ -656,13 +804,13 @@ export async function saveSecret(request: FastifyRequest, reply: Fas if (found) { throw { status: 500, message: `Secret ${name} already exists.` } } else { - value = encrypt(value); + value = encrypt(value.trim()); await prisma.secret.create({ data: { name, value, isBuildSecret, isPRMRSecret, application: { connect: { id } } } }); } } else { - value = encrypt(value); + value = encrypt(value.trim()); const found = await prisma.secret.findFirst({ where: { applicationId: id, name, isPRMRSecret } }); if (found) { @@ -779,7 +927,6 @@ export async function getPreviews(request: FastifyRequest) { }) } } catch ({ status, message }) { - console.log({ status, message }) return errorHandler({ status, message }) } } @@ -872,8 +1019,13 @@ export async function getBuildIdLogs(request: FastifyRequest) { orderBy: { time: 'asc' } }); const data = await prisma.build.findFirst({ where: { id: buildId } }); + const createdAt = day(data.createdAt).utc(); return { - logs, + logs: logs.map(log => { + log.time = Number(log.time) + return log + }), + took: day().diff(createdAt) / 1000, status: data?.status || 'queued' } } catch ({ status, message }) { @@ -948,4 +1100,59 @@ export async function cancelDeployment(request: FastifyRequest } catch ({ status, message }) { return errorHandler({ status, message }) } +} + + +export async function createdBranchDatabase(database: any, baseDatabaseBranch: string, pullmergeRequestId: string) { + try { + if (!baseDatabaseBranch) return + const { id, type, destinationDockerId, rootUser, rootUserPassword, dbUser } = database; + if (destinationDockerId) { + if (type === 'postgresql') { + const decryptedRootUserPassword = decrypt(rootUserPassword); + await executeDockerCmd({ + dockerId: destinationDockerId, + command: `docker exec ${id} pg_dump -d "postgresql://postgres:${decryptedRootUserPassword}@${id}:5432/${baseDatabaseBranch}" --encoding=UTF8 --schema-only -f /tmp/${baseDatabaseBranch}.dump` + }) + await executeDockerCmd({ + dockerId: destinationDockerId, + command: `docker exec ${id} psql postgresql://postgres:${decryptedRootUserPassword}@${id}:5432 -c "CREATE DATABASE branch_${pullmergeRequestId}"` + }) + await executeDockerCmd({ + dockerId: destinationDockerId, + command: `docker exec ${id} psql -d "postgresql://postgres:${decryptedRootUserPassword}@${id}:5432/branch_${pullmergeRequestId}" -f /tmp/${baseDatabaseBranch}.dump` + }) + await executeDockerCmd({ + dockerId: destinationDockerId, + command: `docker exec ${id} psql postgresql://postgres:${decryptedRootUserPassword}@${id}:5432 -c "ALTER DATABASE branch_${pullmergeRequestId} OWNER TO ${dbUser}"` + }) + } + } + + + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} +export async function removeBranchDatabase(database: any, pullmergeRequestId: string) { + try { + const { id, type, destinationDockerId, rootUser, rootUserPassword } = database; + if (destinationDockerId) { + if (type === 'postgresql') { + const decryptedRootUserPassword = decrypt(rootUserPassword); + // Terminate all connections to the database + await executeDockerCmd({ + dockerId: destinationDockerId, + command: `docker exec ${id} psql postgresql://postgres:${decryptedRootUserPassword}@${id}:5432 -c "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'branch_${pullmergeRequestId}' AND pid <> pg_backend_pid();"` + }) + + await executeDockerCmd({ + dockerId: destinationDockerId, + command: `docker exec ${id} psql postgresql://postgres:${decryptedRootUserPassword}@${id}:5432 -c "DROP DATABASE branch_${pullmergeRequestId}"` + }) + } + } + } catch ({ status, message }) { + return errorHandler({ status, message }) + } } \ No newline at end of file diff --git a/apps/api/src/routes/api/v1/applications/index.ts b/apps/api/src/routes/api/v1/applications/index.ts index 2f698ddeb..d42906066 100644 --- a/apps/api/src/routes/api/v1/applications/index.ts +++ b/apps/api/src/routes/api/v1/applications/index.ts @@ -1,6 +1,6 @@ import { FastifyPluginAsync } from 'fastify'; import { OnlyId } from '../../../../types'; -import { cancelDeployment, checkDNS, checkDomain, checkRepository, deleteApplication, deleteSecret, deleteStorage, deployApplication, getApplication, getApplicationLogs, getApplicationStatus, getBuildIdLogs, getBuildLogs, getBuildPack, getGitHubToken, getGitLabSSHKey, getImages, getPreviews, getSecrets, getStorages, getUsage, listApplications, newApplication, saveApplication, saveApplicationSettings, saveApplicationSource, saveBuildPack, saveDeployKey, saveDestination, saveGitLabSSHKey, saveRepository, saveSecret, saveStorage, stopApplication, stopPreviewApplication } from './handlers'; +import { cancelDeployment, checkDNS, checkDomain, checkRepository, deleteApplication, deleteSecret, deleteStorage, deployApplication, getApplication, getApplicationLogs, getApplicationStatus, getBuildIdLogs, getBuildLogs, getBuildPack, getGitHubToken, getGitLabSSHKey, getImages, getPreviews, getSecrets, getStorages, getUsage, listApplications, newApplication, restartApplication, saveApplication, saveApplicationSettings, saveApplicationSource, saveBuildPack, saveConnectedDatabase, saveDeployKey, saveDestination, saveGitLabSSHKey, saveRepository, saveSecret, saveStorage, stopApplication, stopPreviewApplication } from './handlers'; import type { CancelDeployment, CheckDNS, CheckDomain, CheckRepository, DeleteApplication, DeleteSecret, DeleteStorage, DeployApplication, GetApplicationLogs, GetBuildIdLogs, GetBuildLogs, GetImages, SaveApplication, SaveApplicationSettings, SaveApplicationSource, SaveDeployKey, SaveDestination, SaveSecret, SaveStorage, StopPreviewApplication } from './types'; @@ -19,6 +19,7 @@ const root: FastifyPluginAsync = async (fastify): Promise => { fastify.get('/:id/status', async (request) => await getApplicationStatus(request)); + fastify.post('/:id/restart', async (request, reply) => await restartApplication(request, reply)); fastify.post('/:id/stop', async (request, reply) => await stopApplication(request, reply)); fastify.post('/:id/stop/preview', async (request, reply) => await stopPreviewApplication(request, reply)); @@ -54,6 +55,8 @@ const root: FastifyPluginAsync = async (fastify): Promise => { fastify.get('/:id/configuration/buildpack', async (request) => await getBuildPack(request)); fastify.post('/:id/configuration/buildpack', async (request, reply) => await saveBuildPack(request, reply)); + fastify.post('/:id/configuration/database', async (request, reply) => await saveConnectedDatabase(request, reply)); + fastify.get('/:id/configuration/sshkey', async (request) => await getGitLabSSHKey(request)); fastify.post('/:id/configuration/sshkey', async (request, reply) => await saveGitLabSSHKey(request, reply)); diff --git a/apps/api/src/routes/api/v1/applications/types.ts b/apps/api/src/routes/api/v1/applications/types.ts index 40dabc20a..e88a79d72 100644 --- a/apps/api/src/routes/api/v1/applications/types.ts +++ b/apps/api/src/routes/api/v1/applications/types.ts @@ -20,15 +20,17 @@ export interface SaveApplication extends OnlyId { denoOptions: string, baseImage: string, baseBuildImage: string, - deploymentType: string + deploymentType: string, + baseDatabaseBranch: string } } export interface SaveApplicationSettings extends OnlyId { Querystring: { domain: string; }; - Body: { debug: boolean; previews: boolean; dualCerts: boolean; autodeploy: boolean; branch: string; projectId: number; }; + Body: { debug: boolean; previews: boolean; dualCerts: boolean; autodeploy: boolean; branch: string; projectId: number; isBot: boolean; isDBBranching: boolean }; } export interface DeleteApplication extends OnlyId { Querystring: { domain: string; }; + Body: { force: boolean } } export interface CheckDomain extends OnlyId { Querystring: { domain: string; }; @@ -44,13 +46,13 @@ export interface CheckDNS extends OnlyId { } export interface DeployApplication { Querystring: { domain: string } - Body: { pullmergeRequestId: string | null, branch: string } + Body: { pullmergeRequestId: string | null, branch: string, forceRebuild?: boolean } } export interface GetImages { Body: { buildPack: string, deploymentType: string } } export interface SaveApplicationSource extends OnlyId { - Body: { gitSourceId: string } + Body: { gitSourceId?: string | null, forPublic?: boolean, type?: string } } export interface CheckRepository extends OnlyId { Querystring: { repository: string, branch: string } @@ -115,7 +117,8 @@ export interface CancelDeployment { export interface DeployApplication extends OnlyId { Body: { pullmergeRequestId: string | null, - branch: string + branch: string, + forceRebuild?: boolean } } diff --git a/apps/api/src/routes/api/v1/databases/handlers.ts b/apps/api/src/routes/api/v1/databases/handlers.ts index ca5fc67c0..d646a036f 100644 --- a/apps/api/src/routes/api/v1/databases/handlers.ts +++ b/apps/api/src/routes/api/v1/databases/handlers.ts @@ -4,11 +4,10 @@ import { FastifyReply } from 'fastify'; import yaml from 'js-yaml'; import fs from 'fs/promises'; import { ComposeFile, createDirectories, decrypt, encrypt, errorHandler, executeDockerCmd, generateDatabaseConfiguration, generatePassword, getContainerUsage, getDatabaseImage, getDatabaseVersions, getFreePublicPort, listSettings, makeLabelForStandaloneDatabase, prisma, startTraefikTCPProxy, stopDatabaseContainer, stopTcpHttpProxy, supportedDatabaseTypesAndVersions, uniqueName, updatePasswordInDb } from '../../../../lib/common'; -import { checkContainer } from '../../../../lib/docker'; import { day } from '../../../../lib/dayjs'; import { GetDatabaseLogs, OnlyId, SaveDatabase, SaveDatabaseDestination, SaveDatabaseSettings, SaveVersion } from '../../../../types'; -import { SaveDatabaseType } from './types'; +import { DeleteDatabase, SaveDatabaseType } from './types'; export async function listDatabases(request: FastifyRequest) { try { @@ -30,9 +29,9 @@ export async function newDatabase(request: FastifyRequest, reply: FastifyReply) const name = uniqueName(); const dbUser = cuid(); - const dbUserPassword = encrypt(generatePassword()); + const dbUserPassword = encrypt(generatePassword({})); const rootUser = cuid(); - const rootUserPassword = encrypt(generatePassword()); + const rootUserPassword = encrypt(generatePassword({})); const defaultDatabase = cuid(); const { id } = await prisma.database.create({ @@ -93,14 +92,15 @@ export async function getDatabase(request: FastifyRequest) { if (!database) { throw { status: 404, message: 'Database not found.' } } + const { arch } = await listSettings(); if (database.dbUserPassword) database.dbUserPassword = decrypt(database.dbUserPassword); if (database.rootUserPassword) database.rootUserPassword = decrypt(database.rootUserPassword); - const configuration = generateDatabaseConfiguration(database); + const configuration = generateDatabaseConfiguration(database, arch); const settings = await listSettings(); return { privatePort: configuration?.privatePort, database, - versions: await getDatabaseVersions(database.type), + versions: await getDatabaseVersions(database.type, arch), settings }; } catch ({ status, message }) { @@ -137,8 +137,10 @@ export async function getVersions(request: FastifyRequest) { where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } }, include: { destinationDocker: true, settings: true } }); + const { arch } = await listSettings(); + const versions = getDatabaseVersions(type, arch); return { - versions: supportedDatabaseTypesAndVersions.find((name) => name.name === type).versions + versions } } catch ({ status, message }) { return errorHandler({ status, message }) @@ -165,6 +167,7 @@ export async function saveDatabaseDestination(request: FastifyRequest) { where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } }, include: { destinationDocker: true, settings: true } }); + const { arch } = await listSettings(); if (database.dbUserPassword) database.dbUserPassword = decrypt(database.dbUserPassword); if (database.rootUserPassword) database.rootUserPassword = decrypt(database.rootUserPassword); const { @@ -228,8 +232,8 @@ export async function startDatabase(request: FastifyRequest) { publicPort, settings: { isPublic } } = database; - const { privatePort, environmentVariables, image, volume, ulimits } = - generateDatabaseConfiguration(database); + const { privatePort, command, environmentVariables, image, volume, ulimits } = + generateDatabaseConfiguration(database, arch); const network = destinationDockerId && destinationDocker.network; const volumeName = volume.split(':')[0]; @@ -243,6 +247,7 @@ export async function startDatabase(request: FastifyRequest) { [id]: { container_name: id, image, + command, networks: [network], environment: environmentVariables, volumes: [volume], @@ -270,13 +275,12 @@ export async function startDatabase(request: FastifyRequest) { } } }; + const composeFileDestination = `${workdir}/docker-compose.yaml`; await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); try { await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker volume create ${volumeName}` }) - } catch (error) { - console.log(error); - } + } catch (error) { } try { await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up -d` }) if (isPublic) await startTraefikTCPProxy(destinationDocker, id, publicPort, privatePort); @@ -354,19 +358,22 @@ export async function getDatabaseLogs(request: FastifyRequest) return errorHandler({ status, message }) } } -export async function deleteDatabase(request: FastifyRequest) { +export async function deleteDatabase(request: FastifyRequest) { try { const teamId = request.user.teamId; const { id } = request.params; + const { force } = request.body; const database = await prisma.database.findFirst({ where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } }, include: { destinationDocker: true, settings: true } }); - if (database.dbUserPassword) database.dbUserPassword = decrypt(database.dbUserPassword); - if (database.rootUserPassword) database.rootUserPassword = decrypt(database.rootUserPassword); - if (database.destinationDockerId) { - const everStarted = await stopDatabaseContainer(database); - if (everStarted) await stopTcpHttpProxy(id, database.destinationDocker, database.publicPort); + if (!force) { + if (database.dbUserPassword) database.dbUserPassword = decrypt(database.dbUserPassword); + if (database.rootUserPassword) database.rootUserPassword = decrypt(database.rootUserPassword); + if (database.destinationDockerId) { + const everStarted = await stopDatabaseContainer(database); + if (everStarted) await stopTcpHttpProxy(id, database.destinationDocker, database.publicPort); + } } await prisma.databaseSettings.deleteMany({ where: { databaseId: id } }); await prisma.database.delete({ where: { id } }); @@ -427,9 +434,13 @@ export async function saveDatabaseSettings(request: FastifyRequest => { @@ -13,7 +13,7 @@ const root: FastifyPluginAsync = async (fastify): Promise => { fastify.get('/:id', async (request) => await getDatabase(request)); fastify.post('/:id', async (request, reply) => await saveDatabase(request, reply)); - fastify.delete('/:id', async (request) => await deleteDatabase(request)); + fastify.delete('/:id', async (request) => await deleteDatabase(request)); fastify.get('/:id/status', async (request) => await getDatabaseStatus(request)); diff --git a/apps/api/src/routes/api/v1/databases/types.ts b/apps/api/src/routes/api/v1/databases/types.ts index b7e4c8692..a56a45c23 100644 --- a/apps/api/src/routes/api/v1/databases/types.ts +++ b/apps/api/src/routes/api/v1/databases/types.ts @@ -2,4 +2,7 @@ import type { OnlyId } from "../../../../types"; export interface SaveDatabaseType extends OnlyId { Body: { type: string } +} +export interface DeleteDatabase extends OnlyId { + Body: { force: string } } \ No newline at end of file diff --git a/apps/api/src/routes/api/v1/destinations/handlers.ts b/apps/api/src/routes/api/v1/destinations/handlers.ts index 81fcaf28e..bb96981cf 100644 --- a/apps/api/src/routes/api/v1/destinations/handlers.ts +++ b/apps/api/src/routes/api/v1/destinations/handlers.ts @@ -4,7 +4,7 @@ import sshConfig from 'ssh-config' import fs from 'fs/promises' import os from 'os'; -import { asyncExecShell, decrypt, errorHandler, executeDockerCmd, listSettings, prisma, startTraefikProxy, stopTraefikProxy } from '../../../../lib/common'; +import { asyncExecShell, createRemoteEngineConfiguration, decrypt, errorHandler, executeDockerCmd, listSettings, prisma, startTraefikProxy, stopTraefikProxy } from '../../../../lib/common'; import { checkContainer } from '../../../../lib/docker'; import type { OnlyId } from '../../../../types'; @@ -53,13 +53,13 @@ export async function getDestination(request: FastifyRequest) { const teamId = request.user?.teamId; const destination = await prisma.destinationDocker.findFirst({ where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } }, - include: { sshKey: true } + include: { sshKey: true, application: true, service: true, database: true } }); if (!destination && id !== 'new') { throw { status: 404, message: `Destination not found.` }; } const settings = await listSettings(); - let payload = { + const payload = { destination, settings }; @@ -78,7 +78,6 @@ export async function newDestination(request: FastifyRequest, re let { name, network, engine, isCoolifyProxyUsed, remoteIpAddress, remoteUser, remotePort } = request.body if (id === 'new') { - console.log(engine) if (engine) { const { stdout } = await asyncExecShell(`DOCKER_HOST=unix:///var/run/docker.sock docker network ls --filter 'name=^${network}$' --format '{{json .}}'`); if (stdout === '') { @@ -114,7 +113,6 @@ export async function newDestination(request: FastifyRequest, re } } catch ({ status, message }) { - console.log({ status, message }) return errorHandler({ status, message }) } } @@ -162,7 +160,6 @@ export async function startProxy(request: FastifyRequest) { await startTraefikProxy(id); return {} } catch ({ status, message }) { - console.log({ status, message }) await stopTraefikProxy(id); return errorHandler({ status, message }) } @@ -205,41 +202,21 @@ export async function assignSSHKey(request: FastifyRequest) { return errorHandler({ status, message }) } } -export async function verifyRemoteDockerEngine(request: FastifyRequest, reply: FastifyReply) { +export async function verifyRemoteDockerEngine(request: FastifyRequest, reply: FastifyReply) { try { const { id } = request.params; - const homedir = os.homedir(); - - const { sshKey: { privateKey }, remoteIpAddress, remotePort, remoteUser, network } = await prisma.destinationDocker.findFirst({ where: { id }, include: { sshKey: true } }) - - await fs.writeFile(`/tmp/id_rsa_verification_${id}`, decrypt(privateKey) + '\n', { encoding: 'utf8', mode: 400 }) - + await createRemoteEngineConfiguration(id); + const { remoteIpAddress, remoteUser, network, isCoolifyProxyUsed } = await prisma.destinationDocker.findFirst({ where: { id } }) const host = `ssh://${remoteUser}@${remoteIpAddress}` - - const config = sshConfig.parse('') - const found = config.find({ Host: remoteIpAddress }) - if (!found) { - config.append({ - Host: remoteIpAddress, - Port: remotePort.toString(), - User: remoteUser, - IdentityFile: `/tmp/id_rsa_verification_${id}`, - StrictHostKeyChecking: 'no' - }) - } - try { - await fs.stat(`${homedir}/.ssh/`) - } catch (error) { - await fs.mkdir(`${homedir}/.ssh/`) - } - await fs.writeFile(`${homedir}/.ssh/config`, sshConfig.stringify(config)) - const { stdout } = await asyncExecShell(`DOCKER_HOST=${host} docker network ls --filter 'name=${network}' --no-trunc --format "{{json .}}"`); - if (!stdout) { await asyncExecShell(`DOCKER_HOST=${host} docker network create --attachable ${network}`); } - + const { stdout: coolifyNetwork } = await asyncExecShell(`DOCKER_HOST=${host} docker network ls --filter 'name=coolify-infra' --no-trunc --format "{{json .}}"`); + if (!coolifyNetwork) { + await asyncExecShell(`DOCKER_HOST=${host} docker network create --attachable coolify-infra`); + } + if (isCoolifyProxyUsed) await startTraefikProxy(id); await prisma.destinationDocker.update({ where: { id }, data: { remoteVerified: true } }) return reply.code(201).send() @@ -252,7 +229,7 @@ export async function getDestinationStatus(request: FastifyRequest) { try { const { id } = request.params const destination = await prisma.destinationDocker.findUnique({ where: { id } }) - const isRunning = await checkContainer({ dockerId: destination.id, container: 'coolify-proxy' }) + const isRunning = await checkContainer({ dockerId: destination.id, container: 'coolify-proxy', remove: true }) return { isRunning } diff --git a/apps/api/src/routes/api/v1/destinations/index.ts b/apps/api/src/routes/api/v1/destinations/index.ts index 007242695..774afa285 100644 --- a/apps/api/src/routes/api/v1/destinations/index.ts +++ b/apps/api/src/routes/api/v1/destinations/index.ts @@ -23,7 +23,7 @@ const root: FastifyPluginAsync = async (fastify): Promise => { fastify.post('/:id/configuration/sshKey', async (request) => await assignSSHKey(request)); - fastify.post('/:id/verify', async (request, reply) => await verifyRemoteDockerEngine(request, reply)); + fastify.post('/:id/verify', async (request, reply) => await verifyRemoteDockerEngine(request, reply)); }; export default root; diff --git a/apps/api/src/routes/api/v1/handlers.ts b/apps/api/src/routes/api/v1/handlers.ts index 69dd9b468..702ad31a8 100644 --- a/apps/api/src/routes/api/v1/handlers.ts +++ b/apps/api/src/routes/api/v1/handlers.ts @@ -1,11 +1,11 @@ import os from 'node:os'; import osu from 'node-os-utils'; import axios from 'axios'; -import compare from 'compare-versions'; +import { compareVersions } from 'compare-versions'; import cuid from 'cuid'; import bcrypt from 'bcryptjs'; -import { asyncExecShell, asyncSleep, cleanupDockerStorage, errorHandler, isDev, prisma, uniqueName, version } from '../../../lib/common'; - +import { asyncExecShell, asyncSleep, cleanupDockerStorage, errorHandler, isDev, listSettings, prisma, uniqueName, version } from '../../../lib/common'; +import { supportedServiceTypesAndVersions } from '../../../lib/services/supportedVersions'; import type { FastifyReply, FastifyRequest } from 'fastify'; import type { Login, Update } from '.'; import type { GetCurrentUser } from './types'; @@ -31,11 +31,14 @@ export async function checkUpdate(request: FastifyRequest) { const { data: versions } = await axios.get( `https://get.coollabs.io/versions.json?appId=${process.env['COOLIFY_APP_ID']}&version=${currentVersion}` ); - const latestVersion = - isStaging - ? versions['coolify'].next.version - : versions['coolify'].main.version; - const isUpdateAvailable = compare(latestVersion, currentVersion); + const latestVersion = versions['coolify'].main.version + const isUpdateAvailable = compareVersions(latestVersion, currentVersion); + if (isStaging) { + return { + isUpdateAvailable: true, + latestVersion: 'next' + } + } return { isUpdateAvailable: isStaging ? true : isUpdateAvailable === 1, latestVersion @@ -62,7 +65,6 @@ export async function update(request: FastifyRequest) { ); return {}; } else { - console.log(latestVersion); await asyncSleep(2000); return {}; } @@ -70,6 +72,22 @@ export async function update(request: FastifyRequest) { return errorHandler({ status, message }) } } +export async function restartCoolify(request: FastifyRequest) { + try { + const teamId = request.user.teamId; + if (teamId === '0') { + if (!isDev) { + asyncExecShell(`docker restart coolify`); + return {}; + } else { + return {}; + } + } + throw { status: 500, message: 'You are not authorized to restart Coolify.' }; + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} export async function showUsage() { try { return { @@ -93,34 +111,23 @@ export async function showDashboard(request: FastifyRequest) { try { const userId = request.user.userId; const teamId = request.user.teamId; - const applicationsCount = await prisma.application.count({ + const applications = await prisma.application.findMany({ + where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } }, + include: { settings: true } + }); + const databases = await prisma.database.findMany({ + where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } }, + include: { settings: true } + }); + const services = await prisma.service.findMany({ where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } } }); - const sourcesCount = await prisma.gitSource.count({ - where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } } - }); - const destinationsCount = await prisma.destinationDocker.count({ - where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } } - }); - const teamsCount = await prisma.permission.count({ where: { userId } }); - const databasesCount = await prisma.database.count({ - where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } } - }); - const servicesCount = await prisma.service.count({ - where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } } - }); - const teams = await prisma.permission.findMany({ - where: { userId }, - include: { team: { include: { _count: { select: { users: true } } } } } - }); + const settings = await listSettings(); return { - teams, - applicationsCount, - sourcesCount, - destinationsCount, - teamsCount, - databasesCount, - servicesCount, + applications, + databases, + services, + settings, }; } catch ({ status, message }) { return errorHandler({ status, message }) @@ -291,6 +298,7 @@ export async function getCurrentUser(request: FastifyRequest, fa } return { settings: await prisma.setting.findFirst(), + supportedServiceTypesAndVersions, token, ...request.user } diff --git a/apps/api/src/routes/api/v1/iam/handlers.ts b/apps/api/src/routes/api/v1/iam/handlers.ts index 72d648793..b423b16bb 100644 --- a/apps/api/src/routes/api/v1/iam/handlers.ts +++ b/apps/api/src/routes/api/v1/iam/handlers.ts @@ -158,8 +158,11 @@ export async function getTeam(request: FastifyRequest, reply: FastifyRep }); const team = await prisma.team.findUnique({ where: { id }, include: { permissions: true } }); const invitations = await prisma.teamInvitation.findMany({ where: { teamId: team.id } }); + const { teams } = await prisma.user.findUnique({ where: { id: userId }, include: { teams: true } }) return { + currentTeam: teamId, team, + teams, permissions, invitations }; @@ -275,10 +278,10 @@ export async function inviteToTeam(request: FastifyRequest, reply: if (!userFound) { throw { message: `No user found with '${email}' email address.` - }; + }; } const uid = userFound.id; - if (uid === userId) { + if (uid === userId) { throw { message: `Invitation to yourself? Whaaaaat?` }; diff --git a/apps/api/src/routes/api/v1/index.ts b/apps/api/src/routes/api/v1/index.ts index 0d145312d..8f9f821f8 100644 --- a/apps/api/src/routes/api/v1/index.ts +++ b/apps/api/src/routes/api/v1/index.ts @@ -1,5 +1,5 @@ import { FastifyPluginAsync } from 'fastify'; -import { checkUpdate, login, showDashboard, update, showUsage, getCurrentUser, cleanupManually } from './handlers'; +import { checkUpdate, login, showDashboard, update, showUsage, getCurrentUser, cleanupManually, restartCoolify } from './handlers'; import { GetCurrentUser } from './types'; export interface Update { @@ -47,6 +47,10 @@ const root: FastifyPluginAsync = async (fastify): Promise => { onRequest: [fastify.authenticate] }, async () => await showUsage()); + fastify.post('/internal/restart', { + onRequest: [fastify.authenticate] + }, async (request) => await restartCoolify(request)); + fastify.post('/internal/cleanup', { onRequest: [fastify.authenticate] }, async () => await cleanupManually()); diff --git a/apps/api/src/routes/api/v1/services/handlers.ts b/apps/api/src/routes/api/v1/services/handlers.ts index cb2b2abb7..c6858a7d7 100644 --- a/apps/api/src/routes/api/v1/services/handlers.ts +++ b/apps/api/src/routes/api/v1/services/handlers.ts @@ -1,146 +1,15 @@ import type { FastifyReply, FastifyRequest } from 'fastify'; import fs from 'fs/promises'; import yaml from 'js-yaml'; -import bcrypt from 'bcryptjs'; -import { prisma, uniqueName, asyncExecShell, getServiceImage, configureServiceType, getServiceFromDB, getContainerUsage, removeService, isDomainConfigured, saveUpdateableFields, fixType, decrypt, encrypt, getServiceMainPort, createDirectories, ComposeFile, makeLabelForServices, getFreePublicPort, getDomain, errorHandler, generatePassword, isDev, stopTcpHttpProxy, supportedServiceTypesAndVersions, executeDockerCmd, listSettings, getFreeExposedPort, checkDomainsIsValidInDNS } from '../../../../lib/common'; +import { prisma, uniqueName, asyncExecShell, getServiceFromDB, getContainerUsage, isDomainConfigured, saveUpdateableFields, fixType, decrypt, encrypt, ComposeFile, getFreePublicPort, getDomain, errorHandler, generatePassword, isDev, stopTcpHttpProxy, executeDockerCmd, checkDomainsIsValidInDNS, checkExposedPort } from '../../../../lib/common'; import { day } from '../../../../lib/dayjs'; -import { checkContainer, isContainerExited, removeContainer } from '../../../../lib/docker'; +import { checkContainer, isContainerExited } from '../../../../lib/docker'; import cuid from 'cuid'; import type { OnlyId } from '../../../../types'; -import type { ActivateWordpressFtp, CheckService, CheckServiceDomain, DeleteServiceSecret, DeleteServiceStorage, GetServiceLogs, SaveService, SaveServiceDestination, SaveServiceSecret, SaveServiceSettings, SaveServiceStorage, SaveServiceType, SaveServiceVersion, ServiceStartStop, SetWordpressSettings } from './types'; - -// async function startServiceNew(request: FastifyRequest) { -// try { -// const { id } = request.params; -// const teamId = request.user.teamId; -// const service = await getServiceFromDB({ id, teamId }); -// const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort } = -// service; -// const network = destinationDockerId && destinationDocker.network; -// const host = getEngine(destinationDocker.engine); -// const port = getServiceMainPort(type); - -// const { workdir } = await createDirectories({ repository: type, buildId: id }); -// const image = getServiceImage(type); -// const config = (await getAvailableServices()).find((name) => name.name === type).compose -// const environmentVariables = {} -// if (serviceSecret.length > 0) { -// serviceSecret.forEach((secret) => { -// environmentVariables[secret.name] = secret.value; -// }); -// } -// config.newVolumes = {} -// for (const service of Object.entries(config.services)) { -// const name = service[0] -// const details: any = service[1] -// config.services[`${id}-${name}`] = JSON.parse(JSON.stringify(details)) -// config.services[`${id}-${name}`].container_name = `${id}-${name}` -// config.services[`${id}-${name}`].restart = "always" -// config.services[`${id}-${name}`].networks = [network] -// config.services[`${id}-${name}`].labels = makeLabelForServices(type) -// if (name === config.name) { -// config.services[`${id}-${name}`].image = `${details.image.split(':')[0]}:${version}` -// config.services[`${id}-${name}`].ports = (exposePort ? [`${exposePort}:${port}`] : []) -// config.services[`${id}-${name}`].environment = environmentVariables -// } -// config.services[`${id}-${name}`].deploy = { -// restart_policy: { -// condition: 'on-failure', -// delay: '5s', -// max_attempts: 3, -// window: '120s' -// } -// } -// if (config.services[`${id}-${name}`]?.volumes?.length > 0) { -// config.services[`${id}-${name}`].volumes.forEach((volume, index) => { -// let oldVolumeName = volume.split(':')[0] -// const path = volume.split(':')[1] -// // if (config?.volumes[oldVolumeName]) delete config?.volumes[oldVolumeName] -// const newName = convertTolOldVolumeNames(type) -// if (newName) oldVolumeName = newName - -// const volumeName = `${id}-${oldVolumeName}` -// config.newVolumes[volumeName] = { -// name: volumeName -// } -// config.services[`${id}-${name}`].volumes[index] = `${volumeName}:${path}` -// }) -// config.services[`${id}-${config.name}`] = { -// ...config.services[`${id}-${config.name}`], -// environment: environmentVariables -// } -// } -// config.networks = { -// [network]: { -// external: true -// } -// } - -// config.volumes = config.newVolumes - -// // config.services[`${id}-${name}`]?.volumes?.length > 0 && config.services[`${id}-${name}`].volumes.forEach((volume, index) => { -// // let oldVolumeName = volume.split(':')[0] -// // const path = volume.split(':')[1] -// // oldVolumeName = convertTolOldVolumeNames(type) -// // const volumeName = `${id}-${oldVolumeName}` -// // config.volumes[volumeName] = { -// // name: volumeName -// // } -// // config.services[`${id}-${name}`].volumes[index] = `${volumeName}:${path}` -// // }) -// // config.services[`${id}-${config.name}`] = { -// // ...config.services[`${id}-${config.name}`], -// // environment: environmentVariables -// // } -// delete config.services[name] - -// } -// console.log(config.services) -// console.log(config.volumes) - -// // config.services[id] = JSON.parse(JSON.stringify(config.services[type])) -// // config.services[id].container_name = id -// // config.services[id].image = `${image}:${version}` -// // config.services[id].ports = (exposePort ? [`${exposePort}:${port}`] : []), -// // config.services[id].restart = "always" -// // config.services[id].networks = [network] -// // config.services[id].labels = makeLabelForServices(type) -// // config.services[id].deploy = { -// // restart_policy: { -// // condition: 'on-failure', -// // delay: '5s', -// // max_attempts: 3, -// // window: '120s' -// // } -// // } -// // config.networks = { -// // [network]: { -// // external: true -// // } -// // } -// // config.volumes = {} -// // config.services[id].volumes.forEach((volume, index) => { -// // let oldVolumeName = volume.split(':')[0] -// // const path = volume.split(':')[1] -// // oldVolumeName = convertTolOldVolumeNames(type) -// // const volumeName = `${id}-${oldVolumeName}` -// // config.volumes[volumeName] = { -// // name: volumeName -// // } -// // config.services[id].volumes[index] = `${volumeName}:${path}` -// // }) -// // delete config.services[type] -// // config.services[id].environment = environmentVariables -// const composeFileDestination = `${workdir}/docker-compose.yaml`; -// // await fs.writeFile(composeFileDestination, yaml.dump(config)); -// // await asyncExecShell(`DOCKER_HOST=${host} docker compose -f ${composeFileDestination} pull`); -// // await asyncExecShell(`DOCKER_HOST=${host} docker compose -f ${composeFileDestination} up -d`); -// return {} -// } catch ({ status, message }) { -// return errorHandler({ status, message }) -// } -// } +import type { ActivateWordpressFtp, CheckService, CheckServiceDomain, DeleteServiceSecret, DeleteServiceStorage, GetServiceLogs, SaveService, SaveServiceDestination, SaveServiceSecret, SaveServiceSettings, SaveServiceStorage, SaveServiceType, SaveServiceVersion, ServiceStartStop, SetGlitchTipSettings, SetWordpressSettings } from './types'; +import { supportedServiceTypesAndVersions } from '../../../../lib/services/supportedVersions'; +import { configureServiceType, removeService } from '../../../../lib/services/common'; export async function listServices(request: FastifyRequest) { try { @@ -197,13 +66,11 @@ export async function getService(request: FastifyRequest) { const teamId = request.user.teamId; const { id } = request.params; const service = await getServiceFromDB({ id, teamId }); - const settings = await listSettings() if (!service) { throw { status: 404, message: 'Service not found.' } } return { - service, - settings + service } } catch ({ status, message }) { return errorHandler({ status, message }) @@ -368,30 +235,19 @@ export async function checkService(request: FastifyRequest) { const { destinationDocker: { id: dockerId, remoteIpAddress, remoteEngine }, exposePort: configuredPort } = await prisma.service.findUnique({ where: { id }, include: { destinationDocker: true } }) const { isDNSCheckEnabled } = await prisma.setting.findFirst({}); - let found = await isDomainConfigured({ id, fqdn, dockerId }); + let found = await isDomainConfigured({ id, fqdn, remoteIpAddress }); if (found) { throw { status: 500, message: `Domain ${getDomain(fqdn).replace('www.', '')} is already in use!` } } if (otherFqdns && otherFqdns.length > 0) { for (const ofqdn of otherFqdns) { - found = await isDomainConfigured({ id, fqdn: ofqdn, dockerId }); + found = await isDomainConfigured({ id, fqdn: ofqdn, remoteIpAddress }); if (found) { throw { status: 500, message: `Domain ${getDomain(ofqdn).replace('www.', '')} is already in use!` } } } } - if (exposePort) { - if (exposePort < 1024 || exposePort > 65535) { - throw { status: 500, message: `Exposed Port needs to be between 1024 and 65535.` } - } - - if (configuredPort !== exposePort) { - const availablePort = await getFreeExposedPort(id, exposePort, dockerId, remoteIpAddress); - if (availablePort.toString() !== exposePort.toString()) { - throw { status: 500, message: `Port ${exposePort} is already in use.` } - } - } - } + if (exposePort) await checkExposedPort({ id, configuredPort, exposePort, dockerId, remoteIpAddress }) if (isDNSCheckEnabled && !isDev && !forceSave) { let hostname = request.hostname.split(':')[0]; if (remoteEngine) hostname = remoteIpAddress; @@ -411,7 +267,6 @@ export async function saveService(request: FastifyRequest, reply: F if (exposePort) exposePort = Number(exposePort); type = fixType(type) - const update = saveUpdateableFields(type, request.body[type]) const data = { fqdn, @@ -460,13 +315,13 @@ export async function saveServiceSecret(request: FastifyRequest) { - try { - const { type } = request.params - if (type === 'plausibleanalytics') { - return await startPlausibleAnalyticsService(request) - } - if (type === 'nocodb') { - return await startNocodbService(request) - } - if (type === 'minio') { - return await startMinioService(request) - } - if (type === 'vscodeserver') { - return await startVscodeService(request) - } - if (type === 'wordpress') { - return await startWordpressService(request) - } - if (type === 'vaultwarden') { - return await startVaultwardenService(request) - } - if (type === 'languagetool') { - return await startLanguageToolService(request) - } - if (type === 'n8n') { - return await startN8nService(request) - } - if (type === 'uptimekuma') { - return await startUptimekumaService(request) - } - if (type === 'ghost') { - return await startGhostService(request) - } - if (type === 'meilisearch') { - return await startMeilisearchService(request) - } - if (type === 'umami') { - return await startUmamiService(request) - } - if (type === 'hasura') { - return await startHasuraService(request) - } - if (type === 'fider') { - return await startFiderService(request) - } - if (type === 'moodle') { - return await startMoodleService(request) - } - throw `Service type ${type} not supported.` - } catch (error) { - throw { status: 500, message: error?.message || error } - } -} -export async function stopService(request: FastifyRequest) { - try { - const { type } = request.params - if (type === 'plausibleanalytics') { - return await stopPlausibleAnalyticsService(request) - } - if (type === 'nocodb') { - return await stopNocodbService(request) - } - if (type === 'minio') { - return await stopMinioService(request) - } - if (type === 'vscodeserver') { - return await stopVscodeService(request) - } - if (type === 'wordpress') { - return await stopWordpressService(request) - } - if (type === 'vaultwarden') { - return await stopVaultwardenService(request) - } - if (type === 'languagetool') { - return await stopLanguageToolService(request) - } - if (type === 'n8n') { - return await stopN8nService(request) - } - if (type === 'uptimekuma') { - return await stopUptimekumaService(request) - } - if (type === 'ghost') { - return await stopGhostService(request) - } - if (type === 'meilisearch') { - return await stopMeilisearchService(request) - } - if (type === 'umami') { - return await stopUmamiService(request) - } - if (type === 'hasura') { - return await stopHasuraService(request) - } - if (type === 'fider') { - return await stopFiderService(request) - } - if (type === 'moodle') { - return await stopMoodleService(request) - } - throw `Service type ${type} not supported.` - } catch (error) { - throw { status: 500, message: error?.message || error } - } -} -export async function setSettingsService(request: FastifyRequest, reply: FastifyReply) { +export async function setSettingsService(request: FastifyRequest, reply: FastifyReply) { try { const { type } = request.params if (type === 'wordpress') { return await setWordpressSettings(request, reply) } + if (type === 'glitchtip') { + return await setGlitchTipSettings(request, reply) + } throw `Service type ${type} not supported.` } catch ({ status, message }) { return errorHandler({ status, message }) } } +async function setGlitchTipSettings(request: FastifyRequest, reply: FastifyReply) { + try { + const { id } = request.params + const { enableOpenUserRegistration, emailSmtpUseSsl, emailSmtpUseTls } = request.body + await prisma.glitchTip.update({ + where: { serviceId: id }, + data: { enableOpenUserRegistration, emailSmtpUseSsl, emailSmtpUseTls } + }); + return reply.code(201).send() + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} async function setWordpressSettings(request: FastifyRequest, reply: FastifyReply) { try { const { id } = request.params @@ -673,1999 +438,6 @@ async function setWordpressSettings(request: FastifyRequest) { - try { - const { id } = request.params - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { - type, - version, - fqdn, - destinationDockerId, - destinationDocker, - serviceSecret, - exposePort, - plausibleAnalytics: { - id: plausibleDbId, - username, - email, - password, - postgresqlDatabase, - postgresqlPassword, - postgresqlUser, - secretKeyBase - } - } = service; - const image = getServiceImage(type); - - const config = { - plausibleAnalytics: { - image: `${image}:${version}`, - environmentVariables: { - ADMIN_USER_EMAIL: email, - ADMIN_USER_NAME: username, - ADMIN_USER_PWD: password, - BASE_URL: fqdn, - SECRET_KEY_BASE: secretKeyBase, - DISABLE_AUTH: 'false', - DISABLE_REGISTRATION: 'true', - DATABASE_URL: `postgresql://${postgresqlUser}:${postgresqlPassword}@${id}-postgresql:5432/${postgresqlDatabase}`, - CLICKHOUSE_DATABASE_URL: `http://${id}-clickhouse:8123/plausible` - } - }, - postgresql: { - volume: `${plausibleDbId}-postgresql-data:/bitnami/postgresql/`, - image: 'bitnami/postgresql:13.2.0', - environmentVariables: { - POSTGRESQL_PASSWORD: postgresqlPassword, - POSTGRESQL_USERNAME: postgresqlUser, - POSTGRESQL_DATABASE: postgresqlDatabase - } - }, - clickhouse: { - volume: `${plausibleDbId}-clickhouse-data:/var/lib/clickhouse`, - image: 'yandex/clickhouse-server:21.3.2.5', - environmentVariables: {}, - ulimits: { - nofile: { - soft: 262144, - hard: 262144 - } - } - } - }; - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.plausibleAnalytics.environmentVariables[secret.name] = secret.value; - }); - } - const network = destinationDockerId && destinationDocker.network; - const port = getServiceMainPort('plausibleanalytics'); - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - - const clickhouseConfigXml = ` - - - warning - true - - - - - - - - - - `; - const clickhouseUserConfigXml = ` - - - - 0 - 0 - - - `; - - const initQuery = 'CREATE DATABASE IF NOT EXISTS plausible;'; - const initScript = 'clickhouse client --queries-file /docker-entrypoint-initdb.d/init.query'; - await fs.writeFile(`${workdir}/clickhouse-config.xml`, clickhouseConfigXml); - await fs.writeFile(`${workdir}/clickhouse-user-config.xml`, clickhouseUserConfigXml); - await fs.writeFile(`${workdir}/init.query`, initQuery); - await fs.writeFile(`${workdir}/init-db.sh`, initScript); - - const Dockerfile = ` -FROM ${config.clickhouse.image} -COPY ./clickhouse-config.xml /etc/clickhouse-server/users.d/logging.xml -COPY ./clickhouse-user-config.xml /etc/clickhouse-server/config.d/logging.xml -COPY ./init.query /docker-entrypoint-initdb.d/init.query -COPY ./init-db.sh /docker-entrypoint-initdb.d/init-db.sh`; - - await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile); - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.plausibleAnalytics.image, - command: - 'sh -c "sleep 10 && /entrypoint.sh db createdb && /entrypoint.sh db migrate && /entrypoint.sh db init-admin && /entrypoint.sh run"', - networks: [network], - environment: config.plausibleAnalytics.environmentVariables, - restart: 'always', - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - depends_on: [`${id}-postgresql`, `${id}-clickhouse`], - labels: makeLabelForServices('plausibleAnalytics'), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '10s', - max_attempts: 5, - window: '120s' - } - } - }, - [`${id}-postgresql`]: { - container_name: `${id}-postgresql`, - image: config.postgresql.image, - networks: [network], - environment: config.postgresql.environmentVariables, - volumes: [config.postgresql.volume], - restart: 'always', - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '10s', - max_attempts: 5, - window: '120s' - } - } - }, - [`${id}-clickhouse`]: { - build: workdir, - container_name: `${id}-clickhouse`, - networks: [network], - environment: config.clickhouse.environmentVariables, - volumes: [config.clickhouse.volume], - restart: 'always', - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '10s', - max_attempts: 5, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.postgresql.volume.split(':')[0]]: { - name: config.postgresql.volume.split(':')[0] - }, - [config.clickhouse.volume.split(':')[0]]: { - name: config.clickhouse.volume.split(':')[0] - } - } - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopPlausibleAnalyticsService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker, fqdn } = service; - if (destinationDockerId) { - const engine = destinationDocker.engine; - - let found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - found = await checkContainer({ dockerId: destinationDocker.id, container: `${id}-postgresql` }); - if (found) { - await removeContainer({ id: `${id}-postgresql`, dockerId: destinationDocker.id }); - } - found = await checkContainer({ dockerId: destinationDocker.id, container: `${id}-clickhouse` }); - if (found) { - await removeContainer({ id: `${id}-clickhouse`, dockerId: destinationDocker.id }); - } - } - - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startNocodbService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort } = - service; - const network = destinationDockerId && destinationDocker.network; - const port = getServiceMainPort('nocodb'); - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const image = getServiceImage(type); - - const config = { - image: `${image}:${version}`, - volume: `${id}-nc:/usr/app/data`, - environmentVariables: {} - }; - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.environmentVariables[secret.name] = secret.value; - }); - } - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.image, - networks: [network], - volumes: [config.volume], - environment: config.environmentVariables, - restart: 'always', - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - labels: makeLabelForServices('nocodb'), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.volume.split(':')[0]]: { - name: config.volume.split(':')[0] - } - } - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopNocodbService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker, fqdn } = service; - if (destinationDockerId) { - const found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startMinioService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { - type, - version, - fqdn, - destinationDockerId, - destinationDocker, - exposePort, - minio: { rootUser, rootUserPassword }, - serviceSecret - } = service; - - const network = destinationDockerId && destinationDocker.network; - const port = getServiceMainPort('minio'); - - const { service: { destinationDocker: { id: dockerId } } } = await prisma.minio.findUnique({ where: { serviceId: id }, include: { service: { include: { destinationDocker: true } } } }) - const publicPort = await getFreePublicPort(id, dockerId); - - const consolePort = 9001; - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const image = getServiceImage(type); - - const config = { - image: `${image}:${version}`, - volume: `${id}-minio-data:/data`, - environmentVariables: { - MINIO_ROOT_USER: rootUser, - MINIO_ROOT_PASSWORD: rootUserPassword, - MINIO_BROWSER_REDIRECT_URL: fqdn - } - }; - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.environmentVariables[secret.name] = secret.value; - }); - } - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.image, - command: `server /data --console-address ":${consolePort}"`, - environment: config.environmentVariables, - networks: [network], - volumes: [config.volume], - restart: 'always', - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - labels: makeLabelForServices('minio'), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.volume.split(':')[0]]: { - name: config.volume.split(':')[0] - } - } - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - await prisma.minio.update({ where: { serviceId: id }, data: { publicPort } }); - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopMinioService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker } = service; - await prisma.minio.update({ where: { serviceId: id }, data: { publicPort: null } }) - if (destinationDockerId) { - const found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startVscodeService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { - type, - version, - destinationDockerId, - destinationDocker, - serviceSecret, - persistentStorage, - exposePort, - vscodeserver: { password } - } = service; - - const network = destinationDockerId && destinationDocker.network; - const port = getServiceMainPort('vscodeserver'); - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const image = getServiceImage(type); - - const config = { - image: `${image}:${version}`, - volume: `${id}-vscodeserver-data:/home/coder`, - environmentVariables: { - PASSWORD: password - } - }; - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.environmentVariables[secret.name] = secret.value; - }); - } - - const volumes = - persistentStorage?.map((storage) => { - return `${id}${storage.path.replace(/\//gi, '-')}:${storage.path}`; - }) || []; - - const composeVolumes = volumes.map((volume) => { - return { - [`${volume.split(':')[0]}`]: { - name: volume.split(':')[0] - } - }; - }); - const volumeMounts = Object.assign( - {}, - { - [config.volume.split(':')[0]]: { - name: config.volume.split(':')[0] - } - }, - ...composeVolumes - ); - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.image, - environment: config.environmentVariables, - networks: [network], - volumes: [config.volume, ...volumes], - restart: 'always', - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - labels: makeLabelForServices('vscodeServer'), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: volumeMounts - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - - const changePermissionOn = persistentStorage.map((p) => p.path); - if (changePermissionOn.length > 0) { - await executeDockerCmd({ - dockerId: destinationDocker.id, command: `docker exec -u root ${id} chown -R 1000:1000 ${changePermissionOn.join( - ' ' - )}` - }) - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopVscodeService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker } = service; - if (destinationDockerId) { - const found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startWordpressService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { - type, - version, - destinationDockerId, - serviceSecret, - destinationDocker, - exposePort, - wordpress: { - mysqlDatabase, - mysqlHost, - mysqlPort, - mysqlUser, - mysqlPassword, - extraConfig, - mysqlRootUser, - mysqlRootUserPassword, - ownMysql - } - } = service; - - const network = destinationDockerId && destinationDocker.network; - const image = getServiceImage(type); - const port = getServiceMainPort('wordpress'); - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const config = { - wordpress: { - image: `${image}:${version}`, - volume: `${id}-wordpress-data:/var/www/html`, - environmentVariables: { - WORDPRESS_DB_HOST: ownMysql ? `${mysqlHost}:${mysqlPort}` : `${id}-mysql`, - WORDPRESS_DB_USER: mysqlUser, - WORDPRESS_DB_PASSWORD: mysqlPassword, - WORDPRESS_DB_NAME: mysqlDatabase, - WORDPRESS_CONFIG_EXTRA: extraConfig - } - }, - mysql: { - image: `bitnami/mysql:5.7`, - volume: `${id}-mysql-data:/bitnami/mysql/data`, - environmentVariables: { - MYSQL_ROOT_PASSWORD: mysqlRootUserPassword, - MYSQL_ROOT_USER: mysqlRootUser, - MYSQL_USER: mysqlUser, - MYSQL_PASSWORD: mysqlPassword, - MYSQL_DATABASE: mysqlDatabase - } - } - }; - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.wordpress.environmentVariables[secret.name] = secret.value; - }); - } - let composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.wordpress.image, - environment: config.wordpress.environmentVariables, - volumes: [config.wordpress.volume], - networks: [network], - restart: 'always', - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - labels: makeLabelForServices('wordpress'), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.wordpress.volume.split(':')[0]]: { - name: config.wordpress.volume.split(':')[0] - } - } - }; - if (!ownMysql) { - composeFile.services[id].depends_on = [`${id}-mysql`]; - composeFile.services[`${id}-mysql`] = { - container_name: `${id}-mysql`, - image: config.mysql.image, - volumes: [config.mysql.volume], - environment: config.mysql.environmentVariables, - networks: [network], - restart: 'always', - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - }; - - composeFile.volumes[config.mysql.volume.split(':')[0]] = { - name: config.mysql.volume.split(':')[0] - }; - } - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopWordpressService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { - destinationDockerId, - destinationDocker, - wordpress: { ftpEnabled } - } = service; - if (destinationDockerId) { - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: `${id}-mysql` }); - if (found) { - await removeContainer({ id: `${id}-mysql`, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - try { - if (ftpEnabled) { - const found = await checkContainer({ dockerId: destinationDocker.id, container: `${id}-ftp` }); - if (found) { - await removeContainer({ id: `${id}-ftp`, dockerId: destinationDocker.id }); - } - await prisma.wordpress.update({ - where: { serviceId: id }, - data: { ftpEnabled: false } - }); - } - } catch (error) { - console.error(error); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startVaultwardenService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort } = - service; - - const network = destinationDockerId && destinationDocker.network; - const port = getServiceMainPort('vaultwarden'); - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const image = getServiceImage(type); - - const config = { - image: `${image}:${version}`, - volume: `${id}-vaultwarden-data:/data/`, - environmentVariables: {} - }; - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.environmentVariables[secret.name] = secret.value; - }); - } - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.image, - environment: config.environmentVariables, - networks: [network], - volumes: [config.volume], - restart: 'always', - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - labels: makeLabelForServices('vaultWarden'), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.volume.split(':')[0]]: { - name: config.volume.split(':')[0] - } - } - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopVaultwardenService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker } = service; - if (destinationDockerId) { - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startLanguageToolService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort } = - service; - const network = destinationDockerId && destinationDocker.network; - const port = getServiceMainPort('languagetool'); - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const image = getServiceImage(type); - - const config = { - image: `${image}:${version}`, - volume: `${id}-ngrams:/ngrams`, - environmentVariables: {} - }; - - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.environmentVariables[secret.name] = secret.value; - }); - } - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.image, - networks: [network], - environment: config.environmentVariables, - restart: 'always', - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - volumes: [config.volume], - labels: makeLabelForServices('languagetool'), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.volume.split(':')[0]]: { - name: config.volume.split(':')[0] - } - } - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopLanguageToolService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker } = service; - if (destinationDockerId) { - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startN8nService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort } = - service; - const network = destinationDockerId && destinationDocker.network; - const port = getServiceMainPort('n8n'); - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const image = getServiceImage(type); - - const config = { - image: `${image}:${version}`, - volume: `${id}-n8n:/root/.n8n`, - environmentVariables: { - WEBHOOK_URL: `${service.fqdn}` - } - }; - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.environmentVariables[secret.name] = secret.value; - }); - } - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.image, - networks: [network], - volumes: [config.volume], - environment: config.environmentVariables, - restart: 'always', - labels: makeLabelForServices('n8n'), - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.volume.split(':')[0]]: { - name: config.volume.split(':')[0] - } - } - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopN8nService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker } = service; - if (destinationDockerId) { - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startUptimekumaService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort } = - service; - const network = destinationDockerId && destinationDocker.network; - const port = getServiceMainPort('uptimekuma'); - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const image = getServiceImage(type); - - const config = { - image: `${image}:${version}`, - volume: `${id}-uptimekuma:/app/data`, - environmentVariables: {} - }; - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.environmentVariables[secret.name] = secret.value; - }); - } - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.image, - networks: [network], - volumes: [config.volume], - environment: config.environmentVariables, - restart: 'always', - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - labels: makeLabelForServices('uptimekuma'), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.volume.split(':')[0]]: { - name: config.volume.split(':')[0] - } - } - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopUptimekumaService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker } = service; - if (destinationDockerId) { - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startGhostService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { - type, - version, - destinationDockerId, - destinationDocker, - serviceSecret, - exposePort, - fqdn, - ghost: { - defaultEmail, - defaultPassword, - mariadbRootUser, - mariadbRootUserPassword, - mariadbDatabase, - mariadbPassword, - mariadbUser - } - } = service; - const network = destinationDockerId && destinationDocker.network; - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const image = getServiceImage(type); - const domain = getDomain(fqdn); - const port = getServiceMainPort('ghost'); - const isHttps = fqdn.startsWith('https://'); - const config = { - ghost: { - image: `${image}:${version}`, - volume: `${id}-ghost:/bitnami/ghost`, - environmentVariables: { - url: fqdn, - GHOST_HOST: domain, - GHOST_ENABLE_HTTPS: isHttps ? 'yes' : 'no', - GHOST_EMAIL: defaultEmail, - GHOST_PASSWORD: defaultPassword, - GHOST_DATABASE_HOST: `${id}-mariadb`, - GHOST_DATABASE_USER: mariadbUser, - GHOST_DATABASE_PASSWORD: mariadbPassword, - GHOST_DATABASE_NAME: mariadbDatabase, - GHOST_DATABASE_PORT_NUMBER: 3306 - } - }, - mariadb: { - image: `bitnami/mariadb:latest`, - volume: `${id}-mariadb:/bitnami/mariadb`, - environmentVariables: { - MARIADB_USER: mariadbUser, - MARIADB_PASSWORD: mariadbPassword, - MARIADB_DATABASE: mariadbDatabase, - MARIADB_ROOT_USER: mariadbRootUser, - MARIADB_ROOT_PASSWORD: mariadbRootUserPassword - } - } - }; - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.ghost.environmentVariables[secret.name] = secret.value; - }); - } - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.ghost.image, - networks: [network], - volumes: [config.ghost.volume], - environment: config.ghost.environmentVariables, - restart: 'always', - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - labels: makeLabelForServices('ghost'), - depends_on: [`${id}-mariadb`], - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - }, - [`${id}-mariadb`]: { - container_name: `${id}-mariadb`, - image: config.mariadb.image, - networks: [network], - volumes: [config.mariadb.volume], - environment: config.mariadb.environmentVariables, - restart: 'always', - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.ghost.volume.split(':')[0]]: { - name: config.ghost.volume.split(':')[0] - }, - [config.mariadb.volume.split(':')[0]]: { - name: config.mariadb.volume.split(':')[0] - } - } - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopGhostService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker } = service; - if (destinationDockerId) { - try { - let found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - found = await checkContainer({ dockerId: destinationDocker.id, container: `${id}-mariadb` }); - if (found) { - await removeContainer({ id: `${id}-mariadb`, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startMeilisearchService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { - meiliSearch: { masterKey } - } = service; - const { type, version, destinationDockerId, destinationDocker, serviceSecret, exposePort } = - service; - const network = destinationDockerId && destinationDocker.network; - const port = getServiceMainPort('meilisearch'); - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const image = getServiceImage(type); - - const config = { - image: `${image}:${version}`, - volume: `${id}-datams:/data.ms`, - environmentVariables: { - MEILI_MASTER_KEY: masterKey - } - }; - - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.environmentVariables[secret.name] = secret.value; - }); - } - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.image, - networks: [network], - environment: config.environmentVariables, - restart: 'always', - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - volumes: [config.volume], - labels: makeLabelForServices('meilisearch'), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.volume.split(':')[0]]: { - name: config.volume.split(':')[0] - } - } - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - - - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopMeilisearchService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker } = service; - if (destinationDockerId) { - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startUmamiService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { - type, - version, - destinationDockerId, - destinationDocker, - serviceSecret, - exposePort, - umami: { - umamiAdminPassword, - postgresqlUser, - postgresqlPassword, - postgresqlDatabase, - hashSalt - } - } = service; - const network = destinationDockerId && destinationDocker.network; - const port = getServiceMainPort('umami'); - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const image = getServiceImage(type); - - const config = { - umami: { - image: `${image}:${version}`, - environmentVariables: { - DATABASE_URL: `postgresql://${postgresqlUser}:${postgresqlPassword}@${id}-postgresql:5432/${postgresqlDatabase}`, - DATABASE_TYPE: 'postgresql', - HASH_SALT: hashSalt - } - }, - postgresql: { - image: 'postgres:12-alpine', - volume: `${id}-postgresql-data:/var/lib/postgresql/data`, - environmentVariables: { - POSTGRES_USER: postgresqlUser, - POSTGRES_PASSWORD: postgresqlPassword, - POSTGRES_DB: postgresqlDatabase - } - } - }; - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.umami.environmentVariables[secret.name] = secret.value; - }); - } - - const initDbSQL = ` - drop table if exists event; - drop table if exists pageview; - drop table if exists session; - drop table if exists website; - drop table if exists account; - - create table account ( - user_id serial primary key, - username varchar(255) unique not null, - password varchar(60) not null, - is_admin bool not null default false, - created_at timestamp with time zone default current_timestamp, - updated_at timestamp with time zone default current_timestamp - ); - - create table website ( - website_id serial primary key, - website_uuid uuid unique not null, - user_id int not null references account(user_id) on delete cascade, - name varchar(100) not null, - domain varchar(500), - share_id varchar(64) unique, - created_at timestamp with time zone default current_timestamp - ); - - create table session ( - session_id serial primary key, - session_uuid uuid unique not null, - website_id int not null references website(website_id) on delete cascade, - created_at timestamp with time zone default current_timestamp, - hostname varchar(100), - browser varchar(20), - os varchar(20), - device varchar(20), - screen varchar(11), - language varchar(35), - country char(2) - ); - - create table pageview ( - view_id serial primary key, - website_id int not null references website(website_id) on delete cascade, - session_id int not null references session(session_id) on delete cascade, - created_at timestamp with time zone default current_timestamp, - url varchar(500) not null, - referrer varchar(500) - ); - - create table event ( - event_id serial primary key, - website_id int not null references website(website_id) on delete cascade, - session_id int not null references session(session_id) on delete cascade, - created_at timestamp with time zone default current_timestamp, - url varchar(500) not null, - event_type varchar(50) not null, - event_value varchar(50) not null - ); - - create index website_user_id_idx on website(user_id); - - create index session_created_at_idx on session(created_at); - create index session_website_id_idx on session(website_id); - - create index pageview_created_at_idx on pageview(created_at); - create index pageview_website_id_idx on pageview(website_id); - create index pageview_session_id_idx on pageview(session_id); - create index pageview_website_id_created_at_idx on pageview(website_id, created_at); - create index pageview_website_id_session_id_created_at_idx on pageview(website_id, session_id, created_at); - - create index event_created_at_idx on event(created_at); - create index event_website_id_idx on event(website_id); - create index event_session_id_idx on event(session_id); - - insert into account (username, password, is_admin) values ('admin', '${bcrypt.hashSync( - umamiAdminPassword, - 10 - )}', true);`; - await fs.writeFile(`${workdir}/schema.postgresql.sql`, initDbSQL); - const Dockerfile = ` - FROM ${config.postgresql.image} - COPY ./schema.postgresql.sql /docker-entrypoint-initdb.d/schema.postgresql.sql`; - await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile); - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.umami.image, - environment: config.umami.environmentVariables, - networks: [network], - volumes: [], - restart: 'always', - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - labels: makeLabelForServices('umami'), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - }, - depends_on: [`${id}-postgresql`] - }, - [`${id}-postgresql`]: { - build: workdir, - container_name: `${id}-postgresql`, - environment: config.postgresql.environmentVariables, - networks: [network], - volumes: [config.postgresql.volume], - restart: 'always', - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.postgresql.volume.split(':')[0]]: { - name: config.postgresql.volume.split(':')[0] - } - } - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - - - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopUmamiService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker } = service; - if (destinationDockerId) { - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: `${id}-postgresql` }); - if (found) { - await removeContainer({ id: `${id}-postgresql`, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startHasuraService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { - type, - version, - destinationDockerId, - destinationDocker, - serviceSecret, - exposePort, - hasura: { postgresqlUser, postgresqlPassword, postgresqlDatabase } - } = service; - const network = destinationDockerId && destinationDocker.network; - const port = getServiceMainPort('hasura'); - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const image = getServiceImage(type); - - const config = { - hasura: { - image: `${image}:${version}`, - environmentVariables: { - HASURA_GRAPHQL_METADATA_DATABASE_URL: `postgresql://${postgresqlUser}:${postgresqlPassword}@${id}-postgresql:5432/${postgresqlDatabase}` - } - }, - postgresql: { - image: 'postgres:12-alpine', - volume: `${id}-postgresql-data:/var/lib/postgresql/data`, - environmentVariables: { - POSTGRES_USER: postgresqlUser, - POSTGRES_PASSWORD: postgresqlPassword, - POSTGRES_DB: postgresqlDatabase - } - } - }; - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.hasura.environmentVariables[secret.name] = secret.value; - }); - } - - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.hasura.image, - environment: config.hasura.environmentVariables, - networks: [network], - volumes: [], - restart: 'always', - labels: makeLabelForServices('hasura'), - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - }, - depends_on: [`${id}-postgresql`] - }, - [`${id}-postgresql`]: { - image: config.postgresql.image, - container_name: `${id}-postgresql`, - environment: config.postgresql.environmentVariables, - networks: [network], - volumes: [config.postgresql.volume], - restart: 'always', - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.postgresql.volume.split(':')[0]]: { - name: config.postgresql.volume.split(':')[0] - } - } - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopHasuraService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker } = service; - if (destinationDockerId) { - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: `${id}-postgresql` }); - if (found) { - await removeContainer({ id: `${id}-postgresql`, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startFiderService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { - type, - version, - fqdn, - destinationDockerId, - destinationDocker, - serviceSecret, - exposePort, - fider: { - postgresqlUser, - postgresqlPassword, - postgresqlDatabase, - jwtSecret, - emailNoreply, - emailMailgunApiKey, - emailMailgunDomain, - emailMailgunRegion, - emailSmtpHost, - emailSmtpPort, - emailSmtpUser, - emailSmtpPassword, - emailSmtpEnableStartTls - } - } = service; - const network = destinationDockerId && destinationDocker.network; - const port = getServiceMainPort('fider'); - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const image = getServiceImage(type); - const domain = getDomain(fqdn); - const config = { - fider: { - image: `${image}:${version}`, - environmentVariables: { - BASE_URL: domain, - DATABASE_URL: `postgresql://${postgresqlUser}:${postgresqlPassword}@${id}-postgresql:5432/${postgresqlDatabase}?sslmode=disable`, - JWT_SECRET: `${jwtSecret.replace(/\$/g, '$$$')}`, - EMAIL_NOREPLY: emailNoreply, - EMAIL_MAILGUN_API: emailMailgunApiKey, - EMAIL_MAILGUN_REGION: emailMailgunRegion, - EMAIL_MAILGUN_DOMAIN: emailMailgunDomain, - EMAIL_SMTP_HOST: emailSmtpHost, - EMAIL_SMTP_PORT: emailSmtpPort, - EMAIL_SMTP_USER: emailSmtpUser, - EMAIL_SMTP_PASSWORD: emailSmtpPassword, - EMAIL_SMTP_ENABLE_STARTTLS: emailSmtpEnableStartTls - } - }, - postgresql: { - image: 'postgres:12-alpine', - volume: `${id}-postgresql-data:/var/lib/postgresql/data`, - environmentVariables: { - POSTGRES_USER: postgresqlUser, - POSTGRES_PASSWORD: postgresqlPassword, - POSTGRES_DB: postgresqlDatabase - } - } - }; - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.fider.environmentVariables[secret.name] = secret.value; - }); - } - - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.fider.image, - environment: config.fider.environmentVariables, - networks: [network], - volumes: [], - restart: 'always', - labels: makeLabelForServices('fider'), - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - }, - depends_on: [`${id}-postgresql`] - }, - [`${id}-postgresql`]: { - image: config.postgresql.image, - container_name: `${id}-postgresql`, - environment: config.postgresql.environmentVariables, - networks: [network], - volumes: [config.postgresql.volume], - restart: 'always', - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - } - } - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.postgresql.volume.split(':')[0]]: { - name: config.postgresql.volume.split(':')[0] - } - } - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopFiderService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker } = service; - if (destinationDockerId) { - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: `${id}-postgresql` }); - if (found) { - await removeContainer({ id: `${id}-postgresql`, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - -async function startMoodleService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { - type, - version, - fqdn, - destinationDockerId, - destinationDocker, - serviceSecret, - exposePort, - moodle: { - defaultUsername, - defaultPassword, - defaultEmail, - mariadbRootUser, - mariadbRootUserPassword, - mariadbDatabase, - mariadbPassword, - mariadbUser - } - } = service; - const network = destinationDockerId && destinationDocker.network; - const port = getServiceMainPort('moodle'); - - const { workdir } = await createDirectories({ repository: type, buildId: id }); - const image = getServiceImage(type); - const config = { - moodle: { - image: `${image}:${version}`, - volume: `${id}-data:/bitnami/moodle`, - environmentVariables: { - MOODLE_USERNAME: defaultUsername, - MOODLE_PASSWORD: defaultPassword, - MOODLE_EMAIL: defaultEmail, - MOODLE_DATABASE_HOST: `${id}-mariadb`, - MOODLE_DATABASE_USER: mariadbUser, - MOODLE_DATABASE_PASSWORD: mariadbPassword, - MOODLE_DATABASE_NAME: mariadbDatabase, - MOODLE_REVERSEPROXY: 'yes' - } - }, - mariadb: { - image: 'bitnami/mariadb:latest', - volume: `${id}-mariadb-data:/bitnami/mariadb`, - environmentVariables: { - MARIADB_USER: mariadbUser, - MARIADB_PASSWORD: mariadbPassword, - MARIADB_DATABASE: mariadbDatabase, - MARIADB_ROOT_USER: mariadbRootUser, - MARIADB_ROOT_PASSWORD: mariadbRootUserPassword - } - } - }; - if (serviceSecret.length > 0) { - serviceSecret.forEach((secret) => { - config.moodle.environmentVariables[secret.name] = secret.value; - }); - } - - const composeFile: ComposeFile = { - version: '3.8', - services: { - [id]: { - container_name: id, - image: config.moodle.image, - environment: config.moodle.environmentVariables, - networks: [network], - volumes: [], - restart: 'always', - labels: makeLabelForServices('moodle'), - ...(exposePort ? { ports: [`${exposePort}:${port}`] } : {}), - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - }, - depends_on: [`${id}-mariadb`] - }, - [`${id}-mariadb`]: { - container_name: `${id}-mariadb`, - image: config.mariadb.image, - environment: config.mariadb.environmentVariables, - networks: [network], - volumes: [], - restart: 'always', - deploy: { - restart_policy: { - condition: 'on-failure', - delay: '5s', - max_attempts: 3, - window: '120s' - } - }, - depends_on: [] - } - - }, - networks: { - [network]: { - external: true - } - }, - volumes: { - [config.moodle.volume.split(':')[0]]: { - name: config.moodle.volume.split(':')[0] - }, - [config.mariadb.volume.split(':')[0]]: { - name: config.mariadb.volume.split(':')[0] - } - } - - }; - const composeFileDestination = `${workdir}/docker-compose.yaml`; - await fs.writeFile(composeFileDestination, yaml.dump(composeFile)); - - - //await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} pull` }) - await executeDockerCmd({ dockerId: destinationDocker.id, command: `docker compose -f ${composeFileDestination} up --build -d` }) - - - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} -async function stopMoodleService(request: FastifyRequest) { - try { - const { id } = request.params; - const teamId = request.user.teamId; - const service = await getServiceFromDB({ id, teamId }); - const { destinationDockerId, destinationDocker } = service; - if (destinationDockerId) { - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: id }); - if (found) { - await removeContainer({ id, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - try { - const found = await checkContainer({ dockerId: destinationDocker.id, container: `${id}-mariadb` }); - if (found) { - await removeContainer({ id: `${id}-mariadb`, dockerId: destinationDocker.id }); - } - } catch (error) { - console.error(error); - } - } - return {} - } catch ({ status, message }) { - return errorHandler({ status, message }) - } -} - export async function activatePlausibleUsers(request: FastifyRequest, reply: FastifyReply) { try { @@ -2688,6 +460,26 @@ export async function activatePlausibleUsers(request: FastifyRequest, re return errorHandler({ status, message }) } } +export async function cleanupPlausibleLogs(request: FastifyRequest, reply: FastifyReply) { + try { + const { id } = request.params + const teamId = request.user.teamId; + const { + destinationDockerId, + destinationDocker, + } = await getServiceFromDB({ id, teamId }); + if (destinationDockerId) { + await executeDockerCmd({ + dockerId: destinationDocker.id, + command: `docker exec ${id}-clickhouse sh -c "/usr/bin/clickhouse-client -q \\"SELECT name FROM system.tables WHERE name LIKE '%log%';\\"| xargs -I{} /usr/bin/clickhouse-client -q \"TRUNCATE TABLE system.{};\""` + }) + return await reply.code(201).send() + } + throw { status: 500, message: 'Could cleanup logs.' } + } catch ({ status, message }) { + return errorHandler({ status, message }) + } +} export async function activateWordpressFtp(request: FastifyRequest, reply: FastifyReply) { const { id } = request.params const { ftpEnabled } = request.body; @@ -2697,7 +489,7 @@ export async function activateWordpressFtp(request: FastifyRequest => { fastify.addHook('onRequest', async (request) => { @@ -71,9 +71,10 @@ const root: FastifyPluginAsync = async (fastify): Promise => { fastify.post('/:id/:type/start', async (request) => await startService(request)); fastify.post('/:id/:type/stop', async (request) => await stopService(request)); - fastify.post('/:id/:type/settings', async (request, reply) => await setSettingsService(request, reply)); + fastify.post('/:id/:type/settings', async (request, reply) => await setSettingsService(request, reply)); fastify.post('/:id/plausibleanalytics/activate', async (request, reply) => await activatePlausibleUsers(request, reply)); + fastify.post('/:id/plausibleanalytics/cleanup', async (request, reply) => await cleanupPlausibleLogs(request, reply)); fastify.post('/:id/wordpress/ftp', async (request, reply) => await activateWordpressFtp(request, reply)); }; diff --git a/apps/api/src/routes/api/v1/services/types.ts b/apps/api/src/routes/api/v1/services/types.ts index f09b4423f..3de06fa57 100644 --- a/apps/api/src/routes/api/v1/services/types.ts +++ b/apps/api/src/routes/api/v1/services/types.ts @@ -89,6 +89,10 @@ export interface ActivateWordpressFtp extends OnlyId { } } - - - +export interface SetGlitchTipSettings extends OnlyId { + Body: { + enableOpenUserRegistration: boolean, + emailSmtpUseSsl: boolean, + emailSmtpUseTls: boolean + } +} diff --git a/apps/api/src/routes/api/v1/settings/handlers.ts b/apps/api/src/routes/api/v1/settings/handlers.ts index 073dbd7e3..e9d91dd8c 100644 --- a/apps/api/src/routes/api/v1/settings/handlers.ts +++ b/apps/api/src/routes/api/v1/settings/handlers.ts @@ -28,17 +28,19 @@ export async function saveSettings(request: FastifyRequest, reply: try { const { fqdn, + isAPIDebuggingEnabled, isRegistrationEnabled, dualCerts, minPort, maxPort, isAutoUpdateEnabled, - isDNSCheckEnabled + isDNSCheckEnabled, + DNSServers } = request.body const { id } = await listSettings(); await prisma.setting.update({ where: { id }, - data: { isRegistrationEnabled, dualCerts, isAutoUpdateEnabled, isDNSCheckEnabled } + data: { isRegistrationEnabled, dualCerts, isAutoUpdateEnabled, isDNSCheckEnabled, DNSServers, isAPIDebuggingEnabled } }); if (fqdn) { await prisma.setting.update({ where: { id }, data: { fqdn } }); @@ -54,6 +56,10 @@ export async function saveSettings(request: FastifyRequest, reply: export async function deleteDomain(request: FastifyRequest, reply: FastifyReply) { try { const { fqdn } = request.body + const { DNSServers } = await listSettings(); + if (DNSServers) { + dns.setServers([DNSServers]); + } let ip; try { ip = await dns.resolve(fqdn); diff --git a/apps/api/src/routes/api/v1/settings/types.ts b/apps/api/src/routes/api/v1/settings/types.ts index a33b614a4..956c58b5c 100644 --- a/apps/api/src/routes/api/v1/settings/types.ts +++ b/apps/api/src/routes/api/v1/settings/types.ts @@ -3,12 +3,14 @@ import { OnlyId } from "../../../../types" export interface SaveSettings { Body: { fqdn: string, + isAPIDebuggingEnabled: boolean, isRegistrationEnabled: boolean, dualCerts: boolean, minPort: number, maxPort: number, isAutoUpdateEnabled: boolean, - isDNSCheckEnabled: boolean + isDNSCheckEnabled: boolean, + DNSServers: string } } export interface DeleteDomain { diff --git a/apps/api/src/routes/webhooks/github/handlers.ts b/apps/api/src/routes/webhooks/github/handlers.ts index 968305a97..de288022d 100644 --- a/apps/api/src/routes/webhooks/github/handlers.ts +++ b/apps/api/src/routes/webhooks/github/handlers.ts @@ -3,8 +3,7 @@ import cuid from "cuid"; import crypto from "crypto"; import { encrypt, errorHandler, getUIUrl, isDev, prisma } from "../../../lib/common"; import { checkContainer, removeContainer } from "../../../lib/docker"; -import { scheduler } from "../../../lib/scheduler"; -import { getApplicationFromDBWebhook } from "../../api/v1/applications/handlers"; +import { createdBranchDatabase, getApplicationFromDBWebhook, removeBranchDatabase } from "../../api/v1/applications/handlers"; import type { FastifyReply, FastifyRequest } from "fastify"; import type { GitHubEvents, InstallGithub } from "./types"; @@ -67,7 +66,6 @@ export async function configureGitHubApp(request, reply) { } export async function gitHubEvents(request: FastifyRequest): Promise { try { - const buildId = cuid(); const allowedGithubEvents = ['push', 'pull_request']; const allowedActions = ['opened', 'reopened', 'synchronize', 'closed']; const githubEvent = request.headers['x-github-event']?.toString().toLowerCase(); @@ -87,137 +85,139 @@ export async function gitHubEvents(request: FastifyRequest): Promi if (!projectId || !branch) { throw { status: 500, message: 'Cannot parse projectId or branch from the webhook?!' } } - const applicationFound = await getApplicationFromDBWebhook(projectId, branch); - if (applicationFound) { - const webhookSecret = applicationFound.gitSource.githubApp.webhookSecret || null; - //@ts-ignore - const hmac = crypto.createHmac('sha256', webhookSecret); - const digest = Buffer.from( - 'sha256=' + hmac.update(JSON.stringify(body)).digest('hex'), - 'utf8' - ); - if (!isDev) { - const checksum = Buffer.from(githubSignature, 'utf8'); + const applicationsFound = await getApplicationFromDBWebhook(projectId, branch); + if (applicationsFound && applicationsFound.length > 0) { + for (const application of applicationsFound) { + const buildId = cuid(); + const webhookSecret = application.gitSource.githubApp.webhookSecret || null; //@ts-ignore - if (checksum.length !== digest.length || !crypto.timingSafeEqual(digest, checksum)) { - throw { status: 500, message: 'SHA256 checksum failed. Are you doing something fishy?' } - }; - } - - - if (githubEvent === 'push') { - if (!applicationFound.configHash) { - const configHash = crypto - //@ts-ignore - .createHash('sha256') - .update( - JSON.stringify({ - buildPack: applicationFound.buildPack, - port: applicationFound.port, - exposePort: applicationFound.exposePort, - installCommand: applicationFound.installCommand, - buildCommand: applicationFound.buildCommand, - startCommand: applicationFound.startCommand - }) - ) - .digest('hex'); - await prisma.application.updateMany({ - where: { branch, projectId }, - data: { configHash } - }); - } - await prisma.application.update({ - where: { id: applicationFound.id }, - data: { updatedAt: new Date() } - }); - await prisma.build.create({ - data: { - id: buildId, - applicationId: applicationFound.id, - destinationDockerId: applicationFound.destinationDocker.id, - gitSourceId: applicationFound.gitSource.id, - githubAppId: applicationFound.gitSource.githubApp?.id, - gitlabAppId: applicationFound.gitSource.gitlabApp?.id, - status: 'queued', - type: 'webhook_commit' - } - }); - scheduler.workers.get('deployApplication').postMessage({ - build_id: buildId, - type: 'webhook_commit', - ...applicationFound - }); - - return { - message: 'Queued. Thank you!' - }; - } else if (githubEvent === 'pull_request') { - const pullmergeRequestId = body.number; - const pullmergeRequestAction = body.action; - const sourceBranch = body.pull_request.head.ref.includes('/') ? body.pull_request.head.ref.split('/')[2] : body.pull_request.head.ref; - if (!allowedActions.includes(pullmergeRequestAction)) { - throw { status: 500, message: 'Action not allowed.' } + const hmac = crypto.createHmac('sha256', webhookSecret); + const digest = Buffer.from( + 'sha256=' + hmac.update(JSON.stringify(body)).digest('hex'), + 'utf8' + ); + if (!isDev) { + const checksum = Buffer.from(githubSignature, 'utf8'); + //@ts-ignore + if (checksum.length !== digest.length || !crypto.timingSafeEqual(digest, checksum)) { + throw { status: 500, message: 'SHA256 checksum failed. Are you doing something fishy?' } + }; } - if (applicationFound.settings.previews) { - if (applicationFound.destinationDockerId) { - const isRunning = await checkContainer( - { - dockerId: applicationFound.destinationDocker.id, - container: applicationFound.id - } - ); - if (!isRunning) { - throw { status: 500, message: 'Application not running.' } - } - } - if ( - pullmergeRequestAction === 'opened' || - pullmergeRequestAction === 'reopened' || - pullmergeRequestAction === 'synchronize' - ) { + if (githubEvent === 'push') { + if (!application.configHash) { + const configHash = crypto + //@ts-ignore + .createHash('sha256') + .update( + JSON.stringify({ + buildPack: application.buildPack, + port: application.port, + exposePort: application.exposePort, + installCommand: application.installCommand, + buildCommand: application.buildCommand, + startCommand: application.startCommand + }) + ) + .digest('hex'); await prisma.application.update({ - where: { id: applicationFound.id }, - data: { updatedAt: new Date() } + where: { id: application.id }, + data: { configHash } }); - await prisma.build.create({ - data: { - id: buildId, - applicationId: applicationFound.id, - destinationDockerId: applicationFound.destinationDocker.id, - gitSourceId: applicationFound.gitSource.id, - githubAppId: applicationFound.gitSource.githubApp?.id, - gitlabAppId: applicationFound.gitSource.gitlabApp?.id, - status: 'queued', - type: 'webhook_pr' - } - }); - scheduler.workers.get('deployApplication').postMessage({ - build_id: buildId, - type: 'webhook_pr', - ...applicationFound, - sourceBranch, - pullmergeRequestId - }); - - return { - message: 'Queued. Thank you!' - }; - } else if (pullmergeRequestAction === 'closed') { - if (applicationFound.destinationDockerId) { - const id = `${applicationFound.id}-${pullmergeRequestId}`; - await removeContainer({ id, dockerId: applicationFound.destinationDocker.id }); - } - return { - message: 'Removed preview. Thank you!' - }; } - } else { - throw { status: 500, message: 'Pull request previews are not enabled.' } + + await prisma.application.update({ + where: { id: application.id }, + data: { updatedAt: new Date() } + }); + await prisma.build.create({ + data: { + id: buildId, + applicationId: application.id, + destinationDockerId: application.destinationDocker.id, + gitSourceId: application.gitSource.id, + githubAppId: application.gitSource.githubApp?.id, + gitlabAppId: application.gitSource.gitlabApp?.id, + status: 'queued', + type: 'webhook_commit' + } + }); + console.log(`Webhook for ${application.name} queued.`) + + } else if (githubEvent === 'pull_request') { + const pullmergeRequestId = body.number.toString(); + const pullmergeRequestAction = body.action; + const sourceBranch = body.pull_request.head.ref.includes('/') ? body.pull_request.head.ref.split('/')[2] : body.pull_request.head.ref; + if (!allowedActions.includes(pullmergeRequestAction)) { + throw { status: 500, message: 'Action not allowed.' } + } + + if (application.settings.previews) { + if (application.destinationDockerId) { + const isRunning = await checkContainer( + { + dockerId: application.destinationDocker.id, + container: application.id + } + ); + if (!isRunning) { + throw { status: 500, message: 'Application not running.' } + } + } + if ( + pullmergeRequestAction === 'opened' || + pullmergeRequestAction === 'reopened' || + pullmergeRequestAction === 'synchronize' + ) { + await prisma.application.update({ + where: { id: application.id }, + data: { updatedAt: new Date() } + }); + if (application.connectedDatabase && pullmergeRequestAction === 'opened' || pullmergeRequestAction === 'reopened') { + // Coolify hosted database + if (application.connectedDatabase.databaseId) { + const databaseId = application.connectedDatabase.databaseId; + const database = await prisma.database.findUnique({ where: { id: databaseId } }); + if (database) { + await createdBranchDatabase(database, application.connectedDatabase.hostedDatabaseDBName, pullmergeRequestId); + } + } + } + await prisma.build.create({ + data: { + id: buildId, + pullmergeRequestId, + sourceBranch, + applicationId: application.id, + destinationDockerId: application.destinationDocker.id, + gitSourceId: application.gitSource.id, + githubAppId: application.gitSource.githubApp?.id, + gitlabAppId: application.gitSource.gitlabApp?.id, + status: 'queued', + type: 'webhook_pr' + } + }); + + + } else if (pullmergeRequestAction === 'closed') { + if (application.destinationDockerId) { + const id = `${application.id}-${pullmergeRequestId}`; + try { + await removeContainer({ id, dockerId: application.destinationDocker.id }); + } catch (error) { } + } + if (application.connectedDatabase.databaseId) { + const databaseId = application.connectedDatabase.databaseId; + const database = await prisma.database.findUnique({ where: { id: databaseId } }); + if (database) { + await removeBranchDatabase(database, pullmergeRequestId); + } + } + } + } } } } - throw { status: 500, message: 'Not handled event.' } } catch ({ status, message }) { return errorHandler({ status, message }) } diff --git a/apps/api/src/routes/webhooks/gitlab/handlers.ts b/apps/api/src/routes/webhooks/gitlab/handlers.ts index 0e7f8ec5d..58d01182a 100644 --- a/apps/api/src/routes/webhooks/gitlab/handlers.ts +++ b/apps/api/src/routes/webhooks/gitlab/handlers.ts @@ -2,9 +2,8 @@ import axios from "axios"; import cuid from "cuid"; import crypto from "crypto"; import type { FastifyReply, FastifyRequest } from "fastify"; -import { errorHandler, getAPIUrl, isDev, listSettings, prisma } from "../../../lib/common"; +import { errorHandler, getAPIUrl, getUIUrl, isDev, listSettings, prisma } from "../../../lib/common"; import { checkContainer, removeContainer } from "../../../lib/docker"; -import { scheduler } from "../../../lib/scheduler"; import { getApplicationFromDB, getApplicationFromDBWebhook } from "../../api/v1/applications/handlers"; import type { ConfigureGitLabApp, GitLabEvents } from "./types"; @@ -30,7 +29,7 @@ export async function configureGitLabApp(request: FastifyRequest) { const { object_kind: objectKind, ref, project_id } = request.body try { - const buildId = cuid(); const allowedActions = ['opened', 'reopen', 'close', 'open', 'update']; const webhookToken = request.headers['x-gitlab-token']; - if (!webhookToken) { + if (!webhookToken && !isDev) { throw { status: 500, message: 'Invalid webhookToken.' } } if (objectKind === 'push') { const projectId = Number(project_id); const branch = ref.split('/')[2]; - const applicationFound = await getApplicationFromDBWebhook(projectId, branch); - if (applicationFound) { - if (!applicationFound.configHash) { - const configHash = crypto - .createHash('sha256') - .update( - JSON.stringify({ - buildPack: applicationFound.buildPack, - port: applicationFound.port, - exposePort: applicationFound.exposePort, - installCommand: applicationFound.installCommand, - buildCommand: applicationFound.buildCommand, - startCommand: applicationFound.startCommand - }) - ) - .digest('hex'); - await prisma.application.updateMany({ - where: { branch, projectId }, - data: { configHash } + const applicationsFound = await getApplicationFromDBWebhook(projectId, branch); + if (applicationsFound && applicationsFound.length > 0) { + for (const application of applicationsFound) { + const buildId = cuid(); + if (!application.configHash) { + const configHash = crypto + .createHash('sha256') + .update( + JSON.stringify({ + buildPack: application.buildPack, + port: application.port, + exposePort: application.exposePort, + installCommand: application.installCommand, + buildCommand: application.buildCommand, + startCommand: application.startCommand + }) + ) + .digest('hex'); + await prisma.application.update({ + where: { id: application.id }, + data: { configHash } + }); + } + await prisma.application.update({ + where: { id: application.id }, + data: { updatedAt: new Date() } + }); + await prisma.build.create({ + data: { + id: buildId, + applicationId: application.id, + destinationDockerId: application.destinationDocker.id, + gitSourceId: application.gitSource.id, + githubAppId: application.gitSource.githubApp?.id, + gitlabAppId: application.gitSource.gitlabApp?.id, + status: 'queued', + type: 'webhook_commit' + } }); } - await prisma.application.update({ - where: { id: applicationFound.id }, - data: { updatedAt: new Date() } - }); - await prisma.build.create({ - data: { - id: buildId, - applicationId: applicationFound.id, - destinationDockerId: applicationFound.destinationDocker.id, - gitSourceId: applicationFound.gitSource.id, - githubAppId: applicationFound.gitSource.githubApp?.id, - gitlabAppId: applicationFound.gitSource.gitlabApp?.id, - status: 'queued', - type: 'webhook_commit' - } - }); - - scheduler.workers.get('deployApplication').postMessage({ - build_id: buildId, - type: 'webhook_commit', - ...applicationFound - }); - - return { - message: 'Queued. Thank you!' - }; - } } else if (objectKind === 'merge_request') { const { object_attributes: { work_in_progress: isDraft, action, source_branch: sourceBranch, target_branch: targetBranch, iid: pullmergeRequestId }, project: { id } } = request.body @@ -111,71 +101,63 @@ export async function gitLabEvents(request: FastifyRequest) { throw { status: 500, message: 'Draft MR, do nothing.' } } - const applicationFound = await getApplicationFromDBWebhook(projectId, targetBranch); - if (applicationFound) { - if (applicationFound.settings.previews) { - if (applicationFound.destinationDockerId) { - const isRunning = await checkContainer( - { - dockerId: applicationFound.destinationDocker.id, - container: applicationFound.id + const applicationsFound = await getApplicationFromDBWebhook(projectId, targetBranch); + if (applicationsFound && applicationsFound.length > 0) { + for (const application of applicationsFound) { + const buildId = cuid(); + if (application.settings.previews) { + if (application.destinationDockerId) { + const isRunning = await checkContainer( + { + dockerId: application.destinationDocker.id, + container: application.id + } + ); + if (!isRunning) { + throw { status: 500, message: 'Application not running.' } } - ); - if (!isRunning) { - throw { status: 500, message: 'Application not running.' } } - } - if (!isDev && applicationFound.gitSource.gitlabApp.webhookToken !== webhookToken) { - throw { status: 500, message: 'Invalid webhookToken. Are you doing something nasty?!' } - } - if ( - action === 'opened' || - action === 'reopen' || - action === 'open' || - action === 'update' - ) { - await prisma.application.update({ - where: { id: applicationFound.id }, - data: { updatedAt: new Date() } - }); - await prisma.build.create({ - data: { - id: buildId, - applicationId: applicationFound.id, - destinationDockerId: applicationFound.destinationDocker.id, - gitSourceId: applicationFound.gitSource.id, - githubAppId: applicationFound.gitSource.githubApp?.id, - gitlabAppId: applicationFound.gitSource.gitlabApp?.id, - status: 'queued', - type: 'webhook_mr' + if (!isDev && application.gitSource.gitlabApp.webhookToken !== webhookToken) { + throw { status: 500, message: 'Invalid webhookToken. Are you doing something nasty?!' } + } + if ( + action === 'opened' || + action === 'reopen' || + action === 'open' || + action === 'update' + ) { + await prisma.application.update({ + where: { id: application.id }, + data: { updatedAt: new Date() } + }); + await prisma.build.create({ + data: { + id: buildId, + pullmergeRequestId: pullmergeRequestId.toString(), + sourceBranch, + applicationId: application.id, + destinationDockerId: application.destinationDocker.id, + gitSourceId: application.gitSource.id, + githubAppId: application.gitSource.githubApp?.id, + gitlabAppId: application.gitSource.gitlabApp?.id, + status: 'queued', + type: 'webhook_mr' + } + }); + return { + message: 'Queued. Thank you!' + }; + } else if (action === 'close') { + if (application.destinationDockerId) { + const id = `${application.id}-${pullmergeRequestId}`; + await removeContainer({ id, dockerId: application.destinationDocker.id }); } - }); - scheduler.workers.get('deployApplication').postMessage({ - build_id: buildId, - type: 'webhook_mr', - ...applicationFound, - sourceBranch, - pullmergeRequestId - }); - return { - message: 'Queued. Thank you!' - }; - } else if (action === 'close') { - if (applicationFound.destinationDockerId) { - const id = `${applicationFound.id}-${pullmergeRequestId}`; - const engine = applicationFound.destinationDocker.engine; - await removeContainer({ id, dockerId: applicationFound.destinationDocker.id }); } - return { - message: 'Removed preview. Thank you!' - }; } } - throw { status: 500, message: 'Merge request previews are not enabled.' } } } - throw { status: 500, message: 'Not handled event.' } } catch ({ status, message }) { return errorHandler({ status, message }) } diff --git a/apps/api/src/routes/webhooks/traefik/handlers.ts b/apps/api/src/routes/webhooks/traefik/handlers.ts index de805ee71..3e2cd5952 100644 --- a/apps/api/src/routes/webhooks/traefik/handlers.ts +++ b/apps/api/src/routes/webhooks/traefik/handlers.ts @@ -1,6 +1,9 @@ import { FastifyRequest } from "fastify"; -import { errorHandler, getDomain, isDev, prisma, supportedServiceTypesAndVersions, include, executeDockerCmd } from "../../../lib/common"; +import { errorHandler, getDomain, isDev, prisma, executeDockerCmd } from "../../../lib/common"; +import { supportedServiceTypesAndVersions } from "../../../lib/services/supportedVersions"; +import { includeServices } from "../../../lib/services/common"; import { TraefikOtherConfiguration } from "./types"; +import { OnlyId } from "../../../types"; function configureMiddleware( { id, container, port, domain, nakedDomain, isHttps, isWWW, isDualCerts, scriptName, type }, @@ -23,7 +26,30 @@ function configureMiddleware( ] } }; + if (type === 'appwrite') { + traefik.http.routers[`${id}-realtime`] = { + entrypoints: ['websecure'], + rule: `(Host(\`${nakedDomain}\`) || Host(\`www.${nakedDomain}\`)) && PathPrefix(\`/v1/realtime\`)`, + service: `${`${id}-realtime`}`, + tls: { + domains: { + main: `${domain}` + } + }, + middlewares: [] + }; + + traefik.http.services[`${id}-realtime`] = { + loadbalancer: { + servers: [ + { + url: `http://${container}-realtime:${port}` + } + ] + } + }; + } if (isDualCerts) { traefik.http.routers[`${id}-secure`] = { entrypoints: ['websecure'], @@ -110,6 +136,23 @@ function configureMiddleware( ] } }; + if (type === 'appwrite') { + traefik.http.routers[`${id}-realtime`] = { + entrypoints: ['web'], + rule: `(Host(\`${nakedDomain}\`) || Host(\`www.${nakedDomain}\`)) && PathPrefix(\`/v1/realtime\`)`, + service: `${id}-realtime`, + middlewares: [] + }; + traefik.http.services[`${id}-realtime`] = { + loadbalancer: { + servers: [ + { + url: `http://${container}-realtime:${port}` + } + ] + } + }; + } if (!isDualCerts) { if (isWWW) { @@ -234,7 +277,7 @@ export async function traefikConfiguration(request, reply) { } const services: any = await prisma.service.findMany({ where: { destinationDocker: { remoteEngine: false } }, - include, + include: includeServices, orderBy: { createdAt: 'desc' }, }); @@ -484,12 +527,11 @@ export async function traefikOtherConfiguration(request: FastifyRequest) { const { id } = request.params try { const traefik = { @@ -591,7 +633,7 @@ export async function remoteTraefikConfiguration(request: FastifyRequest) { } const services: any = await prisma.service.findMany({ where: { destinationDocker: { id } }, - include, + include: includeServices, orderBy: { createdAt: 'desc' } }); diff --git a/apps/api/src/routes/webhooks/traefik/index.ts b/apps/api/src/routes/webhooks/traefik/index.ts index f9c7ff4b8..3769c8eb3 100644 --- a/apps/api/src/routes/webhooks/traefik/index.ts +++ b/apps/api/src/routes/webhooks/traefik/index.ts @@ -1,4 +1,5 @@ import { FastifyPluginAsync } from 'fastify'; +import { OnlyId } from '../../../types'; import { remoteTraefikConfiguration, traefikConfiguration, traefikOtherConfiguration } from './handlers'; import { TraefikOtherConfiguration } from './types'; @@ -6,7 +7,7 @@ const root: FastifyPluginAsync = async (fastify): Promise => { fastify.get('/main.json', async (request, reply) => traefikConfiguration(request, reply)); fastify.get('/other.json', async (request, reply) => traefikOtherConfiguration(request)); - fastify.get('/remote/:id', async (request) => remoteTraefikConfiguration(request)); + fastify.get('/remote/:id', async (request) => remoteTraefikConfiguration(request)); }; export default root; diff --git a/apps/api/src/types.ts b/apps/api/src/types.ts index 6367fd566..71f3db158 100644 --- a/apps/api/src/types.ts +++ b/apps/api/src/types.ts @@ -36,4 +36,3 @@ export interface SaveDatabaseSettings extends OnlyId { } - diff --git a/apps/i18n/.env.example b/apps/i18n/.env.example new file mode 100644 index 000000000..8bdf45a64 --- /dev/null +++ b/apps/i18n/.env.example @@ -0,0 +1,4 @@ +WEBLATE_INSTANCE_URL=http://localhost +WEBLATE_COMPONENT_NAME=coolify +WEBLATE_TOKEN= +TRANSLATION_DIR= \ No newline at end of file diff --git a/apps/i18n/.gitignore b/apps/i18n/.gitignore new file mode 100644 index 000000000..df67586b0 --- /dev/null +++ b/apps/i18n/.gitignore @@ -0,0 +1 @@ +locales/* \ No newline at end of file diff --git a/apps/i18n/index.mjs b/apps/i18n/index.mjs new file mode 100644 index 000000000..85e146073 --- /dev/null +++ b/apps/i18n/index.mjs @@ -0,0 +1,63 @@ +import dotenv from 'dotenv'; +dotenv.config() +import fs from 'fs' +import path from 'path' +import { fileURLToPath } from 'url'; +import Gettext from 'node-gettext' +import { po } from 'gettext-parser' +import got from 'got'; +const __filename = fileURLToPath(import.meta.url); + +const __dirname = path.dirname(__filename); + +const weblateInstanceURL = process.env.WEBLATE_INSTANCE_URL; +const weblateComponentName = process.env.WEBLATE_COMPONENT_NAME +const token = process.env.WEBLATE_TOKEN; + +const translationsDir = process.env.TRANSLATION_DIR; +const translationsPODir = './locales'; +const locales = [] +const domain = 'locale' + +const translations = await got(`${weblateInstanceURL}/api/components/${weblateComponentName}/glossary/translations/?format=json`, { + headers: { + "Authorization": `Token ${token}` + } +}).json() +for (const translation of translations.results) { + const code = translation.language_code + locales.push(code) + + const fileUrl = translation.file_url.replace('=json', '=po') + const file = await got(fileUrl, { + headers: { + "Authorization": `Token ${token}` + } + }).text() + fs.writeFileSync(path.join(__dirname, translationsPODir, domain + '-' + code + '.po'), file) +} + + +const gt = new Gettext() + +locales.forEach((locale) => { + let json = {} + const fileName = `${domain}-${locale}.po` + const translationsFilePath = path.join(translationsPODir, fileName) + const translationsContent = fs.readFileSync(translationsFilePath) + + const parsedTranslations = po.parse(translationsContent) + const a = gt.gettext(parsedTranslations) + for (const [key, value] of Object.entries(a)) { + if (key === 'translations') { + for (const [key1, value1] of Object.entries(value)) { + if (key1 !== '') { + for (const [key2, value2] of Object.entries(value1)) { + json[value2.msgctxt] = value2.msgstr[0] + } + } + } + } + } + fs.writeFileSync(`${translationsDir}/${locale}.json`, JSON.stringify(json)) +}) \ No newline at end of file diff --git a/apps/i18n/package.json b/apps/i18n/package.json new file mode 100644 index 000000000..bb4534514 --- /dev/null +++ b/apps/i18n/package.json @@ -0,0 +1,15 @@ +{ + "name": "i18n-converter", + "description": "Convert Weblate translations to sveltekit-i18n", + "license": "Apache-2.0", + "scripts": { + "translate": "node index.mjs" + }, + "type": "module", + "dependencies": { + "node-gettext": "3.0.0", + "gettext-parser": "6.0.0", + "got": "12.3.1", + "dotenv": "16.0.2" + } +} \ No newline at end of file diff --git a/apps/ui/README.md b/apps/ui/README.md deleted file mode 100644 index 374efec4c..000000000 --- a/apps/ui/README.md +++ /dev/null @@ -1,38 +0,0 @@ -# create-svelte - -Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/master/packages/create-svelte). - -## Creating a project - -If you're seeing this, you've probably already done this step. Congrats! - -```bash -# create a new project in the current directory -npm init svelte - -# create a new project in my-app -npm init svelte my-app -``` - -## Developing - -Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server: - -```bash -npm run dev - -# or start the server and open the app in a new browser tab -npm run dev -- --open -``` - -## Building - -To create a production version of your app: - -```bash -npm run build -``` - -You can preview the production build with `npm run preview`. - -> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment. diff --git a/apps/ui/package.json b/apps/ui/package.json index 10b2d5219..caf05c233 100644 --- a/apps/ui/package.json +++ b/apps/ui/package.json @@ -1,13 +1,12 @@ { - "name": "coolify-ui", + "name": "ui", "description": "Coolify's SvelteKit UI", - "license": "AGPL-3.0", + "license": "Apache-2.0", "scripts": { "dev": "vite dev", "build": "vite build", "package": "svelte-kit package", "preview": "svelte-kit preview", - "prepare": "svelte-kit sync", "test": "playwright test", "check": "svelte-check --tsconfig ./tsconfig.json", "check:watch": "svelte-check --tsconfig ./tsconfig.json --watch", @@ -15,32 +14,38 @@ "format": "prettier --write --plugin-search-dir=. ." }, "devDependencies": { - "@playwright/test": "1.23.4", - "@sveltejs/kit": "1.0.0-next.377", + "@floating-ui/dom": "1.0.1", + "@playwright/test": "1.25.1", + "@popperjs/core": "2.11.6", + "@sveltejs/kit": "1.0.0-next.405", "@types/js-cookie": "3.0.2", - "@typescript-eslint/eslint-plugin": "5.30.6", - "@typescript-eslint/parser": "5.30.6", - "autoprefixer": "10.4.7", - "eslint": "8.20.0", + "@typescript-eslint/eslint-plugin": "5.36.1", + "@typescript-eslint/parser": "5.36.1", + "autoprefixer": "10.4.8", + "classnames": "2.3.1", + "eslint": "8.23.0", "eslint-config-prettier": "8.5.0", "eslint-plugin-svelte3": "4.0.0", - "postcss": "8.4.14", + "flowbite": "1.5.2", + "flowbite-svelte": "0.26.2", + "postcss": "8.4.16", "prettier": "2.7.1", "prettier-plugin-svelte": "2.7.0", - "svelte": "3.49.0", - "svelte-check": "2.8.0", + "svelte": "3.50.0", + "svelte-check": "2.9.0", "svelte-preprocess": "4.10.7", - "tailwindcss": "3.1.6", + "tailwindcss": "3.1.8", "tailwindcss-scrollbar": "0.1.0", "tslib": "2.4.0", - "typescript": "4.7.4", - "vite": "3.0.1" + "typescript": "4.8.2", + "vite": "3.1.0" }, "type": "module", "dependencies": { - "@sveltejs/adapter-static": "1.0.0-next.37", - "@zerodevx/svelte-toast": "0.7.2", + "@sveltejs/adapter-static": "1.0.0-next.39", + "@tailwindcss/typography": "^0.5.7", "cuid": "2.1.8", + "daisyui": "2.24.2", "js-cookie": "3.0.1", "p-limit": "4.0.0", "svelte-select": "4.4.7", diff --git a/apps/ui/src/app.d.ts b/apps/ui/src/app.d.ts index ed5f4e197..ebc7c2668 100644 --- a/apps/ui/src/app.d.ts +++ b/apps/ui/src/app.d.ts @@ -21,4 +21,5 @@ declare namespace App { } declare const GITPOD_WORKSPACE_URL: string + \ No newline at end of file diff --git a/apps/ui/src/app.html b/apps/ui/src/app.html index af82b3042..16d104bc7 100644 --- a/apps/ui/src/app.html +++ b/apps/ui/src/app.html @@ -1,5 +1,5 @@ - + diff --git a/apps/ui/src/lib/api.ts b/apps/ui/src/lib/api.ts index fc11e09d3..697a29338 100644 --- a/apps/ui/src/lib/api.ts +++ b/apps/ui/src/lib/api.ts @@ -7,10 +7,12 @@ export function getAPIUrl() { const newURL = href.replace('https://', 'https://3001-').replace(/\/$/, '') return newURL } + if (CODESANDBOX_HOST) { + return `https://${CODESANDBOX_HOST.replace(/\$PORT/,'3001')}` + } return dev ? 'http://localhost:3001' : 'http://localhost:3000'; } export function getWebhookUrl(type: string) { - console.log(GITPOD_WORKSPACE_URL) if (GITPOD_WORKSPACE_URL) { const { href } = new URL(GITPOD_WORKSPACE_URL) const newURL = href.replace('https://', 'https://3001-').replace(/\/$/, '') @@ -21,6 +23,15 @@ export function getWebhookUrl(type: string) { return `${newURL}/webhooks/gitlab/events` } } + if (CODESANDBOX_HOST) { + const newURL = `https://${CODESANDBOX_HOST.replace(/\$PORT/,'3001')}` + if (type === 'github') { + return `${newURL}/webhooks/github/events` + } + if (type === 'gitlab') { + return `${newURL}/webhooks/gitlab/events` + } + } return `https://webhook.site/0e5beb2c-4e9b-40e2-a89e-32295e570c21/events`; } async function send({ diff --git a/apps/ui/src/lib/common.ts b/apps/ui/src/lib/common.ts index e0396f19c..4af26c100 100644 --- a/apps/ui/src/lib/common.ts +++ b/apps/ui/src/lib/common.ts @@ -1,165 +1,4 @@ -import { toast } from '@zerodevx/svelte-toast'; - -export const supportedServiceTypesAndVersions = [ - { - name: 'plausibleanalytics', - fancyName: 'Plausible Analytics', - baseImage: 'plausible/analytics', - images: ['bitnami/postgresql:13.2.0', 'yandex/clickhouse-server:21.3.2.5'], - versions: ['latest', 'stable'], - recommendedVersion: 'stable', - ports: { - main: 8000 - } - }, - { - name: 'nocodb', - fancyName: 'NocoDB', - baseImage: 'nocodb/nocodb', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 8080 - } - }, - { - name: 'minio', - fancyName: 'MinIO', - baseImage: 'minio/minio', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 9001 - } - }, - { - name: 'vscodeserver', - fancyName: 'VSCode Server', - baseImage: 'codercom/code-server', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 8080 - } - }, - { - name: 'wordpress', - fancyName: 'Wordpress', - baseImage: 'wordpress', - images: ['bitnami/mysql:5.7'], - versions: ['latest', 'php8.1', 'php8.0', 'php7.4', 'php7.3'], - recommendedVersion: 'latest', - ports: { - main: 80 - } - }, - { - name: 'vaultwarden', - fancyName: 'Vaultwarden', - baseImage: 'vaultwarden/server', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 80 - } - }, - { - name: 'languagetool', - fancyName: 'LanguageTool', - baseImage: 'silviof/docker-languagetool', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 8010 - } - }, - { - name: 'n8n', - fancyName: 'n8n', - baseImage: 'n8nio/n8n', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 5678 - } - }, - { - name: 'uptimekuma', - fancyName: 'Uptime Kuma', - baseImage: 'louislam/uptime-kuma', - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 3001 - } - }, - { - name: 'ghost', - fancyName: 'Ghost', - baseImage: 'bitnami/ghost', - images: ['bitnami/mariadb'], - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 2368 - } - }, - { - name: 'meilisearch', - fancyName: 'Meilisearch', - baseImage: 'getmeili/meilisearch', - images: [], - versions: ['latest'], - recommendedVersion: 'latest', - ports: { - main: 7700 - } - }, - { - name: 'umami', - fancyName: 'Umami', - baseImage: 'ghcr.io/mikecao/umami', - images: ['postgres:12-alpine'], - versions: ['postgresql-latest'], - recommendedVersion: 'postgresql-latest', - ports: { - main: 3000 - } - }, - { - name: 'hasura', - fancyName: 'Hasura', - baseImage: 'hasura/graphql-engine', - images: ['postgres:12-alpine'], - versions: ['latest', 'v2.5.1'], - recommendedVersion: 'v2.5.1', - ports: { - main: 8080 - } - }, - { - name: 'fider', - fancyName: 'Fider', - baseImage: 'getfider/fider', - images: ['postgres:12-alpine'], - versions: ['stable'], - recommendedVersion: 'stable', - ports: { - main: 3000 - } - }, - // { - // name: 'moodle', - // fancyName: 'Moodle', - // baseImage: 'bitnami/moodle', - // images: [], - // versions: ['latest', 'v4.0.2'], - // recommendedVersion: 'latest', - // ports: { - // main: 8080 - // } - // } -]; +import { addToast } from '$lib/store'; export const asyncSleep = (delay: number) => new Promise((resolve) => setTimeout(resolve, delay)); @@ -167,12 +6,20 @@ export const asyncSleep = (delay: number) => export function errorNotification(error: any): void { if (error.message) { if (error.message === 'Cannot read properties of undefined (reading \'postMessage\')') { - toast.push('Currently there is background process in progress. Please try again later.'); - return; + return addToast({ + message: 'Currently there is background process in progress. Please try again later.', + type: 'error', + }); } - toast.push(error.message); + addToast({ + message: error.message, + type: 'error', + }); } else { - toast.push('Ooops, something is not okay, are you okay?'); + addToast({ + message: 'Ooops, something is not okay, are you okay?', + type: 'error', + }); } console.error(JSON.stringify(error)); } @@ -210,7 +57,7 @@ export const staticDeployments = [ 'astro', 'eleventy' ]; -export const notNodeDeployments = ['php', 'docker', 'rust', 'python', 'deno', 'laravel']; +export const notNodeDeployments = ['php', 'docker', 'rust', 'python', 'deno', 'laravel', 'heroku']; export function generateRemoteEngine(destination: any) { @@ -224,44 +71,6 @@ export function changeQueryParams(buildId: string) { return history.pushState(null, null, '?' + queryParams.toString()); } -export const supportedDatabaseTypesAndVersions = [ - { - name: 'mongodb', - fancyName: 'MongoDB', - baseImage: 'bitnami/mongodb', - versions: ['5.0', '4.4', '4.2'] - }, - { name: 'mysql', fancyName: 'MySQL', baseImage: 'bitnami/mysql', versions: ['8.0', '5.7'] }, - { - name: 'mariadb', - fancyName: 'MariaDB', - baseImage: 'bitnami/mariadb', - versions: ['10.7', '10.6', '10.5', '10.4', '10.3', '10.2'] - }, - { - name: 'postgresql', - fancyName: 'PostgreSQL', - baseImage: 'bitnami/postgresql', - versions: ['14.2.0', '13.6.0', '12.10.0 ', '11.15.0', '10.20.0'] - }, - { - name: 'redis', - fancyName: 'Redis', - baseImage: 'bitnami/redis', - versions: ['6.2', '6.0', '5.0'] - }, - { name: 'couchdb', fancyName: 'CouchDB', baseImage: 'bitnami/couchdb', versions: ['3.2.1'] } -]; - -export const getServiceMainPort = (service: string) => { - const serviceType = supportedServiceTypesAndVersions.find((s) => s.name === service); - if (serviceType) { - return serviceType.ports.main; - } - return null; -}; - - export function handlerNotFoundLoad(error: any, url: URL) { if (error?.status === 404) { diff --git a/apps/ui/src/lib/components/CopyPasswordField.svelte b/apps/ui/src/lib/components/CopyPasswordField.svelte index 103065601..0a6fba471 100644 --- a/apps/ui/src/lib/components/CopyPasswordField.svelte +++ b/apps/ui/src/lib/components/CopyPasswordField.svelte @@ -1,6 +1,6 @@ diff --git a/apps/ui/src/lib/components/DocLink.svelte b/apps/ui/src/lib/components/DocLink.svelte new file mode 100644 index 000000000..0646734be --- /dev/null +++ b/apps/ui/src/lib/components/DocLink.svelte @@ -0,0 +1,32 @@ + + + + + + + + + + +See details in the documentation diff --git a/apps/ui/src/lib/components/Explainer.svelte b/apps/ui/src/lib/components/Explainer.svelte index 813220c67..e51934a58 100644 --- a/apps/ui/src/lib/components/Explainer.svelte +++ b/apps/ui/src/lib/components/Explainer.svelte @@ -1,6 +1,31 @@ -
{@html text}
+
+ + +
+{#if id} + {@html explanation} +{/if} diff --git a/apps/ui/src/lib/components/Setting.svelte b/apps/ui/src/lib/components/Setting.svelte index d1cf55dc0..b8aafbba8 100644 --- a/apps/ui/src/lib/components/Setting.svelte +++ b/apps/ui/src/lib/components/Setting.svelte @@ -1,6 +1,8 @@
-
{title}
- +
+ {title} +
-
+
Use setting
+ +{#if dataTooltip} + {dataTooltip} +{/if} diff --git a/apps/ui/src/lib/components/SimpleExplainer.svelte b/apps/ui/src/lib/components/SimpleExplainer.svelte new file mode 100644 index 000000000..6a3198c27 --- /dev/null +++ b/apps/ui/src/lib/components/SimpleExplainer.svelte @@ -0,0 +1,6 @@ + + +
{@html text}
\ No newline at end of file diff --git a/apps/ui/src/lib/components/Toast.svelte b/apps/ui/src/lib/components/Toast.svelte new file mode 100644 index 000000000..b0586a51f --- /dev/null +++ b/apps/ui/src/lib/components/Toast.svelte @@ -0,0 +1,59 @@ + + +
dispatch('click')} + on:mouseover={() => dispatch('pause')} + on:focus={() => dispatch('pause')} + on:mouseout={() => dispatch('resume')} + on:blur={() => dispatch('resume')} + class="alert shadow-lg text-white rounded hover:scale-105 transition-all duration-100 cursor-pointer" + class:bg-coollabs={type === 'success'} + class:alert-error={type === 'error'} + class:alert-info={type === 'info'} +> + {#if type === 'success'} + + {:else if type === 'error'} + + {:else if type === 'info'} + + {/if} + +
diff --git a/apps/ui/src/lib/components/Toasts.svelte b/apps/ui/src/lib/components/Toasts.svelte new file mode 100644 index 000000000..1c7c8cbc0 --- /dev/null +++ b/apps/ui/src/lib/components/Toasts.svelte @@ -0,0 +1,27 @@ + + +{#if $toasts} +
+ +
+{/if} + + diff --git a/apps/ui/src/lib/components/Tooltip.svelte b/apps/ui/src/lib/components/Tooltip.svelte new file mode 100644 index 000000000..c20e4836d --- /dev/null +++ b/apps/ui/src/lib/components/Tooltip.svelte @@ -0,0 +1,8 @@ + + + diff --git a/apps/ui/src/lib/components/UpdateAvailable.svelte b/apps/ui/src/lib/components/UpdateAvailable.svelte index 4171a1c5f..db98d8699 100644 --- a/apps/ui/src/lib/components/UpdateAvailable.svelte +++ b/apps/ui/src/lib/components/UpdateAvailable.svelte @@ -1,8 +1,7 @@ -{#if $appSession.teamId === '0'} -
Server Usage
-
-
-
Total Memory
-
- {(usage?.memory.totalMemMb).toFixed(0)}MB -
+
+
+

Hardware Details

+
+ {#if $appSession.teamId === '0'} + + {/if} +
+
+
+
+
+
+
Total Memory
+
+ {(usage?.memory.totalMemMb).toFixed(0)}MB +
+
+ +
+
Used Memory
+
+ {(usage?.memory.usedMemMb).toFixed(0)}MB +
+
+ +
+
Free Memory
+
+ {usage?.memory.freeMemPercentage}% +
+
-
-
Used Memory
-
- {(usage?.memory.usedMemMb).toFixed(0)}MB -
-
+
+
+
Total CPU
+
+ {usage?.cpu.count} +
+
-
-
Free Memory
-
- {usage?.memory.freeMemPercentage}% - {#if !warning.memory} - - {/if} -
-
-
-
-
-
Total CPUs
-
- {usage?.cpu.count} -
-
-
-
CPU Usage
-
- {usage?.cpu.usage}% - {#if !warning.cpu} - - {/if} -
-
-
-
Load Average (5/10/30mins)
-
- {usage?.cpu.load.join('/')} -
-
-
-
-
-
Total Disk
-
- {usage?.disk.totalGb}GB -
-
-
-
Used Disk
-
- {usage?.disk.usedGb}GB -
- -
-
-
Free Disk
-
- {usage?.disk.freePercentage}% - {#if !warning.disk} - - {/if} -
-
-
+
+
CPU Usage
+
+ {usage?.cpu.usage}% +
+
-
Resources
-{/if} +
+
Load Average (5,10,30mins)
+
{usage?.cpu.load}
+
+
+
+
+
Total Disk
+
+ {usage?.disk.totalGb}GB +
+
+ +
+
Used Disk
+
+ {usage?.disk.usedGb}GB +
+
+ +
+
Free Disk
+
+ {usage?.disk.freePercentage}% +
+
+
+ + diff --git a/apps/ui/src/lib/components/svg/applications/ApplicationIcons.svelte b/apps/ui/src/lib/components/svg/applications/ApplicationIcons.svelte new file mode 100644 index 000000000..0980063c6 --- /dev/null +++ b/apps/ui/src/lib/components/svg/applications/ApplicationIcons.svelte @@ -0,0 +1,43 @@ + + +{#if application.buildPack?.toLowerCase() === 'rust'} + +{:else if application.buildPack?.toLowerCase() === 'node'} + +{:else if application.buildPack?.toLowerCase() === 'react'} + +{:else if application.buildPack?.toLowerCase() === 'svelte'} + +{:else if application.buildPack?.toLowerCase() === 'vuejs'} + +{:else if application.buildPack?.toLowerCase() === 'php'} + +{:else if application.buildPack?.toLowerCase() === 'python'} + +{:else if application.buildPack?.toLowerCase() === 'static'} + +{:else if application.buildPack?.toLowerCase() === 'nestjs'} + +{:else if application.buildPack?.toLowerCase() === 'nuxtjs'} + +{:else if application.buildPack?.toLowerCase() === 'nextjs'} + +{:else if application.buildPack?.toLowerCase() === 'gatsby'} + +{:else if application.buildPack?.toLowerCase() === 'docker'} + +{:else if application.buildPack?.toLowerCase() === 'astro'} + +{:else if application.buildPack?.toLowerCase() === 'eleventy'} + +{:else if application.buildPack?.toLowerCase() === 'deno'} + +{:else if application.buildPack?.toLowerCase() === 'laravel'} + +{:else if application.buildPack?.toLowerCase() === 'heroku'} + +{/if} diff --git a/apps/ui/src/lib/components/svg/applications/Astro.svelte b/apps/ui/src/lib/components/svg/applications/Astro.svelte index df8d0804f..2344372ab 100644 --- a/apps/ui/src/lib/components/svg/applications/Astro.svelte +++ b/apps/ui/src/lib/components/svg/applications/Astro.svelte @@ -1,5 +1,9 @@ + + + export let isAbsolute = true; + + + + + + + + + diff --git a/apps/ui/src/lib/components/svg/applications/Eleventy.svelte b/apps/ui/src/lib/components/svg/applications/Eleventy.svelte index 691a10520..b2d8d6122 100644 --- a/apps/ui/src/lib/components/svg/applications/Eleventy.svelte +++ b/apps/ui/src/lib/components/svg/applications/Eleventy.svelte @@ -1,4 +1,11 @@ - + + + + + + + export let isAbsolute = true; + + + + + diff --git a/apps/ui/src/lib/components/svg/applications/Laravel.svelte b/apps/ui/src/lib/components/svg/applications/Laravel.svelte index ab544a596..d13694a8c 100644 --- a/apps/ui/src/lib/components/svg/applications/Laravel.svelte +++ b/apps/ui/src/lib/components/svg/applications/Laravel.svelte @@ -1,5 +1,9 @@ + + Logomark + + + + + + diff --git a/apps/ui/src/lib/components/svg/applications/Nodejs.svelte b/apps/ui/src/lib/components/svg/applications/Nodejs.svelte index 3e7e84d28..93140f08f 100644 --- a/apps/ui/src/lib/components/svg/applications/Nodejs.svelte +++ b/apps/ui/src/lib/components/svg/applications/Nodejs.svelte @@ -1,5 +1,9 @@ + + moodle logo diff --git a/apps/ui/src/lib/components/svg/services/N8n.svelte b/apps/ui/src/lib/components/svg/services/N8n.svelte index 04b2e8216..da7ab2b88 100644 --- a/apps/ui/src/lib/components/svg/services/N8n.svelte +++ b/apps/ui/src/lib/components/svg/services/N8n.svelte @@ -3,7 +3,7 @@ diff --git a/apps/ui/src/lib/components/svg/services/NocoDB.svelte b/apps/ui/src/lib/components/svg/services/NocoDB.svelte index ba93c4f78..fcaac6a96 100644 --- a/apps/ui/src/lib/components/svg/services/NocoDB.svelte +++ b/apps/ui/src/lib/components/svg/services/NocoDB.svelte @@ -4,6 +4,6 @@ nocodb logo diff --git a/apps/ui/src/lib/components/svg/services/PlausibleAnalytics.svelte b/apps/ui/src/lib/components/svg/services/PlausibleAnalytics.svelte index c02a9e6d9..e10ead645 100644 --- a/apps/ui/src/lib/components/svg/services/PlausibleAnalytics.svelte +++ b/apps/ui/src/lib/components/svg/services/PlausibleAnalytics.svelte @@ -4,6 +4,6 @@ plausible logo diff --git a/apps/ui/src/lib/components/svg/services/Searxng.svelte b/apps/ui/src/lib/components/svg/services/Searxng.svelte new file mode 100644 index 000000000..bb775d2bf --- /dev/null +++ b/apps/ui/src/lib/components/svg/services/Searxng.svelte @@ -0,0 +1,56 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + diff --git a/apps/ui/src/lib/components/svg/services/ServiceIcons.svelte b/apps/ui/src/lib/components/svg/services/ServiceIcons.svelte new file mode 100644 index 000000000..4cc5426b2 --- /dev/null +++ b/apps/ui/src/lib/components/svg/services/ServiceIcons.svelte @@ -0,0 +1,45 @@ + + +{#if type === 'plausibleanalytics'} + +{:else if type === 'nocodb'} + +{:else if type === 'minio'} + +{:else if type === 'vscodeserver'} + +{:else if type === 'wordpress'} + +{:else if type === 'vaultwarden'} + +{:else if type === 'languagetool'} + +{:else if type === 'n8n'} + +{:else if type === 'uptimekuma'} + +{:else if type === 'ghost'} + +{:else if type === 'meilisearch'} + +{:else if type === 'umami'} + +{:else if type === 'hasura'} + +{:else if type === 'fider'} + +{:else if type === 'appwrite'} + +{:else if type === 'moodle'} + +{:else if type === 'glitchTip'} + +{:else if type === 'searxng'} + +{:else if type === 'weblate'} + +{/if} diff --git a/apps/ui/src/lib/components/svg/services/Umami.svelte b/apps/ui/src/lib/components/svg/services/Umami.svelte index e1c9b1e67..7faeca3fb 100644 --- a/apps/ui/src/lib/components/svg/services/Umami.svelte +++ b/apps/ui/src/lib/components/svg/services/Umami.svelte @@ -7,7 +7,7 @@ xmlns="http://www.w3.org/2000/svg" viewBox="0 0 856.000000 856.000000" preserveAspectRatio="xMidYMid meet" - class={isAbsolute ? 'w-10 h-10 absolute top-0 left-0 -m-5' : 'w-8 mx-auto'} + class={isAbsolute ? 'w-10 h-10 absolute top-0 left-0 -m-5' : 'w-8 h-8 mx-auto'} > Created by potrace 1.11, written by Peter Selinger 2001-2013 + export let isAbsolute = false; + + + diff --git a/apps/ui/src/lib/components/svg/services/Wordpress.svelte b/apps/ui/src/lib/components/svg/services/Wordpress.svelte index aaccb931a..c6a79e5e9 100644 --- a/apps/ui/src/lib/components/svg/services/Wordpress.svelte +++ b/apps/ui/src/lib/components/svg/services/Wordpress.svelte @@ -2,7 +2,7 @@ export let isAbsolute = false; - + Add them to your firewall (if applicable).

You can specify a range of ports, eg: 9000-9100", + "public_port_range_explainer": "Ports used to expose databases/services/internal services.
Add them to your firewall (if applicable).

You can specify a range of ports, eg: 9000-9100", "no_actions_available": "No actions available", "admin_api_key": "Admin API key" }, @@ -159,23 +159,23 @@ "storage_saved": "Storage saved.", "storage_updated": "Storage updated.", "storage_deleted": "Storage deleted.", - "persistent_storage_explainer": "You can specify any folder that you want to be persistent across deployments.
This is useful for storing data such as a database (SQLite) or a cache." + "persistent_storage_explainer": "You can specify any folder that you want to be persistent across deployments.
/example means it will preserve /app/example in the container as /app is the root directory for your application.

This is useful for storing data such as a database (SQLite) or a cache." }, "deployment_queued": "Deployment queued.", "confirm_to_delete": "Are you sure you would like to delete '{{name}}'?", - "stop_application": "Stop application", + "stop_application": "Stop Application", "permission_denied_stop_application": "You do not have permission to stop the application.", - "rebuild_application": "Rebuild application", + "rebuild_application": "Rebuild Application", "permission_denied_rebuild_application": "You do not have permission to rebuild application.", - "build_and_start_application": "Build and start application", - "permission_denied_build_and_start_application": "You do not have permission to Build and start application.", + "build_and_start_application": "Deploy", + "permission_denied_build_and_start_application": "You do not have permission to deploy application.", "configurations": "Configurations", "secret": "Secrets", "persistent_storage": "Persistent Storage", "previews": "Previews", "logs": "Application Logs", "build_logs": "Build Logs", - "delete_application": "Delete application", + "delete_application": "Delete", "permission_denied_delete_application": "You do not have permission to delete this application", "domain_already_in_use": "Domain {{domain}} is already used.", "dns_not_set_error": "DNS not set correctly or propogated for {{domain}}.

Please check your DNS settings.", @@ -209,7 +209,7 @@ "expose_a_port": "Expose a port", "enable_preview_deploy_mr_pr_requests": "Enable preview deployments from pull or merge requests.", "debug_logs": "Debug Logs", - "enable_debug_log_during_build": "Enable debug logs during build phase.
Sensitive information could be visible and saved in logs.", + "enable_debug_log_during_build": "Enable debug logs during build phase.
Sensitive information could be visible and saved in logs.", "cant_activate_auto_deploy_without_repo": "Cannot activate automatic deployments until only one application is defined for this repository / branch.", "no_applications_found": "No applications found", "secret__batch_dot_env": "Paste .env file", @@ -227,17 +227,17 @@ "select_database_type": "Select a Database type", "select_database_version": "Select a Database version", "confirm_stop": "Are you sure you would like to stop {{name}}?", - "stop_database": "Stop database", + "stop_database": "Stop", "permission_denied_stop_database": "You do not have permission to stop the database.", - "start_database": "Start database", + "start_database": "Start", "permission_denied_start_database": "You do not have permission to start the database.", - "delete_database": "Delete Database", + "delete_database": "Delete", "permission_denied_delete_database": "You do not have permission to delete a Database", "no_databases_found": "No databases found", - "logs": "Database Logs" + "logs": "Logs" }, "destination": { - "delete_destination": "Delete Destination", + "delete_destination": "Delete", "permission_denied_delete_destination": "You do not have permission to delete this destination", "add_to_coolify": "Add to Coolify", "coolify_proxy_stopped": "Coolify Proxy stopped!", @@ -267,7 +267,7 @@ "official_providers": "Official providers" }, "no_git_sources_found": "No git sources found", - "delete_git_source": "Delete Git Source", + "delete_git_source": "Delete", "permission_denied": "You do not have permission to delete a Git Source", "create_new_app": "Create new {{name}} App", "change_app_settings": "Change {{name}} App Settings", @@ -275,7 +275,7 @@ "application_id": "Application ID", "group_name": "Group Name", "oauth_id": "OAuth ID", - "oauth_id_explainer": "The OAuth ID is the unique identifier of the GitLab application.
You can find it in the URL of your GitLab OAuth Application.", + "oauth_id_explainer": "The OAuth ID is the unique identifier of the GitLab application.
You can find it in the URL of your GitLab OAuth Application.", "register_oauth_gitlab": "Register new OAuth application on GitLab", "gitlab": { "self_hosted": "Instance-wide application (self-hosted)", @@ -293,20 +293,20 @@ "generate_www_non_www_ssl": "It will generate certificates for both www and non-www.
You need to have both DNS entries set in advance.

Service needs to be restarted." }, "service": { - "stop_service": "Stop Service", + "stop_service": "Stop", "permission_denied_stop_service": "You do not have permission to stop the service.", - "start_service": "Start Service", + "start_service": "Start", "permission_denied_start_service": "You do not have permission to start the service.", - "delete_service": "Delete Service", + "delete_service": "Delete", "permission_denied_delete_service": "You do not have permission to delete a service.", "no_service": "No services found", - "logs": "Service Logs" + "logs": "Logs" }, "setting": { "change_language": "Change Language", "permission_denied": "You do not have permission to do this. \\nAsk an admin to modify your permissions.", "domain_removed": "Domain removed", - "ssl_explainer": "If you specify https, Coolify will be accessible only over https. SSL certificate will be generated for you.
If you specify www, Coolify will be redirected (302) from non-www and vice versa.

WARNING: If you change an already set domain, it will brake webhooks and other integrations! You need to manually update them.", + "ssl_explainer": "If you specify https, Coolify will be accessible only over https. SSL certificate will be generated for you.
If you specify www, Coolify will be redirected (302) from non-www and vice versa.

WARNING: If you change an already set domain, it will break webhooks and other integrations! You need to manually update them.", "must_remove_domain_before_changing": "Must remove the domain before you can change this setting.", "registration_allowed": "Registration allowed?", "registration_allowed_explainer": "Allow further registrations to the application.
It's turned off after the first registration.", @@ -314,7 +314,7 @@ "credential_stat_explainer": "Credentials for stats page.", "auto_update_enabled": "Auto update enabled?", "auto_update_enabled_explainer": "Enable automatic updates for Coolify. It will be done automatically behind the scenes, if there is no build process running.", - "generate_www_non_www_ssl": "It will generate certificates for both www and non-www.
You need to have both DNS entries set in advance.", + "generate_www_non_www_ssl": "It will generate certificates for both www and non-www.
You need to have both DNS entries set in advance.", "is_dns_check_enabled": "DNS check enabled?", "is_dns_check_enabled_explainer": "You can disable DNS check before creating SSL certificates.

Turning it off is useful when Coolify is behind a reverse proxy or tunnel." }, diff --git a/apps/ui/src/lib/locales/fr.json b/apps/ui/src/lib/locales/fr.json index 242ac6fce..9dc5aa8c4 100644 --- a/apps/ui/src/lib/locales/fr.json +++ b/apps/ui/src/lib/locales/fr.json @@ -50,7 +50,7 @@ "delete_application": "Supprimer l'application", "deployment_queued": "Déploiement en file d'attente.", "destination": "Destination", - "directory_to_use_explainer": "Répertoire à utiliser comme base pour toutes les commandes.
Pourrait être utile avec monorepos.", + "directory_to_use_explainer": "Répertoire à utiliser comme base pour toutes les commandes.
Pourrait être utile avec monorepos.", "dns_not_set_error": "DNS non défini ou propagé pour {{domain}}.

Veuillez vérifier vos paramètres DNS.", "dns_not_set_partial_error": "DNS non défini", "domain_already_in_use": "Le domaine {{domain}} est déjà utilisé.", @@ -181,7 +181,7 @@ "path": "Chemin", "port": "Port", "public_port_range": "Gamme de ports publics", - "public_port_range_explainer": "Ports utilisés pour exposer les bases de données/services/services internes.
Ajoutez-les à votre pare-feu (le cas échéant).

Vous pouvez spécifier une plage de ports, par exemple : 9000-9100", + "public_port_range_explainer": "Ports utilisés pour exposer les bases de données/services/services internes.
Ajoutez-les à votre pare-feu (le cas échéant).

Vous pouvez spécifier une plage de ports, par exemple : 9000-9100", "publish_directory": "Publier le répertoire", "remove": "Retirer", "remove_domain": "Supprimer le domaine", @@ -266,7 +266,7 @@ "permission_denied": "Vous n'avez pas la permission de faire cela. \n\\nDemandez à un administrateur de modifier vos autorisations.", "registration_allowed": "Inscription autorisée ?", "registration_allowed_explainer": "Autoriser d'autres inscriptions à l'application. \n
Il est désactivé après la première inscription.", - "ssl_explainer": "Si vous spécifiez https, Coolify sera accessible uniquement via https. \nUn certificat SSL sera généré pour vous.
Si vous spécifiez www, Coolify sera redirigé (302) à partir de non-www et vice versa." + "ssl_explainer": "Si vous spécifiez https, Coolify sera accessible uniquement via https. \nUn certificat SSL sera généré pour vous.
Si vous spécifiez www, Coolify sera redirigé (302) à partir de non-www et vice versa." }, "source": { "application_id": "ID d'application", diff --git a/apps/ui/src/lib/store.ts b/apps/ui/src/lib/store.ts index 627885385..4114026d5 100644 --- a/apps/ui/src/lib/store.ts +++ b/apps/ui/src/lib/store.ts @@ -1,6 +1,9 @@ -import { writable, readable, type Writable, type Readable } from 'svelte/store'; +import { dev } from '$app/env'; +import cuid from 'cuid'; +import { writable, readable, type Writable } from 'svelte/store'; interface AppSession { + registrationEnabled: boolean; ipv4: string | null, ipv6: string | null, version: string | null, @@ -15,7 +18,13 @@ interface AppSession { tokens: { github: string | null, gitlab: string | null, - } + }, + supportedServiceTypesAndVersions: Array +} +interface AddToast { + type?: "info" | "success" | "error", + message: string, + timeout?: number | undefined } export const loginEmail: Writable = writable() export const appSession: Writable = writable({ @@ -33,9 +42,30 @@ export const appSession: Writable = writable({ tokens: { github: null, gitlab: null - } + }, + supportedServiceTypesAndVersions: [] }); export const disabledButton: Writable = writable(false); +export const isDeploymentEnabled: Writable = writable(false); +export function checkIfDeploymentEnabledApplications(isAdmin: boolean, application: any) { + return ( + isAdmin && + (application.fqdn || application.settings.isBot) && + application.gitSource && + application.repository && + application.destinationDocker && + application.buildPack + ); +} +export function checkIfDeploymentEnabledServices(isAdmin: boolean, service: any) { + return ( + isAdmin && + service.fqdn && + service.destinationDocker && + service.version && + service.type + ); +} export const status: Writable = writable({ application: { isRunning: false, @@ -64,14 +94,61 @@ export const features = readable({ }); export const location: Writable = writable(null) -export const setLocation = (resource: any) => { +export const setLocation = (resource: any, settings?: any) => { + if (resource.settings.isBot && resource.exposePort) { + disabledButton.set(false); + return location.set(`http://${dev ? 'localhost' : settings.ipv4}:${resource.exposePort}`) + } if (GITPOD_WORKSPACE_URL && resource.exposePort) { const { href } = new URL(GITPOD_WORKSPACE_URL); const newURL = href .replace('https://', `https://${resource.exposePort}-`) .replace(/\/$/, ''); - location.set(newURL) - } else { - location.set(resource.fqdn) + return location.set(newURL) + } else if (CODESANDBOX_HOST) { + const newURL = `https://${CODESANDBOX_HOST.replace(/\$PORT/, resource.exposePort)}` + return location.set(newURL) } + if (resource.fqdn) { + return location.set(resource.fqdn) + } else { + location.set(null); + disabledButton.set(false); + } +} + +export const toasts: any = writable([]) + +export const dismissToast = (id: string) => { + toasts.update((all: any) => all.filter((t: any) => t.id !== id)) +} +export const pauseToast = (id: string) => { + toasts.update((all: any) => { + const index = all.findIndex((t: any) => t.id === id); + if (index > -1) clearTimeout(all[index].timeoutInterval); + return all; + }) +} +export const resumeToast = (id: string) => { + toasts.update((all: any) => { + const index = all.findIndex((t: any) => t.id === id); + if (index > -1) { + all[index].timeoutInterval = setTimeout(() => { + dismissToast(id) + }, all[index].timeout) + } + return all; + }) +} + +export const addToast = (toast: AddToast) => { + const id = cuid(); + const defaults = { + id, + type: 'info', + timeout: 2000, + } + let t: any = { ...defaults, ...toast } + if (t.timeout) t.timeoutInterval = setTimeout(() => dismissToast(id), t.timeout) + toasts.update((all: any) => [t, ...all]) } \ No newline at end of file diff --git a/apps/ui/src/lib/templates.ts b/apps/ui/src/lib/templates.ts index b2e27ad1c..c4ec05ad6 100644 --- a/apps/ui/src/lib/templates.ts +++ b/apps/ui/src/lib/templates.ts @@ -170,6 +170,16 @@ export function findBuildPack(pack: string, packageManager = 'npm') { port: 80 }; } + if (pack === 'heroku') { + return { + ...metaData, + installCommand: null, + buildCommand: null, + startCommand: null, + publishDirectory: null, + port: 5000 + }; + } return { name: 'node', fancyName: 'Node.js', @@ -187,112 +197,137 @@ export const buildPacks = [ name: 'node', fancyName: 'Node.js', hoverColor: 'hover:bg-green-700', - color: 'bg-green-700' + color: 'bg-green-700', + isCoolifyBuildPack: true, }, { name: 'static', fancyName: 'Static', hoverColor: 'hover:bg-orange-700', - color: 'bg-orange-700' + color: 'bg-orange-700', + isCoolifyBuildPack: true, }, { name: 'php', fancyName: 'PHP', hoverColor: 'hover:bg-indigo-700', - color: 'bg-indigo-700' + color: 'bg-indigo-700', + isCoolifyBuildPack: true, }, { name: 'laravel', fancyName: 'Laravel', hoverColor: 'hover:bg-indigo-700', - color: 'bg-indigo-700' + color: 'bg-indigo-700', + isCoolifyBuildPack: true, }, { name: 'docker', fancyName: 'Docker', hoverColor: 'hover:bg-sky-700', - color: 'bg-sky-700' + color: 'bg-sky-700', + isCoolifyBuildPack: true, }, { name: 'svelte', fancyName: 'Svelte', hoverColor: 'hover:bg-orange-700', - color: 'bg-orange-700' + color: 'bg-orange-700', + isCoolifyBuildPack: true, }, { name: 'vuejs', fancyName: 'VueJS', hoverColor: 'hover:bg-green-700', - color: 'bg-green-700' + color: 'bg-green-700', + isCoolifyBuildPack: true, }, { name: 'nuxtjs', fancyName: 'NuxtJS', hoverColor: 'hover:bg-green-700', - color: 'bg-green-700' + color: 'bg-green-700', + isCoolifyBuildPack: true, }, { name: 'gatsby', fancyName: 'Gatsby', hoverColor: 'hover:bg-blue-700', - color: 'bg-blue-700' + color: 'bg-blue-700', + isCoolifyBuildPack: true, }, { name: 'astro', fancyName: 'Astro', hoverColor: 'hover:bg-pink-700', - color: 'bg-pink-700' + color: 'bg-pink-700', + isCoolifyBuildPack: true, }, { name: 'eleventy', fancyName: 'Eleventy', hoverColor: 'hover:bg-red-700', - color: 'bg-red-700' + color: 'bg-red-700', + isCoolifyBuildPack: true, }, { name: 'react', fancyName: 'React', hoverColor: 'hover:bg-blue-700', - color: 'bg-blue-700' + color: 'bg-blue-700', + isCoolifyBuildPack: true, }, { name: 'preact', fancyName: 'Preact', hoverColor: 'hover:bg-blue-700', - color: 'bg-blue-700' + color: 'bg-blue-700', + isCoolifyBuildPack: true, }, { name: 'nextjs', fancyName: 'NextJS', hoverColor: 'hover:bg-blue-700', - color: 'bg-blue-700' + color: 'bg-blue-700', + isCoolifyBuildPack: true, }, { name: 'nestjs', fancyName: 'NestJS', hoverColor: 'hover:bg-red-700', - color: 'bg-red-700' + color: 'bg-red-700', + isCoolifyBuildPack: true, }, { name: 'rust', fancyName: 'Rust', hoverColor: 'hover:bg-pink-700', - color: 'bg-pink-700' + color: 'bg-pink-700', + isCoolifyBuildPack: true, }, { name: 'python', fancyName: 'Python', hoverColor: 'hover:bg-green-700', - color: 'bg-green-700' + color: 'bg-green-700', + isCoolifyBuildPack: true, }, { name: 'deno', fancyName: 'Deno', hoverColor: 'hover:bg-green-700', - color: 'bg-green-700' - } + color: 'bg-green-700', + isCoolifyBuildPack: true, + }, + { + name: 'heroku', + fancyName: 'Heroku', + hoverColor: 'hover:bg-purple-700', + color: 'bg-purple-700', + isHerokuBuildPack: true, + } ]; export const scanningTemplates = { '@sveltejs/kit': { diff --git a/apps/ui/src/routes/__layout.svelte b/apps/ui/src/routes/__layout.svelte index 4df7f920b..901aedea5 100644 --- a/apps/ui/src/routes/__layout.svelte +++ b/apps/ui/src/routes/__layout.svelte @@ -65,11 +65,14 @@ - -
-
-
{title}
- -
-
-
-
- Use setting - - - - -
-
diff --git a/apps/ui/src/routes/applications/[id]/_Storage.svelte b/apps/ui/src/routes/applications/[id]/_Storage.svelte index 803b1ed9d..f67686eeb 100644 --- a/apps/ui/src/routes/applications/[id]/_Storage.svelte +++ b/apps/ui/src/routes/applications/[id]/_Storage.svelte @@ -8,9 +8,9 @@ import { page } from '$app/stores'; import { createEventDispatcher } from 'svelte'; - import { toast } from '@zerodevx/svelte-toast'; import { t } from '$lib/translations'; import { errorNotification } from '$lib/common'; + import { addToast } from '$lib/store'; const { id } = $page.params; const dispatch = createEventDispatcher(); @@ -30,8 +30,17 @@ storage.path = null; storage.id = null; } - if (newStorage) toast.push($t('application.storage.storage_saved')); - else toast.push($t('application.storage.storage_updated')); + if (newStorage) { + addToast({ + message: $t('application.storage.storage_saved'), + type: 'success' + }); + } else { + addToast({ + message: $t('application.storage.storage_updated'), + type: 'success' + }); + } } catch (error) { return errorNotification(error); } @@ -40,7 +49,10 @@ try { await del(`/applications/${id}/storages`, { path: storage.path }); dispatch('refresh'); - toast.push($t('application.storage.storage_deleted')); + addToast({ + message: $t('application.storage.storage_deleted'), + type: 'success' + }); } catch (error) { return errorNotification(error); } @@ -52,23 +64,24 @@ bind:value={storage.path} required placeholder="eg: /sqlite.db" - class=" border border-dashed border-coolgray-300" /> {#if isNew}
-
{:else}
- +
-
diff --git a/apps/ui/src/routes/applications/[id]/__layout.svelte b/apps/ui/src/routes/applications/[id]/__layout.svelte index 8d1f52015..0384dab28 100644 --- a/apps/ui/src/routes/applications/[id]/__layout.svelte +++ b/apps/ui/src/routes/applications/[id]/__layout.svelte @@ -16,7 +16,7 @@ export const load: Load = async ({ fetch, url, params }) => { try { const response = await get(`/applications/${params.id}`); - let { application, appId, settings, isQueueActive } = response; + let { application, appId, settings } = response; if (!application || Object.entries(application).length === 0) { return { status: 302, @@ -36,7 +36,8 @@ return { props: { - application + application, + settings }, stuff: { application, @@ -52,35 +53,42 @@ diff --git a/apps/ui/src/routes/applications/[id]/configuration/_BuildPack.svelte b/apps/ui/src/routes/applications/[id]/configuration/_BuildPack.svelte index 93e336dc6..89625336b 100644 --- a/apps/ui/src/routes/applications/[id]/configuration/_BuildPack.svelte +++ b/apps/ui/src/routes/applications/[id]/configuration/_BuildPack.svelte @@ -26,7 +26,7 @@ delete tempBuildPack.color; delete tempBuildPack.hoverColor; - if (foundConfig.buildPack !== name) { + if (foundConfig?.buildPack !== name) { await post(`/applications/${id}`, { ...tempBuildPack, buildPack: name }); } await post(`/applications/${id}/configuration/buildpack`, { buildPack: name }); diff --git a/apps/ui/src/routes/applications/[id]/configuration/_GithubRepositories.svelte b/apps/ui/src/routes/applications/[id]/configuration/_GithubRepositories.svelte index cff6769d0..922c2b174 100644 --- a/apps/ui/src/routes/applications/[id]/configuration/_GithubRepositories.svelte +++ b/apps/ui/src/routes/applications/[id]/configuration/_GithubRepositories.svelte @@ -95,19 +95,19 @@ async function isBranchAlreadyUsed(event: any) { selected.branch = event.detail.value; try { - const data = await get( - `/applications/${id}/configuration/repository?repository=${selected.repository}&branch=${selected.branch}` - ); - if (data.used) { - const sure = confirm($t('application.configuration.branch_already_in_use')); - if (sure) { - selected.autodeploy = false; - showSave = true; - return true; - } - showSave = false; - return true; - } + // const data = await get( + // `/applications/${id}/configuration/repository?repository=${selected.repository}&branch=${selected.branch}` + // ); + // if (data.used) { + // const sure = confirm($t('application.configuration.branch_already_in_use')); + // if (sure) { + // selected.autodeploy = false; + // showSave = true; + // return true; + // } + // showSave = false; + // return true; + // } showSave = true; } catch (error) { showSave = false; @@ -190,11 +190,11 @@
{$t('forms.save')}
diff --git a/apps/ui/src/routes/applications/[id]/configuration/_GitlabRepositories.svelte b/apps/ui/src/routes/applications/[id]/configuration/_GitlabRepositories.svelte index a91ebcc27..3da8c6415 100644 --- a/apps/ui/src/routes/applications/[id]/configuration/_GitlabRepositories.svelte +++ b/apps/ui/src/routes/applications/[id]/configuration/_GitlabRepositories.svelte @@ -169,10 +169,6 @@ } } } - function selectBranch(event: any) { - selected.branch = event.detail; - isBranchAlreadyUsed(); - } async function loadBranches(page: number = 1) { let perPage = 100; //@ts-ignore @@ -199,21 +195,22 @@ } } - async function isBranchAlreadyUsed() { + async function isBranchAlreadyUsed(event) { + selected.branch = event.detail; try { - const data = await get( - `/applications/${id}/configuration/repository?repository=${selected.project.path_with_namespace}&branch=${selected.branch.name}` - ); - if (data.used) { - const sure = confirm($t('application.configuration.branch_already_in_use')); - if (sure) { - autodeploy = false; - showSave = true; - return true; - } - showSave = false; - return true; - } + // const data = await get( + // `/applications/${id}/configuration/repository?repository=${selected.project.path_with_namespace}&branch=${selected.branch.name}` + // ); + // if (data.used) { + // const sure = confirm($t('application.configuration.branch_already_in_use')); + // if (sure) { + // autodeploy = false; + // showSave = true; + // return true; + // } + // showSave = false; + // return true; + // } showSave = true; } catch (error) { return errorNotification(error); @@ -227,9 +224,7 @@ } } async function setWebhook(url: any, webhookToken: any) { - const host = dev - ? getWebhookUrl('gitlab') - : `${window.location.origin}/webhooks/gitlab/events`; + const host = dev ? getWebhookUrl('gitlab') : `${window.location.origin}/webhooks/gitlab/events`; try { await post( url, @@ -294,17 +289,15 @@ ); await post(updateDeployKeyIdUrl, { deployKeyId: id }); } catch (error) { - return errorNotification(error); - } finally { loading.save = false; + return errorNotification(error); } try { await setWebhook(webhookUrl, webhookToken); } catch (error) { - return errorNotification(error); - } finally { loading.save = false; + return errorNotification(error); } const url = `/applications/${id}/configuration/repository`; @@ -317,11 +310,11 @@ autodeploy, webhookToken }); + loading.save = false; return await goto(from || `/applications/${id}/configuration/buildpack`); } catch (error) { - return errorNotification(error); - } finally { loading.save = false; + return errorNotification(error); } } async function handleSubmit() { @@ -396,7 +389,7 @@ showIndicator={!loading.branches} isWaiting={loading.branches} isDisabled={loading.branches || !selected.project} - on:select={selectBranch} + on:select={isBranchAlreadyUsed} on:clear={() => { showSave = false; selected.branch = null; @@ -413,11 +406,10 @@
{#if tryAgain} @@ -426,7 +418,7 @@ configuration here.
+ -
handleSubmit(source.id)}> - -
- - {/each} - + {/each} + - {#if otherSources.length > 0 && $appSession.teamId === '0'} -
Other Sources
+ {#if otherSources.length > 0 && $appSession.teamId === '0'} +
Other Sources
+ {/if} +
+ {#each otherSources as source} +
+
handleSubmit(source.id)}> + +
+
+ {/each} +
{/if} -
- {#each otherSources as source} -
-
handleSubmit(source.id)}> - -
-
- {/each} -
- {/if} + +
+
Public Repository
+ +
+ diff --git a/apps/ui/src/routes/applications/[id]/index.svelte b/apps/ui/src/routes/applications/[id]/index.svelte index 05cc368c6..291ebd820 100644 --- a/apps/ui/src/routes/applications/[id]/index.svelte +++ b/apps/ui/src/routes/applications/[id]/index.svelte @@ -5,7 +5,8 @@ if (stuff?.application?.id) { return { props: { - application: stuff.application + application: stuff.application, + settings: stuff.settings } }; } @@ -26,22 +27,32 @@ -{#if loading} - -{:else} -
- {#if currentStatus === 'running'} - - {/if} - {#if currentStatus === 'queued'} -
{$t('application.build.queued_waiting_exec')}
- {:else} -
+
+ {#if currentStatus === 'running'} + + {/if} + {#if currentStatus === 'queued'} +
{$t('application.build.queued_waiting_exec')}
+ {:else} +
+ + Follow Logs + {#if currentStatus === 'running'} - {#if currentStatus === 'running'} - - {/if} -
- {#if logs.length > 0} -
- {#each logs as log} -
{log.line + '\n'}
- {/each} -
- {:else} -
- No logs found. -
+ Cancel build {/if} +
+ {#if logs.length > 0} +
+ {#each logs as log} +
{log.line + '\n'}
+ {/each} +
+ {:else} +
+ No logs found. +
{/if} -
-{/if} + {/if} +
diff --git a/apps/ui/src/routes/applications/[id]/logs/build.svelte b/apps/ui/src/routes/applications/[id]/logs/build.svelte index eb213c85e..faeec72c0 100644 --- a/apps/ui/src/routes/applications/[id]/logs/build.svelte +++ b/apps/ui/src/routes/applications/[id]/logs/build.svelte @@ -28,17 +28,20 @@ import { get } from '$lib/api'; import { t } from '$lib/translations'; import { changeQueryParams, dateOptions, errorNotification } from '$lib/common'; + import Tooltip from '$lib/components/Tooltip.svelte'; let buildId: any; let skip = 0; let noMoreBuilds = buildCount < 5 || buildCount <= skip; + + let buildTook = 0; const { id } = $page.params; let preselectedBuildId = $page.url.searchParams.get('buildId'); if (preselectedBuildId) buildId = preselectedBuildId; async function updateBuildStatus({ detail }: { detail: any }) { - const { status } = detail; + const { status, took } = detail; if (status !== 'running') { try { const data = await get(`/applications/${id}/logs/build?buildId=${buildId}`); @@ -58,6 +61,7 @@ if (build.id === buildId) build.status = status; return build; }); + buildTook = took; } } async function loadMoreBuilds() { @@ -137,19 +141,18 @@
{#each builds as build, index (build.id)}
loadBuild(build.id)} class:rounded-tr={index === 0} class:rounded-br={index === builds.length - 1} - class="tooltip-top flex cursor-pointer items-center justify-center border-l-2 py-4 no-underline transition-all duration-100 hover:bg-coolgray-400 hover:shadow-xl " + class="flex cursor-pointer items-center justify-center border-l-2 py-4 no-underline transition-all duration-100 hover:bg-coolgray-400 hover:shadow-xl" class:bg-coolgray-400={buildId === build.id} class:border-red-500={build.status === 'failed'} + class:border-orange-500={build.status === 'canceled'} class:border-green-500={build.status === 'success'} class:border-yellow-500={build.status === 'running'} > -
+
{build.branch || application.branch}
@@ -157,11 +160,14 @@ {build.type}
-
{#if build.status === 'running'}
{$t('application.build.running')}
+
+ Elapsed + {buildTook}s +
{:else if build.status === 'queued'}
{$t('application.build.queued')}
{:else} @@ -172,12 +178,16 @@ {/if}
+ {new Intl.DateTimeFormat('default', dateOptions).format(new Date(build.createdAt)) + + `\n${build.status}`} {/each}
{#if !noMoreBuilds} {#if buildCount > 5}
-
diff --git a/apps/ui/src/routes/applications/[id]/logs/index.svelte b/apps/ui/src/routes/applications/[id]/logs/index.svelte index 7a20d8104..160787f1d 100644 --- a/apps/ui/src/routes/applications/[id]/logs/index.svelte +++ b/apps/ui/src/routes/applications/[id]/logs/index.svelte @@ -5,6 +5,7 @@ import { errorNotification } from '$lib/common'; import LoadingLogs from '$lib/components/LoadingLogs.svelte'; import { onMount, onDestroy } from 'svelte'; + import Tooltip from '$lib/components/Tooltip.svelte'; let application: any = {}; let logsLoading = false; @@ -38,7 +39,6 @@ logs = data.logs; } } catch (error) { - console.log(error); return errorNotification(error); } finally { logsLoading = false; @@ -146,9 +146,9 @@ {/if}
+ Follow Logs
- Useful for creating staging environments." @@ -191,12 +194,14 @@
- redeploy(container)}>{$t('application.preview.redeploy')}