Skip to content

Commit

Permalink
[rebuild] fix 16535: auto manage windows
Browse files Browse the repository at this point in the history
  • Loading branch information
akosyakov committed Feb 24, 2023
1 parent bffd32c commit 010e3f0
Show file tree
Hide file tree
Showing 12 changed files with 503 additions and 246 deletions.
37 changes: 18 additions & 19 deletions components/gitpod-cli/cmd/rebuild.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,9 @@ func runRebuild(ctx context.Context, supervisorClient *supervisor.SupervisorClie
for _, env := range debugEnvs.Envs {
envs += env + "\n"
}
for _, env := range rebuildOpts.GitpodEnvs {
envs += env + "\n"
}
for _, env := range workspaceEnvs {
envs += fmt.Sprintf("%s=%s\n", env.Name, env.Value)
}
Expand Down Expand Up @@ -303,9 +306,9 @@ Connect using SSH keys (https://gitpod.io/keys):
%s
%s`, sep, workspaceUrl, ssh, sep)
err := notify(ctx, supervisorClient, workspaceUrl.String(), "The workspace is UP.")
err := openWindow(ctx, workspaceUrl.String())
if err != nil && ctx.Err() == nil {
log.WithError(err).Error("failed to notify")
log.WithError(err).Error("failed to open window")
}
}()

Expand Down Expand Up @@ -405,33 +408,25 @@ func setLoggerFormatter(logger *logrus.Logger) {
})
}

func notify(ctx context.Context, supervisorClient *supervisor.SupervisorClient, workspaceUrl, message string) error {
response, err := supervisorClient.Notification.Notify(ctx, &api.NotifyRequest{
Level: api.NotifyRequest_INFO,
Message: message,
Actions: []string{"Open"},
})
func openWindow(ctx context.Context, workspaceUrl string) error {
gpPath, err := exec.LookPath("gp")
if err != nil {
return err
}
if response.Action == "Open" {
gpPath, err := exec.LookPath("gp")
if err != nil {
return err
}
gpCmd := exec.CommandContext(ctx, gpPath, "preview", "--external", workspaceUrl)
gpCmd.Stdout = os.Stdout
gpCmd.Stderr = os.Stderr
return gpCmd.Run()
}
return nil
gpCmd := exec.CommandContext(ctx, gpPath, "preview", "--external", workspaceUrl)
gpCmd.Stdout = os.Stdout
gpCmd.Stderr = os.Stderr
return gpCmd.Run()
}

var rebuildOpts struct {
WorkspaceFolder string
LogLevel string
From string
Prebuild bool

// internal
GitpodEnvs []string
}

var rebuildCmd = &cobra.Command{
Expand Down Expand Up @@ -467,4 +462,8 @@ func init() {
rebuildCmd.PersistentFlags().StringVarP(&rebuildOpts.LogLevel, "log", "", "error", "Log level to use. Allowed values are 'error', 'warn', 'info', 'debug', 'trace'.")
rebuildCmd.PersistentFlags().StringVarP(&rebuildOpts.From, "from", "", "", "Starts from 'prebuild' or 'snapshot'.")
rebuildCmd.PersistentFlags().BoolVarP(&rebuildOpts.Prebuild, "prebuild", "", false, "starts as a prebuild workspace (--from is ignored).")

// internal
rebuildCmd.PersistentFlags().StringArrayVarP(&rebuildOpts.GitpodEnvs, "gitpod-env", "", nil, "")
rebuildCmd.PersistentFlags().MarkHidden("gitpod-env")
}
18 changes: 18 additions & 0 deletions components/gitpod-cli/rebuild.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#!/bin/bash
# Copyright (c) 2023 Gitpod GmbH. All rights reserved.
# Licensed under the GNU Affero General Public License (AGPL).
# See License.AGPL.txt in the project root for license information.

set -Eeuo pipefail

DIR="$(dirname "$(realpath "$0")")"
COMPONENT="$(basename "$DIR")"
cd "$DIR"

# build
go build .
echo "$COMPONENT built"

sudo rm -rf "/.supervisor/$COMPONENT" && true
sudo mv ./"$COMPONENT" /.supervisor
echo "$COMPONENT in /.supervisor replaced"
462 changes: 239 additions & 223 deletions components/supervisor-api/go/status.pb.go

Large diffs are not rendered by default.

121 changes: 121 additions & 0 deletions components/supervisor-api/go/status.pb.gw.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 7 additions & 1 deletion components/supervisor-api/status.proto
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ service StatusService {
rpc SupervisorStatus(SupervisorStatusRequest) returns (SupervisorStatusResponse) {
option (google.api.http) = {
get: "/v1/status/supervisor"
additional_bindings {
get: "/v1/status/supervisor/willShutdown/{willShutdown=true}",
}
};
}

Expand Down Expand Up @@ -81,7 +84,10 @@ service StatusService {

}

message SupervisorStatusRequest {}
message SupervisorStatusRequest {
// if true this request will return either when it times out or when the supervisor is about to shutdown.
bool willShutdown = 1;
}
message SupervisorStatusResponse {
bool ok = 1;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
ContentStatusResponse,
} from "@gitpod/supervisor-api-grpc/lib/status_pb";
import { WorkspaceInfoResponse } from "@gitpod/supervisor-api-grpc/lib/info_pb";

import { GitpodHostUrl } from "@gitpod/gitpod-protocol/lib/util/gitpod-host-url";

export class SupervisorServiceClient {
Expand All @@ -26,10 +25,46 @@ export class SupervisorServiceClient {
readonly ideReady = this.supervisorReady.then(() => this.checkReady("ide"));
readonly contentReady = Promise.all([this.supervisorReady]).then(() => this.checkReady("content"));
readonly getWorkspaceInfoPromise = this.supervisorReady.then(() => this.getWorkspaceInfo());
readonly supervisorWillShutdown = this.supervisorReady.then(() => this.checkWillShutdown());

private constructor() {}

private async checkReady(kind: "content" | "ide" | "supervisor", delay?: boolean): Promise<any> {
private async checkWillShutdown(delay = false): Promise<void> {
if (delay) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
try {
const wsSupervisorStatusUrl = GitpodHostUrl.fromWorkspaceUrl(window.location.href).with((url) => {
return {
pathname: "/_supervisor/v1/status/supervisor/willShutdown/true",
};
});
const response = await fetch(wsSupervisorStatusUrl.toString(), { credentials: "include" });
let result;
if (response.ok) {
result = await response.json();
if ((result as SupervisorStatusResponse.AsObject).ok) {
return;
}
}
if (response.status === 502) {
// bad gateway, supervisor is gone
return
}
console.debug(
`failed to check whether is about to shutdown, trying again...`,
response.status,
response.statusText,
JSON.stringify(result, undefined, 2),
);
} catch (e) {
// network errors
console.debug(`failed to check whether is about to shutdown, trying again...`, e);
}
await this.checkWillShutdown(true);
}

private async checkReady(kind: "content" | "ide" | "supervisor" , delay?: boolean): Promise<any> {
if (delay) {
await new Promise((resolve) => setTimeout(resolve, 1000));
}
Expand Down
10 changes: 10 additions & 0 deletions components/supervisor/frontend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import * as IDEWorker from "./ide/ide-worker";
import * as IDEWebSocket from "./ide/ide-web-socket";
import { SupervisorServiceClient } from "./ide/supervisor-service-client";
import * as LoadingFrame from "./shared/loading-frame";
import { workspaceUrl } from "./shared/urls";

window.gitpod = {} as any;
IDEWorker.install();
Expand Down Expand Up @@ -248,11 +249,15 @@ LoadingFrame.load().then(async (loading) => {
})();

(async () => {
const debugWorkspace = workspaceUrl.debugWorkspace;
//#region ide lifecycle
function isWorkspaceInstancePhase(phase: WorkspaceInstancePhase): boolean {
return frontendDashboardServiceClient.latestInfo?.statusPhase === phase;
}
if (!isWorkspaceInstancePhase("running")) {
if (debugWorkspace && frontendDashboardServiceClient.latestInfo) {
window.open('', '_self')?.close()
}
await new Promise<void>((resolve) => {
frontendDashboardServiceClient.onInfoUpdate((status) => {
if (status.statusPhase === "running") {
Expand All @@ -262,6 +267,11 @@ LoadingFrame.load().then(async (loading) => {
});
}
const supervisorServiceClient = SupervisorServiceClient.get();
if (debugWorkspace) {
supervisorServiceClient.supervisorWillShutdown.then(() => {
window.open('', '_self')?.close()
})
}
const [ideStatus] = await Promise.all([
supervisorServiceClient.ideReady,
supervisorServiceClient.contentReady,
Expand Down
Loading

0 comments on commit 010e3f0

Please sign in to comment.