Просмотр исходного кода

Enabled clone for apps and jobs deployed from docker

jnfrati 4 лет назад
Родитель
Сommit
ff92ed1501

+ 29 - 0
dashboard/src/main/home/cluster-dashboard/expanded-chart/SettingsSection.tsx

@@ -15,6 +15,7 @@ import CopyToClipboard from "components/CopyToClipboard";
 import useAuth from "shared/auth/useAuth";
 import Loading from "components/Loading";
 import NotificationSettingsSection from "./NotificationSettingsSection";
+import { Link } from "react-router-dom";
 
 type PropsType = {
   currentChart: ChartType;
@@ -174,6 +175,21 @@ const SettingsSection: React.FC<PropsType> = ({
     }
   };
 
+  const getCloneUrl = () => {
+    const params = new URLSearchParams();
+    params.append("project_id", currentProject.id.toString());
+    params.append("shouldClone", "true");
+    params.append("release_namespace", currentChart.namespace);
+    params.append(
+      "release_template_version",
+      currentChart.chart.metadata.version
+    );
+    params.append("release_type", currentChart.chart.metadata.name);
+    params.append("release_name", currentChart.name);
+    params.append("release_version", currentChart.version.toString());
+    return `/launch?${params.toString()}`;
+  };
+
   const renderWebhookSection = () => {
     if (!currentChart?.form?.hasSource) {
       return;
@@ -264,6 +280,13 @@ const SettingsSection: React.FC<PropsType> = ({
     );
   };
 
+  const chartWasDeployedWithGithub = () => {
+    if (currentChart.git_action_config || currentChart.image_repo_uri) {
+      return true;
+    }
+    return false;
+  };
+
   return (
     <Wrapper>
       {!loadingWebhookToken ? (
@@ -271,6 +294,12 @@ const SettingsSection: React.FC<PropsType> = ({
           {renderWebhookSection()}
           <NotificationSettingsSection currentChart={currentChart} />
           <Heading>Additional Settings</Heading>
+          {/* Prevent the clone button to be rendered in github deployed charts */}
+          {!chartWasDeployedWithGithub() && (
+            <Button as={Link} to={getCloneUrl()}>
+              Clone
+            </Button>
+          )}
           <Button color="#b91133" onClick={() => setShowDeleteOverlay(true)}>
             Delete {currentChart.name}
           </Button>

+ 153 - 66
dashboard/src/main/home/launch/Launch.tsx

@@ -3,7 +3,11 @@ import styled from "styled-components";
 
 import { Context } from "shared/Context";
 import api from "shared/api";
-import { PorterTemplate } from "shared/types";
+import {
+  ChartTypeWithExtendedConfig,
+  PorterTemplate,
+  StorageType,
+} from "shared/types";
 
 import TabSelector from "components/TabSelector";
 import ExpandedTemplate from "./expanded-template/ExpandedTemplate";
@@ -14,13 +18,15 @@ import TitleSection from "components/TitleSection";
 
 import { hardcodedNames } from "shared/hardcodedNameDict";
 import semver from "semver";
+import { RouteComponentProps, withRouter } from "react-router";
+import { getQueryParam, getQueryParams } from "shared/routing";
 
 const tabOptions = [
   { label: "New Application", value: "porter" },
   { label: "Community Add-ons", value: "community" },
 ];
 
-type PropsType = {};
+type PropsType = RouteComponentProps & {};
 
 type StateType = {
   currentTemplate: PorterTemplate | null;
@@ -31,9 +37,10 @@ type StateType = {
   loading: boolean;
   error: boolean;
   isOnLaunchFlow: boolean;
+  clonedChart: ChartTypeWithExtendedConfig;
 };
 
-export default class Templates extends Component<PropsType, StateType> {
+class Templates extends Component<PropsType, StateType> {
   state = {
     currentTemplate: null as PorterTemplate | null,
     form: null as any,
@@ -43,84 +50,157 @@ export default class Templates extends Component<PropsType, StateType> {
     loading: true,
     error: false,
     isOnLaunchFlow: false,
+    clonedChart: null as ChartTypeWithExtendedConfig,
   };
 
-  componentDidMount() {
-    api
-      .getTemplates(
+  async componentDidMount() {
+    try {
+      const res = await api.getTemplates(
         "<token>",
         {
           repo_url: process.env.ADDON_CHART_REPO_URL,
         },
         {}
-      )
-      .then((res) => {
-        let sortedVersionData = res.data.map((template: any) => {
-          let versions = template.versions.reverse();
-
-          versions = template.versions.sort(semver.rcompare);
-
-          return {
-            ...template,
-            versions,
-            currentVersion: versions[0],
-          };
-        });
-
-        this.setState(
-          { addonTemplates: sortedVersionData, error: false },
-          () => {
-            this.state.addonTemplates.sort((a, b) =>
-              a.name > b.name ? 1 : -1
-            );
-
-            this.setState({
-              loading: false,
-            });
-          }
-        );
-      })
-      .catch(() => this.setState({ loading: false, error: true }));
-
-    api
-      .getTemplates(
+      );
+      let sortedVersionData = res.data.map((template: any) => {
+        let versions = template.versions.reverse();
+
+        versions = template.versions.sort(semver.rcompare);
+
+        return {
+          ...template,
+          versions,
+          currentVersion: versions[0],
+        };
+      });
+      sortedVersionData.sort((a: any, b: any) => (a.name > b.name ? 1 : -1));
+
+      this.setState({ addonTemplates: sortedVersionData, error: false });
+    } catch (error) {
+      this.setState({ loading: false, error: true });
+    }
+    try {
+      const res = await api.getTemplates(
         "<token>",
         {
           repo_url: process.env.APPLICATION_CHART_REPO_URL,
         },
         {}
-      )
-      .then((res) => {
-        let sortedVersionData = res.data.map((template: any) => {
-          let versions = template.versions.reverse();
-
-          versions = template.versions.sort(semver.rcompare);
-
-          return {
-            ...template,
-            versions,
-            currentVersion: versions[0],
-          };
-        });
-
-        this.setState(
-          { applicationTemplates: sortedVersionData, error: false },
-          () => {
-            let preferredOrder = ["web", "worker", "job"];
-            this.state.applicationTemplates.sort((a, b) => {
-              return (
-                preferredOrder.indexOf(a.name) - preferredOrder.indexOf(b.name)
-              );
-            });
-            this.setState({
-              loading: false,
-            });
-          }
+      );
+      let sortedVersionData = res.data.map((template: any) => {
+        let versions = template.versions.reverse();
+
+        versions = template.versions.sort(semver.rcompare);
+
+        return {
+          ...template,
+          versions,
+          currentVersion: versions[0],
+        };
+      });
+
+      let currentTemplate = null;
+      let isOnLaunchFlow = false;
+      let form = null;
+      let clonedChart = null;
+      if (this.isTryingToClone() && this.areCloneQueryParamsValid()) {
+        isOnLaunchFlow = true;
+        const template_name = getQueryParam(this.props, "release_type");
+        const version = getQueryParam(this.props, "release_template_version");
+        currentTemplate = sortedVersionData.find(
+          (v: any) => v.name === template_name
         );
-      })
-      .catch(() => this.setState({ loading: false, error: true }));
+
+        console.log(currentTemplate);
+        if (currentTemplate.versions.find((v: any) => v === version)) {
+          currentTemplate.currentVersion = version;
+        }
+        const release = await this.getClonedRelease().then((res) => res.data);
+        form = release.form;
+        clonedChart = release;
+        if (release.git_action_config || release.image_repo_uri) {
+          this.context.setCurrentError(
+            "Application/Jobs deployed with GitHub are not supported for cloning yet!"
+          );
+          this.props.history.push("/dashboard");
+          return;
+        }
+      }
+
+      this.setState(
+        {
+          applicationTemplates: sortedVersionData,
+          error: false,
+          currentTemplate,
+          isOnLaunchFlow,
+          form,
+          clonedChart,
+        },
+        () => {
+          let preferredOrder = ["web", "worker", "job"];
+          this.state.applicationTemplates.sort((a, b) => {
+            return (
+              preferredOrder.indexOf(a.name) - preferredOrder.indexOf(b.name)
+            );
+          });
+          this.setState({
+            loading: false,
+          });
+        }
+      );
+    } catch (error) {
+      this.setState({ loading: false, error: true });
+    }
   }
 
+  isTryingToClone = () => {
+    const queryParams = getQueryParams({ location });
+    return queryParams.has("shouldClone");
+  };
+
+  areCloneQueryParamsValid = () => {
+    const qp = getQueryParams(this.props);
+
+    const requiredParams = [
+      "release_namespace",
+      "release_template_version",
+      "release_name",
+      "release_version",
+      "release_type",
+    ];
+    // Check if we have all the params we need to make the request for the cloned app
+    // If the any param is missing then the some function will return true, so the validation
+    // went wrong.
+    return !requiredParams.some((rp) => !qp.has(rp));
+  };
+
+  getClonedRelease = () => {
+    const queryParams = getQueryParams(this.props);
+
+    if (!this.areCloneQueryParamsValid()) {
+      this.context.setCurrentError(
+        "Url has missing params to clone the app. Please try again."
+      );
+      this.props.history.push("/dashboard");
+      return;
+    }
+
+    return api.getChart<ChartTypeWithExtendedConfig>(
+      "<token>",
+      {
+        namespace: queryParams.get("release_namespace"),
+        cluster_id: this.context?.currentCluster?.id,
+        storage: StorageType.Secret,
+      },
+      {
+        id: this.context.currentProject.id,
+        name: queryParams.get("release_name"),
+        // This will get by default the last available version
+        revision: Number(queryParams.get("release_version")),
+      }
+    );
+  };
+
   renderIcon = (icon: string) => {
     if (icon) {
       return <Icon src={icon} />;
@@ -232,6 +312,9 @@ export default class Templates extends Component<PropsType, StateType> {
   };
 
   render() {
+    if (this.isTryingToClone() && this.state.loading) {
+      return <Loading />;
+    }
     if (!this.state.isOnLaunchFlow || !this.state.currentTemplate) {
       return (
         <TemplatesWrapper>
@@ -247,6 +330,8 @@ export default class Templates extends Component<PropsType, StateType> {
     } else {
       return (
         <LaunchFlow
+          isCloning={this.isTryingToClone()}
+          clonedChart={this.state.clonedChart}
           form={this.state.form}
           currentTab={this.state.currentTab}
           currentTemplate={this.state.currentTemplate}
@@ -259,6 +344,8 @@ export default class Templates extends Component<PropsType, StateType> {
 
 Templates.contextType = Context;
 
+export default withRouter(Templates);
+
 const Placeholder = styled.div`
   padding-top: 200px;
   width: 100%;

+ 2 - 2
dashboard/src/main/home/launch/expanded-template/ExpandedTemplate.tsx

@@ -119,10 +119,10 @@ export default class ExpandedTemplate extends Component<PropsType, StateType> {
 const FadeWrapper = styled.div`
   animation: fadeIn 0.2s;
   @keyframes fadeIn {
-    from: {
+    from {
       opacity: 0;
     }
-    to: {
+    to {
       opacity: 1;
     }
   }

+ 29 - 8
dashboard/src/main/home/launch/launch-flow/LaunchFlow.tsx

@@ -6,7 +6,7 @@ import { RouteComponentProps, withRouter } from "react-router";
 
 import api from "shared/api";
 import { Context } from "shared/Context";
-import { pushFiltered } from "shared/routing";
+import { getQueryParam, getQueryParams, pushFiltered } from "shared/routing";
 
 import { hardcodedNames } from "shared/hardcodedNameDict";
 import SourcePage from "./SourcePage";
@@ -16,6 +16,7 @@ import TitleSection from "components/TitleSection";
 
 import {
   ActionConfigType,
+  ChartTypeWithExtendedConfig,
   FullActionConfigType,
   PorterTemplate,
   StorageType,
@@ -26,6 +27,8 @@ type PropsType = RouteComponentProps & {
   currentTemplate: PorterTemplate;
   hideLaunchFlow: () => void;
   form: any;
+  isCloning: boolean;
+  clonedChart: ChartTypeWithExtendedConfig;
 };
 
 const defaultActionConfig: ActionConfigType = {
@@ -38,7 +41,9 @@ const defaultActionConfig: ActionConfigType = {
 const LaunchFlow: React.FC<PropsType> = (props) => {
   const context = useContext(Context);
 
-  const [currentPage, setCurrentPage] = useState("source");
+  const [currentPage, setCurrentPage] = useState(
+    props.isCloning ? "settings" : "source"
+  );
   const [templateName, setTemplateName] = useState("");
   const [saveValuesStatus, setSaveValuesStatus] = useState("");
   const [sourceType, setSourceType] = useState("");
@@ -159,8 +164,14 @@ const LaunchFlow: React.FC<PropsType> = (props) => {
       _.set(values, key, rawValues[key]);
     }
 
-    let url = imageUrl,
-      tag = imageTag;
+    let url = imageUrl;
+    let tag = imageTag;
+
+    if (props.isCloning) {
+      url = props.clonedChart.config.image.repository;
+      tag = props.clonedChart.config.image.tag;
+    }
+
     if (url.includes(":")) {
       let splits = url.split(":");
       url = splits[0];
@@ -242,7 +253,11 @@ const LaunchFlow: React.FC<PropsType> = (props) => {
 
     let githubActionConfig: FullActionConfigType = null;
     if (sourceType === "repo") {
-      githubActionConfig = getFullActionConfig();
+      if (props.isCloning) {
+        githubActionConfig = props.clonedChart?.git_action_config;
+      } else {
+        githubActionConfig = getFullActionConfig();
+      }
     }
 
     api
@@ -341,6 +356,7 @@ const LaunchFlow: React.FC<PropsType> = (props) => {
     // Display main (non-source) settings page
     return (
       <SettingsPage
+        isCloning={props.isCloning}
         onSubmit={currentTab === "porter" ? handleSubmit : handleSubmitAddon}
         saveValuesStatus={saveValuesStatus}
         selectedNamespace={selectedNamespace}
@@ -377,10 +393,14 @@ const LaunchFlow: React.FC<PropsType> = (props) => {
   }
 
   return (
-    <StyledLaunchFlow>
+    <StyledLaunchFlow disableMarginTop={props.isCloning}>
       <TitleSection handleNavBack={props.hideLaunchFlow}>
         {renderIcon()}
-        New {currentTemplateName} {currentTab === "porter" ? null : "Instance"}
+        {!props.isCloning
+          ? `New ${currentTemplateName} ${
+              currentTab === "porter" ? null : "Instance"
+            }`
+          : `Cloning ${currentTemplateName} deployment: ${props.clonedChart.name}`}
       </TitleSection>
       {renderCurrentPage()}
       <Br />
@@ -428,5 +448,6 @@ const Polymer = styled.div`
 const StyledLaunchFlow = styled.div`
   width: calc(90% - 130px);
   min-width: 300px;
-  margin-top: calc(50vh - 380px);
+  margin-top: ${(props: { disableMarginTop: boolean }) =>
+    props.disableMarginTop ? "inherit" : "calc(50vh - 380px)"};
 `;

+ 34 - 22
dashboard/src/main/home/launch/launch-flow/SettingsPage.tsx

@@ -30,6 +30,7 @@ type PropsType = WithAuthProps & {
   selectedNamespace: string;
   setSelectedNamespace: (x: string) => void;
   saveValuesStatus: string;
+  isCloning: boolean;
 };
 
 type StateType = {
@@ -182,28 +183,8 @@ class SettingsPage extends Component<PropsType, StateType> {
     }
   };
 
-  renderHeaderSection = () => {
-    let {
-      hasSource,
-      sourceType,
-      templateName,
-      setPage,
-      setTemplateName,
-    } = this.props;
-
-    if (hasSource) {
-      const [pageKey, pageName] =
-        sourceType === "repo"
-          ? ["workflow", "GitHub Actions"]
-          : ["source", "Source Settings"];
-
-      return (
-        <BackButton width="155px" onClick={() => setPage(pageKey)}>
-          <i className="material-icons">first_page</i>
-          {pageName}
-        </BackButton>
-      );
-    }
+  getNameInput = () => {
+    const { templateName, setTemplateName } = this.props;
 
     return (
       <>
@@ -229,6 +210,36 @@ class SettingsPage extends Component<PropsType, StateType> {
     );
   };
 
+  renderHeaderSection = () => {
+    let {
+      hasSource,
+      sourceType,
+      templateName,
+      setPage,
+      setTemplateName,
+    } = this.props;
+
+    if (this.props.isCloning) {
+      return null;
+    }
+
+    if (hasSource) {
+      const [pageKey, pageName] =
+        sourceType === "repo"
+          ? ["workflow", "GitHub Actions"]
+          : ["source", "Source Settings"];
+
+      return (
+        <BackButton width="155px" onClick={() => setPage(pageKey)}>
+          <i className="material-icons">first_page</i>
+          {pageName}
+        </BackButton>
+      );
+    }
+
+    return this.getNameInput();
+  };
+
   render() {
     let { selectedCluster } = this.state;
 
@@ -238,6 +249,7 @@ class SettingsPage extends Component<PropsType, StateType> {
       <PaddingWrapper>
         <StyledSettingsPage>
           {this.renderHeaderSection()}
+          {this.props.isCloning && this.getNameInput()}
           <Heading>Destination</Heading>
           <Helper>
             Specify the cluster and namespace you would like to deploy your