Skip to content

Commit

Permalink
feat: cronjob sts && template readme (#5324)
Browse files Browse the repository at this point in the history
* feat: cronjob sts

* fix readme cors

* img no-referrer
  • Loading branch information
zjy365 authored Jan 6, 2025
1 parent 5dcd1f9 commit b6f13c0
Show file tree
Hide file tree
Showing 11 changed files with 62 additions and 61 deletions.
4 changes: 2 additions & 2 deletions frontend/providers/cronjob/src/api/app.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { GET } from '@/services/request';
import { AppListItemType } from '@/types/app';
import { adaptAppListItem, adaptServiceAccountList } from '@/utils/adapt';
import { V1Deployment, V1ServiceAccount } from '@kubernetes/client-node';

export const getMyApps = () =>
GET<V1Deployment[]>('/api/launchpad/getApps').then((res) => res.map(adaptAppListItem));
export const getMyApps = () => GET<AppListItemType[]>('/api/launchpad/getApps');

export const getMyServiceAccount = () =>
GET<V1ServiceAccount[]>('/api/launchpad/getServiceAccount').then((res) =>
Expand Down
1 change: 1 addition & 0 deletions frontend/providers/cronjob/src/constants/job.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ export const DefaultJobEditValue: CronJobEditType = {
launchpadName: '',
launchpadId: '',
serviceAccountName: '',
launchpadKind: 'Deployment',
status: CronJobStatusMap['Running'],
isPause: false,
creatTime: '',
Expand Down
11 changes: 9 additions & 2 deletions frontend/providers/cronjob/src/pages/api/launchpad/getApps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ApiResp } from '@/services/kubernet';
import { authSession } from '@/services/backend/auth';
import { getK8s } from '@/services/backend/kubernetes';
import { jsonRes } from '@/services/backend/response';
import { adaptAppListItem } from '@/utils/adapt';

export const appDeployKey = 'cloud.sealos.io/app-deploy-manager';

Expand Down Expand Up @@ -33,11 +34,17 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse<

const apps = response
.filter((item) => item.status === 'fulfilled')
.map((item: any) => item?.value?.body?.items)
.map((item: any, index) => {
const items = item?.value?.body?.items || [];
return items.map((app: any) => ({
...app,
kind: index === 0 ? 'Deployment' : 'StatefulSet'
}));
})
.filter((item) => item)
.flat();

jsonRes(res, { data: apps });
jsonRes(res, { data: apps.map(adaptAppListItem) });
} catch (err: any) {
jsonRes(res, {
code: 500,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ export default function AppBaseInfo({
? '#33BABB'
: jobItem.status === 'failed'
? '#FF8492'
: jobItem.status === 'active'
? '#33BABB'
: '#FF8492'
}}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,7 @@ const Form = ({ formHook }: { formHook: UseFormReturn<CronJobEditType, any> }) =
setValue('replicas', launchpad.replicas);
setValue('cpu', launchpad.cpu);
setValue('memory', launchpad.memory);
setValue('launchpadKind', launchpad.kind);
}}
/>
)}
Expand Down
1 change: 1 addition & 0 deletions frontend/providers/cronjob/src/types/app.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ export interface AppListItemType {
cpu: number;
memory: number;
replicas: number;
kind: string;
}
2 changes: 2 additions & 0 deletions frontend/providers/cronjob/src/types/job.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export type CronJobEditType = {
launchpadName: string;
launchpadId: string;
serviceAccountName: string;
launchpadKind: string;
} & CronJobDetailType;

export type CronJobDetailType = {
Expand Down Expand Up @@ -115,4 +116,5 @@ export type CronJobAnnotations = {
launchpadName: string;
launchpadId: string;
replicas: string;
launchpadKind: string;
};
21 changes: 16 additions & 5 deletions frontend/providers/cronjob/src/utils/adapt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import {
V1Deployment,
V1Job,
V1Pod,
V1ServiceAccount
V1ServiceAccount,
V1StatefulSet
} from '@kubernetes/client-node';
import dayjs from 'dayjs';
import cronstrue from 'cronstrue';
Expand Down Expand Up @@ -56,8 +57,16 @@ export const adaptCronJobDetail = async (job: V1CronJob): Promise<CronJobEditTyp
.next()
.toString();
const status_str = job.spec?.suspend ? StatusEnum.Stopped : StatusEnum.Running;
const { cpu, enableNumberCopies, enableResources, launchpadId, launchpadName, memory, replicas } =
job.metadata?.annotations as CronJobAnnotations;
const {
cpu,
enableNumberCopies,
enableResources,
launchpadId,
launchpadName,
memory,
replicas,
launchpadKind
} = job.metadata?.annotations as CronJobAnnotations;

const getUrl = (): string => {
const commands = job.spec?.jobTemplate?.spec?.template?.spec?.containers?.[0]?.args;
Expand Down Expand Up @@ -101,6 +110,7 @@ export const adaptCronJobDetail = async (job: V1CronJob): Promise<CronJobEditTyp
memory: memoryFormatToMi(memory || '0'),
launchpadName: launchpadName || '',
launchpadId: launchpadId || '',
launchpadKind: launchpadKind || '',
serviceAccountName: 'userns',
// detail page
status: CronJobStatusMap[status_str]
Expand Down Expand Up @@ -130,7 +140,7 @@ export const sliderNumber2MarkList = ({
}));
};

export const adaptAppListItem = (app: V1Deployment): AppListItemType => {
export const adaptAppListItem = (app: V1Deployment | V1StatefulSet): AppListItemType => {
return {
id: app.metadata?.uid || ``,
name: app.metadata?.name || 'app name',
Expand All @@ -140,7 +150,8 @@ export const adaptAppListItem = (app: V1Deployment): AppListItemType => {
memory: memoryFormatToMi(
app.spec?.template?.spec?.containers?.[0]?.resources?.limits?.memory || '0'
),
replicas: app.spec?.replicas || 0
replicas: app.spec?.replicas || 0,
kind: app.kind || ''
};
};

Expand Down
5 changes: 3 additions & 2 deletions frontend/providers/cronjob/src/utils/json2Yaml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export const json2CronJob = (data: CronJobEditType) => {
command += ` && curl -k -X POST -H "Authorization: $(cat ~/.kube/config | jq -sRr @uri)" -d "appName=${data.launchpadName}&replica=${data.replicas}" https://${applaunchpadUrl}/api/v1alpha/updateReplica`;
}
if (data.enableResources) {
command += ` && kubectl set resources deployment ${data.launchpadName} --limits=cpu=${resources.limits.cpu},memory=${resources.limits.memory} --requests=cpu=${resources.requests.cpu},memory=${resources.requests.memory}`;
command += ` && kubectl set resources ${data.launchpadKind} ${data.launchpadName} --limits=cpu=${resources.limits.cpu},memory=${resources.limits.memory} --requests=cpu=${resources.requests.cpu},memory=${resources.requests.memory}`;
}

return command.replace(/\n/g, '') || '';
Expand All @@ -70,7 +70,8 @@ export const json2CronJob = (data: CronJobEditType) => {
memory: `${str2Num(data.memory)}Mi`,
launchpadName: data.launchpadName,
launchpadId: data.launchpadId,
replicas: `${data.replicas}`
replicas: `${data.replicas}`,
launchpadKind: data.launchpadKind
};
}

Expand Down
51 changes: 6 additions & 45 deletions frontend/providers/template/src/pages/deploy/components/ReadMe.tsx
Original file line number Diff line number Diff line change
@@ -1,60 +1,21 @@
import MyIcon from '@/components/Icon';
import { TemplateType } from '@/types/app';
import { Box } from '@chakra-ui/react';
import 'github-markdown-css/github-markdown-light.css';
import { useEffect, useMemo, useState } from 'react';
import ReactMarkdown from 'react-markdown';
import rehypeRaw from 'rehype-raw';
import rehypeRewrite from 'rehype-rewrite';
import remarkGfm from 'remark-gfm';
import remarkUnwrapImages from 'remark-unwrap-images';
import rehypeRewrite from 'rehype-rewrite';
import styles from './index.module.scss';
import { parseGithubUrl } from '@/utils/tools';
import { Octokit, App } from 'octokit';
import { useTranslation } from 'next-i18next';

const ReadMe = ({ templateDetail }: { templateDetail: TemplateType }) => {
const { i18n } = useTranslation();
const [templateReadMe, setTemplateReadMe] = useState('');

const readme =
templateDetail?.spec?.i18n?.[i18n.language]?.readme ?? templateDetail?.spec?.readme;

// const octokit = new Octokit({
// auth: ''
// });
// useEffect(() => {
// (async () => {
// const result = await octokit.request('GET /repos/{owner}/{repo}/readme', {
// owner: 'appsmithorg',
// repo: 'appsmith',
// headers: {}
// });
// console.log(result);
// })();
// }, []);

const githubOptions = useMemo(() => parseGithubUrl(readme), [readme]);

useEffect(() => {
if (readme) {
(async () => {
try {
const res = await (await fetch(readme)).text();
setTemplateReadMe(res);
} catch (error) {
console.log(error);
}
})();
}
}, [readme]);

const ReadMe = ({ readUrl, readmeContent }: { readUrl: string; readmeContent: string }) => {
// @ts-ignore
const myRewrite = (node, index, parent) => {
if (node.tagName === 'img' && !node.properties.src.startsWith('http')) {
const imgSrc = node.properties.src.replace(/^\.\/|^\//, '');

node.properties.src = `https://${githubOptions?.hostname}/${githubOptions?.organization}/${githubOptions?.repository}/${githubOptions?.branch}/${imgSrc}`;
const baseUrl = readUrl?.substring(0, readUrl?.lastIndexOf('/') + 1);
node.properties.referrerPolicy = 'no-referrer';
node.properties.src = `${baseUrl}${imgSrc}`;
}
};

Expand All @@ -76,7 +37,7 @@ const ReadMe = ({ templateDetail }: { templateDetail: TemplateType }) => {
rehypePlugins={[rehypeRaw, [rehypeRewrite, { rewrite: myRewrite }]]}
remarkPlugins={[remarkGfm, remarkUnwrapImages]}
>
{templateReadMe}
{readmeContent}
</ReactMarkdown>
</Box>
</Box>
Expand Down
24 changes: 19 additions & 5 deletions frontend/providers/template/src/pages/deploy/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ const Header = dynamic(() => import('./components/Header'), { ssr: false });
export default function EditApp({
appName,
metaData,
brandName
brandName,
readmeContent,
readUrl
}: {
appName?: string;
metaData: {
Expand All @@ -42,6 +44,8 @@ export default function EditApp({
description: string;
};
brandName?: string;
readmeContent: string;
readUrl: string;
}) {
const { t, i18n } = useTranslation();
const { message: toast } = useMessage();
Expand Down Expand Up @@ -387,7 +391,7 @@ export default function EditApp({
platformEnvs={platformEnvs!}
/>
{/* <Yaml yamlList={yamlList} pxVal={pxVal}></Yaml> */}
<ReadMe templateDetail={data?.templateYaml!} />
<ReadMe key={readUrl} readUrl={readUrl} readmeContent={readmeContent} />
</Flex>
</Flex>
</Flex>
Expand Down Expand Up @@ -421,23 +425,33 @@ export async function getServerSideProps(content: any) {
keywords: '',
description: ''
};
let readmeContent = '';
let readUrl = '';

try {
const templateSource: { data: TemplateSourceType } = await (
await fetch(`${baseurl}/api/getTemplateSource?templateName=${appName}`)
).json();
const templateDetail = templateSource?.data.templateYaml;

metaData = {
title: templateSource?.data.templateYaml.spec.title,
keywords: templateSource?.data.templateYaml.spec.description,
description: templateSource?.data.templateYaml.spec.description
title: templateDetail?.spec?.title,
keywords: templateDetail?.spec?.description,
description: templateDetail?.spec?.description
};

const readme = templateDetail?.spec?.i18n?.[local]?.readme ?? templateDetail?.spec?.readme;
readUrl = readme;
readmeContent = await (await fetch(readme)).text();
} catch (error) {}

return {
props: {
appName,
metaData,
brandName,
readmeContent,
readUrl,
...(await serviceSideProps(content))
}
};
Expand Down

0 comments on commit b6f13c0

Please sign in to comment.