Skip to content

Commit

Permalink
Merge branch 'master' into stacks-v2-filter-predeploy-logs
Browse files Browse the repository at this point in the history
  • Loading branch information
Feroze Mohideen authored Sep 19, 2023
2 parents 2a69af1 + 8282c88 commit 38e0abc
Show file tree
Hide file tree
Showing 5 changed files with 115 additions and 68 deletions.
41 changes: 31 additions & 10 deletions api/server/handlers/porter_app/create_secret_and_open_pr.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/porter-dev/porter/internal/auth/token"
"github.com/porter-dev/porter/internal/integrations/ci/actions"
"github.com/porter-dev/porter/internal/models"
"github.com/porter-dev/porter/internal/telemetry"
)

type OpenStackPRHandler struct {
Expand All @@ -34,9 +35,12 @@ func NewOpenStackPRHandler(
}

func (c *OpenStackPRHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
user, _ := r.Context().Value(types.UserScope).(*models.User)
project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
ctx, span := telemetry.NewSpan(r.Context(), "serve-open-stack-pr")
defer span.End()

user, _ := ctx.Value(types.UserScope).(*models.User)
project, _ := ctx.Value(types.ProjectScope).(*models.Project)
cluster, _ := ctx.Value(types.ClusterScope).(*models.Cluster)
appName, reqErr := requestutils.GetURLParamString(r, types.URLParamPorterAppName)
if reqErr != nil {
c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(reqErr, http.StatusBadRequest))
Expand All @@ -45,11 +49,14 @@ func (c *OpenStackPRHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

request := &types.CreateSecretAndOpenGHPRRequest{}
if ok := c.DecodeAndValidate(w, r, request); !ok {
err := telemetry.Error(ctx, span, nil, "error decoding request")
c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
return
}

client, err := getGithubClient(c.Config(), request.GithubAppInstallationID)
if err != nil {
err := telemetry.Error(ctx, span, err, "error creating github client")
c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
return
}
Expand All @@ -59,12 +66,16 @@ func (c *OpenStackPRHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// generate porter jwt token
jwt, err := token.GetTokenForAPI(user.ID, project.ID)
if err != nil {
c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error getting token for API: %w", err)))
err = fmt.Errorf("error getting token for API: %w", err)
err := telemetry.Error(ctx, span, err, err.Error())
c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
return
}
encoded, err := jwt.EncodeToken(c.Config().TokenConf)
if err != nil {
c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error encoding API token: %w", err)))
err = fmt.Errorf("error encoding API token: %w", err)
err := telemetry.Error(ctx, span, err, err.Error())
c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
return
}

Expand All @@ -78,7 +89,9 @@ func (c *OpenStackPRHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
request.GithubRepoName,
)
if err != nil {
c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error generating secret: %w", err)))
err = fmt.Errorf("error generating secret: %w", err)
err := telemetry.Error(ctx, span, err, err.Error())
c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
return
}
}
Expand Down Expand Up @@ -113,12 +126,16 @@ func (c *OpenStackPRHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if unwrappedErr != nil {
if errors.Is(unwrappedErr, actions.ErrProtectedBranch) {
c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
return
} else if errors.Is(unwrappedErr, actions.ErrCreatePRForProtectedBranch) {
c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusPreconditionFailed))
return
}
} else {
c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error setting up application in the github "+
"repo: %w", err)))
err = fmt.Errorf("error setting up application in the github "+
"repo: %w", err)
err := telemetry.Error(ctx, span, err, err.Error())
c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
return
}
}
Expand All @@ -133,15 +150,19 @@ func (c *OpenStackPRHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// update DB with the PR url
porterApp, err := c.Repo().PorterApp().ReadPorterAppByName(cluster.ID, appName)
if err != nil {
c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("unable to get porter app db: %w", err)))
err = fmt.Errorf("unable to get porter app db: %w", err)
err := telemetry.Error(ctx, span, err, err.Error())
c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
return
}

porterApp.PullRequestURL = pr.GetHTMLURL()

_, err = c.Repo().PorterApp().UpdatePorterApp(porterApp)
if err != nil {
c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("unable to write pr url to porter app db: %w", err)))
err = fmt.Errorf("unable to write pr url to porter app db: %w", err)
err := telemetry.Error(ctx, span, err, err.Error())
c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
return
}
}
Expand Down
15 changes: 11 additions & 4 deletions dashboard/src/components/PreflightChecks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import Loading from "./Loading";
type Props = RouteComponentProps & {
preflightData: any
provider: 'AWS' | 'GCP' | 'DEFAULT';
error?: string;

};

Expand Down Expand Up @@ -97,10 +98,16 @@ const PreflightChecks: React.FC<Props> = (props) => {
Porter checks that the account has the right permissions and resources to provision a cluster.
</Text>
<Spacer y={1} />
{Object.keys(currentMessageConst).map((checkKey) => (
<PreflightCheckItem key={checkKey} checkKey={checkKey} />
))}
</AppearingDiv>
{
props.error ?
<Error message="Selected region is not available for your account. Please select another region" />
:
Object.keys(currentMessageConst).map((checkKey) => (
<PreflightCheckItem key={checkKey} checkKey={checkKey} />
))

}
</AppearingDiv >
);
};

Expand Down
83 changes: 46 additions & 37 deletions dashboard/src/components/ProvisionerSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ const ProvisionerSettings: React.FC<Props> = (props) => {
const [isLoading, setIsLoading] = useState(false);
const [preflightData, setPreflightData] = useState(null)
const [preflightFailed, setPreflightFailed] = useState<boolean>(true)
const [preflightError, setPreflightError] = useState<string>("")

const markStepStarted = async (step: string, errMessage?: string) => {
try {
Expand Down Expand Up @@ -480,52 +481,60 @@ const ProvisionerSettings: React.FC<Props> = (props) => {
useEffect(() => {
if (!props.clusterId) {
setStep(1)
setPreflightData(null)
preflightChecks()
}
}, [props.selectedClusterVersion, awsRegion]);


const preflightChecks = async () => {
setIsLoading(true);
setPreflightData(null);

var data = new PreflightCheckRequest({
projectId: BigInt(currentProject.id),
cloudProvider: EnumCloudProvider.AWS,
cloudProviderCredentialsId: props.credentialId,
preflightValues: {
case: "eksPreflightValues",
value: new EKSPreflightValues({
region: awsRegion,
})
try {
setIsLoading(true);
setPreflightData(null);
setPreflightFailed(true)
setPreflightError("");

var data = new PreflightCheckRequest({
projectId: BigInt(currentProject.id),
cloudProvider: EnumCloudProvider.AWS,
cloudProviderCredentialsId: props.credentialId,
preflightValues: {
case: "eksPreflightValues",
value: new EKSPreflightValues({
region: awsRegion,
})
}
});
const preflightDataResp = await api.preflightCheck(
"<token>", data,
{
id: currentProject.id,
}
)
// Check if any of the preflight checks has a message
let hasMessage = false;
let errors = "Preflight Checks Failed : ";
for (let check in preflightDataResp?.data?.Msg.preflight_checks) {
if (preflightDataResp?.data?.Msg.preflight_checks[check]?.message) {
hasMessage = true;
errors = errors + check + ", "
}
}
});
const preflightDataResp = await api.preflightCheck(
"<token>", data,
{
id: currentProject.id,
// If none of the checks have a message, set setPreflightFailed to false
if (hasMessage) {
markStepStarted("provisioning-failed", errors);
}
)
// Check if any of the preflight checks has a message
let hasMessage = false;
let errors = "Preflight Checks Failed : ";
for (let check in preflightDataResp?.data?.Msg.preflight_checks) {
if (preflightDataResp?.data?.Msg.preflight_checks[check]?.message) {
hasMessage = true;
errors = errors + check + ", "
if (!hasMessage) {
setPreflightFailed(false);
setStep(2);
}
setPreflightData(preflightDataResp?.data?.Msg);
setIsLoading(false)
} catch (err) {
setPreflightError(err)
setIsLoading(false)
setPreflightFailed(true);
}
// If none of the checks have a message, set setPreflightFailed to false
if (hasMessage) {
markStepStarted("provisioning-failed", errors);
}
if (!hasMessage) {
setPreflightFailed(false);
setStep(2);
}
setPreflightData(preflightDataResp?.data?.Msg);
setIsLoading(false)

}
const renderAdvancedSettings = () => {
Expand Down Expand Up @@ -984,7 +993,7 @@ const ProvisionerSettings: React.FC<Props> = (props) => {
</Text><Spacer height="10px" /><SelectRow
options={regionOptions}
width="350px"
disabled={isReadOnly}
disabled={isReadOnly || isLoading}
value={awsRegion}
scrollBuffer={true}
dropdownMaxHeight="240px"
Expand All @@ -997,7 +1006,7 @@ const ProvisionerSettings: React.FC<Props> = (props) => {
</>
</>,
<>
<PreflightChecks provider='AWS' preflightData={preflightData} />
<PreflightChecks provider='AWS' preflightData={preflightData} error={preflightError} />
<Spacer y={.5} />
{(preflightFailed && preflightData) &&
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ const ClusterSettings: React.FC<Props> = (props) => {
</Helper>
);

if (!currentCluster?.infra_id || !currentCluster?.service) {
if (!currentCluster?.infra_id && !currentProject?.capi_provisioner_enabled || !currentCluster?.service) {
helperText = (
<Helper>
Remove this cluster from Porter. Since this cluster was not provisioned
Expand Down
42 changes: 26 additions & 16 deletions dashboard/src/main/home/modals/UpdateClusterModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class UpdateClusterModal extends Component<PropsType, StateType> {
cluster_id: currentCluster.id,
}
)
.then((_) => {
.then(async (_) => {
if (!currentCluster?.infra_id) {
// TODO: make this more declarative from the Home component
this.props.setRefreshClusters(true);
Expand All @@ -61,24 +61,34 @@ class UpdateClusterModal extends Component<PropsType, StateType> {
pushFiltered(this.props, "/dashboard", ["project_id"], {
tab: "overview",
});


// Handle destroying infra we've provisioned
api
.destroyInfra(
"<token>",
{},
{
project_id: currentProject.id,
infra_id: currentCluster.infra_id,
}
)
.then(() =>
console.log("destroyed provisioned infra:", currentCluster.infra_id)
)
.catch(console.log);

if (currentProject.simplified_view_enabled) {
await api.saveOnboardingState(
"<token>",
{ current_step: "connect_source" },
{ project_id: currentProject.id }
);
window.location.reload();
}
return;
}

// Handle destroying infra we've provisioned
api
.destroyInfra(
"<token>",
{},
{
project_id: currentProject.id,
infra_id: currentCluster.infra_id,
}
)
.then(() =>
console.log("destroyed provisioned infra:", currentCluster.infra_id)
)
.catch(console.log);

this.props.setRefreshClusters(true);
this.setState({ status: "successful", showDeleteOverlay: false });
this.context.setCurrentModal(null, null);
Expand Down

0 comments on commit 38e0abc

Please sign in to comment.