mirror of
https://github.com/Dokploy/dokploy
synced 2025-06-26 18:27:59 +00:00
Merge remote-tracking branch 'origin/feature/delete-docker-volumes' into feature/delete-docker-volumes
This commit is contained in:
@@ -1,5 +1,6 @@
|
|||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
@@ -31,6 +32,7 @@ const deleteApplicationSchema = z.object({
|
|||||||
projectName: z.string().min(1, {
|
projectName: z.string().min(1, {
|
||||||
message: "Application name is required",
|
message: "Application name is required",
|
||||||
}),
|
}),
|
||||||
|
deleteVolumes: z.boolean(),
|
||||||
});
|
});
|
||||||
|
|
||||||
type DeleteApplication = z.infer<typeof deleteApplicationSchema>;
|
type DeleteApplication = z.infer<typeof deleteApplicationSchema>;
|
||||||
@@ -50,6 +52,7 @@ export const DeleteApplication = ({ applicationId }: Props) => {
|
|||||||
const form = useForm<DeleteApplication>({
|
const form = useForm<DeleteApplication>({
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
projectName: "",
|
projectName: "",
|
||||||
|
deleteVolumes: false,
|
||||||
},
|
},
|
||||||
resolver: zodResolver(deleteApplicationSchema),
|
resolver: zodResolver(deleteApplicationSchema),
|
||||||
});
|
});
|
||||||
@@ -59,6 +62,7 @@ export const DeleteApplication = ({ applicationId }: Props) => {
|
|||||||
if (formData.projectName === expectedName) {
|
if (formData.projectName === expectedName) {
|
||||||
await mutateAsync({
|
await mutateAsync({
|
||||||
applicationId,
|
applicationId,
|
||||||
|
deleteVolumes: formData.deleteVolumes,
|
||||||
})
|
})
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
push(`/dashboard/project/${data?.projectId}`);
|
push(`/dashboard/project/${data?.projectId}`);
|
||||||
@@ -134,6 +138,27 @@ export const DeleteApplication = ({ applicationId }: Props) => {
|
|||||||
</FormItem>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="deleteVolumes"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<div className="flex items-center">
|
||||||
|
<FormControl>
|
||||||
|
<Checkbox
|
||||||
|
checked={field.value}
|
||||||
|
onCheckedChange={field.onChange}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormLabel className="ml-2">
|
||||||
|
Delete volumes associated with this compose
|
||||||
|
</FormLabel>
|
||||||
|
</div>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
</form>
|
</form>
|
||||||
</Form>
|
</Form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
import { db } from "@/server/db";
|
import { db } from "@/server/db";
|
||||||
import {
|
import {
|
||||||
apiCreateApplication,
|
apiCreateApplication,
|
||||||
|
apiDeleteApplication,
|
||||||
apiFindMonitoringStats,
|
apiFindMonitoringStats,
|
||||||
apiFindOneApplication,
|
apiFindOneApplication,
|
||||||
apiReloadApplication,
|
apiReloadApplication,
|
||||||
@@ -142,7 +143,7 @@ export const applicationRouter = createTRPCRouter({
|
|||||||
}),
|
}),
|
||||||
|
|
||||||
delete: protectedProcedure
|
delete: protectedProcedure
|
||||||
.input(apiFindOneApplication)
|
.input(apiDeleteApplication)
|
||||||
.mutation(async ({ input, ctx }) => {
|
.mutation(async ({ input, ctx }) => {
|
||||||
if (ctx.user.rol === "user") {
|
if (ctx.user.rol === "user") {
|
||||||
await checkServiceAccess(
|
await checkServiceAccess(
|
||||||
@@ -178,7 +179,11 @@ export const applicationRouter = createTRPCRouter({
|
|||||||
async () =>
|
async () =>
|
||||||
await removeTraefikConfig(application.appName, application.serverId),
|
await removeTraefikConfig(application.appName, application.serverId),
|
||||||
async () =>
|
async () =>
|
||||||
await removeService(application?.appName, application.serverId),
|
await removeService(
|
||||||
|
application?.appName,
|
||||||
|
application.serverId,
|
||||||
|
input.deleteVolumes,
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const operation of cleanupOperations) {
|
for (const operation of cleanupOperations) {
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import { github } from "./github";
|
|||||||
import { gitlab } from "./gitlab";
|
import { gitlab } from "./gitlab";
|
||||||
import { mounts } from "./mount";
|
import { mounts } from "./mount";
|
||||||
import { ports } from "./port";
|
import { ports } from "./port";
|
||||||
|
import { previewDeployments } from "./preview-deployments";
|
||||||
import { projects } from "./project";
|
import { projects } from "./project";
|
||||||
import { redirects } from "./redirects";
|
import { redirects } from "./redirects";
|
||||||
import { registry } from "./registry";
|
import { registry } from "./registry";
|
||||||
@@ -25,7 +26,6 @@ import { server } from "./server";
|
|||||||
import { applicationStatus, certificateType } from "./shared";
|
import { applicationStatus, certificateType } from "./shared";
|
||||||
import { sshKeys } from "./ssh-key";
|
import { sshKeys } from "./ssh-key";
|
||||||
import { generateAppName } from "./utils";
|
import { generateAppName } from "./utils";
|
||||||
import { previewDeployments } from "./preview-deployments";
|
|
||||||
|
|
||||||
export const sourceType = pgEnum("sourceType", [
|
export const sourceType = pgEnum("sourceType", [
|
||||||
"docker",
|
"docker",
|
||||||
@@ -518,3 +518,8 @@ export const apiUpdateApplication = createSchema
|
|||||||
applicationId: z.string().min(1),
|
applicationId: z.string().min(1),
|
||||||
})
|
})
|
||||||
.omit({ serverId: true });
|
.omit({ serverId: true });
|
||||||
|
|
||||||
|
export const apiDeleteApplication = z.object({
|
||||||
|
applicationId: z.string().min(1),
|
||||||
|
deleteVolumes: z.boolean(),
|
||||||
|
});
|
||||||
|
|||||||
@@ -15,520 +15,528 @@ import { spawnAsync } from "../process/spawnAsync";
|
|||||||
import { getRemoteDocker } from "../servers/remote-docker";
|
import { getRemoteDocker } from "../servers/remote-docker";
|
||||||
|
|
||||||
interface RegistryAuth {
|
interface RegistryAuth {
|
||||||
username: string;
|
username: string;
|
||||||
password: string;
|
password: string;
|
||||||
registryUrl: string;
|
registryUrl: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const pullImage = async (
|
export const pullImage = async (
|
||||||
dockerImage: string,
|
dockerImage: string,
|
||||||
onData?: (data: any) => void,
|
onData?: (data: any) => void,
|
||||||
authConfig?: Partial<RegistryAuth>,
|
authConfig?: Partial<RegistryAuth>
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
if (!dockerImage) {
|
if (!dockerImage) {
|
||||||
throw new Error("Docker image not found");
|
throw new Error("Docker image not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (authConfig?.username && authConfig?.password) {
|
if (authConfig?.username && authConfig?.password) {
|
||||||
await spawnAsync(
|
await spawnAsync(
|
||||||
"docker",
|
"docker",
|
||||||
[
|
[
|
||||||
"login",
|
"login",
|
||||||
authConfig.registryUrl || "",
|
authConfig.registryUrl || "",
|
||||||
"-u",
|
"-u",
|
||||||
authConfig.username,
|
authConfig.username,
|
||||||
"-p",
|
"-p",
|
||||||
authConfig.password,
|
authConfig.password,
|
||||||
],
|
],
|
||||||
onData,
|
onData
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
await spawnAsync("docker", ["pull", dockerImage], onData);
|
await spawnAsync("docker", ["pull", dockerImage], onData);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const pullRemoteImage = async (
|
export const pullRemoteImage = async (
|
||||||
dockerImage: string,
|
dockerImage: string,
|
||||||
serverId: string,
|
serverId: string,
|
||||||
onData?: (data: any) => void,
|
onData?: (data: any) => void,
|
||||||
authConfig?: Partial<RegistryAuth>,
|
authConfig?: Partial<RegistryAuth>
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
if (!dockerImage) {
|
if (!dockerImage) {
|
||||||
throw new Error("Docker image not found");
|
throw new Error("Docker image not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const remoteDocker = await getRemoteDocker(serverId);
|
const remoteDocker = await getRemoteDocker(serverId);
|
||||||
|
|
||||||
await new Promise((resolve, reject) => {
|
await new Promise((resolve, reject) => {
|
||||||
remoteDocker.pull(
|
remoteDocker.pull(
|
||||||
dockerImage,
|
dockerImage,
|
||||||
{ authconfig: authConfig },
|
{ authconfig: authConfig },
|
||||||
(err, stream) => {
|
(err, stream) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(err);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
remoteDocker.modem.followProgress(
|
remoteDocker.modem.followProgress(
|
||||||
stream as Readable,
|
stream as Readable,
|
||||||
(err: Error | null, res) => {
|
(err: Error | null, res) => {
|
||||||
if (!err) {
|
if (!err) {
|
||||||
resolve(res);
|
resolve(res);
|
||||||
}
|
}
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(err);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
(event) => {
|
(event) => {
|
||||||
onData?.(event);
|
onData?.(event);
|
||||||
},
|
}
|
||||||
);
|
);
|
||||||
},
|
}
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const containerExists = async (containerName: string) => {
|
export const containerExists = async (containerName: string) => {
|
||||||
const container = docker.getContainer(containerName);
|
const container = docker.getContainer(containerName);
|
||||||
try {
|
try {
|
||||||
await container.inspect();
|
await container.inspect();
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const stopService = async (appName: string) => {
|
export const stopService = async (appName: string) => {
|
||||||
try {
|
try {
|
||||||
await execAsync(`docker service scale ${appName}=0 `);
|
await execAsync(`docker service scale ${appName}=0 `);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
return error;
|
return error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const stopServiceRemote = async (serverId: string, appName: string) => {
|
export const stopServiceRemote = async (serverId: string, appName: string) => {
|
||||||
try {
|
try {
|
||||||
await execAsyncRemote(serverId, `docker service scale ${appName}=0 `);
|
await execAsyncRemote(serverId, `docker service scale ${appName}=0 `);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
return error;
|
return error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getContainerByName = (name: string): Promise<ContainerInfo> => {
|
export const getContainerByName = (name: string): Promise<ContainerInfo> => {
|
||||||
const opts = {
|
const opts = {
|
||||||
limit: 1,
|
limit: 1,
|
||||||
filters: {
|
filters: {
|
||||||
name: [name],
|
name: [name],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
docker.listContainers(opts, (err, containers) => {
|
docker.listContainers(opts, (err, containers) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(err);
|
||||||
} else if (containers?.length === 0) {
|
} else if (containers?.length === 0) {
|
||||||
reject(new Error(`No container found with name: ${name}`));
|
reject(new Error(`No container found with name: ${name}`));
|
||||||
} else if (containers && containers?.length > 0 && containers[0]) {
|
} else if (containers && containers?.length > 0 && containers[0]) {
|
||||||
resolve(containers[0]);
|
resolve(containers[0]);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
export const cleanUpUnusedImages = async (serverId?: string) => {
|
export const cleanUpUnusedImages = async (serverId?: string) => {
|
||||||
try {
|
try {
|
||||||
if (serverId) {
|
if (serverId) {
|
||||||
await execAsyncRemote(serverId, "docker image prune --all --force");
|
await execAsyncRemote(serverId, "docker image prune --all --force");
|
||||||
} else {
|
} else {
|
||||||
await execAsync("docker image prune --all --force");
|
await execAsync("docker image prune --all --force");
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const cleanStoppedContainers = async (serverId?: string) => {
|
export const cleanStoppedContainers = async (serverId?: string) => {
|
||||||
try {
|
try {
|
||||||
if (serverId) {
|
if (serverId) {
|
||||||
await execAsyncRemote(serverId, "docker container prune --force");
|
await execAsyncRemote(serverId, "docker container prune --force");
|
||||||
} else {
|
} else {
|
||||||
await execAsync("docker container prune --force");
|
await execAsync("docker container prune --force");
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const cleanUpUnusedVolumes = async (serverId?: string) => {
|
export const cleanUpUnusedVolumes = async (serverId?: string) => {
|
||||||
try {
|
try {
|
||||||
if (serverId) {
|
if (serverId) {
|
||||||
await execAsyncRemote(serverId, "docker volume prune --all --force");
|
await execAsyncRemote(serverId, "docker volume prune --all --force");
|
||||||
} else {
|
} else {
|
||||||
await execAsync("docker volume prune --all --force");
|
await execAsync("docker volume prune --all --force");
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const cleanUpInactiveContainers = async () => {
|
export const cleanUpInactiveContainers = async () => {
|
||||||
try {
|
try {
|
||||||
const containers = await docker.listContainers({ all: true });
|
const containers = await docker.listContainers({ all: true });
|
||||||
const inactiveContainers = containers.filter(
|
const inactiveContainers = containers.filter(
|
||||||
(container) => container.State !== "running",
|
(container) => container.State !== "running"
|
||||||
);
|
);
|
||||||
|
|
||||||
for (const container of inactiveContainers) {
|
for (const container of inactiveContainers) {
|
||||||
await docker.getContainer(container.Id).remove({ force: true });
|
await docker.getContainer(container.Id).remove({ force: true });
|
||||||
console.log(`Cleaning up inactive container: ${container.Id}`);
|
console.log(`Cleaning up inactive container: ${container.Id}`);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error cleaning up inactive containers:", error);
|
console.error("Error cleaning up inactive containers:", error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const cleanUpDockerBuilder = async (serverId?: string) => {
|
export const cleanUpDockerBuilder = async (serverId?: string) => {
|
||||||
if (serverId) {
|
if (serverId) {
|
||||||
await execAsyncRemote(serverId, "docker builder prune --all --force");
|
await execAsyncRemote(serverId, "docker builder prune --all --force");
|
||||||
} else {
|
} else {
|
||||||
await execAsync("docker builder prune --all --force");
|
await execAsync("docker builder prune --all --force");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const cleanUpSystemPrune = async (serverId?: string) => {
|
export const cleanUpSystemPrune = async (serverId?: string) => {
|
||||||
if (serverId) {
|
if (serverId) {
|
||||||
await execAsyncRemote(
|
await execAsyncRemote(
|
||||||
serverId,
|
serverId,
|
||||||
"docker system prune --all --force --volumes",
|
"docker system prune --all --force --volumes"
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
await execAsync("docker system prune --all --force --volumes");
|
await execAsync("docker system prune --all --force --volumes");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const startService = async (appName: string) => {
|
export const startService = async (appName: string) => {
|
||||||
try {
|
try {
|
||||||
await execAsync(`docker service scale ${appName}=1 `);
|
await execAsync(`docker service scale ${appName}=1 `);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const startServiceRemote = async (serverId: string, appName: string) => {
|
export const startServiceRemote = async (serverId: string, appName: string) => {
|
||||||
try {
|
try {
|
||||||
await execAsyncRemote(serverId, `docker service scale ${appName}=1 `);
|
await execAsyncRemote(serverId, `docker service scale ${appName}=1 `);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const removeService = async (
|
export const removeService = async (
|
||||||
appName: string,
|
appName: string,
|
||||||
serverId?: string | null,
|
serverId?: string | null,
|
||||||
|
deleteVolumes = false
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const command = `docker service rm ${appName}`;
|
let command: string;
|
||||||
if (serverId) {
|
|
||||||
await execAsyncRemote(serverId, command);
|
if (deleteVolumes) {
|
||||||
} else {
|
command = `docker service rm --force ${appName}`;
|
||||||
await execAsync(command);
|
} else {
|
||||||
}
|
command = `docker service rm ${appName}`;
|
||||||
} catch (error) {
|
}
|
||||||
return error;
|
|
||||||
}
|
if (serverId) {
|
||||||
|
await execAsyncRemote(serverId, command);
|
||||||
|
} else {
|
||||||
|
await execAsync(command);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const prepareEnvironmentVariables = (
|
export const prepareEnvironmentVariables = (
|
||||||
serviceEnv: string | null,
|
serviceEnv: string | null,
|
||||||
projectEnv?: string | null,
|
projectEnv?: string | null
|
||||||
) => {
|
) => {
|
||||||
const projectVars = parse(projectEnv ?? "");
|
const projectVars = parse(projectEnv ?? "");
|
||||||
const serviceVars = parse(serviceEnv ?? "");
|
const serviceVars = parse(serviceEnv ?? "");
|
||||||
|
|
||||||
const resolvedVars = Object.entries(serviceVars).map(([key, value]) => {
|
const resolvedVars = Object.entries(serviceVars).map(([key, value]) => {
|
||||||
let resolvedValue = value;
|
let resolvedValue = value;
|
||||||
if (projectVars) {
|
if (projectVars) {
|
||||||
resolvedValue = value.replace(/\$\{\{project\.(.*?)\}\}/g, (_, ref) => {
|
resolvedValue = value.replace(/\$\{\{project\.(.*?)\}\}/g, (_, ref) => {
|
||||||
if (projectVars[ref] !== undefined) {
|
if (projectVars[ref] !== undefined) {
|
||||||
return projectVars[ref];
|
return projectVars[ref];
|
||||||
}
|
}
|
||||||
throw new Error(`Invalid project environment variable: project.${ref}`);
|
throw new Error(`Invalid project environment variable: project.${ref}`);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return `${key}=${resolvedValue}`;
|
return `${key}=${resolvedValue}`;
|
||||||
});
|
});
|
||||||
|
|
||||||
return resolvedVars;
|
return resolvedVars;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const prepareBuildArgs = (input: string | null) => {
|
export const prepareBuildArgs = (input: string | null) => {
|
||||||
const pairs = (input ?? "").split("\n");
|
const pairs = (input ?? "").split("\n");
|
||||||
|
|
||||||
const jsonObject: Record<string, string> = {};
|
const jsonObject: Record<string, string> = {};
|
||||||
|
|
||||||
for (const pair of pairs) {
|
for (const pair of pairs) {
|
||||||
const [key, value] = pair.split("=");
|
const [key, value] = pair.split("=");
|
||||||
if (key && value) {
|
if (key && value) {
|
||||||
jsonObject[key] = value;
|
jsonObject[key] = value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return jsonObject;
|
return jsonObject;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const generateVolumeMounts = (mounts: ApplicationNested["mounts"]) => {
|
export const generateVolumeMounts = (mounts: ApplicationNested["mounts"]) => {
|
||||||
if (!mounts || mounts.length === 0) {
|
if (!mounts || mounts.length === 0) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
return mounts
|
return mounts
|
||||||
.filter((mount) => mount.type === "volume")
|
.filter((mount) => mount.type === "volume")
|
||||||
.map((mount) => ({
|
.map((mount) => ({
|
||||||
Type: "volume" as const,
|
Type: "volume" as const,
|
||||||
Source: mount.volumeName || "",
|
Source: mount.volumeName || "",
|
||||||
Target: mount.mountPath,
|
Target: mount.mountPath,
|
||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
|
|
||||||
type Resources = {
|
type Resources = {
|
||||||
memoryLimit: number | null;
|
memoryLimit: number | null;
|
||||||
memoryReservation: number | null;
|
memoryReservation: number | null;
|
||||||
cpuLimit: number | null;
|
cpuLimit: number | null;
|
||||||
cpuReservation: number | null;
|
cpuReservation: number | null;
|
||||||
};
|
};
|
||||||
export const calculateResources = ({
|
export const calculateResources = ({
|
||||||
memoryLimit,
|
memoryLimit,
|
||||||
memoryReservation,
|
memoryReservation,
|
||||||
cpuLimit,
|
cpuLimit,
|
||||||
cpuReservation,
|
cpuReservation,
|
||||||
}: Resources): ResourceRequirements => {
|
}: Resources): ResourceRequirements => {
|
||||||
return {
|
return {
|
||||||
Limits: {
|
Limits: {
|
||||||
MemoryBytes: memoryLimit ?? undefined,
|
MemoryBytes: memoryLimit ?? undefined,
|
||||||
NanoCPUs: cpuLimit ?? undefined,
|
NanoCPUs: cpuLimit ?? undefined,
|
||||||
},
|
},
|
||||||
Reservations: {
|
Reservations: {
|
||||||
MemoryBytes: memoryReservation ?? undefined,
|
MemoryBytes: memoryReservation ?? undefined,
|
||||||
NanoCPUs: cpuReservation ?? undefined,
|
NanoCPUs: cpuReservation ?? undefined,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export const generateConfigContainer = (application: ApplicationNested) => {
|
export const generateConfigContainer = (application: ApplicationNested) => {
|
||||||
const {
|
const {
|
||||||
healthCheckSwarm,
|
healthCheckSwarm,
|
||||||
restartPolicySwarm,
|
restartPolicySwarm,
|
||||||
placementSwarm,
|
placementSwarm,
|
||||||
updateConfigSwarm,
|
updateConfigSwarm,
|
||||||
rollbackConfigSwarm,
|
rollbackConfigSwarm,
|
||||||
modeSwarm,
|
modeSwarm,
|
||||||
labelsSwarm,
|
labelsSwarm,
|
||||||
replicas,
|
replicas,
|
||||||
mounts,
|
mounts,
|
||||||
networkSwarm,
|
networkSwarm,
|
||||||
} = application;
|
} = application;
|
||||||
|
|
||||||
const haveMounts = mounts.length > 0;
|
const haveMounts = mounts.length > 0;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...(healthCheckSwarm && {
|
...(healthCheckSwarm && {
|
||||||
HealthCheck: healthCheckSwarm,
|
HealthCheck: healthCheckSwarm,
|
||||||
}),
|
}),
|
||||||
...(restartPolicySwarm
|
...(restartPolicySwarm
|
||||||
? {
|
? {
|
||||||
RestartPolicy: restartPolicySwarm,
|
RestartPolicy: restartPolicySwarm,
|
||||||
}
|
}
|
||||||
: {}),
|
: {}),
|
||||||
...(placementSwarm
|
...(placementSwarm
|
||||||
? {
|
? {
|
||||||
Placement: placementSwarm,
|
Placement: placementSwarm,
|
||||||
}
|
}
|
||||||
: {
|
: {
|
||||||
// if app have mounts keep manager as constraint
|
// if app have mounts keep manager as constraint
|
||||||
Placement: {
|
Placement: {
|
||||||
Constraints: haveMounts ? ["node.role==manager"] : [],
|
Constraints: haveMounts ? ["node.role==manager"] : [],
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
...(labelsSwarm && {
|
...(labelsSwarm && {
|
||||||
Labels: labelsSwarm,
|
Labels: labelsSwarm,
|
||||||
}),
|
}),
|
||||||
...(modeSwarm
|
...(modeSwarm
|
||||||
? {
|
? {
|
||||||
Mode: modeSwarm,
|
Mode: modeSwarm,
|
||||||
}
|
}
|
||||||
: {
|
: {
|
||||||
// use replicas value if no modeSwarm provided
|
// use replicas value if no modeSwarm provided
|
||||||
Mode: {
|
Mode: {
|
||||||
Replicated: {
|
Replicated: {
|
||||||
Replicas: replicas,
|
Replicas: replicas,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
...(rollbackConfigSwarm && {
|
...(rollbackConfigSwarm && {
|
||||||
RollbackConfig: rollbackConfigSwarm,
|
RollbackConfig: rollbackConfigSwarm,
|
||||||
}),
|
}),
|
||||||
...(updateConfigSwarm
|
...(updateConfigSwarm
|
||||||
? { UpdateConfig: updateConfigSwarm }
|
? { UpdateConfig: updateConfigSwarm }
|
||||||
: {
|
: {
|
||||||
// default config if no updateConfigSwarm provided
|
// default config if no updateConfigSwarm provided
|
||||||
UpdateConfig: {
|
UpdateConfig: {
|
||||||
Parallelism: 1,
|
Parallelism: 1,
|
||||||
Order: "start-first",
|
Order: "start-first",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
...(networkSwarm
|
...(networkSwarm
|
||||||
? {
|
? {
|
||||||
Networks: networkSwarm,
|
Networks: networkSwarm,
|
||||||
}
|
}
|
||||||
: {
|
: {
|
||||||
Networks: [{ Target: "dokploy-network" }],
|
Networks: [{ Target: "dokploy-network" }],
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export const generateBindMounts = (mounts: ApplicationNested["mounts"]) => {
|
export const generateBindMounts = (mounts: ApplicationNested["mounts"]) => {
|
||||||
if (!mounts || mounts.length === 0) {
|
if (!mounts || mounts.length === 0) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
return mounts
|
return mounts
|
||||||
.filter((mount) => mount.type === "bind")
|
.filter((mount) => mount.type === "bind")
|
||||||
.map((mount) => ({
|
.map((mount) => ({
|
||||||
Type: "bind" as const,
|
Type: "bind" as const,
|
||||||
Source: mount.hostPath || "",
|
Source: mount.hostPath || "",
|
||||||
Target: mount.mountPath,
|
Target: mount.mountPath,
|
||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
|
|
||||||
export const generateFileMounts = (
|
export const generateFileMounts = (
|
||||||
appName: string,
|
appName: string,
|
||||||
service:
|
service:
|
||||||
| ApplicationNested
|
| ApplicationNested
|
||||||
| MongoNested
|
| MongoNested
|
||||||
| MariadbNested
|
| MariadbNested
|
||||||
| MysqlNested
|
| MysqlNested
|
||||||
| PostgresNested
|
| PostgresNested
|
||||||
| RedisNested,
|
| RedisNested
|
||||||
) => {
|
) => {
|
||||||
const { mounts } = service;
|
const { mounts } = service;
|
||||||
const { APPLICATIONS_PATH } = paths(!!service.serverId);
|
const { APPLICATIONS_PATH } = paths(!!service.serverId);
|
||||||
if (!mounts || mounts.length === 0) {
|
if (!mounts || mounts.length === 0) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
return mounts
|
return mounts
|
||||||
.filter((mount) => mount.type === "file")
|
.filter((mount) => mount.type === "file")
|
||||||
.map((mount) => {
|
.map((mount) => {
|
||||||
const fileName = mount.filePath;
|
const fileName = mount.filePath;
|
||||||
const absoluteBasePath = path.resolve(APPLICATIONS_PATH);
|
const absoluteBasePath = path.resolve(APPLICATIONS_PATH);
|
||||||
const directory = path.join(absoluteBasePath, appName, "files");
|
const directory = path.join(absoluteBasePath, appName, "files");
|
||||||
const sourcePath = path.join(directory, fileName || "");
|
const sourcePath = path.join(directory, fileName || "");
|
||||||
return {
|
return {
|
||||||
Type: "bind" as const,
|
Type: "bind" as const,
|
||||||
Source: sourcePath,
|
Source: sourcePath,
|
||||||
Target: mount.mountPath,
|
Target: mount.mountPath,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const createFile = async (
|
export const createFile = async (
|
||||||
outputPath: string,
|
outputPath: string,
|
||||||
filePath: string,
|
filePath: string,
|
||||||
content: string,
|
content: string
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const fullPath = path.join(outputPath, filePath);
|
const fullPath = path.join(outputPath, filePath);
|
||||||
if (fullPath.endsWith(path.sep) || filePath.endsWith("/")) {
|
if (fullPath.endsWith(path.sep) || filePath.endsWith("/")) {
|
||||||
fs.mkdirSync(fullPath, { recursive: true });
|
fs.mkdirSync(fullPath, { recursive: true });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const directory = path.dirname(fullPath);
|
const directory = path.dirname(fullPath);
|
||||||
fs.mkdirSync(directory, { recursive: true });
|
fs.mkdirSync(directory, { recursive: true });
|
||||||
fs.writeFileSync(fullPath, content || "");
|
fs.writeFileSync(fullPath, content || "");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
export const encodeBase64 = (content: string) =>
|
export const encodeBase64 = (content: string) =>
|
||||||
Buffer.from(content, "utf-8").toString("base64");
|
Buffer.from(content, "utf-8").toString("base64");
|
||||||
|
|
||||||
export const getCreateFileCommand = (
|
export const getCreateFileCommand = (
|
||||||
outputPath: string,
|
outputPath: string,
|
||||||
filePath: string,
|
filePath: string,
|
||||||
content: string,
|
content: string
|
||||||
) => {
|
) => {
|
||||||
const fullPath = path.join(outputPath, filePath);
|
const fullPath = path.join(outputPath, filePath);
|
||||||
if (fullPath.endsWith(path.sep) || filePath.endsWith("/")) {
|
if (fullPath.endsWith(path.sep) || filePath.endsWith("/")) {
|
||||||
return `mkdir -p ${fullPath};`;
|
return `mkdir -p ${fullPath};`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const directory = path.dirname(fullPath);
|
const directory = path.dirname(fullPath);
|
||||||
const encodedContent = encodeBase64(content);
|
const encodedContent = encodeBase64(content);
|
||||||
return `
|
return `
|
||||||
mkdir -p ${directory};
|
mkdir -p ${directory};
|
||||||
echo "${encodedContent}" | base64 -d > "${fullPath}";
|
echo "${encodedContent}" | base64 -d > "${fullPath}";
|
||||||
`;
|
`;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getServiceContainer = async (appName: string) => {
|
export const getServiceContainer = async (appName: string) => {
|
||||||
try {
|
try {
|
||||||
const filter = {
|
const filter = {
|
||||||
status: ["running"],
|
status: ["running"],
|
||||||
label: [`com.docker.swarm.service.name=${appName}`],
|
label: [`com.docker.swarm.service.name=${appName}`],
|
||||||
};
|
};
|
||||||
|
|
||||||
const containers = await docker.listContainers({
|
const containers = await docker.listContainers({
|
||||||
filters: JSON.stringify(filter),
|
filters: JSON.stringify(filter),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (containers.length === 0 || !containers[0]) {
|
if (containers.length === 0 || !containers[0]) {
|
||||||
throw new Error(`No container found with name: ${appName}`);
|
throw new Error(`No container found with name: ${appName}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const container = containers[0];
|
const container = containers[0];
|
||||||
|
|
||||||
return container;
|
return container;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getRemoteServiceContainer = async (
|
export const getRemoteServiceContainer = async (
|
||||||
serverId: string,
|
serverId: string,
|
||||||
appName: string,
|
appName: string
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const filter = {
|
const filter = {
|
||||||
status: ["running"],
|
status: ["running"],
|
||||||
label: [`com.docker.swarm.service.name=${appName}`],
|
label: [`com.docker.swarm.service.name=${appName}`],
|
||||||
};
|
};
|
||||||
const remoteDocker = await getRemoteDocker(serverId);
|
const remoteDocker = await getRemoteDocker(serverId);
|
||||||
const containers = await remoteDocker.listContainers({
|
const containers = await remoteDocker.listContainers({
|
||||||
filters: JSON.stringify(filter),
|
filters: JSON.stringify(filter),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (containers.length === 0 || !containers[0]) {
|
if (containers.length === 0 || !containers[0]) {
|
||||||
throw new Error(`No container found with name: ${appName}`);
|
throw new Error(`No container found with name: ${appName}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const container = containers[0];
|
const container = containers[0];
|
||||||
|
|
||||||
return container;
|
return container;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user