feat: Add queue reset button

This commit is contained in:
Andras Bacsai 2022-09-11 11:51:43 +00:00
parent 0a68a48fc5
commit 143cd46a81
6 changed files with 346 additions and 279 deletions

View File

@ -21,7 +21,7 @@ import { scheduler } from './scheduler';
import { supportedServiceTypesAndVersions } from './services/supportedVersions'; import { supportedServiceTypesAndVersions } from './services/supportedVersions';
import { includeServices } from './services/common'; import { includeServices } from './services/common';
export const version = '3.10.1'; export const version = '3.10.2';
export const isDev = process.env.NODE_ENV === 'development'; export const isDev = process.env.NODE_ENV === 'development';
const algorithm = 'aes-256-ctr'; const algorithm = 'aes-256-ctr';

View File

@ -1,296 +1,340 @@
import axios from "axios";
import axios from 'axios'; import { compareVersions } from "compare-versions";
import { compareVersions } from 'compare-versions'; import cuid from "cuid";
import cuid from 'cuid'; import bcrypt from "bcryptjs";
import bcrypt from 'bcryptjs'; import {
import { asyncExecShell, asyncSleep, cleanupDockerStorage, errorHandler, isDev, listSettings, prisma, uniqueName, version } from '../../../lib/common'; asyncExecShell,
import { supportedServiceTypesAndVersions } from '../../../lib/services/supportedVersions'; asyncSleep,
import type { FastifyReply, FastifyRequest } from 'fastify'; cleanupDockerStorage,
import type { Login, Update } from '.'; errorHandler,
import type { GetCurrentUser } from './types'; isDev,
listSettings,
prisma,
uniqueName,
version,
} from "../../../lib/common";
import { supportedServiceTypesAndVersions } from "../../../lib/services/supportedVersions";
import { scheduler } from "../../../lib/scheduler";
import type { FastifyReply, FastifyRequest } from "fastify";
import type { Login, Update } from ".";
import type { GetCurrentUser } from "./types";
export async function hashPassword(password: string): Promise<string> { export async function hashPassword(password: string): Promise<string> {
const saltRounds = 15; const saltRounds = 15;
return bcrypt.hash(password, saltRounds); return bcrypt.hash(password, saltRounds);
} }
export async function cleanupManually(request: FastifyRequest) { export async function cleanupManually(request: FastifyRequest) {
try { try {
const { serverId } = request.body; const { serverId } = request.body;
const destination = await prisma.destinationDocker.findUnique({ where: { id: serverId } }) const destination = await prisma.destinationDocker.findUnique({
await cleanupDockerStorage(destination.id, true, true) where: { id: serverId },
return {} });
} catch ({ status, message }) { await cleanupDockerStorage(destination.id, true, true);
return errorHandler({ status, message }) return {};
} } catch ({ status, message }) {
return errorHandler({ status, message });
}
} }
export async function checkUpdate(request: FastifyRequest) { export async function checkUpdate(request: FastifyRequest) {
try { try {
const isStaging = request.hostname === 'staging.coolify.io' || request.hostname === 'arm.coolify.io' const isStaging =
const currentVersion = version; request.hostname === "staging.coolify.io" ||
const { data: versions } = await axios.get( request.hostname === "arm.coolify.io";
`https://get.coollabs.io/versions.json?appId=${process.env['COOLIFY_APP_ID']}&version=${currentVersion}` const currentVersion = version;
); const { data: versions } = await axios.get(
const latestVersion = versions['coolify'].main.version `https://get.coollabs.io/versions.json?appId=${process.env["COOLIFY_APP_ID"]}&version=${currentVersion}`
const isUpdateAvailable = compareVersions(latestVersion, currentVersion); );
if (isStaging) { const latestVersion = versions["coolify"].main.version;
return { const isUpdateAvailable = compareVersions(latestVersion, currentVersion);
isUpdateAvailable: true, if (isStaging) {
latestVersion: 'next' return {
} isUpdateAvailable: true,
} latestVersion: "next",
return { };
isUpdateAvailable: isStaging ? true : isUpdateAvailable === 1, }
latestVersion return {
}; isUpdateAvailable: isStaging ? true : isUpdateAvailable === 1,
} catch ({ status, message }) { latestVersion,
return errorHandler({ status, message }) };
} } catch ({ status, message }) {
return errorHandler({ status, message });
}
} }
export async function update(request: FastifyRequest<Update>) { export async function update(request: FastifyRequest<Update>) {
const { latestVersion } = request.body; const { latestVersion } = request.body;
try { try {
if (!isDev) { if (!isDev) {
const { isAutoUpdateEnabled } = await prisma.setting.findFirst(); const { isAutoUpdateEnabled } = await prisma.setting.findFirst();
await asyncExecShell(`docker pull coollabsio/coolify:${latestVersion}`); await asyncExecShell(`docker pull coollabsio/coolify:${latestVersion}`);
await asyncExecShell(`env | grep COOLIFY > .env`); await asyncExecShell(`env | grep COOLIFY > .env`);
await asyncExecShell( await asyncExecShell(
`sed -i '/COOLIFY_AUTO_UPDATE=/cCOOLIFY_AUTO_UPDATE=${isAutoUpdateEnabled}' .env` `sed -i '/COOLIFY_AUTO_UPDATE=/cCOOLIFY_AUTO_UPDATE=${isAutoUpdateEnabled}' .env`
); );
await asyncExecShell( 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"` `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"`
); );
return {}; return {};
} else { } else {
await asyncSleep(2000); await asyncSleep(2000);
return {}; return {};
} }
} catch ({ status, message }) { } catch ({ status, message }) {
return errorHandler({ status, message }) return errorHandler({ status, message });
} }
}
export async function resetQueue(request: FastifyRequest<any>) {
try {
const teamId = request.user.teamId;
if (teamId === "0") {
await prisma.build.updateMany({
where: { status: { in: ["queued", "running"] } },
data: { status: "canceled" },
});
scheduler.workers.get("deployApplication").postMessage("cancel");
}
} catch ({ status, message }) {
return errorHandler({ status, message });
}
} }
export async function restartCoolify(request: FastifyRequest<any>) { export async function restartCoolify(request: FastifyRequest<any>) {
try { try {
const teamId = request.user.teamId; const teamId = request.user.teamId;
if (teamId === '0') { if (teamId === "0") {
if (!isDev) { if (!isDev) {
asyncExecShell(`docker restart coolify`); asyncExecShell(`docker restart coolify`);
return {}; return {};
} else { } else {
return {}; return {};
} }
} }
throw { status: 500, message: 'You are not authorized to restart Coolify.' }; throw {
} catch ({ status, message }) { status: 500,
return errorHandler({ status, message }) message: "You are not authorized to restart Coolify.",
} };
} catch ({ status, message }) {
return errorHandler({ status, message });
}
} }
export async function showDashboard(request: FastifyRequest) { export async function showDashboard(request: FastifyRequest) {
try { try {
const userId = request.user.userId; const userId = request.user.userId;
const teamId = request.user.teamId; const teamId = request.user.teamId;
const applications = await prisma.application.findMany({ const applications = await prisma.application.findMany({
where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } }, where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } },
include: { settings: true, destinationDocker: true, teams: true } include: { settings: true, destinationDocker: true, teams: true },
}); });
const databases = await prisma.database.findMany({ const databases = await prisma.database.findMany({
where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } }, where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } },
include: { settings: true, destinationDocker: true, teams: true } include: { settings: true, destinationDocker: true, teams: true },
}); });
const services = await prisma.service.findMany({ const services = await prisma.service.findMany({
where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } }, where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } },
include: { destinationDocker: true, teams: true } include: { destinationDocker: true, teams: true },
}); });
const gitSources = await prisma.gitSource.findMany({ const gitSources = await prisma.gitSource.findMany({
where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } }, where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } },
include: { teams: true } include: { teams: true },
}); });
const destinations = await prisma.destinationDocker.findMany({ const destinations = await prisma.destinationDocker.findMany({
where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } }, where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } },
include: { teams: true } include: { teams: true },
}); });
const settings = await listSettings(); const settings = await listSettings();
return { return {
applications, applications,
databases, databases,
services, services,
gitSources, gitSources,
destinations, destinations,
settings, settings,
}; };
} catch ({ status, message }) { } catch ({ status, message }) {
return errorHandler({ status, message }) return errorHandler({ status, message });
} }
} }
export async function login(request: FastifyRequest<Login>, reply: FastifyReply) { export async function login(
if (request.user) { request: FastifyRequest<Login>,
return reply.redirect('/dashboard'); reply: FastifyReply
} else { ) {
const { email, password, isLogin } = request.body || {}; if (request.user) {
if (!email || !password) { return reply.redirect("/dashboard");
throw { status: 500, message: 'Email and password are required.' }; } else {
} const { email, password, isLogin } = request.body || {};
const users = await prisma.user.count(); if (!email || !password) {
const userFound = await prisma.user.findUnique({ throw { status: 500, message: "Email and password are required." };
where: { email }, }
include: { teams: true, permission: true }, const users = await prisma.user.count();
rejectOnNotFound: false const userFound = await prisma.user.findUnique({
}); where: { email },
if (!userFound && isLogin) { include: { teams: true, permission: true },
throw { status: 500, message: 'User not found.' }; rejectOnNotFound: false,
} });
const { isRegistrationEnabled, id } = await prisma.setting.findFirst() if (!userFound && isLogin) {
let uid = cuid(); throw { status: 500, message: "User not found." };
let permission = 'read'; }
let isAdmin = false; const { isRegistrationEnabled, id } = await prisma.setting.findFirst();
let uid = cuid();
let permission = "read";
let isAdmin = false;
if (users === 0) { if (users === 0) {
await prisma.setting.update({ where: { id }, data: { isRegistrationEnabled: false } }); await prisma.setting.update({
uid = '0'; where: { id },
} data: { isRegistrationEnabled: false },
if (userFound) { });
if (userFound.type === 'email') { uid = "0";
if (userFound.password === 'RESETME') { }
const hashedPassword = await hashPassword(password); if (userFound) {
if (userFound.updatedAt < new Date(Date.now() - 1000 * 60 * 10)) { if (userFound.type === "email") {
if (userFound.id === '0') { if (userFound.password === "RESETME") {
await prisma.user.update({ const hashedPassword = await hashPassword(password);
where: { email: userFound.email }, if (userFound.updatedAt < new Date(Date.now() - 1000 * 60 * 10)) {
data: { password: 'RESETME' } if (userFound.id === "0") {
}); await prisma.user.update({
} else { where: { email: userFound.email },
await prisma.user.update({ data: { password: "RESETME" },
where: { email: userFound.email }, });
data: { password: 'RESETTIMEOUT' } } else {
}); await prisma.user.update({
} where: { email: userFound.email },
data: { password: "RESETTIMEOUT" },
});
}
throw { throw {
status: 500, status: 500,
message: 'Password reset link has expired. Please request a new one.' message:
}; "Password reset link has expired. Please request a new one.",
} else { };
await prisma.user.update({ } else {
where: { email: userFound.email }, await prisma.user.update({
data: { password: hashedPassword } where: { email: userFound.email },
}); data: { password: hashedPassword },
return { });
userId: userFound.id, return {
teamId: userFound.id, userId: userFound.id,
permission: userFound.permission, teamId: userFound.id,
isAdmin: true permission: userFound.permission,
}; isAdmin: true,
} };
} }
}
const passwordMatch = await bcrypt.compare(password, userFound.password); const passwordMatch = await bcrypt.compare(
if (!passwordMatch) { password,
throw { userFound.password
status: 500, );
message: 'Wrong password or email address.' if (!passwordMatch) {
}; throw {
} status: 500,
uid = userFound.id; message: "Wrong password or email address.",
isAdmin = true; };
} }
} else { uid = userFound.id;
permission = 'owner'; isAdmin = true;
isAdmin = true; }
if (!isRegistrationEnabled) { } else {
throw { permission = "owner";
status: 404, isAdmin = true;
message: 'Registration disabled by administrator.' if (!isRegistrationEnabled) {
}; throw {
} status: 404,
const hashedPassword = await hashPassword(password); message: "Registration disabled by administrator.",
if (users === 0) { };
await prisma.user.create({ }
data: { const hashedPassword = await hashPassword(password);
id: uid, if (users === 0) {
email, await prisma.user.create({
password: hashedPassword, data: {
type: 'email', id: uid,
teams: { email,
create: { password: hashedPassword,
id: uid, type: "email",
name: uniqueName(), teams: {
destinationDocker: { connect: { network: 'coolify' } } create: {
} id: uid,
}, name: uniqueName(),
permission: { create: { teamId: uid, permission: 'owner' } } destinationDocker: { connect: { network: "coolify" } },
}, },
include: { teams: true } },
}); permission: { create: { teamId: uid, permission: "owner" } },
} else { },
await prisma.user.create({ include: { teams: true },
data: { });
id: uid, } else {
email, await prisma.user.create({
password: hashedPassword, data: {
type: 'email', id: uid,
teams: { email,
create: { password: hashedPassword,
id: uid, type: "email",
name: uniqueName() teams: {
} create: {
}, id: uid,
permission: { create: { teamId: uid, permission: 'owner' } } name: uniqueName(),
}, },
include: { teams: true } },
}); permission: { create: { teamId: uid, permission: "owner" } },
} },
} include: { teams: true },
return { });
userId: uid, }
teamId: uid, }
permission, return {
isAdmin userId: uid,
}; teamId: uid,
} permission,
isAdmin,
};
}
} }
export async function getCurrentUser(request: FastifyRequest<GetCurrentUser>, fastify) { export async function getCurrentUser(
let token = null request: FastifyRequest<GetCurrentUser>,
const { teamId } = request.query fastify
try { ) {
const user = await prisma.user.findUnique({ let token = null;
where: { id: request.user.userId } const { teamId } = request.query;
}) try {
if (!user) { const user = await prisma.user.findUnique({
throw "User not found"; where: { id: request.user.userId },
} });
} catch (error) { if (!user) {
throw { status: 401, message: error }; throw "User not found";
} }
if (teamId) { } catch (error) {
try { throw { status: 401, message: error };
const user = await prisma.user.findFirst({ }
where: { id: request.user.userId, teams: { some: { id: teamId } } }, if (teamId) {
include: { teams: true, permission: true } try {
}) const user = await prisma.user.findFirst({
if (user) { where: { id: request.user.userId, teams: { some: { id: teamId } } },
const permission = user.permission.find(p => p.teamId === teamId).permission include: { teams: true, permission: true },
const payload = { });
...request.user, if (user) {
teamId, const permission = user.permission.find(
permission: permission || null, (p) => p.teamId === teamId
isAdmin: permission === 'owner' || permission === 'admin' ).permission;
const payload = {
} ...request.user,
token = fastify.jwt.sign(payload) teamId,
} permission: permission || null,
isAdmin: permission === "owner" || permission === "admin",
} catch (error) { };
// No new token -> not switching teams token = fastify.jwt.sign(payload);
} }
} } catch (error) {
return { // No new token -> not switching teams
settings: await prisma.setting.findFirst(), }
supportedServiceTypesAndVersions, }
token, return {
...request.user settings: await prisma.setting.findFirst(),
} supportedServiceTypesAndVersions,
token,
...request.user,
};
} }

View File

@ -1,5 +1,5 @@
import { FastifyPluginAsync } from 'fastify'; import { FastifyPluginAsync } from 'fastify';
import { checkUpdate, login, showDashboard, update, showUsage, getCurrentUser, cleanupManually, restartCoolify } from './handlers'; import { checkUpdate, login, showDashboard, update, resetQueue, getCurrentUser, cleanupManually, restartCoolify } from './handlers';
import { GetCurrentUser } from './types'; import { GetCurrentUser } from './types';
export interface Update { export interface Update {
@ -47,6 +47,10 @@ const root: FastifyPluginAsync = async (fastify): Promise<void> => {
onRequest: [fastify.authenticate] onRequest: [fastify.authenticate]
}, async (request) => await restartCoolify(request)); }, async (request) => await restartCoolify(request));
fastify.post('/internal/resetQueue', {
onRequest: [fastify.authenticate]
}, async (request) => await resetQueue(request));
fastify.post('/internal/cleanup', { fastify.post('/internal/cleanup', {
onRequest: [fastify.authenticate] onRequest: [fastify.authenticate]
}, async (request) => await cleanupManually(request)); }, async (request) => await cleanupManually(request));

View File

@ -24,8 +24,9 @@
export let buildCount: any; export let buildCount: any;
import { page } from '$app/stores'; import { page } from '$app/stores';
import {addToast} from '$lib/store';
import BuildLog from './_BuildLog.svelte'; import BuildLog from './_BuildLog.svelte';
import { get } from '$lib/api'; import { get, post } from '$lib/api';
import { t } from '$lib/translations'; import { t } from '$lib/translations';
import { changeQueryParams, dateOptions, errorNotification } from '$lib/common'; import { changeQueryParams, dateOptions, errorNotification } from '$lib/common';
import Tooltip from '$lib/components/Tooltip.svelte'; import Tooltip from '$lib/components/Tooltip.svelte';
@ -83,6 +84,21 @@
buildId = build; buildId = build;
return changeQueryParams(buildId); return changeQueryParams(buildId);
} }
async function resetQueue() {
const sure = confirm('It will reset all build queues for all applications. If something is queued, it will be canceled automatically. Are you sure? ');
if (sure) {
try {
await post(`/internal/resetQueue`, {});
addToast({
message: 'Queue reset done.',
type: 'success'
});
} catch (error) {
return errorNotification(error);
}
}
}
</script> </script>
<div class="flex items-center space-x-2 p-5 px-6 font-bold"> <div class="flex items-center space-x-2 p-5 px-6 font-bold">
@ -138,6 +154,7 @@
</div> </div>
<div class="block flex-row justify-start space-x-2 px-5 pt-6 sm:px-10 md:flex"> <div class="block flex-row justify-start space-x-2 px-5 pt-6 sm:px-10 md:flex">
<div class="mb-4 min-w-[16rem] space-y-2 md:mb-0 "> <div class="mb-4 min-w-[16rem] space-y-2 md:mb-0 ">
<button class="btn btn-sm text-xs w-full bg-error" on:click={resetQueue}>Reset Build Queue</button>
<div class="top-4 md:sticky"> <div class="top-4 md:sticky">
{#each builds as build, index (build.id)} {#each builds as build, index (build.id)}
<div <div
@ -187,7 +204,7 @@
{#if !noMoreBuilds} {#if !noMoreBuilds}
{#if buildCount > 5} {#if buildCount > 5}
<div class="flex space-x-2"> <div class="flex space-x-2">
<button disabled={noMoreBuilds} class=" btn btn-sm w-full" on:click={loadMoreBuilds} <button disabled={noMoreBuilds} class=" btn btn-sm w-full text-xs" on:click={loadMoreBuilds}
>{$t('application.build.load_more')}</button >{$t('application.build.load_more')}</button
> >
</div> </div>

View File

@ -32,7 +32,7 @@
import Usage from '$lib/components/Usage.svelte'; import Usage from '$lib/components/Usage.svelte';
import { t } from '$lib/translations'; import { t } from '$lib/translations';
import { asyncSleep } from '$lib/common'; import { asyncSleep } from '$lib/common';
import { appSession, search } from '$lib/store'; import { appSession, search, addToast} from '$lib/store';
import ApplicationsIcons from '$lib/components/svg/applications/ApplicationIcons.svelte'; import ApplicationsIcons from '$lib/components/svg/applications/ApplicationIcons.svelte';
import DatabaseIcons from '$lib/components/svg/databases/DatabaseIcons.svelte'; import DatabaseIcons from '$lib/components/svg/databases/DatabaseIcons.svelte';
@ -273,6 +273,7 @@
filtered = setInitials(); filtered = setInitials();
} }
} }
</script> </script>
<div class="flex space-x-1 p-6 font-bold"> <div class="flex space-x-1 p-6 font-bold">
@ -280,6 +281,7 @@
{#if $appSession.isAdmin && (applications.length !== 0 || destinations.length !== 0 || databases.length !== 0 || services.length !== 0 || gitSources.length !== 0 || destinations.length !== 0)} {#if $appSession.isAdmin && (applications.length !== 0 || destinations.length !== 0 || databases.length !== 0 || services.length !== 0 || gitSources.length !== 0 || destinations.length !== 0)}
<NewResource /> <NewResource />
{/if} {/if}
</div> </div>
<div class="container lg:mx-auto lg:p-0 px-8 p-5"> <div class="container lg:mx-auto lg:p-0 px-8 p-5">
<!-- {#if $appSession.teamId === '0'} <!-- {#if $appSession.teamId === '0'}

View File

@ -1,7 +1,7 @@
{ {
"name": "coolify", "name": "coolify",
"description": "An open-source & self-hostable Heroku / Netlify alternative.", "description": "An open-source & self-hostable Heroku / Netlify alternative.",
"version": "3.10.1", "version": "3.10.2",
"license": "Apache-2.0", "license": "Apache-2.0",
"repository": "github:coollabsio/coolify", "repository": "github:coollabsio/coolify",
"scripts": { "scripts": {