Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Change formatting and timestamp passing

Tomas Valenta089d1e4a1e64
diff --git a/packages/cli/src/commands/sandbox/logs.ts b/packages/cli/src/commands/sandbox/logs.ts
index 894e836b5..620c51cba 100644
--- a/packages/cli/src/commands/sandbox/logs.ts
+++ b/packages/cli/src/commands/sandbox/logs.ts
@@ -1,10 +1,13 @@
import * as commander from 'commander'
import * as e2b from 'e2b'
import * as util from 'util'
+import * as chalk from 'chalk'
import { ensureAPIKey } from 'src/api'
-import { asBold, asTimestamp, asPrimary } from 'src/utils/format'
+import { asBold, asTimestamp, withUnderline } from 'src/utils/format'
import { listSandboxes } from './list'
+import { wait } from 'src/utils/wait'
+import { createDeferredPromise } from 'src/utils/promise'
const getSandboxLogs = e2b.withAPIKey(
e2b.api.path('/sandboxes/{sandboxID}/logs').method('get').create(),
@@ -12,6 +15,45 @@ const getSandboxLogs = e2b.withAPIKey(
const maxRuntime = 24 * 60 * 60 * 1000 // 24 hours in milliseconds
+function getLongID(sandboxID: string, clientID?: string) {
+ if (clientID) {
+ return `${sandboxID}-${clientID}`
+ }
+ return sandboxID
+}
+
+async function waitForSandboxEnd(apiKey: string, sandboxID: string) {
+ const deferredPromise = createDeferredPromise()
+
+ async function monitor() {
+ const startTime = new Date().getTime()
+
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ await wait(10000)
+
+ const currentTime = new Date().getTime()
+ const elapsedTime = currentTime - startTime // Time elapsed in milliseconds
+
+ // Check if 24 hours (in milliseconds) have passed
+ if (elapsedTime >= maxRuntime) {
+ break
+ }
+
+ const response = await listSandboxes({ apiKey })
+ const sandbox = response.find(s => getLongID(s.sandboxID, s.clientID) === sandboxID)
+ if (!sandbox) {
+ deferredPromise.resolve()
+ break
+ }
+ }
+ }
+
+ monitor()
+
+ return deferredPromise.promise
+}
+
export const logsCommand = new commander.Command('logs')
.description('show logs for sandbox')
.argument('<sandboxID>', `show longs for sandbox specified by ${asBold('<sandboxID>')}`)
@@ -23,6 +65,13 @@ export const logsCommand = new commander.Command('logs')
const startTime = new Date().getTime()
+ let isFirstRun = true
+ let isRunning = true
+
+ waitForSandboxEnd(apiKey, sandboxID).then(() => {
+ isRunning = false
+ })
+
let start: number | undefined
// eslint-disable-next-line no-constant-condition
while (true) {
@@ -35,32 +84,67 @@ export const logsCommand = new commander.Command('logs')
break
}
- const [info, logs] = await Promise.all([
- start === undefined ? runningSandboxes : undefined,
- listSandboxLogs({ apiKey, sandboxID, start }),
- ])
-
- const sandbox = info ? info.find(s => s.sandboxID === sandboxID) : undefined
- const isRunning = !!sandbox
+ const logsPromise = listSandboxLogs({ apiKey, sandboxID, start })
+ const info = await runningSandboxes
- printSandboxInfo({
- isRunning: isRunning,
- sandboxID: sandboxID,
- })
+ const sandbox = info ? info.find(s => getLongID(s.sandboxID, s.clientID) === sandboxID) : undefined
+ isRunning = !!sandbox
- for (const log of logs) {
- printLog(log.timestamp, log.line)
+ if (isFirstRun) {
+ printSandboxInfo({
+ isRunning: isRunning,
+ sandboxID: sandboxID,
+ })
}
- if (!isRunning) {
- console.log('\nStopped printing logs — sandbox is closed')
- break
+ try {
+ const logs = await logsPromise
+
+ for (const log of logs) {
+ printLog(log.timestamp, log.line)
+ }
+
+ console.log('new logs', logs.length)
+
+ if (!isRunning && logs.length === 0 && isFirstRun) {
+ console.log(`\nStopped printing logs — sandbox ${withUnderline('not found')}`)
+ break
+ }
+
+ if (!isRunning) {
+ console.log(`\nStopped printing logs — sandbox is ${withUnderline('closed')}`)
+ break
+ }
+
+ const lastLog = logs[logs.length - 1]
+ start = (lastLog
+ ? new Date(lastLog.timestamp).getTime() + 1
+ : Date.now())
+ } catch (e) {
+ if (e instanceof getSandboxLogs.Error) {
+ console.log('is instance of Error', e.getActualType())
+ const error = e.getActualType()
+ if (error.status === 401) {
+ throw new Error(
+ `Error getting sandbox logs - (${error.status}) bad request: ${error}`,
+ )
+ }
+ if (error.status === 404) {
+ throw new Error(
+ `Error getting sandbox logs - (${error.status}) not found: ${error}`,
+ )
+ }
+ if (error.status === 500) {
+ throw new Error(
+ `Error getting sandbox logs - (${error.status}) server error: ${error}`,
+ )
+ }
+ }
+ throw e
}
- const lastLog = logs[logs.length - 1]
- if (lastLog) {
- start = new Date(lastLog.timestamp).getTime()
- }
+ await wait(500)
+ isFirstRun = false
}
} catch (err: any) {
console.error(err)
@@ -72,14 +156,29 @@ function printSandboxInfo({ sandboxID, isRunning }: {
sandboxID: string,
isRunning: boolean,
}) {
- process.stdout.write(`\nLogs for ${asBold(isRunning ? 'running' : 'closed')} sandbox ${asPrimary(sandboxID)}:\n\n`)
+ process.stdout.write(`\nLogs for ${withUnderline(isRunning ? 'running' : 'closed')} sandbox ${asBold(sandboxID)}:\n\n`)
}
function printLog(timestamp: string, line: string) {
const log = JSON.parse(line)
- const time = `[${new Date(timestamp).toISOString()}]`
- const level = log['level'].toUpperCase()
+ const time = `[${new Date(timestamp).toISOString().replace(/T/, ' ').replace(/\..+/, '')}]`
+ let level = log['level'].toUpperCase()
+
+ switch (level) {
+ case 'DEBUG':
+ level = chalk.default.bgWhite(level)
+ break
+ case 'INFO':
+ level = chalk.default.bgGreen(level)
+ break
+ case 'WARN':
+ level = chalk.default.bgYellow(level)
+ break
+ case 'ERROR':
+ level = chalk.default.white(chalk.default.bgRed(level))
+ break
+ }
delete log['traceID']
delete log['instanceID']
diff --git a/packages/cli/src/utils/format.ts b/packages/cli/src/utils/format.ts
index 229bc4f69..81b858302 100644
--- a/packages/cli/src/utils/format.ts
+++ b/packages/cli/src/utils/format.ts
@@ -66,6 +66,11 @@ export function asHeadline(content: string) {
return chalk.default.underline(asPrimary(asBold(content)))
}
+export function withUnderline(content: string) {
+ return chalk.default.underline(content)
+
+}
+
export function listAliases(aliases: string[] | undefined) {
if (!aliases) return undefined
return aliases.join(' | ')