summaryrefslogtreecommitdiff
path: root/extension/src/activation/environmentSetup.ts
blob: 10a9f75ff29549b523dca6911f33f3e6ccc9c73a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import { getExtensionUri } from "../util/vscode";
const util = require("util");
const exec = util.promisify(require("child_process").exec);
const { spawn } = require("child_process");
import * as path from "path";
import * as fs from "fs";
import { getContinueServerUrl } from "../bridge";
import fetch from "node-fetch";
import * as vscode from "vscode";
import * as os from "os";
import fkill from "fkill";

async function runCommand(cmd: string): Promise<[string, string | undefined]> {
  var stdout: any = "";
  var stderr: any = "";
  try {
    var { stdout, stderr } = await exec(cmd, {
      shell: process.platform === "win32" ? "powershell.exe" : undefined,
    });
  } catch (e: any) {
    stderr = e.stderr;
    stdout = e.stdout;
  }
  if (stderr === "") {
    stderr = undefined;
  }
  if (typeof stdout === "undefined") {
    stdout = "";
  }

  return [stdout, stderr];
}

async function checkServerRunning(serverUrl: string): Promise<boolean> {
  // Check if already running by calling /health
  try {
    const response = await fetch(`${serverUrl}/health`);
    if (response.status === 200) {
      console.log("Continue python server already running");
      return true;
    } else {
      return false;
    }
  } catch (e) {
    return false;
  }
}

export function getContinueGlobalPath(): string {
  // This is ~/.continue on mac/linux
  const continuePath = path.join(os.homedir(), ".continue");
  if (!fs.existsSync(continuePath)) {
    fs.mkdirSync(continuePath);
  }
  return continuePath;
}

function serverPath(): string {
  const sPath = path.join(getContinueGlobalPath(), "server");
  if (!fs.existsSync(sPath)) {
    fs.mkdirSync(sPath);
  }
  return sPath;
}

export function devDataPath(): string {
  const sPath = path.join(getContinueGlobalPath(), "dev_data");
  if (!fs.existsSync(sPath)) {
    fs.mkdirSync(sPath);
  }
  return sPath;
}

function serverVersionPath(): string {
  return path.join(serverPath(), "server_version.txt");
}

export function getExtensionVersion() {
  const extension = vscode.extensions.getExtension("continue.continue");
  return extension?.packageJSON.version || "";
}

// Returns whether a server of the current version is already running
async function checkOrKillRunningServer(serverUrl: string): Promise<boolean> {
  console.log("Checking if server is old version");
  const serverRunning = await checkServerRunning(serverUrl);
  // Kill the server if it is running an old version
  if (fs.existsSync(serverVersionPath())) {
    const serverVersion = fs.readFileSync(serverVersionPath(), "utf8");
    if (serverVersion === getExtensionVersion() && serverRunning) {
      // The current version is already up and running, no need to continue
      return true;
    }
  }
  if (serverRunning) {
    console.log("Killing old server...");
    try {
      await fkill(":65432");
    } catch (e: any) {
      if (!e.message.includes("Process doesn't exist")) {
        console.log("Failed to kill old server:", e);
      }
    }
  }
  return false;
}

function ensureDirectoryExistence(filePath: string) {
  const dirname = path.dirname(filePath);
  if (fs.existsSync(dirname)) {
    return true;
  }
  ensureDirectoryExistence(dirname);
  fs.mkdirSync(dirname);
}

export async function downloadFromS3(
  bucket: string,
  fileName: string,
  destination: string,
  region: string
) {
  const s3Url = `https://${bucket}.s3.${region}.amazonaws.com/${fileName}`;
  const response = await fetch(s3Url, {
    method: "GET",
  });
  if (!response.ok) {
    const text = await response.text();
    const errText = `Failed to download Continue server from S3: ${text}`;
    vscode.window.showErrorMessage(errText);
    throw new Error(errText);
  }
  const buffer = await response.buffer();
  ensureDirectoryExistence(destination);
  fs.writeFileSync(destination, buffer);
}

export async function startContinuePythonServer() {
  // Check vscode settings
  const serverUrl = getContinueServerUrl();
  if (serverUrl !== "http://localhost:65432") {
    console.log("Continue server is being run manually, skipping start");
    return;
  }

  // Check if server is already running
  if (await checkOrKillRunningServer(serverUrl)) {
    console.log("Continue server already running");
    return;
  }

  // Download the server executable
  const bucket = "continue-server-binaries";
  const fileName =
    os.platform() === "win32"
      ? "windows/run.exe"
      : os.platform() === "darwin"
      ? "mac/run"
      : "linux/run";

  const destination = path.join(
    getExtensionUri().fsPath,
    "server",
    "exe",
    `run${os.platform() === "win32" ? ".exe" : ""}`
  );

  // First, check if the server is already downloaded
  let shouldDownload = true;
  if (fs.existsSync(destination)) {
    // Check if the server is the correct version
    const serverVersion = fs.readFileSync(serverVersionPath(), "utf8");
    if (serverVersion === getExtensionVersion()) {
      // The current version is already up and running, no need to continue
      console.log("Continue server already downloaded");
      shouldDownload = false;
    } else {
      fs.unlinkSync(destination);
    }
  }

  if (shouldDownload) {
    await vscode.window.withProgress(
      {
        location: vscode.ProgressLocation.Notification,
        title: "Installing Continue server...",
        cancellable: false,
      },
      async () => {
        await downloadFromS3(bucket, fileName, destination, "us-west-1");
      }
    );
  }

  console.log("Downloaded server executable at ", destination);
  // Get name of the corresponding executable for platform
  if (os.platform() === "darwin") {
    // Add necessary permissions
    console.log("Setting permissions for Continue server...");
    fs.chmodSync(destination, 0o7_5_5);
    const [stdout1, stderr1] = await runCommand(
      `xattr -dr com.apple.quarantine ${destination}`
    );
    console.log("stdout: ", stdout1);
    console.log("stderr: ", stderr1);
  } else if (os.platform() === "linux") {
    // Add necessary permissions
    console.log("Setting permissions for Continue server...");
    fs.chmodSync(destination, 0o7_5_5);
  }

  // Validate that the file exists
  if (!fs.existsSync(destination)) {
    const errText = `- Failed to install Continue server.`;
    vscode.window.showErrorMessage(errText);
    throw new Error(errText);
  }

  // Run the executable
  console.log("Starting Continue server...");
  const child = spawn(destination, {
    shell: true,
  });
  child.stderr.on("data", (data: any) => {
    console.log(data.toString());
  });

  child.on("error", (error: any) => {
    console.log(`error: ${error.message}`);
  });

  child.on("close", (code: any) => {
    console.log(`child process exited with code ${code}`);
  });

  child.stdout.on("data", (data: any) => {
    console.log(`stdout: ${data.toString()}`);
  });

  // Write the current version of vscode extension to a file called server_version.txt
  fs.writeFileSync(serverVersionPath(), getExtensionVersion());
}