Brijesh's Git Server — navigator-v2 @ 19f964e87980aeb2d2f6a016091d7bfe1bdb3732

api/internal/browser/service.go (view raw)

 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
package browser

import (
	"api/internal/database"
	"context"
	"errors"
	"fmt"
	"net"
	"os"
	"os/exec"
	"sync"
	"time"

	"github.com/google/uuid"
)

const (
	XvfbPath = "/usr/bin/Xvfb"
	VNCPath  = "/usr/bin/x11vnc"
)

type Service interface {
	StartSession(ctx context.Context) (*database.BrowserSession, error)
	StopSession(ctx context.Context, id uuid.UUID) error
	GetSession(ctx context.Context, id uuid.UUID) (*database.BrowserSession, error)
	ListSessions(ctx context.Context) ([]*database.BrowserSession, error)
}

type service struct {
	db     database.Service
	config database.Config
	mu     sync.Mutex
}

func NewService(db database.Service, config database.Config) Service {
	return &service{
		db:     db,
		config: config,
	}
}

func (s *service) StartSession(ctx context.Context) (*database.BrowserSession, error) {
	s.mu.Lock()
	defer s.mu.Unlock()

	// Check if we haven't exceeded max sessions
	sessions, err := s.db.ListBrowserSessions(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed to list sessions: %w", err)
	}
	if len(sessions) >= s.config.MaxSessions {
		return nil, errors.New("maximum number of sessions reached")
	}

	// Get next available display number
	displayNum, err := s.db.GetNextAvailableDisplayNumber(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed to get display number: %w", err)
	}

	// Calculate ports
	vncPort := s.config.BaseVNCPort + displayNum
	debugPort := s.config.BaseDebugPort + displayNum

	// Create new session
	session := &database.BrowserSession{
		ID:            uuid.New(),
		DisplayNumber: displayNum,
		VNCPort:       vncPort,
		DebugPort:     debugPort,
		Status:        database.StatusStarting,
	}

	// Create session in database
	if err := s.db.CreateBrowserSession(ctx, session); err != nil {
		return nil, fmt.Errorf("failed to create session: %w", err)
	}

	// Start the processes
	if err := s.startProcesses(ctx, session); err != nil {
		session.Status = database.StatusFailed
		errMsg := err.Error()
		session.ErrorMessage = &errMsg
		_ = s.db.UpdateBrowserSession(ctx, session)
		return nil, err
	}

	session.Status = database.StatusRunning
	if err := s.db.UpdateBrowserSession(ctx, session); err != nil {
		return nil, fmt.Errorf("failed to update session status: %w", err)
	}

	return session, nil
}

func (s *service) startProcesses(ctx context.Context, session *database.BrowserSession) error {
	// Start Xvfb with full path
	fmt.Printf("\nCOMMAND: %s %s -screen 0 %dx%dx%d\n\n",
		XvfbPath,
		fmt.Sprintf(":%d", session.DisplayNumber),
		s.config.ScreenWidth,
		s.config.ScreenHeight,
		s.config.ScreenDepth,
	)
	xvfbCmd := exec.Command(XvfbPath,
		fmt.Sprintf(":%d", session.DisplayNumber),
		"-screen", "0",
		fmt.Sprintf("%dx%dx%d", s.config.ScreenWidth, s.config.ScreenHeight, s.config.ScreenDepth),
	)
	xvfbCmd.Stdout = os.Stdout
	xvfbCmd.Stderr = os.Stderr
	if err := xvfbCmd.Start(); err != nil {
		return fmt.Errorf("failed to start Xvfb: %w", err)
	}
	session.XvfbPID = &xvfbCmd.Process.Pid

	// Wait for Xvfb to start
	time.Sleep(2 * time.Second)

	// Start Chrome with GPU disabled due to initialization errors
	fmt.Printf("\nCOMMAND: %s --no-sandbox --remote-debugging-address=0.0.0.0 --remote-debugging-port=%d\n\n",
		s.config.ChromePath,
		session.DebugPort,
	)
	chromeCmd := exec.Command(s.config.ChromePath,
		"--no-sandbox",
		"--disable-gpu",
		"--remote-debugging-address=0.0.0.0",
		fmt.Sprintf("--remote-debugging-port=%d", session.DebugPort),
	)
	chromeCmd.Env = append(os.Environ(),
		fmt.Sprintf("DISPLAY=:%d", session.DisplayNumber),
		"DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus",
	)
	chromeCmd.Stdout = os.Stdout
	chromeCmd.Stderr = os.Stderr
	if err := chromeCmd.Start(); err != nil {
		s.killProcess(xvfbCmd.Process.Pid)
		return fmt.Errorf("failed to start Chrome: %w", err)
	}
	session.ChromePID = &chromeCmd.Process.Pid

	time.Sleep(5 * time.Second)

	// Start VNC server with full path
	fmt.Printf("\nCOMMAND: %s -display :%d -nopw -forever -localhost\n\n",
		VNCPath,
		session.DisplayNumber,
	)
	vncCmd := exec.Command(VNCPath,
		"-display", fmt.Sprintf(":%d", session.DisplayNumber),
		"-nopw",
		"-forever",
		"-localhost",
		"-rfbport", fmt.Sprintf("%d", session.VNCPort),
	)
	vncCmd.Stdout = os.Stdout
	vncCmd.Stderr = os.Stderr
	if err := vncCmd.Start(); err != nil {
		s.killProcess(xvfbCmd.Process.Pid)
		s.killProcess(chromeCmd.Process.Pid)
		return fmt.Errorf("failed to start VNC server: %w", err)
	} else {
		fmt.Printf("\nVNC server started on port %d\n\n", session.VNCPort)
	}
	session.VNCPID = &vncCmd.Process.Pid

	// Add a longer delay for VNC server startup
	time.Sleep(5 * time.Second)

	// Try to connect to VNC server to verify it's running
	conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", session.VNCPort), 5*time.Second)
	if err != nil {
		fmt.Printf("\nCOMMAND: nc -zv localhost %d\nError: %v\n\n", session.VNCPort, err)
		s.killProcess(xvfbCmd.Process.Pid)
		s.killProcess(chromeCmd.Process.Pid)
		s.killProcess(vncCmd.Process.Pid)
		return fmt.Errorf("failed to connect to VNC server: %w", err)
	}

	// Update session with PIDs
	if err := s.db.UpdateBrowserSession(ctx, session); err != nil {
		s.killProcess(xvfbCmd.Process.Pid)
		s.killProcess(chromeCmd.Process.Pid)
		s.killProcess(vncCmd.Process.Pid)
		return fmt.Errorf("failed to update session with PIDs: %w", err)
	}

	conn.Close()

	return nil
}

func (s *service) killProcess(pid int) {
	process, err := os.FindProcess(pid)
	if err == nil {
		_ = process.Kill()
	}
}

func (s *service) StopSession(ctx context.Context, id uuid.UUID) error {
	session, err := s.db.GetBrowserSession(ctx, id)
	if err != nil {
		return fmt.Errorf("failed to get session: %w", err)
	}

	// Kill all processes
	if session.XvfbPID != nil {
		s.killProcess(*session.XvfbPID)
	}
	if session.ChromePID != nil {
		s.killProcess(*session.ChromePID)
	}
	if session.VNCPID != nil {
		s.killProcess(*session.VNCPID)
	}

	session.Status = database.StatusStopped
	return s.db.UpdateBrowserSession(ctx, session)
}

func (s *service) GetSession(ctx context.Context, id uuid.UUID) (*database.BrowserSession, error) {
	return s.db.GetBrowserSession(ctx, id)
}

func (s *service) ListSessions(ctx context.Context) ([]*database.BrowserSession, error) {
	return s.db.ListBrowserSessions(ctx)
}