diff --git a/.claude/docs/DATABASE.md b/.claude/docs/DATABASE.md new file mode 100644 index 0000000000000..fe977297f8670 --- /dev/null +++ b/.claude/docs/DATABASE.md @@ -0,0 +1,218 @@ +# Database Development Patterns + +## Database Work Overview + +### Database Generation Process + +1. Modify SQL files in `coderd/database/queries/` +2. Run `make gen` +3. If errors about audit table, update `enterprise/audit/table.go` +4. Run `make gen` again +5. Run `make lint` to catch any remaining issues + +## Migration Guidelines + +### Creating Migration Files + +**Location**: `coderd/database/migrations/` +**Format**: `{number}_{description}.{up|down}.sql` + +- Number must be unique and sequential +- Always include both up and down migrations + +### Helper Scripts + +| Script | Purpose | +|---------------------------------------------------------------------|-----------------------------------------| +| `./coderd/database/migrations/create_migration.sh "migration name"` | Creates new migration files | +| `./coderd/database/migrations/fix_migration_numbers.sh` | Renumbers migrations to avoid conflicts | +| `./coderd/database/migrations/create_fixture.sh "fixture name"` | Creates test fixtures for migrations | + +### Database Query Organization + +- **MUST DO**: Any changes to database - adding queries, modifying queries should be done in the `coderd/database/queries/*.sql` files +- **MUST DO**: Queries are grouped in files relating to context - e.g. `prebuilds.sql`, `users.sql`, `oauth2.sql` +- After making changes to any `coderd/database/queries/*.sql` files you must run `make gen` to generate respective ORM changes + +## Handling Nullable Fields + +Use `sql.NullString`, `sql.NullBool`, etc. for optional database fields: + +```go +CodeChallenge: sql.NullString{ + String: params.codeChallenge, + Valid: params.codeChallenge != "", +} +``` + +Set `.Valid = true` when providing values. + +## Audit Table Updates + +If adding fields to auditable types: + +1. Update `enterprise/audit/table.go` +2. Add each new field with appropriate action: + - `ActionTrack`: Field should be tracked in audit logs + - `ActionIgnore`: Field should be ignored in audit logs + - `ActionSecret`: Field contains sensitive data +3. Run `make gen` to verify no audit errors + +## Database Architecture + +### Core Components + +- **PostgreSQL 13+** recommended for production +- **Migrations** managed with `migrate` +- **Database authorization** through `dbauthz` package + +### Authorization Patterns + +```go +// Public endpoints needing system access (OAuth2 registration) +app, err := api.Database.GetOAuth2ProviderAppByClientID(dbauthz.AsSystemRestricted(ctx), clientID) + +// Authenticated endpoints with user context +app, err := api.Database.GetOAuth2ProviderAppByClientID(ctx, clientID) + +// System operations in middleware +roles, err := db.GetAuthorizationUserRoles(dbauthz.AsSystemRestricted(ctx), userID) +``` + +## Common Database Issues + +### Migration Issues + +1. **Migration conflicts**: Use `fix_migration_numbers.sh` to renumber +2. **Missing down migration**: Always create both up and down files +3. **Schema inconsistencies**: Verify against existing schema + +### Field Handling Issues + +1. **Nullable field errors**: Use `sql.Null*` types consistently +2. **Missing audit entries**: Update `enterprise/audit/table.go` + +### Query Issues + +1. **Query organization**: Group related queries in appropriate files +2. **Generated code errors**: Run `make gen` after query changes +3. **Performance issues**: Add appropriate indexes in migrations + +## Database Testing + +### Test Database Setup + +```go +func TestDatabaseFunction(t *testing.T) { + db := dbtestutil.NewDB(t) + + // Test with real database + result, err := db.GetSomething(ctx, param) + require.NoError(t, err) + require.Equal(t, expected, result) +} +``` + +## Best Practices + +### Schema Design + +1. **Use appropriate data types**: VARCHAR for strings, TIMESTAMP for times +2. **Add constraints**: NOT NULL, UNIQUE, FOREIGN KEY as appropriate +3. **Create indexes**: For frequently queried columns +4. **Consider performance**: Normalize appropriately but avoid over-normalization + +### Query Writing + +1. **Use parameterized queries**: Prevent SQL injection +2. **Handle errors appropriately**: Check for specific error types +3. **Use transactions**: For related operations that must succeed together +4. **Optimize queries**: Use EXPLAIN to understand query performance + +### Migration Writing + +1. **Make migrations reversible**: Always include down migration +2. **Test migrations**: On copy of production data if possible +3. **Keep migrations small**: One logical change per migration +4. **Document complex changes**: Add comments explaining rationale + +## Advanced Patterns + +### Complex Queries + +```sql +-- Example: Complex join with aggregation +SELECT + u.id, + u.username, + COUNT(w.id) as workspace_count +FROM users u +LEFT JOIN workspaces w ON u.id = w.owner_id +WHERE u.created_at > $1 +GROUP BY u.id, u.username +ORDER BY workspace_count DESC; +``` + +### Conditional Queries + +```sql +-- Example: Dynamic filtering +SELECT * FROM oauth2_provider_apps +WHERE + ($1::text IS NULL OR name ILIKE '%' || $1 || '%') + AND ($2::uuid IS NULL OR organization_id = $2) +ORDER BY created_at DESC; +``` + +### Audit Patterns + +```go +// Example: Auditable database operation +func (q *sqlQuerier) UpdateUser(ctx context.Context, arg UpdateUserParams) (User, error) { + // Implementation here + + // Audit the change + if auditor := audit.FromContext(ctx); auditor != nil { + auditor.Record(audit.UserUpdate{ + UserID: arg.ID, + Old: oldUser, + New: newUser, + }) + } + + return newUser, nil +} +``` + +## Debugging Database Issues + +### Common Debug Commands + +```bash +# Check database connection +make test-postgres + +# Run specific database tests +go test ./coderd/database/... -run TestSpecificFunction + +# Check query generation +make gen + +# Verify audit table +make lint +``` + +### Debug Techniques + +1. **Enable query logging**: Set appropriate log levels +2. **Use database tools**: pgAdmin, psql for direct inspection +3. **Check constraints**: UNIQUE, FOREIGN KEY violations +4. **Analyze performance**: Use EXPLAIN ANALYZE for slow queries + +### Troubleshooting Checklist + +- [ ] Migration files exist (both up and down) +- [ ] `make gen` run after query changes +- [ ] Audit table updated for new fields +- [ ] Nullable fields use `sql.Null*` types +- [ ] Authorization context appropriate for endpoint type diff --git a/.claude/docs/OAUTH2.md b/.claude/docs/OAUTH2.md new file mode 100644 index 0000000000000..4716fc672a1e3 --- /dev/null +++ b/.claude/docs/OAUTH2.md @@ -0,0 +1,157 @@ +# OAuth2 Development Guide + +## RFC Compliance Development + +### Implementing Standard Protocols + +When implementing standard protocols (OAuth2, OpenID Connect, etc.): + +1. **Fetch and Analyze Official RFCs**: + - Always read the actual RFC specifications before implementation + - Use WebFetch tool to get current RFC content for compliance verification + - Document RFC requirements in code comments + +2. **Default Values Matter**: + - Pay close attention to RFC-specified default values + - Example: RFC 7591 specifies `client_secret_basic` as default, not `client_secret_post` + - Ensure consistency between database migrations and application code + +3. **Security Requirements**: + - Follow RFC security considerations precisely + - Example: RFC 7592 prohibits returning registration access tokens in GET responses + - Implement proper error responses per protocol specifications + +4. **Validation Compliance**: + - Implement comprehensive validation per RFC requirements + - Support protocol-specific features (e.g., custom schemes for native OAuth2 apps) + - Test edge cases defined in specifications + +## OAuth2 Provider Implementation + +### OAuth2 Spec Compliance + +1. **Follow RFC 6749 for token responses** + - Use `expires_in` (seconds) not `expiry` (timestamp) in token responses + - Return proper OAuth2 error format: `{"error": "code", "error_description": "details"}` + +2. **Error Response Format** + - Create OAuth2-compliant error responses for token endpoint + - Use standard error codes: `invalid_client`, `invalid_grant`, `invalid_request` + - Avoid generic error responses for OAuth2 endpoints + +### PKCE Implementation + +- Support both with and without PKCE for backward compatibility +- Use S256 method for code challenge +- Properly validate code_verifier against stored code_challenge + +### UI Authorization Flow + +- Use POST requests for consent, not GET with links +- Avoid dependency on referer headers for security decisions +- Support proper state parameter validation + +### RFC 8707 Resource Indicators + +- Store resource parameters in database for server-side validation (opaque tokens) +- Validate resource consistency between authorization and token requests +- Support audience validation in refresh token flows +- Resource parameter is optional but must be consistent when provided + +## OAuth2 Error Handling Pattern + +```go +// Define specific OAuth2 errors +var ( + errInvalidPKCE = xerrors.New("invalid code_verifier") +) + +// Use OAuth2-compliant error responses +type OAuth2Error struct { + Error string `json:"error"` + ErrorDescription string `json:"error_description,omitempty"` +} + +// Return proper OAuth2 errors +if errors.Is(err, errInvalidPKCE) { + writeOAuth2Error(ctx, rw, http.StatusBadRequest, "invalid_grant", "The PKCE code verifier is invalid") + return +} +``` + +## Testing OAuth2 Features + +### Test Scripts + +Located in `./scripts/oauth2/`: + +- `test-mcp-oauth2.sh` - Full automated test suite +- `setup-test-app.sh` - Create test OAuth2 app +- `cleanup-test-app.sh` - Remove test app +- `generate-pkce.sh` - Generate PKCE parameters +- `test-manual-flow.sh` - Manual browser testing + +Always run the full test suite after OAuth2 changes: + +```bash +./scripts/oauth2/test-mcp-oauth2.sh +``` + +### RFC Protocol Testing + +1. **Compliance Test Coverage**: + - Test all RFC-defined error codes and responses + - Validate proper HTTP status codes for different scenarios + - Test protocol-specific edge cases (URI formats, token formats, etc.) + +2. **Security Boundary Testing**: + - Test client isolation and privilege separation + - Verify information disclosure protections + - Test token security and proper invalidation + +## Common OAuth2 Issues + +1. **OAuth2 endpoints returning wrong error format** - Ensure OAuth2 endpoints return RFC 6749 compliant errors +2. **Resource indicator validation failing** - Ensure database stores and retrieves resource parameters correctly +3. **PKCE tests failing** - Verify both authorization code storage and token exchange handle PKCE fields +4. **RFC compliance failures** - Verify against actual RFC specifications, not assumptions +5. **Authorization context errors in public endpoints** - Use `dbauthz.AsSystemRestricted(ctx)` pattern +6. **Default value mismatches** - Ensure database migrations match application code defaults +7. **Bearer token authentication issues** - Check token extraction precedence and format validation +8. **URI validation failures** - Support both standard schemes and custom schemes per protocol requirements + +## Authorization Context Patterns + +```go +// Public endpoints needing system access (OAuth2 registration) +app, err := api.Database.GetOAuth2ProviderAppByClientID(dbauthz.AsSystemRestricted(ctx), clientID) + +// Authenticated endpoints with user context +app, err := api.Database.GetOAuth2ProviderAppByClientID(ctx, clientID) + +// System operations in middleware +roles, err := db.GetAuthorizationUserRoles(dbauthz.AsSystemRestricted(ctx), userID) +``` + +## OAuth2/Authentication Work Patterns + +- Types go in `codersdk/oauth2.go` or similar +- Handlers go in `coderd/oauth2.go` or `coderd/identityprovider/` +- Database fields need migration + audit table updates +- Always support backward compatibility + +## Protocol Implementation Checklist + +Before completing OAuth2 or authentication feature work: + +- [ ] Verify RFC compliance by reading actual specifications +- [ ] Implement proper error response formats per protocol +- [ ] Add comprehensive validation for all protocol fields +- [ ] Test security boundaries and token handling +- [ ] Update RBAC permissions for new resources +- [ ] Add audit logging support if applicable +- [ ] Create database migrations with proper defaults +- [ ] Add comprehensive test coverage including edge cases +- [ ] Verify linting compliance +- [ ] Test both positive and negative scenarios +- [ ] Document protocol-specific patterns and requirements diff --git a/.claude/docs/TESTING.md b/.claude/docs/TESTING.md new file mode 100644 index 0000000000000..eff655b0acadc --- /dev/null +++ b/.claude/docs/TESTING.md @@ -0,0 +1,212 @@ +# Testing Patterns and Best Practices + +## Testing Best Practices + +### Avoiding Race Conditions + +1. **Unique Test Identifiers**: + - Never use hardcoded names in concurrent tests + - Use `time.Now().UnixNano()` or similar for unique identifiers + - Example: `fmt.Sprintf("test-client-%s-%d", t.Name(), time.Now().UnixNano())` + +2. **Database Constraint Awareness**: + - Understand unique constraints that can cause test conflicts + - Generate unique values for all constrained fields + - Test name isolation prevents cross-test interference + +### Testing Patterns + +- Use table-driven tests for comprehensive coverage +- Mock external dependencies +- Test both positive and negative cases +- Use `testutil.WaitLong` for timeouts in tests + +### Test Package Naming + +- **Test packages**: Use `package_test` naming (e.g., `identityprovider_test`) for black-box testing + +## RFC Protocol Testing + +### Compliance Test Coverage + +1. **Test all RFC-defined error codes and responses** +2. **Validate proper HTTP status codes for different scenarios** +3. **Test protocol-specific edge cases** (URI formats, token formats, etc.) + +### Security Boundary Testing + +1. **Test client isolation and privilege separation** +2. **Verify information disclosure protections** +3. **Test token security and proper invalidation** + +## Test Organization + +### Test File Structure + +``` +coderd/ +├── oauth2.go # Implementation +├── oauth2_test.go # Main tests +├── oauth2_test_helpers.go # Test utilities +└── oauth2_validation.go # Validation logic +``` + +### Test Categories + +1. **Unit Tests**: Test individual functions in isolation +2. **Integration Tests**: Test API endpoints with database +3. **End-to-End Tests**: Full workflow testing +4. **Race Tests**: Concurrent access testing + +## Test Commands + +### Running Tests + +| Command | Purpose | +|---------|---------| +| `make test` | Run all Go tests | +| `make test RUN=TestFunctionName` | Run specific test | +| `go test -v ./path/to/package -run TestFunctionName` | Run test with verbose output | +| `make test-postgres` | Run tests with Postgres database | +| `make test-race` | Run tests with Go race detector | +| `make test-e2e` | Run end-to-end tests | + +### Frontend Testing + +| Command | Purpose | +|---------|---------| +| `pnpm test` | Run frontend tests | +| `pnpm check` | Run code checks | + +## Common Testing Issues + +### Database-Related + +1. **SQL type errors** - Use `sql.Null*` types for nullable fields +2. **Race conditions in tests** - Use unique identifiers instead of hardcoded names + +### OAuth2 Testing + +1. **PKCE tests failing** - Verify both authorization code storage and token exchange handle PKCE fields +2. **Resource indicator validation failing** - Ensure database stores and retrieves resource parameters correctly + +### General Issues + +1. **Missing newlines** - Ensure files end with newline character +2. **Package naming errors** - Use `package_test` naming for test files +3. **Log message formatting errors** - Use lowercase, descriptive messages without special characters + +## Systematic Testing Approach + +### Multi-Issue Problem Solving + +When facing multiple failing tests or complex integration issues: + +1. **Identify Root Causes**: + - Run failing tests individually to isolate issues + - Use LSP tools to trace through call chains + - Check both compilation and runtime errors + +2. **Fix in Logical Order**: + - Address compilation issues first (imports, syntax) + - Fix authorization and RBAC issues next + - Resolve business logic and validation issues + - Handle edge cases and race conditions last + +3. **Verification Strategy**: + - Test each fix individually before moving to next issue + - Use `make lint` and `make gen` after database changes + - Verify RFC compliance with actual specifications + - Run comprehensive test suites before considering complete + +## Test Data Management + +### Unique Test Data + +```go +// Good: Unique identifiers prevent conflicts +clientName := fmt.Sprintf("test-client-%s-%d", t.Name(), time.Now().UnixNano()) + +// Bad: Hardcoded names cause race conditions +clientName := "test-client" +``` + +### Test Cleanup + +```go +func TestSomething(t *testing.T) { + // Setup + client := coderdtest.New(t, nil) + + // Test code here + + // Cleanup happens automatically via t.Cleanup() in coderdtest +} +``` + +## Test Utilities + +### Common Test Patterns + +```go +// Table-driven tests +tests := []struct { + name string + input InputType + expected OutputType + wantErr bool +}{ + { + name: "valid input", + input: validInput, + expected: expectedOutput, + wantErr: false, + }, + // ... more test cases +} + +for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result, err := functionUnderTest(tt.input) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + require.Equal(t, tt.expected, result) + }) +} +``` + +### Test Assertions + +```go +// Use testify/require for assertions +require.NoError(t, err) +require.Equal(t, expected, actual) +require.NotNil(t, result) +require.True(t, condition) +``` + +## Performance Testing + +### Load Testing + +- Use `scaletest/` directory for load testing scenarios +- Run `./scaletest/scaletest.sh` for performance testing + +### Benchmarking + +```go +func BenchmarkFunction(b *testing.B) { + for i := 0; i < b.N; i++ { + // Function call to benchmark + _ = functionUnderTest(input) + } +} +``` + +Run benchmarks with: +```bash +go test -bench=. -benchmem ./package/path +``` diff --git a/.claude/docs/TROUBLESHOOTING.md b/.claude/docs/TROUBLESHOOTING.md new file mode 100644 index 0000000000000..28851b5b640f0 --- /dev/null +++ b/.claude/docs/TROUBLESHOOTING.md @@ -0,0 +1,231 @@ +# Troubleshooting Guide + +## Common Issues + +### Database Issues + +1. **"Audit table entry missing action"** + - **Solution**: Update `enterprise/audit/table.go` + - Add each new field with appropriate action (ActionTrack, ActionIgnore, ActionSecret) + - Run `make gen` to verify no audit errors + +2. **SQL type errors** + - **Solution**: Use `sql.Null*` types for nullable fields + - Set `.Valid = true` when providing values + - Example: + + ```go + CodeChallenge: sql.NullString{ + String: params.codeChallenge, + Valid: params.codeChallenge != "", + } + ``` + +### Testing Issues + +3. **"package should be X_test"** + - **Solution**: Use `package_test` naming for test files + - Example: `identityprovider_test` for black-box testing + +4. **Race conditions in tests** + - **Solution**: Use unique identifiers instead of hardcoded names + - Example: `fmt.Sprintf("test-client-%s-%d", t.Name(), time.Now().UnixNano())` + - Never use hardcoded names in concurrent tests + +5. **Missing newlines** + - **Solution**: Ensure files end with newline character + - Most editors can be configured to add this automatically + +### OAuth2 Issues + +6. **OAuth2 endpoints returning wrong error format** + - **Solution**: Ensure OAuth2 endpoints return RFC 6749 compliant errors + - Use standard error codes: `invalid_client`, `invalid_grant`, `invalid_request` + - Format: `{"error": "code", "error_description": "details"}` + +7. **Resource indicator validation failing** + - **Solution**: Ensure database stores and retrieves resource parameters correctly + - Check both authorization code storage and token exchange handling + +8. **PKCE tests failing** + - **Solution**: Verify both authorization code storage and token exchange handle PKCE fields + - Check `CodeChallenge` and `CodeChallengeMethod` field handling + +### RFC Compliance Issues + +9. **RFC compliance failures** + - **Solution**: Verify against actual RFC specifications, not assumptions + - Use WebFetch tool to get current RFC content for compliance verification + - Read the actual RFC specifications before implementation + +10. **Default value mismatches** + - **Solution**: Ensure database migrations match application code defaults + - Example: RFC 7591 specifies `client_secret_basic` as default, not `client_secret_post` + +### Authorization Issues + +11. **Authorization context errors in public endpoints** + - **Solution**: Use `dbauthz.AsSystemRestricted(ctx)` pattern + - Example: + + ```go + // Public endpoints needing system access + app, err := api.Database.GetOAuth2ProviderAppByClientID(dbauthz.AsSystemRestricted(ctx), clientID) + ``` + +### Authentication Issues + +12. **Bearer token authentication issues** + - **Solution**: Check token extraction precedence and format validation + - Ensure proper RFC 6750 Bearer Token Support implementation + +13. **URI validation failures** + - **Solution**: Support both standard schemes and custom schemes per protocol requirements + - Native OAuth2 apps may use custom schemes + +### General Development Issues + +14. **Log message formatting errors** + - **Solution**: Use lowercase, descriptive messages without special characters + - Follow Go logging conventions + +## Systematic Debugging Approach + +### Multi-Issue Problem Solving + +When facing multiple failing tests or complex integration issues: + +1. **Identify Root Causes**: + - Run failing tests individually to isolate issues + - Use LSP tools to trace through call chains + - Check both compilation and runtime errors + +2. **Fix in Logical Order**: + - Address compilation issues first (imports, syntax) + - Fix authorization and RBAC issues next + - Resolve business logic and validation issues + - Handle edge cases and race conditions last + +3. **Verification Strategy**: + - Test each fix individually before moving to next issue + - Use `make lint` and `make gen` after database changes + - Verify RFC compliance with actual specifications + - Run comprehensive test suites before considering complete + +## Debug Commands + +### Useful Debug Commands + +| Command | Purpose | +|----------------------------------------------|---------------------------------------| +| `make lint` | Run all linters | +| `make gen` | Generate mocks, database queries | +| `go test -v ./path/to/package -run TestName` | Run specific test with verbose output | +| `go test -race ./...` | Run tests with race detector | + +### LSP Debugging + +#### Go LSP (Backend) + +| Command | Purpose | +|----------------------------------------------------|------------------------------| +| `mcp__go-language-server__definition symbolName` | Find function definition | +| `mcp__go-language-server__references symbolName` | Find all references | +| `mcp__go-language-server__diagnostics filePath` | Check for compilation errors | +| `mcp__go-language-server__hover filePath line col` | Get type information | + +#### TypeScript LSP (Frontend) + +| Command | Purpose | +|----------------------------------------------------------------------------|------------------------------------| +| `mcp__typescript-language-server__definition symbolName` | Find component/function definition | +| `mcp__typescript-language-server__references symbolName` | Find all component/type usages | +| `mcp__typescript-language-server__diagnostics filePath` | Check for TypeScript errors | +| `mcp__typescript-language-server__hover filePath line col` | Get type information | +| `mcp__typescript-language-server__rename_symbol filePath line col newName` | Rename across codebase | + +## Common Error Messages + +### Database Errors + +**Error**: `pq: relation "oauth2_provider_app_codes" does not exist` + +- **Cause**: Missing database migration +- **Solution**: Run database migrations, check migration files + +**Error**: `audit table entry missing action for field X` + +- **Cause**: New field added without audit table update +- **Solution**: Update `enterprise/audit/table.go` + +### Go Compilation Errors + +**Error**: `package should be identityprovider_test` + +- **Cause**: Test package naming convention violation +- **Solution**: Use `package_test` naming for black-box tests + +**Error**: `cannot use X (type Y) as type Z` + +- **Cause**: Type mismatch, often with nullable fields +- **Solution**: Use appropriate `sql.Null*` types + +### OAuth2 Errors + +**Error**: `invalid_client` but client exists + +- **Cause**: Authorization context issue +- **Solution**: Use `dbauthz.AsSystemRestricted(ctx)` for public endpoints + +**Error**: PKCE validation failing + +- **Cause**: Missing PKCE fields in database operations +- **Solution**: Ensure `CodeChallenge` and `CodeChallengeMethod` are handled + +## Prevention Strategies + +### Before Making Changes + +1. **Read the relevant documentation** +2. **Check if similar patterns exist in codebase** +3. **Understand the authorization context requirements** +4. **Plan database changes carefully** + +### During Development + +1. **Run tests frequently**: `make test` +2. **Use LSP tools for navigation**: Avoid manual searching +3. **Follow RFC specifications precisely** +4. **Update audit tables when adding database fields** + +### Before Committing + +1. **Run full test suite**: `make test` +2. **Check linting**: `make lint` +3. **Test with race detector**: `make test-race` + +## Getting Help + +### Internal Resources + +- Check existing similar implementations in codebase +- Use LSP tools to understand code relationships + - For Go code: Use `mcp__go-language-server__*` commands + - For TypeScript/React code: Use `mcp__typescript-language-server__*` commands +- Read related test files for expected behavior + +### External Resources + +- Official RFC specifications for protocol compliance +- Go documentation for language features +- PostgreSQL documentation for database issues + +### Debug Information Collection + +When reporting issues, include: + +1. **Exact error message** +2. **Steps to reproduce** +3. **Relevant code snippets** +4. **Test output (if applicable)** +5. **Environment information** (OS, Go version, etc.) diff --git a/.claude/docs/WORKFLOWS.md b/.claude/docs/WORKFLOWS.md new file mode 100644 index 0000000000000..8fc43002bba7d --- /dev/null +++ b/.claude/docs/WORKFLOWS.md @@ -0,0 +1,223 @@ +# Development Workflows and Guidelines + +## Quick Start Checklist for New Features + +### Before Starting + +- [ ] Run `git pull` to ensure you're on latest code +- [ ] Check if feature touches database - you'll need migrations +- [ ] Check if feature touches audit logs - update `enterprise/audit/table.go` + +## Development Server + +### Starting Development Mode + +- **Use `./scripts/develop.sh` to start Coder in development mode** +- This automatically builds and runs with `--dev` flag and proper access URL +- **⚠️ Do NOT manually run `make build && ./coder server --dev` - use the script instead** + +### Development Workflow + +1. **Always start with the development script**: `./scripts/develop.sh` +2. **Make changes** to your code +3. **The script will automatically rebuild** and restart as needed +4. **Access the development server** at the URL provided by the script + +## Code Style Guidelines + +### Go Style + +- Follow [Effective Go](https://go.dev/doc/effective_go) and [Go's Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments) +- Create packages when used during implementation +- Validate abstractions against implementations +- **Test packages**: Use `package_test` naming (e.g., `identityprovider_test`) for black-box testing + +### Error Handling + +- Use descriptive error messages +- Wrap errors with context +- Propagate errors appropriately +- Use proper error types +- Pattern: `xerrors.Errorf("failed to X: %w", err)` + +### Naming Conventions + +- Use clear, descriptive names +- Abbreviate only when obvious +- Follow Go and TypeScript naming conventions + +### Comments + +- Document exported functions, types, and non-obvious logic +- Follow JSDoc format for TypeScript +- Use godoc format for Go code + +## Database Migration Workflows + +### Migration Guidelines + +1. **Create migration files**: + - Location: `coderd/database/migrations/` + - Format: `{number}_{description}.{up|down}.sql` + - Number must be unique and sequential + - Always include both up and down migrations + +2. **Use helper scripts**: + - `./coderd/database/migrations/create_migration.sh "migration name"` - Creates new migration files + - `./coderd/database/migrations/fix_migration_numbers.sh` - Renumbers migrations to avoid conflicts + - `./coderd/database/migrations/create_fixture.sh "fixture name"` - Creates test fixtures for migrations + +3. **Update database queries**: + - **MUST DO**: Any changes to database - adding queries, modifying queries should be done in the `coderd/database/queries/*.sql` files + - **MUST DO**: Queries are grouped in files relating to context - e.g. `prebuilds.sql`, `users.sql`, `oauth2.sql` + - After making changes to any `coderd/database/queries/*.sql` files you must run `make gen` to generate respective ORM changes + +4. **Handle nullable fields**: + - Use `sql.NullString`, `sql.NullBool`, etc. for optional database fields + - Set `.Valid = true` when providing values + +5. **Audit table updates**: + - If adding fields to auditable types, update `enterprise/audit/table.go` + - Add each new field with appropriate action (ActionTrack, ActionIgnore, ActionSecret) + - Run `make gen` to verify no audit errors + +### Database Generation Process + +1. Modify SQL files in `coderd/database/queries/` +2. Run `make gen` +3. If errors about audit table, update `enterprise/audit/table.go` +4. Run `make gen` again +5. Run `make lint` to catch any remaining issues + +## API Development Workflow + +### Adding New API Endpoints + +1. **Define types** in `codersdk/` package +2. **Add handler** in appropriate `coderd/` file +3. **Register route** in `coderd/coderd.go` +4. **Add tests** in `coderd/*_test.go` files +5. **Update OpenAPI** by running `make gen` + +## Testing Workflows + +### Test Execution + +- Run full test suite: `make test` +- Run specific test: `make test RUN=TestFunctionName` +- Run with Postgres: `make test-postgres` +- Run with race detector: `make test-race` +- Run end-to-end tests: `make test-e2e` + +### Test Development + +- Use table-driven tests for comprehensive coverage +- Mock external dependencies +- Test both positive and negative cases +- Use `testutil.WaitLong` for timeouts in tests +- Always use `t.Parallel()` in tests + +## Commit Style + +- Follow [Conventional Commits 1.0.0](https://www.conventionalcommits.org/en/v1.0.0/) +- Format: `type(scope): message` +- Types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore` +- Keep message titles concise (~70 characters) +- Use imperative, present tense in commit titles + +## Code Navigation and Investigation + +### Using LSP Tools (STRONGLY RECOMMENDED) + +**IMPORTANT**: Always use LSP tools for code navigation and understanding. These tools provide accurate, real-time analysis of the codebase and should be your first choice for code investigation. + +#### Go LSP Tools (for backend code) + +1. **Find function definitions** (USE THIS FREQUENTLY): + - `mcp__go-language-server__definition symbolName` + - Example: `mcp__go-language-server__definition getOAuth2ProviderAppAuthorize` + - Quickly jump to function implementations across packages + +2. **Find symbol references** (ESSENTIAL FOR UNDERSTANDING IMPACT): + - `mcp__go-language-server__references symbolName` + - Locate all usages of functions, types, or variables + - Critical for refactoring and understanding data flow + +3. **Get symbol information**: + - `mcp__go-language-server__hover filePath line column` + - Get type information and documentation at specific positions + +#### TypeScript LSP Tools (for frontend code in site/) + +1. **Find component/function definitions** (USE THIS FREQUENTLY): + - `mcp__typescript-language-server__definition symbolName` + - Example: `mcp__typescript-language-server__definition LoginPage` + - Quickly navigate to React components, hooks, and utility functions + +2. **Find symbol references** (ESSENTIAL FOR UNDERSTANDING IMPACT): + - `mcp__typescript-language-server__references symbolName` + - Locate all usages of components, types, or functions + - Critical for refactoring React components and understanding prop usage + +3. **Get type information**: + - `mcp__typescript-language-server__hover filePath line column` + - Get TypeScript type information and JSDoc documentation + +4. **Rename symbols safely**: + - `mcp__typescript-language-server__rename_symbol filePath line column newName` + - Rename components, props, or functions across the entire codebase + +5. **Check for TypeScript errors**: + - `mcp__typescript-language-server__diagnostics filePath` + - Get compilation errors and warnings for a specific file + +### Investigation Strategy (LSP-First Approach) + +#### Backend Investigation (Go) + +1. **Start with route registration** in `coderd/coderd.go` to understand API endpoints +2. **Use Go LSP `definition` lookup** to trace from route handlers to actual implementations +3. **Use Go LSP `references`** to understand how functions are called throughout the codebase +4. **Follow the middleware chain** using LSP tools to understand request processing flow +5. **Check test files** for expected behavior and error patterns + +#### Frontend Investigation (TypeScript/React) + +1. **Start with route definitions** in `site/src/App.tsx` or router configuration +2. **Use TypeScript LSP `definition`** to navigate to React components and hooks +3. **Use TypeScript LSP `references`** to find all component usages and prop drilling +4. **Follow the component hierarchy** using LSP tools to understand data flow +5. **Check for TypeScript errors** with `diagnostics` before making changes +6. **Examine test files** (`.test.tsx`) for component behavior and expected props + +## Troubleshooting Development Issues + +### Common Issues + +1. **Development server won't start** - Use `./scripts/develop.sh` instead of manual commands +2. **Database migration errors** - Check migration file format and use helper scripts +3. **Audit table errors** - Update `enterprise/audit/table.go` with new fields +4. **OAuth2 compliance issues** - Ensure RFC-compliant error responses + +### Debug Commands + +- Check linting: `make lint` +- Generate code: `make gen` +- Clean build: `make clean` + +## Development Environment Setup + +### Prerequisites + +- Go (version specified in go.mod) +- Node.js and pnpm for frontend development +- PostgreSQL for database testing +- Docker for containerized testing + +### First Time Setup + +1. Clone the repository +2. Run `./scripts/develop.sh` to start development server +3. Access the development URL provided +4. Create admin user as prompted +5. Begin development diff --git a/.claude/scripts/format.sh b/.claude/scripts/format.sh new file mode 100755 index 0000000000000..4d57c8cf17368 --- /dev/null +++ b/.claude/scripts/format.sh @@ -0,0 +1,133 @@ +#!/bin/bash + +# Claude Code hook script for file formatting +# This script integrates with the centralized Makefile formatting targets +# and supports the Claude Code hooks system for automatic file formatting. + +set -euo pipefail + +# A variable to memoize the command for canonicalizing paths. +_CANONICALIZE_CMD="" + +# canonicalize_path resolves a path to its absolute, canonical form. +# It tries 'realpath' and 'readlink -f' in order. +# The chosen command is memoized to avoid repeated checks. +# If none of these are available, it returns an empty string. +canonicalize_path() { + local path_to_resolve="$1" + + # If we haven't determined a command yet, find one. + if [[ -z "$_CANONICALIZE_CMD" ]]; then + if command -v realpath >/dev/null 2>&1; then + _CANONICALIZE_CMD="realpath" + elif command -v readlink >/dev/null 2>&1 && readlink -f . >/dev/null 2>&1; then + _CANONICALIZE_CMD="readlink" + else + # No command found, so we can't resolve. + # We set a "none" value to prevent re-checking. + _CANONICALIZE_CMD="none" + fi + fi + + # Now, execute the command. + case "$_CANONICALIZE_CMD" in + realpath) + realpath "$path_to_resolve" 2>/dev/null + ;; + readlink) + readlink -f "$path_to_resolve" 2>/dev/null + ;; + *) + # This handles the "none" case or any unexpected error. + echo "" + ;; + esac +} + +# Read JSON input from stdin +input=$(cat) + +# Extract the file path from the JSON input +# Expected format: {"tool_input": {"file_path": "/absolute/path/to/file"}} or {"tool_response": {"filePath": "/absolute/path/to/file"}} +file_path=$(echo "$input" | jq -r '.tool_input.file_path // .tool_response.filePath // empty') + +# Secure path canonicalization to prevent path traversal attacks +# Resolve repo root to an absolute, canonical path. +repo_root_raw="$(cd "$(dirname "$0")/../.." && pwd)" +repo_root="$(canonicalize_path "$repo_root_raw")" +if [[ -z "$repo_root" ]]; then + # Fallback if canonicalization fails + repo_root="$repo_root_raw" +fi + +# Resolve the input path to an absolute path +if [[ "$file_path" = /* ]]; then + # Already absolute + abs_file_path="$file_path" +else + # Make relative paths absolute from repo root + abs_file_path="$repo_root/$file_path" +fi + +# Canonicalize the path (resolve symlinks and ".." segments) +canonical_file_path="$(canonicalize_path "$abs_file_path")" + +# Check if canonicalization failed or if the resolved path is outside the repo +if [[ -z "$canonical_file_path" ]] || { [[ "$canonical_file_path" != "$repo_root" ]] && [[ "$canonical_file_path" != "$repo_root"/* ]]; }; then + echo "Error: File path is outside repository or invalid: $file_path" >&2 + exit 1 +fi + +# Handle the case where the file path is the repository root itself. +if [[ "$canonical_file_path" == "$repo_root" ]]; then + echo "Warning: Formatting the repository root is not a supported operation. Skipping." >&2 + exit 0 +fi + +# Convert back to relative path from repo root for consistency +file_path="${canonical_file_path#"$repo_root"/}" + +if [[ -z "$file_path" ]]; then + echo "Error: No file path provided in input" >&2 + exit 1 +fi + +# Check if file exists +if [[ ! -f "$file_path" ]]; then + echo "Error: File does not exist: $file_path" >&2 + exit 1 +fi + +# Get the file extension to determine the appropriate formatter +file_ext="${file_path##*.}" + +# Change to the project root directory (where the Makefile is located) +cd "$(dirname "$0")/../.." + +# Call the appropriate Makefile target based on file extension +case "$file_ext" in +go) + make fmt/go FILE="$file_path" + echo "✓ Formatted Go file: $file_path" + ;; +js | jsx | ts | tsx) + make fmt/ts FILE="$file_path" + echo "✓ Formatted TypeScript/JavaScript file: $file_path" + ;; +tf | tfvars) + make fmt/terraform FILE="$file_path" + echo "✓ Formatted Terraform file: $file_path" + ;; +sh) + make fmt/shfmt FILE="$file_path" + echo "✓ Formatted shell script: $file_path" + ;; +md) + make fmt/markdown FILE="$file_path" + echo "✓ Formatted Markdown file: $file_path" + ;; +*) + echo "No formatter available for file extension: $file_ext" + exit 0 + ;; +esac diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000000000..a0753e0c11cd6 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Edit|Write|MultiEdit", + "hooks": [ + { + "type": "command", + "command": ".claude/scripts/format.sh" + } + ] + } + ] + } +} diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 0000000000000..03acfa4335995 --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,28 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json + +# CodeRabbit Configuration +# This configuration disables automatic reviews entirely + +language: "en-US" +early_access: false + +reviews: + # Disable automatic reviews for new PRs, but allow incremental reviews + auto_review: + enabled: false # Disable automatic review of new/updated PRs + drafts: false # Don't review draft PRs automatically + + # Other review settings (only apply if manually requested) + profile: "chill" + request_changes_workflow: false + high_level_summary: false + poem: false + review_status: false + collapse_walkthrough: true + high_level_summary_in_walkthrough: true + +chat: + auto_reply: true # Allow automatic chat replies + +# Note: With auto_review.enabled: false, CodeRabbit will only perform initial +# reviews when manually requested, but incremental reviews and chat replies remain enabled diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 907287634c2c4..591848bfb09dd 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,11 +1,16 @@ { "name": "Development environments on your infrastructure", "image": "codercom/oss-dogfood:latest", - "features": { - // See all possible options here https://github.com/devcontainers/features/tree/main/src/docker-in-docker "ghcr.io/devcontainers/features/docker-in-docker:2": { "moby": "false" + }, + "ghcr.io/coder/devcontainer-features/code-server:1": { + "auth": "none", + "port": 13337 + }, + "./filebrowser": { + "folder": "${containerWorkspaceFolder}" } }, // SYS_PTRACE to enable go debugging @@ -13,6 +18,65 @@ "customizations": { "vscode": { "extensions": ["biomejs.biome"] + }, + "coder": { + "apps": [ + { + "slug": "cursor", + "displayName": "Cursor Desktop", + "url": "cursor://coder.coder-remote/openDevContainer?owner=${localEnv:CODER_WORKSPACE_OWNER_NAME}&workspace=${localEnv:CODER_WORKSPACE_NAME}&agent=${localEnv:CODER_WORKSPACE_PARENT_AGENT_NAME}&url=${localEnv:CODER_URL}&token=$SESSION_TOKEN&devContainerName=${localEnv:CONTAINER_ID}&devContainerFolder=${containerWorkspaceFolder}&localWorkspaceFolder=${localWorkspaceFolder}", + "external": true, + "icon": "/icon/cursor.svg", + "order": 1 + }, + { + "slug": "windsurf", + "displayName": "Windsurf Editor", + "url": "windsurf://coder.coder-remote/openDevContainer?owner=${localEnv:CODER_WORKSPACE_OWNER_NAME}&workspace=${localEnv:CODER_WORKSPACE_NAME}&agent=${localEnv:CODER_WORKSPACE_PARENT_AGENT_NAME}&url=${localEnv:CODER_URL}&token=$SESSION_TOKEN&devContainerName=${localEnv:CONTAINER_ID}&devContainerFolder=${containerWorkspaceFolder}&localWorkspaceFolder=${localWorkspaceFolder}", + "external": true, + "icon": "/icon/windsurf.svg", + "order": 4 + }, + { + "slug": "zed", + "displayName": "Zed Editor", + "url": "zed://ssh/${localEnv:CODER_WORKSPACE_AGENT_NAME}.${localEnv:CODER_WORKSPACE_NAME}.${localEnv:CODER_WORKSPACE_OWNER_NAME}.coder${containerWorkspaceFolder}", + "external": true, + "icon": "/icon/zed.svg", + "order": 5 + }, + // Reproduce `code-server` app here from the code-server + // feature so that we can set the correct folder and order. + // Currently, the order cannot be specified via option because + // we parse it as a number whereas variable interpolation + // results in a string. Additionally we set health check which + // is not yet set in the feature. + { + "slug": "code-server", + "displayName": "code-server", + "url": "http://${localEnv:FEATURE_CODE_SERVER_OPTION_HOST:127.0.0.1}:${localEnv:FEATURE_CODE_SERVER_OPTION_PORT:8080}/?folder=${containerWorkspaceFolder}", + "openIn": "${localEnv:FEATURE_CODE_SERVER_OPTION_APPOPENIN:slim-window}", + "share": "${localEnv:FEATURE_CODE_SERVER_OPTION_APPSHARE:owner}", + "icon": "/icon/code.svg", + "group": "${localEnv:FEATURE_CODE_SERVER_OPTION_APPGROUP:Web Editors}", + "order": 3, + "healthCheck": { + "url": "http://${localEnv:FEATURE_CODE_SERVER_OPTION_HOST:127.0.0.1}:${localEnv:FEATURE_CODE_SERVER_OPTION_PORT:8080}/healthz", + "interval": 5, + "threshold": 2 + } + } + ] } - } + }, + "mounts": [ + // Add a volume for the Coder home directory to persist shell history, + // and speed up dotfiles init and/or personalization. + "source=coder-coder-devcontainer-home,target=/home/coder,type=volume", + // Mount the entire home because conditional mounts are not supported. + // See: https://github.com/devcontainers/spec/issues/132 + "source=${localEnv:HOME},target=/mnt/home/coder,type=bind,readonly" + ], + "postCreateCommand": ["./.devcontainer/scripts/post_create.sh"], + "postStartCommand": ["./.devcontainer/scripts/post_start.sh"] } diff --git a/.devcontainer/filebrowser/devcontainer-feature.json b/.devcontainer/filebrowser/devcontainer-feature.json new file mode 100644 index 0000000000000..c7a55a0d8a14e --- /dev/null +++ b/.devcontainer/filebrowser/devcontainer-feature.json @@ -0,0 +1,46 @@ +{ + "id": "filebrowser", + "version": "0.0.1", + "name": "File Browser", + "description": "A web-based file browser for your development container", + "options": { + "port": { + "type": "string", + "default": "13339", + "description": "The port to run filebrowser on" + }, + "folder": { + "type": "string", + "default": "", + "description": "The root directory for filebrowser to serve" + }, + "baseUrl": { + "type": "string", + "default": "", + "description": "The base URL for filebrowser (e.g., /filebrowser)" + } + }, + "entrypoint": "/usr/local/bin/filebrowser-entrypoint", + "dependsOn": { + "ghcr.io/devcontainers/features/common-utils:2": {} + }, + "customizations": { + "coder": { + "apps": [ + { + "slug": "filebrowser", + "displayName": "File Browser", + "url": "http://localhost:${localEnv:FEATURE_FILEBROWSER_OPTION_PORT:13339}", + "icon": "/icon/filebrowser.svg", + "order": 3, + "subdomain": true, + "healthcheck": { + "url": "http://localhost:${localEnv:FEATURE_FILEBROWSER_OPTION_PORT:13339}/health", + "interval": 5, + "threshold": 2 + } + } + ] + } + } +} diff --git a/.devcontainer/filebrowser/install.sh b/.devcontainer/filebrowser/install.sh new file mode 100644 index 0000000000000..48158a38cd782 --- /dev/null +++ b/.devcontainer/filebrowser/install.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash + +set -euo pipefail + +BOLD='\033[0;1m' + +printf "%sInstalling filebrowser\n\n" "${BOLD}" + +# Check if filebrowser is installed. +if ! command -v filebrowser &>/dev/null; then + curl -fsSL https://raw.githubusercontent.com/filebrowser/get/master/get.sh | bash +fi + +# Create entrypoint. +cat >/usr/local/bin/filebrowser-entrypoint <>\${LOG_PATH} 2>&1 + filebrowser users add admin "" --perm.admin=true --viewMode=mosaic >>\${LOG_PATH} 2>&1 +fi + +filebrowser config set --baseurl=\${BASEURL} --port=\${PORT} --auth.method=noauth --root=\${FOLDER} >>\${LOG_PATH} 2>&1 + +printf "👷 Starting filebrowser...\n\n" + +printf "📂 Serving \${FOLDER} at http://localhost:\${PORT}\n\n" + +filebrowser >>\${LOG_PATH} 2>&1 & + +printf "📝 Logs at \${LOG_PATH}\n\n" +EOF + +chmod +x /usr/local/bin/filebrowser-entrypoint + +printf "🥳 Installation complete!\n\n" diff --git a/.devcontainer/scripts/post_create.sh b/.devcontainer/scripts/post_create.sh new file mode 100755 index 0000000000000..8799908311431 --- /dev/null +++ b/.devcontainer/scripts/post_create.sh @@ -0,0 +1,59 @@ +#!/bin/sh + +install_devcontainer_cli() { + npm install -g @devcontainers/cli +} + +install_ssh_config() { + echo "🔑 Installing SSH configuration..." + rsync -a /mnt/home/coder/.ssh/ ~/.ssh/ + chmod 0700 ~/.ssh +} + +install_git_config() { + echo "📂 Installing Git configuration..." + if [ -f /mnt/home/coder/git/config ]; then + rsync -a /mnt/home/coder/git/ ~/.config/git/ + elif [ -d /mnt/home/coder/.gitconfig ]; then + rsync -a /mnt/home/coder/.gitconfig ~/.gitconfig + else + echo "⚠️ Git configuration directory not found." + fi +} + +install_dotfiles() { + if [ ! -d /mnt/home/coder/.config/coderv2/dotfiles ]; then + echo "⚠️ Dotfiles directory not found." + return + fi + + cd /mnt/home/coder/.config/coderv2/dotfiles || return + for script in install.sh install bootstrap.sh bootstrap script/bootstrap setup.sh setup script/setup; do + if [ -x $script ]; then + echo "📦 Installing dotfiles..." + ./$script || { + echo "❌ Error running $script. Please check the script for issues." + return + } + echo "✅ Dotfiles installed successfully." + return + fi + done + echo "⚠️ No install script found in dotfiles directory." +} + +personalize() { + # Allow script to continue as Coder dogfood utilizes a hack to + # synchronize startup script execution. + touch /tmp/.coder-startup-script.done + + if [ -x /mnt/home/coder/personalize ]; then + echo "🎨 Personalizing environment..." + /mnt/home/coder/personalize + fi +} + +install_devcontainer_cli +install_ssh_config +install_dotfiles +personalize diff --git a/.devcontainer/scripts/post_start.sh b/.devcontainer/scripts/post_start.sh new file mode 100755 index 0000000000000..c98674037d353 --- /dev/null +++ b/.devcontainer/scripts/post_start.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +# Start Docker service if not already running. +sudo service docker start diff --git a/.gitattributes b/.gitattributes index 1da452829a70a..ed396ce0044eb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -15,6 +15,8 @@ provisionersdk/proto/*.go linguist-generated=true *.tfstate.json linguist-generated=true *.tfstate.dot linguist-generated=true *.tfplan.dot linguist-generated=true +site/e2e/google/protobuf/timestampGenerated.ts site/e2e/provisionerGenerated.ts linguist-generated=true +site/src/api/countriesGenerated.tsx linguist-generated=true +site/src/api/rbacresourcesGenerated.tsx linguist-generated=true site/src/api/typesGenerated.ts linguist-generated=true -site/src/pages/SetupPage/countries.tsx linguist-generated=true diff --git a/.github/.linkspector.yml b/.github/.linkspector.yml index 1bbf60c200175..f5f99caf57708 100644 --- a/.github/.linkspector.yml +++ b/.github/.linkspector.yml @@ -25,5 +25,6 @@ ignorePatterns: - pattern: "docs.github.com" - pattern: "claude.ai" - pattern: "splunk.com" + - pattern: "stackoverflow.com/questions" aliveStatusCodes: - 200 diff --git a/.github/actions/embedded-pg-cache/download/action.yml b/.github/actions/embedded-pg-cache/download/action.yml new file mode 100644 index 0000000000000..c2c3c0c0b299c --- /dev/null +++ b/.github/actions/embedded-pg-cache/download/action.yml @@ -0,0 +1,47 @@ +name: "Download Embedded Postgres Cache" +description: | + Downloads the embedded postgres cache and outputs today's cache key. + A PR job can use a cache if it was created by its base branch, its current + branch, or the default branch. + https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/caching-dependencies-to-speed-up-workflows#restrictions-for-accessing-a-cache +outputs: + cache-key: + description: "Today's cache key" + value: ${{ steps.vars.outputs.cache-key }} +inputs: + key-prefix: + description: "Prefix for the cache key" + required: true + cache-path: + description: "Path to the cache directory" + required: true +runs: + using: "composite" + steps: + - name: Get date values and cache key + id: vars + shell: bash + run: | + export YEAR_MONTH=$(date +'%Y-%m') + export PREV_YEAR_MONTH=$(date -d 'last month' +'%Y-%m') + export DAY=$(date +'%d') + echo "year-month=$YEAR_MONTH" >> $GITHUB_OUTPUT + echo "prev-year-month=$PREV_YEAR_MONTH" >> $GITHUB_OUTPUT + echo "cache-key=${{ inputs.key-prefix }}-${YEAR_MONTH}-${DAY}" >> $GITHUB_OUTPUT + + # By default, depot keeps caches for 14 days. This is plenty for embedded + # postgres, which changes infrequently. + # https://depot.dev/docs/github-actions/overview#cache-retention-policy + - name: Download embedded Postgres cache + uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3 + with: + path: ${{ inputs.cache-path }} + key: ${{ steps.vars.outputs.cache-key }} + # > If there are multiple partial matches for a restore key, the action returns the most recently created cache. + # https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/caching-dependencies-to-speed-up-workflows#matching-a-cache-key + # The second restore key allows non-main branches to use the cache from the previous month. + # This prevents PRs from rebuilding the cache on the first day of the month. + # It also makes sure that once a month, the cache is fully reset. + restore-keys: | + ${{ inputs.key-prefix }}-${{ steps.vars.outputs.year-month }}- + ${{ github.ref != 'refs/heads/main' && format('{0}-{1}-', inputs.key-prefix, steps.vars.outputs.prev-year-month) || '' }} diff --git a/.github/actions/embedded-pg-cache/upload/action.yml b/.github/actions/embedded-pg-cache/upload/action.yml new file mode 100644 index 0000000000000..19b37bb65665b --- /dev/null +++ b/.github/actions/embedded-pg-cache/upload/action.yml @@ -0,0 +1,18 @@ +name: "Upload Embedded Postgres Cache" +description: Uploads the embedded Postgres cache. This only runs on the main branch. +inputs: + cache-key: + description: "Cache key" + required: true + cache-path: + description: "Path to the cache directory" + required: true +runs: + using: "composite" + steps: + - name: Upload Embedded Postgres cache + if: ${{ github.ref == 'refs/heads/main' }} + uses: actions/cache/save@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3 + with: + path: ${{ inputs.cache-path }} + key: ${{ inputs.cache-key }} diff --git a/.github/actions/setup-embedded-pg-cache-paths/action.yml b/.github/actions/setup-embedded-pg-cache-paths/action.yml new file mode 100644 index 0000000000000..019ff4e6dc746 --- /dev/null +++ b/.github/actions/setup-embedded-pg-cache-paths/action.yml @@ -0,0 +1,33 @@ +name: "Setup Embedded Postgres Cache Paths" +description: Sets up a path for cached embedded postgres binaries. +outputs: + embedded-pg-cache: + description: "Value of EMBEDDED_PG_CACHE_DIR" + value: ${{ steps.paths.outputs.embedded-pg-cache }} + cached-dirs: + description: "directories that should be cached between CI runs" + value: ${{ steps.paths.outputs.cached-dirs }} +runs: + using: "composite" + steps: + - name: Override Go paths + id: paths + uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7 + with: + script: | + const path = require('path'); + + // RUNNER_TEMP should be backed by a RAM disk on Windows if + // coder/setup-ramdisk-action was used + const runnerTemp = process.env.RUNNER_TEMP; + const embeddedPgCacheDir = path.join(runnerTemp, 'embedded-pg-cache'); + core.exportVariable('EMBEDDED_PG_CACHE_DIR', embeddedPgCacheDir); + core.setOutput('embedded-pg-cache', embeddedPgCacheDir); + const cachedDirs = `${embeddedPgCacheDir}`; + core.setOutput('cached-dirs', cachedDirs); + + - name: Create directories + shell: bash + run: | + set -e + mkdir -p "$EMBEDDED_PG_CACHE_DIR" diff --git a/.github/actions/setup-go/action.yaml b/.github/actions/setup-go/action.yaml index a8a88621dda18..097a1b6cfd119 100644 --- a/.github/actions/setup-go/action.yaml +++ b/.github/actions/setup-go/action.yaml @@ -4,7 +4,7 @@ description: | inputs: version: description: "The Go version to use." - default: "1.24.4" + default: "1.24.6" use-preinstalled-go: description: "Whether to use preinstalled Go." default: "false" diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index b0a27b2db4de7..fbc34b0dfb6ec 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -34,7 +34,7 @@ jobs: tailnet-integration: ${{ steps.filter.outputs.tailnet-integration }} steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -154,7 +154,7 @@ jobs: runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }} steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -187,7 +187,7 @@ jobs: # Check for any typos - name: Check for typos - uses: crate-ci/typos@b1ae8d918b6e85bd611117d3d9a3be4f903ee5e4 # v1.33.1 + uses: crate-ci/typos@392b78fe18a52790c53f42456e46124f77346842 # v1.34.0 with: config: .github/workflows/typos.toml @@ -226,7 +226,7 @@ jobs: if: ${{ !cancelled() }} steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -281,7 +281,7 @@ jobs: timeout-minutes: 7 steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -311,94 +311,6 @@ jobs: - name: Check for unstaged files run: ./scripts/check_unstaged.sh - test-go: - runs-on: ${{ matrix.os == 'ubuntu-latest' && github.repository_owner == 'coder' && 'depot-ubuntu-22.04-4' || matrix.os == 'macos-latest' && github.repository_owner == 'coder' && 'depot-macos-latest' || matrix.os == 'windows-2022' && github.repository_owner == 'coder' && 'depot-windows-2022-16' || matrix.os }} - needs: changes - if: needs.changes.outputs.go == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main' - timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - os: - - ubuntu-latest - - macos-latest - - windows-2022 - steps: - - name: Harden Runner - # Harden Runner is only supported on Ubuntu runners. - if: runner.os == 'Linux' - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 - with: - egress-policy: audit - - # Set up RAM disks to speed up the rest of the job. This action is in - # a separate repository to allow its use before actions/checkout. - - name: Setup RAM Disks - if: runner.os == 'Windows' - uses: coder/setup-ramdisk-action@e1100847ab2d7bcd9d14bcda8f2d1b0f07b36f1b - - - name: Checkout - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - with: - fetch-depth: 1 - - - name: Setup Go Paths - uses: ./.github/actions/setup-go-paths - - - name: Setup Go - uses: ./.github/actions/setup-go - with: - # Runners have Go baked-in and Go will automatically - # download the toolchain configured in go.mod, so we don't - # need to reinstall it. It's faster on Windows runners. - use-preinstalled-go: ${{ runner.os == 'Windows' }} - - - name: Setup Terraform - uses: ./.github/actions/setup-tf - - - name: Download Test Cache - id: download-cache - uses: ./.github/actions/test-cache/download - with: - key-prefix: test-go-${{ runner.os }}-${{ runner.arch }} - - - name: Test with Mock Database - id: test - shell: bash - run: | - # if macOS, install google-chrome for scaletests. As another concern, - # should we really have this kind of external dependency requirement - # on standard CI? - if [ "${{ matrix.os }}" == "macos-latest" ]; then - brew install google-chrome - fi - - # By default Go will use the number of logical CPUs, which - # is a fine default. - PARALLEL_FLAG="" - - # macOS will output "The default interactive shell is now zsh" - # intermittently in CI... - if [ "${{ matrix.os }}" == "macos-latest" ]; then - touch ~/.bash_profile && echo "export BASH_SILENCE_DEPRECATION_WARNING=1" >> ~/.bash_profile - fi - export TS_DEBUG_DISCO=true - gotestsum --junitfile="gotests.xml" --jsonfile="gotests.json" --rerun-fails=2 \ - --packages="./..." -- $PARALLEL_FLAG -short - - - name: Upload Test Cache - uses: ./.github/actions/test-cache/upload - with: - cache-key: ${{ steps.download-cache.outputs.cache-key }} - - - name: Upload test stats to Datadog - timeout-minutes: 1 - continue-on-error: true - uses: ./.github/actions/upload-datadog - if: success() || failure() - with: - api-key: ${{ secrets.DATADOG_API_KEY }} - test-go-pg: # make sure to adjust NUM_PARALLEL_PACKAGES and NUM_PARALLEL_TESTS below # when changing runner sizes @@ -418,7 +330,7 @@ jobs: - windows-2022 steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -428,6 +340,11 @@ jobs: - name: Disable Spotlight Indexing if: runner.os == 'macOS' run: | + enabled=$(sudo mdutil -a -s | grep "Indexing enabled" | wc -l) + if [ $enabled -eq 0 ]; then + echo "Spotlight indexing is already disabled" + exit 0 + fi sudo mdutil -a -i off sudo mdutil -X / sudo launchctl bootout system /System/Library/LaunchDaemons/com.apple.metadata.mds.plist @@ -473,6 +390,17 @@ jobs: with: key-prefix: test-go-pg-${{ runner.os }}-${{ runner.arch }} + - name: Setup Embedded Postgres Cache Paths + id: embedded-pg-cache + uses: ./.github/actions/setup-embedded-pg-cache-paths + + - name: Download Embedded Postgres Cache + id: download-embedded-pg-cache + uses: ./.github/actions/embedded-pg-cache/download + with: + key-prefix: embedded-pg-${{ runner.os }}-${{ runner.arch }} + cache-path: ${{ steps.embedded-pg-cache.outputs.cached-dirs }} + - name: Normalize File and Directory Timestamps shell: bash # Normalize file modification timestamps so that go test can use the @@ -497,12 +425,12 @@ jobs: # Create a temp dir on the R: ramdisk drive for Windows. The default # C: drive is extremely slow: https://github.com/actions/runner-images/issues/8755 mkdir -p "R:/temp/embedded-pg" - go run scripts/embedded-pg/main.go -path "R:/temp/embedded-pg" + go run scripts/embedded-pg/main.go -path "R:/temp/embedded-pg" -cache "${EMBEDDED_PG_CACHE_DIR}" elif [ "${{ runner.os }}" == "macOS" ]; then # Postgres runs faster on a ramdisk on macOS too mkdir -p /tmp/tmpfs sudo mount_tmpfs -o noowners -s 8g /tmp/tmpfs - go run scripts/embedded-pg/main.go -path /tmp/tmpfs/embedded-pg + go run scripts/embedded-pg/main.go -path /tmp/tmpfs/embedded-pg -cache "${EMBEDDED_PG_CACHE_DIR}" elif [ "${{ runner.os }}" == "Linux" ]; then make test-postgres-docker fi @@ -528,16 +456,21 @@ jobs: # Postgres tends not to choke. NUM_PARALLEL_PACKAGES=8 NUM_PARALLEL_TESTS=16 + # Only the CLI and Agent are officially supported on Windows and the rest are too flaky + PACKAGES="./cli/... ./enterprise/cli/... ./agent/..." elif [ "${{ runner.os }}" == "macOS" ]; then # Our macOS runners have 8 cores. We set NUM_PARALLEL_TESTS to 16 # because the tests complete faster and Postgres doesn't choke. It seems # that macOS's tmpfs is faster than the one on Windows. NUM_PARALLEL_PACKAGES=8 NUM_PARALLEL_TESTS=16 + # Only the CLI and Agent are officially supported on macOS and the rest are too flaky + PACKAGES="./cli/... ./enterprise/cli/... ./agent/..." elif [ "${{ runner.os }}" == "Linux" ]; then # Our Linux runners have 8 cores. NUM_PARALLEL_PACKAGES=8 NUM_PARALLEL_TESTS=8 + PACKAGES="./..." fi # by default, run tests with cache @@ -554,10 +487,7 @@ jobs: # invalidated. See scripts/normalize_path.sh for more details. normalize_path_with_symlinks "$RUNNER_TEMP/sym" "$(dirname $(which terraform))" - # We rerun failing tests to counteract flakiness coming from Postgres - # choking on macOS and Windows sometimes. - DB=ci gotestsum --rerun-fails=2 --rerun-fails-max-failures=50 \ - --format standard-quiet --packages "./..." \ + gotestsum --format standard-quiet --packages "$PACKAGES" \ -- -timeout=20m -v -p $NUM_PARALLEL_PACKAGES -parallel=$NUM_PARALLEL_TESTS $TESTCOUNT - name: Upload Go Build Cache @@ -571,6 +501,14 @@ jobs: with: cache-key: ${{ steps.download-cache.outputs.cache-key }} + - name: Upload Embedded Postgres Cache + uses: ./.github/actions/embedded-pg-cache/upload + # We only use the embedded Postgres cache on macOS and Windows runners. + if: runner.OS == 'macOS' || runner.OS == 'Windows' + with: + cache-key: ${{ steps.download-embedded-pg-cache.outputs.cache-key }} + cache-path: "${{ steps.embedded-pg-cache.outputs.embedded-pg-cache }}" + - name: Upload test stats to Datadog timeout-minutes: 1 continue-on-error: true @@ -594,7 +532,7 @@ jobs: timeout-minutes: 25 steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -619,7 +557,6 @@ jobs: env: POSTGRES_VERSION: "17" TS_DEBUG_DISCO: "true" - TEST_RETRIES: 2 run: | make test-postgres @@ -636,55 +573,6 @@ jobs: with: api-key: ${{ secrets.DATADOG_API_KEY }} - test-go-race: - runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-16' || 'ubuntu-latest' }} - needs: changes - if: needs.changes.outputs.go == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main' - timeout-minutes: 25 - steps: - - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 - with: - egress-policy: audit - - - name: Checkout - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - with: - fetch-depth: 1 - - - name: Setup Go - uses: ./.github/actions/setup-go - - - name: Setup Terraform - uses: ./.github/actions/setup-tf - - - name: Download Test Cache - id: download-cache - uses: ./.github/actions/test-cache/download - with: - key-prefix: test-go-race-${{ runner.os }}-${{ runner.arch }} - - # We run race tests with reduced parallelism because they use more CPU and we were finding - # instances where tests appear to hang for multiple seconds, resulting in flaky tests when - # short timeouts are used. - # c.f. discussion on https://github.com/coder/coder/pull/15106 - - name: Run Tests - run: | - gotestsum --junitfile="gotests.xml" --packages="./..." --rerun-fails=2 --rerun-fails-abort-on-data-race -- -race -parallel 4 -p 4 - - - name: Upload Test Cache - uses: ./.github/actions/test-cache/upload - with: - cache-key: ${{ steps.download-cache.outputs.cache-key }} - - - name: Upload test stats to Datadog - timeout-minutes: 1 - continue-on-error: true - uses: ./.github/actions/upload-datadog - if: always() - with: - api-key: ${{ secrets.DATADOG_API_KEY }} - test-go-race-pg: runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-16' || 'ubuntu-latest' }} needs: changes @@ -692,7 +580,7 @@ jobs: timeout-minutes: 25 steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -722,7 +610,7 @@ jobs: POSTGRES_VERSION: "17" run: | make test-postgres-docker - DB=ci gotestsum --junitfile="gotests.xml" --packages="./..." --rerun-fails=2 --rerun-fails-abort-on-data-race -- -race -parallel 4 -p 4 + gotestsum --junitfile="gotests.xml" --packages="./..." -- -race -parallel 4 -p 4 - name: Upload Test Cache uses: ./.github/actions/test-cache/upload @@ -751,7 +639,7 @@ jobs: timeout-minutes: 20 steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -777,7 +665,7 @@ jobs: timeout-minutes: 20 steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -809,7 +697,7 @@ jobs: name: ${{ matrix.variant.name }} steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -844,7 +732,6 @@ jobs: if: ${{ !matrix.variant.premium }} env: DEBUG: pw:api - CODER_E2E_TEST_RETRIES: 2 working-directory: site # Run all of the tests with a premium license @@ -854,7 +741,6 @@ jobs: DEBUG: pw:api CODER_E2E_LICENSE: ${{ secrets.CODER_E2E_LICENSE }} CODER_E2E_REQUIRE_PREMIUM_TESTS: "1" - CODER_E2E_TEST_RETRIES: 2 working-directory: site - name: Upload Playwright Failed Tests @@ -882,7 +768,7 @@ jobs: if: needs.changes.outputs.site == 'true' || needs.changes.outputs.ci == 'true' steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -902,7 +788,7 @@ jobs: # the check to pass. This is desired in PRs, but not in mainline. - name: Publish to Chromatic (non-mainline) if: github.ref != 'refs/heads/main' && github.repository_owner == 'coder' - uses: chromaui/action@b5848056bb67ce5f1cccca8e62a37cbd9dd42871 # v13.0.1 + uses: chromaui/action@4d8ebd13658d795114f8051e25c28d66f14886c6 # v13.1.2 env: NODE_OPTIONS: "--max_old_space_size=4096" STORYBOOK: true @@ -934,7 +820,7 @@ jobs: # infinitely "in progress" in mainline unless we re-review each build. - name: Publish to Chromatic (mainline) if: github.ref == 'refs/heads/main' && github.repository_owner == 'coder' - uses: chromaui/action@b5848056bb67ce5f1cccca8e62a37cbd9dd42871 # v13.0.1 + uses: chromaui/action@4d8ebd13658d795114f8051e25c28d66f14886c6 # v13.1.2 env: NODE_OPTIONS: "--max_old_space_size=4096" STORYBOOK: true @@ -962,7 +848,7 @@ jobs: steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -1018,9 +904,7 @@ jobs: - fmt - lint - gen - - test-go - test-go-pg - - test-go-race - test-go-race-pg - test-js - test-e2e @@ -1031,7 +915,7 @@ jobs: if: always() steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -1041,9 +925,7 @@ jobs: echo "- fmt: ${{ needs.fmt.result }}" echo "- lint: ${{ needs.lint.result }}" echo "- gen: ${{ needs.gen.result }}" - echo "- test-go: ${{ needs.test-go.result }}" echo "- test-go-pg: ${{ needs.test-go-pg.result }}" - echo "- test-go-race: ${{ needs.test-go-race.result }}" echo "- test-go-race-pg: ${{ needs.test-go-race-pg.result }}" echo "- test-js: ${{ needs.test-js.result }}" echo "- test-e2e: ${{ needs.test-e2e.result }}" @@ -1082,7 +964,7 @@ jobs: - name: Switch XCode Version uses: maxim-lobanov/setup-xcode@60606e260d2fc5762a71e64e74b2174e8ea3c8bd # v1.6.0 with: - xcode-version: "16.0.0" + xcode-version: "16.1.0" - name: Setup Go uses: ./.github/actions/setup-go @@ -1161,7 +1043,7 @@ jobs: IMAGE: ghcr.io/coder/coder-preview:${{ steps.build-docker.outputs.tag }} steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -1183,6 +1065,27 @@ jobs: - name: Setup Go uses: ./.github/actions/setup-go + - name: Install rcodesign + run: | + set -euo pipefail + wget -O /tmp/rcodesign.tar.gz https://github.com/indygreg/apple-platform-rs/releases/download/apple-codesign%2F0.22.0/apple-codesign-0.22.0-x86_64-unknown-linux-musl.tar.gz + sudo tar -xzf /tmp/rcodesign.tar.gz \ + -C /usr/bin \ + --strip-components=1 \ + apple-codesign-0.22.0-x86_64-unknown-linux-musl/rcodesign + rm /tmp/rcodesign.tar.gz + + - name: Setup Apple Developer certificate + run: | + set -euo pipefail + touch /tmp/{apple_cert.p12,apple_cert_password.txt} + chmod 600 /tmp/{apple_cert.p12,apple_cert_password.txt} + echo "$AC_CERTIFICATE_P12_BASE64" | base64 -d > /tmp/apple_cert.p12 + echo "$AC_CERTIFICATE_PASSWORD" > /tmp/apple_cert_password.txt + env: + AC_CERTIFICATE_P12_BASE64: ${{ secrets.AC_CERTIFICATE_P12_BASE64 }} + AC_CERTIFICATE_PASSWORD: ${{ secrets.AC_CERTIFICATE_PASSWORD }} + # Necessary for signing Windows binaries. - name: Setup Java uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1 @@ -1218,14 +1121,14 @@ jobs: # Setup GCloud for signing Windows binaries. - name: Authenticate to Google Cloud id: gcloud_auth - uses: google-github-actions/auth@ba79af03959ebeac9769e648f473a284504d9193 # v2.1.10 + uses: google-github-actions/auth@140bb5113ffb6b65a7e9b937a81fa96cf5064462 # v2.1.11 with: workload_identity_provider: ${{ secrets.GCP_CODE_SIGNING_WORKLOAD_ID_PROVIDER }} service_account: ${{ secrets.GCP_CODE_SIGNING_SERVICE_ACCOUNT }} token_format: "access_token" - name: Setup GCloud SDK - uses: google-github-actions/setup-gcloud@77e7a554d41e2ee56fc945c52dfd3f33d12def9a # v2.1.4 + uses: google-github-actions/setup-gcloud@6a7c903a70c8625ed6700fa299f5ddb4ca6022e9 # v2.1.5 - name: Download dylibs uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 @@ -1259,6 +1162,11 @@ jobs: # do (see above). CODER_SIGN_WINDOWS: "1" CODER_WINDOWS_RESOURCES: "1" + CODER_SIGN_GPG: "1" + CODER_GPG_RELEASE_KEY_BASE64: ${{ secrets.GPG_RELEASE_KEY_BASE64 }} + CODER_SIGN_DARWIN: "1" + AC_CERTIFICATE_FILE: /tmp/apple_cert.p12 + AC_CERTIFICATE_PASSWORD_FILE: /tmp/apple_cert_password.txt EV_KEY: ${{ secrets.EV_KEY }} EV_KEYSTORE: ${{ secrets.EV_KEYSTORE }} EV_TSA_URL: ${{ secrets.EV_TSA_URL }} @@ -1507,7 +1415,7 @@ jobs: id-token: write steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -1517,22 +1425,22 @@ jobs: fetch-depth: 0 - name: Authenticate to Google Cloud - uses: google-github-actions/auth@ba79af03959ebeac9769e648f473a284504d9193 # v2.1.10 + uses: google-github-actions/auth@140bb5113ffb6b65a7e9b937a81fa96cf5064462 # v2.1.11 with: workload_identity_provider: projects/573722524737/locations/global/workloadIdentityPools/github/providers/github service_account: coder-ci@coder-dogfood.iam.gserviceaccount.com - name: Set up Google Cloud SDK - uses: google-github-actions/setup-gcloud@77e7a554d41e2ee56fc945c52dfd3f33d12def9a # v2.1.4 + uses: google-github-actions/setup-gcloud@6a7c903a70c8625ed6700fa299f5ddb4ca6022e9 # v2.1.5 - name: Set up Flux CLI - uses: fluxcd/flux2/action@a48f81a66c4ca9fbd993233ab99dd03a7cfbe09a # v2.6.2 + uses: fluxcd/flux2/action@6bf37f6a560fd84982d67f853162e4b3c2235edb # v2.6.4 with: # Keep this and the github action up to date with the version of flux installed in dogfood cluster version: "2.5.1" - name: Get Cluster Credentials - uses: google-github-actions/get-gke-credentials@d0cee45012069b163a631894b98904a9e6723729 # v2.3.3 + uses: google-github-actions/get-gke-credentials@8e574c49425fa7efed1e74650a449bfa6a23308a # v2.3.4 with: cluster_name: dogfood-v2 location: us-central1-a @@ -1571,7 +1479,7 @@ jobs: if: github.ref == 'refs/heads/main' && !github.event.pull_request.head.repo.fork steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -1606,7 +1514,7 @@ jobs: if: needs.changes.outputs.db == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main' steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit diff --git a/.github/workflows/docker-base.yaml b/.github/workflows/docker-base.yaml index f74e71ba2909b..bb45d4c0a0601 100644 --- a/.github/workflows/docker-base.yaml +++ b/.github/workflows/docker-base.yaml @@ -38,7 +38,7 @@ jobs: if: github.repository_owner == 'coder' steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit diff --git a/.github/workflows/docs-ci.yaml b/.github/workflows/docs-ci.yaml index 30ac97706d9f8..39954783f1ba8 100644 --- a/.github/workflows/docs-ci.yaml +++ b/.github/workflows/docs-ci.yaml @@ -28,7 +28,7 @@ jobs: - name: Setup Node uses: ./.github/actions/setup-node - - uses: tj-actions/changed-files@666c9d29007687c52e3c7aa2aac6c0ffcadeadc3 # v45.0.7 + - uses: tj-actions/changed-files@055970845dd036d7345da7399b7e89f2e10f2b04 # v45.0.7 id: changed-files with: files: | diff --git a/.github/workflows/dogfood.yaml b/.github/workflows/dogfood.yaml index b5b2447bd44bf..bafdb5fb19767 100644 --- a/.github/workflows/dogfood.yaml +++ b/.github/workflows/dogfood.yaml @@ -27,7 +27,7 @@ jobs: runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-4' || 'ubuntu-latest' }} steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -35,7 +35,11 @@ jobs: uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Setup Nix - uses: nixbuild/nix-quick-install-action@889f3180bb5f064ee9e3201428d04ae9e41d54ad # v31 + uses: nixbuild/nix-quick-install-action@63ca48f939ee3b8d835f4126562537df0fee5b91 # v32 + with: + # Pinning to 2.28 here, as Nix gets a "error: [json.exception.type_error.302] type must be array, but is string" + # on version 2.29 and above. + nix_version: "2.28.4" - uses: nix-community/cache-nix-action@135667ec418502fa5a3598af6fb9eb733888ce6a # v6.1.3 with: @@ -114,7 +118,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -125,7 +129,7 @@ jobs: uses: ./.github/actions/setup-tf - name: Authenticate to Google Cloud - uses: google-github-actions/auth@ba79af03959ebeac9769e648f473a284504d9193 # v2.1.10 + uses: google-github-actions/auth@140bb5113ffb6b65a7e9b937a81fa96cf5064462 # v2.1.11 with: workload_identity_provider: projects/573722524737/locations/global/workloadIdentityPools/github/providers/github service_account: coder-ci@coder-dogfood.iam.gserviceaccount.com diff --git a/.github/workflows/nightly-gauntlet.yaml b/.github/workflows/nightly-gauntlet.yaml new file mode 100644 index 0000000000000..a8e8fc957ee37 --- /dev/null +++ b/.github/workflows/nightly-gauntlet.yaml @@ -0,0 +1,203 @@ +# The nightly-gauntlet runs tests that are either too flaky or too slow to block +# every PR. +name: nightly-gauntlet +on: + schedule: + # Every day at 4AM + - cron: "0 4 * * 1-5" + workflow_dispatch: + +permissions: + contents: read + +jobs: + test-go-pg: + # make sure to adjust NUM_PARALLEL_PACKAGES and NUM_PARALLEL_TESTS below + # when changing runner sizes + runs-on: ${{ matrix.os == 'macos-latest' && github.repository_owner == 'coder' && 'depot-macos-latest' || matrix.os == 'windows-2022' && github.repository_owner == 'coder' && 'depot-windows-2022-16' || matrix.os }} + # This timeout must be greater than the timeout set by `go test` in + # `make test-postgres` to ensure we receive a trace of running + # goroutines. Setting this to the timeout +5m should work quite well + # even if some of the preceding steps are slow. + timeout-minutes: 25 + strategy: + matrix: + os: + - macos-latest + - windows-2022 + steps: + - name: Harden Runner + uses: step-security/harden-runner@6c439dc8bdf85cadbbce9ed30d1c7b959517bc49 # v2.12.2 + with: + egress-policy: audit + + # macOS indexes all new files in the background. Our Postgres tests + # create and destroy thousands of databases on disk, and Spotlight + # tries to index all of them, seriously slowing down the tests. + - name: Disable Spotlight Indexing + if: runner.os == 'macOS' + run: | + sudo mdutil -a -i off + sudo mdutil -X / + sudo launchctl bootout system /System/Library/LaunchDaemons/com.apple.metadata.mds.plist + + # Set up RAM disks to speed up the rest of the job. This action is in + # a separate repository to allow its use before actions/checkout. + - name: Setup RAM Disks + if: runner.os == 'Windows' + uses: coder/setup-ramdisk-action@e1100847ab2d7bcd9d14bcda8f2d1b0f07b36f1b + + - name: Checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 1 + + - name: Setup Go + uses: ./.github/actions/setup-go + with: + # Runners have Go baked-in and Go will automatically + # download the toolchain configured in go.mod, so we don't + # need to reinstall it. It's faster on Windows runners. + use-preinstalled-go: ${{ runner.os == 'Windows' }} + + - name: Setup Terraform + uses: ./.github/actions/setup-tf + + - name: Setup Embedded Postgres Cache Paths + id: embedded-pg-cache + uses: ./.github/actions/setup-embedded-pg-cache-paths + + - name: Download Embedded Postgres Cache + id: download-embedded-pg-cache + uses: ./.github/actions/embedded-pg-cache/download + with: + key-prefix: embedded-pg-${{ runner.os }}-${{ runner.arch }} + cache-path: ${{ steps.embedded-pg-cache.outputs.cached-dirs }} + + - name: Test with PostgreSQL Database + env: + POSTGRES_VERSION: "13" + TS_DEBUG_DISCO: "true" + LC_CTYPE: "en_US.UTF-8" + LC_ALL: "en_US.UTF-8" + shell: bash + run: | + set -o errexit + set -o pipefail + + if [ "${{ runner.os }}" == "Windows" ]; then + # Create a temp dir on the R: ramdisk drive for Windows. The default + # C: drive is extremely slow: https://github.com/actions/runner-images/issues/8755 + mkdir -p "R:/temp/embedded-pg" + go run scripts/embedded-pg/main.go -path "R:/temp/embedded-pg" -cache "${EMBEDDED_PG_CACHE_DIR}" + elif [ "${{ runner.os }}" == "macOS" ]; then + # Postgres runs faster on a ramdisk on macOS too + mkdir -p /tmp/tmpfs + sudo mount_tmpfs -o noowners -s 8g /tmp/tmpfs + go run scripts/embedded-pg/main.go -path /tmp/tmpfs/embedded-pg -cache "${EMBEDDED_PG_CACHE_DIR}" + elif [ "${{ runner.os }}" == "Linux" ]; then + make test-postgres-docker + fi + + # if macOS, install google-chrome for scaletests + # As another concern, should we really have this kind of external dependency + # requirement on standard CI? + if [ "${{ matrix.os }}" == "macos-latest" ]; then + brew install google-chrome + fi + + # macOS will output "The default interactive shell is now zsh" + # intermittently in CI... + if [ "${{ matrix.os }}" == "macos-latest" ]; then + touch ~/.bash_profile && echo "export BASH_SILENCE_DEPRECATION_WARNING=1" >> ~/.bash_profile + fi + + if [ "${{ runner.os }}" == "Windows" ]; then + # Our Windows runners have 16 cores. + # On Windows Postgres chokes up when we have 16x16=256 tests + # running in parallel, and dbtestutil.NewDB starts to take more than + # 10s to complete sometimes causing test timeouts. With 16x8=128 tests + # Postgres tends not to choke. + NUM_PARALLEL_PACKAGES=8 + NUM_PARALLEL_TESTS=16 + elif [ "${{ runner.os }}" == "macOS" ]; then + # Our macOS runners have 8 cores. We set NUM_PARALLEL_TESTS to 16 + # because the tests complete faster and Postgres doesn't choke. It seems + # that macOS's tmpfs is faster than the one on Windows. + NUM_PARALLEL_PACKAGES=8 + NUM_PARALLEL_TESTS=16 + elif [ "${{ runner.os }}" == "Linux" ]; then + # Our Linux runners have 8 cores. + NUM_PARALLEL_PACKAGES=8 + NUM_PARALLEL_TESTS=8 + fi + + # run tests without cache + TESTCOUNT="-count=1" + + DB=ci gotestsum \ + --format standard-quiet --packages "./..." \ + -- -timeout=20m -v -p $NUM_PARALLEL_PACKAGES -parallel=$NUM_PARALLEL_TESTS $TESTCOUNT + + - name: Upload Embedded Postgres Cache + uses: ./.github/actions/embedded-pg-cache/upload + # We only use the embedded Postgres cache on macOS and Windows runners. + if: runner.OS == 'macOS' || runner.OS == 'Windows' + with: + cache-key: ${{ steps.download-embedded-pg-cache.outputs.cache-key }} + cache-path: "${{ steps.embedded-pg-cache.outputs.embedded-pg-cache }}" + + - name: Upload test stats to Datadog + timeout-minutes: 1 + continue-on-error: true + uses: ./.github/actions/upload-datadog + if: success() || failure() + with: + api-key: ${{ secrets.DATADOG_API_KEY }} + + notify-slack-on-failure: + needs: + - test-go-pg + runs-on: ubuntu-latest + if: failure() && github.ref == 'refs/heads/main' + + steps: + - name: Send Slack notification + run: | + curl -X POST -H 'Content-type: application/json' \ + --data '{ + "blocks": [ + { + "type": "header", + "text": { + "type": "plain_text", + "text": "❌ Nightly gauntlet failed", + "emoji": true + } + }, + { + "type": "section", + "fields": [ + { + "type": "mrkdwn", + "text": "*Workflow:*\n${{ github.workflow }}" + }, + { + "type": "mrkdwn", + "text": "*Committer:*\n${{ github.actor }}" + }, + { + "type": "mrkdwn", + "text": "*Commit:*\n${{ github.sha }}" + } + ] + }, + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": "*View failure:* <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|Click here>" + } + } + ] + }' ${{ secrets.CI_FAILURE_SLACK_WEBHOOK }} diff --git a/.github/workflows/pr-auto-assign.yaml b/.github/workflows/pr-auto-assign.yaml index 28935d74507e5..746b471f57b39 100644 --- a/.github/workflows/pr-auto-assign.yaml +++ b/.github/workflows/pr-auto-assign.yaml @@ -14,7 +14,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit diff --git a/.github/workflows/pr-cleanup.yaml b/.github/workflows/pr-cleanup.yaml index 184486a711fbb..4c3023990efe5 100644 --- a/.github/workflows/pr-cleanup.yaml +++ b/.github/workflows/pr-cleanup.yaml @@ -19,7 +19,7 @@ jobs: packages: write steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit diff --git a/.github/workflows/pr-deploy.yaml b/.github/workflows/pr-deploy.yaml index fe64c47aebc6e..c82861db22094 100644 --- a/.github/workflows/pr-deploy.yaml +++ b/.github/workflows/pr-deploy.yaml @@ -39,7 +39,7 @@ jobs: PR_OPEN: ${{ steps.check_pr.outputs.pr_open }} steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -74,7 +74,7 @@ jobs: runs-on: "ubuntu-latest" steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -174,7 +174,7 @@ jobs: pull-requests: write # needed for commenting on PRs steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -218,7 +218,7 @@ jobs: CODER_IMAGE_TAG: ${{ needs.get_info.outputs.CODER_IMAGE_TAG }} steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -276,7 +276,7 @@ jobs: PR_HOSTNAME: "pr${{ needs.get_info.outputs.PR_NUMBER }}.${{ secrets.PR_DEPLOYMENTS_DOMAIN }}" steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit diff --git a/.github/workflows/release-validation.yaml b/.github/workflows/release-validation.yaml index 1e4e928f32f73..3555e2a8fc50d 100644 --- a/.github/workflows/release-validation.yaml +++ b/.github/workflows/release-validation.yaml @@ -14,7 +14,7 @@ jobs: steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 69043dc833362..6ea28ad87a90c 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -60,7 +60,7 @@ jobs: - name: Switch XCode Version uses: maxim-lobanov/setup-xcode@60606e260d2fc5762a71e64e74b2174e8ea3c8bd # v1.6.0 with: - xcode-version: "16.0.0" + xcode-version: "16.1.0" - name: Setup Go uses: ./.github/actions/setup-go @@ -134,7 +134,7 @@ jobs: version: ${{ steps.version.outputs.version }} steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -286,14 +286,14 @@ jobs: # Setup GCloud for signing Windows binaries. - name: Authenticate to Google Cloud id: gcloud_auth - uses: google-github-actions/auth@ba79af03959ebeac9769e648f473a284504d9193 # v2.1.10 + uses: google-github-actions/auth@140bb5113ffb6b65a7e9b937a81fa96cf5064462 # v2.1.11 with: workload_identity_provider: ${{ secrets.GCP_CODE_SIGNING_WORKLOAD_ID_PROVIDER }} service_account: ${{ secrets.GCP_CODE_SIGNING_SERVICE_ACCOUNT }} token_format: "access_token" - name: Setup GCloud SDK - uses: google-github-actions/setup-gcloud@77e7a554d41e2ee56fc945c52dfd3f33d12def9a # v2.1.4 + uses: google-github-actions/setup-gcloud@6a7c903a70c8625ed6700fa299f5ddb4ca6022e9 # v2.1.5 - name: Download dylibs uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 @@ -323,6 +323,8 @@ jobs: env: CODER_SIGN_WINDOWS: "1" CODER_SIGN_DARWIN: "1" + CODER_SIGN_GPG: "1" + CODER_GPG_RELEASE_KEY_BASE64: ${{ secrets.GPG_RELEASE_KEY_BASE64 }} CODER_WINDOWS_RESOURCES: "1" AC_CERTIFICATE_FILE: /tmp/apple_cert.p12 AC_CERTIFICATE_PASSWORD_FILE: /tmp/apple_cert_password.txt @@ -632,6 +634,29 @@ jobs: - name: ls build run: ls -lh build + - name: Publish Coder CLI binaries and detached signatures to GCS + if: ${{ !inputs.dry_run && github.ref == 'refs/heads/main' && github.repository_owner == 'coder'}} + run: | + set -euxo pipefail + + version="$(./scripts/version.sh)" + + binaries=( + "coder-darwin-amd64" + "coder-darwin-arm64" + "coder-linux-amd64" + "coder-linux-arm64" + "coder-linux-armv7" + "coder-windows-amd64.exe" + "coder-windows-arm64.exe" + ) + + for binary in "${binaries[@]}"; do + detached_signature="${binary}.asc" + gcloud storage cp "./site/out/bin/${binary}" "gs://releases.coder.com/coder-cli/${version}/${binary}" + gcloud storage cp "./site/out/bin/${detached_signature}" "gs://releases.coder.com/coder-cli/${version}/${detached_signature}" + done + - name: Publish release run: | set -euo pipefail @@ -671,13 +696,13 @@ jobs: CODER_GPG_RELEASE_KEY_BASE64: ${{ secrets.GPG_RELEASE_KEY_BASE64 }} - name: Authenticate to Google Cloud - uses: google-github-actions/auth@ba79af03959ebeac9769e648f473a284504d9193 # v2.1.10 + uses: google-github-actions/auth@140bb5113ffb6b65a7e9b937a81fa96cf5064462 # v2.1.11 with: workload_identity_provider: ${{ secrets.GCP_WORKLOAD_ID_PROVIDER }} service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }} - name: Setup GCloud SDK - uses: google-github-actions/setup-gcloud@77e7a554d41e2ee56fc945c52dfd3f33d12def9a # 2.1.4 + uses: google-github-actions/setup-gcloud@6a7c903a70c8625ed6700fa299f5ddb4ca6022e9 # 2.1.5 - name: Publish Helm Chart if: ${{ !inputs.dry_run }} @@ -693,6 +718,8 @@ jobs: gsutil -h "Cache-Control:no-cache,max-age=0" cp build/helm/provisioner_helm_${version}.tgz gs://helm.coder.com/v2 gsutil -h "Cache-Control:no-cache,max-age=0" cp build/helm/index.yaml gs://helm.coder.com/v2 gsutil -h "Cache-Control:no-cache,max-age=0" cp helm/artifacthub-repo.yml gs://helm.coder.com/v2 + helm push build/coder_helm_${version}.tgz oci://ghcr.io/coder/chart + helm push build/provisioner_helm_${version}.tgz oci://ghcr.io/coder/chart - name: Upload artifacts to actions (if dry-run) if: ${{ inputs.dry_run }} @@ -737,7 +764,7 @@ jobs: # TODO: skip this if it's not a new release (i.e. a backport). This is # fine right now because it just makes a PR that we can close. - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -813,7 +840,7 @@ jobs: steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -903,7 +930,7 @@ jobs: if: ${{ !inputs.dry_run }} steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index d773ad74e5adc..1e5104310e085 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -20,7 +20,7 @@ jobs: steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -47,6 +47,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@ce28f5bb42b7a9f2c824e633a3f6ee835bab6858 # v3.29.0 + uses: github/codeql-action/upload-sarif@d6bbdef45e766d081b84a2def353b0055f728d3e # v3.29.3 with: sarif_file: results.sarif diff --git a/.github/workflows/security.yaml b/.github/workflows/security.yaml index be4811e05e813..d31595c3a8465 100644 --- a/.github/workflows/security.yaml +++ b/.github/workflows/security.yaml @@ -27,7 +27,7 @@ jobs: runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }} steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -38,7 +38,7 @@ jobs: uses: ./.github/actions/setup-go - name: Initialize CodeQL - uses: github/codeql-action/init@ce28f5bb42b7a9f2c824e633a3f6ee835bab6858 # v3.29.0 + uses: github/codeql-action/init@d6bbdef45e766d081b84a2def353b0055f728d3e # v3.29.3 with: languages: go, javascript @@ -48,7 +48,7 @@ jobs: rm Makefile - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@ce28f5bb42b7a9f2c824e633a3f6ee835bab6858 # v3.29.0 + uses: github/codeql-action/analyze@d6bbdef45e766d081b84a2def353b0055f728d3e # v3.29.3 - name: Send Slack notification on failure if: ${{ failure() }} @@ -67,7 +67,7 @@ jobs: runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }} steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -142,7 +142,7 @@ jobs: echo "image=$(cat "$image_job")" >> $GITHUB_OUTPUT - name: Run Trivy vulnerability scanner - uses: aquasecurity/trivy-action@76071ef0d7ec797419534a183b498b4d6366cf37 + uses: aquasecurity/trivy-action@dc5a429b52fcf669ce959baa2c2dd26090d2a6c4 with: image-ref: ${{ steps.build.outputs.image }} format: sarif @@ -150,7 +150,7 @@ jobs: severity: "CRITICAL,HIGH" - name: Upload Trivy scan results to GitHub Security tab - uses: github/codeql-action/upload-sarif@ce28f5bb42b7a9f2c824e633a3f6ee835bab6858 # v3.29.0 + uses: github/codeql-action/upload-sarif@d6bbdef45e766d081b84a2def353b0055f728d3e # v3.29.3 with: sarif_file: trivy-results.sarif category: "Trivy" diff --git a/.github/workflows/stale.yaml b/.github/workflows/stale.yaml index 2563367d840e2..00d7eef888833 100644 --- a/.github/workflows/stale.yaml +++ b/.github/workflows/stale.yaml @@ -18,7 +18,7 @@ jobs: pull-requests: write steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -96,7 +96,7 @@ jobs: contents: write steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -118,7 +118,7 @@ jobs: actions: write steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit diff --git a/.github/workflows/start-workspace.yaml b/.github/workflows/start-workspace.yaml index 975acd7e1d939..9c1106a040a0e 100644 --- a/.github/workflows/start-workspace.yaml +++ b/.github/workflows/start-workspace.yaml @@ -19,7 +19,7 @@ jobs: timeout-minutes: 5 steps: - name: Start Coder workspace - uses: coder/start-workspace-action@35a4608cefc7e8cc56573cae7c3b85304575cb72 + uses: coder/start-workspace-action@f97a681b4cc7985c9eef9963750c7cc6ebc93a19 with: github-token: ${{ secrets.GITHUB_TOKEN }} github-username: >- diff --git a/.github/workflows/weekly-docs.yaml b/.github/workflows/weekly-docs.yaml index c4b2a33361657..dd83a5629ca83 100644 --- a/.github/workflows/weekly-docs.yaml +++ b/.github/workflows/weekly-docs.yaml @@ -21,7 +21,7 @@ jobs: pull-requests: write # required to post PR review comments by the action steps: - name: Harden Runner - uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1 + uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0 with: egress-policy: audit @@ -29,7 +29,7 @@ jobs: uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Check Markdown links - uses: umbrelladocs/action-linkspector@e2ccef58c4b9eb89cd71ee23a8629744bba75aa6 # v1.3.5 + uses: umbrelladocs/action-linkspector@874d01cae9fd488e3077b08952093235bd626977 # v1.3.7 id: markdown-link-check # checks all markdown files from /docs including all subfolders with: diff --git a/.golangci.yaml b/.golangci.yaml index 2e1e853a0425a..aeebaf47e29a6 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -181,7 +181,6 @@ linters-settings: issues: exclude-dirs: - - coderd/database/dbmem - node_modules - .git diff --git a/.mcp.json b/.mcp.json new file mode 100644 index 0000000000000..3f3734e4fef14 --- /dev/null +++ b/.mcp.json @@ -0,0 +1,36 @@ +{ + "mcpServers": { + "go-language-server": { + "type": "stdio", + "command": "go", + "args": [ + "run", + "github.com/isaacphi/mcp-language-server@latest", + "-workspace", + "./", + "-lsp", + "go", + "--", + "run", + "golang.org/x/tools/gopls@latest" + ], + "env": {} + }, + "typescript-language-server": { + "type": "stdio", + "command": "go", + "args": [ + "run", + "github.com/isaacphi/mcp-language-server@latest", + "-workspace", + "./site/", + "-lsp", + "pnpx", + "--", + "typescript-language-server", + "--stdio" + ], + "env": {} + } + } +} \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md index 5462f9c3018e4..3de33a5466054 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,21 +1,25 @@ # Coder Development Guidelines -Read [cursor rules](.cursorrules). - -## Build/Test/Lint Commands - -### Main Commands - -- `make build` or `make build-fat` - Build all "fat" binaries (includes "server" functionality) -- `make build-slim` - Build "slim" binaries -- `make test` - Run Go tests -- `make test RUN=TestFunctionName` or `go test -v ./path/to/package -run TestFunctionName` - Test single -- `make test-postgres` - Run tests with Postgres database -- `make test-race` - Run tests with Go race detector -- `make test-e2e` - Run end-to-end tests -- `make lint` - Run all linters -- `make fmt` - Format all code -- `make gen` - Generates mocks, database queries and other auto-generated files +@.claude/docs/WORKFLOWS.md +@.cursorrules +@README.md +@package.json + +## 🚀 Essential Commands + +| Task | Command | Notes | +|-------------------|--------------------------|----------------------------------| +| **Development** | `./scripts/develop.sh` | ⚠️ Don't use manual build | +| **Build** | `make build` | Fat binaries (includes server) | +| **Build Slim** | `make build-slim` | Slim binaries | +| **Test** | `make test` | Full test suite | +| **Test Single** | `make test RUN=TestName` | Faster than full suite | +| **Test Postgres** | `make test-postgres` | Run tests with Postgres database | +| **Test Race** | `make test-race` | Run tests with Go race detector | +| **Lint** | `make lint` | Always run after changes | +| **Generate** | `make gen` | After database changes | +| **Format** | `make fmt` | Auto-format code | +| **Clean** | `make clean` | Clean build artifacts | ### Frontend Commands (site directory) @@ -26,81 +30,109 @@ Read [cursor rules](.cursorrules). - `pnpm lint` - Lint frontend code - `pnpm test` - Run frontend tests -## Code Style Guidelines +### Documentation Commands + +- `pnpm run format-docs` - Format markdown tables in docs +- `pnpm run lint-docs` - Lint and fix markdown files +- `pnpm run storybook` - Run Storybook (from site directory) + +## 🔧 Critical Patterns + +### Database Changes (ALWAYS FOLLOW) + +1. Modify `coderd/database/queries/*.sql` files +2. Run `make gen` +3. If audit errors: update `enterprise/audit/table.go` +4. Run `make gen` again + +### LSP Navigation (USE FIRST) + +#### Go LSP (for backend code) + +- **Find definitions**: `mcp__go-language-server__definition symbolName` +- **Find references**: `mcp__go-language-server__references symbolName` +- **Get type info**: `mcp__go-language-server__hover filePath line column` +- **Rename symbol**: `mcp__go-language-server__rename_symbol filePath line column newName` + +#### TypeScript LSP (for frontend code in site/) + +- **Find definitions**: `mcp__typescript-language-server__definition symbolName` +- **Find references**: `mcp__typescript-language-server__references symbolName` +- **Get type info**: `mcp__typescript-language-server__hover filePath line column` +- **Rename symbol**: `mcp__typescript-language-server__rename_symbol filePath line column newName` + +### OAuth2 Error Handling + +```go +// OAuth2-compliant error responses +writeOAuth2Error(ctx, rw, http.StatusBadRequest, "invalid_grant", "description") +``` -### Go +### Authorization Context -- Follow [Effective Go](https://go.dev/doc/effective_go) and [Go's Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments) -- Use `gofumpt` for formatting -- Create packages when used during implementation -- Validate abstractions against implementations +```go +// Public endpoints needing system access +app, err := api.Database.GetOAuth2ProviderAppByClientID(dbauthz.AsSystemRestricted(ctx), clientID) -### Error Handling +// Authenticated endpoints with user context +app, err := api.Database.GetOAuth2ProviderAppByClientID(ctx, clientID) +``` -- Use descriptive error messages -- Wrap errors with context -- Propagate errors appropriately -- Use proper error types -- (`xerrors.Errorf("failed to X: %w", err)`) +## 📋 Quick Reference -### Naming +### Full workflows available in imported WORKFLOWS.md -- Use clear, descriptive names -- Abbreviate only when obvious -- Follow Go and TypeScript naming conventions +### New Feature Checklist -### Comments +- [ ] Run `git pull` to ensure latest code +- [ ] Check if feature touches database - you'll need migrations +- [ ] Check if feature touches audit logs - update `enterprise/audit/table.go` -- Document exported functions, types, and non-obvious logic -- Follow JSDoc format for TypeScript -- Use godoc format for Go code +## 🏗️ Architecture -## Commit Style +- **coderd**: Main API service +- **provisionerd**: Infrastructure provisioning +- **Agents**: Workspace services (SSH, port forwarding) +- **Database**: PostgreSQL with `dbauthz` authorization -- Follow [Conventional Commits 1.0.0](https://www.conventionalcommits.org/en/v1.0.0/) -- Format: `type(scope): message` -- Types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore` -- Keep message titles concise (~70 characters) -- Use imperative, present tense in commit titles +## 🧪 Testing -## Database queries +### Race Condition Prevention -- MUST DO! Any changes to database - adding queries, modifying queries should be done in the `coderd\database\queries\*.sql` files. Use `make gen` to generate necessary changes after. -- MUST DO! Queries are grouped in files relating to context - e.g. `prebuilds.sql`, `users.sql`, `provisionerjobs.sql`. -- After making changes to any `coderd\database\queries\*.sql` files you must run `make gen` to generate respective ORM changes. +- Use unique identifiers: `fmt.Sprintf("test-client-%s-%d", t.Name(), time.Now().UnixNano())` +- Never use hardcoded names in concurrent tests -## Architecture +### OAuth2 Testing -### Core Components +- Full suite: `./scripts/oauth2/test-mcp-oauth2.sh` +- Manual testing: `./scripts/oauth2/test-manual-flow.sh` -- **coderd**: Main API service connecting workspaces, provisioners, and users -- **provisionerd**: Execution context for infrastructure-modifying providers -- **Agents**: Services in remote workspaces providing features like SSH and port forwarding -- **Workspaces**: Cloud resources defined by Terraform +### Timing Issues -## Sub-modules +NEVER use `time.Sleep` to mitigate timing issues. If an issue +seems like it should use `time.Sleep`, read through https://github.com/coder/quartz and specifically the [README](https://github.com/coder/quartz/blob/main/README.md) to better understand how to handle timing issues. -### Template System +## 🎯 Code Style -- Templates define infrastructure for workspaces using Terraform -- Environment variables pass context between Coder and templates -- Official modules extend development environments +### Detailed guidelines in imported WORKFLOWS.md -### RBAC System +- Follow [Uber Go Style Guide](https://github.com/uber-go/guide/blob/master/style.md) +- Commit format: `type(scope): message` -- Permissions defined at site, organization, and user levels -- Object-Action model protects resources -- Built-in roles: owner, member, auditor, templateAdmin -- Permission format: `?...` +## 📚 Detailed Development Guides -### Database +@.claude/docs/OAUTH2.md +@.claude/docs/TESTING.md +@.claude/docs/TROUBLESHOOTING.md +@.claude/docs/DATABASE.md -- PostgreSQL 13+ recommended for production -- Migrations managed with `migrate` -- Database authorization through `dbauthz` package +## 🚨 Common Pitfalls -## Frontend +1. **Audit table errors** → Update `enterprise/audit/table.go` +2. **OAuth2 errors** → Return RFC-compliant format +3. **Race conditions** → Use unique test identifiers +4. **Missing newlines** → Ensure files end with newline -The frontend is contained in the site folder. +--- -For building Frontend refer to [this document](docs/about/contributing/frontend.md) +*This file stays lean and actionable. Detailed workflows and explanations are imported automatically.* diff --git a/CODEOWNERS b/CODEOWNERS index 327c43dd3bb81..e571a160b12b7 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1,8 +1,31 @@ -# These APIs are versioned, so any changes need to be carefully reviewed for whether -# to bump API major or minor versions. +# These APIs are versioned, so any changes need to be carefully reviewed for +# whether to bump API major or minor versions. agent/proto/ @spikecurtis @johnstcn +provisionerd/proto/ @spikecurtis @johnstcn +provisionersdk/proto/ @spikecurtis @johnstcn tailnet/proto/ @spikecurtis @johnstcn vpn/vpn.proto @spikecurtis @johnstcn vpn/version.go @spikecurtis @johnstcn -provisionerd/proto/ @spikecurtis @johnstcn -provisionersdk/proto/ @spikecurtis @johnstcn + + +# This caching code is particularly tricky, and one must be very careful when +# altering it. +coderd/files/ @aslilac + +coderd/dynamicparameters/ @Emyrk +coderd/rbac/ @Emyrk + +# Mainly dependent on coder/guts, which is maintained by @Emyrk +scripts/apitypings/ @Emyrk +scripts/gensite/ @aslilac + +site/ @aslilac +site/src/hooks/ @Parkreiner +# These rules intentionally do not specify any owners. More specific rules +# override less specific rules, so these files are "ignored" by the site/ rule. +site/e2e/google/protobuf/timestampGenerated.ts +site/e2e/provisionerGenerated.ts +site/src/api/countriesGenerated.ts +site/src/api/rbacresourcesGenerated.ts +site/src/api/typesGenerated.ts +site/CLAUDE.md diff --git a/Makefile b/Makefile index b6e69ac28f223..bd3f04a4874cd 100644 --- a/Makefile +++ b/Makefile @@ -252,6 +252,10 @@ $(CODER_ALL_BINARIES): go.mod go.sum \ fi cp "$@" "./site/out/bin/coder-$$os-$$arch$$dot_ext" + + if [[ "$${CODER_SIGN_GPG:-0}" == "1" ]]; then + cp "$@.asc" "./site/out/bin/coder-$$os-$$arch$$dot_ext.asc" + fi fi # This task builds Coder Desktop dylibs @@ -456,16 +460,31 @@ fmt: fmt/ts fmt/go fmt/terraform fmt/shfmt fmt/biome fmt/markdown .PHONY: fmt fmt/go: +ifdef FILE + # Format single file + if [[ -f "$(FILE)" ]] && [[ "$(FILE)" == *.go ]] && ! grep -q "DO NOT EDIT" "$(FILE)"; then \ + echo "$(GREEN)==>$(RESET) $(BOLD)fmt/go$(RESET) $(FILE)"; \ + go run mvdan.cc/gofumpt@v0.8.0 -w -l "$(FILE)"; \ + fi +else go mod tidy echo "$(GREEN)==>$(RESET) $(BOLD)fmt/go$(RESET)" # VS Code users should check out # https://github.com/mvdan/gofumpt#visual-studio-code find . $(FIND_EXCLUSIONS) -type f -name '*.go' -print0 | \ - xargs -0 grep --null -L "DO NOT EDIT" | \ - xargs -0 go run mvdan.cc/gofumpt@v0.4.0 -w -l + xargs -0 grep -E --null -L '^// Code generated .* DO NOT EDIT\.$$' | \ + xargs -0 go run mvdan.cc/gofumpt@v0.8.0 -w -l +endif .PHONY: fmt/go fmt/ts: site/node_modules/.installed +ifdef FILE + # Format single TypeScript/JavaScript file + if [[ -f "$(FILE)" ]] && [[ "$(FILE)" == *.ts ]] || [[ "$(FILE)" == *.tsx ]] || [[ "$(FILE)" == *.js ]] || [[ "$(FILE)" == *.jsx ]]; then \ + echo "$(GREEN)==>$(RESET) $(BOLD)fmt/ts$(RESET) $(FILE)"; \ + (cd site/ && pnpm exec biome format --write "../$(FILE)"); \ + fi +else echo "$(GREEN)==>$(RESET) $(BOLD)fmt/ts$(RESET)" cd site # Avoid writing files in CI to reduce file write activity @@ -474,9 +493,17 @@ ifdef CI else pnpm run check:fix endif +endif .PHONY: fmt/ts fmt/biome: site/node_modules/.installed +ifdef FILE + # Format single file with biome + if [[ -f "$(FILE)" ]] && [[ "$(FILE)" == *.ts ]] || [[ "$(FILE)" == *.tsx ]] || [[ "$(FILE)" == *.js ]] || [[ "$(FILE)" == *.jsx ]]; then \ + echo "$(GREEN)==>$(RESET) $(BOLD)fmt/biome$(RESET) $(FILE)"; \ + (cd site/ && pnpm exec biome format --write "../$(FILE)"); \ + fi +else echo "$(GREEN)==>$(RESET) $(BOLD)fmt/biome$(RESET)" cd site/ # Avoid writing files in CI to reduce file write activity @@ -485,14 +512,30 @@ ifdef CI else pnpm run format endif +endif .PHONY: fmt/biome fmt/terraform: $(wildcard *.tf) +ifdef FILE + # Format single Terraform file + if [[ -f "$(FILE)" ]] && [[ "$(FILE)" == *.tf ]] || [[ "$(FILE)" == *.tfvars ]]; then \ + echo "$(GREEN)==>$(RESET) $(BOLD)fmt/terraform$(RESET) $(FILE)"; \ + terraform fmt "$(FILE)"; \ + fi +else echo "$(GREEN)==>$(RESET) $(BOLD)fmt/terraform$(RESET)" terraform fmt -recursive +endif .PHONY: fmt/terraform fmt/shfmt: $(SHELL_SRC_FILES) +ifdef FILE + # Format single shell script + if [[ -f "$(FILE)" ]] && [[ "$(FILE)" == *.sh ]]; then \ + echo "$(GREEN)==>$(RESET) $(BOLD)fmt/shfmt$(RESET) $(FILE)"; \ + shfmt -w "$(FILE)"; \ + fi +else echo "$(GREEN)==>$(RESET) $(BOLD)fmt/shfmt$(RESET)" # Only do diff check in CI, errors on diff. ifdef CI @@ -500,11 +543,20 @@ ifdef CI else shfmt -w $(SHELL_SRC_FILES) endif +endif .PHONY: fmt/shfmt fmt/markdown: node_modules/.installed +ifdef FILE + # Format single markdown file + if [[ -f "$(FILE)" ]] && [[ "$(FILE)" == *.md ]]; then \ + echo "$(GREEN)==>$(RESET) $(BOLD)fmt/markdown$(RESET) $(FILE)"; \ + pnpm exec markdown-table-formatter "$(FILE)"; \ + fi +else echo "$(GREEN)==>$(RESET) $(BOLD)fmt/markdown$(RESET)" pnpm format-docs +endif .PHONY: fmt/markdown lint: lint/shellcheck lint/go lint/ts lint/examples lint/helm lint/site-icons lint/markdown @@ -551,7 +603,6 @@ DB_GEN_FILES := \ coderd/database/dump.sql \ coderd/database/querier.go \ coderd/database/unique_constraint.go \ - coderd/database/dbmem/dbmem.go \ coderd/database/dbmetrics/dbmetrics.go \ coderd/database/dbauthz/dbauthz.go \ coderd/database/dbmock/dbmock.go @@ -925,7 +976,7 @@ sqlc-vet: test-postgres-docker test-postgres: test-postgres-docker # The postgres test is prone to failure, so we limit parallelism for # more consistent execution. - $(GIT_FLAGS) DB=ci gotestsum \ + $(GIT_FLAGS) gotestsum \ --junitfile="gotests.xml" \ --jsonfile="gotests.json" \ $(GOTESTSUM_RETRY_FLAGS) \ diff --git a/agent/agent.go b/agent/agent.go index 833b4032d491b..e4d7ab60e076b 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -91,13 +91,14 @@ type Options struct { Execer agentexec.Execer Devcontainers bool DevcontainerAPIOptions []agentcontainers.Option // Enable Devcontainers for these to be effective. + Clock quartz.Clock } type Client interface { ConnectRPC26(ctx context.Context) ( proto.DRPCAgentClient26, tailnetproto.DRPCTailnetClient26, error, ) - RewriteDERPMap(derpMap *tailcfg.DERPMap) + tailnet.DERPMapRewriter } type Agent interface { @@ -144,6 +145,9 @@ func New(options Options) Agent { if options.PortCacheDuration == 0 { options.PortCacheDuration = 1 * time.Second } + if options.Clock == nil { + options.Clock = quartz.NewReal() + } prometheusRegistry := options.PrometheusRegistry if prometheusRegistry == nil { @@ -157,6 +161,7 @@ func New(options Options) Agent { hardCtx, hardCancel := context.WithCancel(context.Background()) gracefulCtx, gracefulCancel := context.WithCancel(hardCtx) a := &agent{ + clock: options.Clock, tailnetListenPort: options.TailnetListenPort, reconnectingPTYTimeout: options.ReconnectingPTYTimeout, logger: options.Logger, @@ -204,6 +209,7 @@ func New(options Options) Agent { } type agent struct { + clock quartz.Clock logger slog.Logger client Client exchangeToken func(ctx context.Context) (string, error) @@ -273,7 +279,7 @@ type agent struct { devcontainers bool containerAPIOptions []agentcontainers.Option - containerAPI atomic.Pointer[agentcontainers.API] // Set by apiHandler. + containerAPI *agentcontainers.API } func (a *agent) TailnetConn() *tailnet.Conn { @@ -330,6 +336,17 @@ func (a *agent) init() { // will not report anywhere. a.scriptRunner.RegisterMetrics(a.prometheusRegistry) + containerAPIOpts := []agentcontainers.Option{ + agentcontainers.WithExecer(a.execer), + agentcontainers.WithCommandEnv(a.sshServer.CommandEnv), + agentcontainers.WithScriptLogger(func(logSourceID uuid.UUID) agentcontainers.ScriptLogger { + return a.logSender.GetScriptLogger(logSourceID) + }), + } + containerAPIOpts = append(containerAPIOpts, a.containerAPIOptions...) + + a.containerAPI = agentcontainers.NewAPI(a.logger.Named("containers"), containerAPIOpts...) + a.reconnectingPTYServer = reconnectingpty.NewServer( a.logger.Named("reconnecting-pty"), a.sshServer, @@ -546,7 +563,6 @@ func (a *agent) reportMetadata(ctx context.Context, aAPI proto.DRPCAgentClient26 // channel to synchronize the results and avoid both messy // mutex logic and overloading the API. for _, md := range manifest.Metadata { - md := md // We send the result to the channel in the goroutine to avoid // sending the same result multiple times. So, we don't care about // the return values. @@ -1141,17 +1157,27 @@ func (a *agent) handleManifest(manifestOK *checkpoint) func(ctx context.Context, } var ( - scripts = manifest.Scripts - scriptRunnerOpts []agentscripts.InitOption + scripts = manifest.Scripts + devcontainerScripts map[uuid.UUID]codersdk.WorkspaceAgentScript ) if a.devcontainers { - var dcScripts []codersdk.WorkspaceAgentScript - scripts, dcScripts = agentcontainers.ExtractAndInitializeDevcontainerScripts(manifest.Devcontainers, scripts) - // See ExtractAndInitializeDevcontainerScripts for motivation - // behind running dcScripts as post start scripts. - scriptRunnerOpts = append(scriptRunnerOpts, agentscripts.WithPostStartScripts(dcScripts...)) + // Init the container API with the manifest and client so that + // we can start accepting requests. The final start of the API + // happens after the startup scripts have been executed to + // ensure the presence of required tools. This means we can + // return existing devcontainers but actual container detection + // and creation will be deferred. + a.containerAPI.Init( + agentcontainers.WithManifestInfo(manifest.OwnerName, manifest.WorkspaceName, manifest.AgentName, manifest.Directory), + agentcontainers.WithDevcontainers(manifest.Devcontainers, manifest.Scripts), + agentcontainers.WithSubAgentClient(agentcontainers.NewSubAgentClientFromAPI(a.logger, aAPI)), + ) + + // Since devcontainer are enabled, remove devcontainer scripts + // from the main scripts list to avoid showing an error. + scripts, devcontainerScripts = agentcontainers.ExtractDevcontainerScripts(manifest.Devcontainers, scripts) } - err = a.scriptRunner.Init(scripts, aAPI.ScriptCompleted, scriptRunnerOpts...) + err = a.scriptRunner.Init(scripts, aAPI.ScriptCompleted) if err != nil { return xerrors.Errorf("init script runner: %w", err) } @@ -1168,7 +1194,18 @@ func (a *agent) handleManifest(manifestOK *checkpoint) func(ctx context.Context, // finished (both start and post start). For instance, an // autostarted devcontainer will be included in this time. err := a.scriptRunner.Execute(a.gracefulCtx, agentscripts.ExecuteStartScripts) - err = errors.Join(err, a.scriptRunner.Execute(a.gracefulCtx, agentscripts.ExecutePostStartScripts)) + + if a.devcontainers { + // Start the container API after the startup scripts have + // been executed to ensure that the required tools can be + // installed. + a.containerAPI.Start() + for _, dc := range manifest.Devcontainers { + cErr := a.createDevcontainer(ctx, aAPI, dc, devcontainerScripts[dc.ID]) + err = errors.Join(err, cErr) + } + } + dur := time.Since(start).Seconds() if err != nil { a.logger.Warn(ctx, "startup script(s) failed", slog.Error(err)) @@ -1187,14 +1224,6 @@ func (a *agent) handleManifest(manifestOK *checkpoint) func(ctx context.Context, } a.metrics.startupScriptSeconds.WithLabelValues(label).Set(dur) a.scriptRunner.StartCron() - - // If the container API is enabled, trigger an immediate refresh - // for quick sub agent injection. - if cAPI := a.containerAPI.Load(); cAPI != nil { - if err := cAPI.RefreshContainers(ctx); err != nil { - a.logger.Error(ctx, "failed to refresh containers", slog.Error(err)) - } - } }) if err != nil { return xerrors.Errorf("track conn goroutine: %w", err) @@ -1204,6 +1233,38 @@ func (a *agent) handleManifest(manifestOK *checkpoint) func(ctx context.Context, } } +func (a *agent) createDevcontainer( + ctx context.Context, + aAPI proto.DRPCAgentClient26, + dc codersdk.WorkspaceAgentDevcontainer, + script codersdk.WorkspaceAgentScript, +) (err error) { + var ( + exitCode = int32(0) + startTime = a.clock.Now() + status = proto.Timing_OK + ) + if err = a.containerAPI.CreateDevcontainer(dc.WorkspaceFolder, dc.ConfigPath); err != nil { + exitCode = 1 + status = proto.Timing_EXIT_FAILURE + } + endTime := a.clock.Now() + + if _, scriptErr := aAPI.ScriptCompleted(ctx, &proto.WorkspaceAgentScriptCompletedRequest{ + Timing: &proto.Timing{ + ScriptId: script.ID[:], + Start: timestamppb.New(startTime), + End: timestamppb.New(endTime), + ExitCode: exitCode, + Stage: proto.Timing_START, + Status: status, + }, + }); scriptErr != nil { + a.logger.Warn(ctx, "reporting script completed failed", slog.Error(scriptErr)) + } + return err +} + // createOrUpdateNetwork waits for the manifest to be set using manifestOK, then creates or updates // the tailnet using the information in the manifest func (a *agent) createOrUpdateNetwork(manifestOK, networkOK *checkpoint) func(context.Context, proto.DRPCAgentClient26) error { @@ -1227,7 +1288,6 @@ func (a *agent) createOrUpdateNetwork(manifestOK, networkOK *checkpoint) func(co // agent API. network, err = a.createTailnet( a.gracefulCtx, - aAPI, manifest.AgentID, manifest.DERPMap, manifest.DERPForceWebSockets, @@ -1262,9 +1322,9 @@ func (a *agent) createOrUpdateNetwork(manifestOK, networkOK *checkpoint) func(co network.SetBlockEndpoints(manifest.DisableDirectConnections) // Update the subagent client if the container API is available. - if cAPI := a.containerAPI.Load(); cAPI != nil { + if a.containerAPI != nil { client := agentcontainers.NewSubAgentClientFromAPI(a.logger, aAPI) - cAPI.UpdateSubAgentClient(client) + a.containerAPI.UpdateSubAgentClient(client) } } return nil @@ -1382,7 +1442,6 @@ func (a *agent) trackGoroutine(fn func()) error { func (a *agent) createTailnet( ctx context.Context, - aAPI proto.DRPCAgentClient26, agentID uuid.UUID, derpMap *tailcfg.DERPMap, derpForceWebSockets, disableDirectConnections bool, @@ -1515,10 +1574,7 @@ func (a *agent) createTailnet( }() if err = a.trackGoroutine(func() { defer apiListener.Close() - apiHandler, closeAPIHAndler := a.apiHandler(aAPI) - defer func() { - _ = closeAPIHAndler() - }() + apiHandler := a.apiHandler() server := &http.Server{ BaseContext: func(net.Listener) context.Context { return ctx }, Handler: apiHandler, @@ -1532,7 +1588,6 @@ func (a *agent) createTailnet( case <-ctx.Done(): case <-a.hardCtx.Done(): } - _ = closeAPIHAndler() _ = server.Close() }() @@ -1871,6 +1926,10 @@ func (a *agent) Close() error { a.logger.Error(a.hardCtx, "script runner close", slog.Error(err)) } + if err := a.containerAPI.Close(); err != nil { + a.logger.Error(a.hardCtx, "container API close", slog.Error(err)) + } + // Wait for the graceful shutdown to complete, but don't wait forever so // that we don't break user expectations. go func() { diff --git a/agent/agent_test.go b/agent/agent_test.go index 1b24520e45cc5..d87148be9ad15 100644 --- a/agent/agent_test.go +++ b/agent/agent_test.go @@ -2130,7 +2130,7 @@ func TestAgent_DevcontainerAutostart(t *testing.T) { "name": "mywork", "image": "ubuntu:latest", "cmd": ["sleep", "infinity"], - "runArgs": ["--network=host"] + "runArgs": ["--network=host", "--label=`+agentcontainers.DevcontainerIsTestRunLabel+`=true"] }`), 0o600) require.NoError(t, err, "write devcontainer.json") @@ -2167,6 +2167,7 @@ func TestAgent_DevcontainerAutostart(t *testing.T) { // Only match this specific dev container. agentcontainers.WithClock(mClock), agentcontainers.WithContainerLabelIncludeFilter("devcontainer.local_folder", tempWorkspaceFolder), + agentcontainers.WithContainerLabelIncludeFilter(agentcontainers.DevcontainerIsTestRunLabel, "true"), agentcontainers.WithSubAgentURL(srv.URL), // The agent will copy "itself", but in the case of this test, the // agent is actually this test binary. So we'll tell the test binary @@ -2288,7 +2289,8 @@ func TestAgent_DevcontainerRecreate(t *testing.T) { err = os.WriteFile(devcontainerFile, []byte(`{ "name": "mywork", "image": "busybox:latest", - "cmd": ["sleep", "infinity"] + "cmd": ["sleep", "infinity"], + "runArgs": ["--label=`+agentcontainers.DevcontainerIsTestRunLabel+`=true"] }`), 0o600) require.NoError(t, err, "write devcontainer.json") @@ -2315,6 +2317,7 @@ func TestAgent_DevcontainerRecreate(t *testing.T) { o.Devcontainers = true o.DevcontainerAPIOptions = append(o.DevcontainerAPIOptions, agentcontainers.WithContainerLabelIncludeFilter("devcontainer.local_folder", workspaceFolder), + agentcontainers.WithContainerLabelIncludeFilter(agentcontainers.DevcontainerIsTestRunLabel, "true"), ) }) @@ -2369,7 +2372,7 @@ func TestAgent_DevcontainerRecreate(t *testing.T) { // devcontainer, we do it in a goroutine so we can process logs // concurrently. go func(container codersdk.WorkspaceAgentContainer) { - _, err := conn.RecreateDevcontainer(ctx, container.ID) + _, err := conn.RecreateDevcontainer(ctx, devcontainerID.String()) assert.NoError(t, err, "recreate devcontainer should succeed") }(container) @@ -2438,7 +2441,8 @@ func TestAgent_DevcontainersDisabledForSubAgent(t *testing.T) { // Setup the agent with devcontainers enabled initially. //nolint:dogsled - conn, _, _, _, _ := setupAgent(t, manifest, 0, func(*agenttest.Client, *agent.Options) { + conn, _, _, _, _ := setupAgent(t, manifest, 0, func(_ *agenttest.Client, o *agent.Options) { + o.Devcontainers = true }) // Query the containers API endpoint. This should fail because @@ -2450,8 +2454,8 @@ func TestAgent_DevcontainersDisabledForSubAgent(t *testing.T) { require.Error(t, err) // Verify the error message contains the expected text. - require.Contains(t, err.Error(), "The agent dev containers feature is experimental and not enabled by default.") - require.Contains(t, err.Error(), "To enable this feature, set CODER_AGENT_DEVCONTAINERS_ENABLE=true in your template.") + require.Contains(t, err.Error(), "Dev Container feature not supported.") + require.Contains(t, err.Error(), "Dev Container integration inside other Dev Containers is explicitly not supported.") } func TestAgent_Dial(t *testing.T) { diff --git a/agent/agentcontainers/api.go b/agent/agentcontainers/api.go index 6d2c46b961122..dce0fb27bfc25 100644 --- a/agent/agentcontainers/api.go +++ b/agent/agentcontainers/api.go @@ -2,8 +2,11 @@ package agentcontainers import ( "context" + "encoding/json" "errors" "fmt" + "io/fs" + "maps" "net/http" "os" "path" @@ -18,10 +21,13 @@ import ( "github.com/fsnotify/fsnotify" "github.com/go-chi/chi/v5" + "github.com/go-git/go-git/v5/plumbing/format/gitignore" "github.com/google/uuid" + "github.com/spf13/afero" "golang.org/x/xerrors" "cdr.dev/slog" + "github.com/coder/coder/v2/agent/agentcontainers/ignore" "github.com/coder/coder/v2/agent/agentcontainers/watcher" "github.com/coder/coder/v2/agent/agentexec" "github.com/coder/coder/v2/agent/usershell" @@ -30,6 +36,7 @@ import ( "github.com/coder/coder/v2/codersdk/agentsdk" "github.com/coder/coder/v2/provisioner" "github.com/coder/quartz" + "github.com/coder/websocket" ) const ( @@ -53,11 +60,12 @@ type API struct { cancel context.CancelFunc watcherDone chan struct{} updaterDone chan struct{} - initialUpdateDone chan struct{} // Closed after first update in updaterLoop. + discoverDone chan struct{} updateTrigger chan chan error // Channel to trigger manual refresh. updateInterval time.Duration // Interval for periodic container updates. logger slog.Logger watcher watcher.Watcher + fs afero.Fs execer agentexec.Execer commandEnv CommandEnv ccli ContainerCLI @@ -69,15 +77,23 @@ type API struct { subAgentURL string subAgentEnv []string - ownerName string - workspaceName string + projectDiscovery bool // If we should perform project discovery or not. + discoveryAutostart bool // If we should autostart discovered projects. - mu sync.RWMutex + ownerName string + workspaceName string + parentAgent string + agentDirectory string + + mu sync.RWMutex // Protects the following fields. + initDone chan struct{} // Closed by Init. + updateChans []chan struct{} closed bool containers codersdk.WorkspaceAgentListContainersResponse // Output from the last list operation. containersErr error // Error from the last list operation. devcontainerNames map[string]bool // By devcontainer name. knownDevcontainers map[string]codersdk.WorkspaceAgentDevcontainer // By workspace folder. + devcontainerLogSourceIDs map[string]uuid.UUID // By workspace folder. configFileModifiedTimes map[string]time.Time // By config file path. recreateSuccessTimes map[string]time.Time // By workspace folder. recreateErrorTimes map[string]time.Time // By workspace folder. @@ -85,8 +101,6 @@ type API struct { usingWorkspaceFolderName map[string]bool // By workspace folder. ignoredDevcontainers map[string]bool // By workspace folder. Tracks three states (true, false and not checked). asyncWg sync.WaitGroup - - devcontainerLogSourceIDs map[string]uuid.UUID // By workspace folder. } type subAgentProcess struct { @@ -130,7 +144,9 @@ func WithCommandEnv(ce CommandEnv) Option { strings.HasPrefix(s, "CODER_WORKSPACE_AGENT_URL=") || strings.HasPrefix(s, "CODER_AGENT_TOKEN=") || strings.HasPrefix(s, "CODER_AGENT_AUTH=") || - strings.HasPrefix(s, "CODER_AGENT_DEVCONTAINERS_ENABLE=") + strings.HasPrefix(s, "CODER_AGENT_DEVCONTAINERS_ENABLE=") || + strings.HasPrefix(s, "CODER_AGENT_DEVCONTAINERS_PROJECT_DISCOVERY_ENABLE=") || + strings.HasPrefix(s, "CODER_AGENT_DEVCONTAINERS_DISCOVERY_AUTOSTART_ENABLE=") }) return shell, dir, env, nil } @@ -188,10 +204,12 @@ func WithSubAgentEnv(env ...string) Option { // WithManifestInfo sets the owner name, and workspace name // for the sub-agent. -func WithManifestInfo(owner, workspace string) Option { +func WithManifestInfo(owner, workspace, parentAgent, agentDirectory string) Option { return func(api *API) { api.ownerName = owner api.workspaceName = workspace + api.parentAgent = parentAgent + api.agentDirectory = agentDirectory } } @@ -207,6 +225,29 @@ func WithDevcontainers(devcontainers []codersdk.WorkspaceAgentDevcontainer, scri api.devcontainerNames = make(map[string]bool, len(devcontainers)) api.devcontainerLogSourceIDs = make(map[string]uuid.UUID) for _, dc := range devcontainers { + if dc.Status == "" { + dc.Status = codersdk.WorkspaceAgentDevcontainerStatusStarting + } + logger := api.logger.With( + slog.F("devcontainer_id", dc.ID), + slog.F("devcontainer_name", dc.Name), + slog.F("workspace_folder", dc.WorkspaceFolder), + slog.F("config_path", dc.ConfigPath), + ) + + // Devcontainers have a name originating from Terraform, but + // we need to ensure that the name is unique. We will use + // the workspace folder name to generate a unique agent name, + // and if that fails, we will fall back to the devcontainers + // original name. + name, usingWorkspaceFolder := api.makeAgentName(dc.WorkspaceFolder, dc.Name) + if name != dc.Name { + logger = logger.With(slog.F("devcontainer_name", name)) + logger.Debug(api.ctx, "updating devcontainer name", slog.F("devcontainer_old_name", dc.Name)) + dc.Name = name + api.usingWorkspaceFolderName[dc.WorkspaceFolder] = usingWorkspaceFolder + } + api.knownDevcontainers[dc.WorkspaceFolder] = dc api.devcontainerNames[dc.Name] = true for _, script := range scripts { @@ -218,12 +259,7 @@ func WithDevcontainers(devcontainers []codersdk.WorkspaceAgentDevcontainer, scri } } if api.devcontainerLogSourceIDs[dc.WorkspaceFolder] == uuid.Nil { - api.logger.Error(api.ctx, "devcontainer log source ID not found for devcontainer", - slog.F("devcontainer_id", dc.ID), - slog.F("devcontainer_name", dc.Name), - slog.F("workspace_folder", dc.WorkspaceFolder), - slog.F("config_path", dc.ConfigPath), - ) + logger.Error(api.ctx, "devcontainer log source ID not found for devcontainer") } } } @@ -238,6 +274,29 @@ func WithWatcher(w watcher.Watcher) Option { } } +// WithFileSystem sets the file system used for discovering projects. +func WithFileSystem(fileSystem afero.Fs) Option { + return func(api *API) { + api.fs = fileSystem + } +} + +// WithProjectDiscovery sets if the API should attempt to discover +// projects on the filesystem. +func WithProjectDiscovery(projectDiscovery bool) Option { + return func(api *API) { + api.projectDiscovery = projectDiscovery + } +} + +// WithDiscoveryAutostart sets if the API should attempt to autostart +// projects that have been discovered +func WithDiscoveryAutostart(discoveryAutostart bool) Option { + return func(api *API) { + api.discoveryAutostart = discoveryAutostart + } +} + // ScriptLogger is an interface for sending devcontainer logs to the // controlplane. type ScriptLogger interface { @@ -265,9 +324,7 @@ func NewAPI(logger slog.Logger, options ...Option) *API { api := &API{ ctx: ctx, cancel: cancel, - watcherDone: make(chan struct{}), - updaterDone: make(chan struct{}), - initialUpdateDone: make(chan struct{}), + initDone: make(chan struct{}), updateTrigger: make(chan chan error), updateInterval: defaultUpdateInterval, logger: logger, @@ -310,15 +367,217 @@ func NewAPI(logger slog.Logger, options ...Option) *API { api.watcher = watcher.NewNoop() } } + if api.fs == nil { + api.fs = afero.NewOsFs() + } if api.subAgentClient.Load() == nil { var c SubAgentClient = noopSubAgentClient{} api.subAgentClient.Store(&c) } + return api +} + +// Init applies a final set of options to the API and then +// closes initDone. This method can only be called once. +func (api *API) Init(opts ...Option) { + api.mu.Lock() + defer api.mu.Unlock() + if api.closed { + return + } + select { + case <-api.initDone: + return + default: + } + defer close(api.initDone) + + for _, opt := range opts { + opt(api) + } +} + +// Start starts the API by initializing the watcher and updater loops. +// This method calls Init, if it is desired to apply options after +// the API has been created, it should be done by calling Init before +// Start. This method must only be called once. +func (api *API) Start() { + api.Init() + + api.mu.Lock() + defer api.mu.Unlock() + if api.closed { + return + } + + if api.projectDiscovery && api.agentDirectory != "" { + api.discoverDone = make(chan struct{}) + + go api.discover() + } + + api.watcherDone = make(chan struct{}) + api.updaterDone = make(chan struct{}) + go api.watcherLoop() go api.updaterLoop() +} - return api +func (api *API) discover() { + defer close(api.discoverDone) + defer api.logger.Debug(api.ctx, "project discovery finished") + api.logger.Debug(api.ctx, "project discovery started") + + if err := api.discoverDevcontainerProjects(); err != nil { + api.logger.Error(api.ctx, "discovering dev container projects", slog.Error(err)) + } + + if err := api.RefreshContainers(api.ctx); err != nil { + api.logger.Error(api.ctx, "refreshing containers after discovery", slog.Error(err)) + } +} + +func (api *API) discoverDevcontainerProjects() error { + isGitProject, err := afero.DirExists(api.fs, filepath.Join(api.agentDirectory, ".git")) + if err != nil { + return xerrors.Errorf(".git dir exists: %w", err) + } + + // If the agent directory is a git project, we'll search + // the project for any `.devcontainer/devcontainer.json` + // files. + if isGitProject { + return api.discoverDevcontainersInProject(api.agentDirectory) + } + + // The agent directory is _not_ a git project, so we'll + // search the top level of the agent directory for any + // git projects, and search those. + entries, err := afero.ReadDir(api.fs, api.agentDirectory) + if err != nil { + return xerrors.Errorf("read agent directory: %w", err) + } + + for _, entry := range entries { + if !entry.IsDir() { + continue + } + + isGitProject, err = afero.DirExists(api.fs, filepath.Join(api.agentDirectory, entry.Name(), ".git")) + if err != nil { + return xerrors.Errorf(".git dir exists: %w", err) + } + + // If this directory is a git project, we'll search + // it for any `.devcontainer/devcontainer.json` files. + if isGitProject { + if err := api.discoverDevcontainersInProject(filepath.Join(api.agentDirectory, entry.Name())); err != nil { + return err + } + } + } + + return nil +} + +func (api *API) discoverDevcontainersInProject(projectPath string) error { + logger := api.logger. + Named("project-discovery"). + With(slog.F("project_path", projectPath)) + + globalPatterns, err := ignore.LoadGlobalPatterns(api.fs) + if err != nil { + return xerrors.Errorf("read global git ignore patterns: %w", err) + } + + patterns, err := ignore.ReadPatterns(api.ctx, logger, api.fs, projectPath) + if err != nil { + return xerrors.Errorf("read git ignore patterns: %w", err) + } + + matcher := gitignore.NewMatcher(append(globalPatterns, patterns...)) + + devcontainerConfigPaths := []string{ + "/.devcontainer/devcontainer.json", + "/.devcontainer.json", + } + + return afero.Walk(api.fs, projectPath, func(path string, info fs.FileInfo, err error) error { + if err != nil { + logger.Error(api.ctx, "encountered error while walking for dev container projects", + slog.F("path", path), + slog.Error(err)) + return nil + } + + pathParts := ignore.FilePathToParts(path) + + // We know that a directory entry cannot be a `devcontainer.json` file, so we + // always skip processing directories. If the directory happens to be ignored + // by git then we'll make sure to ignore all of the children of that directory. + if info.IsDir() { + if matcher.Match(pathParts, true) { + return fs.SkipDir + } + + return nil + } + + if matcher.Match(pathParts, false) { + return nil + } + + for _, relativeConfigPath := range devcontainerConfigPaths { + if !strings.HasSuffix(path, relativeConfigPath) { + continue + } + + workspaceFolder := strings.TrimSuffix(path, relativeConfigPath) + + logger := logger.With(slog.F("workspace_folder", workspaceFolder)) + logger.Debug(api.ctx, "discovered dev container project") + + api.mu.Lock() + if _, found := api.knownDevcontainers[workspaceFolder]; !found { + logger.Debug(api.ctx, "adding dev container project") + + dc := codersdk.WorkspaceAgentDevcontainer{ + ID: uuid.New(), + Name: "", // Updated later based on container state. + WorkspaceFolder: workspaceFolder, + ConfigPath: path, + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + Dirty: false, // Updated later based on config file changes. + Container: nil, + } + + if api.discoveryAutostart { + config, err := api.dccli.ReadConfig(api.ctx, workspaceFolder, path, []string{}) + if err != nil { + logger.Error(api.ctx, "read project configuration", slog.Error(err)) + } else if config.Configuration.Customizations.Coder.AutoStart { + dc.Status = codersdk.WorkspaceAgentDevcontainerStatusStarting + } + } + + api.knownDevcontainers[workspaceFolder] = dc + api.broadcastUpdatesLocked() + + if dc.Status == codersdk.WorkspaceAgentDevcontainerStatusStarting { + api.asyncWg.Add(1) + go func() { + defer api.asyncWg.Done() + + _ = api.CreateDevcontainer(dc.WorkspaceFolder, dc.ConfigPath) + }() + } + } + api.mu.Unlock() + } + + return nil + }) } func (api *API) watcherLoop() { @@ -391,28 +650,37 @@ func (api *API) updaterLoop() { } else { api.logger.Debug(api.ctx, "initial containers update complete") } - // Signal that the initial update attempt (successful or not) is done. - // Other services can wait on this if they need the first data to be available. - close(api.initialUpdateDone) // We utilize a TickerFunc here instead of a regular Ticker so that // we can guarantee execution of the updateContainers method after // advancing the clock. + var prevErr error ticker := api.clock.TickerFunc(api.ctx, api.updateInterval, func() error { done := make(chan error, 1) - defer close(done) - + var sent bool + defer func() { + if !sent { + close(done) + } + }() select { case <-api.ctx.Done(): return api.ctx.Err() case api.updateTrigger <- done: + sent = true err := <-done if err != nil { if errors.Is(err, context.Canceled) { api.logger.Warn(api.ctx, "updater loop ticker canceled", slog.Error(err)) - } else { + return nil + } + // Avoid excessive logging of the same error. + if prevErr == nil || prevErr.Error() != err.Error() { api.logger.Error(api.ctx, "updater loop ticker failed", slog.Error(err)) } + prevErr = err + } else { + prevErr = nil } default: api.logger.Debug(api.ctx, "updater loop ticker skipped, update in progress") @@ -434,6 +702,7 @@ func (api *API) updaterLoop() { // Note that although we pass api.ctx here, updateContainers // has an internal timeout to prevent long blocking calls. done <- api.updateContainers(api.ctx) + close(done) } } } @@ -447,7 +716,7 @@ func (api *API) UpdateSubAgentClient(client SubAgentClient) { func (api *API) Routes() http.Handler { r := chi.NewRouter() - ensureInitialUpdateDoneMW := func(next http.Handler) http.Handler { + ensureInitDoneMW := func(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { select { case <-api.ctx.Done(): @@ -458,9 +727,8 @@ func (api *API) Routes() http.Handler { return case <-r.Context().Done(): return - case <-api.initialUpdateDone: - // Initial update is done, we can start processing - // requests. + case <-api.initDone: + // API init is done, we can start processing requests. } next.ServeHTTP(rw, r) }) @@ -469,18 +737,101 @@ func (api *API) Routes() http.Handler { // For now, all endpoints require the initial update to be done. // If we want to allow some endpoints to be available before // the initial update, we can enable this per-route. - r.Use(ensureInitialUpdateDoneMW) + r.Use(ensureInitDoneMW) r.Get("/", api.handleList) + r.Get("/watch", api.watchContainers) // TODO(mafredri): Simplify this route as the previous /devcontainers // /-route was dropped. We can drop the /devcontainers prefix here too. - r.Route("/devcontainers", func(r chi.Router) { - r.Post("/container/{container}/recreate", api.handleDevcontainerRecreate) + r.Route("/devcontainers/{devcontainer}", func(r chi.Router) { + r.Post("/recreate", api.handleDevcontainerRecreate) }) return r } +func (api *API) broadcastUpdatesLocked() { + // Broadcast state changes to WebSocket listeners. + for _, ch := range api.updateChans { + select { + case ch <- struct{}{}: + default: + } + } +} + +func (api *API) watchContainers(rw http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + conn, err := websocket.Accept(rw, r, nil) + if err != nil { + httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ + Message: "Failed to upgrade connection to websocket.", + Detail: err.Error(), + }) + return + } + + // Here we close the websocket for reading, so that the websocket library will handle pings and + // close frames. + _ = conn.CloseRead(context.Background()) + + ctx, wsNetConn := codersdk.WebsocketNetConn(ctx, conn, websocket.MessageText) + defer wsNetConn.Close() + + go httpapi.Heartbeat(ctx, conn) + + updateCh := make(chan struct{}, 1) + + api.mu.Lock() + api.updateChans = append(api.updateChans, updateCh) + api.mu.Unlock() + + defer func() { + api.mu.Lock() + api.updateChans = slices.DeleteFunc(api.updateChans, func(ch chan struct{}) bool { + return ch == updateCh + }) + close(updateCh) + api.mu.Unlock() + }() + + encoder := json.NewEncoder(wsNetConn) + + ct, err := api.getContainers() + if err != nil { + api.logger.Error(ctx, "unable to get containers", slog.Error(err)) + return + } + + if err := encoder.Encode(ct); err != nil { + api.logger.Error(ctx, "encode container list", slog.Error(err)) + return + } + + for { + select { + case <-api.ctx.Done(): + return + + case <-ctx.Done(): + return + + case <-updateCh: + ct, err := api.getContainers() + if err != nil { + api.logger.Error(ctx, "unable to get containers", slog.Error(err)) + continue + } + + if err := encoder.Encode(ct); err != nil { + api.logger.Error(ctx, "encode container list", slog.Error(err)) + return + } + } + } +} + // handleList handles the HTTP request to list containers. func (api *API) handleList(rw http.ResponseWriter, r *http.Request) { ct, err := api.getContainers() @@ -508,7 +859,6 @@ func (api *API) updateContainers(ctx context.Context) error { // will clear up on the next update. if !errors.Is(err, context.Canceled) { api.mu.Lock() - api.containers = codersdk.WorkspaceAgentListContainersResponse{} api.containersErr = err api.mu.Unlock() } @@ -521,8 +871,26 @@ func (api *API) updateContainers(ctx context.Context) error { api.mu.Lock() defer api.mu.Unlock() + var previouslyKnownDevcontainers map[string]codersdk.WorkspaceAgentDevcontainer + if len(api.updateChans) > 0 { + previouslyKnownDevcontainers = maps.Clone(api.knownDevcontainers) + } + api.processUpdatedContainersLocked(ctx, updated) + if len(api.updateChans) > 0 { + statesAreEqual := maps.EqualFunc( + previouslyKnownDevcontainers, + api.knownDevcontainers, + func(dc1, dc2 codersdk.WorkspaceAgentDevcontainer) bool { + return dc1.Equals(dc2) + }) + + if !statesAreEqual { + api.broadcastUpdatesLocked() + } + } + api.logger.Debug(ctx, "containers updated successfully", slog.F("container_count", len(api.containers.Containers)), slog.F("warning_count", len(api.containers.Warnings)), slog.F("devcontainer_count", len(api.knownDevcontainers))) return nil @@ -571,7 +939,8 @@ func (api *API) processUpdatedContainersLocked(ctx context.Context, updated code slog.F("config_file", configFile), ) - if len(api.containerLabelIncludeFilter) > 0 { + // Filter out devcontainer tests, unless explicitly set in include filters. + if len(api.containerLabelIncludeFilter) > 0 || container.Labels[DevcontainerIsTestRunLabel] == "true" { var ok bool for label, value := range api.containerLabelIncludeFilter { if v, found := container.Labels[label]; found && v == value { @@ -661,6 +1030,9 @@ func (api *API) processUpdatedContainersLocked(ctx context.Context, updated code err := api.maybeInjectSubAgentIntoContainerLocked(ctx, dc) if err != nil { logger.Error(ctx, "inject subagent into container failed", slog.Error(err)) + dc.Error = err.Error() + } else { + dc.Error = "" } } @@ -777,12 +1149,19 @@ func (api *API) RefreshContainers(ctx context.Context) (err error) { }() done := make(chan error, 1) + var sent bool + defer func() { + if !sent { + close(done) + } + }() select { case <-api.ctx.Done(): return xerrors.Errorf("API closed: %w", api.ctx.Err()) case <-ctx.Done(): return ctx.Err() case api.updateTrigger <- done: + sent = true select { case <-api.ctx.Done(): return xerrors.Errorf("API closed: %w", api.ctx.Err()) @@ -823,7 +1202,7 @@ func (api *API) getContainers() (codersdk.WorkspaceAgentListContainersResponse, devcontainers = append(devcontainers, dc) } slices.SortFunc(devcontainers, func(a, b codersdk.WorkspaceAgentDevcontainer) int { - return strings.Compare(a.Name, b.Name) + return strings.Compare(a.WorkspaceFolder, b.WorkspaceFolder) }) } @@ -838,68 +1217,40 @@ func (api *API) getContainers() (codersdk.WorkspaceAgentListContainersResponse, // devcontainer by referencing the container. func (api *API) handleDevcontainerRecreate(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - containerID := chi.URLParam(r, "container") + devcontainerID := chi.URLParam(r, "devcontainer") - if containerID == "" { + if devcontainerID == "" { httpapi.Write(ctx, w, http.StatusBadRequest, codersdk.Response{ - Message: "Missing container ID or name", - Detail: "Container ID or name is required to recreate a devcontainer.", - }) - return - } - - containers, err := api.getContainers() - if err != nil { - httpapi.Write(ctx, w, http.StatusInternalServerError, codersdk.Response{ - Message: "Could not list containers", - Detail: err.Error(), - }) - return - } - - containerIdx := slices.IndexFunc(containers.Containers, func(c codersdk.WorkspaceAgentContainer) bool { return c.Match(containerID) }) - if containerIdx == -1 { - httpapi.Write(ctx, w, http.StatusNotFound, codersdk.Response{ - Message: "Container not found", - Detail: "Container ID or name not found in the list of containers.", - }) - return - } - - container := containers.Containers[containerIdx] - workspaceFolder := container.Labels[DevcontainerLocalFolderLabel] - configPath := container.Labels[DevcontainerConfigFileLabel] - - // Workspace folder is required to recreate a container, we don't verify - // the config path here because it's optional. - if workspaceFolder == "" { - httpapi.Write(ctx, w, http.StatusBadRequest, codersdk.Response{ - Message: "Missing workspace folder label", - Detail: "The container is not a devcontainer, the container must have the workspace folder label to support recreation.", + Message: "Missing devcontainer ID", + Detail: "Devcontainer ID is required to recreate a devcontainer.", }) return } api.mu.Lock() - dc, ok := api.knownDevcontainers[workspaceFolder] - switch { - case !ok: + var dc codersdk.WorkspaceAgentDevcontainer + for _, knownDC := range api.knownDevcontainers { + if knownDC.ID.String() == devcontainerID { + dc = knownDC + break + } + } + if dc.ID == uuid.Nil { api.mu.Unlock() - // This case should not happen if the container is a valid devcontainer. - api.logger.Error(ctx, "devcontainer not found for workspace folder", slog.F("workspace_folder", workspaceFolder)) - httpapi.Write(ctx, w, http.StatusInternalServerError, codersdk.Response{ + httpapi.Write(ctx, w, http.StatusNotFound, codersdk.Response{ Message: "Devcontainer not found.", - Detail: fmt.Sprintf("Could not find devcontainer for workspace folder: %q", workspaceFolder), + Detail: fmt.Sprintf("Could not find devcontainer with ID: %q", devcontainerID), }) return - case dc.Status == codersdk.WorkspaceAgentDevcontainerStatusStarting: + } + if dc.Status == codersdk.WorkspaceAgentDevcontainerStatusStarting { api.mu.Unlock() httpapi.Write(ctx, w, http.StatusConflict, codersdk.Response{ Message: "Devcontainer recreation already in progress", - Detail: fmt.Sprintf("Recreation for workspace folder %q is already underway.", dc.WorkspaceFolder), + Detail: fmt.Sprintf("Recreation for devcontainer %q is already underway.", dc.Name), }) return } @@ -908,52 +1259,69 @@ func (api *API) handleDevcontainerRecreate(w http.ResponseWriter, r *http.Reques // devcontainer multiple times in parallel. dc.Status = codersdk.WorkspaceAgentDevcontainerStatusStarting dc.Container = nil + dc.Error = "" api.knownDevcontainers[dc.WorkspaceFolder] = dc - api.asyncWg.Add(1) - go api.recreateDevcontainer(dc, configPath) + api.broadcastUpdatesLocked() + + go func() { + _ = api.CreateDevcontainer(dc.WorkspaceFolder, dc.ConfigPath, WithRemoveExistingContainer()) + }() api.mu.Unlock() httpapi.Write(ctx, w, http.StatusAccepted, codersdk.Response{ Message: "Devcontainer recreation initiated", - Detail: fmt.Sprintf("Recreation process for workspace folder %q has started.", dc.WorkspaceFolder), + Detail: fmt.Sprintf("Recreation process for devcontainer %q has started.", dc.Name), }) } -// recreateDevcontainer should run in its own goroutine and is responsible for +// createDevcontainer should run in its own goroutine and is responsible for // recreating a devcontainer based on the provided devcontainer configuration. // It updates the devcontainer status and logs the process. The configPath is // passed as a parameter for the odd chance that the container being recreated // has a different config file than the one stored in the devcontainer state. // The devcontainer state must be set to starting and the asyncWg must be // incremented before calling this function. -func (api *API) recreateDevcontainer(dc codersdk.WorkspaceAgentDevcontainer, configPath string) { - defer api.asyncWg.Done() +func (api *API) CreateDevcontainer(workspaceFolder, configPath string, opts ...DevcontainerCLIUpOptions) error { + api.mu.Lock() + if api.closed { + api.mu.Unlock() + return nil + } + + dc, found := api.knownDevcontainers[workspaceFolder] + if !found { + api.mu.Unlock() + return xerrors.Errorf("devcontainer not found") + } var ( - err error ctx = api.ctx logger = api.logger.With( slog.F("devcontainer_id", dc.ID), slog.F("devcontainer_name", dc.Name), slog.F("workspace_folder", dc.WorkspaceFolder), - slog.F("config_path", configPath), + slog.F("config_path", dc.ConfigPath), ) ) - if dc.ConfigPath != configPath { - logger.Warn(ctx, "devcontainer config path mismatch", - slog.F("config_path_param", configPath), - ) - } - // Send logs via agent logging facilities. logSourceID := api.devcontainerLogSourceIDs[dc.WorkspaceFolder] if logSourceID == uuid.Nil { - // Fallback to the external log source ID if not found. + api.logger.Debug(api.ctx, "devcontainer log source ID not found, falling back to external log source ID") logSourceID = agentsdk.ExternalLogSourceID } + api.asyncWg.Add(1) + defer api.asyncWg.Done() + api.mu.Unlock() + + if dc.ConfigPath != configPath { + logger.Warn(ctx, "devcontainer config path mismatch", + slog.F("config_path_param", configPath), + ) + } + scriptLogger := api.scriptLogger(logSourceID) defer func() { flushCtx, cancel := context.WithTimeout(api.ctx, 5*time.Second) @@ -969,24 +1337,29 @@ func (api *API) recreateDevcontainer(dc codersdk.WorkspaceAgentDevcontainer, con logger.Debug(ctx, "starting devcontainer recreation") - _, err = api.dccli.Up(ctx, dc.WorkspaceFolder, configPath, WithUpOutput(infoW, errW), WithRemoveExistingContainer()) + upOptions := []DevcontainerCLIUpOptions{WithUpOutput(infoW, errW)} + upOptions = append(upOptions, opts...) + + _, err := api.dccli.Up(ctx, dc.WorkspaceFolder, configPath, upOptions...) if err != nil { // No need to log if the API is closing (context canceled), as this // is expected behavior when the API is shutting down. if !errors.Is(err, context.Canceled) { - logger.Error(ctx, "devcontainer recreation failed", slog.Error(err)) + logger.Error(ctx, "devcontainer creation failed", slog.Error(err)) } api.mu.Lock() dc = api.knownDevcontainers[dc.WorkspaceFolder] dc.Status = codersdk.WorkspaceAgentDevcontainerStatusError + dc.Error = err.Error() api.knownDevcontainers[dc.WorkspaceFolder] = dc api.recreateErrorTimes[dc.WorkspaceFolder] = api.clock.Now("agentcontainers", "recreate", "errorTimes") api.mu.Unlock() - return + + return xerrors.Errorf("start devcontainer: %w", err) } - logger.Info(ctx, "devcontainer recreated successfully") + logger.Info(ctx, "devcontainer created successfully") api.mu.Lock() dc = api.knownDevcontainers[dc.WorkspaceFolder] @@ -1002,15 +1375,20 @@ func (api *API) recreateDevcontainer(dc codersdk.WorkspaceAgentDevcontainer, con } } dc.Dirty = false + dc.Error = "" api.recreateSuccessTimes[dc.WorkspaceFolder] = api.clock.Now("agentcontainers", "recreate", "successTimes") api.knownDevcontainers[dc.WorkspaceFolder] = dc + api.broadcastUpdatesLocked() api.mu.Unlock() // Ensure an immediate refresh to accurately reflect the // devcontainer state after recreation. if err := api.RefreshContainers(ctx); err != nil { - logger.Error(ctx, "failed to trigger immediate refresh after devcontainer recreation", slog.Error(err)) + logger.Error(ctx, "failed to trigger immediate refresh after devcontainer creation", slog.Error(err)) + return xerrors.Errorf("refresh containers: %w", err) } + + return nil } // markDevcontainerDirty finds the devcontainer with the given config file path @@ -1259,6 +1637,7 @@ func (api *API) maybeInjectSubAgentIntoContainerLocked(ctx context.Context, dc c } var ( + featureOptionsAsEnvs []string appsWithPossibleDuplicates []SubAgentApp workspaceFolder = DevcontainerDefaultContainerWorkspaceFolder ) @@ -1270,12 +1649,16 @@ func (api *API) maybeInjectSubAgentIntoContainerLocked(ctx context.Context, dc c ) readConfig := func() (DevcontainerConfig, error) { - return api.dccli.ReadConfig(ctx, dc.WorkspaceFolder, dc.ConfigPath, []string{ - fmt.Sprintf("CODER_WORKSPACE_AGENT_NAME=%s", subAgentConfig.Name), - fmt.Sprintf("CODER_WORKSPACE_OWNER_NAME=%s", api.ownerName), - fmt.Sprintf("CODER_WORKSPACE_NAME=%s", api.workspaceName), - fmt.Sprintf("CODER_URL=%s", api.subAgentURL), - }) + return api.dccli.ReadConfig(ctx, dc.WorkspaceFolder, dc.ConfigPath, + append(featureOptionsAsEnvs, []string{ + fmt.Sprintf("CODER_WORKSPACE_AGENT_NAME=%s", subAgentConfig.Name), + fmt.Sprintf("CODER_WORKSPACE_OWNER_NAME=%s", api.ownerName), + fmt.Sprintf("CODER_WORKSPACE_NAME=%s", api.workspaceName), + fmt.Sprintf("CODER_WORKSPACE_PARENT_AGENT_NAME=%s", api.parentAgent), + fmt.Sprintf("CODER_URL=%s", api.subAgentURL), + fmt.Sprintf("CONTAINER_ID=%s", container.ID), + }...), + ) } if config, err = readConfig(); err != nil { @@ -1291,6 +1674,11 @@ func (api *API) maybeInjectSubAgentIntoContainerLocked(ctx context.Context, dc c workspaceFolder = config.Workspace.WorkspaceFolder + featureOptionsAsEnvs = config.MergedConfiguration.Features.OptionsAsEnvs() + if len(featureOptionsAsEnvs) > 0 { + configOutdated = true + } + // NOTE(DanielleMaywood): // We only want to take an agent name specified in the root customization layer. // This restricts the ability for a feature to specify the agent name. We may revisit @@ -1415,6 +1803,11 @@ func (api *API) maybeInjectSubAgentIntoContainerLocked(ctx context.Context, dc c return xerrors.Errorf("set agent binary executable: %w", err) } + // Make sure the agent binary is owned by a valid user so we can run it. + if _, err := api.ccli.ExecAs(ctx, container.ID, "root", "/bin/sh", "-c", fmt.Sprintf("chown $(id -u):$(id -g) %s", coderPathInsideContainer)); err != nil { + return xerrors.Errorf("set agent binary ownership: %w", err) + } + // Attempt to add CAP_NET_ADMIN to the binary to improve network // performance (optional, allow to fail). See `bootstrap_linux.sh`. // TODO(mafredri): Disable for now until we can figure out why this @@ -1452,7 +1845,9 @@ func (api *API) maybeInjectSubAgentIntoContainerLocked(ctx context.Context, dc c originalName := subAgentConfig.Name for attempt := 1; attempt <= maxAttemptsToNameAgent; attempt++ { - if proc.agent, err = client.Create(ctx, subAgentConfig); err == nil { + agent, err := client.Create(ctx, subAgentConfig) + if err == nil { + proc.agent = agent // Only reassign on success. if api.usingWorkspaceFolderName[dc.WorkspaceFolder] { api.devcontainerNames[dc.Name] = true delete(api.usingWorkspaceFolderName, dc.WorkspaceFolder) @@ -1460,7 +1855,6 @@ func (api *API) maybeInjectSubAgentIntoContainerLocked(ctx context.Context, dc c break } - // NOTE(DanielleMaywood): // Ordinarily we'd use `errors.As` here, but it didn't appear to work. Not // sure if this is because of the communication protocol? Instead I've opted @@ -1609,8 +2003,15 @@ func (api *API) Close() error { err := api.watcher.Close() // Wait for loops to finish. - <-api.watcherDone - <-api.updaterDone + if api.watcherDone != nil { + <-api.watcherDone + } + if api.updaterDone != nil { + <-api.updaterDone + } + if api.discoverDone != nil { + <-api.discoverDone + } // Wait for all async tasks to complete. api.asyncWg.Wait() diff --git a/agent/agentcontainers/api_test.go b/agent/agentcontainers/api_test.go index b6bae46c835c9..76e0fca6714d5 100644 --- a/agent/agentcontainers/api_test.go +++ b/agent/agentcontainers/api_test.go @@ -9,6 +9,7 @@ import ( "net/http/httptest" "os" "os/exec" + "path/filepath" "runtime" "slices" "strings" @@ -20,12 +21,14 @@ import ( "github.com/go-chi/chi/v5" "github.com/google/uuid" "github.com/lib/pq" + "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" "golang.org/x/xerrors" "cdr.dev/slog" + "cdr.dev/slog/sloggers/sloghuman" "cdr.dev/slog/sloggers/slogtest" "github.com/coder/coder/v2/agent/agentcontainers" "github.com/coder/coder/v2/agent/agentcontainers/acmock" @@ -35,6 +38,7 @@ import ( "github.com/coder/coder/v2/pty" "github.com/coder/coder/v2/testutil" "github.com/coder/quartz" + "github.com/coder/websocket" ) // fakeContainerCLI implements the agentcontainers.ContainerCLI interface for @@ -69,7 +73,7 @@ func (f *fakeContainerCLI) ExecAs(ctx context.Context, name, user string, args . type fakeDevcontainerCLI struct { upID string upErr error - upErrC chan error // If set, send to return err, close to return upErr. + upErrC chan func() error // If set, send to return err, close to return upErr. execErr error execErrC chan func(cmd string, args ...string) error // If set, send fn to return err, nil or close to return execErr. readConfig agentcontainers.DevcontainerConfig @@ -82,9 +86,9 @@ func (f *fakeDevcontainerCLI) Up(ctx context.Context, _, _ string, _ ...agentcon select { case <-ctx.Done(): return "", ctx.Err() - case err, ok := <-f.upErrC: + case fn, ok := <-f.upErrC: if ok { - return f.upID, err + return f.upID, fn() } } } @@ -342,6 +346,283 @@ func (f *fakeExecer) getLastCommand() *exec.Cmd { func TestAPI(t *testing.T) { t.Parallel() + t.Run("NoUpdaterLoopLogspam", func(t *testing.T) { + t.Parallel() + + var ( + ctx = testutil.Context(t, testutil.WaitShort) + logbuf strings.Builder + logger = slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}).Leveled(slog.LevelDebug).AppendSinks(sloghuman.Sink(&logbuf)) + mClock = quartz.NewMock(t) + tickerTrap = mClock.Trap().TickerFunc("updaterLoop") + firstErr = xerrors.New("first error") + secondErr = xerrors.New("second error") + fakeCLI = &fakeContainerCLI{ + listErr: firstErr, + } + fWatcher = newFakeWatcher(t) + ) + + api := agentcontainers.NewAPI(logger, + agentcontainers.WithWatcher(fWatcher), + agentcontainers.WithClock(mClock), + agentcontainers.WithContainerCLI(fakeCLI), + ) + api.Start() + defer api.Close() + + // The watcherLoop writes a log when it is initialized. + // We want to ensure this has happened before we start + // the test so that it does not intefere. + fWatcher.waitNext(ctx) + + // Make sure the ticker function has been registered + // before advancing the clock. + tickerTrap.MustWait(ctx).MustRelease(ctx) + tickerTrap.Close() + + logbuf.Reset() + + // First tick should handle the error. + _, aw := mClock.AdvanceNext() + aw.MustWait(ctx) + + // Verify first error is logged. + got := logbuf.String() + t.Logf("got log: %q", got) + require.Contains(t, got, "updater loop ticker failed", "first error should be logged") + require.Contains(t, got, "first error", "should contain first error message") + logbuf.Reset() + + // Second tick should handle the same error without logging it again. + _, aw = mClock.AdvanceNext() + aw.MustWait(ctx) + + // Verify same error is not logged again. + got = logbuf.String() + t.Logf("got log: %q", got) + require.Empty(t, got, "same error should not be logged again") + + // Change to a different error. + fakeCLI.listErr = secondErr + + // Third tick should handle the different error and log it. + _, aw = mClock.AdvanceNext() + aw.MustWait(ctx) + + // Verify different error is logged. + got = logbuf.String() + t.Logf("got log: %q", got) + require.Contains(t, got, "updater loop ticker failed", "different error should be logged") + require.Contains(t, got, "second error", "should contain second error message") + logbuf.Reset() + + // Clear the error to simulate success. + fakeCLI.listErr = nil + + // Fourth tick should succeed. + _, aw = mClock.AdvanceNext() + aw.MustWait(ctx) + + // Fifth tick should continue to succeed. + _, aw = mClock.AdvanceNext() + aw.MustWait(ctx) + + // Verify successful operations are logged properly. + got = logbuf.String() + t.Logf("got log: %q", got) + gotSuccessCount := strings.Count(got, "containers updated successfully") + require.GreaterOrEqual(t, gotSuccessCount, 2, "should have successful update got") + require.NotContains(t, got, "updater loop ticker failed", "no errors should be logged during success") + logbuf.Reset() + + // Reintroduce the original error. + fakeCLI.listErr = firstErr + + // Sixth tick should handle the error after success and log it. + _, aw = mClock.AdvanceNext() + aw.MustWait(ctx) + + // Verify error after success is logged. + got = logbuf.String() + t.Logf("got log: %q", got) + require.Contains(t, got, "updater loop ticker failed", "error after success should be logged") + require.Contains(t, got, "first error", "should contain first error message") + logbuf.Reset() + }) + + t.Run("Watch", func(t *testing.T) { + t.Parallel() + + fakeContainer1 := fakeContainer(t, func(c *codersdk.WorkspaceAgentContainer) { + c.ID = "container1" + c.FriendlyName = "devcontainer1" + c.Image = "busybox:latest" + c.Labels = map[string]string{ + agentcontainers.DevcontainerLocalFolderLabel: "/home/coder/project1", + agentcontainers.DevcontainerConfigFileLabel: "/home/coder/project1/.devcontainer/devcontainer.json", + } + }) + + fakeContainer2 := fakeContainer(t, func(c *codersdk.WorkspaceAgentContainer) { + c.ID = "container2" + c.FriendlyName = "devcontainer2" + c.Image = "ubuntu:latest" + c.Labels = map[string]string{ + agentcontainers.DevcontainerLocalFolderLabel: "/home/coder/project2", + agentcontainers.DevcontainerConfigFileLabel: "/home/coder/project2/.devcontainer/devcontainer.json", + } + }) + + stages := []struct { + containers []codersdk.WorkspaceAgentContainer + expected codersdk.WorkspaceAgentListContainersResponse + }{ + { + containers: []codersdk.WorkspaceAgentContainer{fakeContainer1}, + expected: codersdk.WorkspaceAgentListContainersResponse{ + Containers: []codersdk.WorkspaceAgentContainer{fakeContainer1}, + Devcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + Name: "project1", + WorkspaceFolder: fakeContainer1.Labels[agentcontainers.DevcontainerLocalFolderLabel], + ConfigPath: fakeContainer1.Labels[agentcontainers.DevcontainerConfigFileLabel], + Status: "running", + Container: &fakeContainer1, + }, + }, + }, + }, + { + containers: []codersdk.WorkspaceAgentContainer{fakeContainer1, fakeContainer2}, + expected: codersdk.WorkspaceAgentListContainersResponse{ + Containers: []codersdk.WorkspaceAgentContainer{fakeContainer1, fakeContainer2}, + Devcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + Name: "project1", + WorkspaceFolder: fakeContainer1.Labels[agentcontainers.DevcontainerLocalFolderLabel], + ConfigPath: fakeContainer1.Labels[agentcontainers.DevcontainerConfigFileLabel], + Status: "running", + Container: &fakeContainer1, + }, + { + Name: "project2", + WorkspaceFolder: fakeContainer2.Labels[agentcontainers.DevcontainerLocalFolderLabel], + ConfigPath: fakeContainer2.Labels[agentcontainers.DevcontainerConfigFileLabel], + Status: "running", + Container: &fakeContainer2, + }, + }, + }, + }, + { + containers: []codersdk.WorkspaceAgentContainer{fakeContainer2}, + expected: codersdk.WorkspaceAgentListContainersResponse{ + Containers: []codersdk.WorkspaceAgentContainer{fakeContainer2}, + Devcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + Name: "", + WorkspaceFolder: fakeContainer1.Labels[agentcontainers.DevcontainerLocalFolderLabel], + ConfigPath: fakeContainer1.Labels[agentcontainers.DevcontainerConfigFileLabel], + Status: "stopped", + Container: nil, + }, + { + Name: "project2", + WorkspaceFolder: fakeContainer2.Labels[agentcontainers.DevcontainerLocalFolderLabel], + ConfigPath: fakeContainer2.Labels[agentcontainers.DevcontainerConfigFileLabel], + Status: "running", + Container: &fakeContainer2, + }, + }, + }, + }, + } + + var ( + ctx = testutil.Context(t, testutil.WaitShort) + mClock = quartz.NewMock(t) + updaterTickerTrap = mClock.Trap().TickerFunc("updaterLoop") + mCtrl = gomock.NewController(t) + mLister = acmock.NewMockContainerCLI(mCtrl) + logger = slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}).Leveled(slog.LevelDebug) + ) + + // Set up initial state for immediate send on connection + mLister.EXPECT().List(gomock.Any()).Return(codersdk.WorkspaceAgentListContainersResponse{Containers: stages[0].containers}, nil) + mLister.EXPECT().DetectArchitecture(gomock.Any(), gomock.Any()).Return("", nil).AnyTimes() + + api := agentcontainers.NewAPI(logger, + agentcontainers.WithClock(mClock), + agentcontainers.WithContainerCLI(mLister), + agentcontainers.WithWatcher(watcher.NewNoop()), + ) + api.Start() + defer api.Close() + + srv := httptest.NewServer(api.Routes()) + defer srv.Close() + + updaterTickerTrap.MustWait(ctx).MustRelease(ctx) + defer updaterTickerTrap.Close() + + client, res, err := websocket.Dial(ctx, srv.URL+"/watch", nil) + require.NoError(t, err) + if res != nil && res.Body != nil { + defer res.Body.Close() + } + + // Read initial state sent immediately on connection + mt, msg, err := client.Read(ctx) + require.NoError(t, err) + require.Equal(t, websocket.MessageText, mt) + + var got codersdk.WorkspaceAgentListContainersResponse + err = json.Unmarshal(msg, &got) + require.NoError(t, err) + + require.Equal(t, stages[0].expected.Containers, got.Containers) + require.Len(t, got.Devcontainers, len(stages[0].expected.Devcontainers)) + for j, expectedDev := range stages[0].expected.Devcontainers { + gotDev := got.Devcontainers[j] + require.Equal(t, expectedDev.Name, gotDev.Name) + require.Equal(t, expectedDev.WorkspaceFolder, gotDev.WorkspaceFolder) + require.Equal(t, expectedDev.ConfigPath, gotDev.ConfigPath) + require.Equal(t, expectedDev.Status, gotDev.Status) + require.Equal(t, expectedDev.Container, gotDev.Container) + } + + // Process remaining stages through updater loop + for i, stage := range stages[1:] { + mLister.EXPECT().List(gomock.Any()).Return(codersdk.WorkspaceAgentListContainersResponse{Containers: stage.containers}, nil) + + // Given: We allow the update loop to progress + _, aw := mClock.AdvanceNext() + aw.MustWait(ctx) + + // When: We attempt to read a message from the socket. + mt, msg, err := client.Read(ctx) + require.NoError(t, err) + require.Equal(t, websocket.MessageText, mt) + + // Then: We expect the receieved message matches the expected response. + var got codersdk.WorkspaceAgentListContainersResponse + err = json.Unmarshal(msg, &got) + require.NoError(t, err) + + require.Equal(t, stages[i+1].expected.Containers, got.Containers) + require.Len(t, got.Devcontainers, len(stages[i+1].expected.Devcontainers)) + for j, expectedDev := range stages[i+1].expected.Devcontainers { + gotDev := got.Devcontainers[j] + require.Equal(t, expectedDev.Name, gotDev.Name) + require.Equal(t, expectedDev.WorkspaceFolder, gotDev.WorkspaceFolder) + require.Equal(t, expectedDev.ConfigPath, gotDev.ConfigPath) + require.Equal(t, expectedDev.Status, gotDev.Status) + require.Equal(t, expectedDev.Container, gotDev.Container) + } + } + }) + // List tests the API.getContainers method using a mock // implementation. It specifically tests caching behavior. t.Run("List", func(t *testing.T) { @@ -437,6 +718,7 @@ func TestAPI(t *testing.T) { agentcontainers.WithContainerCLI(mLister), agentcontainers.WithContainerLabelIncludeFilter("this.label.does.not.exist.ignore.devcontainers", "true"), ) + api.Start() defer api.Close() r.Mount("/", api.Routes()) @@ -492,78 +774,77 @@ func TestAPI(t *testing.T) { t.Run("Recreate", func(t *testing.T) { t.Parallel() - validContainer := codersdk.WorkspaceAgentContainer{ - ID: "container-id", - FriendlyName: "container-name", + devcontainerID1 := uuid.New() + devcontainerID2 := uuid.New() + workspaceFolder1 := "/workspace/test1" + workspaceFolder2 := "/workspace/test2" + configPath1 := "/workspace/test1/.devcontainer/devcontainer.json" + configPath2 := "/workspace/test2/.devcontainer/devcontainer.json" + + // Create a container that represents an existing devcontainer + devContainer1 := codersdk.WorkspaceAgentContainer{ + ID: "container-1", + FriendlyName: "test-container-1", Running: true, Labels: map[string]string{ - agentcontainers.DevcontainerLocalFolderLabel: "/workspaces", - agentcontainers.DevcontainerConfigFileLabel: "/workspace/.devcontainer/devcontainer.json", + agentcontainers.DevcontainerLocalFolderLabel: workspaceFolder1, + agentcontainers.DevcontainerConfigFileLabel: configPath1, }, } - missingFolderContainer := codersdk.WorkspaceAgentContainer{ - ID: "missing-folder-container", - FriendlyName: "missing-folder-container", - Labels: map[string]string{}, + devContainer2 := codersdk.WorkspaceAgentContainer{ + ID: "container-2", + FriendlyName: "test-container-2", + Running: true, + Labels: map[string]string{ + agentcontainers.DevcontainerLocalFolderLabel: workspaceFolder2, + agentcontainers.DevcontainerConfigFileLabel: configPath2, + }, } tests := []struct { - name string - containerID string - lister *fakeContainerCLI - devcontainerCLI *fakeDevcontainerCLI - wantStatus []int - wantBody []string + name string + devcontainerID string + setupDevcontainers []codersdk.WorkspaceAgentDevcontainer + lister *fakeContainerCLI + devcontainerCLI *fakeDevcontainerCLI + wantStatus []int + wantBody []string }{ { - name: "Missing container ID", - containerID: "", + name: "Missing devcontainer ID", + devcontainerID: "", lister: &fakeContainerCLI{}, devcontainerCLI: &fakeDevcontainerCLI{}, wantStatus: []int{http.StatusBadRequest}, - wantBody: []string{"Missing container ID or name"}, - }, - { - name: "List error", - containerID: "container-id", - lister: &fakeContainerCLI{ - listErr: xerrors.New("list error"), - }, - devcontainerCLI: &fakeDevcontainerCLI{}, - wantStatus: []int{http.StatusInternalServerError}, - wantBody: []string{"Could not list containers"}, + wantBody: []string{"Missing devcontainer ID"}, }, { - name: "Container not found", - containerID: "nonexistent-container", + name: "Devcontainer not found", + devcontainerID: uuid.NewString(), lister: &fakeContainerCLI{ - containers: codersdk.WorkspaceAgentListContainersResponse{ - Containers: []codersdk.WorkspaceAgentContainer{validContainer}, - }, + arch: "", // Unsupported architecture, don't inject subagent. }, devcontainerCLI: &fakeDevcontainerCLI{}, wantStatus: []int{http.StatusNotFound}, - wantBody: []string{"Container not found"}, + wantBody: []string{"Devcontainer not found"}, }, { - name: "Missing workspace folder label", - containerID: "missing-folder-container", - lister: &fakeContainerCLI{ - containers: codersdk.WorkspaceAgentListContainersResponse{ - Containers: []codersdk.WorkspaceAgentContainer{missingFolderContainer}, + name: "Devcontainer CLI error", + devcontainerID: devcontainerID1.String(), + setupDevcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + ID: devcontainerID1, + Name: "test-devcontainer-1", + WorkspaceFolder: workspaceFolder1, + ConfigPath: configPath1, + Status: codersdk.WorkspaceAgentDevcontainerStatusRunning, + Container: &devContainer1, }, }, - devcontainerCLI: &fakeDevcontainerCLI{}, - wantStatus: []int{http.StatusBadRequest}, - wantBody: []string{"Missing workspace folder label"}, - }, - { - name: "Devcontainer CLI error", - containerID: "container-id", lister: &fakeContainerCLI{ containers: codersdk.WorkspaceAgentListContainersResponse{ - Containers: []codersdk.WorkspaceAgentContainer{validContainer}, + Containers: []codersdk.WorkspaceAgentContainer{devContainer1}, }, arch: "", // Unsupported architecture, don't inject subagent. }, @@ -574,11 +855,21 @@ func TestAPI(t *testing.T) { wantBody: []string{"Devcontainer recreation initiated", "Devcontainer recreation already in progress"}, }, { - name: "OK", - containerID: "container-id", + name: "OK", + devcontainerID: devcontainerID2.String(), + setupDevcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + ID: devcontainerID2, + Name: "test-devcontainer-2", + WorkspaceFolder: workspaceFolder2, + ConfigPath: configPath2, + Status: codersdk.WorkspaceAgentDevcontainerStatusRunning, + Container: &devContainer2, + }, + }, lister: &fakeContainerCLI{ containers: codersdk.WorkspaceAgentListContainersResponse{ - Containers: []codersdk.WorkspaceAgentContainer{validContainer}, + Containers: []codersdk.WorkspaceAgentContainer{devContainer2}, }, arch: "", // Unsupported architecture, don't inject subagent. }, @@ -603,17 +894,21 @@ func TestAPI(t *testing.T) { nowRecreateErrorTrap := mClock.Trap().Now("recreate", "errorTimes") nowRecreateSuccessTrap := mClock.Trap().Now("recreate", "successTimes") - tt.devcontainerCLI.upErrC = make(chan error) + tt.devcontainerCLI.upErrC = make(chan func() error) // Setup router with the handler under test. r := chi.NewRouter() + api := agentcontainers.NewAPI( logger, agentcontainers.WithClock(mClock), agentcontainers.WithContainerCLI(tt.lister), agentcontainers.WithDevcontainerCLI(tt.devcontainerCLI), agentcontainers.WithWatcher(watcher.NewNoop()), + agentcontainers.WithDevcontainers(tt.setupDevcontainers, nil), ) + + api.Start() defer api.Close() r.Mount("/", api.Routes()) @@ -624,7 +919,7 @@ func TestAPI(t *testing.T) { for i := range tt.wantStatus { // Simulate HTTP request to the recreate endpoint. - req := httptest.NewRequest(http.MethodPost, "/devcontainers/container/"+tt.containerID+"/recreate", nil). + req := httptest.NewRequest(http.MethodPost, "/devcontainers/"+tt.devcontainerID+"/recreate", nil). WithContext(ctx) rec := httptest.NewRecorder() r.ServeHTTP(rec, req) @@ -747,6 +1042,7 @@ func TestAPI(t *testing.T) { knownDevcontainers []codersdk.WorkspaceAgentDevcontainer wantStatus int wantCount int + wantTestContainer bool verify func(t *testing.T, devcontainers []codersdk.WorkspaceAgentDevcontainer) }{ { @@ -993,6 +1289,13 @@ func TestAPI(t *testing.T) { assert.Len(t, names, 4, "should have four unique devcontainer names") }, }, + { + name: "Include test containers", + lister: &fakeContainerCLI{}, + wantStatus: http.StatusOK, + wantTestContainer: true, + wantCount: 1, // Will be appended. + }, } for _, tt := range tests { @@ -1005,14 +1308,33 @@ func TestAPI(t *testing.T) { mClock.Set(time.Now()).MustWait(testutil.Context(t, testutil.WaitShort)) tickerTrap := mClock.Trap().TickerFunc("updaterLoop") + // This container should be ignored unless explicitly included. + tt.lister.containers.Containers = append(tt.lister.containers.Containers, codersdk.WorkspaceAgentContainer{ + ID: "test-container-1", + FriendlyName: "test-container-1", + Running: true, + Labels: map[string]string{ + agentcontainers.DevcontainerLocalFolderLabel: "/workspace/test1", + agentcontainers.DevcontainerConfigFileLabel: "/workspace/test1/.devcontainer/devcontainer.json", + agentcontainers.DevcontainerIsTestRunLabel: "true", + }, + }) + // Setup router with the handler under test. r := chi.NewRouter() apiOptions := []agentcontainers.Option{ agentcontainers.WithClock(mClock), agentcontainers.WithContainerCLI(tt.lister), + agentcontainers.WithDevcontainerCLI(&fakeDevcontainerCLI{}), agentcontainers.WithWatcher(watcher.NewNoop()), } + if tt.wantTestContainer { + apiOptions = append(apiOptions, agentcontainers.WithContainerLabelIncludeFilter( + agentcontainers.DevcontainerIsTestRunLabel, "true", + )) + } + // Generate matching scripts for the known devcontainers // (required to extract log source ID). var scripts []codersdk.WorkspaceAgentScript @@ -1027,6 +1349,7 @@ func TestAPI(t *testing.T) { } api := agentcontainers.NewAPI(logger, apiOptions...) + api.Start() defer api.Close() r.Mount("/", api.Routes()) @@ -1038,6 +1361,11 @@ func TestAPI(t *testing.T) { tickerTrap.MustWait(ctx).MustRelease(ctx) tickerTrap.Close() + for _, dc := range tt.knownDevcontainers { + err := api.CreateDevcontainer(dc.WorkspaceFolder, dc.ConfigPath) + require.NoError(t, err) + } + // Advance the clock to run the updater loop. _, aw := mClock.AdvanceNext() aw.MustWait(ctx) @@ -1111,6 +1439,7 @@ func TestAPI(t *testing.T) { []codersdk.WorkspaceAgentScript{{LogSourceID: uuid.New(), ID: dc.ID}}, ), ) + api.Start() defer api.Close() // Make sure the ticker function has been registered @@ -1206,6 +1535,7 @@ func TestAPI(t *testing.T) { agentcontainers.WithWatcher(fWatcher), agentcontainers.WithClock(mClock), ) + api.Start() defer api.Close() r := chi.NewRouter() @@ -1343,6 +1673,7 @@ func TestAPI(t *testing.T) { mCCLI.EXPECT().ExecAs(gomock.Any(), "test-container-id", "root", "mkdir", "-p", "/.coder-agent").Return(nil, nil), mCCLI.EXPECT().Copy(gomock.Any(), "test-container-id", coderBin, "/.coder-agent/coder").Return(nil), mCCLI.EXPECT().ExecAs(gomock.Any(), "test-container-id", "root", "chmod", "0755", "/.coder-agent", "/.coder-agent/coder").Return(nil, nil), + mCCLI.EXPECT().ExecAs(gomock.Any(), "test-container-id", "root", "/bin/sh", "-c", "chown $(id -u):$(id -g) /.coder-agent/coder").Return(nil, nil), ) mClock.Set(time.Now()).MustWait(ctx) @@ -1356,8 +1687,9 @@ func TestAPI(t *testing.T) { agentcontainers.WithSubAgentClient(fakeSAC), agentcontainers.WithSubAgentURL("test-subagent-url"), agentcontainers.WithDevcontainerCLI(fakeDCCLI), - agentcontainers.WithManifestInfo("test-user", "test-workspace"), + agentcontainers.WithManifestInfo("test-user", "test-workspace", "test-parent-agent", "/parent-agent"), ) + api.Start() apiClose := func() { closeOnce.Do(func() { // Close before api.Close() defer to avoid deadlock after test. @@ -1377,7 +1709,9 @@ func TestAPI(t *testing.T) { assert.Contains(t, envs, "CODER_WORKSPACE_AGENT_NAME=coder") assert.Contains(t, envs, "CODER_WORKSPACE_NAME=test-workspace") assert.Contains(t, envs, "CODER_WORKSPACE_OWNER_NAME=test-user") + assert.Contains(t, envs, "CODER_WORKSPACE_PARENT_AGENT_NAME=test-parent-agent") assert.Contains(t, envs, "CODER_URL=test-subagent-url") + assert.Contains(t, envs, "CONTAINER_ID=test-container-id") return nil }) @@ -1428,6 +1762,7 @@ func TestAPI(t *testing.T) { mCCLI.EXPECT().ExecAs(gomock.Any(), "test-container-id", "root", "mkdir", "-p", "/.coder-agent").Return(nil, nil), mCCLI.EXPECT().Copy(gomock.Any(), "test-container-id", coderBin, "/.coder-agent/coder").Return(nil), mCCLI.EXPECT().ExecAs(gomock.Any(), "test-container-id", "root", "chmod", "0755", "/.coder-agent", "/.coder-agent/coder").Return(nil, nil), + mCCLI.EXPECT().ExecAs(gomock.Any(), "test-container-id", "root", "/bin/sh", "-c", "chown $(id -u):$(id -g) /.coder-agent/coder").Return(nil, nil), ) // Verify that the agent has started. @@ -1488,6 +1823,7 @@ func TestAPI(t *testing.T) { mCCLI.EXPECT().ExecAs(gomock.Any(), "new-test-container-id", "root", "mkdir", "-p", "/.coder-agent").Return(nil, nil), mCCLI.EXPECT().Copy(gomock.Any(), "new-test-container-id", coderBin, "/.coder-agent/coder").Return(nil), mCCLI.EXPECT().ExecAs(gomock.Any(), "new-test-container-id", "root", "chmod", "0755", "/.coder-agent", "/.coder-agent/coder").Return(nil, nil), + mCCLI.EXPECT().ExecAs(gomock.Any(), "new-test-container-id", "root", "/bin/sh", "-c", "chown $(id -u):$(id -g) /.coder-agent/coder").Return(nil, nil), ) fakeDCCLI.readConfig.MergedConfiguration.Customizations.Coder = []agentcontainers.CoderCustomization{ @@ -1519,7 +1855,9 @@ func TestAPI(t *testing.T) { assert.Contains(t, envs, "CODER_WORKSPACE_AGENT_NAME=coder") assert.Contains(t, envs, "CODER_WORKSPACE_NAME=test-workspace") assert.Contains(t, envs, "CODER_WORKSPACE_OWNER_NAME=test-user") + assert.Contains(t, envs, "CODER_WORKSPACE_PARENT_AGENT_NAME=test-parent-agent") assert.Contains(t, envs, "CODER_URL=test-subagent-url") + assert.NotContains(t, envs, "CONTAINER_ID=test-container-id") return nil }) @@ -1578,6 +1916,7 @@ func TestAPI(t *testing.T) { agentcontainers.WithSubAgentClient(fakeSAC), agentcontainers.WithDevcontainerCLI(&fakeDevcontainerCLI{}), ) + api.Start() defer api.Close() tickerTrap.MustWait(ctx).MustRelease(ctx) @@ -1591,6 +1930,240 @@ func TestAPI(t *testing.T) { assert.Empty(t, fakeSAC.agents) }) + t.Run("Error", func(t *testing.T) { + t.Parallel() + + if runtime.GOOS == "windows" { + t.Skip("Dev Container tests are not supported on Windows (this test uses mocks but fails due to Windows paths)") + } + + t.Run("DuringUp", func(t *testing.T) { + t.Parallel() + + var ( + ctx = testutil.Context(t, testutil.WaitMedium) + logger = slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}).Leveled(slog.LevelDebug) + mClock = quartz.NewMock(t) + fCCLI = &fakeContainerCLI{arch: ""} + fDCCLI = &fakeDevcontainerCLI{ + upErrC: make(chan func() error, 1), + } + fSAC = &fakeSubAgentClient{ + logger: logger.Named("fakeSubAgentClient"), + } + + testDevcontainer = codersdk.WorkspaceAgentDevcontainer{ + ID: uuid.New(), + Name: "test-devcontainer", + WorkspaceFolder: "/workspaces/project", + ConfigPath: "/workspaces/project/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + } + ) + + mClock.Set(time.Now()).MustWait(ctx) + tickerTrap := mClock.Trap().TickerFunc("updaterLoop") + nowRecreateErrorTrap := mClock.Trap().Now("recreate", "errorTimes") + nowRecreateSuccessTrap := mClock.Trap().Now("recreate", "successTimes") + + api := agentcontainers.NewAPI(logger, + agentcontainers.WithClock(mClock), + agentcontainers.WithContainerCLI(fCCLI), + agentcontainers.WithDevcontainerCLI(fDCCLI), + agentcontainers.WithDevcontainers( + []codersdk.WorkspaceAgentDevcontainer{testDevcontainer}, + []codersdk.WorkspaceAgentScript{{ID: testDevcontainer.ID, LogSourceID: uuid.New()}}, + ), + agentcontainers.WithSubAgentClient(fSAC), + agentcontainers.WithSubAgentURL("test-subagent-url"), + agentcontainers.WithWatcher(watcher.NewNoop()), + ) + api.Start() + defer func() { + close(fDCCLI.upErrC) + api.Close() + }() + + r := chi.NewRouter() + r.Mount("/", api.Routes()) + + tickerTrap.MustWait(ctx).MustRelease(ctx) + tickerTrap.Close() + + // Given: We send a 'recreate' request. + req := httptest.NewRequest(http.MethodPost, "/devcontainers/"+testDevcontainer.ID.String()+"/recreate", nil) + rec := httptest.NewRecorder() + r.ServeHTTP(rec, req) + require.Equal(t, http.StatusAccepted, rec.Code) + + // Given: We simulate an error running `devcontainer up` + simulatedError := xerrors.New("simulated error") + testutil.RequireSend(ctx, t, fDCCLI.upErrC, func() error { return simulatedError }) + + nowRecreateErrorTrap.MustWait(ctx).MustRelease(ctx) + nowRecreateErrorTrap.Close() + + req = httptest.NewRequest(http.MethodGet, "/", nil) + rec = httptest.NewRecorder() + r.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + + var response codersdk.WorkspaceAgentListContainersResponse + err := json.NewDecoder(rec.Body).Decode(&response) + require.NoError(t, err) + + // Then: We expect that there will be an error associated with the devcontainer. + require.Len(t, response.Devcontainers, 1) + require.Equal(t, "simulated error", response.Devcontainers[0].Error) + + // Given: We send another 'recreate' request. + req = httptest.NewRequest(http.MethodPost, "/devcontainers/"+testDevcontainer.ID.String()+"/recreate", nil) + rec = httptest.NewRecorder() + r.ServeHTTP(rec, req) + require.Equal(t, http.StatusAccepted, rec.Code) + + // Given: We allow `devcontainer up` to succeed. + testutil.RequireSend(ctx, t, fDCCLI.upErrC, func() error { + req = httptest.NewRequest(http.MethodGet, "/", nil) + rec = httptest.NewRecorder() + r.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + + response = codersdk.WorkspaceAgentListContainersResponse{} + err = json.NewDecoder(rec.Body).Decode(&response) + require.NoError(t, err) + + // Then: We make sure that the error has been cleared before running up. + require.Len(t, response.Devcontainers, 1) + require.Equal(t, "", response.Devcontainers[0].Error) + + return nil + }) + + nowRecreateSuccessTrap.MustWait(ctx).MustRelease(ctx) + nowRecreateSuccessTrap.Close() + + req = httptest.NewRequest(http.MethodGet, "/", nil) + rec = httptest.NewRecorder() + r.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + + response = codersdk.WorkspaceAgentListContainersResponse{} + err = json.NewDecoder(rec.Body).Decode(&response) + require.NoError(t, err) + + // Then: We also expect no error after running up.. + require.Len(t, response.Devcontainers, 1) + require.Equal(t, "", response.Devcontainers[0].Error) + }) + + t.Run("DuringInjection", func(t *testing.T) { + t.Parallel() + + var ( + ctx = testutil.Context(t, testutil.WaitMedium) + logger = slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}).Leveled(slog.LevelDebug) + mClock = quartz.NewMock(t) + mCCLI = acmock.NewMockContainerCLI(gomock.NewController(t)) + fDCCLI = &fakeDevcontainerCLI{} + fSAC = &fakeSubAgentClient{ + logger: logger.Named("fakeSubAgentClient"), + createErrC: make(chan error, 1), + } + + containerCreatedAt = time.Now() + testContainer = codersdk.WorkspaceAgentContainer{ + ID: "test-container-id", + FriendlyName: "test-container", + Image: "test-image", + Running: true, + CreatedAt: containerCreatedAt, + Labels: map[string]string{ + agentcontainers.DevcontainerLocalFolderLabel: "/workspaces", + agentcontainers.DevcontainerConfigFileLabel: "/workspace/.devcontainer/devcontainer.json", + }, + } + ) + + coderBin, err := os.Executable() + require.NoError(t, err) + + // Mock the `List` function to always return the test container. + mCCLI.EXPECT().List(gomock.Any()).Return(codersdk.WorkspaceAgentListContainersResponse{ + Containers: []codersdk.WorkspaceAgentContainer{testContainer}, + }, nil).AnyTimes() + + // We're going to force the container CLI to fail, which will allow us to test the + // error handling. + simulatedError := xerrors.New("simulated error") + mCCLI.EXPECT().DetectArchitecture(gomock.Any(), testContainer.ID).Return("", simulatedError).Times(1) + + mClock.Set(containerCreatedAt).MustWait(ctx) + tickerTrap := mClock.Trap().TickerFunc("updaterLoop") + + api := agentcontainers.NewAPI(logger, + agentcontainers.WithClock(mClock), + agentcontainers.WithContainerCLI(mCCLI), + agentcontainers.WithDevcontainerCLI(fDCCLI), + agentcontainers.WithSubAgentClient(fSAC), + agentcontainers.WithSubAgentURL("test-subagent-url"), + agentcontainers.WithWatcher(watcher.NewNoop()), + ) + api.Start() + defer func() { + close(fSAC.createErrC) + api.Close() + }() + + r := chi.NewRouter() + r.Mount("/", api.Routes()) + + // Given: We allow an attempt at creation to occur. + tickerTrap.MustWait(ctx).MustRelease(ctx) + tickerTrap.Close() + + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + r.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + + var response codersdk.WorkspaceAgentListContainersResponse + err = json.NewDecoder(rec.Body).Decode(&response) + require.NoError(t, err) + + // Then: We expect that there will be an error associated with the devcontainer. + require.Len(t, response.Devcontainers, 1) + require.Equal(t, "detect architecture: simulated error", response.Devcontainers[0].Error) + + gomock.InOrder( + mCCLI.EXPECT().DetectArchitecture(gomock.Any(), testContainer.ID).Return(runtime.GOARCH, nil), + mCCLI.EXPECT().ExecAs(gomock.Any(), testContainer.ID, "root", "mkdir", "-p", "/.coder-agent").Return(nil, nil), + mCCLI.EXPECT().Copy(gomock.Any(), testContainer.ID, coderBin, "/.coder-agent/coder").Return(nil), + mCCLI.EXPECT().ExecAs(gomock.Any(), testContainer.ID, "root", "chmod", "0755", "/.coder-agent", "/.coder-agent/coder").Return(nil, nil), + mCCLI.EXPECT().ExecAs(gomock.Any(), testContainer.ID, "root", "/bin/sh", "-c", "chown $(id -u):$(id -g) /.coder-agent/coder").Return(nil, nil), + ) + + // Given: We allow creation to succeed. + testutil.RequireSend(ctx, t, fSAC.createErrC, nil) + + _, aw := mClock.AdvanceNext() + aw.MustWait(ctx) + + req = httptest.NewRequest(http.MethodGet, "/", nil) + rec = httptest.NewRecorder() + r.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + + response = codersdk.WorkspaceAgentListContainersResponse{} + err = json.NewDecoder(rec.Body).Decode(&response) + require.NoError(t, err) + + // Then: We expect that the error will be gone + require.Len(t, response.Devcontainers, 1) + require.Equal(t, "", response.Devcontainers[0].Error) + }) + }) + t.Run("Create", func(t *testing.T) { t.Parallel() @@ -1886,6 +2459,7 @@ func TestAPI(t *testing.T) { mCCLI.EXPECT().ExecAs(gomock.Any(), testContainer.ID, "root", "mkdir", "-p", "/.coder-agent").Return(nil, nil), mCCLI.EXPECT().Copy(gomock.Any(), testContainer.ID, coderBin, "/.coder-agent/coder").Return(nil), mCCLI.EXPECT().ExecAs(gomock.Any(), testContainer.ID, "root", "chmod", "0755", "/.coder-agent", "/.coder-agent/coder").Return(nil, nil), + mCCLI.EXPECT().ExecAs(gomock.Any(), testContainer.ID, "root", "/bin/sh", "-c", "chown $(id -u):$(id -g) /.coder-agent/coder").Return(nil, nil), ) mClock.Set(time.Now()).MustWait(ctx) @@ -1899,6 +2473,7 @@ func TestAPI(t *testing.T) { agentcontainers.WithSubAgentURL("test-subagent-url"), agentcontainers.WithWatcher(watcher.NewNoop()), ) + api.Start() defer api.Close() // Close before api.Close() defer to avoid deadlock after test. @@ -1978,6 +2553,7 @@ func TestAPI(t *testing.T) { mCCLI.EXPECT().ExecAs(gomock.Any(), testContainer.ID, "root", "mkdir", "-p", "/.coder-agent").Return(nil, nil), mCCLI.EXPECT().Copy(gomock.Any(), testContainer.ID, coderBin, "/.coder-agent/coder").Return(nil), mCCLI.EXPECT().ExecAs(gomock.Any(), testContainer.ID, "root", "chmod", "0755", "/.coder-agent", "/.coder-agent/coder").Return(nil, nil), + mCCLI.EXPECT().ExecAs(gomock.Any(), testContainer.ID, "root", "/bin/sh", "-c", "chown $(id -u):$(id -g) /.coder-agent/coder").Return(nil, nil), ) mClock.Set(time.Now()).MustWait(ctx) @@ -1991,6 +2567,7 @@ func TestAPI(t *testing.T) { agentcontainers.WithSubAgentURL("test-subagent-url"), agentcontainers.WithWatcher(watcher.NewNoop()), ) + api.Start() defer api.Close() // Close before api.Close() defer to avoid deadlock after test. @@ -2019,32 +2596,154 @@ func TestAPI(t *testing.T) { require.Len(t, fSAC.created, 1) }) - t.Run("CommandEnv", func(t *testing.T) { + t.Run("ReadConfigWithFeatureOptions", func(t *testing.T) { t.Parallel() - ctx := testutil.Context(t, testutil.WaitShort) - logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}).Leveled(slog.LevelDebug) - - // Create fake execer to track execution details. - fakeExec := &fakeExecer{} - - // Custom CommandEnv that returns specific values. - testShell := "/bin/custom-shell" - testDir := t.TempDir() - testEnv := []string{"CUSTOM_VAR=test_value", "PATH=/custom/path"} - - commandEnv := func(ei usershell.EnvInfoer, addEnv []string) (shell, dir string, env []string, err error) { - return testShell, testDir, testEnv, nil + if runtime.GOOS == "windows" { + t.Skip("Dev Container tests are not supported on Windows (this test uses mocks but fails due to Windows paths)") } - mClock := quartz.NewMock(t) // Stop time. + var ( + ctx = testutil.Context(t, testutil.WaitMedium) + logger = testutil.Logger(t) + mClock = quartz.NewMock(t) + mCCLI = acmock.NewMockContainerCLI(gomock.NewController(t)) + fSAC = &fakeSubAgentClient{ + logger: logger.Named("fakeSubAgentClient"), + createErrC: make(chan error, 1), + } + fDCCLI = &fakeDevcontainerCLI{ + readConfig: agentcontainers.DevcontainerConfig{ + MergedConfiguration: agentcontainers.DevcontainerMergedConfiguration{ + Features: agentcontainers.DevcontainerFeatures{ + "./code-server": map[string]any{ + "port": 9090, + }, + "ghcr.io/devcontainers/features/docker-in-docker:2": map[string]any{ + "moby": "false", + }, + }, + }, + Workspace: agentcontainers.DevcontainerWorkspace{ + WorkspaceFolder: "/workspaces/coder", + }, + }, + readConfigErrC: make(chan func(envs []string) error, 2), + } - // Create API with CommandEnv. + testContainer = codersdk.WorkspaceAgentContainer{ + ID: "test-container-id", + FriendlyName: "test-container", + Image: "test-image", + Running: true, + CreatedAt: time.Now(), + Labels: map[string]string{ + agentcontainers.DevcontainerLocalFolderLabel: "/workspaces/coder", + agentcontainers.DevcontainerConfigFileLabel: "/workspaces/coder/.devcontainer/devcontainer.json", + }, + } + ) + + coderBin, err := os.Executable() + require.NoError(t, err) + + // Mock the `List` function to always return our test container. + mCCLI.EXPECT().List(gomock.Any()).Return(codersdk.WorkspaceAgentListContainersResponse{ + Containers: []codersdk.WorkspaceAgentContainer{testContainer}, + }, nil).AnyTimes() + + // Mock the steps used for injecting the coder agent. + gomock.InOrder( + mCCLI.EXPECT().DetectArchitecture(gomock.Any(), testContainer.ID).Return(runtime.GOARCH, nil), + mCCLI.EXPECT().ExecAs(gomock.Any(), testContainer.ID, "root", "mkdir", "-p", "/.coder-agent").Return(nil, nil), + mCCLI.EXPECT().Copy(gomock.Any(), testContainer.ID, coderBin, "/.coder-agent/coder").Return(nil), + mCCLI.EXPECT().ExecAs(gomock.Any(), testContainer.ID, "root", "chmod", "0755", "/.coder-agent", "/.coder-agent/coder").Return(nil, nil), + mCCLI.EXPECT().ExecAs(gomock.Any(), testContainer.ID, "root", "/bin/sh", "-c", "chown $(id -u):$(id -g) /.coder-agent/coder").Return(nil, nil), + ) + + mClock.Set(time.Now()).MustWait(ctx) + tickerTrap := mClock.Trap().TickerFunc("updaterLoop") + + api := agentcontainers.NewAPI(logger, + agentcontainers.WithClock(mClock), + agentcontainers.WithContainerCLI(mCCLI), + agentcontainers.WithDevcontainerCLI(fDCCLI), + agentcontainers.WithSubAgentClient(fSAC), + agentcontainers.WithSubAgentURL("test-subagent-url"), + agentcontainers.WithWatcher(watcher.NewNoop()), + agentcontainers.WithManifestInfo("test-user", "test-workspace", "test-parent-agent", "/parent-agent"), + ) + api.Start() + defer api.Close() + + // Close before api.Close() defer to avoid deadlock after test. + defer close(fSAC.createErrC) + defer close(fDCCLI.readConfigErrC) + + // Allow agent creation and injection to succeed. + testutil.RequireSend(ctx, t, fSAC.createErrC, nil) + + testutil.RequireSend(ctx, t, fDCCLI.readConfigErrC, func(envs []string) error { + assert.Contains(t, envs, "CODER_WORKSPACE_AGENT_NAME=coder") + assert.Contains(t, envs, "CODER_WORKSPACE_NAME=test-workspace") + assert.Contains(t, envs, "CODER_WORKSPACE_OWNER_NAME=test-user") + assert.Contains(t, envs, "CODER_WORKSPACE_PARENT_AGENT_NAME=test-parent-agent") + assert.Contains(t, envs, "CODER_URL=test-subagent-url") + assert.Contains(t, envs, "CONTAINER_ID=test-container-id") + // First call should not have feature envs. + assert.NotContains(t, envs, "FEATURE_CODE_SERVER_OPTION_PORT=9090") + assert.NotContains(t, envs, "FEATURE_DOCKER_IN_DOCKER_OPTION_MOBY=false") + return nil + }) + + testutil.RequireSend(ctx, t, fDCCLI.readConfigErrC, func(envs []string) error { + assert.Contains(t, envs, "CODER_WORKSPACE_AGENT_NAME=coder") + assert.Contains(t, envs, "CODER_WORKSPACE_NAME=test-workspace") + assert.Contains(t, envs, "CODER_WORKSPACE_OWNER_NAME=test-user") + assert.Contains(t, envs, "CODER_WORKSPACE_PARENT_AGENT_NAME=test-parent-agent") + assert.Contains(t, envs, "CODER_URL=test-subagent-url") + assert.Contains(t, envs, "CONTAINER_ID=test-container-id") + // Second call should have feature envs from the first config read. + assert.Contains(t, envs, "FEATURE_CODE_SERVER_OPTION_PORT=9090") + assert.Contains(t, envs, "FEATURE_DOCKER_IN_DOCKER_OPTION_MOBY=false") + return nil + }) + + // Wait until the ticker has been registered. + tickerTrap.MustWait(ctx).MustRelease(ctx) + tickerTrap.Close() + + // Verify agent was created successfully + require.Len(t, fSAC.created, 1) + }) + + t.Run("CommandEnv", func(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitShort) + logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}).Leveled(slog.LevelDebug) + + // Create fake execer to track execution details. + fakeExec := &fakeExecer{} + + // Custom CommandEnv that returns specific values. + testShell := "/bin/custom-shell" + testDir := t.TempDir() + testEnv := []string{"CUSTOM_VAR=test_value", "PATH=/custom/path"} + + commandEnv := func(ei usershell.EnvInfoer, addEnv []string) (shell, dir string, env []string, err error) { + return testShell, testDir, testEnv, nil + } + + mClock := quartz.NewMock(t) // Stop time. + + // Create API with CommandEnv. api := agentcontainers.NewAPI(logger, agentcontainers.WithClock(mClock), agentcontainers.WithExecer(fakeExec), agentcontainers.WithCommandEnv(commandEnv), ) + api.Start() defer api.Close() // Call RefreshContainers directly to trigger CommandEnv usage. @@ -2134,12 +2833,16 @@ func TestAPI(t *testing.T) { agentcontainers.WithWatcher(fWatcher), agentcontainers.WithClock(mClock), ) + api.Start() defer func() { close(fakeSAC.createErrC) close(fakeSAC.deleteErrC) api.Close() }() + err := api.RefreshContainers(ctx) + require.NoError(t, err, "RefreshContainers should not error") + r := chi.NewRouter() r.Mount("/", api.Routes()) @@ -2150,7 +2853,7 @@ func TestAPI(t *testing.T) { require.Equal(t, http.StatusOK, rec.Code) var response codersdk.WorkspaceAgentListContainersResponse - err := json.NewDecoder(rec.Body).Decode(&response) + err = json.NewDecoder(rec.Body).Decode(&response) require.NoError(t, err) assert.Empty(t, response.Devcontainers, "ignored devcontainer should not be in response when ignore=true") @@ -2189,8 +2892,12 @@ func TestAPI(t *testing.T) { Op: fsnotify.Write, }) - err = api.RefreshContainers(ctx) - require.NoError(t, err) + require.Eventuallyf(t, func() bool { + err = api.RefreshContainers(ctx) + require.NoError(t, err) + + return len(fakeSAC.agents) == 1 + }, testutil.WaitShort, testutil.IntervalFast, "subagent should be created after config change") t.Log("Phase 2: Cont, waiting for sub agent to exit") exitSubAgentOnce.Do(func() { @@ -2225,8 +2932,12 @@ func TestAPI(t *testing.T) { Op: fsnotify.Write, }) - err = api.RefreshContainers(ctx) - require.NoError(t, err) + require.Eventuallyf(t, func() bool { + err = api.RefreshContainers(ctx) + require.NoError(t, err) + + return len(fakeSAC.agents) == 0 + }, testutil.WaitShort, testutil.IntervalFast, "subagent should be deleted after config change") req = httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx) rec = httptest.NewRecorder() @@ -2334,6 +3045,7 @@ func TestSubAgentCreationWithNameRetry(t *testing.T) { agentcontainers.WithSubAgentClient(fSAC), agentcontainers.WithWatcher(watcher.NewNoop()), ) + api.Start() defer api.Close() tickerTrap.MustWait(ctx).MustRelease(ctx) @@ -2407,3 +3119,769 @@ func fakeContainer(t *testing.T, mut ...func(*codersdk.WorkspaceAgentContainer)) } return ct } + +func TestWithDevcontainersNameGeneration(t *testing.T) { + t.Parallel() + + if runtime.GOOS == "windows" { + t.Skip("Dev Container tests are not supported on Windows") + } + + devcontainers := []codersdk.WorkspaceAgentDevcontainer{ + { + ID: uuid.New(), + Name: "original-name", + WorkspaceFolder: "/home/coder/foo/project", + ConfigPath: "/home/coder/foo/project/.devcontainer/devcontainer.json", + }, + { + ID: uuid.New(), + Name: "another-name", + WorkspaceFolder: "/home/coder/bar/project", + ConfigPath: "/home/coder/bar/project/.devcontainer/devcontainer.json", + }, + } + + scripts := []codersdk.WorkspaceAgentScript{ + {ID: devcontainers[0].ID, LogSourceID: uuid.New()}, + {ID: devcontainers[1].ID, LogSourceID: uuid.New()}, + } + + logger := testutil.Logger(t) + + // This should trigger the WithDevcontainers code path where names are generated + api := agentcontainers.NewAPI(logger, + agentcontainers.WithDevcontainers(devcontainers, scripts), + agentcontainers.WithContainerCLI(&fakeContainerCLI{ + containers: codersdk.WorkspaceAgentListContainersResponse{ + Containers: []codersdk.WorkspaceAgentContainer{ + fakeContainer(t, func(c *codersdk.WorkspaceAgentContainer) { + c.ID = "some-container-id-1" + c.FriendlyName = "container-name-1" + c.Labels[agentcontainers.DevcontainerLocalFolderLabel] = "/home/coder/baz/project" + c.Labels[agentcontainers.DevcontainerConfigFileLabel] = "/home/coder/baz/project/.devcontainer/devcontainer.json" + }), + }, + }, + }), + agentcontainers.WithDevcontainerCLI(&fakeDevcontainerCLI{}), + agentcontainers.WithSubAgentClient(&fakeSubAgentClient{}), + agentcontainers.WithWatcher(watcher.NewNoop()), + ) + defer api.Close() + api.Start() + + r := chi.NewRouter() + r.Mount("/", api.Routes()) + + ctx := context.Background() + + err := api.RefreshContainers(ctx) + require.NoError(t, err, "RefreshContainers should not error") + + // Initial request returns the initial data. + req := httptest.NewRequest(http.MethodGet, "/", nil). + WithContext(ctx) + rec := httptest.NewRecorder() + r.ServeHTTP(rec, req) + + require.Equal(t, http.StatusOK, rec.Code) + var response codersdk.WorkspaceAgentListContainersResponse + err = json.NewDecoder(rec.Body).Decode(&response) + require.NoError(t, err) + + // Verify the devcontainers have the expected names. + require.Len(t, response.Devcontainers, 3, "should have two devcontainers") + assert.NotEqual(t, "original-name", response.Devcontainers[2].Name, "first devcontainer should not keep original name") + assert.Equal(t, "project", response.Devcontainers[2].Name, "first devcontainer should use the project folder name") + assert.NotEqual(t, "another-name", response.Devcontainers[0].Name, "second devcontainer should not keep original name") + assert.Equal(t, "bar-project", response.Devcontainers[0].Name, "second devcontainer should has a collision and uses the folder name with a prefix") + assert.Equal(t, "baz-project", response.Devcontainers[1].Name, "third devcontainer should use the folder name with a prefix since it collides with the first two") +} + +func TestDevcontainerDiscovery(t *testing.T) { + t.Parallel() + + if runtime.GOOS == "windows" { + t.Skip("Dev Container tests are not supported on Windows") + } + + // We discover dev container projects by searching + // for git repositories at the agent's directory, + // and then recursively walking through these git + // repositories to find any `.devcontainer/devcontainer.json` + // files. These tests are to validate that behavior. + + homeDir, err := os.UserHomeDir() + require.NoError(t, err) + + tests := []struct { + name string + agentDir string + fs map[string]string + expected []codersdk.WorkspaceAgentDevcontainer + }{ + { + name: "GitProjectInRootDir/SingleProject", + agentDir: "/home/coder", + fs: map[string]string{ + "/home/coder/.git/HEAD": "", + "/home/coder/.devcontainer/devcontainer.json": "", + }, + expected: []codersdk.WorkspaceAgentDevcontainer{ + { + WorkspaceFolder: "/home/coder", + ConfigPath: "/home/coder/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + }, + }, + { + name: "GitProjectInRootDir/MultipleProjects", + agentDir: "/home/coder", + fs: map[string]string{ + "/home/coder/.git/HEAD": "", + "/home/coder/.devcontainer/devcontainer.json": "", + "/home/coder/site/.devcontainer/devcontainer.json": "", + }, + expected: []codersdk.WorkspaceAgentDevcontainer{ + { + WorkspaceFolder: "/home/coder", + ConfigPath: "/home/coder/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + { + WorkspaceFolder: "/home/coder/site", + ConfigPath: "/home/coder/site/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + }, + }, + { + name: "GitProjectInChildDir/SingleProject", + agentDir: "/home/coder", + fs: map[string]string{ + "/home/coder/coder/.git/HEAD": "", + "/home/coder/coder/.devcontainer/devcontainer.json": "", + }, + expected: []codersdk.WorkspaceAgentDevcontainer{ + { + WorkspaceFolder: "/home/coder/coder", + ConfigPath: "/home/coder/coder/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + }, + }, + { + name: "GitProjectInChildDir/MultipleProjects", + agentDir: "/home/coder", + fs: map[string]string{ + "/home/coder/coder/.git/HEAD": "", + "/home/coder/coder/.devcontainer/devcontainer.json": "", + "/home/coder/coder/site/.devcontainer/devcontainer.json": "", + }, + expected: []codersdk.WorkspaceAgentDevcontainer{ + { + WorkspaceFolder: "/home/coder/coder", + ConfigPath: "/home/coder/coder/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + { + WorkspaceFolder: "/home/coder/coder/site", + ConfigPath: "/home/coder/coder/site/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + }, + }, + { + name: "GitProjectInMultipleChildDirs/SingleProjectEach", + agentDir: "/home/coder", + fs: map[string]string{ + "/home/coder/coder/.git/HEAD": "", + "/home/coder/coder/.devcontainer/devcontainer.json": "", + "/home/coder/envbuilder/.git/HEAD": "", + "/home/coder/envbuilder/.devcontainer/devcontainer.json": "", + }, + expected: []codersdk.WorkspaceAgentDevcontainer{ + { + WorkspaceFolder: "/home/coder/coder", + ConfigPath: "/home/coder/coder/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + { + WorkspaceFolder: "/home/coder/envbuilder", + ConfigPath: "/home/coder/envbuilder/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + }, + }, + { + name: "GitProjectInMultipleChildDirs/MultipleProjectEach", + agentDir: "/home/coder", + fs: map[string]string{ + "/home/coder/coder/.git/HEAD": "", + "/home/coder/coder/.devcontainer/devcontainer.json": "", + "/home/coder/coder/site/.devcontainer/devcontainer.json": "", + "/home/coder/envbuilder/.git/HEAD": "", + "/home/coder/envbuilder/.devcontainer/devcontainer.json": "", + "/home/coder/envbuilder/x/.devcontainer/devcontainer.json": "", + }, + expected: []codersdk.WorkspaceAgentDevcontainer{ + { + WorkspaceFolder: "/home/coder/coder", + ConfigPath: "/home/coder/coder/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + { + WorkspaceFolder: "/home/coder/coder/site", + ConfigPath: "/home/coder/coder/site/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + { + WorkspaceFolder: "/home/coder/envbuilder", + ConfigPath: "/home/coder/envbuilder/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + { + WorkspaceFolder: "/home/coder/envbuilder/x", + ConfigPath: "/home/coder/envbuilder/x/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + }, + }, + { + name: "RespectGitIgnore", + agentDir: "/home/coder", + fs: map[string]string{ + "/home/coder/coder/.git/HEAD": "", + "/home/coder/coder/.gitignore": "y/", + "/home/coder/coder/.devcontainer.json": "", + "/home/coder/coder/x/y/.devcontainer.json": "", + }, + expected: []codersdk.WorkspaceAgentDevcontainer{ + { + WorkspaceFolder: "/home/coder/coder", + ConfigPath: "/home/coder/coder/.devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + }, + }, + { + name: "RespectNestedGitIgnore", + agentDir: "/home/coder", + fs: map[string]string{ + "/home/coder/coder/.git/HEAD": "", + "/home/coder/coder/.devcontainer.json": "", + "/home/coder/coder/y/.devcontainer.json": "", + "/home/coder/coder/x/.gitignore": "y/", + "/home/coder/coder/x/y/.devcontainer.json": "", + }, + expected: []codersdk.WorkspaceAgentDevcontainer{ + { + WorkspaceFolder: "/home/coder/coder", + ConfigPath: "/home/coder/coder/.devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + { + WorkspaceFolder: "/home/coder/coder/y", + ConfigPath: "/home/coder/coder/y/.devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + }, + }, + { + name: "RespectGitInfoExclude", + agentDir: "/home/coder", + fs: map[string]string{ + "/home/coder/coder/.git/HEAD": "", + "/home/coder/coder/.git/info/exclude": "y/", + "/home/coder/coder/.devcontainer.json": "", + "/home/coder/coder/x/y/.devcontainer.json": "", + }, + expected: []codersdk.WorkspaceAgentDevcontainer{ + { + WorkspaceFolder: "/home/coder/coder", + ConfigPath: "/home/coder/coder/.devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + }, + }, + { + name: "RespectHomeGitConfig", + agentDir: homeDir, + fs: map[string]string{ + "/tmp/.gitignore": "node_modules/", + filepath.Join(homeDir, ".gitconfig"): ` + [core] + excludesFile = /tmp/.gitignore + `, + + filepath.Join(homeDir, ".git/HEAD"): "", + filepath.Join(homeDir, ".devcontainer.json"): "", + filepath.Join(homeDir, "node_modules/y/.devcontainer.json"): "", + }, + expected: []codersdk.WorkspaceAgentDevcontainer{ + { + WorkspaceFolder: homeDir, + ConfigPath: filepath.Join(homeDir, ".devcontainer.json"), + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + }, + }, + { + name: "IgnoreNonsenseDevcontainerNames", + agentDir: "/home/coder", + fs: map[string]string{ + "/home/coder/.git/HEAD": "", + + "/home/coder/.devcontainer/devcontainer.json.bak": "", + "/home/coder/.devcontainer/devcontainer.json.old": "", + "/home/coder/.devcontainer/devcontainer.json~": "", + "/home/coder/.devcontainer/notdevcontainer.json": "", + "/home/coder/.devcontainer/devcontainer.json.swp": "", + + "/home/coder/foo/.devcontainer.json.bak": "", + "/home/coder/foo/.devcontainer.json.old": "", + "/home/coder/foo/.devcontainer.json~": "", + "/home/coder/foo/.notdevcontainer.json": "", + "/home/coder/foo/.devcontainer.json.swp": "", + + "/home/coder/bar/.devcontainer.json": "", + }, + expected: []codersdk.WorkspaceAgentDevcontainer{ + { + WorkspaceFolder: "/home/coder/bar", + ConfigPath: "/home/coder/bar/.devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }, + }, + }, + } + + initFS := func(t *testing.T, files map[string]string) afero.Fs { + t.Helper() + + fs := afero.NewMemMapFs() + for name, content := range files { + err := afero.WriteFile(fs, name, []byte(content+"\n"), 0o600) + require.NoError(t, err) + } + return fs + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + var ( + ctx = testutil.Context(t, testutil.WaitShort) + logger = testutil.Logger(t) + mClock = quartz.NewMock(t) + tickerTrap = mClock.Trap().TickerFunc("updaterLoop") + + r = chi.NewRouter() + ) + + api := agentcontainers.NewAPI(logger, + agentcontainers.WithClock(mClock), + agentcontainers.WithWatcher(watcher.NewNoop()), + agentcontainers.WithFileSystem(initFS(t, tt.fs)), + agentcontainers.WithManifestInfo("owner", "workspace", "parent-agent", tt.agentDir), + agentcontainers.WithContainerCLI(&fakeContainerCLI{}), + agentcontainers.WithDevcontainerCLI(&fakeDevcontainerCLI{}), + agentcontainers.WithProjectDiscovery(true), + ) + api.Start() + defer api.Close() + r.Mount("/", api.Routes()) + + tickerTrap.MustWait(ctx).MustRelease(ctx) + tickerTrap.Close() + + // Wait until all projects have been discovered + require.Eventuallyf(t, func() bool { + req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx) + rec := httptest.NewRecorder() + r.ServeHTTP(rec, req) + + got := codersdk.WorkspaceAgentListContainersResponse{} + err := json.NewDecoder(rec.Body).Decode(&got) + require.NoError(t, err) + + return len(got.Devcontainers) >= len(tt.expected) + }, testutil.WaitShort, testutil.IntervalFast, "dev containers never found") + + // Now projects have been discovered, we'll allow the updater loop + // to set the appropriate status for these containers. + _, aw := mClock.AdvanceNext() + aw.MustWait(ctx) + + // Now we'll fetch the list of dev containers + req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx) + rec := httptest.NewRecorder() + r.ServeHTTP(rec, req) + + got := codersdk.WorkspaceAgentListContainersResponse{} + err := json.NewDecoder(rec.Body).Decode(&got) + require.NoError(t, err) + + // We will set the IDs of each dev container to uuid.Nil to simplify + // this check. + for idx := range got.Devcontainers { + got.Devcontainers[idx].ID = uuid.Nil + } + + // Sort the expected dev containers and got dev containers by their workspace folder. + // This helps ensure a deterministic test. + slices.SortFunc(tt.expected, func(a, b codersdk.WorkspaceAgentDevcontainer) int { + return strings.Compare(a.WorkspaceFolder, b.WorkspaceFolder) + }) + slices.SortFunc(got.Devcontainers, func(a, b codersdk.WorkspaceAgentDevcontainer) int { + return strings.Compare(a.WorkspaceFolder, b.WorkspaceFolder) + }) + + require.Equal(t, tt.expected, got.Devcontainers) + }) + } + + t.Run("NoErrorWhenAgentDirAbsent", func(t *testing.T) { + t.Parallel() + + logger := testutil.Logger(t) + + // Given: We have an empty agent directory + agentDir := "" + + api := agentcontainers.NewAPI(logger, + agentcontainers.WithWatcher(watcher.NewNoop()), + agentcontainers.WithManifestInfo("owner", "workspace", "parent-agent", agentDir), + agentcontainers.WithContainerCLI(&fakeContainerCLI{}), + agentcontainers.WithDevcontainerCLI(&fakeDevcontainerCLI{}), + agentcontainers.WithProjectDiscovery(true), + ) + + // When: We start and close the API + api.Start() + api.Close() + + // Then: We expect there to have been no errors. + // This is implicitly handled by `testutil.Logger` failing when it + // detects an error has been logged. + }) + + t.Run("AutoStart", func(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + agentDir string + fs map[string]string + expectDevcontainerCount int + setupMocks func(mDCCLI *acmock.MockDevcontainerCLI) + }{ + { + name: "SingleEnabled", + agentDir: "/home/coder", + expectDevcontainerCount: 1, + fs: map[string]string{ + "/home/coder/.git/HEAD": "", + "/home/coder/.devcontainer/devcontainer.json": "", + }, + setupMocks: func(mDCCLI *acmock.MockDevcontainerCLI) { + gomock.InOrder( + // Given: This dev container has auto start enabled. + mDCCLI.EXPECT().ReadConfig(gomock.Any(), + "/home/coder", + "/home/coder/.devcontainer/devcontainer.json", + []string{}, + ).Return(agentcontainers.DevcontainerConfig{ + Configuration: agentcontainers.DevcontainerConfiguration{ + Customizations: agentcontainers.DevcontainerCustomizations{ + Coder: agentcontainers.CoderCustomization{ + AutoStart: true, + }, + }, + }, + }, nil), + + // Then: We expect it to be started. + mDCCLI.EXPECT().Up(gomock.Any(), + "/home/coder", + "/home/coder/.devcontainer/devcontainer.json", + gomock.Any(), + ).Return("", nil), + ) + }, + }, + { + name: "SingleDisabled", + agentDir: "/home/coder", + expectDevcontainerCount: 1, + fs: map[string]string{ + "/home/coder/.git/HEAD": "", + "/home/coder/.devcontainer/devcontainer.json": "", + }, + setupMocks: func(mDCCLI *acmock.MockDevcontainerCLI) { + gomock.InOrder( + // Given: This dev container has auto start disabled. + mDCCLI.EXPECT().ReadConfig(gomock.Any(), + "/home/coder", + "/home/coder/.devcontainer/devcontainer.json", + []string{}, + ).Return(agentcontainers.DevcontainerConfig{ + Configuration: agentcontainers.DevcontainerConfiguration{ + Customizations: agentcontainers.DevcontainerCustomizations{ + Coder: agentcontainers.CoderCustomization{ + AutoStart: false, + }, + }, + }, + }, nil), + + // Then: We expect it to _not_ be started. + mDCCLI.EXPECT().Up(gomock.Any(), + "/home/coder", + "/home/coder/.devcontainer/devcontainer.json", + gomock.Any(), + ).Return("", nil).Times(0), + ) + }, + }, + { + name: "OneEnabledOneDisabled", + agentDir: "/home/coder", + expectDevcontainerCount: 2, + fs: map[string]string{ + "/home/coder/.git/HEAD": "", + "/home/coder/.devcontainer/devcontainer.json": "", + "/home/coder/project/.devcontainer.json": "", + }, + setupMocks: func(mDCCLI *acmock.MockDevcontainerCLI) { + gomock.InOrder( + // Given: This dev container has auto start enabled. + mDCCLI.EXPECT().ReadConfig(gomock.Any(), + "/home/coder", + "/home/coder/.devcontainer/devcontainer.json", + []string{}, + ).Return(agentcontainers.DevcontainerConfig{ + Configuration: agentcontainers.DevcontainerConfiguration{ + Customizations: agentcontainers.DevcontainerCustomizations{ + Coder: agentcontainers.CoderCustomization{ + AutoStart: true, + }, + }, + }, + }, nil), + + // Then: We expect it to be started. + mDCCLI.EXPECT().Up(gomock.Any(), + "/home/coder", + "/home/coder/.devcontainer/devcontainer.json", + gomock.Any(), + ).Return("", nil), + ) + + gomock.InOrder( + // Given: This dev container has auto start disabled. + mDCCLI.EXPECT().ReadConfig(gomock.Any(), + "/home/coder/project", + "/home/coder/project/.devcontainer.json", + []string{}, + ).Return(agentcontainers.DevcontainerConfig{ + Configuration: agentcontainers.DevcontainerConfiguration{ + Customizations: agentcontainers.DevcontainerCustomizations{ + Coder: agentcontainers.CoderCustomization{ + AutoStart: false, + }, + }, + }, + }, nil), + + // Then: We expect it to _not_ be started. + mDCCLI.EXPECT().Up(gomock.Any(), + "/home/coder/project", + "/home/coder/project/.devcontainer.json", + gomock.Any(), + ).Return("", nil).Times(0), + ) + }, + }, + { + name: "MultipleEnabled", + agentDir: "/home/coder", + expectDevcontainerCount: 2, + fs: map[string]string{ + "/home/coder/.git/HEAD": "", + "/home/coder/.devcontainer/devcontainer.json": "", + "/home/coder/project/.devcontainer.json": "", + }, + setupMocks: func(mDCCLI *acmock.MockDevcontainerCLI) { + gomock.InOrder( + // Given: This dev container has auto start enabled. + mDCCLI.EXPECT().ReadConfig(gomock.Any(), + "/home/coder", + "/home/coder/.devcontainer/devcontainer.json", + []string{}, + ).Return(agentcontainers.DevcontainerConfig{ + Configuration: agentcontainers.DevcontainerConfiguration{ + Customizations: agentcontainers.DevcontainerCustomizations{ + Coder: agentcontainers.CoderCustomization{ + AutoStart: true, + }, + }, + }, + }, nil), + + // Then: We expect it to be started. + mDCCLI.EXPECT().Up(gomock.Any(), + "/home/coder", + "/home/coder/.devcontainer/devcontainer.json", + gomock.Any(), + ).Return("", nil), + ) + + gomock.InOrder( + // Given: This dev container has auto start enabled. + mDCCLI.EXPECT().ReadConfig(gomock.Any(), + "/home/coder/project", + "/home/coder/project/.devcontainer.json", + []string{}, + ).Return(agentcontainers.DevcontainerConfig{ + Configuration: agentcontainers.DevcontainerConfiguration{ + Customizations: agentcontainers.DevcontainerCustomizations{ + Coder: agentcontainers.CoderCustomization{ + AutoStart: true, + }, + }, + }, + }, nil), + + // Then: We expect it to be started. + mDCCLI.EXPECT().Up(gomock.Any(), + "/home/coder/project", + "/home/coder/project/.devcontainer.json", + gomock.Any(), + ).Return("", nil), + ) + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + var ( + ctx = testutil.Context(t, testutil.WaitShort) + logger = testutil.Logger(t) + mClock = quartz.NewMock(t) + mDCCLI = acmock.NewMockDevcontainerCLI(gomock.NewController(t)) + + r = chi.NewRouter() + ) + + // Given: We setup our mocks. These mocks handle our expectations for these + // tests. If there are missing/unexpected mock calls, the test will fail. + tt.setupMocks(mDCCLI) + + api := agentcontainers.NewAPI(logger, + agentcontainers.WithClock(mClock), + agentcontainers.WithWatcher(watcher.NewNoop()), + agentcontainers.WithFileSystem(initFS(t, tt.fs)), + agentcontainers.WithManifestInfo("owner", "workspace", "parent-agent", "/home/coder"), + agentcontainers.WithContainerCLI(&fakeContainerCLI{}), + agentcontainers.WithDevcontainerCLI(mDCCLI), + agentcontainers.WithProjectDiscovery(true), + agentcontainers.WithDiscoveryAutostart(true), + ) + api.Start() + defer api.Close() + r.Mount("/", api.Routes()) + + // When: All expected dev containers have been found. + require.Eventuallyf(t, func() bool { + req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx) + rec := httptest.NewRecorder() + r.ServeHTTP(rec, req) + + got := codersdk.WorkspaceAgentListContainersResponse{} + err := json.NewDecoder(rec.Body).Decode(&got) + require.NoError(t, err) + + return len(got.Devcontainers) >= tt.expectDevcontainerCount + }, testutil.WaitShort, testutil.IntervalFast, "dev containers never found") + + // Then: We expect the mock infra to not fail. + }) + } + + t.Run("Disabled", func(t *testing.T) { + t.Parallel() + var ( + ctx = testutil.Context(t, testutil.WaitShort) + logger = testutil.Logger(t) + mClock = quartz.NewMock(t) + mDCCLI = acmock.NewMockDevcontainerCLI(gomock.NewController(t)) + + fs = map[string]string{ + "/home/coder/.git/HEAD": "", + "/home/coder/.devcontainer/devcontainer.json": "", + } + + r = chi.NewRouter() + ) + + // We expect that neither `ReadConfig`, nor `Up` are called as we + // have explicitly disabled the agentcontainers API from attempting + // to autostart devcontainers that it discovers. + mDCCLI.EXPECT().ReadConfig(gomock.Any(), + "/home/coder", + "/home/coder/.devcontainer/devcontainer.json", + []string{}, + ).Return(agentcontainers.DevcontainerConfig{ + Configuration: agentcontainers.DevcontainerConfiguration{ + Customizations: agentcontainers.DevcontainerCustomizations{ + Coder: agentcontainers.CoderCustomization{ + AutoStart: true, + }, + }, + }, + }, nil).Times(0) + + mDCCLI.EXPECT().Up(gomock.Any(), + "/home/coder", + "/home/coder/.devcontainer/devcontainer.json", + gomock.Any(), + ).Return("", nil).Times(0) + + api := agentcontainers.NewAPI(logger, + agentcontainers.WithClock(mClock), + agentcontainers.WithWatcher(watcher.NewNoop()), + agentcontainers.WithFileSystem(initFS(t, fs)), + agentcontainers.WithManifestInfo("owner", "workspace", "parent-agent", "/home/coder"), + agentcontainers.WithContainerCLI(&fakeContainerCLI{}), + agentcontainers.WithDevcontainerCLI(mDCCLI), + agentcontainers.WithProjectDiscovery(true), + agentcontainers.WithDiscoveryAutostart(false), + ) + api.Start() + defer api.Close() + r.Mount("/", api.Routes()) + + // When: All expected dev containers have been found. + require.Eventuallyf(t, func() bool { + req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx) + rec := httptest.NewRecorder() + r.ServeHTTP(rec, req) + + got := codersdk.WorkspaceAgentListContainersResponse{} + err := json.NewDecoder(rec.Body).Decode(&got) + require.NoError(t, err) + + return len(got.Devcontainers) >= 1 + }, testutil.WaitShort, testutil.IntervalFast, "dev containers never found") + + // Then: We expect the mock infra to not fail. + }) + }) +} diff --git a/agent/agentcontainers/dcspec/gen.sh b/agent/agentcontainers/dcspec/gen.sh index 276cb24cb4123..056fd218fd247 100755 --- a/agent/agentcontainers/dcspec/gen.sh +++ b/agent/agentcontainers/dcspec/gen.sh @@ -61,7 +61,7 @@ fi exec 3>&- # Format the generated code. -go run mvdan.cc/gofumpt@v0.4.0 -w -l "${TMPDIR}/${DEST_FILENAME}" +go run mvdan.cc/gofumpt@v0.8.0 -w -l "${TMPDIR}/${DEST_FILENAME}" # Add a header so that Go recognizes this as a generated file. if grep -q -- "\[-i extension\]" < <(sed -h 2>&1); then diff --git a/agent/agentcontainers/devcontainer.go b/agent/agentcontainers/devcontainer.go index f13963d7b63d7..555e406e0b52c 100644 --- a/agent/agentcontainers/devcontainer.go +++ b/agent/agentcontainers/devcontainer.go @@ -2,10 +2,10 @@ package agentcontainers import ( "context" - "fmt" "os" "path/filepath" - "strings" + + "github.com/google/uuid" "cdr.dev/slog" "github.com/coder/coder/v2/codersdk" @@ -18,37 +18,25 @@ const ( // DevcontainerConfigFileLabel is the label that contains the path to // the devcontainer.json configuration file. DevcontainerConfigFileLabel = "devcontainer.config_file" + // DevcontainerIsTestRunLabel is set if the devcontainer is part of a test + // and should be excluded. + DevcontainerIsTestRunLabel = "devcontainer.is_test_run" // The default workspace folder inside the devcontainer. DevcontainerDefaultContainerWorkspaceFolder = "/workspaces" ) -const devcontainerUpScriptTemplate = ` -if ! which devcontainer > /dev/null 2>&1; then - echo "ERROR: Unable to start devcontainer, @devcontainers/cli is not installed or not found in \$PATH." 1>&2 - echo "Please install @devcontainers/cli by running \"npm install -g @devcontainers/cli\" or by using the \"devcontainers-cli\" Coder module." 1>&2 - exit 1 -fi -devcontainer up %s -` - -// ExtractAndInitializeDevcontainerScripts extracts devcontainer scripts from -// the given scripts and devcontainers. The devcontainer scripts are removed -// from the returned scripts so that they can be run separately. -// -// Dev Containers have an inherent dependency on start scripts, since they -// initialize the workspace (e.g. git clone, npm install, etc). This is -// important if e.g. a Coder module to install @devcontainer/cli is used. -func ExtractAndInitializeDevcontainerScripts( +func ExtractDevcontainerScripts( devcontainers []codersdk.WorkspaceAgentDevcontainer, scripts []codersdk.WorkspaceAgentScript, -) (filteredScripts []codersdk.WorkspaceAgentScript, devcontainerScripts []codersdk.WorkspaceAgentScript) { +) (filteredScripts []codersdk.WorkspaceAgentScript, devcontainerScripts map[uuid.UUID]codersdk.WorkspaceAgentScript) { + devcontainerScripts = make(map[uuid.UUID]codersdk.WorkspaceAgentScript) ScriptLoop: for _, script := range scripts { for _, dc := range devcontainers { // The devcontainer scripts match the devcontainer ID for // identification. if script.ID == dc.ID { - devcontainerScripts = append(devcontainerScripts, devcontainerStartupScript(dc, script)) + devcontainerScripts[dc.ID] = script continue ScriptLoop } } @@ -59,24 +47,6 @@ ScriptLoop: return filteredScripts, devcontainerScripts } -func devcontainerStartupScript(dc codersdk.WorkspaceAgentDevcontainer, script codersdk.WorkspaceAgentScript) codersdk.WorkspaceAgentScript { - args := []string{ - "--log-format json", - fmt.Sprintf("--workspace-folder %q", dc.WorkspaceFolder), - } - if dc.ConfigPath != "" { - args = append(args, fmt.Sprintf("--config %q", dc.ConfigPath)) - } - cmd := fmt.Sprintf(devcontainerUpScriptTemplate, strings.Join(args, " ")) - // Force the script to run in /bin/sh, since some shells (e.g. fish) - // don't support the script. - script.Script = fmt.Sprintf("/bin/sh -c '%s'", cmd) - // Disable RunOnStart, scripts have this set so that when devcontainers - // have not been enabled, a warning will be surfaced in the agent logs. - script.RunOnStart = false - return script -} - // ExpandAllDevcontainerPaths expands all devcontainer paths in the given // devcontainers. This is required by the devcontainer CLI, which requires // absolute paths for the workspace folder and config path. diff --git a/agent/agentcontainers/devcontainer_test.go b/agent/agentcontainers/devcontainer_test.go deleted file mode 100644 index b20c943175821..0000000000000 --- a/agent/agentcontainers/devcontainer_test.go +++ /dev/null @@ -1,274 +0,0 @@ -package agentcontainers_test - -import ( - "path/filepath" - "strings" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" - "github.com/google/uuid" - "github.com/stretchr/testify/require" - - "cdr.dev/slog/sloggers/slogtest" - "github.com/coder/coder/v2/agent/agentcontainers" - "github.com/coder/coder/v2/codersdk" -) - -func TestExtractAndInitializeDevcontainerScripts(t *testing.T) { - t.Parallel() - - scriptIDs := []uuid.UUID{uuid.New(), uuid.New()} - devcontainerIDs := []uuid.UUID{uuid.New(), uuid.New()} - - type args struct { - expandPath func(string) (string, error) - devcontainers []codersdk.WorkspaceAgentDevcontainer - scripts []codersdk.WorkspaceAgentScript - } - tests := []struct { - name string - args args - wantFilteredScripts []codersdk.WorkspaceAgentScript - wantDevcontainerScripts []codersdk.WorkspaceAgentScript - - skipOnWindowsDueToPathSeparator bool - }{ - { - name: "no scripts", - args: args{ - expandPath: nil, - devcontainers: nil, - scripts: nil, - }, - wantFilteredScripts: nil, - wantDevcontainerScripts: nil, - }, - { - name: "no devcontainers", - args: args{ - expandPath: nil, - devcontainers: nil, - scripts: []codersdk.WorkspaceAgentScript{ - {ID: scriptIDs[0]}, - {ID: scriptIDs[1]}, - }, - }, - wantFilteredScripts: []codersdk.WorkspaceAgentScript{ - {ID: scriptIDs[0]}, - {ID: scriptIDs[1]}, - }, - wantDevcontainerScripts: nil, - }, - { - name: "no scripts match devcontainers", - args: args{ - expandPath: nil, - devcontainers: []codersdk.WorkspaceAgentDevcontainer{ - {ID: devcontainerIDs[0]}, - {ID: devcontainerIDs[1]}, - }, - scripts: []codersdk.WorkspaceAgentScript{ - {ID: scriptIDs[0]}, - {ID: scriptIDs[1]}, - }, - }, - wantFilteredScripts: []codersdk.WorkspaceAgentScript{ - {ID: scriptIDs[0]}, - {ID: scriptIDs[1]}, - }, - wantDevcontainerScripts: nil, - }, - { - name: "scripts match devcontainers and sets RunOnStart=false", - args: args{ - expandPath: nil, - devcontainers: []codersdk.WorkspaceAgentDevcontainer{ - {ID: devcontainerIDs[0], WorkspaceFolder: "workspace1"}, - {ID: devcontainerIDs[1], WorkspaceFolder: "workspace2"}, - }, - scripts: []codersdk.WorkspaceAgentScript{ - {ID: scriptIDs[0], RunOnStart: true}, - {ID: scriptIDs[1], RunOnStart: true}, - {ID: devcontainerIDs[0], RunOnStart: true}, - {ID: devcontainerIDs[1], RunOnStart: true}, - }, - }, - wantFilteredScripts: []codersdk.WorkspaceAgentScript{ - {ID: scriptIDs[0], RunOnStart: true}, - {ID: scriptIDs[1], RunOnStart: true}, - }, - wantDevcontainerScripts: []codersdk.WorkspaceAgentScript{ - { - ID: devcontainerIDs[0], - Script: "devcontainer up --log-format json --workspace-folder \"workspace1\"", - RunOnStart: false, - }, - { - ID: devcontainerIDs[1], - Script: "devcontainer up --log-format json --workspace-folder \"workspace2\"", - RunOnStart: false, - }, - }, - }, - { - name: "scripts match devcontainers with config path", - args: args{ - expandPath: nil, - devcontainers: []codersdk.WorkspaceAgentDevcontainer{ - { - ID: devcontainerIDs[0], - WorkspaceFolder: "workspace1", - ConfigPath: "config1", - }, - { - ID: devcontainerIDs[1], - WorkspaceFolder: "workspace2", - ConfigPath: "config2", - }, - }, - scripts: []codersdk.WorkspaceAgentScript{ - {ID: devcontainerIDs[0]}, - {ID: devcontainerIDs[1]}, - }, - }, - wantFilteredScripts: []codersdk.WorkspaceAgentScript{}, - wantDevcontainerScripts: []codersdk.WorkspaceAgentScript{ - { - ID: devcontainerIDs[0], - Script: "devcontainer up --log-format json --workspace-folder \"workspace1\" --config \"workspace1/config1\"", - RunOnStart: false, - }, - { - ID: devcontainerIDs[1], - Script: "devcontainer up --log-format json --workspace-folder \"workspace2\" --config \"workspace2/config2\"", - RunOnStart: false, - }, - }, - skipOnWindowsDueToPathSeparator: true, - }, - { - name: "scripts match devcontainers with expand path", - args: args{ - expandPath: func(s string) (string, error) { - return "/home/" + s, nil - }, - devcontainers: []codersdk.WorkspaceAgentDevcontainer{ - { - ID: devcontainerIDs[0], - WorkspaceFolder: "workspace1", - ConfigPath: "config1", - }, - { - ID: devcontainerIDs[1], - WorkspaceFolder: "workspace2", - ConfigPath: "config2", - }, - }, - scripts: []codersdk.WorkspaceAgentScript{ - {ID: devcontainerIDs[0], RunOnStart: true}, - {ID: devcontainerIDs[1], RunOnStart: true}, - }, - }, - wantFilteredScripts: []codersdk.WorkspaceAgentScript{}, - wantDevcontainerScripts: []codersdk.WorkspaceAgentScript{ - { - ID: devcontainerIDs[0], - Script: "devcontainer up --log-format json --workspace-folder \"/home/workspace1\" --config \"/home/workspace1/config1\"", - RunOnStart: false, - }, - { - ID: devcontainerIDs[1], - Script: "devcontainer up --log-format json --workspace-folder \"/home/workspace2\" --config \"/home/workspace2/config2\"", - RunOnStart: false, - }, - }, - skipOnWindowsDueToPathSeparator: true, - }, - { - name: "expand config path when ~", - args: args{ - expandPath: func(s string) (string, error) { - s = strings.Replace(s, "~/", "", 1) - if filepath.IsAbs(s) { - return s, nil - } - return "/home/" + s, nil - }, - devcontainers: []codersdk.WorkspaceAgentDevcontainer{ - { - ID: devcontainerIDs[0], - WorkspaceFolder: "workspace1", - ConfigPath: "~/config1", - }, - { - ID: devcontainerIDs[1], - WorkspaceFolder: "workspace2", - ConfigPath: "/config2", - }, - }, - scripts: []codersdk.WorkspaceAgentScript{ - {ID: devcontainerIDs[0], RunOnStart: true}, - {ID: devcontainerIDs[1], RunOnStart: true}, - }, - }, - wantFilteredScripts: []codersdk.WorkspaceAgentScript{}, - wantDevcontainerScripts: []codersdk.WorkspaceAgentScript{ - { - ID: devcontainerIDs[0], - Script: "devcontainer up --log-format json --workspace-folder \"/home/workspace1\" --config \"/home/config1\"", - RunOnStart: false, - }, - { - ID: devcontainerIDs[1], - Script: "devcontainer up --log-format json --workspace-folder \"/home/workspace2\" --config \"/config2\"", - RunOnStart: false, - }, - }, - skipOnWindowsDueToPathSeparator: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - if tt.skipOnWindowsDueToPathSeparator && filepath.Separator == '\\' { - t.Skip("Skipping test on Windows due to path separator difference.") - } - - logger := slogtest.Make(t, nil) - if tt.args.expandPath == nil { - tt.args.expandPath = func(s string) (string, error) { - return s, nil - } - } - gotFilteredScripts, gotDevcontainerScripts := agentcontainers.ExtractAndInitializeDevcontainerScripts( - agentcontainers.ExpandAllDevcontainerPaths(logger, tt.args.expandPath, tt.args.devcontainers), - tt.args.scripts, - ) - - if diff := cmp.Diff(tt.wantFilteredScripts, gotFilteredScripts, cmpopts.EquateEmpty()); diff != "" { - t.Errorf("ExtractAndInitializeDevcontainerScripts() gotFilteredScripts mismatch (-want +got):\n%s", diff) - } - - // Preprocess the devcontainer scripts to remove scripting part. - for i := range gotDevcontainerScripts { - gotDevcontainerScripts[i].Script = textGrep("devcontainer up", gotDevcontainerScripts[i].Script) - require.NotEmpty(t, gotDevcontainerScripts[i].Script, "devcontainer up script not found") - } - if diff := cmp.Diff(tt.wantDevcontainerScripts, gotDevcontainerScripts); diff != "" { - t.Errorf("ExtractAndInitializeDevcontainerScripts() gotDevcontainerScripts mismatch (-want +got):\n%s", diff) - } - }) - } -} - -// textGrep returns matching lines from multiline string. -func textGrep(want, got string) (filtered string) { - var lines []string - for _, line := range strings.Split(got, "\n") { - if strings.Contains(line, want) { - lines = append(lines, line) - } - } - return strings.Join(lines, "\n") -} diff --git a/agent/agentcontainers/devcontainercli.go b/agent/agentcontainers/devcontainercli.go index e49c6900facdb..2242e62f602e8 100644 --- a/agent/agentcontainers/devcontainercli.go +++ b/agent/agentcontainers/devcontainercli.go @@ -6,7 +6,10 @@ import ( "context" "encoding/json" "errors" + "fmt" "io" + "slices" + "strings" "golang.org/x/xerrors" @@ -26,12 +29,55 @@ type DevcontainerConfig struct { type DevcontainerMergedConfiguration struct { Customizations DevcontainerMergedCustomizations `json:"customizations,omitempty"` + Features DevcontainerFeatures `json:"features,omitempty"` } type DevcontainerMergedCustomizations struct { Coder []CoderCustomization `json:"coder,omitempty"` } +type DevcontainerFeatures map[string]any + +// OptionsAsEnvs converts the DevcontainerFeatures into a list of +// environment variables that can be used to set feature options. +// The format is FEATURE__OPTION_=. +// For example, if the feature is: +// +// "ghcr.io/coder/devcontainer-features/code-server:1": { +// "port": 9090, +// } +// +// It will produce: +// +// FEATURE_CODE_SERVER_OPTION_PORT=9090 +// +// Note that the feature name is derived from the last part of the key, +// so "ghcr.io/coder/devcontainer-features/code-server:1" becomes +// "CODE_SERVER". The version part (e.g. ":1") is removed, and dashes in +// the feature and option names are replaced with underscores. +func (f DevcontainerFeatures) OptionsAsEnvs() []string { + var env []string + for k, v := range f { + vv, ok := v.(map[string]any) + if !ok { + continue + } + // Take the last part of the key as the feature name/path. + k = k[strings.LastIndex(k, "/")+1:] + // Remove ":" and anything following it. + if idx := strings.Index(k, ":"); idx != -1 { + k = k[:idx] + } + k = strings.ReplaceAll(k, "-", "_") + for k2, v2 := range vv { + k2 = strings.ReplaceAll(k2, "-", "_") + env = append(env, fmt.Sprintf("FEATURE_%s_OPTION_%s=%s", strings.ToUpper(k), strings.ToUpper(k2), fmt.Sprintf("%v", v2))) + } + } + slices.Sort(env) + return env +} + type DevcontainerConfiguration struct { Customizations DevcontainerCustomizations `json:"customizations,omitempty"` } @@ -45,6 +91,7 @@ type CoderCustomization struct { Apps []SubAgentApp `json:"apps,omitempty"` Name string `json:"name,omitempty"` Ignore bool `json:"ignore,omitempty"` + AutoStart bool `json:"autoStart,omitempty"` } type DevcontainerWorkspace struct { @@ -60,63 +107,63 @@ type DevcontainerCLI interface { // DevcontainerCLIUpOptions are options for the devcontainer CLI Up // command. -type DevcontainerCLIUpOptions func(*devcontainerCLIUpConfig) +type DevcontainerCLIUpOptions func(*DevcontainerCLIUpConfig) -type devcontainerCLIUpConfig struct { - args []string // Additional arguments for the Up command. - stdout io.Writer - stderr io.Writer +type DevcontainerCLIUpConfig struct { + Args []string // Additional arguments for the Up command. + Stdout io.Writer + Stderr io.Writer } // WithRemoveExistingContainer is an option to remove the existing // container. func WithRemoveExistingContainer() DevcontainerCLIUpOptions { - return func(o *devcontainerCLIUpConfig) { - o.args = append(o.args, "--remove-existing-container") + return func(o *DevcontainerCLIUpConfig) { + o.Args = append(o.Args, "--remove-existing-container") } } // WithUpOutput sets additional stdout and stderr writers for logs // during Up operations. func WithUpOutput(stdout, stderr io.Writer) DevcontainerCLIUpOptions { - return func(o *devcontainerCLIUpConfig) { - o.stdout = stdout - o.stderr = stderr + return func(o *DevcontainerCLIUpConfig) { + o.Stdout = stdout + o.Stderr = stderr } } // DevcontainerCLIExecOptions are options for the devcontainer CLI Exec // command. -type DevcontainerCLIExecOptions func(*devcontainerCLIExecConfig) +type DevcontainerCLIExecOptions func(*DevcontainerCLIExecConfig) -type devcontainerCLIExecConfig struct { - args []string // Additional arguments for the Exec command. - stdout io.Writer - stderr io.Writer +type DevcontainerCLIExecConfig struct { + Args []string // Additional arguments for the Exec command. + Stdout io.Writer + Stderr io.Writer } // WithExecOutput sets additional stdout and stderr writers for logs // during Exec operations. func WithExecOutput(stdout, stderr io.Writer) DevcontainerCLIExecOptions { - return func(o *devcontainerCLIExecConfig) { - o.stdout = stdout - o.stderr = stderr + return func(o *DevcontainerCLIExecConfig) { + o.Stdout = stdout + o.Stderr = stderr } } // WithExecContainerID sets the container ID to target a specific // container. func WithExecContainerID(id string) DevcontainerCLIExecOptions { - return func(o *devcontainerCLIExecConfig) { - o.args = append(o.args, "--container-id", id) + return func(o *DevcontainerCLIExecConfig) { + o.Args = append(o.Args, "--container-id", id) } } // WithRemoteEnv sets environment variables for the Exec command. func WithRemoteEnv(env ...string) DevcontainerCLIExecOptions { - return func(o *devcontainerCLIExecConfig) { + return func(o *DevcontainerCLIExecConfig) { for _, e := range env { - o.args = append(o.args, "--remote-env", e) + o.Args = append(o.Args, "--remote-env", e) } } } @@ -139,8 +186,8 @@ func WithReadConfigOutput(stdout, stderr io.Writer) DevcontainerCLIReadConfigOpt } } -func applyDevcontainerCLIUpOptions(opts []DevcontainerCLIUpOptions) devcontainerCLIUpConfig { - conf := devcontainerCLIUpConfig{} +func applyDevcontainerCLIUpOptions(opts []DevcontainerCLIUpOptions) DevcontainerCLIUpConfig { + conf := DevcontainerCLIUpConfig{Stdout: io.Discard, Stderr: io.Discard} for _, opt := range opts { if opt != nil { opt(&conf) @@ -149,8 +196,8 @@ func applyDevcontainerCLIUpOptions(opts []DevcontainerCLIUpOptions) devcontainer return conf } -func applyDevcontainerCLIExecOptions(opts []DevcontainerCLIExecOptions) devcontainerCLIExecConfig { - conf := devcontainerCLIExecConfig{} +func applyDevcontainerCLIExecOptions(opts []DevcontainerCLIExecOptions) DevcontainerCLIExecConfig { + conf := DevcontainerCLIExecConfig{Stdout: io.Discard, Stderr: io.Discard} for _, opt := range opts { if opt != nil { opt(&conf) @@ -160,7 +207,7 @@ func applyDevcontainerCLIExecOptions(opts []DevcontainerCLIExecOptions) devconta } func applyDevcontainerCLIReadConfigOptions(opts []DevcontainerCLIReadConfigOptions) devcontainerCLIReadConfigConfig { - conf := devcontainerCLIReadConfigConfig{} + conf := devcontainerCLIReadConfigConfig{stdout: io.Discard, stderr: io.Discard} for _, opt := range opts { if opt != nil { opt(&conf) @@ -195,22 +242,25 @@ func (d *devcontainerCLI) Up(ctx context.Context, workspaceFolder, configPath st if configPath != "" { args = append(args, "--config", configPath) } - args = append(args, conf.args...) + args = append(args, conf.Args...) cmd := d.execer.CommandContext(ctx, "devcontainer", args...) // Capture stdout for parsing and stream logs for both default and provided writers. var stdoutBuf bytes.Buffer - stdoutWriters := []io.Writer{&stdoutBuf, &devcontainerCLILogWriter{ctx: ctx, logger: logger.With(slog.F("stdout", true))}} - if conf.stdout != nil { - stdoutWriters = append(stdoutWriters, conf.stdout) - } - cmd.Stdout = io.MultiWriter(stdoutWriters...) + cmd.Stdout = io.MultiWriter( + &stdoutBuf, + &devcontainerCLILogWriter{ + ctx: ctx, + logger: logger.With(slog.F("stdout", true)), + writer: conf.Stdout, + }, + ) // Stream stderr logs and provided writer if any. - stderrWriters := []io.Writer{&devcontainerCLILogWriter{ctx: ctx, logger: logger.With(slog.F("stderr", true))}} - if conf.stderr != nil { - stderrWriters = append(stderrWriters, conf.stderr) + cmd.Stderr = &devcontainerCLILogWriter{ + ctx: ctx, + logger: logger.With(slog.F("stderr", true)), + writer: conf.Stderr, } - cmd.Stderr = io.MultiWriter(stderrWriters...) if err := cmd.Run(); err != nil { _, err2 := parseDevcontainerCLILastLine[devcontainerCLIResult](ctx, logger, stdoutBuf.Bytes()) @@ -244,21 +294,21 @@ func (d *devcontainerCLI) Exec(ctx context.Context, workspaceFolder, configPath if configPath != "" { args = append(args, "--config", configPath) } - args = append(args, conf.args...) + args = append(args, conf.Args...) args = append(args, cmd) args = append(args, cmdArgs...) c := d.execer.CommandContext(ctx, "devcontainer", args...) - stdoutWriters := []io.Writer{&devcontainerCLILogWriter{ctx: ctx, logger: logger.With(slog.F("stdout", true))}} - if conf.stdout != nil { - stdoutWriters = append(stdoutWriters, conf.stdout) - } - c.Stdout = io.MultiWriter(stdoutWriters...) - stderrWriters := []io.Writer{&devcontainerCLILogWriter{ctx: ctx, logger: logger.With(slog.F("stderr", true))}} - if conf.stderr != nil { - stderrWriters = append(stderrWriters, conf.stderr) - } - c.Stderr = io.MultiWriter(stderrWriters...) + c.Stdout = io.MultiWriter(conf.Stdout, &devcontainerCLILogWriter{ + ctx: ctx, + logger: logger.With(slog.F("stdout", true)), + writer: io.Discard, + }) + c.Stderr = io.MultiWriter(conf.Stderr, &devcontainerCLILogWriter{ + ctx: ctx, + logger: logger.With(slog.F("stderr", true)), + writer: io.Discard, + }) if err := c.Run(); err != nil { return xerrors.Errorf("devcontainer exec failed: %w", err) @@ -283,16 +333,19 @@ func (d *devcontainerCLI) ReadConfig(ctx context.Context, workspaceFolder, confi c.Env = append(c.Env, env...) var stdoutBuf bytes.Buffer - stdoutWriters := []io.Writer{&stdoutBuf, &devcontainerCLILogWriter{ctx: ctx, logger: logger.With(slog.F("stdout", true))}} - if conf.stdout != nil { - stdoutWriters = append(stdoutWriters, conf.stdout) + c.Stdout = io.MultiWriter( + &stdoutBuf, + &devcontainerCLILogWriter{ + ctx: ctx, + logger: logger.With(slog.F("stdout", true)), + writer: conf.stdout, + }, + ) + c.Stderr = &devcontainerCLILogWriter{ + ctx: ctx, + logger: logger.With(slog.F("stderr", true)), + writer: conf.stderr, } - c.Stdout = io.MultiWriter(stdoutWriters...) - stderrWriters := []io.Writer{&devcontainerCLILogWriter{ctx: ctx, logger: logger.With(slog.F("stderr", true))}} - if conf.stderr != nil { - stderrWriters = append(stderrWriters, conf.stderr) - } - c.Stderr = io.MultiWriter(stderrWriters...) if err := c.Run(); err != nil { return DevcontainerConfig{}, xerrors.Errorf("devcontainer read-configuration failed: %w", err) @@ -385,6 +438,7 @@ type devcontainerCLIJSONLogLine struct { type devcontainerCLILogWriter struct { ctx context.Context logger slog.Logger + writer io.Writer } func (l *devcontainerCLILogWriter) Write(p []byte) (n int, err error) { @@ -405,8 +459,20 @@ func (l *devcontainerCLILogWriter) Write(p []byte) (n int, err error) { } if logLine.Level >= 3 { l.logger.Info(l.ctx, "@devcontainer/cli", slog.F("line", string(line))) + _, _ = l.writer.Write([]byte(strings.TrimSpace(logLine.Text) + "\n")) continue } + // If we've successfully parsed the final log line, it will successfully parse + // but will not fill out any of the fields for `logLine`. In this scenario we + // assume it is the final log line, unmarshal it as that, and check if the + // outcome is a non-empty string. + if logLine.Level == 0 { + var lastLine devcontainerCLIResult + if err := json.Unmarshal(line, &lastLine); err == nil && lastLine.Outcome != "" { + _, _ = l.writer.Write(line) + _, _ = l.writer.Write([]byte{'\n'}) + } + } l.logger.Debug(l.ctx, "@devcontainer/cli", slog.F("line", string(line))) } if err := s.Err(); err != nil { diff --git a/agent/agentcontainers/devcontainercli_test.go b/agent/agentcontainers/devcontainercli_test.go index 821e6e8f95e76..e3f0445751eb7 100644 --- a/agent/agentcontainers/devcontainercli_test.go +++ b/agent/agentcontainers/devcontainercli_test.go @@ -3,6 +3,7 @@ package agentcontainers_test import ( "bytes" "context" + "encoding/json" "errors" "flag" "fmt" @@ -10,9 +11,11 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "testing" + "github.com/google/go-cmp/cmp" "github.com/ory/dockertest/v3" "github.com/ory/dockertest/v3/docker" "github.com/stretchr/testify/assert" @@ -341,6 +344,10 @@ func TestDevcontainerCLI_WithOutput(t *testing.T) { t.Run("Up", func(t *testing.T) { t.Parallel() + if runtime.GOOS == "windows" { + t.Skip("Windows uses CRLF line endings, golden file is LF") + } + // Buffers to capture stdout and stderr. outBuf := &bytes.Buffer{} errBuf := &bytes.Buffer{} @@ -363,7 +370,7 @@ func TestDevcontainerCLI_WithOutput(t *testing.T) { require.NotEmpty(t, containerID, "expected non-empty container ID") // Read expected log content. - expLog, err := os.ReadFile(filepath.Join("testdata", "devcontainercli", "parse", "up.log")) + expLog, err := os.ReadFile(filepath.Join("testdata", "devcontainercli", "parse", "up.golden")) require.NoError(t, err, "reading expected log file") // Verify stdout buffer contains the CLI logs and stderr is empty. @@ -586,7 +593,7 @@ func setupDevcontainerWorkspace(t *testing.T, workspaceFolder string) string { "containerEnv": { "TEST_CONTAINER": "true" }, - "runArgs": ["--label", "com.coder.test=devcontainercli"] + "runArgs": ["--label=com.coder.test=devcontainercli", "--label=` + agentcontainers.DevcontainerIsTestRunLabel + `=true"] }` err = os.WriteFile(configPath, []byte(content), 0o600) require.NoError(t, err, "create devcontainer.json file") @@ -637,3 +644,107 @@ func removeDevcontainerByID(t *testing.T, pool *dockertest.Pool, id string) { assert.NoError(t, err, "remove container failed") } } + +func TestDevcontainerFeatures_OptionsAsEnvs(t *testing.T) { + t.Parallel() + + realConfigJSON := `{ + "mergedConfiguration": { + "features": { + "./code-server": { + "port": 9090 + }, + "ghcr.io/devcontainers/features/docker-in-docker:2": { + "moby": "false" + } + } + } + }` + var realConfig agentcontainers.DevcontainerConfig + err := json.Unmarshal([]byte(realConfigJSON), &realConfig) + require.NoError(t, err, "unmarshal JSON payload") + + tests := []struct { + name string + features agentcontainers.DevcontainerFeatures + want []string + }{ + { + name: "code-server feature", + features: agentcontainers.DevcontainerFeatures{ + "./code-server": map[string]any{ + "port": 9090, + }, + }, + want: []string{ + "FEATURE_CODE_SERVER_OPTION_PORT=9090", + }, + }, + { + name: "docker-in-docker feature", + features: agentcontainers.DevcontainerFeatures{ + "ghcr.io/devcontainers/features/docker-in-docker:2": map[string]any{ + "moby": "false", + }, + }, + want: []string{ + "FEATURE_DOCKER_IN_DOCKER_OPTION_MOBY=false", + }, + }, + { + name: "multiple features with multiple options", + features: agentcontainers.DevcontainerFeatures{ + "./code-server": map[string]any{ + "port": 9090, + "password": "secret", + }, + "ghcr.io/devcontainers/features/docker-in-docker:2": map[string]any{ + "moby": "false", + "docker-dash-compose-version": "v2", + }, + }, + want: []string{ + "FEATURE_CODE_SERVER_OPTION_PASSWORD=secret", + "FEATURE_CODE_SERVER_OPTION_PORT=9090", + "FEATURE_DOCKER_IN_DOCKER_OPTION_DOCKER_DASH_COMPOSE_VERSION=v2", + "FEATURE_DOCKER_IN_DOCKER_OPTION_MOBY=false", + }, + }, + { + name: "feature with non-map value (should be ignored)", + features: agentcontainers.DevcontainerFeatures{ + "./code-server": map[string]any{ + "port": 9090, + }, + "./invalid-feature": "not-a-map", + }, + want: []string{ + "FEATURE_CODE_SERVER_OPTION_PORT=9090", + }, + }, + { + name: "real config example", + features: realConfig.MergedConfiguration.Features, + want: []string{ + "FEATURE_CODE_SERVER_OPTION_PORT=9090", + "FEATURE_DOCKER_IN_DOCKER_OPTION_MOBY=false", + }, + }, + { + name: "empty features", + features: agentcontainers.DevcontainerFeatures{}, + want: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + got := tt.features.OptionsAsEnvs() + if diff := cmp.Diff(tt.want, got); diff != "" { + require.Failf(t, "OptionsAsEnvs() mismatch (-want +got):\n%s", diff) + } + }) + } +} diff --git a/agent/agentcontainers/ignore/dir.go b/agent/agentcontainers/ignore/dir.go new file mode 100644 index 0000000000000..d97e2ef2235a3 --- /dev/null +++ b/agent/agentcontainers/ignore/dir.go @@ -0,0 +1,124 @@ +package ignore + +import ( + "bytes" + "context" + "errors" + "io/fs" + "os" + "path/filepath" + "strings" + + "github.com/go-git/go-git/v5/plumbing/format/config" + "github.com/go-git/go-git/v5/plumbing/format/gitignore" + "github.com/spf13/afero" + "golang.org/x/xerrors" + + "cdr.dev/slog" +) + +const ( + gitconfigFile = ".gitconfig" + gitignoreFile = ".gitignore" + gitInfoExcludeFile = ".git/info/exclude" +) + +func FilePathToParts(path string) []string { + components := []string{} + + if path == "" { + return components + } + + for segment := range strings.SplitSeq(filepath.Clean(path), string(filepath.Separator)) { + if segment != "" { + components = append(components, segment) + } + } + + return components +} + +func readIgnoreFile(fileSystem afero.Fs, path, ignore string) ([]gitignore.Pattern, error) { + var ps []gitignore.Pattern + + data, err := afero.ReadFile(fileSystem, filepath.Join(path, ignore)) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + + for s := range strings.SplitSeq(string(data), "\n") { + if !strings.HasPrefix(s, "#") && len(strings.TrimSpace(s)) > 0 { + ps = append(ps, gitignore.ParsePattern(s, FilePathToParts(path))) + } + } + + return ps, nil +} + +func ReadPatterns(ctx context.Context, logger slog.Logger, fileSystem afero.Fs, path string) ([]gitignore.Pattern, error) { + var ps []gitignore.Pattern + + subPs, err := readIgnoreFile(fileSystem, path, gitInfoExcludeFile) + if err != nil { + return nil, err + } + + ps = append(ps, subPs...) + + if err := afero.Walk(fileSystem, path, func(path string, info fs.FileInfo, err error) error { + if err != nil { + logger.Error(ctx, "encountered error while walking for git ignore files", + slog.F("path", path), + slog.Error(err)) + return nil + } + + if !info.IsDir() { + return nil + } + + subPs, err := readIgnoreFile(fileSystem, path, gitignoreFile) + if err != nil { + return err + } + + ps = append(ps, subPs...) + + return nil + }); err != nil { + return nil, err + } + + return ps, nil +} + +func loadPatterns(fileSystem afero.Fs, path string) ([]gitignore.Pattern, error) { + data, err := afero.ReadFile(fileSystem, path) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + + decoder := config.NewDecoder(bytes.NewBuffer(data)) + + conf := config.New() + if err := decoder.Decode(conf); err != nil { + return nil, xerrors.Errorf("decode config: %w", err) + } + + excludes := conf.Section("core").Options.Get("excludesfile") + if excludes == "" { + return nil, nil + } + + return readIgnoreFile(fileSystem, "", excludes) +} + +func LoadGlobalPatterns(fileSystem afero.Fs) ([]gitignore.Pattern, error) { + home, err := os.UserHomeDir() + if err != nil { + return nil, err + } + + return loadPatterns(fileSystem, filepath.Join(home, gitconfigFile)) +} diff --git a/agent/agentcontainers/ignore/dir_test.go b/agent/agentcontainers/ignore/dir_test.go new file mode 100644 index 0000000000000..2af54cf63930d --- /dev/null +++ b/agent/agentcontainers/ignore/dir_test.go @@ -0,0 +1,38 @@ +package ignore_test + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/coder/coder/v2/agent/agentcontainers/ignore" +) + +func TestFilePathToParts(t *testing.T) { + t.Parallel() + + tests := []struct { + path string + expected []string + }{ + {"", []string{}}, + {"/", []string{}}, + {"foo", []string{"foo"}}, + {"/foo", []string{"foo"}}, + {"./foo/bar", []string{"foo", "bar"}}, + {"../foo/bar", []string{"..", "foo", "bar"}}, + {"foo/bar/baz", []string{"foo", "bar", "baz"}}, + {"/foo/bar/baz", []string{"foo", "bar", "baz"}}, + {"foo/../bar", []string{"bar"}}, + } + + for _, tt := range tests { + t.Run(fmt.Sprintf("`%s`", tt.path), func(t *testing.T) { + t.Parallel() + + parts := ignore.FilePathToParts(tt.path) + require.Equal(t, tt.expected, parts) + }) + } +} diff --git a/agent/agentcontainers/subagent.go b/agent/agentcontainers/subagent.go index 42df7080a890a..7d7603feef21d 100644 --- a/agent/agentcontainers/subagent.go +++ b/agent/agentcontainers/subagent.go @@ -188,7 +188,7 @@ func (a *subAgentAPIClient) List(ctx context.Context) ([]SubAgent, error) { return agents, nil } -func (a *subAgentAPIClient) Create(ctx context.Context, agent SubAgent) (SubAgent, error) { +func (a *subAgentAPIClient) Create(ctx context.Context, agent SubAgent) (_ SubAgent, err error) { a.logger.Debug(ctx, "creating sub agent", slog.F("name", agent.Name), slog.F("directory", agent.Directory)) displayApps := make([]agentproto.CreateSubAgentRequest_DisplayApp, 0, len(agent.DisplayApps)) @@ -233,19 +233,27 @@ func (a *subAgentAPIClient) Create(ctx context.Context, agent SubAgent) (SubAgen if err != nil { return SubAgent{}, err } + defer func() { + if err != nil { + // Best effort. + _, _ = a.api.DeleteSubAgent(ctx, &agentproto.DeleteSubAgentRequest{ + Id: resp.GetAgent().GetId(), + }) + } + }() - agent.Name = resp.Agent.Name - agent.ID, err = uuid.FromBytes(resp.Agent.Id) + agent.Name = resp.GetAgent().GetName() + agent.ID, err = uuid.FromBytes(resp.GetAgent().GetId()) if err != nil { - return agent, err + return SubAgent{}, err } - agent.AuthToken, err = uuid.FromBytes(resp.Agent.AuthToken) + agent.AuthToken, err = uuid.FromBytes(resp.GetAgent().GetAuthToken()) if err != nil { - return agent, err + return SubAgent{}, err } - for _, appError := range resp.AppCreationErrors { - app := apps[appError.Index] + for _, appError := range resp.GetAppCreationErrors() { + app := apps[appError.GetIndex()] a.logger.Warn(ctx, "unable to create app", slog.F("agent_name", agent.Name), diff --git a/agent/agentcontainers/testdata/devcontainercli/parse/up.golden b/agent/agentcontainers/testdata/devcontainercli/parse/up.golden new file mode 100644 index 0000000000000..022869052cf4b --- /dev/null +++ b/agent/agentcontainers/testdata/devcontainercli/parse/up.golden @@ -0,0 +1,64 @@ +@devcontainers/cli 0.75.0. Node.js v23.9.0. darwin 24.4.0 arm64. +Resolving Feature dependencies for 'ghcr.io/devcontainers/features/docker-in-docker:2'... +Soft-dependency 'ghcr.io/devcontainers/features/common-utils' is not required. Removing from installation order... +Files to omit: '' +Run: docker buildx build --load --build-context dev_containers_feature_content_source=/var/folders/1y/cm8mblxd7_x9cljwl_jvfprh0000gn/T/devcontainercli/container-features/0.75.0-1744102171193 --build-arg _DEV_CONTAINERS_BASE_IMAGE=mcr.microsoft.com/devcontainers/javascript-node:1-18-bullseye --build-arg _DEV_CONTAINERS_IMAGE_USER=root --build-arg _DEV_CONTAINERS_FEATURE_CONTENT_SOURCE=dev_container_feature_content_temp --target dev_containers_target_stage -f /var/folders/1y/cm8mblxd7_x9cljwl_jvfprh0000gn/T/devcontainercli/container-features/0.75.0-1744102171193/Dockerfile.extended -t vsc-devcontainers-template-starter-81d8f17e32abef6d434cbb5a37fe05e5c8a6f8ccede47a61197f002dcbf60566-features /var/folders/1y/cm8mblxd7_x9cljwl_jvfprh0000gn/T/devcontainercli/empty-folder +#0 building with "orbstack" instance using docker driver + +#1 [internal] load build definition from Dockerfile.extended +#1 transferring dockerfile: 3.09kB done +#1 DONE 0.0s + +#2 resolve image config for docker-image://docker.io/docker/dockerfile:1.4 +#2 DONE 1.3s +#3 docker-image://docker.io/docker/dockerfile:1.4@sha256:9ba7531bd80fb0a858632727cf7a112fbfd19b17e94c4e84ced81e24ef1a0dbc +#3 CACHED + +#4 [internal] load .dockerignore +#4 transferring context: 2B done +#4 DONE 0.0s + +#5 [internal] load metadata for mcr.microsoft.com/devcontainers/javascript-node:1-18-bullseye +#5 DONE 0.0s + +#6 [context dev_containers_feature_content_source] load .dockerignore +#6 transferring dev_containers_feature_content_source: 2B done +#6 DONE 0.0s + +#7 [dev_containers_feature_content_normalize 1/3] FROM mcr.microsoft.com/devcontainers/javascript-node:1-18-bullseye +#7 DONE 0.0s + +#8 [context dev_containers_feature_content_source] load from client +#8 transferring dev_containers_feature_content_source: 82.11kB 0.0s done +#8 DONE 0.0s + +#9 [dev_containers_feature_content_normalize 2/3] COPY --from=dev_containers_feature_content_source devcontainer-features.builtin.env /tmp/build-features/ +#9 CACHED + +#10 [dev_containers_target_stage 2/5] RUN mkdir -p /tmp/dev-container-features +#10 CACHED + +#11 [dev_containers_target_stage 3/5] COPY --from=dev_containers_feature_content_normalize /tmp/build-features/ /tmp/dev-container-features +#11 CACHED + +#12 [dev_containers_target_stage 4/5] RUN echo "_CONTAINER_USER_HOME=$( (command -v getent >/dev/null 2>&1 && getent passwd 'root' || grep -E '^root|^[^:]*:[^:]*:root:' /etc/passwd || true) | cut -d: -f6)" >> /tmp/dev-container-features/devcontainer-features.builtin.env && echo "_REMOTE_USER_HOME=$( (command -v getent >/dev/null 2>&1 && getent passwd 'node' || grep -E '^node|^[^:]*:[^:]*:node:' /etc/passwd || true) | cut -d: -f6)" >> /tmp/dev-container-features/devcontainer-features.builtin.env +#12 CACHED + +#13 [dev_containers_feature_content_normalize 3/3] RUN chmod -R 0755 /tmp/build-features/ +#13 CACHED + +#14 [dev_containers_target_stage 5/5] RUN --mount=type=bind,from=dev_containers_feature_content_source,source=docker-in-docker_0,target=/tmp/build-features-src/docker-in-docker_0 cp -ar /tmp/build-features-src/docker-in-docker_0 /tmp/dev-container-features && chmod -R 0755 /tmp/dev-container-features/docker-in-docker_0 && cd /tmp/dev-container-features/docker-in-docker_0 && chmod +x ./devcontainer-features-install.sh && ./devcontainer-features-install.sh && rm -rf /tmp/dev-container-features/docker-in-docker_0 +#14 CACHED + +#15 exporting to image +#15 exporting layers done +#15 writing image sha256:275dc193c905d448ef3945e3fc86220cc315fe0cb41013988d6ff9f8d6ef2357 done +#15 naming to docker.io/library/vsc-devcontainers-template-starter-81d8f17e32abef6d434cbb5a37fe05e5c8a6f8ccede47a61197f002dcbf60566-features done +#15 DONE 0.0s +Run: docker buildx build --load --build-context dev_containers_feature_content_source=/var/folders/1y/cm8mblxd7_x9cljwl_jvfprh0000gn/T/devcontainercli/container-features/0.75.0-1744102171193 --build-arg _DEV_CONTAINERS_BASE_IMAGE=mcr.microsoft.com/devcontainers/javascript-node:1-18-bullseye --build-arg _DEV_CONTAINERS_IMAGE_USER=root --build-arg _DEV_CONTAINERS_FEATURE_CONTENT_SOURCE=dev_container_feature_content_temp --target dev_containers_target_stage -f /var/folders/1y/cm8mblxd7_x9cljwl_jvfprh0000gn/T/devcontainercli/container-features/0.75.0-1744102171193/Dockerfile.extended -t vsc-devcontainers-template-starter-81d8f17e32abef6d434cbb5a37fe05e5c8a6f8ccede47a61197f002dcbf60566-features /var/folders/1y/cm8mblxd7_x9cljwl_jvfprh0000gn/T/devcontainercli/empty-folder +Run: docker run --sig-proxy=false -a STDOUT -a STDERR --mount type=bind,source=/code/devcontainers-template-starter,target=/workspaces/devcontainers-template-starter,consistency=cached --mount type=volume,src=dind-var-lib-docker-0pctifo8bbg3pd06g3j5s9ae8j7lp5qfcd67m25kuahurel7v7jm,dst=/var/lib/docker -l devcontainer.local_folder=/code/devcontainers-template-starter -l devcontainer.config_file=/code/devcontainers-template-starter/.devcontainer/devcontainer.json --privileged --entrypoint /bin/sh vsc-devcontainers-template-starter-81d8f17e32abef6d434cbb5a37fe05e5c8a6f8ccede47a61197f002dcbf60566-features -c echo Container started +Container started +Not setting dockerd DNS manually. +Running the postCreateCommand from devcontainer.json... +added 1 package in 784ms +{"outcome":"success","containerId":"bc72db8d0c4c4e941bd9ffc341aee64a18d3397fd45b87cd93d4746150967ba8","remoteUser":"node","remoteWorkspaceFolder":"/workspaces/devcontainers-template-starter"} diff --git a/agent/agentcontainers/watcher/watcher_test.go b/agent/agentcontainers/watcher/watcher_test.go index 6cddfbdcee276..08222357d5fd0 100644 --- a/agent/agentcontainers/watcher/watcher_test.go +++ b/agent/agentcontainers/watcher/watcher_test.go @@ -4,6 +4,7 @@ import ( "context" "os" "path/filepath" + "runtime" "testing" "github.com/fsnotify/fsnotify" @@ -88,24 +89,34 @@ func TestFSNotifyWatcher(t *testing.T) { break } - err = os.WriteFile(testFile+".atomic", []byte(`{"test": "atomic"}`), 0o600) - require.NoError(t, err, "write new atomic test file failed") - - err = os.Rename(testFile+".atomic", testFile) - require.NoError(t, err, "rename atomic test file failed") - - // Verify that we receive the event we want. - for { - event, err := wut.Next(ctx) - require.NoError(t, err, "next event failed") - require.NotNil(t, event, "want non-nil event") - if !event.Has(fsnotify.Create) { - t.Logf("Ignoring event: %s", event) - continue + // TODO(DanielleMaywood): + // Unfortunately it appears this atomic-rename phase of the test is flakey on macOS. + // + // This test flake could be indicative of an issue that may present itself + // in a running environment. Fortunately, we only use this (as of 2025-07-29) + // for our dev container integration. We do not expect the host workspace + // (where this is used), to ever be run on macOS, as containers are a linux + // paradigm. + if runtime.GOOS != "darwin" { + err = os.WriteFile(testFile+".atomic", []byte(`{"test": "atomic"}`), 0o600) + require.NoError(t, err, "write new atomic test file failed") + + err = os.Rename(testFile+".atomic", testFile) + require.NoError(t, err, "rename atomic test file failed") + + // Verify that we receive the event we want. + for { + event, err := wut.Next(ctx) + require.NoError(t, err, "next event failed") + require.NotNil(t, event, "want non-nil event") + if !event.Has(fsnotify.Create) { + t.Logf("Ignoring event: %s", event) + continue + } + require.Truef(t, event.Has(fsnotify.Create), "want create event: %s", event.String()) + require.Equal(t, event.Name, testFile, "want event for test file") + break } - require.Truef(t, event.Has(fsnotify.Create), "want create event: %s", event.String()) - require.Equal(t, event.Name, testFile, "want event for test file") - break } // Test removing the file from the watcher. diff --git a/agent/agentscripts/agentscripts.go b/agent/agentscripts/agentscripts.go index 79606a80233b9..bde3305b15415 100644 --- a/agent/agentscripts/agentscripts.go +++ b/agent/agentscripts/agentscripts.go @@ -79,21 +79,6 @@ func New(opts Options) *Runner { type ScriptCompletedFunc func(context.Context, *proto.WorkspaceAgentScriptCompletedRequest) (*proto.WorkspaceAgentScriptCompletedResponse, error) -type runnerScript struct { - runOnPostStart bool - codersdk.WorkspaceAgentScript -} - -func toRunnerScript(scripts ...codersdk.WorkspaceAgentScript) []runnerScript { - var rs []runnerScript - for _, s := range scripts { - rs = append(rs, runnerScript{ - WorkspaceAgentScript: s, - }) - } - return rs -} - type Runner struct { Options @@ -103,7 +88,7 @@ type Runner struct { closed chan struct{} closeMutex sync.Mutex cron *cron.Cron - scripts []runnerScript + scripts []codersdk.WorkspaceAgentScript dataDir string scriptCompleted ScriptCompletedFunc @@ -138,19 +123,6 @@ func (r *Runner) RegisterMetrics(reg prometheus.Registerer) { // InitOption describes an option for the runner initialization. type InitOption func(*Runner) -// WithPostStartScripts adds scripts that should be run after the workspace -// start scripts but before the workspace is marked as started. -func WithPostStartScripts(scripts ...codersdk.WorkspaceAgentScript) InitOption { - return func(r *Runner) { - for _, s := range scripts { - r.scripts = append(r.scripts, runnerScript{ - runOnPostStart: true, - WorkspaceAgentScript: s, - }) - } - } -} - // Init initializes the runner with the provided scripts. // It also schedules any scripts that have a schedule. // This function must be called before Execute. @@ -161,7 +133,7 @@ func (r *Runner) Init(scripts []codersdk.WorkspaceAgentScript, scriptCompleted S return xerrors.New("init: already initialized") } r.initialized = true - r.scripts = toRunnerScript(scripts...) + r.scripts = scripts r.scriptCompleted = scriptCompleted for _, opt := range opts { opt(r) @@ -177,9 +149,8 @@ func (r *Runner) Init(scripts []codersdk.WorkspaceAgentScript, scriptCompleted S if script.Cron == "" { continue } - script := script _, err := r.cron.AddFunc(script.Cron, func() { - err := r.trackRun(r.cronCtx, script.WorkspaceAgentScript, ExecuteCronScripts) + err := r.trackRun(r.cronCtx, script, ExecuteCronScripts) if err != nil { r.Logger.Warn(context.Background(), "run agent script on schedule", slog.Error(err)) } @@ -223,7 +194,6 @@ type ExecuteOption int const ( ExecuteAllScripts ExecuteOption = iota ExecuteStartScripts - ExecutePostStartScripts ExecuteStopScripts ExecuteCronScripts ) @@ -246,7 +216,6 @@ func (r *Runner) Execute(ctx context.Context, option ExecuteOption) error { for _, script := range r.scripts { runScript := (option == ExecuteStartScripts && script.RunOnStart) || (option == ExecuteStopScripts && script.RunOnStop) || - (option == ExecutePostStartScripts && script.runOnPostStart) || (option == ExecuteCronScripts && script.Cron != "") || option == ExecuteAllScripts @@ -254,9 +223,8 @@ func (r *Runner) Execute(ctx context.Context, option ExecuteOption) error { continue } - script := script eg.Go(func() error { - err := r.trackRun(ctx, script.WorkspaceAgentScript, option) + err := r.trackRun(ctx, script, option) if err != nil { return xerrors.Errorf("run agent script %q: %w", script.LogSourceID, err) } diff --git a/agent/agentscripts/agentscripts_test.go b/agent/agentscripts/agentscripts_test.go index f50a0cc065138..c032ea1f83a1a 100644 --- a/agent/agentscripts/agentscripts_test.go +++ b/agent/agentscripts/agentscripts_test.go @@ -4,7 +4,6 @@ import ( "context" "path/filepath" "runtime" - "slices" "sync" "testing" "time" @@ -177,11 +176,6 @@ func TestExecuteOptions(t *testing.T) { Script: "echo stop", RunOnStop: true, } - postStartScript := codersdk.WorkspaceAgentScript{ - ID: uuid.New(), - LogSourceID: uuid.New(), - Script: "echo poststart", - } regularScript := codersdk.WorkspaceAgentScript{ ID: uuid.New(), LogSourceID: uuid.New(), @@ -193,10 +187,9 @@ func TestExecuteOptions(t *testing.T) { stopScript, regularScript, } - allScripts := append(slices.Clone(scripts), postStartScript) scriptByID := func(t *testing.T, id uuid.UUID) codersdk.WorkspaceAgentScript { - for _, script := range allScripts { + for _, script := range scripts { if script.ID == id { return script } @@ -206,10 +199,9 @@ func TestExecuteOptions(t *testing.T) { } wantOutput := map[uuid.UUID]string{ - startScript.ID: "start", - stopScript.ID: "stop", - postStartScript.ID: "poststart", - regularScript.ID: "regular", + startScript.ID: "start", + stopScript.ID: "stop", + regularScript.ID: "regular", } testCases := []struct { @@ -220,18 +212,13 @@ func TestExecuteOptions(t *testing.T) { { name: "ExecuteAllScripts", option: agentscripts.ExecuteAllScripts, - wantRun: []uuid.UUID{startScript.ID, stopScript.ID, regularScript.ID, postStartScript.ID}, + wantRun: []uuid.UUID{startScript.ID, stopScript.ID, regularScript.ID}, }, { name: "ExecuteStartScripts", option: agentscripts.ExecuteStartScripts, wantRun: []uuid.UUID{startScript.ID}, }, - { - name: "ExecutePostStartScripts", - option: agentscripts.ExecutePostStartScripts, - wantRun: []uuid.UUID{postStartScript.ID}, - }, { name: "ExecuteStopScripts", option: agentscripts.ExecuteStopScripts, @@ -260,7 +247,6 @@ func TestExecuteOptions(t *testing.T) { err := runner.Init( scripts, aAPI.ScriptCompleted, - agentscripts.WithPostStartScripts(postStartScript), ) require.NoError(t, err) @@ -274,7 +260,7 @@ func TestExecuteOptions(t *testing.T) { "script %s should have run when using filter %s", scriptByID(t, id).Script, tc.name) } - for _, script := range allScripts { + for _, script := range scripts { if _, ok := gotRun[script.ID]; ok { continue } diff --git a/agent/agentssh/agentssh.go b/agent/agentssh/agentssh.go index f49a64924bd36..f53fe207c72cf 100644 --- a/agent/agentssh/agentssh.go +++ b/agent/agentssh/agentssh.go @@ -117,6 +117,10 @@ type Config struct { // Note that this is different from the devcontainers feature, which uses // subagents. ExperimentalContainers bool + // X11Net allows overriding the networking implementation used for X11 + // forwarding listeners. When nil, a default implementation backed by the + // standard library networking package is used. + X11Net X11Network } type Server struct { @@ -125,14 +129,16 @@ type Server struct { listeners map[net.Listener]struct{} conns map[net.Conn]struct{} sessions map[ssh.Session]struct{} + processes map[*os.Process]struct{} closing chan struct{} // Wait for goroutines to exit, waited without // a lock on mu but protected by closing. wg sync.WaitGroup - Execer agentexec.Execer - logger slog.Logger - srv *ssh.Server + Execer agentexec.Execer + logger slog.Logger + srv *ssh.Server + x11Forwarder *x11Forwarder config *Config @@ -183,11 +189,26 @@ func NewServer(ctx context.Context, logger slog.Logger, prometheusRegistry *prom fs: fs, conns: make(map[net.Conn]struct{}), sessions: make(map[ssh.Session]struct{}), + processes: make(map[*os.Process]struct{}), logger: logger, config: config, metrics: metrics, + x11Forwarder: &x11Forwarder{ + logger: logger, + x11HandlerErrors: metrics.x11HandlerErrors, + fs: fs, + displayOffset: *config.X11DisplayOffset, + sessions: make(map[*x11Session]struct{}), + connections: make(map[net.Conn]struct{}), + network: func() X11Network { + if config.X11Net != nil { + return config.X11Net + } + return osNet{} + }(), + }, } srv := &ssh.Server{ @@ -455,7 +476,7 @@ func (s *Server) sessionHandler(session ssh.Session) { x11, hasX11 := session.X11() if hasX11 { - display, handled := s.x11Handler(ctx, x11) + display, handled := s.x11Forwarder.x11Handler(ctx, session) if !handled { logger.Error(ctx, "x11 handler failed") closeCause("x11 handler failed") @@ -587,7 +608,12 @@ func (s *Server) startNonPTYSession(logger slog.Logger, session ssh.Session, mag // otherwise context cancellation will not propagate properly // and SSH server close may be delayed. cmd.SysProcAttr = cmdSysProcAttr() - cmd.Cancel = cmdCancel(session.Context(), logger, cmd) + + // to match OpenSSH, we don't actually tear a non-TTY command down, even if the session ends. OpenSSH closes the + // pipes to the process when the session ends; which is what happens here since we wire the command up to the + // session for I/O. + // c.f. https://github.com/coder/coder/issues/18519#issuecomment-3019118271 + cmd.Cancel = nil cmd.Stdout = session cmd.Stderr = session.Stderr() @@ -610,6 +636,16 @@ func (s *Server) startNonPTYSession(logger slog.Logger, session ssh.Session, mag s.metrics.sessionErrors.WithLabelValues(magicTypeLabel, "no", "start_command").Add(1) return xerrors.Errorf("start: %w", err) } + + // Since we don't cancel the process when the session stops, we still need to tear it down if we are closing. So + // track it here. + if !s.trackProcess(cmd.Process, true) { + // must be closing + err = cmdCancel(logger, cmd.Process) + return xerrors.Errorf("failed to track process: %w", err) + } + defer s.trackProcess(cmd.Process, false) + sigs := make(chan ssh.Signal, 1) session.Signals(sigs) defer func() { @@ -1070,6 +1106,27 @@ func (s *Server) trackSession(ss ssh.Session, add bool) (ok bool) { return true } +// trackCommand registers the process with the server. If the server is +// closing, the process is not registered and should be closed. +// +//nolint:revive +func (s *Server) trackProcess(p *os.Process, add bool) (ok bool) { + s.mu.Lock() + defer s.mu.Unlock() + if add { + if s.closing != nil { + // Server closed. + return false + } + s.wg.Add(1) + s.processes[p] = struct{}{} + return true + } + s.wg.Done() + delete(s.processes, p) + return true +} + // Close the server and all active connections. Server can be re-used // after Close is done. func (s *Server) Close() error { @@ -1109,11 +1166,18 @@ func (s *Server) Close() error { _ = c.Close() } + for p := range s.processes { + _ = cmdCancel(s.logger, p) + } + s.logger.Debug(ctx, "closing SSH server") err := s.srv.Close() s.mu.Unlock() + s.logger.Debug(ctx, "closing X11 forwarding") + _ = s.x11Forwarder.Close() + s.logger.Debug(ctx, "waiting for all goroutines to exit") s.wg.Wait() // Wait for all goroutines to exit. diff --git a/agent/agentssh/agentssh_test.go b/agent/agentssh/agentssh_test.go index 23d9dcc7da3b7..159fe345483d2 100644 --- a/agent/agentssh/agentssh_test.go +++ b/agent/agentssh/agentssh_test.go @@ -8,7 +8,9 @@ import ( "context" "fmt" "net" + "os" "os/user" + "path/filepath" "runtime" "strings" "sync" @@ -403,6 +405,81 @@ func TestNewServer_Signal(t *testing.T) { }) } +func TestSSHServer_ClosesStdin(t *testing.T) { + t.Parallel() + if runtime.GOOS == "windows" { + t.Skip("bash doesn't exist on Windows") + } + + ctx := testutil.Context(t, testutil.WaitMedium) + logger := testutil.Logger(t) + s, err := agentssh.NewServer(ctx, logger, prometheus.NewRegistry(), afero.NewMemMapFs(), agentexec.DefaultExecer, nil) + require.NoError(t, err) + defer s.Close() + err = s.UpdateHostSigner(42) + assert.NoError(t, err) + + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + + done := make(chan struct{}) + go func() { + defer close(done) + err := s.Serve(ln) + assert.Error(t, err) // Server is closed. + }() + defer func() { + err := s.Close() + require.NoError(t, err) + <-done + }() + + c := sshClient(t, ln.Addr().String()) + + sess, err := c.NewSession() + require.NoError(t, err) + stdout, err := sess.StdoutPipe() + require.NoError(t, err) + stdin, err := sess.StdinPipe() + require.NoError(t, err) + defer stdin.Close() + + dir := t.TempDir() + err = os.MkdirAll(dir, 0o755) + require.NoError(t, err) + filePath := filepath.Join(dir, "result.txt") + + // the shell command `read` will block until data is written to stdin, or closed. It will return + // exit code 1 if it hits EOF, which is what we want to test. + cmdErrCh := make(chan error, 1) + go func() { + cmdErrCh <- sess.Start(fmt.Sprintf(`echo started; echo "read exit code: $(read && echo 0 || echo 1)" > %s`, filePath)) + }() + + cmdErr := testutil.RequireReceive(ctx, t, cmdErrCh) + require.NoError(t, cmdErr) + + readCh := make(chan error, 1) + go func() { + buf := make([]byte, 8) + _, err := stdout.Read(buf) + assert.Equal(t, "started\n", string(buf)) + readCh <- err + }() + err = testutil.RequireReceive(ctx, t, readCh) + require.NoError(t, err) + + sess.Close() + + var content []byte + testutil.Eventually(ctx, t, func(_ context.Context) bool { + content, err = os.ReadFile(filePath) + return err == nil + }, testutil.IntervalFast) + require.NoError(t, err) + require.Equal(t, "read exit code: 1\n", string(content)) +} + func sshClient(t *testing.T, addr string) *ssh.Client { conn, err := net.Dial("tcp", addr) require.NoError(t, err) diff --git a/agent/agentssh/exec_other.go b/agent/agentssh/exec_other.go index 54dfd50899412..aef496a1ef775 100644 --- a/agent/agentssh/exec_other.go +++ b/agent/agentssh/exec_other.go @@ -4,7 +4,7 @@ package agentssh import ( "context" - "os/exec" + "os" "syscall" "cdr.dev/slog" @@ -16,9 +16,7 @@ func cmdSysProcAttr() *syscall.SysProcAttr { } } -func cmdCancel(ctx context.Context, logger slog.Logger, cmd *exec.Cmd) func() error { - return func() error { - logger.Debug(ctx, "cmdCancel: sending SIGHUP to process and children", slog.F("pid", cmd.Process.Pid)) - return syscall.Kill(-cmd.Process.Pid, syscall.SIGHUP) - } +func cmdCancel(logger slog.Logger, p *os.Process) error { + logger.Debug(context.Background(), "cmdCancel: sending SIGHUP to process and children", slog.F("pid", p.Pid)) + return syscall.Kill(-p.Pid, syscall.SIGHUP) } diff --git a/agent/agentssh/exec_windows.go b/agent/agentssh/exec_windows.go index 39f0f97198479..0dafa67958a67 100644 --- a/agent/agentssh/exec_windows.go +++ b/agent/agentssh/exec_windows.go @@ -2,7 +2,7 @@ package agentssh import ( "context" - "os/exec" + "os" "syscall" "cdr.dev/slog" @@ -12,14 +12,12 @@ func cmdSysProcAttr() *syscall.SysProcAttr { return &syscall.SysProcAttr{} } -func cmdCancel(ctx context.Context, logger slog.Logger, cmd *exec.Cmd) func() error { - return func() error { - logger.Debug(ctx, "cmdCancel: killing process", slog.F("pid", cmd.Process.Pid)) - // Windows doesn't support sending signals to process groups, so we - // have to kill the process directly. In the future, we may want to - // implement a more sophisticated solution for process groups on - // Windows, but for now, this is a simple way to ensure that the - // process is terminated when the context is cancelled. - return cmd.Process.Kill() - } +func cmdCancel(logger slog.Logger, p *os.Process) error { + logger.Debug(context.Background(), "cmdCancel: killing process", slog.F("pid", p.Pid)) + // Windows doesn't support sending signals to process groups, so we + // have to kill the process directly. In the future, we may want to + // implement a more sophisticated solution for process groups on + // Windows, but for now, this is a simple way to ensure that the + // process is terminated when the context is cancelled. + return p.Kill() } diff --git a/agent/agentssh/x11.go b/agent/agentssh/x11.go index 439f2c3021791..b02de0dcf003a 100644 --- a/agent/agentssh/x11.go +++ b/agent/agentssh/x11.go @@ -7,15 +7,16 @@ import ( "errors" "fmt" "io" - "math" "net" "os" "path/filepath" "strconv" + "sync" "time" "github.com/gliderlabs/ssh" "github.com/gofrs/flock" + "github.com/prometheus/client_golang/prometheus" "github.com/spf13/afero" gossh "golang.org/x/crypto/ssh" "golang.org/x/xerrors" @@ -29,8 +30,51 @@ const ( X11StartPort = 6000 // X11DefaultDisplayOffset is the default offset for X11 forwarding. X11DefaultDisplayOffset = 10 + X11MaxDisplays = 200 + // X11MaxPort is the highest port we will ever use for X11 forwarding. This limits the total number of TCP sockets + // we will create. It seems more useful to have a maximum port number than a direct limit on sockets with no max + // port because we'd like to be able to tell users the exact range of ports the Agent might use. + X11MaxPort = X11StartPort + X11MaxDisplays ) +// X11Network abstracts the creation of network listeners for X11 forwarding. +// It is intended mainly for testing; production code uses the default +// implementation backed by the operating system networking stack. +type X11Network interface { + Listen(network, address string) (net.Listener, error) +} + +// osNet is the default X11Network implementation that uses the standard +// library network stack. +type osNet struct{} + +func (osNet) Listen(network, address string) (net.Listener, error) { + return net.Listen(network, address) +} + +type x11Forwarder struct { + logger slog.Logger + x11HandlerErrors *prometheus.CounterVec + fs afero.Fs + displayOffset int + + // network creates X11 listener sockets. Defaults to osNet{}. + network X11Network + + mu sync.Mutex + sessions map[*x11Session]struct{} + connections map[net.Conn]struct{} + closing bool + wg sync.WaitGroup +} + +type x11Session struct { + session ssh.Session + display int + listener net.Listener + usedAt time.Time +} + // x11Callback is called when the client requests X11 forwarding. func (*Server) x11Callback(_ ssh.Context, _ ssh.X11) bool { // Always allow. @@ -39,115 +83,243 @@ func (*Server) x11Callback(_ ssh.Context, _ ssh.X11) bool { // x11Handler is called when a session has requested X11 forwarding. // It listens for X11 connections and forwards them to the client. -func (s *Server) x11Handler(ctx ssh.Context, x11 ssh.X11) (displayNumber int, handled bool) { - serverConn, valid := ctx.Value(ssh.ContextKeyConn).(*gossh.ServerConn) +func (x *x11Forwarder) x11Handler(sshCtx ssh.Context, sshSession ssh.Session) (displayNumber int, handled bool) { + x11, hasX11 := sshSession.X11() + if !hasX11 { + return -1, false + } + serverConn, valid := sshCtx.Value(ssh.ContextKeyConn).(*gossh.ServerConn) if !valid { - s.logger.Warn(ctx, "failed to get server connection") + x.logger.Warn(sshCtx, "failed to get server connection") return -1, false } + ctx := slog.With(sshCtx, slog.F("session_id", fmt.Sprintf("%x", serverConn.SessionID()))) hostname, err := os.Hostname() if err != nil { - s.logger.Warn(ctx, "failed to get hostname", slog.Error(err)) - s.metrics.x11HandlerErrors.WithLabelValues("hostname").Add(1) + x.logger.Warn(ctx, "failed to get hostname", slog.Error(err)) + x.x11HandlerErrors.WithLabelValues("hostname").Add(1) return -1, false } - ln, display, err := createX11Listener(ctx, *s.config.X11DisplayOffset) + x11session, err := x.createX11Session(ctx, sshSession) if err != nil { - s.logger.Warn(ctx, "failed to create X11 listener", slog.Error(err)) - s.metrics.x11HandlerErrors.WithLabelValues("listen").Add(1) + x.logger.Warn(ctx, "failed to create X11 listener", slog.Error(err)) + x.x11HandlerErrors.WithLabelValues("listen").Add(1) return -1, false } - s.trackListener(ln, true) defer func() { if !handled { - s.trackListener(ln, false) - _ = ln.Close() + x.closeAndRemoveSession(x11session) } }() - err = addXauthEntry(ctx, s.fs, hostname, strconv.Itoa(display), x11.AuthProtocol, x11.AuthCookie) + err = addXauthEntry(ctx, x.fs, hostname, strconv.Itoa(x11session.display), x11.AuthProtocol, x11.AuthCookie) if err != nil { - s.logger.Warn(ctx, "failed to add Xauthority entry", slog.Error(err)) - s.metrics.x11HandlerErrors.WithLabelValues("xauthority").Add(1) + x.logger.Warn(ctx, "failed to add Xauthority entry", slog.Error(err)) + x.x11HandlerErrors.WithLabelValues("xauthority").Add(1) return -1, false } + // clean up the X11 session if the SSH session completes. go func() { - // Don't leave the listener open after the session is gone. <-ctx.Done() - _ = ln.Close() + x.closeAndRemoveSession(x11session) }() - go func() { - defer ln.Close() - defer s.trackListener(ln, false) - - for { - conn, err := ln.Accept() - if err != nil { - if errors.Is(err, net.ErrClosed) { - return - } - s.logger.Warn(ctx, "failed to accept X11 connection", slog.Error(err)) + go x.listenForConnections(ctx, x11session, serverConn, x11) + x.logger.Debug(ctx, "X11 forwarding started", slog.F("display", x11session.display)) + + return x11session.display, true +} + +func (x *x11Forwarder) trackGoroutine() (closing bool, done func()) { + x.mu.Lock() + defer x.mu.Unlock() + if !x.closing { + x.wg.Add(1) + return false, func() { x.wg.Done() } + } + return true, func() {} +} + +func (x *x11Forwarder) listenForConnections( + ctx context.Context, session *x11Session, serverConn *gossh.ServerConn, x11 ssh.X11, +) { + defer x.closeAndRemoveSession(session) + if closing, done := x.trackGoroutine(); closing { + return + } else { // nolint: revive + defer done() + } + + for { + conn, err := session.listener.Accept() + if err != nil { + if errors.Is(err, net.ErrClosed) { return } - if x11.SingleConnection { - s.logger.Debug(ctx, "single connection requested, closing X11 listener") - _ = ln.Close() - } + x.logger.Warn(ctx, "failed to accept X11 connection", slog.Error(err)) + return + } - tcpConn, ok := conn.(*net.TCPConn) - if !ok { - s.logger.Warn(ctx, fmt.Sprintf("failed to cast connection to TCPConn. got: %T", conn)) - _ = conn.Close() - continue - } - tcpAddr, ok := tcpConn.LocalAddr().(*net.TCPAddr) - if !ok { - s.logger.Warn(ctx, fmt.Sprintf("failed to cast local address to TCPAddr. got: %T", tcpConn.LocalAddr())) - _ = conn.Close() - continue - } + // Update session usage time since a new X11 connection was forwarded. + x.mu.Lock() + session.usedAt = time.Now() + x.mu.Unlock() + if x11.SingleConnection { + x.logger.Debug(ctx, "single connection requested, closing X11 listener") + x.closeAndRemoveSession(session) + } - channel, reqs, err := serverConn.OpenChannel("x11", gossh.Marshal(struct { - OriginatorAddress string - OriginatorPort uint32 - }{ - OriginatorAddress: tcpAddr.IP.String(), + var originAddr string + var originPort uint32 + + if tcpConn, ok := conn.(*net.TCPConn); ok { + if tcpAddr, ok := tcpConn.LocalAddr().(*net.TCPAddr); ok { + originAddr = tcpAddr.IP.String() // #nosec G115 - Safe conversion as TCP port numbers are within uint32 range (0-65535) - OriginatorPort: uint32(tcpAddr.Port), - })) - if err != nil { - s.logger.Warn(ctx, "failed to open X11 channel", slog.Error(err)) - _ = conn.Close() - continue + originPort = uint32(tcpAddr.Port) } - go gossh.DiscardRequests(reqs) + } + // Fallback values for in-memory or non-TCP connections. + if originAddr == "" { + originAddr = "127.0.0.1" + } - if !s.trackConn(ln, conn, true) { - s.logger.Warn(ctx, "failed to track X11 connection") - _ = conn.Close() - continue - } - go func() { - defer s.trackConn(ln, conn, false) - Bicopy(ctx, conn, channel) - }() + channel, reqs, err := serverConn.OpenChannel("x11", gossh.Marshal(struct { + OriginatorAddress string + OriginatorPort uint32 + }{ + OriginatorAddress: originAddr, + OriginatorPort: originPort, + })) + if err != nil { + x.logger.Warn(ctx, "failed to open X11 channel", slog.Error(err)) + _ = conn.Close() + continue } - }() + go gossh.DiscardRequests(reqs) + + if !x.trackConn(conn, true) { + x.logger.Warn(ctx, "failed to track X11 connection") + _ = conn.Close() + continue + } + go func() { + defer x.trackConn(conn, false) + Bicopy(ctx, conn, channel) + }() + } +} + +// closeAndRemoveSession closes and removes the session. +func (x *x11Forwarder) closeAndRemoveSession(x11session *x11Session) { + _ = x11session.listener.Close() + x.mu.Lock() + delete(x.sessions, x11session) + x.mu.Unlock() +} + +// createX11Session creates an X11 forwarding session. +func (x *x11Forwarder) createX11Session(ctx context.Context, sshSession ssh.Session) (*x11Session, error) { + var ( + ln net.Listener + display int + err error + ) + // retry listener creation after evictions. Limit to 10 retries to prevent pathological cases looping forever. + const maxRetries = 10 + for try := range maxRetries { + ln, display, err = x.createX11Listener(ctx) + if err == nil { + break + } + if try == maxRetries-1 { + return nil, xerrors.New("max retries exceeded while creating X11 session") + } + x.logger.Warn(ctx, "failed to create X11 listener; will evict an X11 forwarding session", + slog.F("num_current_sessions", x.numSessions()), + slog.Error(err)) + x.evictLeastRecentlyUsedSession() + } + x.mu.Lock() + defer x.mu.Unlock() + if x.closing { + closeErr := ln.Close() + if closeErr != nil { + x.logger.Error(ctx, "error closing X11 listener", slog.Error(closeErr)) + } + return nil, xerrors.New("server is closing") + } + x11Sess := &x11Session{ + session: sshSession, + display: display, + listener: ln, + usedAt: time.Now(), + } + x.sessions[x11Sess] = struct{}{} + return x11Sess, nil +} + +func (x *x11Forwarder) numSessions() int { + x.mu.Lock() + defer x.mu.Unlock() + return len(x.sessions) +} + +func (x *x11Forwarder) popLeastRecentlyUsedSession() *x11Session { + x.mu.Lock() + defer x.mu.Unlock() + var lru *x11Session + for s := range x.sessions { + if lru == nil { + lru = s + continue + } + if s.usedAt.Before(lru.usedAt) { + lru = s + continue + } + } + if lru == nil { + x.logger.Debug(context.Background(), "tried to pop from empty set of X11 sessions") + return nil + } + delete(x.sessions, lru) + return lru +} - return display, true +func (x *x11Forwarder) evictLeastRecentlyUsedSession() { + lru := x.popLeastRecentlyUsedSession() + if lru == nil { + return + } + err := lru.listener.Close() + if err != nil { + x.logger.Error(context.Background(), "failed to close evicted X11 session listener", slog.Error(err)) + } + // when we evict, we also want to force the SSH session to be closed as well. This is because we intend to reuse + // the X11 TCP listener port for a new X11 forwarding session. If we left the SSH session up, then graphical apps + // started in that session could potentially connect to an unintended X11 Server (i.e. the display on a different + // computer than the one that started the SSH session). Most likely, this session is a zombie anyway if we've + // reached the maximum number of X11 forwarding sessions. + err = lru.session.Close() + if err != nil { + x.logger.Error(context.Background(), "failed to close evicted X11 SSH session", slog.Error(err)) + } } // createX11Listener creates a listener for X11 forwarding, it will use // the next available port starting from X11StartPort and displayOffset. -func createX11Listener(ctx context.Context, displayOffset int) (ln net.Listener, display int, err error) { - var lc net.ListenConfig +func (x *x11Forwarder) createX11Listener(ctx context.Context) (ln net.Listener, display int, err error) { // Look for an open port to listen on. - for port := X11StartPort + displayOffset; port < math.MaxUint16; port++ { - ln, err = lc.Listen(ctx, "tcp", fmt.Sprintf("localhost:%d", port)) + for port := X11StartPort + x.displayOffset; port <= X11MaxPort; port++ { + if ctx.Err() != nil { + return nil, -1, ctx.Err() + } + + ln, err = x.network.Listen("tcp", fmt.Sprintf("localhost:%d", port)) if err == nil { display = port - X11StartPort return ln, display, nil @@ -156,6 +328,49 @@ func createX11Listener(ctx context.Context, displayOffset int) (ln net.Listener, return nil, -1, xerrors.Errorf("failed to find open port for X11 listener: %w", err) } +// trackConn registers the connection with the x11Forwarder. If the server is +// closed, the connection is not registered and should be closed. +// +//nolint:revive +func (x *x11Forwarder) trackConn(c net.Conn, add bool) (ok bool) { + x.mu.Lock() + defer x.mu.Unlock() + if add { + if x.closing { + // Server or listener closed. + return false + } + x.wg.Add(1) + x.connections[c] = struct{}{} + return true + } + x.wg.Done() + delete(x.connections, c) + return true +} + +func (x *x11Forwarder) Close() error { + x.mu.Lock() + x.closing = true + + for s := range x.sessions { + sErr := s.listener.Close() + if sErr != nil { + x.logger.Debug(context.Background(), "failed to close X11 listener", slog.Error(sErr)) + } + } + for c := range x.connections { + cErr := c.Close() + if cErr != nil { + x.logger.Debug(context.Background(), "failed to close X11 connection", slog.Error(cErr)) + } + } + + x.mu.Unlock() + x.wg.Wait() + return nil +} + // addXauthEntry adds an Xauthority entry to the Xauthority file. // The Xauthority file is located at ~/.Xauthority. func addXauthEntry(ctx context.Context, fs afero.Fs, host string, display string, authProtocol string, authCookie string) error { diff --git a/agent/agentssh/x11_test.go b/agent/agentssh/x11_test.go index 2ccbbfe69ca5c..83af8a2f83838 100644 --- a/agent/agentssh/x11_test.go +++ b/agent/agentssh/x11_test.go @@ -3,9 +3,9 @@ package agentssh_test import ( "bufio" "bytes" - "context" "encoding/hex" "fmt" + "io" "net" "os" "path/filepath" @@ -32,10 +32,19 @@ func TestServer_X11(t *testing.T) { t.Skip("X11 forwarding is only supported on Linux") } - ctx := context.Background() + ctx := testutil.Context(t, testutil.WaitShort) logger := testutil.Logger(t) - fs := afero.NewOsFs() - s, err := agentssh.NewServer(ctx, logger, prometheus.NewRegistry(), fs, agentexec.DefaultExecer, &agentssh.Config{}) + fs := afero.NewMemMapFs() + + // Use in-process networking for X11 forwarding. + inproc := testutil.NewInProcNet() + + // Create server config with custom X11 listener. + cfg := &agentssh.Config{ + X11Net: inproc, + } + + s, err := agentssh.NewServer(ctx, logger, prometheus.NewRegistry(), fs, agentexec.DefaultExecer, cfg) require.NoError(t, err) defer s.Close() err = s.UpdateHostSigner(42) @@ -93,17 +102,15 @@ func TestServer_X11(t *testing.T) { x11Chans := c.HandleChannelOpen("x11") payload := "hello world" - require.Eventually(t, func() bool { - conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", agentssh.X11StartPort+displayNumber)) - if err == nil { - _, err = conn.Write([]byte(payload)) - assert.NoError(t, err) - _ = conn.Close() - } - return err == nil - }, testutil.WaitShort, testutil.IntervalFast) + go func() { + conn, err := inproc.Dial(ctx, testutil.NewAddr("tcp", fmt.Sprintf("localhost:%d", agentssh.X11StartPort+displayNumber))) + assert.NoError(t, err) + _, err = conn.Write([]byte(payload)) + assert.NoError(t, err) + _ = conn.Close() + }() - x11 := <-x11Chans + x11 := testutil.RequireReceive(ctx, t, x11Chans) ch, reqs, err := x11.Accept() require.NoError(t, err) go gossh.DiscardRequests(reqs) @@ -121,3 +128,209 @@ func TestServer_X11(t *testing.T) { _, err = fs.Stat(filepath.Join(home, ".Xauthority")) require.NoError(t, err) } + +func TestServer_X11_EvictionLRU(t *testing.T) { + t.Parallel() + if runtime.GOOS != "linux" { + t.Skip("X11 forwarding is only supported on Linux") + } + + ctx := testutil.Context(t, testutil.WaitLong) + logger := testutil.Logger(t) + fs := afero.NewMemMapFs() + + // Use in-process networking for X11 forwarding. + inproc := testutil.NewInProcNet() + + cfg := &agentssh.Config{ + X11Net: inproc, + } + + s, err := agentssh.NewServer(ctx, logger, prometheus.NewRegistry(), fs, agentexec.DefaultExecer, cfg) + require.NoError(t, err) + defer s.Close() + err = s.UpdateHostSigner(42) + require.NoError(t, err) + + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + + done := testutil.Go(t, func() { + err := s.Serve(ln) + assert.Error(t, err) + }) + + c := sshClient(t, ln.Addr().String()) + + // block off one port to test x11Forwarder evicts at highest port, not number of listeners. + externalListener, err := inproc.Listen("tcp", + fmt.Sprintf("localhost:%d", agentssh.X11StartPort+agentssh.X11DefaultDisplayOffset+1)) + require.NoError(t, err) + defer externalListener.Close() + + // Calculate how many simultaneous X11 sessions we can create given the + // configured port range. + + startPort := agentssh.X11StartPort + agentssh.X11DefaultDisplayOffset + maxSessions := agentssh.X11MaxPort - startPort + 1 - 1 // -1 for the blocked port + require.Greater(t, maxSessions, 0, "expected a positive maxSessions value") + + // shellSession holds references to the session and its standard streams so + // that the test can keep them open (and optionally interact with them) for + // the lifetime of the test. If we don't start the Shell with pipes in place, + // the session will be torn down asynchronously during the test. + type shellSession struct { + sess *gossh.Session + stdin io.WriteCloser + stdout io.Reader + stderr io.Reader + // scanner is used to read the output of the session, line by line. + scanner *bufio.Scanner + } + + sessions := make([]shellSession, 0, maxSessions) + for i := 0; i < maxSessions; i++ { + sess, err := c.NewSession() + require.NoError(t, err) + + _, err = sess.SendRequest("x11-req", true, gossh.Marshal(ssh.X11{ + AuthProtocol: "MIT-MAGIC-COOKIE-1", + AuthCookie: hex.EncodeToString([]byte(fmt.Sprintf("cookie%d", i))), + ScreenNumber: uint32(0), + })) + require.NoError(t, err) + + stdin, err := sess.StdinPipe() + require.NoError(t, err) + stdout, err := sess.StdoutPipe() + require.NoError(t, err) + stderr, err := sess.StderrPipe() + require.NoError(t, err) + require.NoError(t, sess.Shell()) + + // The SSH server lazily starts the session. We need to write a command + // and read back to ensure the X11 forwarding is started. + scanner := bufio.NewScanner(stdout) + msg := fmt.Sprintf("ready-%d", i) + _, err = stdin.Write([]byte("echo " + msg + "\n")) + require.NoError(t, err) + // Read until we get the message (first token may be empty due to shell prompt) + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if strings.Contains(line, msg) { + break + } + } + require.NoError(t, scanner.Err()) + + sessions = append(sessions, shellSession{ + sess: sess, + stdin: stdin, + stdout: stdout, + stderr: stderr, + scanner: scanner, + }) + } + + // Connect X11 forwarding to the first session. This is used to test that + // connecting counts as a use of the display. + x11Chans := c.HandleChannelOpen("x11") + payload := "hello world" + go func() { + conn, err := inproc.Dial(ctx, testutil.NewAddr("tcp", fmt.Sprintf("localhost:%d", agentssh.X11StartPort+agentssh.X11DefaultDisplayOffset))) + assert.NoError(t, err) + _, err = conn.Write([]byte(payload)) + assert.NoError(t, err) + _ = conn.Close() + }() + + x11 := testutil.RequireReceive(ctx, t, x11Chans) + ch, reqs, err := x11.Accept() + require.NoError(t, err) + go gossh.DiscardRequests(reqs) + got := make([]byte, len(payload)) + _, err = ch.Read(got) + require.NoError(t, err) + assert.Equal(t, payload, string(got)) + _ = ch.Close() + + // Create one more session which should evict a session and reuse the display. + // The first session was used to connect X11 forwarding, so it should not be evicted. + // Therefore, the second session should be evicted and its display reused. + extraSess, err := c.NewSession() + require.NoError(t, err) + + _, err = extraSess.SendRequest("x11-req", true, gossh.Marshal(ssh.X11{ + AuthProtocol: "MIT-MAGIC-COOKIE-1", + AuthCookie: hex.EncodeToString([]byte("extra")), + ScreenNumber: uint32(0), + })) + require.NoError(t, err) + + // Ask the remote side for the DISPLAY value so we can extract the display + // number that was assigned to this session. + out, err := extraSess.Output("echo DISPLAY=$DISPLAY") + require.NoError(t, err) + + // Example output line: "DISPLAY=localhost:10.0". + var newDisplayNumber int + { + sc := bufio.NewScanner(bytes.NewReader(out)) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if strings.HasPrefix(line, "DISPLAY=") { + parts := strings.SplitN(line, ":", 2) + require.Len(t, parts, 2) + displayPart := parts[1] + if strings.Contains(displayPart, ".") { + displayPart = strings.SplitN(displayPart, ".", 2)[0] + } + var convErr error + newDisplayNumber, convErr = strconv.Atoi(displayPart) + require.NoError(t, convErr) + break + } + } + require.NoError(t, sc.Err()) + } + + // The display number reused should correspond to the SECOND session (display offset 12) + expectedDisplay := agentssh.X11DefaultDisplayOffset + 2 // +1 was blocked port + assert.Equal(t, expectedDisplay, newDisplayNumber, "second session should have been evicted and its display reused") + + // First session should still be alive: send cmd and read output. + msgFirst := "still-alive" + _, err = sessions[0].stdin.Write([]byte("echo " + msgFirst + "\n")) + require.NoError(t, err) + for sessions[0].scanner.Scan() { + line := strings.TrimSpace(sessions[0].scanner.Text()) + if strings.Contains(line, msgFirst) { + break + } + } + require.NoError(t, sessions[0].scanner.Err()) + + // Second session should now be closed. + _, err = sessions[1].stdin.Write([]byte("echo dead\n")) + require.ErrorIs(t, err, io.EOF) + err = sessions[1].sess.Wait() + require.Error(t, err) + + // Cleanup. + for i, sh := range sessions { + if i == 1 { + // already closed + continue + } + err = sh.stdin.Close() + require.NoError(t, err) + err = sh.sess.Wait() + require.NoError(t, err) + } + err = extraSess.Close() + require.ErrorIs(t, err, io.EOF) + + err = s.Close() + require.NoError(t, err) + _ = testutil.TryReceive(ctx, t, done) +} diff --git a/agent/api.go b/agent/api.go index 52c2c0fbb3094..ca0760e130ffe 100644 --- a/agent/api.go +++ b/agent/api.go @@ -6,16 +6,13 @@ import ( "time" "github.com/go-chi/chi/v5" - "github.com/google/uuid" - "github.com/coder/coder/v2/agent/agentcontainers" - "github.com/coder/coder/v2/agent/proto" "github.com/coder/coder/v2/coderd/httpapi" "github.com/coder/coder/v2/codersdk" ) -func (a *agent) apiHandler(aAPI proto.DRPCAgentClient26) (http.Handler, func() error) { +func (a *agent) apiHandler() http.Handler { r := chi.NewRouter() r.Get("/", func(rw http.ResponseWriter, r *http.Request) { httpapi.Write(r.Context(), rw, http.StatusOK, codersdk.Response{ @@ -41,38 +38,18 @@ func (a *agent) apiHandler(aAPI proto.DRPCAgentClient26) (http.Handler, func() e } if a.devcontainers { - containerAPIOpts := []agentcontainers.Option{ - agentcontainers.WithExecer(a.execer), - agentcontainers.WithCommandEnv(a.sshServer.CommandEnv), - agentcontainers.WithScriptLogger(func(logSourceID uuid.UUID) agentcontainers.ScriptLogger { - return a.logSender.GetScriptLogger(logSourceID) - }), - agentcontainers.WithSubAgentClient(agentcontainers.NewSubAgentClientFromAPI(a.logger, aAPI)), - } - manifest := a.manifest.Load() - if manifest != nil { - containerAPIOpts = append(containerAPIOpts, - agentcontainers.WithManifestInfo(manifest.OwnerName, manifest.WorkspaceName), - ) - - if len(manifest.Devcontainers) > 0 { - containerAPIOpts = append( - containerAPIOpts, - agentcontainers.WithDevcontainers(manifest.Devcontainers, manifest.Scripts), - ) - } - } - - // Append after to allow the agent options to override the default options. - containerAPIOpts = append(containerAPIOpts, a.containerAPIOptions...) - - containerAPI := agentcontainers.NewAPI(a.logger.Named("containers"), containerAPIOpts...) - r.Mount("/api/v0/containers", containerAPI.Routes()) - a.containerAPI.Store(containerAPI) + r.Mount("/api/v0/containers", a.containerAPI.Routes()) + } else if manifest := a.manifest.Load(); manifest != nil && manifest.ParentID != uuid.Nil { + r.HandleFunc("/api/v0/containers", func(w http.ResponseWriter, r *http.Request) { + httpapi.Write(r.Context(), w, http.StatusForbidden, codersdk.Response{ + Message: "Dev Container feature not supported.", + Detail: "Dev Container integration inside other Dev Containers is explicitly not supported.", + }) + }) } else { r.HandleFunc("/api/v0/containers", func(w http.ResponseWriter, r *http.Request) { httpapi.Write(r.Context(), w, http.StatusForbidden, codersdk.Response{ - Message: "The agent dev containers feature is experimental and not enabled by default.", + Message: "Dev Container feature not enabled.", Detail: "To enable this feature, set CODER_AGENT_DEVCONTAINERS_ENABLE=true in your template.", }) }) @@ -89,12 +66,7 @@ func (a *agent) apiHandler(aAPI proto.DRPCAgentClient26) (http.Handler, func() e r.Get("/debug/manifest", a.HandleHTTPDebugManifest) r.Get("/debug/prometheus", promHandler.ServeHTTP) - return r, func() error { - if containerAPI := a.containerAPI.Load(); containerAPI != nil { - return containerAPI.Close() - } - return nil - } + return r } type listeningPortsHandler struct { diff --git a/archive/fs/zip.go b/archive/fs/zip.go new file mode 100644 index 0000000000000..81f72d18bdf46 --- /dev/null +++ b/archive/fs/zip.go @@ -0,0 +1,19 @@ +package archivefs + +import ( + "archive/zip" + "io" + "io/fs" + + "github.com/spf13/afero" + "github.com/spf13/afero/zipfs" +) + +// FromZipReader creates a read-only in-memory FS +func FromZipReader(r io.ReaderAt, size int64) (fs.FS, error) { + zr, err := zip.NewReader(r, size) + if err != nil { + return nil, err + } + return afero.NewIOFS(zipfs.New(zr)), nil +} diff --git a/catalog-info.yaml b/catalog-info.yaml new file mode 100644 index 0000000000000..91f59872a89ae --- /dev/null +++ b/catalog-info.yaml @@ -0,0 +1,10 @@ +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: coder + annotations: + github.com/project-slug: 'coder/coder' +spec: + type: service + lifecycle: production + owner: rd diff --git a/cli/agent.go b/cli/agent.go index 2285d44fc3584..c192d4429ccaf 100644 --- a/cli/agent.go +++ b/cli/agent.go @@ -40,22 +40,24 @@ import ( func (r *RootCmd) workspaceAgent() *serpent.Command { var ( - auth string - logDir string - scriptDataDir string - pprofAddress string - noReap bool - sshMaxTimeout time.Duration - tailnetListenPort int64 - prometheusAddress string - debugAddress string - slogHumanPath string - slogJSONPath string - slogStackdriverPath string - blockFileTransfer bool - agentHeaderCommand string - agentHeader []string - devcontainers bool + auth string + logDir string + scriptDataDir string + pprofAddress string + noReap bool + sshMaxTimeout time.Duration + tailnetListenPort int64 + prometheusAddress string + debugAddress string + slogHumanPath string + slogJSONPath string + slogStackdriverPath string + blockFileTransfer bool + agentHeaderCommand string + agentHeader []string + devcontainers bool + devcontainerProjectDiscovery bool + devcontainerDiscoveryAutostart bool ) cmd := &serpent.Command{ Use: "agent", @@ -364,6 +366,8 @@ func (r *RootCmd) workspaceAgent() *serpent.Command { Devcontainers: devcontainers, DevcontainerAPIOptions: []agentcontainers.Option{ agentcontainers.WithSubAgentURL(r.agentURL.String()), + agentcontainers.WithProjectDiscovery(devcontainerProjectDiscovery), + agentcontainers.WithDiscoveryAutostart(devcontainerDiscoveryAutostart), }, }) @@ -510,6 +514,20 @@ func (r *RootCmd) workspaceAgent() *serpent.Command { Description: "Allow the agent to automatically detect running devcontainers.", Value: serpent.BoolOf(&devcontainers), }, + { + Flag: "devcontainers-project-discovery-enable", + Default: "true", + Env: "CODER_AGENT_DEVCONTAINERS_PROJECT_DISCOVERY_ENABLE", + Description: "Allow the agent to search the filesystem for devcontainer projects.", + Value: serpent.BoolOf(&devcontainerProjectDiscovery), + }, + { + Flag: "devcontainers-discovery-autostart-enable", + Default: "false", + Env: "CODER_AGENT_DEVCONTAINERS_DISCOVERY_AUTOSTART_ENABLE", + Description: "Allow the agent to autostart devcontainer projects it discovers based on their configuration.", + Value: serpent.BoolOf(&devcontainerDiscoveryAutostart), + }, } return cmd diff --git a/cli/cliui/resources.go b/cli/cliui/resources.go index be112ea177200..36ce4194d72c8 100644 --- a/cli/cliui/resources.go +++ b/cli/cliui/resources.go @@ -12,6 +12,7 @@ import ( "golang.org/x/mod/semver" "github.com/coder/coder/v2/coderd/database/dbtime" + "github.com/coder/coder/v2/coderd/util/slice" "github.com/coder/coder/v2/codersdk" "github.com/coder/pretty" ) @@ -29,6 +30,7 @@ type WorkspaceResourcesOptions struct { ServerVersion string ListeningPorts map[uuid.UUID]codersdk.WorkspaceAgentListeningPortsResponse Devcontainers map[uuid.UUID]codersdk.WorkspaceAgentListContainersResponse + ShowDetails bool } // WorkspaceResources displays the connection status and tree-view of provided resources. @@ -69,7 +71,11 @@ func WorkspaceResources(writer io.Writer, resources []codersdk.WorkspaceResource totalAgents := 0 for _, resource := range resources { - totalAgents += len(resource.Agents) + for _, agent := range resource.Agents { + if !agent.ParentID.Valid { + totalAgents++ + } + } } for _, resource := range resources { @@ -94,12 +100,15 @@ func WorkspaceResources(writer io.Writer, resources []codersdk.WorkspaceResource "", }) // Display all agents associated with the resource. - for index, agent := range resource.Agents { + agents := slice.Filter(resource.Agents, func(agent codersdk.WorkspaceAgent) bool { + return !agent.ParentID.Valid + }) + for index, agent := range agents { tableWriter.AppendRow(renderAgentRow(agent, index, totalAgents, options)) for _, row := range renderListeningPorts(options, agent.ID, index, totalAgents) { tableWriter.AppendRow(row) } - for _, row := range renderDevcontainers(options, agent.ID, index, totalAgents) { + for _, row := range renderDevcontainers(resources, options, agent.ID, index, totalAgents) { tableWriter.AppendRow(row) } } @@ -125,7 +134,7 @@ func renderAgentRow(agent codersdk.WorkspaceAgent, index, totalAgents int, optio } if !options.HideAccess { sshCommand := "coder ssh " + options.WorkspaceName - if totalAgents > 1 { + if totalAgents > 1 || len(options.Devcontainers) > 0 { sshCommand += "." + agent.Name } sshCommand = pretty.Sprint(DefaultStyles.Code, sshCommand) @@ -164,45 +173,129 @@ func renderPortRow(port codersdk.WorkspaceAgentListeningPort, idx, total int) ta return table.Row{sb.String()} } -func renderDevcontainers(wro WorkspaceResourcesOptions, agentID uuid.UUID, index, totalAgents int) []table.Row { +func renderDevcontainers(resources []codersdk.WorkspaceResource, wro WorkspaceResourcesOptions, agentID uuid.UUID, index, totalAgents int) []table.Row { var rows []table.Row if wro.Devcontainers == nil { return []table.Row{} } dc, ok := wro.Devcontainers[agentID] - if !ok || len(dc.Containers) == 0 { + if !ok || len(dc.Devcontainers) == 0 { return []table.Row{} } rows = append(rows, table.Row{ fmt.Sprintf(" %s─ %s", renderPipe(index, totalAgents), "Devcontainers"), }) - for idx, container := range dc.Containers { - rows = append(rows, renderDevcontainerRow(container, idx, len(dc.Containers))) + for idx, devcontainer := range dc.Devcontainers { + rows = append(rows, renderDevcontainerRow(resources, devcontainer, idx, len(dc.Devcontainers), wro)...) } return rows } -func renderDevcontainerRow(container codersdk.WorkspaceAgentContainer, index, total int) table.Row { - var row table.Row - var sb strings.Builder - _, _ = sb.WriteString(" ") - _, _ = sb.WriteString(renderPipe(index, total)) - _, _ = sb.WriteString("─ ") - _, _ = sb.WriteString(pretty.Sprintf(DefaultStyles.Code, "%s", container.FriendlyName)) - row = append(row, sb.String()) - sb.Reset() - if container.Running { - _, _ = sb.WriteString(pretty.Sprintf(DefaultStyles.Keyword, "(%s)", container.Status)) - } else { - _, _ = sb.WriteString(pretty.Sprintf(DefaultStyles.Error, "(%s)", container.Status)) +func renderDevcontainerRow(resources []codersdk.WorkspaceResource, devcontainer codersdk.WorkspaceAgentDevcontainer, index, total int, wro WorkspaceResourcesOptions) []table.Row { + var rows []table.Row + + // If the devcontainer is running and has an associated agent, we want to + // display the agent's details. Otherwise, we just display the devcontainer + // name and status. + var subAgent *codersdk.WorkspaceAgent + displayName := devcontainer.Name + if devcontainer.Agent != nil && devcontainer.Status == codersdk.WorkspaceAgentDevcontainerStatusRunning { + for _, resource := range resources { + if agent, found := slice.Find(resource.Agents, func(agent codersdk.WorkspaceAgent) bool { + return agent.ID == devcontainer.Agent.ID + }); found { + subAgent = &agent + break + } + } + if subAgent != nil { + displayName = subAgent.Name + displayName += fmt.Sprintf(" (%s, %s)", subAgent.OperatingSystem, subAgent.Architecture) + } + } + + if devcontainer.Container != nil { + displayName += " " + pretty.Sprint(DefaultStyles.Keyword, "["+devcontainer.Container.FriendlyName+"]") + } + + // Build the main row. + row := table.Row{ + fmt.Sprintf(" %s─ %s", renderPipe(index, total), displayName), + } + + // Add status, health, and version columns. + if !wro.HideAgentState { + if subAgent != nil { + row = append(row, renderAgentStatus(*subAgent)) + row = append(row, renderAgentHealth(*subAgent)) + row = append(row, renderAgentVersion(subAgent.Version, wro.ServerVersion)) + } else { + row = append(row, renderDevcontainerStatus(devcontainer.Status)) + row = append(row, "") // No health for devcontainer without agent. + row = append(row, "") // No version for devcontainer without agent. + } + } + + // Add access column. + if !wro.HideAccess { + if subAgent != nil { + accessString := fmt.Sprintf("coder ssh %s.%s", wro.WorkspaceName, subAgent.Name) + row = append(row, pretty.Sprint(DefaultStyles.Code, accessString)) + } else { + row = append(row, "") // No access for devcontainers without agent. + } + } + + rows = append(rows, row) + + // Add error message if present. + if errorMessage := devcontainer.Error; errorMessage != "" { + // Cap error message length for display. + if !wro.ShowDetails && len(errorMessage) > 80 { + errorMessage = errorMessage[:79] + "…" + } + errorRow := table.Row{ + " × " + pretty.Sprint(DefaultStyles.Error, errorMessage), + "", + "", + "", + } + if !wro.HideAccess { + errorRow = append(errorRow, "") + } + rows = append(rows, errorRow) + } + + // Add listening ports for the devcontainer agent. + if subAgent != nil { + portRows := renderListeningPorts(wro, subAgent.ID, index, total) + for _, portRow := range portRows { + // Adjust indentation for ports under devcontainer agent. + if len(portRow) > 0 { + if str, ok := portRow[0].(string); ok { + portRow[0] = " " + str // Add extra indentation. + } + } + rows = append(rows, portRow) + } + } + + return rows +} + +func renderDevcontainerStatus(status codersdk.WorkspaceAgentDevcontainerStatus) string { + switch status { + case codersdk.WorkspaceAgentDevcontainerStatusRunning: + return pretty.Sprint(DefaultStyles.Keyword, "▶ running") + case codersdk.WorkspaceAgentDevcontainerStatusStopped: + return pretty.Sprint(DefaultStyles.Placeholder, "⏹ stopped") + case codersdk.WorkspaceAgentDevcontainerStatusStarting: + return pretty.Sprint(DefaultStyles.Warn, "⧗ starting") + case codersdk.WorkspaceAgentDevcontainerStatusError: + return pretty.Sprint(DefaultStyles.Error, "✘ error") + default: + return pretty.Sprint(DefaultStyles.Placeholder, "○ "+string(status)) } - row = append(row, sb.String()) - sb.Reset() - // "health" is not applicable here. - row = append(row, sb.String()) - _, _ = sb.WriteString(container.Image) - row = append(row, sb.String()) - return row } func renderAgentStatus(agent codersdk.WorkspaceAgent) string { diff --git a/cli/configssh.go b/cli/configssh.go index c1be60b604a9e..b12b9d5c3d5cd 100644 --- a/cli/configssh.go +++ b/cli/configssh.go @@ -446,7 +446,7 @@ func (r *RootCmd) configSSH() *serpent.Command { if !bytes.Equal(configRaw, configModified) { sshDir := filepath.Dir(sshConfigFile) - if err := os.MkdirAll(sshDir, 0700); err != nil { + if err := os.MkdirAll(sshDir, 0o700); err != nil { return xerrors.Errorf("failed to create directory %q: %w", sshDir, err) } diff --git a/cli/configssh_test.go b/cli/configssh_test.go index 1ffe93a7b838c..7e42bfe81a799 100644 --- a/cli/configssh_test.go +++ b/cli/configssh_test.go @@ -204,10 +204,11 @@ func TestConfigSSH_MissingDirectory(t *testing.T) { _, err = os.Stat(sshConfigPath) require.NoError(t, err, "config file should exist") - // Check that the directory has proper permissions (0700) + // Check that the directory has proper permissions (rwx for owner, none for + // group and everyone) sshDirInfo, err := os.Stat(sshDir) require.NoError(t, err) - require.Equal(t, os.FileMode(0700), sshDirInfo.Mode().Perm(), "directory should have 0700 permissions") + require.Equal(t, os.FileMode(0o700), sshDirInfo.Mode().Perm(), "directory should have rwx------ permissions") } func TestConfigSSH_FileWriteAndOptionsFlow(t *testing.T) { @@ -358,7 +359,8 @@ func TestConfigSSH_FileWriteAndOptionsFlow(t *testing.T) { strings.Join([]string{ headerEnd, "", - }, "\n")}, + }, "\n"), + }, }, args: []string{"--ssh-option", "ForwardAgent=yes"}, matches: []match{ @@ -383,7 +385,8 @@ func TestConfigSSH_FileWriteAndOptionsFlow(t *testing.T) { strings.Join([]string{ headerEnd, "", - }, "\n")}, + }, "\n"), + }, }, args: []string{"--ssh-option", "ForwardAgent=yes"}, matches: []match{ diff --git a/cli/create.go b/cli/create.go index fbf26349b3b95..3f52e59e8ad90 100644 --- a/cli/create.go +++ b/cli/create.go @@ -2,6 +2,7 @@ package cli import ( "context" + "errors" "fmt" "io" "slices" @@ -21,10 +22,18 @@ import ( "github.com/coder/serpent" ) +// PresetNone represents the special preset value "none". +// It is used when a user runs `create --preset none`, +// indicating that the CLI should not apply any preset. +const PresetNone = "none" + +var ErrNoPresetFound = xerrors.New("no preset found") + func (r *RootCmd) create() *serpent.Command { var ( templateName string templateVersion string + presetName string startAt string stopAfter time.Duration workspaceName string @@ -263,11 +272,45 @@ func (r *RootCmd) create() *serpent.Command { } } + // Get presets for the template version + tvPresets, err := client.TemplateVersionPresets(inv.Context(), templateVersionID) + if err != nil { + return xerrors.Errorf("failed to get presets: %w", err) + } + + var preset *codersdk.Preset + var presetParameters []codersdk.WorkspaceBuildParameter + + // If the template has no presets, or the user explicitly used --preset none, + // skip applying a preset + if len(tvPresets) > 0 && strings.ToLower(presetName) != PresetNone { + // Attempt to resolve which preset to use + preset, err = resolvePreset(tvPresets, presetName) + if err != nil { + if !errors.Is(err, ErrNoPresetFound) { + return xerrors.Errorf("unable to resolve preset: %w", err) + } + // If no preset found, prompt the user to choose a preset + if preset, err = promptPresetSelection(inv, tvPresets); err != nil { + return xerrors.Errorf("unable to prompt user for preset: %w", err) + } + } + + // Convert preset parameters into workspace build parameters + presetParameters = presetParameterAsWorkspaceBuildParameters(preset.Parameters) + // Inform the user which preset was applied and its parameters + displayAppliedPreset(inv, preset, presetParameters) + } else { + // Inform the user that no preset was applied + _, _ = fmt.Fprintf(inv.Stdout, "%s", cliui.Bold("No preset applied.")) + } + richParameters, err := prepWorkspaceBuild(inv, client, prepWorkspaceBuildArgs{ Action: WorkspaceCreate, TemplateVersionID: templateVersionID, NewWorkspaceName: workspaceName, + PresetParameters: presetParameters, RichParameterFile: parameterFlags.richParameterFile, RichParameters: cliBuildParameters, RichParameterDefaults: cliBuildParameterDefaults, @@ -291,14 +334,21 @@ func (r *RootCmd) create() *serpent.Command { ttlMillis = ptr.Ref(stopAfter.Milliseconds()) } - workspace, err := client.CreateUserWorkspace(inv.Context(), workspaceOwner, codersdk.CreateWorkspaceRequest{ + req := codersdk.CreateWorkspaceRequest{ TemplateVersionID: templateVersionID, Name: workspaceName, AutostartSchedule: schedSpec, TTLMillis: ttlMillis, RichParameterValues: richParameters, AutomaticUpdates: codersdk.AutomaticUpdates(autoUpdates), - }) + } + + // If a preset exists, update the create workspace request's preset ID + if preset != nil { + req.TemplateVersionPresetID = preset.ID + } + + workspace, err := client.CreateUserWorkspace(inv.Context(), workspaceOwner, req) if err != nil { return xerrors.Errorf("create workspace: %w", err) } @@ -333,6 +383,12 @@ func (r *RootCmd) create() *serpent.Command { Description: "Specify a template version name.", Value: serpent.StringOf(&templateVersion), }, + serpent.Option{ + Flag: "preset", + Env: "CODER_PRESET_NAME", + Description: "Specify the name of a template version preset. Use 'none' to explicitly indicate that no preset should be used.", + Value: serpent.StringOf(&presetName), + }, serpent.Option{ Flag: "start-at", Env: "CODER_WORKSPACE_START_AT", @@ -377,12 +433,81 @@ type prepWorkspaceBuildArgs struct { PromptEphemeralParameters bool EphemeralParameters []codersdk.WorkspaceBuildParameter + PresetParameters []codersdk.WorkspaceBuildParameter PromptRichParameters bool RichParameters []codersdk.WorkspaceBuildParameter RichParameterFile string RichParameterDefaults []codersdk.WorkspaceBuildParameter } +// resolvePreset returns the preset matching the given presetName (if specified), +// or the default preset (if any). +// Returns ErrNoPresetFound if no matching or default preset is found. +func resolvePreset(presets []codersdk.Preset, presetName string) (*codersdk.Preset, error) { + // If preset name is specified, find it + if presetName != "" { + for _, p := range presets { + if p.Name == presetName { + return &p, nil + } + } + return nil, xerrors.Errorf("preset %q not found", presetName) + } + + // No preset name specified, search for the default preset + for _, p := range presets { + if p.Default { + return &p, nil + } + } + + // No preset found + return nil, ErrNoPresetFound +} + +// promptPresetSelection shows a CLI selection menu of the presets defined in the template version. +// Returns the selected preset +func promptPresetSelection(inv *serpent.Invocation, presets []codersdk.Preset) (*codersdk.Preset, error) { + presetMap := make(map[string]*codersdk.Preset) + var presetOptions []string + + for _, preset := range presets { + var option string + if preset.Description == "" { + option = preset.Name + } else { + option = fmt.Sprintf("%s: %s", preset.Name, preset.Description) + } + presetOptions = append(presetOptions, option) + presetMap[option] = &preset + } + + // Show selection UI + _, _ = fmt.Fprintln(inv.Stdout, pretty.Sprint(cliui.DefaultStyles.Wrap, "Select a preset below:")) + selected, err := cliui.Select(inv, cliui.SelectOptions{ + Options: presetOptions, + HideSearch: true, + }) + if err != nil { + return nil, xerrors.Errorf("failed to select preset: %w", err) + } + + return presetMap[selected], nil +} + +// displayAppliedPreset shows the user which preset was applied and its parameters +func displayAppliedPreset(inv *serpent.Invocation, preset *codersdk.Preset, parameters []codersdk.WorkspaceBuildParameter) { + label := fmt.Sprintf("Preset '%s'", preset.Name) + if preset.Default { + label += " (default)" + } + + _, _ = fmt.Fprintf(inv.Stdout, "%s applied:\n", cliui.Bold(label)) + for _, param := range parameters { + _, _ = fmt.Fprintf(inv.Stdout, " %s: '%s'\n", cliui.Bold(param.Name), param.Value) + } +} + // prepWorkspaceBuild will ensure a workspace build will succeed on the latest template version. // Any missing params will be prompted to the user. It supports rich parameters. func prepWorkspaceBuild(inv *serpent.Invocation, client *codersdk.Client, args prepWorkspaceBuildArgs) ([]codersdk.WorkspaceBuildParameter, error) { @@ -411,6 +536,7 @@ func prepWorkspaceBuild(inv *serpent.Invocation, client *codersdk.Client, args p WithSourceWorkspaceParameters(args.SourceWorkspaceParameters). WithPromptEphemeralParameters(args.PromptEphemeralParameters). WithEphemeralParameters(args.EphemeralParameters). + WithPresetParameters(args.PresetParameters). WithPromptRichParameters(args.PromptRichParameters). WithRichParameters(args.RichParameters). WithRichParametersFile(parameterFile). diff --git a/cli/create_test.go b/cli/create_test.go index 668fd466d605c..dd26e450d3916 100644 --- a/cli/create_test.go +++ b/cli/create_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/coder/coder/v2/cli" "github.com/coder/coder/v2/cli/clitest" "github.com/coder/coder/v2/coderd/coderdtest" "github.com/coder/coder/v2/coderd/externalauth" @@ -298,7 +299,7 @@ func TestCreate(t *testing.T) { }) } -func prepareEchoResponses(parameters []*proto.RichParameter) *echo.Responses { +func prepareEchoResponses(parameters []*proto.RichParameter, presets ...*proto.Preset) *echo.Responses { return &echo.Responses{ Parse: echo.ParseComplete, ProvisionPlan: []*proto.Response{ @@ -306,6 +307,7 @@ func prepareEchoResponses(parameters []*proto.RichParameter) *echo.Responses { Type: &proto.Response_Plan{ Plan: &proto.PlanComplete{ Parameters: parameters, + Presets: presets, }, }, }, @@ -663,6 +665,642 @@ func TestCreateWithRichParameters(t *testing.T) { }) } +func TestCreateWithPreset(t *testing.T) { + t.Parallel() + + const ( + firstParameterName = "first_parameter" + firstParameterDisplayName = "First Parameter" + firstParameterDescription = "This is the first parameter" + firstParameterValue = "1" + + firstOptionalParameterName = "first_optional_parameter" + firstOptionalParameterDescription = "This is the first optional parameter" + firstOptionalParameterValue = "1" + secondOptionalParameterName = "second_optional_parameter" + secondOptionalParameterDescription = "This is the second optional parameter" + secondOptionalParameterValue = "2" + + thirdParameterName = "third_parameter" + thirdParameterDescription = "This is the third parameter" + thirdParameterValue = "3" + ) + + echoResponses := func(presets ...*proto.Preset) *echo.Responses { + return prepareEchoResponses([]*proto.RichParameter{ + { + Name: firstParameterName, + DisplayName: firstParameterDisplayName, + Description: firstParameterDescription, + Mutable: true, + DefaultValue: firstParameterValue, + Options: []*proto.RichParameterOption{ + { + Name: firstOptionalParameterName, + Description: firstOptionalParameterDescription, + Value: firstOptionalParameterValue, + }, + { + Name: secondOptionalParameterName, + Description: secondOptionalParameterDescription, + Value: secondOptionalParameterValue, + }, + }, + }, + { + Name: thirdParameterName, + Description: thirdParameterDescription, + DefaultValue: thirdParameterValue, + Mutable: true, + }, + }, presets...) + } + + // This test verifies that when a template has presets, + // including a default preset, and the user specifies a `--preset` flag, + // the CLI uses the specified preset instead of the default + t.Run("PresetFlag", func(t *testing.T) { + t.Parallel() + + client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true}) + owner := coderdtest.CreateFirstUser(t, client) + member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) + + // Given: a template and a template version with two presets, including a default + defaultPreset := proto.Preset{ + Name: "preset-default", + Default: true, + Parameters: []*proto.PresetParameter{ + {Name: thirdParameterName, Value: thirdParameterValue}, + }, + } + preset := proto.Preset{ + Name: "preset-test", + Parameters: []*proto.PresetParameter{ + {Name: firstParameterName, Value: secondOptionalParameterValue}, + {Name: thirdParameterName, Value: thirdParameterValue}, + }, + } + version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses(&defaultPreset, &preset)) + coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) + template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) + + // When: running the create command with the specified preset + workspaceName := "my-workspace" + inv, root := clitest.New(t, "create", workspaceName, "--template", template.Name, "-y", "--preset", preset.Name) + clitest.SetupConfig(t, member, root) + pty := ptytest.New(t).Attach(inv) + inv.Stdout = pty.Output() + inv.Stderr = pty.Output() + err := inv.Run() + require.NoError(t, err) + + // Should: display the selected preset as well as its parameters + presetName := fmt.Sprintf("Preset '%s' applied:", preset.Name) + pty.ExpectMatch(presetName) + pty.ExpectMatch(fmt.Sprintf("%s: '%s'", firstParameterName, secondOptionalParameterValue)) + pty.ExpectMatch(fmt.Sprintf("%s: '%s'", thirdParameterName, thirdParameterValue)) + + // Verify if the new workspace uses expected parameters. + ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort) + defer cancel() + + tvPresets, err := client.TemplateVersionPresets(ctx, version.ID) + require.NoError(t, err) + require.Len(t, tvPresets, 2) + var selectedPreset *codersdk.Preset + for _, tvPreset := range tvPresets { + if tvPreset.Name == preset.Name { + selectedPreset = &tvPreset + } + } + require.NotNil(t, selectedPreset) + + workspaces, err := client.Workspaces(ctx, codersdk.WorkspaceFilter{ + Name: workspaceName, + }) + require.NoError(t, err) + require.Len(t, workspaces.Workspaces, 1) + + // Should: create a workspace using the expected template version and the preset-defined parameters + workspaceLatestBuild := workspaces.Workspaces[0].LatestBuild + require.Equal(t, version.ID, workspaceLatestBuild.TemplateVersionID) + require.Equal(t, selectedPreset.ID, *workspaceLatestBuild.TemplateVersionPresetID) + buildParameters, err := client.WorkspaceBuildParameters(ctx, workspaceLatestBuild.ID) + require.NoError(t, err) + require.Len(t, buildParameters, 2) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: firstParameterName, Value: secondOptionalParameterValue}) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: thirdParameterName, Value: thirdParameterValue}) + }) + + // This test verifies that when a template has presets, + // including a default preset, and the user does not specify the `--preset` flag, + // the CLI automatically uses the default preset to create the workspace + t.Run("DefaultPreset", func(t *testing.T) { + t.Parallel() + + client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true}) + owner := coderdtest.CreateFirstUser(t, client) + member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) + + // Given: a template and a template version with two presets, including a default + defaultPreset := proto.Preset{ + Name: "preset-default", + Default: true, + Parameters: []*proto.PresetParameter{ + {Name: firstParameterName, Value: secondOptionalParameterValue}, + {Name: thirdParameterName, Value: thirdParameterValue}, + }, + } + preset := proto.Preset{ + Name: "preset-test", + Parameters: []*proto.PresetParameter{ + {Name: thirdParameterName, Value: thirdParameterValue}, + }, + } + version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses(&defaultPreset, &preset)) + coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) + template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) + + // When: running the create command without a preset + workspaceName := "my-workspace" + inv, root := clitest.New(t, "create", workspaceName, "--template", template.Name, "-y") + clitest.SetupConfig(t, member, root) + pty := ptytest.New(t).Attach(inv) + inv.Stdout = pty.Output() + inv.Stderr = pty.Output() + err := inv.Run() + require.NoError(t, err) + + // Should: display the default preset as well as its parameters + presetName := fmt.Sprintf("Preset '%s' (default) applied:", defaultPreset.Name) + pty.ExpectMatch(presetName) + pty.ExpectMatch(fmt.Sprintf("%s: '%s'", firstParameterName, secondOptionalParameterValue)) + pty.ExpectMatch(fmt.Sprintf("%s: '%s'", thirdParameterName, thirdParameterValue)) + + // Verify if the new workspace uses expected parameters. + ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort) + defer cancel() + + tvPresets, err := client.TemplateVersionPresets(ctx, version.ID) + require.NoError(t, err) + require.Len(t, tvPresets, 2) + var selectedPreset *codersdk.Preset + for _, tvPreset := range tvPresets { + if tvPreset.Default { + selectedPreset = &tvPreset + } + } + require.NotNil(t, selectedPreset) + + workspaces, err := client.Workspaces(ctx, codersdk.WorkspaceFilter{ + Name: workspaceName, + }) + require.NoError(t, err) + require.Len(t, workspaces.Workspaces, 1) + + // Should: create a workspace using the expected template version and the default preset parameters + workspaceLatestBuild := workspaces.Workspaces[0].LatestBuild + require.Equal(t, version.ID, workspaceLatestBuild.TemplateVersionID) + require.Equal(t, selectedPreset.ID, *workspaceLatestBuild.TemplateVersionPresetID) + buildParameters, err := client.WorkspaceBuildParameters(ctx, workspaceLatestBuild.ID) + require.NoError(t, err) + require.Len(t, buildParameters, 2) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: firstParameterName, Value: secondOptionalParameterValue}) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: thirdParameterName, Value: thirdParameterValue}) + }) + + // This test verifies that when a template has presets but no default preset, + // and the user does not provide the `--preset` flag, + // the CLI prompts the user to select a preset. + t.Run("NoDefaultPresetPromptUser", func(t *testing.T) { + t.Parallel() + + client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true}) + owner := coderdtest.CreateFirstUser(t, client) + member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) + + // Given: a template and a template version with two presets + preset := proto.Preset{ + Name: "preset-test", + Description: "Preset Test.", + Parameters: []*proto.PresetParameter{ + {Name: firstParameterName, Value: secondOptionalParameterValue}, + {Name: thirdParameterName, Value: thirdParameterValue}, + }, + } + version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses(&preset)) + coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) + template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) + + // When: running the create command without specifying a preset + workspaceName := "my-workspace" + inv, root := clitest.New(t, "create", workspaceName, "--template", template.Name, + "--parameter", fmt.Sprintf("%s=%s", firstParameterName, firstOptionalParameterValue), + "--parameter", fmt.Sprintf("%s=%s", thirdParameterName, thirdParameterValue)) + clitest.SetupConfig(t, member, root) + doneChan := make(chan struct{}) + pty := ptytest.New(t).Attach(inv) + go func() { + defer close(doneChan) + err := inv.Run() + assert.NoError(t, err) + }() + + // Should: prompt the user for the preset + pty.ExpectMatch("Select a preset below:") + pty.WriteLine("\n") + pty.ExpectMatch("Preset 'preset-test' applied") + pty.ExpectMatch("Confirm create?") + pty.WriteLine("yes") + + <-doneChan + + // Verify if the new workspace uses expected parameters. + ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort) + defer cancel() + + tvPresets, err := client.TemplateVersionPresets(ctx, version.ID) + require.NoError(t, err) + require.Len(t, tvPresets, 1) + + workspaces, err := client.Workspaces(ctx, codersdk.WorkspaceFilter{ + Name: workspaceName, + }) + require.NoError(t, err) + require.Len(t, workspaces.Workspaces, 1) + + // Should: create a workspace using the expected template version and the preset-defined parameters + workspaceLatestBuild := workspaces.Workspaces[0].LatestBuild + require.Equal(t, version.ID, workspaceLatestBuild.TemplateVersionID) + require.Equal(t, tvPresets[0].ID, *workspaceLatestBuild.TemplateVersionPresetID) + buildParameters, err := client.WorkspaceBuildParameters(ctx, workspaceLatestBuild.ID) + require.NoError(t, err) + require.Len(t, buildParameters, 2) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: firstParameterName, Value: secondOptionalParameterValue}) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: thirdParameterName, Value: thirdParameterValue}) + }) + + // This test verifies that when a template version has no presets, + // the CLI does not prompt the user to select a preset and proceeds + // with workspace creation without applying any preset. + t.Run("TemplateVersionWithoutPresets", func(t *testing.T) { + t.Parallel() + + client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true}) + owner := coderdtest.CreateFirstUser(t, client) + member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) + + // Given: a template and a template version without presets + version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses()) + coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) + template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) + + // When: running the create command without a preset + workspaceName := "my-workspace" + inv, root := clitest.New(t, "create", workspaceName, "--template", template.Name, "-y", + "--parameter", fmt.Sprintf("%s=%s", firstParameterName, firstOptionalParameterValue), + "--parameter", fmt.Sprintf("%s=%s", thirdParameterName, thirdParameterValue)) + clitest.SetupConfig(t, member, root) + pty := ptytest.New(t).Attach(inv) + inv.Stdout = pty.Output() + inv.Stderr = pty.Output() + err := inv.Run() + require.NoError(t, err) + pty.ExpectMatch("No preset applied.") + + // Verify if the new workspace uses expected parameters. + ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort) + defer cancel() + + workspaces, err := client.Workspaces(ctx, codersdk.WorkspaceFilter{ + Name: workspaceName, + }) + require.NoError(t, err) + require.Len(t, workspaces.Workspaces, 1) + + // Should: create a workspace using the expected template version and no preset + workspaceLatestBuild := workspaces.Workspaces[0].LatestBuild + require.Equal(t, version.ID, workspaceLatestBuild.TemplateVersionID) + require.Nil(t, workspaceLatestBuild.TemplateVersionPresetID) + buildParameters, err := client.WorkspaceBuildParameters(ctx, workspaceLatestBuild.ID) + require.NoError(t, err) + require.Len(t, buildParameters, 2) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: firstParameterName, Value: firstOptionalParameterValue}) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: thirdParameterName, Value: thirdParameterValue}) + }) + + // This test verifies that when the user provides `--preset none`, + // the CLI skips applying any preset, even if the template version has a default preset. + // The workspace should be created without using any preset-defined parameters. + t.Run("PresetFlagNone", func(t *testing.T) { + t.Parallel() + + client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true}) + owner := coderdtest.CreateFirstUser(t, client) + member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) + + // Given: a template and a template version with a default preset + preset := proto.Preset{ + Name: "preset-test", + Default: true, + Parameters: []*proto.PresetParameter{ + {Name: firstParameterName, Value: secondOptionalParameterValue}, + {Name: thirdParameterName, Value: thirdParameterValue}, + }, + } + version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses(&preset)) + coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) + template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) + + // When: running the create command with flag '--preset none' + workspaceName := "my-workspace" + inv, root := clitest.New(t, "create", workspaceName, "--template", template.Name, "-y", "--preset", cli.PresetNone, + "--parameter", fmt.Sprintf("%s=%s", firstParameterName, firstOptionalParameterValue), + "--parameter", fmt.Sprintf("%s=%s", thirdParameterName, thirdParameterValue)) + clitest.SetupConfig(t, member, root) + pty := ptytest.New(t).Attach(inv) + inv.Stdout = pty.Output() + inv.Stderr = pty.Output() + err := inv.Run() + require.NoError(t, err) + pty.ExpectMatch("No preset applied.") + + // Verify that the new workspace doesn't use the preset parameters. + ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort) + defer cancel() + + tvPresets, err := client.TemplateVersionPresets(ctx, version.ID) + require.NoError(t, err) + require.Len(t, tvPresets, 1) + + workspaces, err := client.Workspaces(ctx, codersdk.WorkspaceFilter{ + Name: workspaceName, + }) + require.NoError(t, err) + require.Len(t, workspaces.Workspaces, 1) + + // Should: create a workspace using the expected template version and no preset + workspaceLatestBuild := workspaces.Workspaces[0].LatestBuild + require.Equal(t, version.ID, workspaceLatestBuild.TemplateVersionID) + require.Nil(t, workspaceLatestBuild.TemplateVersionPresetID) + buildParameters, err := client.WorkspaceBuildParameters(ctx, workspaceLatestBuild.ID) + require.NoError(t, err) + require.Len(t, buildParameters, 2) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: firstParameterName, Value: firstOptionalParameterValue}) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: thirdParameterName, Value: thirdParameterValue}) + }) + + // This test verifies that the CLI returns an appropriate error + // when a user provides a `--preset` value that does not correspond + // to any existing preset in the template version. + t.Run("FailsWhenPresetDoesNotExist", func(t *testing.T) { + t.Parallel() + + client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true}) + owner := coderdtest.CreateFirstUser(t, client) + member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) + + // Given: a template and a template version where the preset defines values for all required parameters + preset := proto.Preset{ + Name: "preset-test", + Parameters: []*proto.PresetParameter{ + {Name: firstParameterName, Value: secondOptionalParameterValue}, + {Name: thirdParameterName, Value: thirdParameterValue}, + }, + } + version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses(&preset)) + coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) + template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) + + // When: running the create command with a non-existent preset + workspaceName := "my-workspace" + inv, root := clitest.New(t, "create", workspaceName, "--template", template.Name, "-y", "--preset", "invalid-preset") + clitest.SetupConfig(t, member, root) + pty := ptytest.New(t).Attach(inv) + inv.Stdout = pty.Output() + inv.Stderr = pty.Output() + err := inv.Run() + + // Should: fail with an error indicating the preset was not found + require.Contains(t, err.Error(), "preset \"invalid-preset\" not found") + }) + + // This test verifies that when both a preset and a user-provided + // `--parameter` flag define a value for the same parameter, + // the preset's value takes precedence over the user's. + // + // The preset defines one parameter (A), and two `--parameter` flags provide A and B. + // The workspace should be created using: + // - the value of parameter A from the preset (overriding the parameter flag's value), + // - and the value of parameter B from the parameter flag. + t.Run("PresetOverridesParameterFlagValues", func(t *testing.T) { + t.Parallel() + + client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true}) + owner := coderdtest.CreateFirstUser(t, client) + member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) + + // Given: a template version with a preset that defines one parameter + preset := proto.Preset{ + Name: "preset-test", + Parameters: []*proto.PresetParameter{ + {Name: firstParameterName, Value: secondOptionalParameterValue}, + }, + } + version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses(&preset)) + coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) + template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) + + // When: creating a workspace with a preset and passing overlapping and additional parameters via `--parameter` + workspaceName := "my-workspace" + inv, root := clitest.New(t, "create", workspaceName, "--template", template.Name, "-y", + "--preset", preset.Name, + "--parameter", fmt.Sprintf("%s=%s", firstParameterName, firstOptionalParameterValue), + "--parameter", fmt.Sprintf("%s=%s", thirdParameterName, thirdParameterValue)) + clitest.SetupConfig(t, member, root) + pty := ptytest.New(t).Attach(inv) + inv.Stdout = pty.Output() + inv.Stderr = pty.Output() + err := inv.Run() + require.NoError(t, err) + + // Should: display the selected preset as well as its parameter + presetName := fmt.Sprintf("Preset '%s' applied:", preset.Name) + pty.ExpectMatch(presetName) + pty.ExpectMatch(fmt.Sprintf("%s: '%s'", firstParameterName, secondOptionalParameterValue)) + + // Verify if the new workspace uses expected parameters. + ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort) + defer cancel() + + tvPresets, err := client.TemplateVersionPresets(ctx, version.ID) + require.NoError(t, err) + require.Len(t, tvPresets, 1) + + workspaces, err := client.Workspaces(ctx, codersdk.WorkspaceFilter{ + Name: workspaceName, + }) + require.NoError(t, err) + require.Len(t, workspaces.Workspaces, 1) + + // Should: include both parameters, one from the preset and one from the `--parameter` flag + workspaceLatestBuild := workspaces.Workspaces[0].LatestBuild + require.Equal(t, version.ID, workspaceLatestBuild.TemplateVersionID) + require.Equal(t, tvPresets[0].ID, *workspaceLatestBuild.TemplateVersionPresetID) + buildParameters, err := client.WorkspaceBuildParameters(ctx, workspaceLatestBuild.ID) + require.NoError(t, err) + require.Len(t, buildParameters, 2) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: firstParameterName, Value: secondOptionalParameterValue}) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: thirdParameterName, Value: thirdParameterValue}) + }) + + // This test verifies that when both a preset and a user-provided + // `--rich-parameter-file` define a value for the same parameter, + // the preset's value takes precedence over the one in the file. + // + // The preset defines one parameter (A), and the parameter file provides two parameters (A and B). + // The workspace should be created using: + // - the value of parameter A from the preset (overriding the file's value), + // - and the value of parameter B from the file. + t.Run("PresetOverridesParameterFileValues", func(t *testing.T) { + t.Parallel() + + client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true}) + owner := coderdtest.CreateFirstUser(t, client) + member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) + + // Given: a template version with a preset that defines one parameter + preset := proto.Preset{ + Name: "preset-test", + Parameters: []*proto.PresetParameter{ + {Name: firstParameterName, Value: secondOptionalParameterValue}, + }, + } + version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses(&preset)) + coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) + template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) + + // When: creating a workspace with the preset and passing the second required parameter via `--rich-parameter-file` + workspaceName := "my-workspace" + tempDir := t.TempDir() + removeTmpDirUntilSuccessAfterTest(t, tempDir) + parameterFile, _ := os.CreateTemp(tempDir, "testParameterFile*.yaml") + _, _ = parameterFile.WriteString( + firstParameterName + ": " + firstOptionalParameterValue + "\n" + + thirdParameterName + ": " + thirdParameterValue) + inv, root := clitest.New(t, "create", workspaceName, "--template", template.Name, "-y", + "--preset", preset.Name, + "--rich-parameter-file", parameterFile.Name()) + clitest.SetupConfig(t, member, root) + pty := ptytest.New(t).Attach(inv) + inv.Stdout = pty.Output() + inv.Stderr = pty.Output() + err := inv.Run() + require.NoError(t, err) + + // Should: display the selected preset as well as its parameter + presetName := fmt.Sprintf("Preset '%s' applied:", preset.Name) + pty.ExpectMatch(presetName) + pty.ExpectMatch(fmt.Sprintf("%s: '%s'", firstParameterName, secondOptionalParameterValue)) + + // Verify if the new workspace uses expected parameters. + ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort) + defer cancel() + + tvPresets, err := client.TemplateVersionPresets(ctx, version.ID) + require.NoError(t, err) + require.Len(t, tvPresets, 1) + + workspaces, err := client.Workspaces(ctx, codersdk.WorkspaceFilter{ + Name: workspaceName, + }) + require.NoError(t, err) + require.Len(t, workspaces.Workspaces, 1) + + // Should: include both parameters, one from the preset and one from the `--rich-parameter-file` flag + workspaceLatestBuild := workspaces.Workspaces[0].LatestBuild + require.Equal(t, version.ID, workspaceLatestBuild.TemplateVersionID) + require.Equal(t, tvPresets[0].ID, *workspaceLatestBuild.TemplateVersionPresetID) + buildParameters, err := client.WorkspaceBuildParameters(ctx, workspaceLatestBuild.ID) + require.NoError(t, err) + require.Len(t, buildParameters, 2) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: firstParameterName, Value: secondOptionalParameterValue}) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: thirdParameterName, Value: thirdParameterValue}) + }) + + // This test verifies that when a preset provides only some parameters, + // and the remaining ones are not provided via flags, + // the CLI prompts the user for input to fill in the missing parameters. + t.Run("PromptsForMissingParametersWhenPresetIsIncomplete", func(t *testing.T) { + t.Parallel() + + client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true}) + owner := coderdtest.CreateFirstUser(t, client) + member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) + + // Given: a template version with a preset that defines one parameter + preset := proto.Preset{ + Name: "preset-test", + Parameters: []*proto.PresetParameter{ + {Name: firstParameterName, Value: secondOptionalParameterValue}, + }, + } + version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses(&preset)) + coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) + template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) + + // When: running the create command with the specified preset + workspaceName := "my-workspace" + inv, root := clitest.New(t, "create", workspaceName, "--template", template.Name, "--preset", preset.Name) + clitest.SetupConfig(t, member, root) + doneChan := make(chan struct{}) + pty := ptytest.New(t).Attach(inv) + go func() { + defer close(doneChan) + err := inv.Run() + assert.NoError(t, err) + }() + + // Should: display the selected preset as well as its parameters + presetName := fmt.Sprintf("Preset '%s' applied:", preset.Name) + pty.ExpectMatch(presetName) + pty.ExpectMatch(fmt.Sprintf("%s: '%s'", firstParameterName, secondOptionalParameterValue)) + + // Should: prompt for the missing parameter + pty.ExpectMatch(thirdParameterDescription) + pty.WriteLine(thirdParameterValue) + pty.ExpectMatch("Confirm create?") + pty.WriteLine("yes") + + <-doneChan + + // Verify if the new workspace uses expected parameters. + ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong) + defer cancel() + + tvPresets, err := client.TemplateVersionPresets(ctx, version.ID) + require.NoError(t, err) + require.Len(t, tvPresets, 1) + + workspaces, err := client.Workspaces(ctx, codersdk.WorkspaceFilter{ + Name: workspaceName, + }) + require.NoError(t, err) + require.Len(t, workspaces.Workspaces, 1) + + // Should: create a workspace using the expected template version and the preset-defined parameters + workspaceLatestBuild := workspaces.Workspaces[0].LatestBuild + require.Equal(t, version.ID, workspaceLatestBuild.TemplateVersionID) + require.Equal(t, tvPresets[0].ID, *workspaceLatestBuild.TemplateVersionPresetID) + buildParameters, err := client.WorkspaceBuildParameters(ctx, workspaceLatestBuild.ID) + require.NoError(t, err) + require.Len(t, buildParameters, 2) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: firstParameterName, Value: secondOptionalParameterValue}) + require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: thirdParameterName, Value: thirdParameterValue}) + }) +} + func TestCreateValidateRichParameters(t *testing.T) { t.Parallel() diff --git a/cli/delete_test.go b/cli/delete_test.go index a48ca98627f65..c01893419f80f 100644 --- a/cli/delete_test.go +++ b/cli/delete_test.go @@ -233,9 +233,6 @@ func TestDelete(t *testing.T) { t.Skip("this test requires postgres") } - clock := quartz.NewMock(t) - ctx := testutil.Context(t, testutil.WaitSuperLong) - // Setup db, pb := dbtestutil.NewDB(t, dbtestutil.WithDumpOnFailure()) client, _ := coderdtest.NewWithProvisionerCloser(t, &coderdtest.Options{ @@ -301,6 +298,9 @@ func TestDelete(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() + clock := quartz.NewMock(t) + ctx := testutil.Context(t, testutil.WaitSuperLong) + // Create one prebuilt workspace (owned by system user) and one normal workspace (owned by a user) // Each workspace is persisted in the DB along with associated workspace jobs and builds. dbPrebuiltWorkspace := setupTestDBWorkspace(t, clock, db, pb, orgID, database.PrebuildsSystemUserID, template.ID, version.ID, preset.ID) diff --git a/cli/exp_mcp.go b/cli/exp_mcp.go index 0a1c9fcbeaf87..d5ea26739085b 100644 --- a/cli/exp_mcp.go +++ b/cli/exp_mcp.go @@ -127,6 +127,7 @@ func (r *RootCmd) mcpConfigureClaudeCode() *serpent.Command { appStatusSlug string testBinaryName string aiAgentAPIURL url.URL + claudeUseBedrock string deprecatedCoderMCPClaudeAPIKey string ) @@ -154,14 +155,15 @@ func (r *RootCmd) mcpConfigureClaudeCode() *serpent.Command { configureClaudeEnv[envAgentURL] = agentClient.SDK.URL.String() configureClaudeEnv[envAgentToken] = agentClient.SDK.SessionToken() } - if claudeAPIKey == "" { - if deprecatedCoderMCPClaudeAPIKey == "" { - cliui.Warnf(inv.Stderr, "CLAUDE_API_KEY is not set.") - } else { - cliui.Warnf(inv.Stderr, "CODER_MCP_CLAUDE_API_KEY is deprecated, use CLAUDE_API_KEY instead") - claudeAPIKey = deprecatedCoderMCPClaudeAPIKey - } + + if deprecatedCoderMCPClaudeAPIKey != "" { + cliui.Warnf(inv.Stderr, "CODER_MCP_CLAUDE_API_KEY is deprecated, use CLAUDE_API_KEY instead") + claudeAPIKey = deprecatedCoderMCPClaudeAPIKey + } + if claudeAPIKey == "" && claudeUseBedrock != "1" { + cliui.Warnf(inv.Stderr, "CLAUDE_API_KEY is not set.") } + if appStatusSlug != "" { configureClaudeEnv[envAppStatusSlug] = appStatusSlug } @@ -280,6 +282,14 @@ func (r *RootCmd) mcpConfigureClaudeCode() *serpent.Command { Value: serpent.StringOf(&testBinaryName), Hidden: true, }, + { + Name: "claude-code-use-bedrock", + Description: "Use Amazon Bedrock.", + Env: "CLAUDE_CODE_USE_BEDROCK", + Flag: "claude-code-use-bedrock", + Value: serpent.StringOf(&claudeUseBedrock), + Hidden: true, + }, }, } return cmd @@ -362,11 +372,19 @@ func (*RootCmd) mcpConfigureCursor() *serpent.Command { } type taskReport struct { - link string - messageID int64 + // link is optional. + link string + // messageID must be set if this update is from a *user* message. A user + // message only happens when interacting via the AI AgentAPI (as opposed to + // interacting with the terminal directly). + messageID *int64 + // selfReported must be set if the update is directly from the AI agent + // (as opposed to the screen watcher). selfReported bool - state codersdk.WorkspaceAppStatusState - summary string + // state must always be set. + state codersdk.WorkspaceAppStatusState + // summary is optional. + summary string } type mcpServer struct { @@ -388,31 +406,48 @@ func (r *RootCmd) mcpServer() *serpent.Command { return &serpent.Command{ Use: "server", Handler: func(inv *serpent.Invocation) error { - // lastUserMessageID is the ID of the last *user* message that we saw. A - // user message only happens when interacting via the AI AgentAPI (as - // opposed to interacting with the terminal directly). - var lastUserMessageID int64 var lastReport taskReport // Create a queue that skips duplicates and preserves summaries. queue := cliutil.NewQueue[taskReport](512).WithPredicate(func(report taskReport) (taskReport, bool) { - // Use "working" status if this is a new user message. If this is not a - // new user message, and the status is "working" and not self-reported - // (meaning it came from the screen watcher), then it means one of two - // things: - // 1. The AI agent is still working, so there is nothing to update. - // 2. The AI agent stopped working, then the user has interacted with - // the terminal directly. For now, we are ignoring these updates. - // This risks missing cases where the user manually submits a new - // prompt and the AI agent becomes active and does not update itself, - // but it avoids spamming useless status updates as the user is - // typing, so the tradeoff is worth it. In the future, if we can - // reliably distinguish between user and AI agent activity, we can - // change this. - if report.messageID > lastUserMessageID { - report.state = codersdk.WorkspaceAppStatusStateWorking - } else if report.state == codersdk.WorkspaceAppStatusStateWorking && !report.selfReported { + // Avoid queuing empty statuses (this would probably indicate a + // developer error) + if report.state == "" { + return report, false + } + // If this is a user message, discard if it is not new. + if report.messageID != nil && lastReport.messageID != nil && + *lastReport.messageID >= *report.messageID { return report, false } + // If this is not a user message, and the status is "working" and not + // self-reported (meaning it came from the screen watcher), then it + // means one of two things: + // + // 1. The AI agent is not working; the user is interacting with the + // terminal directly. + // 2. The AI agent is working. + // + // At the moment, we have no way to tell the difference between these + // two states. In the future, if we can reliably distinguish between + // user and AI agent activity, we can change this. + // + // If this is our first update, we assume it is the AI agent working and + // accept the update. + // + // Otherwise we discard the update. This risks missing cases where the + // user manually submits a new prompt and the AI agent becomes active + // (and does not update itself), but it avoids spamming useless status + // updates as the user is typing, so the tradeoff is worth it. + if report.messageID == nil && + report.state == codersdk.WorkspaceAppStatusStateWorking && + !report.selfReported && lastReport.state != "" { + return report, false + } + // Keep track of the last message ID so we can tell when a message is + // new or if it has been re-emitted. + if report.messageID == nil { + report.messageID = lastReport.messageID + } // Preserve previous message and URI if there was no message. if report.summary == "" { report.summary = lastReport.summary @@ -600,7 +635,8 @@ func (s *mcpServer) startWatcher(ctx context.Context, inv *serpent.Invocation) { case agentapi.EventMessageUpdate: if ev.Role == agentapi.RoleUser { err := s.queue.Push(taskReport{ - messageID: ev.Id, + messageID: &ev.Id, + state: codersdk.WorkspaceAppStatusStateWorking, }) if err != nil { cliui.Warnf(inv.Stderr, "Failed to queue update: %s", err) @@ -650,10 +686,18 @@ func (s *mcpServer) startServer(ctx context.Context, inv *serpent.Invocation, in // Add tool dependencies. toolOpts := []func(*toolsdk.Deps){ toolsdk.WithTaskReporter(func(args toolsdk.ReportTaskArgs) error { + // The agent does not reliably report its status correctly. If AgentAPI + // is enabled, we will always set the status to "working" when we get an + // MCP message, and rely on the screen watcher to eventually catch the + // idle state. + state := codersdk.WorkspaceAppStatusStateWorking + if s.aiAgentAPIClient == nil { + state = codersdk.WorkspaceAppStatusState(args.State) + } return s.queue.Push(taskReport{ link: args.Link, selfReported: true, - state: codersdk.WorkspaceAppStatusState(args.State), + state: state, summary: args.Summary, }) }), diff --git a/cli/exp_mcp_test.go b/cli/exp_mcp_test.go index bcfafb0204874..0a50a41e99ccc 100644 --- a/cli/exp_mcp_test.go +++ b/cli/exp_mcp_test.go @@ -763,220 +763,351 @@ func TestExpMcpReporter(t *testing.T) { <-cmdDone }) - t.Run("OK", func(t *testing.T) { - t.Parallel() + makeStatusEvent := func(status agentapi.AgentStatus) *codersdk.ServerSentEvent { + return &codersdk.ServerSentEvent{ + Type: ServerSentEventTypeStatusChange, + Data: agentapi.EventStatusChange{ + Status: status, + }, + } + } - // Create a test deployment and workspace. - client, db := coderdtest.NewWithDatabase(t, nil) - user := coderdtest.CreateFirstUser(t, client) - client, user2 := coderdtest.CreateAnotherUser(t, client, user.OrganizationID) + makeMessageEvent := func(id int64, role agentapi.ConversationRole) *codersdk.ServerSentEvent { + return &codersdk.ServerSentEvent{ + Type: ServerSentEventTypeMessageUpdate, + Data: agentapi.EventMessageUpdate{ + Id: id, + Role: role, + }, + } + } + + type test struct { + // event simulates an event from the screen watcher. + event *codersdk.ServerSentEvent + // state, summary, and uri simulate a tool call from the AI agent. + state codersdk.WorkspaceAppStatusState + summary string + uri string + expected *codersdk.WorkspaceAppStatus + } - r := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{ - OrganizationID: user.OrganizationID, - OwnerID: user2.ID, - }).WithAgent(func(a []*proto.Agent) []*proto.Agent { - a[0].Apps = []*proto.App{ + runs := []struct { + name string + tests []test + disableAgentAPI bool + }{ + // In this run the AI agent starts with a state change but forgets to update + // that it finished. + { + name: "Active", + tests: []test{ + // First the AI agent updates with a state change. { - Slug: "vscode", + state: codersdk.WorkspaceAppStatusStateWorking, + summary: "doing work", + uri: "https://dev.coder.com", + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateWorking, + Message: "doing work", + URI: "https://dev.coder.com", + }, }, - } - return a - }).Do() - - makeStatusEvent := func(status agentapi.AgentStatus) *codersdk.ServerSentEvent { - return &codersdk.ServerSentEvent{ - Type: ServerSentEventTypeStatusChange, - Data: agentapi.EventStatusChange{ - Status: status, + // Terminal goes quiet but the AI agent forgot the update, and it is + // caught by the screen watcher. Message and URI are preserved. + { + event: makeStatusEvent(agentapi.StatusStable), + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateIdle, + Message: "doing work", + URI: "https://dev.coder.com", + }, }, - } - } - - makeMessageEvent := func(id int64, role agentapi.ConversationRole) *codersdk.ServerSentEvent { - return &codersdk.ServerSentEvent{ - Type: ServerSentEventTypeMessageUpdate, - Data: agentapi.EventMessageUpdate{ - Id: id, - Role: role, + // A stable update now from the watcher should be discarded, as it is a + // duplicate. + { + event: makeStatusEvent(agentapi.StatusStable), }, - } - } - - ctx, cancel := context.WithCancel(testutil.Context(t, testutil.WaitShort)) - - // Mock the AI AgentAPI server. - listening := make(chan func(sse codersdk.ServerSentEvent) error) - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - send, closed, err := httpapi.ServerSentEventSender(w, r) - if err != nil { - httpapi.Write(ctx, w, http.StatusInternalServerError, codersdk.Response{ - Message: "Internal error setting up server-sent events.", - Detail: err.Error(), - }) - return - } - // Send initial message. - send(*makeMessageEvent(0, agentapi.RoleAgent)) - listening <- send - <-closed - })) - t.Cleanup(srv.Close) - aiAgentAPIURL := srv.URL - - // Watch the workspace for changes. - watcher, err := client.WatchWorkspace(ctx, r.Workspace.ID) - require.NoError(t, err) - var lastAppStatus codersdk.WorkspaceAppStatus - nextUpdate := func() codersdk.WorkspaceAppStatus { - for { - select { - case <-ctx.Done(): - require.FailNow(t, "timed out waiting for status update") - case w, ok := <-watcher: - require.True(t, ok, "watch channel closed") - if w.LatestAppStatus != nil && w.LatestAppStatus.ID != lastAppStatus.ID { - lastAppStatus = *w.LatestAppStatus - return lastAppStatus - } - } - } - } - - inv, _ := clitest.New(t, - "exp", "mcp", "server", - // We need the agent credentials, AI AgentAPI url, and a slug for reporting. - "--agent-url", client.URL.String(), - "--agent-token", r.AgentToken, - "--app-status-slug", "vscode", - "--ai-agentapi-url", aiAgentAPIURL, - "--allowed-tools=coder_report_task", - ) - inv = inv.WithContext(ctx) - - pty := ptytest.New(t) - inv.Stdin = pty.Input() - inv.Stdout = pty.Output() - stderr := ptytest.New(t) - inv.Stderr = stderr.Output() - - // Run the MCP server. - cmdDone := make(chan struct{}) - go func() { - defer close(cmdDone) - err := inv.Run() - assert.NoError(t, err) - }() - - // Initialize. - payload := `{"jsonrpc":"2.0","id":1,"method":"initialize"}` - pty.WriteLine(payload) - _ = pty.ReadLine(ctx) // ignore echo - _ = pty.ReadLine(ctx) // ignore init response - - sender := <-listening - - tests := []struct { - // event simulates an event from the screen watcher. - event *codersdk.ServerSentEvent - // state, summary, and uri simulate a tool call from the AI agent. - state codersdk.WorkspaceAppStatusState - summary string - uri string - expected *codersdk.WorkspaceAppStatus - }{ - // First the AI agent updates with a state change. - { - state: codersdk.WorkspaceAppStatusStateWorking, - summary: "doing work", - uri: "https://dev.coder.com", - expected: &codersdk.WorkspaceAppStatus{ - State: codersdk.WorkspaceAppStatusStateWorking, - Message: "doing work", - URI: "https://dev.coder.com", + // Terminal becomes active again according to the screen watcher, but no + // new user message. This could be the AI agent being active again, but + // it could also be the user messing around. We will prefer not updating + // the status so the "working" update here should be skipped. + // + // TODO: How do we test the no-op updates? This update is skipped + // because of the logic mentioned above, but how do we prove this update + // was skipped because of that and not that the next update was skipped + // because it is a duplicate state? We could mock the queue? + { + event: makeStatusEvent(agentapi.StatusRunning), }, - }, - // Terminal goes quiet but the AI agent forgot the update, and it is - // caught by the screen watcher. Message and URI are preserved. - { - event: makeStatusEvent(agentapi.StatusStable), - expected: &codersdk.WorkspaceAppStatus{ - State: codersdk.WorkspaceAppStatusStateIdle, - Message: "doing work", - URI: "https://dev.coder.com", + // Agent messages are ignored. + { + event: makeMessageEvent(0, agentapi.RoleAgent), }, - }, - // A completed update at this point from the watcher should be discarded. - { - event: makeStatusEvent(agentapi.StatusStable), - }, - // Terminal becomes active again according to the screen watcher, but no - // new user message. This could be the AI agent being active again, but - // it could also be the user messing around. We will prefer not updating - // the status so the "working" update here should be skipped. - { - event: makeStatusEvent(agentapi.StatusRunning), - }, - // Agent messages are ignored. - { - event: makeMessageEvent(1, agentapi.RoleAgent), - }, - // AI agent reports that it failed and URI is blank. - { - state: codersdk.WorkspaceAppStatusStateFailure, - summary: "oops", - expected: &codersdk.WorkspaceAppStatus{ - State: codersdk.WorkspaceAppStatusStateFailure, - Message: "oops", - URI: "", + // The watcher reports the screen is active again... + { + event: makeStatusEvent(agentapi.StatusRunning), + }, + // ... but this time we have a new user message so we know there is AI + // agent activity. This time the "working" update will not be skipped. + { + event: makeMessageEvent(1, agentapi.RoleUser), + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateWorking, + Message: "doing work", + URI: "https://dev.coder.com", + }, + }, + // Watcher reports stable again. + { + event: makeStatusEvent(agentapi.StatusStable), + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateIdle, + Message: "doing work", + URI: "https://dev.coder.com", + }, }, }, - // The watcher reports the screen is active again... - { - event: makeStatusEvent(agentapi.StatusRunning), + }, + // In this run the AI agent never sends any state changes. + { + name: "Inactive", + tests: []test{ + // The "working" status from the watcher should be accepted, even though + // there is no new user message, because it is the first update. + { + event: makeStatusEvent(agentapi.StatusRunning), + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateWorking, + Message: "", + URI: "", + }, + }, + // Stable update should be accepted. + { + event: makeStatusEvent(agentapi.StatusStable), + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateIdle, + Message: "", + URI: "", + }, + }, + // Zero ID should be accepted. + { + event: makeMessageEvent(0, agentapi.RoleUser), + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateWorking, + Message: "", + URI: "", + }, + }, + // Stable again. + { + event: makeStatusEvent(agentapi.StatusStable), + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateIdle, + Message: "", + URI: "", + }, + }, + // Next ID. + { + event: makeMessageEvent(1, agentapi.RoleUser), + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateWorking, + Message: "", + URI: "", + }, + }, }, - // ... but this time we have a new user message so we know there is AI - // agent activity. This time the "working" update will not be skipped. - { - event: makeMessageEvent(2, agentapi.RoleUser), - expected: &codersdk.WorkspaceAppStatus{ - State: codersdk.WorkspaceAppStatusStateWorking, - Message: "oops", - URI: "", + }, + // We ignore the state from the agent and assume "working". + { + name: "IgnoreAgentState", + // AI agent reports that it is finished but the summary says it is doing + // work. + tests: []test{ + { + state: codersdk.WorkspaceAppStatusStateIdle, + summary: "doing work", + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateWorking, + Message: "doing work", + }, + }, + // AI agent reports finished again, with a matching summary. We still + // assume it is working. + { + state: codersdk.WorkspaceAppStatusStateIdle, + summary: "finished", + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateWorking, + Message: "finished", + }, + }, + // Once the watcher reports stable, then we record idle. + { + event: makeStatusEvent(agentapi.StatusStable), + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateIdle, + Message: "finished", + }, }, }, - // Watcher reports stable again. - { - event: makeStatusEvent(agentapi.StatusStable), - expected: &codersdk.WorkspaceAppStatus{ - State: codersdk.WorkspaceAppStatusStateIdle, - Message: "oops", - URI: "", + }, + // When AgentAPI is not being used, we accept agent state updates as-is. + { + name: "KeepAgentState", + tests: []test{ + { + state: codersdk.WorkspaceAppStatusStateWorking, + summary: "doing work", + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateWorking, + Message: "doing work", + }, + }, + { + state: codersdk.WorkspaceAppStatusStateIdle, + summary: "finished", + expected: &codersdk.WorkspaceAppStatus{ + State: codersdk.WorkspaceAppStatusStateIdle, + Message: "finished", + }, }, }, - } - for _, test := range tests { - if test.event != nil { - err := sender(*test.event) - require.NoError(t, err) - } else { - // Call the tool and ensure it works. - payload := fmt.Sprintf(`{"jsonrpc":"2.0","id":3,"method":"tools/call", "params": {"name": "coder_report_task", "arguments": {"state": %q, "summary": %q, "link": %q}}}`, test.state, test.summary, test.uri) - pty.WriteLine(payload) - _ = pty.ReadLine(ctx) // ignore echo - output := pty.ReadLine(ctx) - require.NotEmpty(t, output, "did not receive a response from coder_report_task") - // Ensure it is valid JSON. - _, err = json.Marshal(output) - require.NoError(t, err, "did not receive valid JSON from coder_report_task") + disableAgentAPI: true, + }, + } + + for _, run := range runs { + run := run + t.Run(run.name, func(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(testutil.Context(t, testutil.WaitShort)) + + // Create a test deployment and workspace. + client, db := coderdtest.NewWithDatabase(t, nil) + user := coderdtest.CreateFirstUser(t, client) + client, user2 := coderdtest.CreateAnotherUser(t, client, user.OrganizationID) + + r := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{ + OrganizationID: user.OrganizationID, + OwnerID: user2.ID, + }).WithAgent(func(a []*proto.Agent) []*proto.Agent { + a[0].Apps = []*proto.App{ + { + Slug: "vscode", + }, + } + return a + }).Do() + + // Watch the workspace for changes. + watcher, err := client.WatchWorkspace(ctx, r.Workspace.ID) + require.NoError(t, err) + var lastAppStatus codersdk.WorkspaceAppStatus + nextUpdate := func() codersdk.WorkspaceAppStatus { + for { + select { + case <-ctx.Done(): + require.FailNow(t, "timed out waiting for status update") + case w, ok := <-watcher: + require.True(t, ok, "watch channel closed") + if w.LatestAppStatus != nil && w.LatestAppStatus.ID != lastAppStatus.ID { + t.Logf("Got status update: %s > %s", lastAppStatus.State, w.LatestAppStatus.State) + lastAppStatus = *w.LatestAppStatus + return lastAppStatus + } + } + } } - if test.expected != nil { - got := nextUpdate() - require.Equal(t, got.State, test.expected.State) - require.Equal(t, got.Message, test.expected.Message) - require.Equal(t, got.URI, test.expected.URI) + + args := []string{ + "exp", "mcp", "server", + // We need the agent credentials, AI AgentAPI url (if not + // disabled), and a slug for reporting. + "--agent-url", client.URL.String(), + "--agent-token", r.AgentToken, + "--app-status-slug", "vscode", + "--allowed-tools=coder_report_task", } - } - cancel() - <-cmdDone - }) + + // Mock the AI AgentAPI server. + listening := make(chan func(sse codersdk.ServerSentEvent) error) + if !run.disableAgentAPI { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + send, closed, err := httpapi.ServerSentEventSender(w, r) + if err != nil { + httpapi.Write(ctx, w, http.StatusInternalServerError, codersdk.Response{ + Message: "Internal error setting up server-sent events.", + Detail: err.Error(), + }) + return + } + // Send initial message. + send(*makeMessageEvent(0, agentapi.RoleAgent)) + listening <- send + <-closed + })) + t.Cleanup(srv.Close) + aiAgentAPIURL := srv.URL + args = append(args, "--ai-agentapi-url", aiAgentAPIURL) + } + + inv, _ := clitest.New(t, args...) + inv = inv.WithContext(ctx) + + pty := ptytest.New(t) + inv.Stdin = pty.Input() + inv.Stdout = pty.Output() + stderr := ptytest.New(t) + inv.Stderr = stderr.Output() + + // Run the MCP server. + cmdDone := make(chan struct{}) + go func() { + defer close(cmdDone) + err := inv.Run() + assert.NoError(t, err) + }() + + // Initialize. + payload := `{"jsonrpc":"2.0","id":1,"method":"initialize"}` + pty.WriteLine(payload) + _ = pty.ReadLine(ctx) // ignore echo + _ = pty.ReadLine(ctx) // ignore init response + + var sender func(sse codersdk.ServerSentEvent) error + if !run.disableAgentAPI { + sender = <-listening + } + + for _, test := range run.tests { + if test.event != nil { + err := sender(*test.event) + require.NoError(t, err) + } else { + // Call the tool and ensure it works. + payload := fmt.Sprintf(`{"jsonrpc":"2.0","id":3,"method":"tools/call", "params": {"name": "coder_report_task", "arguments": {"state": %q, "summary": %q, "link": %q}}}`, test.state, test.summary, test.uri) + pty.WriteLine(payload) + _ = pty.ReadLine(ctx) // ignore echo + output := pty.ReadLine(ctx) + require.NotEmpty(t, output, "did not receive a response from coder_report_task") + // Ensure it is valid JSON. + _, err = json.Marshal(output) + require.NoError(t, err, "did not receive valid JSON from coder_report_task") + } + if test.expected != nil { + got := nextUpdate() + require.Equal(t, got.State, test.expected.State) + require.Equal(t, got.Message, test.expected.Message) + require.Equal(t, got.URI, test.expected.URI) + } + } + cancel() + <-cmdDone + }) + } } diff --git a/cli/exp_rpty.go b/cli/exp_rpty.go index 48074c7ef5fb9..70154c57ea9bc 100644 --- a/cli/exp_rpty.go +++ b/cli/exp_rpty.go @@ -97,7 +97,7 @@ func handleRPTY(inv *serpent.Invocation, client *codersdk.Client, args handleRPT reconnectID = uuid.New() } - ws, agt, err := getWorkspaceAndAgent(ctx, inv, client, true, args.NamedWorkspace) + ws, agt, _, err := getWorkspaceAndAgent(ctx, inv, client, true, args.NamedWorkspace) if err != nil { return err } diff --git a/cli/exp_rpty_test.go b/cli/exp_rpty_test.go index 213764bb40113..c7a0c47d18908 100644 --- a/cli/exp_rpty_test.go +++ b/cli/exp_rpty_test.go @@ -118,6 +118,7 @@ func TestExpRpty(t *testing.T) { _ = agenttest.New(t, client.URL, agentToken, func(o *agent.Options) { o.Devcontainers = true o.DevcontainerAPIOptions = append(o.DevcontainerAPIOptions, + agentcontainers.WithProjectDiscovery(false), agentcontainers.WithContainerLabelIncludeFilter(wantLabel, "true"), ) }) diff --git a/cli/open.go b/cli/open.go index ff950b552a853..cc21ea863430d 100644 --- a/cli/open.go +++ b/cli/open.go @@ -11,7 +11,9 @@ import ( "runtime" "slices" "strings" + "time" + "github.com/google/uuid" "github.com/skratchdot/open-golang/open" "golang.org/x/xerrors" @@ -42,7 +44,6 @@ func (r *RootCmd) openVSCode() *serpent.Command { generateToken bool testOpenError bool appearanceConfig codersdk.AppearanceConfig - containerName string ) client := new(codersdk.Client) @@ -71,7 +72,7 @@ func (r *RootCmd) openVSCode() *serpent.Command { // need to wait for the agent to start. workspaceQuery := inv.Args[0] autostart := true - workspace, workspaceAgent, err := getWorkspaceAndAgent(ctx, inv, client, autostart, workspaceQuery) + workspace, workspaceAgent, otherWorkspaceAgents, err := getWorkspaceAndAgent(ctx, inv, client, autostart, workspaceQuery) if err != nil { return xerrors.Errorf("get workspace and agent: %w", err) } @@ -79,6 +80,70 @@ func (r *RootCmd) openVSCode() *serpent.Command { workspaceName := workspace.Name + "." + workspaceAgent.Name insideThisWorkspace := insideAWorkspace && inWorkspaceName == workspaceName + // To properly work with devcontainers, VS Code has to connect to + // parent workspace agent. It will then proceed to enter the + // container given the correct parameters. There is inherently no + // dependency on the devcontainer agent in this scenario, but + // relying on it simplifies the logic and ensures the devcontainer + // is ready. To eliminate the dependency we would need to know that + // a sub-agent that hasn't been created yet may be a devcontainer, + // and thus will be created at a later time as well as expose the + // container folder on the API response. + var parentWorkspaceAgent codersdk.WorkspaceAgent + var devcontainer codersdk.WorkspaceAgentDevcontainer + if workspaceAgent.ParentID.Valid { + // This is likely a devcontainer agent, so we need to find the + // parent workspace agent as well as the devcontainer. + for _, otherAgent := range otherWorkspaceAgents { + if otherAgent.ID == workspaceAgent.ParentID.UUID { + parentWorkspaceAgent = otherAgent + break + } + } + if parentWorkspaceAgent.ID == uuid.Nil { + return xerrors.Errorf("parent workspace agent %s not found", workspaceAgent.ParentID.UUID) + } + + printedWaiting := false + for { + resp, err := client.WorkspaceAgentListContainers(ctx, parentWorkspaceAgent.ID, nil) + if err != nil { + return xerrors.Errorf("list parent workspace agent containers: %w", err) + } + + for _, dc := range resp.Devcontainers { + if dc.Agent.ID == workspaceAgent.ID { + devcontainer = dc + break + } + } + if devcontainer.ID == uuid.Nil { + cliui.Warnf(inv.Stderr, "Devcontainer %q not found, opening as a regular workspace...", workspaceAgent.Name) + parentWorkspaceAgent = codersdk.WorkspaceAgent{} // Reset to empty, so we don't use it later. + break + } + + // Precondition, the devcontainer must be running to enter + // it. Once running, devcontainer.Container will be set. + if devcontainer.Status == codersdk.WorkspaceAgentDevcontainerStatusRunning { + break + } + if devcontainer.Status != codersdk.WorkspaceAgentDevcontainerStatusStarting { + return xerrors.Errorf("devcontainer %q is in unexpected status %q, expected %q or %q", + devcontainer.Name, devcontainer.Status, + codersdk.WorkspaceAgentDevcontainerStatusRunning, + codersdk.WorkspaceAgentDevcontainerStatusStarting, + ) + } + + if !printedWaiting { + _, _ = fmt.Fprintf(inv.Stderr, "Waiting for devcontainer %q status to change from %q to %q...\n", devcontainer.Name, devcontainer.Status, codersdk.WorkspaceAgentDevcontainerStatusRunning) + printedWaiting = true + } + time.Sleep(5 * time.Second) // Wait a bit before retrying. + } + } + if !insideThisWorkspace { // Wait for the agent to connect, we don't care about readiness // otherwise (e.g. wait). @@ -99,6 +164,9 @@ func (r *RootCmd) openVSCode() *serpent.Command { // the created state, so we need to wait for that to happen. // However, if no directory is set, the expanded directory will // not be set either. + // + // Note that this is irrelevant for devcontainer sub agents, as + // they always have a directory set. if workspaceAgent.Directory != "" { workspace, workspaceAgent, err = waitForAgentCond(ctx, client, workspace, workspaceAgent, func(_ codersdk.WorkspaceAgent) bool { return workspaceAgent.LifecycleState != codersdk.WorkspaceAgentLifecycleCreated @@ -114,41 +182,6 @@ func (r *RootCmd) openVSCode() *serpent.Command { directory = inv.Args[1] } - if containerName != "" { - containers, err := client.WorkspaceAgentListContainers(ctx, workspaceAgent.ID, map[string]string{"devcontainer.local_folder": ""}) - if err != nil { - return xerrors.Errorf("list workspace agent containers: %w", err) - } - - var foundContainer bool - - for _, container := range containers.Containers { - if container.FriendlyName != containerName { - continue - } - - foundContainer = true - - if directory == "" { - localFolder, ok := container.Labels["devcontainer.local_folder"] - if !ok { - return xerrors.New("container missing `devcontainer.local_folder` label") - } - - directory, ok = container.Volumes[localFolder] - if !ok { - return xerrors.New("container missing volume for `devcontainer.local_folder`") - } - } - - break - } - - if !foundContainer { - return xerrors.New("no container found") - } - } - directory, err = resolveAgentAbsPath(workspaceAgent.ExpandedDirectory, directory, workspaceAgent.OperatingSystem, insideThisWorkspace) if err != nil { return xerrors.Errorf("resolve agent path: %w", err) @@ -174,14 +207,16 @@ func (r *RootCmd) openVSCode() *serpent.Command { u *url.URL qp url.Values ) - if containerName != "" { + if devcontainer.ID != uuid.Nil { u, qp = buildVSCodeWorkspaceDevContainerLink( token, client.URL.String(), workspace, - workspaceAgent, - containerName, + parentWorkspaceAgent, + devcontainer.Container.FriendlyName, directory, + devcontainer.WorkspaceFolder, + devcontainer.ConfigPath, ) } else { u, qp = buildVSCodeWorkspaceLink( @@ -247,13 +282,6 @@ func (r *RootCmd) openVSCode() *serpent.Command { ), Value: serpent.BoolOf(&generateToken), }, - { - Flag: "container", - FlagShorthand: "c", - Description: "Container name to connect to in the workspace.", - Value: serpent.StringOf(&containerName), - Hidden: true, // Hidden until this features is at least in beta. - }, { Flag: "test.open-error", Description: "Don't run the open command.", @@ -288,7 +316,7 @@ func (r *RootCmd) openApp() *serpent.Command { } workspaceName := inv.Args[0] - ws, agt, err := getWorkspaceAndAgent(ctx, inv, client, false, workspaceName) + ws, agt, _, err := getWorkspaceAndAgent(ctx, inv, client, false, workspaceName) if err != nil { var sdkErr *codersdk.Error if errors.As(err, &sdkErr) && sdkErr.StatusCode() == http.StatusNotFound { @@ -430,8 +458,14 @@ func buildVSCodeWorkspaceDevContainerLink( workspaceAgent codersdk.WorkspaceAgent, containerName string, containerFolder string, + localWorkspaceFolder string, + localConfigFile string, ) (*url.URL, url.Values) { containerFolder = filepath.ToSlash(containerFolder) + localWorkspaceFolder = filepath.ToSlash(localWorkspaceFolder) + if localConfigFile != "" { + localConfigFile = filepath.ToSlash(localConfigFile) + } qp := url.Values{} qp.Add("url", clientURL) @@ -440,6 +474,8 @@ func buildVSCodeWorkspaceDevContainerLink( qp.Add("agent", workspaceAgent.Name) qp.Add("devContainerName", containerName) qp.Add("devContainerFolder", containerFolder) + qp.Add("localWorkspaceFolder", localWorkspaceFolder) + qp.Add("localConfigFile", localConfigFile) if token != "" { qp.Add("token", token) @@ -469,7 +505,7 @@ func waitForAgentCond(ctx context.Context, client *codersdk.Client, workspace co } for workspace = range wc { - workspaceAgent, err = getWorkspaceAgent(workspace, workspaceAgent.Name) + workspaceAgent, _, err = getWorkspaceAgent(workspace, workspaceAgent.Name) if err != nil { return workspace, workspaceAgent, xerrors.Errorf("get workspace agent: %w", err) } diff --git a/cli/open_test.go b/cli/open_test.go index b76b603d35b1e..688fc24b5e84d 100644 --- a/cli/open_test.go +++ b/cli/open_test.go @@ -1,8 +1,10 @@ package cli_test import ( + "context" "net/url" "os" + "path" "path/filepath" "runtime" "strings" @@ -11,11 +13,11 @@ import ( "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "go.uber.org/mock/gomock" + "golang.org/x/xerrors" "github.com/coder/coder/v2/agent" "github.com/coder/coder/v2/agent/agentcontainers" - "github.com/coder/coder/v2/agent/agentcontainers/acmock" + "github.com/coder/coder/v2/agent/agentcontainers/watcher" "github.com/coder/coder/v2/agent/agenttest" "github.com/coder/coder/v2/cli/clitest" "github.com/coder/coder/v2/coderd/coderdtest" @@ -289,238 +291,146 @@ func TestOpenVSCode_NoAgentDirectory(t *testing.T) { } } -func TestOpenVSCodeDevContainer(t *testing.T) { - t.Parallel() +type fakeContainerCLI struct { + resp codersdk.WorkspaceAgentListContainersResponse +} - if runtime.GOOS != "linux" { - t.Skip("DevContainers are only supported for agents on Linux") - } +func (f *fakeContainerCLI) List(ctx context.Context) (codersdk.WorkspaceAgentListContainersResponse, error) { + return f.resp, nil +} - agentName := "agent1" - agentDir, err := filepath.Abs(filepath.FromSlash("/tmp")) - require.NoError(t, err) +func (*fakeContainerCLI) DetectArchitecture(ctx context.Context, containerID string) (string, error) { + return runtime.GOARCH, nil +} - containerName := testutil.GetRandomName(t) - containerFolder := "/workspace/coder" +func (*fakeContainerCLI) Copy(ctx context.Context, containerID, src, dst string) error { + return nil +} - ctrl := gomock.NewController(t) - mccli := acmock.NewMockContainerCLI(ctrl) - mccli.EXPECT().List(gomock.Any()).Return( - codersdk.WorkspaceAgentListContainersResponse{ - Containers: []codersdk.WorkspaceAgentContainer{ - { - ID: uuid.NewString(), - CreatedAt: dbtime.Now(), - FriendlyName: containerName, - Image: "busybox:latest", - Labels: map[string]string{ - "devcontainer.local_folder": "/home/coder/coder", - }, - Running: true, - Status: "running", - Volumes: map[string]string{ - "/home/coder/coder": containerFolder, - }, - }, - }, - }, nil, - ).AnyTimes() +func (*fakeContainerCLI) ExecAs(ctx context.Context, containerID, user string, args ...string) ([]byte, error) { + return nil, nil +} - client, workspace, agentToken := setupWorkspaceForAgent(t, func(agents []*proto.Agent) []*proto.Agent { - agents[0].Directory = agentDir - agents[0].Name = agentName - agents[0].OperatingSystem = runtime.GOOS - return agents - }) +type fakeDevcontainerCLI struct { + config agentcontainers.DevcontainerConfig + execAgent func(ctx context.Context, token string) error +} - _ = agenttest.New(t, client.URL, agentToken, func(o *agent.Options) { - o.Devcontainers = true - o.DevcontainerAPIOptions = append(o.DevcontainerAPIOptions, - agentcontainers.WithContainerCLI(mccli), - agentcontainers.WithContainerLabelIncludeFilter("this.label.does.not.exist.ignore.devcontainers", "true"), - ) - }) - _ = coderdtest.NewWorkspaceAgentWaiter(t, client, workspace.ID).Wait() +func (f *fakeDevcontainerCLI) ReadConfig(ctx context.Context, workspaceFolder, configFile string, env []string, opts ...agentcontainers.DevcontainerCLIReadConfigOptions) (agentcontainers.DevcontainerConfig, error) { + return f.config, nil +} - insideWorkspaceEnv := map[string]string{ - "CODER": "true", - "CODER_WORKSPACE_NAME": workspace.Name, - "CODER_WORKSPACE_AGENT_NAME": agentName, +func (f *fakeDevcontainerCLI) Exec(ctx context.Context, workspaceFolder, configFile string, name string, args []string, opts ...agentcontainers.DevcontainerCLIExecOptions) error { + var opt agentcontainers.DevcontainerCLIExecConfig + for _, o := range opts { + o(&opt) } - - wd, err := os.Getwd() - require.NoError(t, err) - - tests := []struct { - name string - env map[string]string - args []string - wantDir string - wantError bool - wantToken bool - }{ - { - name: "nonexistent container", - args: []string{"--test.open-error", workspace.Name, "--container", containerName + "bad"}, - wantError: true, - }, - { - name: "ok", - args: []string{"--test.open-error", workspace.Name, "--container", containerName}, - wantDir: containerFolder, - wantError: false, - }, - { - name: "ok with absolute path", - args: []string{"--test.open-error", workspace.Name, "--container", containerName, containerFolder}, - wantDir: containerFolder, - wantError: false, - }, - { - name: "ok with relative path", - args: []string{"--test.open-error", workspace.Name, "--container", containerName, "my/relative/path"}, - wantDir: filepath.Join(agentDir, filepath.FromSlash("my/relative/path")), - wantError: false, - }, - { - name: "ok with token", - args: []string{"--test.open-error", workspace.Name, "--container", containerName, "--generate-token"}, - wantDir: containerFolder, - wantError: false, - wantToken: true, - }, - // Inside workspace, does not require --test.open-error - { - name: "ok inside workspace", - env: insideWorkspaceEnv, - args: []string{workspace.Name, "--container", containerName}, - wantDir: containerFolder, - }, - { - name: "ok inside workspace relative path", - env: insideWorkspaceEnv, - args: []string{workspace.Name, "--container", containerName, "foo"}, - wantDir: filepath.Join(wd, "foo"), - }, - { - name: "ok inside workspace token", - env: insideWorkspaceEnv, - args: []string{workspace.Name, "--container", containerName, "--generate-token"}, - wantDir: containerFolder, - wantToken: true, - }, + var token string + for _, arg := range opt.Args { + if strings.HasPrefix(arg, "CODER_AGENT_TOKEN=") { + token = strings.TrimPrefix(arg, "CODER_AGENT_TOKEN=") + break + } } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - - inv, root := clitest.New(t, append([]string{"open", "vscode"}, tt.args...)...) - clitest.SetupConfig(t, client, root) - - pty := ptytest.New(t) - inv.Stdin = pty.Input() - inv.Stdout = pty.Output() - - ctx := testutil.Context(t, testutil.WaitLong) - inv = inv.WithContext(ctx) - - for k, v := range tt.env { - inv.Environ.Set(k, v) - } - - w := clitest.StartWithWaiter(t, inv) - - if tt.wantError { - w.RequireError() - return - } - - me, err := client.User(ctx, codersdk.Me) - require.NoError(t, err) - - line := pty.ReadLine(ctx) - u, err := url.ParseRequestURI(line) - require.NoError(t, err, "line: %q", line) - - qp := u.Query() - assert.Equal(t, client.URL.String(), qp.Get("url")) - assert.Equal(t, me.Username, qp.Get("owner")) - assert.Equal(t, workspace.Name, qp.Get("workspace")) - assert.Equal(t, agentName, qp.Get("agent")) - assert.Equal(t, containerName, qp.Get("devContainerName")) - - if tt.wantDir != "" { - assert.Equal(t, tt.wantDir, qp.Get("devContainerFolder")) - } else { - assert.Equal(t, containerFolder, qp.Get("devContainerFolder")) - } - - if tt.wantToken { - assert.NotEmpty(t, qp.Get("token")) - } else { - assert.Empty(t, qp.Get("token")) - } - - w.RequireSuccess() - }) + if token == "" { + return xerrors.New("no agent token provided in args") + } + if f.execAgent == nil { + return nil } + return f.execAgent(ctx, token) +} + +func (*fakeDevcontainerCLI) Up(ctx context.Context, workspaceFolder, configFile string, opts ...agentcontainers.DevcontainerCLIUpOptions) (string, error) { + return "", nil } -func TestOpenVSCodeDevContainer_NoAgentDirectory(t *testing.T) { +func TestOpenVSCodeDevContainer(t *testing.T) { t.Parallel() if runtime.GOOS != "linux" { t.Skip("DevContainers are only supported for agents on Linux") } - agentName := "agent1" + parentAgentName := "agent1" + devcontainerID := uuid.New() + devcontainerName := "wilson" + workspaceFolder := "/home/coder/wilson" + configFile := path.Join(workspaceFolder, ".devcontainer", "devcontainer.json") + + containerID := uuid.NewString() containerName := testutil.GetRandomName(t) - containerFolder := "/workspace/coder" + containerFolder := "/workspaces/wilson" + + client, workspace, agentToken := setupWorkspaceForAgent(t, func(agents []*proto.Agent) []*proto.Agent { + agents[0].Name = parentAgentName + agents[0].OperatingSystem = runtime.GOOS + return agents + }) - ctrl := gomock.NewController(t) - mccli := acmock.NewMockContainerCLI(ctrl) - mccli.EXPECT().List(gomock.Any()).Return( - codersdk.WorkspaceAgentListContainersResponse{ + fCCLI := &fakeContainerCLI{ + resp: codersdk.WorkspaceAgentListContainersResponse{ Containers: []codersdk.WorkspaceAgentContainer{ { - ID: uuid.NewString(), + ID: containerID, CreatedAt: dbtime.Now(), FriendlyName: containerName, Image: "busybox:latest", Labels: map[string]string{ - "devcontainer.local_folder": "/home/coder/coder", + agentcontainers.DevcontainerLocalFolderLabel: workspaceFolder, + agentcontainers.DevcontainerConfigFileLabel: configFile, + agentcontainers.DevcontainerIsTestRunLabel: "true", + "coder.test": t.Name(), }, Running: true, Status: "running", - Volumes: map[string]string{ - "/home/coder/coder": containerFolder, - }, }, }, - }, nil, - ).AnyTimes() - - client, workspace, agentToken := setupWorkspaceForAgent(t, func(agents []*proto.Agent) []*proto.Agent { - agents[0].Name = agentName - agents[0].OperatingSystem = runtime.GOOS - return agents - }) + }, + } + fDCCLI := &fakeDevcontainerCLI{ + config: agentcontainers.DevcontainerConfig{ + Workspace: agentcontainers.DevcontainerWorkspace{ + WorkspaceFolder: containerFolder, + }, + }, + execAgent: func(ctx context.Context, token string) error { + t.Logf("Starting devcontainer subagent with token: %s", token) + _ = agenttest.New(t, client.URL, token) + <-ctx.Done() + return ctx.Err() + }, + } _ = agenttest.New(t, client.URL, agentToken, func(o *agent.Options) { o.Devcontainers = true o.DevcontainerAPIOptions = append(o.DevcontainerAPIOptions, - agentcontainers.WithContainerCLI(mccli), - agentcontainers.WithContainerLabelIncludeFilter("this.label.does.not.exist.ignore.devcontainers", "true"), + agentcontainers.WithProjectDiscovery(false), + agentcontainers.WithContainerCLI(fCCLI), + agentcontainers.WithDevcontainerCLI(fDCCLI), + agentcontainers.WithWatcher(watcher.NewNoop()), + agentcontainers.WithDevcontainers( + []codersdk.WorkspaceAgentDevcontainer{{ + ID: devcontainerID, + Name: devcontainerName, + WorkspaceFolder: workspaceFolder, + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + }}, + []codersdk.WorkspaceAgentScript{{ + ID: devcontainerID, + LogSourceID: uuid.New(), + }}, + ), + agentcontainers.WithContainerLabelIncludeFilter("coder.test", t.Name()), ) }) - _ = coderdtest.NewWorkspaceAgentWaiter(t, client, workspace.ID).Wait() + coderdtest.NewWorkspaceAgentWaiter(t, client, workspace.ID).AgentNames([]string{parentAgentName, devcontainerName}).Wait() insideWorkspaceEnv := map[string]string{ "CODER": "true", "CODER_WORKSPACE_NAME": workspace.Name, - "CODER_WORKSPACE_AGENT_NAME": agentName, + "CODER_WORKSPACE_AGENT_NAME": devcontainerName, } wd, err := os.Getwd() @@ -535,41 +445,48 @@ func TestOpenVSCodeDevContainer_NoAgentDirectory(t *testing.T) { wantToken bool }{ { - name: "ok", - args: []string{"--test.open-error", workspace.Name, "--container", containerName}, + name: "nonexistent container", + args: []string{"--test.open-error", workspace.Name + "." + devcontainerName + "bad"}, + wantError: true, }, { - name: "no agent dir error relative path", - args: []string{"--test.open-error", workspace.Name, "--container", containerName, "my/relative/path"}, - wantDir: filepath.FromSlash("my/relative/path"), - wantError: true, + name: "ok", + args: []string{"--test.open-error", workspace.Name + "." + devcontainerName}, + wantError: false, }, { - name: "ok with absolute path", - args: []string{"--test.open-error", workspace.Name, "--container", containerName, "/home/coder"}, - wantDir: "/home/coder", + name: "ok with absolute path", + args: []string{"--test.open-error", workspace.Name + "." + devcontainerName, containerFolder}, + wantError: false, + }, + { + name: "ok with relative path", + args: []string{"--test.open-error", workspace.Name + "." + devcontainerName, "my/relative/path"}, + wantDir: path.Join(containerFolder, "my/relative/path"), + wantError: false, }, { name: "ok with token", - args: []string{"--test.open-error", workspace.Name, "--container", containerName, "--generate-token"}, + args: []string{"--test.open-error", workspace.Name + "." + devcontainerName, "--generate-token"}, + wantError: false, wantToken: true, }, // Inside workspace, does not require --test.open-error { name: "ok inside workspace", env: insideWorkspaceEnv, - args: []string{workspace.Name, "--container", containerName}, + args: []string{workspace.Name + "." + devcontainerName}, }, { name: "ok inside workspace relative path", env: insideWorkspaceEnv, - args: []string{workspace.Name, "--container", containerName, "foo"}, + args: []string{workspace.Name + "." + devcontainerName, "foo"}, wantDir: filepath.Join(wd, "foo"), }, { name: "ok inside workspace token", env: insideWorkspaceEnv, - args: []string{workspace.Name, "--container", containerName, "--generate-token"}, + args: []string{workspace.Name + "." + devcontainerName, "--generate-token"}, wantToken: true, }, } @@ -610,8 +527,10 @@ func TestOpenVSCodeDevContainer_NoAgentDirectory(t *testing.T) { assert.Equal(t, client.URL.String(), qp.Get("url")) assert.Equal(t, me.Username, qp.Get("owner")) assert.Equal(t, workspace.Name, qp.Get("workspace")) - assert.Equal(t, agentName, qp.Get("agent")) + assert.Equal(t, parentAgentName, qp.Get("agent")) assert.Equal(t, containerName, qp.Get("devContainerName")) + assert.Equal(t, workspaceFolder, qp.Get("localWorkspaceFolder")) + assert.Equal(t, configFile, qp.Get("localConfigFile")) if tt.wantDir != "" { assert.Equal(t, tt.wantDir, qp.Get("devContainerFolder")) diff --git a/cli/organizationroles.go b/cli/organizationroles.go index 4d68ab02ae78d..3651baea88d2f 100644 --- a/cli/organizationroles.go +++ b/cli/organizationroles.go @@ -435,7 +435,6 @@ func applyOrgResourceActions(role *codersdk.Role, resource string, actions []str // Construct new site perms with only new perms for the resource keep := make([]codersdk.Permission, 0) for _, perm := range role.OrganizationPermissions { - perm := perm if string(perm.ResourceType) != resource { keep = append(keep, perm) } diff --git a/cli/organizationsettings.go b/cli/organizationsettings.go index 920ae41ebe1fc..391a4f72e27fd 100644 --- a/cli/organizationsettings.go +++ b/cli/organizationsettings.go @@ -116,7 +116,6 @@ func (r *RootCmd) setOrganizationSettings(orgContext *OrganizationContext, setti } for _, set := range settings { - set := set patch := set.Patch cmd.Children = append(cmd.Children, &serpent.Command{ Use: set.Name, @@ -192,7 +191,6 @@ func (r *RootCmd) printOrganizationSetting(orgContext *OrganizationContext, sett } for _, set := range settings { - set := set fetch := set.Fetch cmd.Children = append(cmd.Children, &serpent.Command{ Use: set.Name, diff --git a/cli/parameter.go b/cli/parameter.go index 02ff4e11f63e4..2b56c364faf23 100644 --- a/cli/parameter.go +++ b/cli/parameter.go @@ -100,6 +100,14 @@ func (wpf *workspaceParameterFlags) alwaysPrompt() serpent.Option { } } +func presetParameterAsWorkspaceBuildParameters(presetParameters []codersdk.PresetParameter) []codersdk.WorkspaceBuildParameter { + var params []codersdk.WorkspaceBuildParameter + for _, parameter := range presetParameters { + params = append(params, codersdk.WorkspaceBuildParameter(parameter)) + } + return params +} + func asWorkspaceBuildParameters(nameValuePairs []string) ([]codersdk.WorkspaceBuildParameter, error) { var params []codersdk.WorkspaceBuildParameter for _, nameValue := range nameValuePairs { @@ -145,9 +153,11 @@ func parseParameterMapFile(parameterFile string) (map[string]string, error) { return parameterMap, nil } -// buildFlags contains options relating to troubleshooting provisioner jobs. +// buildFlags contains options relating to troubleshooting provisioner jobs +// and setting the reason for the workspace build. type buildFlags struct { provisionerLogDebug bool + reason string } func (bf *buildFlags) cliOptions() []serpent.Option { @@ -160,5 +170,17 @@ This is useful for troubleshooting build issues.`, Value: serpent.BoolOf(&bf.provisionerLogDebug), Hidden: true, }, + { + Flag: "reason", + Description: `Sets the reason for the workspace build (cli, vscode_connection, jetbrains_connection).`, + Value: serpent.EnumOf( + &bf.reason, + string(codersdk.BuildReasonCLI), + string(codersdk.BuildReasonVSCodeConnection), + string(codersdk.BuildReasonJetbrainsConnection), + ), + Default: string(codersdk.BuildReasonCLI), + Hidden: true, + }, } } diff --git a/cli/parameterresolver.go b/cli/parameterresolver.go index 40625331fa6aa..cbd00fb59623e 100644 --- a/cli/parameterresolver.go +++ b/cli/parameterresolver.go @@ -26,6 +26,7 @@ type ParameterResolver struct { lastBuildParameters []codersdk.WorkspaceBuildParameter sourceWorkspaceParameters []codersdk.WorkspaceBuildParameter + presetParameters []codersdk.WorkspaceBuildParameter richParameters []codersdk.WorkspaceBuildParameter richParametersDefaults map[string]string richParametersFile map[string]string @@ -45,6 +46,11 @@ func (pr *ParameterResolver) WithSourceWorkspaceParameters(params []codersdk.Wor return pr } +func (pr *ParameterResolver) WithPresetParameters(params []codersdk.WorkspaceBuildParameter) *ParameterResolver { + pr.presetParameters = params + return pr +} + func (pr *ParameterResolver) WithRichParameters(params []codersdk.WorkspaceBuildParameter) *ParameterResolver { pr.richParameters = params return pr @@ -80,6 +86,8 @@ func (pr *ParameterResolver) WithPromptEphemeralParameters(promptEphemeralParame return pr } +// Resolve gathers workspace build parameters in a layered fashion, applying values from various sources +// in order of precedence: parameter file < CLI/ENV < source build < last build < preset < user input. func (pr *ParameterResolver) Resolve(inv *serpent.Invocation, action WorkspaceCLIAction, templateVersionParameters []codersdk.TemplateVersionParameter) ([]codersdk.WorkspaceBuildParameter, error) { var staged []codersdk.WorkspaceBuildParameter var err error @@ -88,6 +96,7 @@ func (pr *ParameterResolver) Resolve(inv *serpent.Invocation, action WorkspaceCL staged = pr.resolveWithCommandLineOrEnv(staged) staged = pr.resolveWithSourceBuildParameters(staged, templateVersionParameters) staged = pr.resolveWithLastBuildParameters(staged, templateVersionParameters) + staged = pr.resolveWithPreset(staged) // Preset parameters take precedence from all other parameters if err = pr.verifyConstraints(staged, action, templateVersionParameters); err != nil { return nil, err } @@ -97,6 +106,21 @@ func (pr *ParameterResolver) Resolve(inv *serpent.Invocation, action WorkspaceCL return staged, nil } +func (pr *ParameterResolver) resolveWithPreset(resolved []codersdk.WorkspaceBuildParameter) []codersdk.WorkspaceBuildParameter { +next: + for _, presetParameter := range pr.presetParameters { + for i, r := range resolved { + if r.Name == presetParameter.Name { + resolved[i].Value = presetParameter.Value + continue next + } + } + resolved = append(resolved, presetParameter) + } + + return resolved +} + func (pr *ParameterResolver) resolveWithParametersMapFile(resolved []codersdk.WorkspaceBuildParameter) []codersdk.WorkspaceBuildParameter { next: for name, value := range pr.richParametersFile { diff --git a/cli/ping.go b/cli/ping.go index f75ed42d26362..0836aa8a135db 100644 --- a/cli/ping.go +++ b/cli/ping.go @@ -53,7 +53,7 @@ func (s *pingSummary) addResult(r *ipnstate.PingResult) { if s.Min == nil || r.LatencySeconds < s.Min.Seconds() { s.Min = ptr.Ref(time.Duration(r.LatencySeconds * float64(time.Second))) } - if s.Max == nil || r.LatencySeconds > s.Min.Seconds() { + if s.Max == nil || r.LatencySeconds > s.Max.Seconds() { s.Max = ptr.Ref(time.Duration(r.LatencySeconds * float64(time.Second))) } s.latencySum += r.LatencySeconds @@ -110,7 +110,7 @@ func (r *RootCmd) ping() *serpent.Command { defer notifyCancel() workspaceName := inv.Args[0] - _, workspaceAgent, err := getWorkspaceAndAgent( + _, workspaceAgent, _, err := getWorkspaceAndAgent( ctx, inv, client, false, // Do not autostart for a ping. workspaceName, diff --git a/cli/ping_internal_test.go b/cli/ping_internal_test.go index 0c131fadfa52a..5448d29f32133 100644 --- a/cli/ping_internal_test.go +++ b/cli/ping_internal_test.go @@ -21,11 +21,11 @@ func TestBuildSummary(t *testing.T) { }, { Err: "", - LatencySeconds: 0.2, + LatencySeconds: 0.3, }, { Err: "", - LatencySeconds: 0.3, + LatencySeconds: 0.2, }, { Err: "ping error", diff --git a/cli/portforward.go b/cli/portforward.go index e6ef2eb11bca8..7a7723213f760 100644 --- a/cli/portforward.go +++ b/cli/portforward.go @@ -84,7 +84,7 @@ func (r *RootCmd) portForward() *serpent.Command { return xerrors.New("no port-forwards requested") } - workspace, workspaceAgent, err := getWorkspaceAndAgent(ctx, inv, client, !disableAutostart, inv.Args[0]) + workspace, workspaceAgent, _, err := getWorkspaceAndAgent(ctx, inv, client, !disableAutostart, inv.Args[0]) if err != nil { return err } diff --git a/cli/portforward_test.go b/cli/portforward_test.go index e995b31950314..9899bd28cccdf 100644 --- a/cli/portforward_test.go +++ b/cli/portforward_test.go @@ -13,7 +13,6 @@ import ( "github.com/pion/udp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "golang.org/x/xerrors" "github.com/coder/coder/v2/agent" "github.com/coder/coder/v2/agent/agenttest" @@ -161,7 +160,7 @@ func TestPortForward(t *testing.T) { inv.Stdout = pty.Output() inv.Stderr = pty.Output() - iNet := newInProcNet() + iNet := testutil.NewInProcNet() inv.Net = iNet ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong) defer cancel() @@ -177,10 +176,10 @@ func TestPortForward(t *testing.T) { // sync. dialCtx, dialCtxCancel := context.WithTimeout(ctx, testutil.WaitShort) defer dialCtxCancel() - c1, err := iNet.dial(dialCtx, addr{c.network, c.localAddress[0]}) + c1, err := iNet.Dial(dialCtx, testutil.NewAddr(c.network, c.localAddress[0])) require.NoError(t, err, "open connection 1 to 'local' listener") defer c1.Close() - c2, err := iNet.dial(dialCtx, addr{c.network, c.localAddress[0]}) + c2, err := iNet.Dial(dialCtx, testutil.NewAddr(c.network, c.localAddress[0])) require.NoError(t, err, "open connection 2 to 'local' listener") defer c2.Close() testDial(t, c2) @@ -218,7 +217,7 @@ func TestPortForward(t *testing.T) { inv.Stdout = pty.Output() inv.Stderr = pty.Output() - iNet := newInProcNet() + iNet := testutil.NewInProcNet() inv.Net = iNet ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong) defer cancel() @@ -232,10 +231,10 @@ func TestPortForward(t *testing.T) { // then test them out of order. dialCtx, dialCtxCancel := context.WithTimeout(ctx, testutil.WaitShort) defer dialCtxCancel() - c1, err := iNet.dial(dialCtx, addr{c.network, c.localAddress[0]}) + c1, err := iNet.Dial(dialCtx, testutil.NewAddr(c.network, c.localAddress[0])) require.NoError(t, err, "open connection 1 to 'local' listener 1") defer c1.Close() - c2, err := iNet.dial(dialCtx, addr{c.network, c.localAddress[1]}) + c2, err := iNet.Dial(dialCtx, testutil.NewAddr(c.network, c.localAddress[1])) require.NoError(t, err, "open connection 2 to 'local' listener 2") defer c2.Close() testDial(t, c2) @@ -257,7 +256,7 @@ func TestPortForward(t *testing.T) { t.Run("All", func(t *testing.T) { t.Parallel() var ( - dials = []addr{} + dials = []testutil.Addr{} flags = []string{} ) @@ -265,10 +264,7 @@ func TestPortForward(t *testing.T) { for _, c := range cases { p := setupTestListener(t, c.setupRemote(t)) - dials = append(dials, addr{ - network: c.network, - addr: c.localAddress[0], - }) + dials = append(dials, testutil.NewAddr(c.network, c.localAddress[0])) flags = append(flags, fmt.Sprintf(c.flag[0], p)) } @@ -279,7 +275,7 @@ func TestPortForward(t *testing.T) { pty := ptytest.New(t).Attach(inv) inv.Stderr = pty.Output() - iNet := newInProcNet() + iNet := testutil.NewInProcNet() inv.Net = iNet ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong) defer cancel() @@ -296,7 +292,7 @@ func TestPortForward(t *testing.T) { ) defer dialCtxCancel() for i, a := range dials { - c, err := iNet.dial(dialCtx, a) + c, err := iNet.Dial(dialCtx, a) require.NoErrorf(t, err, "open connection %v to 'local' listener %v", i+1, i+1) t.Cleanup(func() { _ = c.Close() @@ -340,7 +336,7 @@ func TestPortForward(t *testing.T) { inv.Stdout = pty.Output() inv.Stderr = pty.Output() - iNet := newInProcNet() + iNet := testutil.NewInProcNet() inv.Net = iNet // listen on port 5555 on IPv6 so it's busy when we try to port forward @@ -361,7 +357,7 @@ func TestPortForward(t *testing.T) { // Test IPv4 still works dialCtx, dialCtxCancel := context.WithTimeout(ctx, testutil.WaitShort) defer dialCtxCancel() - c1, err := iNet.dial(dialCtx, addr{"tcp", "127.0.0.1:5555"}) + c1, err := iNet.Dial(dialCtx, testutil.NewAddr("tcp", "127.0.0.1:5555")) require.NoError(t, err, "open connection 1 to 'local' listener") defer c1.Close() testDial(t, c1) @@ -473,95 +469,3 @@ func assertWritePayload(t *testing.T, w io.Writer, payload []byte) { assert.NoError(t, err, "write payload") assert.Equal(t, len(payload), n, "payload length does not match") } - -type addr struct { - network string - addr string -} - -func (a addr) Network() string { - return a.network -} - -func (a addr) Address() string { - return a.addr -} - -func (a addr) String() string { - return a.network + "|" + a.addr -} - -type inProcNet struct { - sync.Mutex - - listeners map[addr]*inProcListener -} - -type inProcListener struct { - c chan net.Conn - n *inProcNet - a addr - o sync.Once -} - -func newInProcNet() *inProcNet { - return &inProcNet{listeners: make(map[addr]*inProcListener)} -} - -func (n *inProcNet) Listen(network, address string) (net.Listener, error) { - a := addr{network, address} - n.Lock() - defer n.Unlock() - if _, ok := n.listeners[a]; ok { - return nil, xerrors.New("busy") - } - l := newInProcListener(n, a) - n.listeners[a] = l - return l, nil -} - -func (n *inProcNet) dial(ctx context.Context, a addr) (net.Conn, error) { - n.Lock() - defer n.Unlock() - l, ok := n.listeners[a] - if !ok { - return nil, xerrors.Errorf("nothing listening on %s", a) - } - x, y := net.Pipe() - select { - case <-ctx.Done(): - return nil, ctx.Err() - case l.c <- x: - return y, nil - } -} - -func newInProcListener(n *inProcNet, a addr) *inProcListener { - return &inProcListener{ - c: make(chan net.Conn), - n: n, - a: a, - } -} - -func (l *inProcListener) Accept() (net.Conn, error) { - c, ok := <-l.c - if !ok { - return nil, net.ErrClosed - } - return c, nil -} - -func (l *inProcListener) Close() error { - l.o.Do(func() { - l.n.Lock() - defer l.n.Unlock() - delete(l.n.listeners, l.a) - close(l.c) - }) - return nil -} - -func (l *inProcListener) Addr() net.Addr { - return l.a -} diff --git a/cli/provisionerjobs.go b/cli/provisionerjobs.go index c2b6b78658447..2ddd04c5b6a29 100644 --- a/cli/provisionerjobs.go +++ b/cli/provisionerjobs.go @@ -166,7 +166,7 @@ func (r *RootCmd) provisionerJobsCancel() *serpent.Command { err = client.CancelTemplateVersion(ctx, ptr.NilToEmpty(job.Input.TemplateVersionID)) case codersdk.ProvisionerJobTypeWorkspaceBuild: _, _ = fmt.Fprintf(inv.Stdout, "Canceling workspace build job %s...\n", job.ID) - err = client.CancelWorkspaceBuild(ctx, ptr.NilToEmpty(job.Input.WorkspaceBuildID)) + err = client.CancelWorkspaceBuild(ctx, ptr.NilToEmpty(job.Input.WorkspaceBuildID), codersdk.CancelWorkspaceBuildParams{}) } if err != nil { return xerrors.Errorf("cancel provisioner job: %w", err) diff --git a/cli/restart.go b/cli/restart.go index 156f506105c5a..20ee0b9b9de9d 100644 --- a/cli/restart.go +++ b/cli/restart.go @@ -51,8 +51,17 @@ func (r *RootCmd) restart() *serpent.Command { return err } + stopParamValues, err := asWorkspaceBuildParameters(parameterFlags.ephemeralParameters) + if err != nil { + return xerrors.Errorf("parse ephemeral parameters: %w", err) + } wbr := codersdk.CreateWorkspaceBuildRequest{ Transition: codersdk.WorkspaceTransitionStop, + // Ephemeral parameters should be passed to both stop and start builds. + // TODO: maybe these values should be sourced from the previous build? + // It has to be manually sourced, as ephemeral parameters do not carry across + // builds. + RichParameterValues: stopParamValues, } if bflags.provisionerLogDebug { wbr.LogLevel = codersdk.ProvisionerLogLevelDebug diff --git a/cli/restart_test.go b/cli/restart_test.go index d69344435bf28..01be7e590cebf 100644 --- a/cli/restart_test.go +++ b/cli/restart_test.go @@ -10,6 +10,7 @@ import ( "github.com/coder/coder/v2/cli/clitest" "github.com/coder/coder/v2/coderd/coderdtest" + "github.com/coder/coder/v2/coderd/util/ptr" "github.com/coder/coder/v2/codersdk" "github.com/coder/coder/v2/provisioner/echo" "github.com/coder/coder/v2/provisionersdk/proto" @@ -70,8 +71,14 @@ func TestRestart(t *testing.T) { member, memberUser := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses()) coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) - template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) - workspace := coderdtest.CreateWorkspace(t, member, template.ID) + template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID, func(request *codersdk.CreateTemplateRequest) { + request.UseClassicParameterFlow = ptr.Ref(true) // TODO: Remove when dynamic parameters prompt missing ephemeral parameters. + }) + workspace := coderdtest.CreateWorkspace(t, member, template.ID, func(request *codersdk.CreateWorkspaceRequest) { + request.RichParameterValues = []codersdk.WorkspaceBuildParameter{ + {Name: ephemeralParameterName, Value: "placeholder"}, + } + }) coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID) inv, root := clitest.New(t, "restart", workspace.Name, "--prompt-ephemeral-parameters") @@ -125,7 +132,11 @@ func TestRestart(t *testing.T) { version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses()) coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) - workspace := coderdtest.CreateWorkspace(t, member, template.ID) + workspace := coderdtest.CreateWorkspace(t, member, template.ID, func(request *codersdk.CreateWorkspaceRequest) { + request.RichParameterValues = []codersdk.WorkspaceBuildParameter{ + {Name: ephemeralParameterName, Value: "placeholder"}, + } + }) coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID) inv, root := clitest.New(t, "restart", workspace.Name, @@ -178,8 +189,14 @@ func TestRestart(t *testing.T) { member, memberUser := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses()) coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) - template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) - workspace := coderdtest.CreateWorkspace(t, member, template.ID) + template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID, func(request *codersdk.CreateTemplateRequest) { + request.UseClassicParameterFlow = ptr.Ref(true) // TODO: Remove when dynamic parameters prompts missing ephemeral parameters + }) + workspace := coderdtest.CreateWorkspace(t, member, template.ID, func(request *codersdk.CreateWorkspaceRequest) { + request.RichParameterValues = []codersdk.WorkspaceBuildParameter{ + {Name: ephemeralParameterName, Value: "placeholder"}, + } + }) coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID) inv, root := clitest.New(t, "restart", workspace.Name, "--build-options") @@ -233,7 +250,11 @@ func TestRestart(t *testing.T) { version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses()) coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) - workspace := coderdtest.CreateWorkspace(t, member, template.ID) + workspace := coderdtest.CreateWorkspace(t, member, template.ID, func(request *codersdk.CreateWorkspaceRequest) { + request.RichParameterValues = []codersdk.WorkspaceBuildParameter{ + {Name: ephemeralParameterName, Value: "placeholder"}, + } + }) coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID) inv, root := clitest.New(t, "restart", workspace.Name, diff --git a/cli/server.go b/cli/server.go index 9af9965210d72..26d0c8f110403 100644 --- a/cli/server.go +++ b/cli/server.go @@ -61,7 +61,6 @@ import ( "github.com/coder/serpent" "github.com/coder/wgtunnel/tunnelsdk" - "github.com/coder/coder/v2/coderd/ai" "github.com/coder/coder/v2/coderd/entitlements" "github.com/coder/coder/v2/coderd/notifications/reports" "github.com/coder/coder/v2/coderd/runtimeconfig" @@ -78,7 +77,6 @@ import ( "github.com/coder/coder/v2/coderd/database" "github.com/coder/coder/v2/coderd/database/awsiamrds" "github.com/coder/coder/v2/coderd/database/dbauthz" - "github.com/coder/coder/v2/coderd/database/dbmem" "github.com/coder/coder/v2/coderd/database/dbmetrics" "github.com/coder/coder/v2/coderd/database/dbpurge" "github.com/coder/coder/v2/coderd/database/migrations" @@ -424,7 +422,7 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd. builtinPostgres := false // Only use built-in if PostgreSQL URL isn't specified! - if !vals.InMemoryDatabase && vals.PostgresURL == "" { + if vals.PostgresURL == "" { var closeFunc func() error cliui.Infof(inv.Stdout, "Using built-in PostgreSQL (%s)", config.PostgresPath()) customPostgresCacheDir := "" @@ -611,22 +609,6 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd. ) } - aiProviders, err := ReadAIProvidersFromEnv(os.Environ()) - if err != nil { - return xerrors.Errorf("read ai providers from env: %w", err) - } - vals.AI.Value.Providers = append(vals.AI.Value.Providers, aiProviders...) - for _, provider := range aiProviders { - logger.Debug( - ctx, "loaded ai provider", - slog.F("type", provider.Type), - ) - } - languageModels, err := ai.ModelsFromConfig(ctx, vals.AI.Value.Providers) - if err != nil { - return xerrors.Errorf("create language models: %w", err) - } - realIPConfig, err := httpmw.ParseRealIPConfig(vals.ProxyTrustedHeaders, vals.ProxyTrustedOrigins) if err != nil { return xerrors.Errorf("parse real ip config: %w", err) @@ -657,7 +639,6 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd. CacheDir: cacheDir, GoogleTokenValidator: googleTokenValidator, ExternalAuthConfigs: externalAuthConfigs, - LanguageModels: languageModels, RealIPConfig: realIPConfig, SSHKeygenAlgorithm: sshKeygenAlgorithm, TracerProvider: tracerProvider, @@ -744,43 +725,38 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd. // nil, that case of the select will just never fire, but it's important not to have a // "bare" read on this channel. var pubsubWatchdogTimeout <-chan struct{} - if vals.InMemoryDatabase { - // This is only used for testing. - options.Database = dbmem.New() - options.Pubsub = pubsub.NewInMemory() - } else { - sqlDB, dbURL, err := getAndMigratePostgresDB(ctx, logger, vals.PostgresURL.String(), codersdk.PostgresAuth(vals.PostgresAuth), sqlDriver) - if err != nil { - return xerrors.Errorf("connect to postgres: %w", err) - } - defer func() { - _ = sqlDB.Close() - }() - if options.DeploymentValues.Prometheus.Enable { - // At this stage we don't think the database name serves much purpose in these metrics. - // It requires parsing the DSN to determine it, which requires pulling in another dependency - // (i.e. https://github.com/jackc/pgx), but it's rather heavy. - // The conn string (https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING) can - // take different forms, which make parsing non-trivial. - options.PrometheusRegistry.MustRegister(collectors.NewDBStatsCollector(sqlDB, "")) - } + sqlDB, dbURL, err := getAndMigratePostgresDB(ctx, logger, vals.PostgresURL.String(), codersdk.PostgresAuth(vals.PostgresAuth), sqlDriver) + if err != nil { + return xerrors.Errorf("connect to postgres: %w", err) + } + defer func() { + _ = sqlDB.Close() + }() - options.Database = database.New(sqlDB) - ps, err := pubsub.New(ctx, logger.Named("pubsub"), sqlDB, dbURL) - if err != nil { - return xerrors.Errorf("create pubsub: %w", err) - } - options.Pubsub = ps - if options.DeploymentValues.Prometheus.Enable { - options.PrometheusRegistry.MustRegister(ps) - } - defer options.Pubsub.Close() - psWatchdog := pubsub.NewWatchdog(ctx, logger.Named("pswatch"), ps) - pubsubWatchdogTimeout = psWatchdog.Timeout() - defer psWatchdog.Close() + if options.DeploymentValues.Prometheus.Enable { + // At this stage we don't think the database name serves much purpose in these metrics. + // It requires parsing the DSN to determine it, which requires pulling in another dependency + // (i.e. https://github.com/jackc/pgx), but it's rather heavy. + // The conn string (https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING) can + // take different forms, which make parsing non-trivial. + options.PrometheusRegistry.MustRegister(collectors.NewDBStatsCollector(sqlDB, "")) } + options.Database = database.New(sqlDB) + ps, err := pubsub.New(ctx, logger.Named("pubsub"), sqlDB, dbURL) + if err != nil { + return xerrors.Errorf("create pubsub: %w", err) + } + options.Pubsub = ps + if options.DeploymentValues.Prometheus.Enable { + options.PrometheusRegistry.MustRegister(ps) + } + defer options.Pubsub.Close() + psWatchdog := pubsub.NewWatchdog(ctx, logger.Named("pswatch"), ps) + pubsubWatchdogTimeout = psWatchdog.Timeout() + defer psWatchdog.Close() + if options.DeploymentValues.Prometheus.Enable && options.DeploymentValues.Prometheus.CollectDBMetrics { options.Database = dbmetrics.NewQueryMetrics(options.Database, options.Logger, options.PrometheusRegistry) } else { @@ -1125,7 +1101,7 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd. autobuildTicker := time.NewTicker(vals.AutobuildPollInterval.Value()) defer autobuildTicker.Stop() autobuildExecutor := autobuild.NewExecutor( - ctx, options.Database, options.Pubsub, coderAPI.FileCache, options.PrometheusRegistry, coderAPI.TemplateScheduleStore, &coderAPI.Auditor, coderAPI.AccessControlStore, logger, autobuildTicker.C, options.NotificationsEnqueuer, coderAPI.Experiments) + ctx, options.Database, options.Pubsub, coderAPI.FileCache, options.PrometheusRegistry, coderAPI.TemplateScheduleStore, &coderAPI.Auditor, coderAPI.AccessControlStore, coderAPI.BuildUsageChecker, logger, autobuildTicker.C, options.NotificationsEnqueuer, coderAPI.Experiments) autobuildExecutor.Run() jobReaperTicker := time.NewTicker(vals.JobReaperDetectorInterval.Value()) @@ -1202,7 +1178,6 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd. var wg sync.WaitGroup for i, provisionerDaemon := range provisionerDaemons { id := i + 1 - provisionerDaemon := provisionerDaemon wg.Add(1) go func() { defer wg.Done() @@ -1680,7 +1655,6 @@ func configureServerTLS(ctx context.Context, logger slog.Logger, tlsMinVersion, // Expensively check which certificate matches the client hello. for _, cert := range certs { - cert := cert if err := hi.SupportsCertificate(&cert); err == nil { return &cert, nil } @@ -2642,77 +2616,6 @@ func redirectHTTPToHTTPSDeprecation(ctx context.Context, logger slog.Logger, inv } } -func ReadAIProvidersFromEnv(environ []string) ([]codersdk.AIProviderConfig, error) { - // The index numbers must be in-order. - sort.Strings(environ) - - var providers []codersdk.AIProviderConfig - for _, v := range serpent.ParseEnviron(environ, "CODER_AI_PROVIDER_") { - tokens := strings.SplitN(v.Name, "_", 2) - if len(tokens) != 2 { - return nil, xerrors.Errorf("invalid env var: %s", v.Name) - } - - providerNum, err := strconv.Atoi(tokens[0]) - if err != nil { - return nil, xerrors.Errorf("parse number: %s", v.Name) - } - - var provider codersdk.AIProviderConfig - switch { - case len(providers) < providerNum: - return nil, xerrors.Errorf( - "provider num %v skipped: %s", - len(providers), - v.Name, - ) - case len(providers) == providerNum: - // At the next next provider. - providers = append(providers, provider) - case len(providers) == providerNum+1: - // At the current provider. - provider = providers[providerNum] - } - - key := tokens[1] - switch key { - case "TYPE": - provider.Type = v.Value - case "API_KEY": - provider.APIKey = v.Value - case "BASE_URL": - provider.BaseURL = v.Value - case "MODELS": - provider.Models = strings.Split(v.Value, ",") - } - providers[providerNum] = provider - } - for _, envVar := range environ { - tokens := strings.SplitN(envVar, "=", 2) - if len(tokens) != 2 { - continue - } - switch tokens[0] { - case "OPENAI_API_KEY": - providers = append(providers, codersdk.AIProviderConfig{ - Type: "openai", - APIKey: tokens[1], - }) - case "ANTHROPIC_API_KEY": - providers = append(providers, codersdk.AIProviderConfig{ - Type: "anthropic", - APIKey: tokens[1], - }) - case "GOOGLE_API_KEY": - providers = append(providers, codersdk.AIProviderConfig{ - Type: "google", - APIKey: tokens[1], - }) - } - } - return providers, nil -} - // ReadExternalAuthProvidersFromEnv is provided for compatibility purposes with // the viper CLI. func ReadExternalAuthProvidersFromEnv(environ []string) ([]codersdk.ExternalAuthConfig, error) { diff --git a/cli/server_test.go b/cli/server_test.go index 2d0bbdd24e83b..435ed2879c9a3 100644 --- a/cli/server_test.go +++ b/cli/server_test.go @@ -59,9 +59,6 @@ import ( ) func dbArg(t *testing.T) string { - if !dbtestutil.WillUsePostgres() { - return "--in-memory" - } dbURL, err := dbtestutil.Open(t) require.NoError(t, err) return "--postgres-url=" + dbURL diff --git a/cli/show.go b/cli/show.go index f2d3df3ecc3c5..284e8581f5dda 100644 --- a/cli/show.go +++ b/cli/show.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" + "github.com/coder/coder/v2/agent/agentcontainers" "github.com/coder/coder/v2/cli/cliui" "github.com/coder/coder/v2/codersdk" "github.com/coder/serpent" @@ -15,9 +16,18 @@ import ( func (r *RootCmd) show() *serpent.Command { client := new(codersdk.Client) + var details bool return &serpent.Command{ Use: "show ", Short: "Display details of a workspace's resources and agents", + Options: serpent.OptionSet{ + { + Flag: "details", + Description: "Show full error messages and additional details.", + Default: "false", + Value: serpent.BoolOf(&details), + }, + }, Middleware: serpent.Chain( serpent.RequireNArgs(1), r.InitClient(client), @@ -35,6 +45,7 @@ func (r *RootCmd) show() *serpent.Command { options := cliui.WorkspaceResourcesOptions{ WorkspaceName: workspace.Name, ServerVersion: buildInfo.Version, + ShowDetails: details, } if workspace.LatestBuild.Status == codersdk.WorkspaceStatusRunning { // Get listening ports for each agent. @@ -42,6 +53,7 @@ func (r *RootCmd) show() *serpent.Command { options.ListeningPorts = ports options.Devcontainers = devcontainers } + return cliui.WorkspaceResources(inv.Stdout, workspace.LatestBuild.Resources, options) }, } @@ -68,13 +80,17 @@ func fetchRuntimeResources(inv *serpent.Invocation, client *codersdk.Client, res ports[agent.ID] = lp mu.Unlock() }() + + if agent.ParentID.Valid { + continue + } wg.Add(1) go func() { defer wg.Done() dc, err := client.WorkspaceAgentListContainers(inv.Context(), agent.ID, map[string]string{ // Labels set by VSCode Remote Containers and @devcontainers/cli. - "devcontainer.config_file": "", - "devcontainer.local_folder": "", + agentcontainers.DevcontainerConfigFileLabel: "", + agentcontainers.DevcontainerLocalFolderLabel: "", }) if err != nil { cliui.Warnf(inv.Stderr, "Failed to get devcontainers for agent %s: %v", agent.Name, err) diff --git a/cli/show_test.go b/cli/show_test.go index 7191898f8c0ec..36a5824174fc4 100644 --- a/cli/show_test.go +++ b/cli/show_test.go @@ -1,12 +1,19 @@ package cli_test import ( + "bytes" "testing" + "time" + "github.com/google/uuid" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/coder/coder/v2/agent/agentcontainers" "github.com/coder/coder/v2/cli/clitest" + "github.com/coder/coder/v2/cli/cliui" "github.com/coder/coder/v2/coderd/coderdtest" + "github.com/coder/coder/v2/codersdk" "github.com/coder/coder/v2/pty/ptytest" ) @@ -53,3 +60,354 @@ func TestShow(t *testing.T) { <-doneChan }) } + +func TestShowDevcontainers_Golden(t *testing.T) { + t.Parallel() + + mainAgentID := uuid.MustParse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa") + agentID := mainAgentID + + testCases := []struct { + name string + showDetails bool + devcontainers []codersdk.WorkspaceAgentDevcontainer + listeningPorts map[uuid.UUID]codersdk.WorkspaceAgentListeningPortsResponse + }{ + { + name: "running_devcontainer_with_agent", + devcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + ID: uuid.MustParse("11111111-1111-1111-1111-111111111111"), + Name: "web-dev", + WorkspaceFolder: "/workspaces/web-dev", + ConfigPath: "/workspaces/web-dev/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusRunning, + Dirty: false, + Container: &codersdk.WorkspaceAgentContainer{ + ID: "container-web-dev", + FriendlyName: "quirky_lovelace", + Image: "mcr.microsoft.com/devcontainers/typescript-node:1.0.0", + Running: true, + Status: "running", + CreatedAt: time.Now().Add(-1 * time.Hour), + Labels: map[string]string{ + agentcontainers.DevcontainerConfigFileLabel: "/workspaces/web-dev/.devcontainer/devcontainer.json", + agentcontainers.DevcontainerLocalFolderLabel: "/workspaces/web-dev", + }, + }, + Agent: &codersdk.WorkspaceAgentDevcontainerAgent{ + ID: uuid.MustParse("22222222-2222-2222-2222-222222222222"), + Name: "web-dev", + Directory: "/workspaces/web-dev", + }, + }, + }, + listeningPorts: map[uuid.UUID]codersdk.WorkspaceAgentListeningPortsResponse{ + uuid.MustParse("22222222-2222-2222-2222-222222222222"): { + Ports: []codersdk.WorkspaceAgentListeningPort{ + { + ProcessName: "node", + Network: "tcp", + Port: 3000, + }, + { + ProcessName: "webpack-dev-server", + Network: "tcp", + Port: 8080, + }, + }, + }, + }, + }, + { + name: "running_devcontainer_without_agent", + devcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + ID: uuid.MustParse("33333333-3333-3333-3333-333333333333"), + Name: "web-server", + WorkspaceFolder: "/workspaces/web-server", + ConfigPath: "/workspaces/web-server/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusRunning, + Dirty: false, + Container: &codersdk.WorkspaceAgentContainer{ + ID: "container-web-server", + FriendlyName: "amazing_turing", + Image: "nginx:latest", + Running: true, + Status: "running", + CreatedAt: time.Now().Add(-30 * time.Minute), + Labels: map[string]string{ + agentcontainers.DevcontainerConfigFileLabel: "/workspaces/web-server/.devcontainer/devcontainer.json", + agentcontainers.DevcontainerLocalFolderLabel: "/workspaces/web-server", + }, + }, + Agent: nil, // No agent for this running container. + }, + }, + }, + { + name: "stopped_devcontainer", + devcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + ID: uuid.MustParse("44444444-4444-4444-4444-444444444444"), + Name: "api-dev", + WorkspaceFolder: "/workspaces/api-dev", + ConfigPath: "/workspaces/api-dev/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + Dirty: false, + Container: &codersdk.WorkspaceAgentContainer{ + ID: "container-api-dev", + FriendlyName: "clever_darwin", + Image: "mcr.microsoft.com/devcontainers/go:1.0.0", + Running: false, + Status: "exited", + CreatedAt: time.Now().Add(-2 * time.Hour), + Labels: map[string]string{ + agentcontainers.DevcontainerConfigFileLabel: "/workspaces/api-dev/.devcontainer/devcontainer.json", + agentcontainers.DevcontainerLocalFolderLabel: "/workspaces/api-dev", + }, + }, + Agent: nil, // No agent for stopped container. + }, + }, + }, + { + name: "starting_devcontainer", + devcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + ID: uuid.MustParse("55555555-5555-5555-5555-555555555555"), + Name: "database-dev", + WorkspaceFolder: "/workspaces/database-dev", + ConfigPath: "/workspaces/database-dev/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusStarting, + Dirty: false, + Container: &codersdk.WorkspaceAgentContainer{ + ID: "container-database-dev", + FriendlyName: "nostalgic_hawking", + Image: "mcr.microsoft.com/devcontainers/postgres:1.0.0", + Running: false, + Status: "created", + CreatedAt: time.Now().Add(-5 * time.Minute), + Labels: map[string]string{ + agentcontainers.DevcontainerConfigFileLabel: "/workspaces/database-dev/.devcontainer/devcontainer.json", + agentcontainers.DevcontainerLocalFolderLabel: "/workspaces/database-dev", + }, + }, + Agent: nil, // No agent yet while starting. + }, + }, + }, + { + name: "error_devcontainer", + devcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + ID: uuid.MustParse("66666666-6666-6666-6666-666666666666"), + Name: "failed-dev", + WorkspaceFolder: "/workspaces/failed-dev", + ConfigPath: "/workspaces/failed-dev/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusError, + Dirty: false, + Error: "Failed to pull image mcr.microsoft.com/devcontainers/go:latest: timeout after 5m0s", + Container: nil, // No container due to error. + Agent: nil, // No agent due to error. + }, + }, + }, + + { + name: "mixed_devcontainer_states", + devcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + ID: uuid.MustParse("88888888-8888-8888-8888-888888888888"), + Name: "frontend", + WorkspaceFolder: "/workspaces/frontend", + Status: codersdk.WorkspaceAgentDevcontainerStatusRunning, + Container: &codersdk.WorkspaceAgentContainer{ + ID: "container-frontend", + FriendlyName: "vibrant_tesla", + Image: "node:18", + Running: true, + Status: "running", + CreatedAt: time.Now().Add(-30 * time.Minute), + }, + Agent: &codersdk.WorkspaceAgentDevcontainerAgent{ + ID: uuid.MustParse("99999999-9999-9999-9999-999999999999"), + Name: "frontend", + Directory: "/workspaces/frontend", + }, + }, + { + ID: uuid.MustParse("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"), + Name: "backend", + WorkspaceFolder: "/workspaces/backend", + Status: codersdk.WorkspaceAgentDevcontainerStatusStopped, + Container: &codersdk.WorkspaceAgentContainer{ + ID: "container-backend", + FriendlyName: "peaceful_curie", + Image: "python:3.11", + Running: false, + Status: "exited", + CreatedAt: time.Now().Add(-1 * time.Hour), + }, + Agent: nil, + }, + { + ID: uuid.MustParse("bbbbbbbb-cccc-dddd-eeee-ffffffffffff"), + Name: "error-container", + WorkspaceFolder: "/workspaces/error-container", + Status: codersdk.WorkspaceAgentDevcontainerStatusError, + Error: "Container build failed: dockerfile syntax error on line 15", + Container: nil, + Agent: nil, + }, + }, + listeningPorts: map[uuid.UUID]codersdk.WorkspaceAgentListeningPortsResponse{ + uuid.MustParse("99999999-9999-9999-9999-999999999999"): { + Ports: []codersdk.WorkspaceAgentListeningPort{ + { + ProcessName: "vite", + Network: "tcp", + Port: 5173, + }, + }, + }, + }, + }, + { + name: "running_devcontainer_with_agent_and_error", + devcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + ID: uuid.MustParse("cccccccc-dddd-eeee-ffff-000000000000"), + Name: "problematic-dev", + WorkspaceFolder: "/workspaces/problematic-dev", + ConfigPath: "/workspaces/problematic-dev/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusRunning, + Dirty: false, + Error: "Warning: Container started but healthcheck failed", + Container: &codersdk.WorkspaceAgentContainer{ + ID: "container-problematic", + FriendlyName: "cranky_mendel", + Image: "mcr.microsoft.com/devcontainers/python:1.0.0", + Running: true, + Status: "running", + CreatedAt: time.Now().Add(-15 * time.Minute), + Labels: map[string]string{ + agentcontainers.DevcontainerConfigFileLabel: "/workspaces/problematic-dev/.devcontainer/devcontainer.json", + agentcontainers.DevcontainerLocalFolderLabel: "/workspaces/problematic-dev", + }, + }, + Agent: &codersdk.WorkspaceAgentDevcontainerAgent{ + ID: uuid.MustParse("dddddddd-eeee-ffff-aaaa-111111111111"), + Name: "problematic-dev", + Directory: "/workspaces/problematic-dev", + }, + }, + }, + listeningPorts: map[uuid.UUID]codersdk.WorkspaceAgentListeningPortsResponse{ + uuid.MustParse("dddddddd-eeee-ffff-aaaa-111111111111"): { + Ports: []codersdk.WorkspaceAgentListeningPort{ + { + ProcessName: "python", + Network: "tcp", + Port: 8000, + }, + }, + }, + }, + }, + { + name: "long_error_message", + devcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + ID: uuid.MustParse("eeeeeeee-ffff-0000-1111-222222222222"), + Name: "long-error-dev", + WorkspaceFolder: "/workspaces/long-error-dev", + ConfigPath: "/workspaces/long-error-dev/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusError, + Dirty: false, + Error: "Failed to build devcontainer: dockerfile parse error at line 25: unknown instruction 'INSTALL', did you mean 'RUN apt-get install'? This is a very long error message that should be truncated when detail flag is not used", + Container: nil, + Agent: nil, + }, + }, + }, + { + name: "long_error_message_with_detail", + showDetails: true, + devcontainers: []codersdk.WorkspaceAgentDevcontainer{ + { + ID: uuid.MustParse("eeeeeeee-ffff-0000-1111-222222222222"), + Name: "long-error-dev", + WorkspaceFolder: "/workspaces/long-error-dev", + ConfigPath: "/workspaces/long-error-dev/.devcontainer/devcontainer.json", + Status: codersdk.WorkspaceAgentDevcontainerStatusError, + Dirty: false, + Error: "Failed to build devcontainer: dockerfile parse error at line 25: unknown instruction 'INSTALL', did you mean 'RUN apt-get install'? This is a very long error message that should be truncated when detail flag is not used", + Container: nil, + Agent: nil, + }, + }, + }, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + var allAgents []codersdk.WorkspaceAgent + mainAgent := codersdk.WorkspaceAgent{ + ID: mainAgentID, + Name: "main", + OperatingSystem: "linux", + Architecture: "amd64", + Status: codersdk.WorkspaceAgentConnected, + Health: codersdk.WorkspaceAgentHealth{Healthy: true}, + Version: "v2.15.0", + } + allAgents = append(allAgents, mainAgent) + + for _, dc := range tc.devcontainers { + if dc.Agent != nil { + devcontainerAgent := codersdk.WorkspaceAgent{ + ID: dc.Agent.ID, + ParentID: uuid.NullUUID{UUID: mainAgentID, Valid: true}, + Name: dc.Agent.Name, + OperatingSystem: "linux", + Architecture: "amd64", + Status: codersdk.WorkspaceAgentConnected, + Health: codersdk.WorkspaceAgentHealth{Healthy: true}, + Version: "v2.15.0", + } + allAgents = append(allAgents, devcontainerAgent) + } + } + + resources := []codersdk.WorkspaceResource{ + { + Type: "compute", + Name: "main", + Agents: allAgents, + }, + } + options := cliui.WorkspaceResourcesOptions{ + WorkspaceName: "test-workspace", + ServerVersion: "v2.15.0", + ShowDetails: tc.showDetails, + Devcontainers: map[uuid.UUID]codersdk.WorkspaceAgentListContainersResponse{ + agentID: { + Devcontainers: tc.devcontainers, + }, + }, + ListeningPorts: tc.listeningPorts, + } + + var buf bytes.Buffer + err := cliui.WorkspaceResources(&buf, resources, options) + require.NoError(t, err) + + replacements := map[string]string{} + clitest.TestGoldenFile(t, "TestShowDevcontainers_Golden/"+tc.name, buf.Bytes(), replacements) + }) + } +} diff --git a/cli/speedtest.go b/cli/speedtest.go index 0d9f839d6b458..08112f50cce2c 100644 --- a/cli/speedtest.go +++ b/cli/speedtest.go @@ -83,7 +83,7 @@ func (r *RootCmd) speedtest() *serpent.Command { return xerrors.Errorf("--direct (-d) is incompatible with --%s", varDisableDirect) } - _, workspaceAgent, err := getWorkspaceAndAgent(ctx, inv, client, false, inv.Args[0]) + _, workspaceAgent, _, err := getWorkspaceAndAgent(ctx, inv, client, false, inv.Args[0]) if err != nil { return err } diff --git a/cli/ssh.go b/cli/ssh.go index 56ab0b2a0d3af..a2bca46c72f32 100644 --- a/cli/ssh.go +++ b/cli/ssh.go @@ -754,7 +754,8 @@ func findWorkspaceAndAgentByHostname( hostname = strings.TrimSuffix(hostname, qualifiedSuffix) } hostname = normalizeWorkspaceInput(hostname) - return getWorkspaceAndAgent(ctx, inv, client, !disableAutostart, hostname) + ws, agent, _, err := getWorkspaceAndAgent(ctx, inv, client, !disableAutostart, hostname) + return ws, agent, err } // watchAndClose ensures closer is called if the context is canceled or @@ -827,9 +828,10 @@ startWatchLoop: } // getWorkspaceAgent returns the workspace and agent selected using either the -// `[.]` syntax via `in`. +// `[.]` syntax via `in`. It will also return any other agents +// in the workspace as a slice for use in child->parent lookups. // If autoStart is true, the workspace will be started if it is not already running. -func getWorkspaceAndAgent(ctx context.Context, inv *serpent.Invocation, client *codersdk.Client, autostart bool, input string) (codersdk.Workspace, codersdk.WorkspaceAgent, error) { //nolint:revive +func getWorkspaceAndAgent(ctx context.Context, inv *serpent.Invocation, client *codersdk.Client, autostart bool, input string) (codersdk.Workspace, codersdk.WorkspaceAgent, []codersdk.WorkspaceAgent, error) { //nolint:revive var ( workspace codersdk.Workspace // The input will be `owner/name.agent` @@ -840,27 +842,27 @@ func getWorkspaceAndAgent(ctx context.Context, inv *serpent.Invocation, client * workspace, err = namedWorkspace(ctx, client, workspaceParts[0]) if err != nil { - return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, err + return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, nil, err } if workspace.LatestBuild.Transition != codersdk.WorkspaceTransitionStart { if !autostart { - return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.New("workspace must be started") + return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, nil, xerrors.New("workspace must be started") } // Autostart the workspace for the user. // For some failure modes, return a better message. if workspace.LatestBuild.Transition == codersdk.WorkspaceTransitionDelete { // Any sort of deleting status, we should reject with a nicer error. - return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("workspace %q is deleted", workspace.Name) + return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, nil, xerrors.Errorf("workspace %q is deleted", workspace.Name) } if workspace.LatestBuild.Job.Status == codersdk.ProvisionerJobFailed { - return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, + return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, nil, xerrors.Errorf("workspace %q is in failed state, unable to autostart the workspace", workspace.Name) } // The workspace needs to be stopped before we can start it. // It cannot be in any pending or failed state. if workspace.LatestBuild.Status != codersdk.WorkspaceStatusStopped { - return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, + return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, nil, xerrors.Errorf("workspace must be started; was unable to autostart as the last build job is %q, expected %q", workspace.LatestBuild.Status, codersdk.WorkspaceStatusStopped, @@ -871,7 +873,9 @@ func getWorkspaceAndAgent(ctx context.Context, inv *serpent.Invocation, client * // It's possible for a workspace build to fail due to the template requiring starting // workspaces with the active version. _, _ = fmt.Fprintf(inv.Stderr, "Workspace was stopped, starting workspace to allow connecting to %q...\n", workspace.Name) - _, err = startWorkspace(inv, client, workspace, workspaceParameterFlags{}, buildFlags{}, WorkspaceStart) + _, err = startWorkspace(inv, client, workspace, workspaceParameterFlags{}, buildFlags{ + reason: string(codersdk.BuildReasonSSHConnection), + }, WorkspaceStart) if cerr, ok := codersdk.AsError(err); ok { switch cerr.StatusCode() { case http.StatusConflict: @@ -881,48 +885,48 @@ func getWorkspaceAndAgent(ctx context.Context, inv *serpent.Invocation, client * case http.StatusForbidden: _, err = startWorkspace(inv, client, workspace, workspaceParameterFlags{}, buildFlags{}, WorkspaceUpdate) if err != nil { - return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("start workspace with active template version: %w", err) + return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, nil, xerrors.Errorf("start workspace with active template version: %w", err) } _, _ = fmt.Fprintln(inv.Stdout, "Unable to start the workspace with template version from last build. Your workspace has been updated to the current active template version.") } } else if err != nil { - return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("start workspace with current template version: %w", err) + return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, nil, xerrors.Errorf("start workspace with current template version: %w", err) } // Refresh workspace state so that `outdated`, `build`,`template_*` fields are up-to-date. workspace, err = namedWorkspace(ctx, client, workspaceParts[0]) if err != nil { - return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, err + return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, nil, err } } if workspace.LatestBuild.Job.CompletedAt == nil { err := cliui.WorkspaceBuild(ctx, inv.Stderr, client, workspace.LatestBuild.ID) if err != nil { - return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, err + return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, nil, err } // Fetch up-to-date build information after completion. workspace.LatestBuild, err = client.WorkspaceBuild(ctx, workspace.LatestBuild.ID) if err != nil { - return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, err + return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, nil, err } } if workspace.LatestBuild.Transition == codersdk.WorkspaceTransitionDelete { - return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("workspace %q is being deleted", workspace.Name) + return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, nil, xerrors.Errorf("workspace %q is being deleted", workspace.Name) } var agentName string if len(workspaceParts) >= 2 { agentName = workspaceParts[1] } - workspaceAgent, err := getWorkspaceAgent(workspace, agentName) + workspaceAgent, otherWorkspaceAgents, err := getWorkspaceAgent(workspace, agentName) if err != nil { - return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, err + return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, nil, err } - return workspace, workspaceAgent, nil + return workspace, workspaceAgent, otherWorkspaceAgents, nil } -func getWorkspaceAgent(workspace codersdk.Workspace, agentName string) (workspaceAgent codersdk.WorkspaceAgent, err error) { +func getWorkspaceAgent(workspace codersdk.Workspace, agentName string) (workspaceAgent codersdk.WorkspaceAgent, otherAgents []codersdk.WorkspaceAgent, err error) { resources := workspace.LatestBuild.Resources var ( @@ -936,22 +940,23 @@ func getWorkspaceAgent(workspace codersdk.Workspace, agentName string) (workspac } } if len(agents) == 0 { - return codersdk.WorkspaceAgent{}, xerrors.Errorf("workspace %q has no agents", workspace.Name) + return codersdk.WorkspaceAgent{}, nil, xerrors.Errorf("workspace %q has no agents", workspace.Name) } slices.Sort(availableNames) if agentName != "" { - for _, otherAgent := range agents { - if otherAgent.Name != agentName { + for i, agent := range agents { + if agent.Name != agentName || agent.ID.String() == agentName { continue } - return otherAgent, nil + otherAgents := slices.Delete(agents, i, i+1) + return agent, otherAgents, nil } - return codersdk.WorkspaceAgent{}, xerrors.Errorf("agent not found by name %q, available agents: %v", agentName, availableNames) + return codersdk.WorkspaceAgent{}, nil, xerrors.Errorf("agent not found by name %q, available agents: %v", agentName, availableNames) } if len(agents) == 1 { - return agents[0], nil + return agents[0], nil, nil } - return codersdk.WorkspaceAgent{}, xerrors.Errorf("multiple agents found, please specify the agent name, available agents: %v", availableNames) + return codersdk.WorkspaceAgent{}, nil, xerrors.Errorf("multiple agents found, please specify the agent name, available agents: %v", availableNames) } // Attempt to poll workspace autostop. We write a per-workspace lockfile to diff --git a/cli/ssh_internal_test.go b/cli/ssh_internal_test.go index 0d956def68938..a7fac11c7254c 100644 --- a/cli/ssh_internal_test.go +++ b/cli/ssh_internal_test.go @@ -376,7 +376,7 @@ func Test_getWorkspaceAgent(t *testing.T) { agent := createAgent("main") workspace := createWorkspaceWithAgents([]codersdk.WorkspaceAgent{agent}) - result, err := getWorkspaceAgent(workspace, "") + result, _, err := getWorkspaceAgent(workspace, "") require.NoError(t, err) assert.Equal(t, agent.ID, result.ID) assert.Equal(t, "main", result.Name) @@ -388,7 +388,7 @@ func Test_getWorkspaceAgent(t *testing.T) { agent2 := createAgent("main2") workspace := createWorkspaceWithAgents([]codersdk.WorkspaceAgent{agent1, agent2}) - _, err := getWorkspaceAgent(workspace, "") + _, _, err := getWorkspaceAgent(workspace, "") require.Error(t, err) assert.Contains(t, err.Error(), "multiple agents found") assert.Contains(t, err.Error(), "available agents: [main1 main2]") @@ -400,10 +400,13 @@ func Test_getWorkspaceAgent(t *testing.T) { agent2 := createAgent("main2") workspace := createWorkspaceWithAgents([]codersdk.WorkspaceAgent{agent1, agent2}) - result, err := getWorkspaceAgent(workspace, "main1") + result, other, err := getWorkspaceAgent(workspace, "main1") require.NoError(t, err) assert.Equal(t, agent1.ID, result.ID) assert.Equal(t, "main1", result.Name) + assert.Len(t, other, 1) + assert.Equal(t, agent2.ID, other[0].ID) + assert.Equal(t, "main2", other[0].Name) }) t.Run("AgentNameSpecified_NotFound", func(t *testing.T) { @@ -412,7 +415,7 @@ func Test_getWorkspaceAgent(t *testing.T) { agent2 := createAgent("main2") workspace := createWorkspaceWithAgents([]codersdk.WorkspaceAgent{agent1, agent2}) - _, err := getWorkspaceAgent(workspace, "nonexistent") + _, _, err := getWorkspaceAgent(workspace, "nonexistent") require.Error(t, err) assert.Contains(t, err.Error(), `agent not found by name "nonexistent"`) assert.Contains(t, err.Error(), "available agents: [main1 main2]") @@ -422,7 +425,7 @@ func Test_getWorkspaceAgent(t *testing.T) { t.Parallel() workspace := createWorkspaceWithAgents([]codersdk.WorkspaceAgent{}) - _, err := getWorkspaceAgent(workspace, "") + _, _, err := getWorkspaceAgent(workspace, "") require.Error(t, err) assert.Contains(t, err.Error(), `workspace "test-workspace" has no agents`) }) @@ -435,7 +438,7 @@ func Test_getWorkspaceAgent(t *testing.T) { agent3 := createAgent("krypton") workspace := createWorkspaceWithAgents([]codersdk.WorkspaceAgent{agent2, agent1, agent3}) - _, err := getWorkspaceAgent(workspace, "nonexistent") + _, _, err := getWorkspaceAgent(workspace, "nonexistent") require.Error(t, err) // Available agents should be sorted alphabetically. assert.Contains(t, err.Error(), "available agents: [clark krypton zod]") diff --git a/cli/ssh_test.go b/cli/ssh_test.go index 582f8a3fdf691..d11748a51f8b8 100644 --- a/cli/ssh_test.go +++ b/cli/ssh_test.go @@ -2031,6 +2031,7 @@ func TestSSH_Container(t *testing.T) { _ = agenttest.New(t, client.URL, agentToken, func(o *agent.Options) { o.Devcontainers = true o.DevcontainerAPIOptions = append(o.DevcontainerAPIOptions, + agentcontainers.WithProjectDiscovery(false), agentcontainers.WithContainerLabelIncludeFilter("this.label.does.not.exist.ignore.devcontainers", "true"), ) }) @@ -2072,6 +2073,7 @@ func TestSSH_Container(t *testing.T) { o.Devcontainers = true o.DevcontainerAPIOptions = append(o.DevcontainerAPIOptions, agentcontainers.WithContainerCLI(mLister), + agentcontainers.WithProjectDiscovery(false), agentcontainers.WithContainerLabelIncludeFilter("this.label.does.not.exist.ignore.devcontainers", "true"), ) }) @@ -2104,7 +2106,7 @@ func TestSSH_Container(t *testing.T) { clitest.SetupConfig(t, client, root) err := inv.WithContext(ctx).Run() - require.ErrorContains(t, err, "The agent dev containers feature is experimental and not enabled by default.") + require.ErrorContains(t, err, "Dev Container feature not enabled.") }) } diff --git a/cli/start.go b/cli/start.go index 94f1a42ef7ac4..66c96cc9c4d75 100644 --- a/cli/start.go +++ b/cli/start.go @@ -169,6 +169,9 @@ func buildWorkspaceStartRequest(inv *serpent.Invocation, client *codersdk.Client if buildFlags.provisionerLogDebug { wbr.LogLevel = codersdk.ProvisionerLogLevelDebug } + if buildFlags.reason != "" { + wbr.Reason = codersdk.CreateWorkspaceBuildReason(buildFlags.reason) + } return wbr, nil } diff --git a/cli/start_test.go b/cli/start_test.go index ec5f0b4735b39..6e58b40e30778 100644 --- a/cli/start_test.go +++ b/cli/start_test.go @@ -113,10 +113,18 @@ func TestStart(t *testing.T) { version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses()) coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) - workspace := coderdtest.CreateWorkspace(t, member, template.ID) + workspace := coderdtest.CreateWorkspace(t, member, template.ID, func(request *codersdk.CreateWorkspaceRequest) { + request.RichParameterValues = []codersdk.WorkspaceBuildParameter{ + {Name: ephemeralParameterName, Value: "foo"}, // Value is required, set it to something + } + }) coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID) // Stop the workspace - workspaceBuild := coderdtest.CreateWorkspaceBuild(t, client, workspace, database.WorkspaceTransitionStop) + workspaceBuild := coderdtest.CreateWorkspaceBuild(t, client, workspace, database.WorkspaceTransitionStop, func(request *codersdk.CreateWorkspaceBuildRequest) { + request.RichParameterValues = []codersdk.WorkspaceBuildParameter{ + {Name: ephemeralParameterName, Value: "foo"}, // Value is required, set it to something + } + }) coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspaceBuild.ID) inv, root := clitest.New(t, "start", workspace.Name, "--prompt-ephemeral-parameters") @@ -167,10 +175,18 @@ func TestStart(t *testing.T) { version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses()) coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID) template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID) - workspace := coderdtest.CreateWorkspace(t, member, template.ID) + workspace := coderdtest.CreateWorkspace(t, member, template.ID, func(request *codersdk.CreateWorkspaceRequest) { + request.RichParameterValues = []codersdk.WorkspaceBuildParameter{ + {Name: ephemeralParameterName, Value: "foo"}, // Value is required, set it to something + } + }) coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID) // Stop the workspace - workspaceBuild := coderdtest.CreateWorkspaceBuild(t, client, workspace, database.WorkspaceTransitionStop) + workspaceBuild := coderdtest.CreateWorkspaceBuild(t, client, workspace, database.WorkspaceTransitionStop, func(request *codersdk.CreateWorkspaceBuildRequest) { + request.RichParameterValues = []codersdk.WorkspaceBuildParameter{ + {Name: ephemeralParameterName, Value: "foo"}, // Value is required, set it to something + } + }) coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspaceBuild.ID) inv, root := clitest.New(t, "start", workspace.Name, @@ -477,3 +493,39 @@ func TestStart_NoWait(t *testing.T) { pty.ExpectMatch("workspace has been started in no-wait mode") _ = testutil.TryReceive(ctx, t, doneChan) } + +func TestStart_WithReason(t *testing.T) { + t.Parallel() + ctx := testutil.Context(t, testutil.WaitShort) + + // Prepare user, template, workspace + client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true}) + owner := coderdtest.CreateFirstUser(t, client) + member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) + version1 := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, nil) + coderdtest.AwaitTemplateVersionJobCompleted(t, client, version1.ID) + template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version1.ID) + workspace := coderdtest.CreateWorkspace(t, member, template.ID) + coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID) + + // Stop the workspace + build := coderdtest.CreateWorkspaceBuild(t, member, workspace, database.WorkspaceTransitionStop) + coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, build.ID) + + // Start the workspace with reason + inv, root := clitest.New(t, "start", workspace.Name, "--reason", "cli") + clitest.SetupConfig(t, member, root) + doneChan := make(chan struct{}) + pty := ptytest.New(t).Attach(inv) + go func() { + defer close(doneChan) + err := inv.Run() + assert.NoError(t, err) + }() + + pty.ExpectMatch("workspace has been started") + _ = testutil.TryReceive(ctx, t, doneChan) + + workspace = coderdtest.MustWorkspace(t, member, workspace.ID) + require.Equal(t, codersdk.BuildReasonCLI, workspace.LatestBuild.Reason) +} diff --git a/cli/templatepresets.go b/cli/templatepresets.go new file mode 100644 index 0000000000000..240abec313a16 --- /dev/null +++ b/cli/templatepresets.go @@ -0,0 +1,177 @@ +package cli + +import ( + "fmt" + "strconv" + "strings" + + "golang.org/x/xerrors" + + "github.com/coder/coder/v2/cli/cliui" + "github.com/coder/coder/v2/codersdk" + "github.com/coder/serpent" +) + +func (r *RootCmd) templatePresets() *serpent.Command { + cmd := &serpent.Command{ + Use: "presets", + Short: "Manage presets of the specified template", + Aliases: []string{"preset"}, + Long: FormatExamples( + Example{ + Description: "List presets for the active version of a template", + Command: "coder templates presets list my-template", + }, + Example{ + Description: "List presets for a specific version of a template", + Command: "coder templates presets list my-template --template-version my-template-version", + }, + ), + Handler: func(inv *serpent.Invocation) error { + return inv.Command.HelpHandler(inv) + }, + Children: []*serpent.Command{ + r.templatePresetsList(), + }, + } + + return cmd +} + +func (r *RootCmd) templatePresetsList() *serpent.Command { + defaultColumns := []string{ + "name", + "description", + "parameters", + "default", + "desired prebuild instances", + } + formatter := cliui.NewOutputFormatter( + cliui.TableFormat([]TemplatePresetRow{}, defaultColumns), + cliui.JSONFormat(), + ) + client := new(codersdk.Client) + orgContext := NewOrganizationContext() + + var templateVersion string + + cmd := &serpent.Command{ + Use: "list