diff --git a/cli/azd/.vscode/cspell.yaml b/cli/azd/.vscode/cspell.yaml index 095264a786b..c2d9f9e1b13 100644 --- a/cli/azd/.vscode/cspell.yaml +++ b/cli/azd/.vscode/cspell.yaml @@ -187,6 +187,28 @@ overrides: - filename: "**/internal/agent/types.go" words: - billionized + - filename: extensions/microsoft.azd.emulators/** + words: + - AMQP + - appconfig + - asrs + - awps + - azuredataexplorer + - devstoreaccount + - durabletask + - kustainer + - kustodata + - OPTOUT + - SASL + - sbemulatorns + - signalr + - SQLCMDPASSWORD + - sqlcmd + - staticwebapps + - TASKHUB + - trimpath + - vnext + - webpubsub - filename: internal/appdetect/aspire_polyglot.go words: - pylock diff --git a/cli/azd/extensions/microsoft.azd.emulators/README.md b/cli/azd/extensions/microsoft.azd.emulators/README.md new file mode 100644 index 00000000000..c62116c8bac --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/README.md @@ -0,0 +1,152 @@ +# Azure Emulators extension + +Launch first-party Azure service emulators and print the connection settings needed by a local application. This is an **alpha**, development-only extension, not a way to host production Azure services. + +## Build and install locally + +Prerequisites: an azd build with beta `add-provider` support (such as the `azd-add-provider` branch), the repository's Go toolchain, and Docker running **Linux containers** with Docker Compose 2.23.1 or later. SignalR, Static Web Apps and Web PubSub also require Docker image-build support. Images and packages are downloaded on first use. + +From this directory: + +```bash +azd extension install microsoft.azd.extensions +azd x build --skip-install +azd x pack --bundle --output ./bin/emulators.zip +azd extension install ./bin/emulators.zip +azd emulators --help +``` + +These commands build and install a self-contained bundle for the current platform. After the initial installation, `azd x build` is sufficient to rebuild the installed binary. There are no published registry artifacts for this extension yet. + +For standalone development without installing into azd: + +```bash +go build -o ./bin/emulators . +./bin/emulators storage +``` + +On Windows, use `.\bin\emulators.exe`. `build.sh` and `build.ps1` produce the standard extension artifact names for all six supported OS/architecture pairs. Set `EXTENSION_PLATFORM` to a single pair, such as `linux/arm64`, to build just that target. + +## Add emulators to a project + +After installing the extension, run `azd add` and choose an item in the **Emulators** category. This edits `azure.yaml` without starting Docker. Subsequent selections go into the same `emulators` infrastructure entry: + +```yaml +infra: + layers: + - name: emulators + provider: emulators + config: + storage: {} + staticwebapps: + directory: dist +``` + +The provisioning phase of `azd up` (or `azd provision`) starts the declared emulators locally and waits for readiness. Docker is needed at that point, not at `azd add`. These commands still have azd's normal Azure sign-in requirements, though the emulator provider itself creates no Azure resources. `azd down` stops and removes the declared emulators and their local data for that project and environment. Run it before removing a declaration you no longer need. + +For this alpha release, provisioning a declared emulator accepts its required license terms by default without prompting. Set `acceptLicense: false` under the emulator's key in `azure.yaml` to block provisioning and see the terms. Standalone commands still require `--accept-license` where applicable. + +`azd add` shows unavailable emulators as disabled, with the reason. Provisioning checks the same requirements before starting any emulator in the layer: Docker must be available, `docker compose` must be version 2.23.1 or later, and the Docker daemon must run Linux containers. Service Bus and Azure Data Explorer (Kusto) also require an AMD64 daemon. The extension does not install anything or use the standalone `docker-compose` command. + +The add menu writes `infra.layers` or `layers[].infra`, depending on the project's layout. Move existing flat infrastructure into a layer first. Project instances use the default ports and separate state from the standalone commands below. Default ports are still shared across the machine. + +## Commands + +Each emulator has its own command. Launches wait for running containers and readiness checks before printing connection information. + +| Command | Default host ports | Connection information | +|---|---|---| +| `azd emulators storage` | 10000 (Blob), 10001 (Queue), 10002 (Table) | Storage connection string and service endpoints | +| `azd emulators cosmosdb` | 8081 (HTTPS gateway), 1234 (Data Explorer), 18081 (health) | NoSQL gateway endpoint, development key, connection string, explorer URL | +| `azd emulators servicebus --accept-license` | 5672 (AMQP), 5300 (management) | Data/admin connection strings, queue, topic and subscription | +| `azd emulators eventhubs --accept-license` | 5673 (AMQP), 9092 (Kafka), 5301 (health) | AMQP connection string, event hub, consumer group and Kafka SASL settings | +| `azd emulators appconfig` | 8483 | Anonymous App Configuration endpoint and web UI | +| `azd emulators kusto --accept-license` | 8085 | Kusto endpoint and unauthenticated connection string | +| `azd emulators durabletask` | 8080 (scheduler), 8082 (dashboard) | Scheduler connection string, task hub and dashboard URL | +| `azd emulators signalr` | 8888 | Serverless SignalR connection string | +| `azd emulators staticwebapps --directory ./dist` | 4280 | Website URL and served directory | +| `azd emulators webpubsub` | 8084 | Preview Web PubSub connection string | +| `azd emulators sqldb --accept-license` | 1433 | Preview Azure SQL Database connection string and generated SQL credentials | + +Default host ports do not overlap, and dependencies have no published ports. Each emulator runs in an isolated Compose project. All published ports bind to `127.0.0.1`, not external interfaces. Printed settings are for applications running on the host. + +### Connection output and automation + +After `azd up` or `azd provision`, connection settings for the emulator layer are available in the active azd environment. The keys use `AZD_EMULATOR__` to avoid overwriting cloud resource outputs or another emulator's settings. For example: + +```bash +azd env get-value AZD_EMULATOR_STORAGE_AZURE_STORAGE_CONNECTION_STRING +azd env get-value AZD_EMULATOR_EVENTHUBS_EVENTHUBS_CONNECTION_STRING +``` + +These settings can include development credentials. Keep your azd environment files private and use these values only for local development. `azd down` removes the settings for the emulator instances it stops. + +```bash +azd emulators storage +azd emulators servicebus --accept-license --output json +azd emulators storage --output none +``` + +Standalone command output lists named connection settings. JSON output contains `emulator`, `status`, `projectName`, `connections` (an array of `{ "name": "...", "value": "..." }`) and optional `notes`. Progress goes to stderr, so stdout can be piped directly to a JSON parser. `--output none` suppresses normal output. Standalone commands do not write credentials into an azd environment. + +Service Bus creates `queue.1`, `topic.1` and `subscription.1`. Its administration connection string uses the management port, not the AMQP port. Event Hubs creates `eh1` with two partitions and consumer group `cg1`. Use the printed Kafka SASL password for Kafka clients, not the AMQP connection string: the emulator uses its endpoint to advertise the Kafka listener. + +### Reuse, ports and cleanup + +```bash +azd emulators storage --port 11000 --queue-port 11001 --table-port 11002 +azd emulators storage +azd emulators storage --stop +``` + +Repeating a launch reuses the saved configuration, container data and generated passwords. Explicitly changing a saved port, directory or upstream URL is rejected. Stop the instance before launching it with different settings. The normal default launch timeout is five minutes, including image pulls and builds. Use `--timeout 10m` for a slow first launch. + +`--stop` removes the emulator's containers, dependencies and anonymous volumes, then deletes its saved state. **All emulator data is discarded.** Downloaded images and build cache remain. Launch-only flags cannot be combined with `--stop`. + +State is private to the azd configuration directory, under `emulators/` (normally `~/.azd/emulators/`, respecting azd's existing `AZD_CONFIG_DIR` override). SQL passwords and SignalR upstream configuration are stored there with private file permissions. Standalone commands keep one saved instance per emulator per azd configuration directory, shared across projects and environments. Explicit `--environment` flags are rejected by those commands. Standalone commands do not require Azure login or a subscription. + +If launch fails, no successful connection result is printed. Partial containers and state remain available for diagnosis and `--stop` cleanup. The error includes the isolated Compose project name when readiness fails. + +### SignalR upstream + +```bash +azd emulators signalr \ + --upstream-url http://host.docker.internal:7071/runtime/webhooks/signalr +``` + +The default upstream is the URL above. It is resolved **inside** the container. `localhost` would refer to the emulator container, not the host. The extension adds Docker's `host.docker.internal` host-gateway mapping. + +### Limits and platform requirements + +These are Microsoft's development/test emulators, with their upstream limitations: + +- **Storage:** Azurite emulates Blob, Queue and Table Storage. Table support is preview. Azure Files and Data Lake Storage Gen2 are not included. +- **Cosmos DB:** Uses the vNext emulator's NoSQL gateway API, not direct mode or other Cosmos DB APIs. Authentication is not enforced. Trust its self-signed HTTPS certificate in the local SDK. +- **Service Bus:** Includes a SQL Server 2022 dependency. The extension requires a native AMD64 Docker daemon and does not probe x64 emulation on ARM64. Emulator data is not durable across restarts. Microsoft's native administration SDK support is limited to .NET. +- **Event Hubs:** Includes a private Azurite dependency. Data is not durable across restarts, and Kafka support is limited to producer/consumer scenarios. +- **App Configuration:** Enables anonymous owner access for local SDKs that support anonymous authentication. +- **Kusto:** Requires an x64 CPU with SSE4.2 and AVX2. Managed ingestion and authentication are not available. +- **Durable Task:** Uses the emulator's `default` task hub and unauthenticated scheduler endpoint. +- **SignalR:** Supports serverless scenarios and transient transport, not a replacement for the hosted SignalR service. +- **Static Web Apps:** Serves the selected static-content directory read-only with local routing and mock authentication. It does not launch a Functions API. +- **Web PubSub:** Uses Microsoft's beta emulator. State is in memory and message TTL expiration is not enforced. +- **Azure SQL Database:** Uses the preview local Azure SQL Database engine, including native x64/ARM64 images. It is not a full managed-service replica. `sa` credentials and `TrustServerCertificate=True` are for local development. + +Review the upstream license URLs shown by commands that require `--accept-license`. Pass the flag only after accepting the emulator and dependency terms. Direct `azd emulators` commands never prompt for license confirmation, so behavior is identical in scripts and with `--no-prompt`. + +Legacy Windows Cloud Services, the archived Event Grid emulator and third-party emulators are outside this extension's scope. + +## Development + +The shared lifecycle/state/readiness code lives in `internal/emulator/`. Each service has a separate implementation in `internal/emulators/`. Command registration and output live in `internal/cmd/`. + +After a successful `azd add`, the listener exits quietly if azd resets the RPC connection during shutdown. Other listener errors are still reported. + +```bash +# From cli/azd +go test ./extensions/microsoft.azd.emulators/... +go test -race ./extensions/microsoft.azd.emulators/... +golangci-lint run ./extensions/microsoft.azd.emulators/... +``` + +The service-first shape (`azd emulators `) intentionally follows this extension's launcher interface rather than the verb-first preference in the [extension style guide](../../docs/extensions/extensions-style-guide.md). diff --git a/cli/azd/extensions/microsoft.azd.emulators/build.ps1 b/cli/azd/extensions/microsoft.azd.emulators/build.ps1 new file mode 100644 index 00000000000..0ff36f4e69b --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/build.ps1 @@ -0,0 +1,36 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +$ErrorActionPreference = 'Stop' +Push-Location $PSScriptRoot + +try { + $outputDir = if ($env:OUTPUT_DIR) { $env:OUTPUT_DIR } else { Join-Path $PSScriptRoot 'bin' } + $extensionId = if ($env:EXTENSION_ID) { $env:EXTENSION_ID } else { 'microsoft.azd.emulators' } + $binaryName = $extensionId -replace '\.', '-' + New-Item -ItemType Directory -Force -Path $outputDir | Out-Null + + $platforms = @('windows/amd64', 'windows/arm64', 'darwin/amd64', 'darwin/arm64', 'linux/amd64', 'linux/arm64') + if ($env:EXTENSION_PLATFORM) { + $platforms = @($env:EXTENSION_PLATFORM) + } + + foreach ($platform in $platforms) { + $os, $arch = $platform -split '/' + $output = Join-Path $outputDir "$binaryName-$os-$arch" + if ($os -eq 'windows') { + $output += '.exe' + } + Write-Host "Building $platform..." + $env:CGO_ENABLED = '0' + $env:GOOS = $os + $env:GOARCH = $arch + go build -trimpath -o $output . + if ($LASTEXITCODE -ne 0) { + throw "Build failed for $platform." + } + } +} +finally { + Pop-Location +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/build.sh b/cli/azd/extensions/microsoft.azd.emulators/build.sh new file mode 100755 index 00000000000..208e8c8d8b2 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/build.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +set -euo pipefail +cd "$(dirname "$0")" + +output_dir="${OUTPUT_DIR:-$PWD/bin}" +extension_id="${EXTENSION_ID:-microsoft.azd.emulators}" +binary_name="${extension_id//./-}" +mkdir -p "$output_dir" + +platforms=("windows/amd64" "windows/arm64" "darwin/amd64" "darwin/arm64" "linux/amd64" "linux/arm64") +if [[ -n "${EXTENSION_PLATFORM:-}" ]]; then + platforms=("$EXTENSION_PLATFORM") +fi + +for platform in "${platforms[@]}"; do + os="${platform%/*}" + arch="${platform#*/}" + output="$output_dir/$binary_name-$os-$arch" + if [[ "$os" == "windows" ]]; then + output+=".exe" + fi + echo "Building $platform..." + CGO_ENABLED=0 GOOS="$os" GOARCH="$arch" go build -trimpath -o "$output" . +done diff --git a/cli/azd/extensions/microsoft.azd.emulators/extension.yaml b/cli/azd/extensions/microsoft.azd.emulators/extension.yaml new file mode 100644 index 00000000000..8136a8e701d --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/extension.yaml @@ -0,0 +1,28 @@ +# yaml-language-server: $schema=../extension.schema.json +id: microsoft.azd.emulators +namespace: emulators +displayName: Azure Emulators +description: Launch local Azure service emulators and display their connection information. +usage: azd emulators [options] +version: 0.1.0 +requiredAzdVersion: ">=1.39.0-beta.1" +language: go +capabilities: + - custom-commands + - metadata + - add-provider + - provisioning-provider +providers: + - name: emulators + type: provisioning-provider + description: Start local Azure emulators declared in an infrastructure layer. +examples: + - name: servicebus + description: Start Service Bus and its SQL Server dependency. + usage: azd emulators servicebus --accept-license + - name: storage + description: Start Azurite and print connection information as JSON. + usage: azd emulators storage --output json + - name: stop + description: Stop and remove the Service Bus emulator and its dependency. + usage: azd emulators servicebus --stop diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/cmd/add_provider.go b/cli/azd/extensions/microsoft.azd.emulators/internal/cmd/add_provider.go new file mode 100644 index 00000000000..47f9ecb9b40 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/cmd/add_provider.go @@ -0,0 +1,286 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package cmd + +import ( + "context" + "errors" + "fmt" + "maps" + "slices" + "strings" + "sync/atomic" + + "github.com/spf13/cobra" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/structpb" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulators" + "github.com/azure/azure-dev/cli/azd/pkg/azdext" + "github.com/azure/azure-dev/cli/azd/pkg/azdext/contracts/v1beta" +) + +const providerName = "emulators" + +func newProviderListener( + resolveLocal func() (launcher, error), resolveProject func(string, string) (launcher, error), +) *cobra.Command { + var addSucceeded atomic.Bool + var listen *cobra.Command + listen = azdext.NewListenCommand(func(host *azdext.ExtensionHost) { + client := host.Client() + definitions := emulators.All() + items := emulatorAddItems(listen.Context(), definitions, resolveLocal) + host.WithBetaAddProvider("Emulators", items, func(ctx context.Context, id string) error { + addSucceeded.Store(false) + for _, item := range items { + if item.GetId() == id && item.GetDisabledReason() != "" { + return &azdext.LocalError{ + Category: azdext.LocalErrorCategoryValidation, Code: azdext.AddItemUnavailableCode, + Message: item.GetDisabledReason(), + } + } + } + err := addEmulator(ctx, client.Project(), client.Prompt(), definitions, id) + addSucceeded.Store(err == nil && ctx.Err() == nil) + return err + }) + host.WithProvisioningProvider(providerName, func() azdext.ProvisioningProvider { + return &emulatorProvider{ + definitions: definitions, resolve: resolveProject, + currentEnvironment: func(ctx context.Context) (string, error) { + current, err := client.Environment().GetCurrent(ctx, &azdext.EmptyRequest{}) + if err != nil { + return "", fmt.Errorf("resolving azd environment: %w", err) + } + return current.GetEnvironment().GetName(), nil + }, + } + }) + }) + runListen := listen.RunE + listen.RunE = func(cmd *cobra.Command, args []string) error { + addSucceeded.Store(false) + err := runListen(cmd, args) + return addListenerError(addSucceeded.Load(), err) + } + return listen +} + +func addListenerError(addSucceeded bool, err error) error { + // azd can reset the listener connection while tearing down a successful add. + if addSucceeded && status.Code(err) == codes.Unavailable && + strings.HasPrefix(err.Error(), "receiver error: stream receive failed: ") && + strings.HasSuffix(err.Error(), "connection reset by peer") { + return nil + } + return err +} + +func emulatorAddItems( + ctx context.Context, definitions []emulator.Definition, resolve func() (launcher, error), +) []*v1beta.AddItem { + var dockerHost emulator.DockerHost + service, dockerErr := resolve() + if dockerErr == nil { + dockerHost, dockerErr = service.CheckDocker(ctx) + } + + items := make([]*v1beta.AddItem, 0, len(definitions)) + for _, definition := range definitions { + item := &v1beta.AddItem{Id: definition.Name, DisplayName: definition.DisplayName} + err := dockerErr + if err == nil { + err = dockerHost.CheckRequirements(definition) + } + if err != nil { + item.DisabledReason = err.Error() + } + items = append(items, item) + } + return items +} + +func addEmulator( + ctx context.Context, + project azdext.ProjectServiceClient, + prompt azdext.PromptServiceClient, + definitions []emulator.Definition, + id string, +) error { + index := slices.IndexFunc(definitions, func(definition emulator.Definition) bool { return definition.Name == id }) + if index < 0 { + return fmt.Errorf("unknown emulator %q", id) + } + read := func(path string) (*azdext.GetProjectConfigValueResponse, error) { + return project.GetConfigValue(ctx, &azdext.GetProjectConfigValueRequest{Path: path}) + } + top, err := read("layers") + if err != nil { + return err + } + path := "infra.layers" + var projectLayers []any + topIndex := -1 + var infra map[string]any + if top.GetFound() { + path = "layers" + var ok bool + projectLayers, ok = top.GetValue().AsInterface().([]any) + if !ok { + return errors.New("layers must be a sequence") + } + infra = map[string]any{"layers": []any{}} + emulatorIndex := -1 + for i, raw := range projectLayers { + layer, ok := raw.(map[string]any) + if !ok { + return fmt.Errorf("layers[%d] must be a mapping", i) + } + if layer["name"] == providerName { + topIndex = i + } + if entries, found := layer["infra"]; found { + if err := scanEmulatorEntry(entries, i, &emulatorIndex); err != nil { + return err + } + } + } + if emulatorIndex >= 0 { + topIndex = emulatorIndex + } + if topIndex >= 0 { + if entries, found := projectLayers[topIndex].(map[string]any)["infra"]; found { + infra["layers"] = entries + } + } + } else { + response, err := read("infra") + if err != nil { + return err + } + if response.GetFound() && response.GetValue().GetStructValue() == nil { + return errors.New("infra must be a mapping") + } + infra = response.GetValue().GetStructValue().AsMap() + } + layers, target, err := emulatorLayers(infra) + if err != nil { + return err + } + config := map[string]any{} + if target >= 0 { + entry := layers[target].(map[string]any) + if raw, present := entry["config"]; present { + existing, ok := raw.(map[string]any) + if !ok { + return errors.New("emulators layer config must be a mapping") + } + maps.Copy(config, existing) + } + } + if _, exists := config[id]; exists { + return &azdext.LocalError{ + Category: azdext.LocalErrorCategoryValidation, Code: azdext.AddItemUnavailableCode, + Message: definitions[index].DisplayName + " is already declared in the emulators layer.", + } + } + settings := map[string]any{} + if definitions[index].HasDirectory { + answer, err := prompt.Prompt(ctx, &azdext.PromptRequest{Options: &azdext.PromptOptions{ + Message: "Static-content directory to serve read-only (relative to the project)", + }}) + if err != nil { + return err + } + directory := strings.TrimSpace(answer.GetValue()) + if !validContentDirectory(directory) { + return &azdext.LocalError{ + Category: azdext.LocalErrorCategoryValidation, Code: azdext.AddItemUnavailableCode, + Message: "Enter a project-relative directory without parent traversal.", + } + } + settings["directory"] = directory + } + config[id] = settings + if target < 0 { + layers = append(layers, map[string]any{"name": providerName, "provider": providerName, "config": config}) + } else { + layers[target].(map[string]any)["config"] = config + } + var updated any = layers + if path == "layers" { + if topIndex < 0 { + projectLayers = append(projectLayers, map[string]any{"name": providerName, "infra": layers}) + } else { + projectLayers[topIndex].(map[string]any)["infra"] = layers + } + updated = projectLayers + } + value, err := structpb.NewValue(updated) + if err != nil { + return err + } + _, err = project.SetConfigValue(ctx, &azdext.SetProjectConfigValueRequest{Path: path, Value: value}) + return err +} + +func scanEmulatorEntry(raw any, index int, found *int) error { + entries, ok := raw.([]any) + if !ok { + return fmt.Errorf("layers[%d].infra must be a sequence", index) + } + for _, rawEntry := range entries { + entry, ok := rawEntry.(map[string]any) + if !ok { + return fmt.Errorf("layers[%d].infra entries must be mappings", index) + } + if entry["provider"] == providerName { + if *found >= 0 { + return errors.New("only one emulators provisioning entry is supported") + } + *found = index + } + } + return nil +} + +func emulatorLayers(infra map[string]any) ([]any, int, error) { + raw, found := infra["layers"] + if !found { + if len(infra) > 0 { + return nil, -1, errors.New("move existing infrastructure into infra.layers before adding emulators") + } + return nil, -1, nil + } + layers, ok := raw.([]any) + if !ok { + return nil, -1, errors.New("infra.layers must be a sequence") + } + target := -1 + nameTaken := false + for i, rawLayer := range layers { + layer, ok := rawLayer.(map[string]any) + if !ok { + return nil, -1, fmt.Errorf("infra.layers[%d] must be a mapping", i) + } + nameTaken = nameTaken || layer["name"] == providerName + provider := layer["provider"] + if provider == nil || provider == "" { + provider = infra["provider"] + } + if provider == providerName { + if target >= 0 { + return nil, -1, errors.New("only one emulators provisioning entry is supported") + } + target = i + } + } + if target < 0 && nameTaken { + return nil, -1, errors.New("the infrastructure layer name emulators is already in use") + } + return layers, target, nil +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/cmd/provisioning.go b/cli/azd/extensions/microsoft.azd.emulators/internal/cmd/provisioning.go new file mode 100644 index 00000000000..c842a5904e8 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/cmd/provisioning.go @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package cmd + +import ( + "context" + "errors" + "fmt" + "maps" + "path/filepath" + "slices" + "strings" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" + "github.com/azure/azure-dev/cli/azd/pkg/azdext" + "github.com/azure/azure-dev/cli/azd/pkg/grpcbroker" +) + +type emulatorProvider struct { + definitions []emulator.Definition + resolve func(string, string) (launcher, error) + currentEnvironment func(context.Context) (string, error) + projectDir string + entries []emulatorEntry +} + +type emulatorEntry struct { + definition emulator.Definition + request emulator.Request +} + +func validContentDirectory(path string) bool { + return filepath.IsLocal(path) && !slices.Contains(strings.Split(filepath.ToSlash(path), "/"), "..") +} + +func (p *emulatorProvider) Initialize(_ context.Context, projectDir string, options *azdext.ProvisioningOptions) error { + projectDir, err := filepath.EvalSymlinks(projectDir) + if err != nil { + return fmt.Errorf("resolving emulator project directory: %w", err) + } + p.projectDir = projectDir + config := options.GetConfig().AsMap() + if len(config) == 0 { + return errors.New("declare at least one emulator in the emulators layer config") + } + entries := make([]emulatorEntry, 0, len(config)) + for _, id := range slices.Sorted(maps.Keys(config)) { + index := slices.IndexFunc(p.definitions, func(definition emulator.Definition) bool { return definition.Name == id }) + if index < 0 { + return fmt.Errorf("unknown emulator %q in layer config", id) + } + definition := p.definitions[index] + settings, ok := config[id].(map[string]any) + if !ok { + return fmt.Errorf("emulator %q settings must be a mapping", id) + } + request := emulator.Request{ + Timeout: defaultTimeout, + AcceptLicense: len(definition.LicenseURLs) > 0, + Options: emulator.Options{Ports: make(map[string]int, len(definition.Ports))}, + } + for _, port := range definition.Ports { + request.Options.Ports[port.Flag] = port.Default + } + if definition.HasUpstream { + request.Options.UpstreamURL = defaultUpstreamURL + } + if definition.HasDirectory { + directory, ok := settings["directory"].(string) + if !ok || !validContentDirectory(directory) { + return fmt.Errorf("emulator %q requires a project-relative directory", id) + } + request.Options.Directory = filepath.Join(p.projectDir, directory) + request.Changed = map[string]bool{"directory": true} + } + for key := range settings { + switch { + case key == "directory" && definition.HasDirectory: + case key == "acceptLicense" && len(definition.LicenseURLs) > 0: + accepted, ok := settings[key].(bool) + if !ok { + return fmt.Errorf("emulator %q acceptLicense must be a boolean", id) + } + request.AcceptLicense = accepted + default: + return fmt.Errorf("unknown setting %q for emulator %q", key, id) + } + } + entries = append(entries, emulatorEntry{definition: definition, request: request}) + } + p.entries = entries + return nil +} + +func (p *emulatorProvider) Deploy( + ctx context.Context, progress grpcbroker.ProgressFunc, +) (*azdext.ProvisioningDeployResult, error) { + entries := slices.Clone(p.entries) + for i := range entries { + definition := entries[i].definition + if len(definition.LicenseURLs) > 0 && !entries[i].request.AcceptLicense { + return nil, &azdext.LocalError{ + Category: azdext.LocalErrorCategoryValidation, Code: "license_not_accepted", + Message: definition.DisplayName + " requires license acceptance before it can start.", + Suggestion: fmt.Sprintf("Review %s. If you accept, set acceptLicense: true under %s in azure.yaml.", + strings.Join(definition.LicenseURLs, ", "), definition.Name), + } + } + if !entries[i].definition.HasDirectory { + continue + } + path, err := filepath.EvalSymlinks(entries[i].request.Options.Directory) + if err != nil { + return nil, fmt.Errorf("resolving static-content directory: %w", err) + } + rel, err := filepath.Rel(p.projectDir, path) + if err != nil || !validContentDirectory(rel) { + return nil, errors.New("static-content directory must be inside the project") + } + entries[i].request.Options.Directory = path + } + service, err := p.resolveLauncher(ctx) + if err != nil { + return nil, err + } + for _, entry := range entries { + if err := service.CheckRequirements(ctx, entry.definition); err != nil { + return nil, err + } + } + outputs := make(map[string]*azdext.ProvisioningOutputParameter) + for _, entry := range entries { + if progress != nil { + progress("Starting " + entry.definition.DisplayName + " locally") + } + result, err := service.Run(ctx, entry.definition, entry.request) + if err != nil { + return nil, fmt.Errorf("provisioning local emulator %s: %w", entry.definition.Name, err) + } + for _, connection := range result.Connections { + key := emulatorOutputKey(entry.definition.Name, connection.Name) + outputs[key] = &azdext.ProvisioningOutputParameter{Type: "string", Value: connection.Value} + } + } + return &azdext.ProvisioningDeployResult{Deployment: &azdext.ProvisioningDeployment{Outputs: outputs}}, nil +} + +func emulatorOutputKey(emulatorName, connectionName string) string { + emulatorName = strings.ReplaceAll(emulatorName, "-", "_") + return "AZD_EMULATOR_" + strings.ToUpper(emulatorName+"_"+connectionName) +} + +func (p *emulatorProvider) Preview( + _ context.Context, _ grpcbroker.ProgressFunc, +) (*azdext.ProvisioningPreviewResult, error) { + var names []string + for _, entry := range p.entries { + names = append(names, entry.definition.DisplayName) + } + return &azdext.ProvisioningPreviewResult{Preview: &azdext.ProvisioningDeploymentPreview{ + Summary: "Start local emulators: " + strings.Join(names, ", "), + }}, nil +} + +func (p *emulatorProvider) Destroy( + ctx context.Context, _ *azdext.ProvisioningDestroyOptions, _ grpcbroker.ProgressFunc, +) (*azdext.ProvisioningDestroyResult, error) { + service, err := p.resolveLauncher(ctx) + if err != nil { + return nil, err + } + var invalidated []string + for _, entry := range p.entries { + result, err := service.Run(ctx, entry.definition, emulator.Request{Stop: true, Timeout: defaultTimeout}) + if emulator.IsInstanceMissing(err) { + continue + } + if err != nil { + return nil, fmt.Errorf("stopping local emulator %s: %w", entry.definition.Name, err) + } + for _, name := range result.RemovedConnectionNames { + invalidated = append(invalidated, emulatorOutputKey(entry.definition.Name, name)) + } + } + return &azdext.ProvisioningDestroyResult{InvalidatedEnvKeys: invalidated}, nil +} + +func (p *emulatorProvider) resolveLauncher(ctx context.Context) (launcher, error) { + environment, err := p.currentEnvironment(ctx) + if err != nil { + return nil, err + } + if environment == "" { + return nil, errors.New("no active azd environment for the emulators layer") + } + return p.resolve(p.projectDir, environment) +} + +func (*emulatorProvider) State( + context.Context, *azdext.ProvisioningStateOptions, +) (*azdext.ProvisioningStateResult, error) { + return &azdext.ProvisioningStateResult{State: &azdext.ProvisioningState{}}, nil +} + +func (*emulatorProvider) EnsureEnv(context.Context) error { return nil } + +func (*emulatorProvider) Parameters(context.Context) ([]*azdext.ProvisioningParameter, error) { + return nil, nil +} + +func (*emulatorProvider) PlannedOutputs(context.Context) ([]*azdext.ProvisioningPlannedOutput, error) { + return nil, nil +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/cmd/root.go b/cli/azd/extensions/microsoft.azd.emulators/internal/cmd/root.go new file mode 100644 index 00000000000..7c4a615eb3d --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/cmd/root.go @@ -0,0 +1,226 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package cmd + +import ( + "context" + "encoding/json" + "fmt" + "io" + "path/filepath" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulators" + "github.com/azure/azure-dev/cli/azd/pkg/azdext" + "github.com/azure/azure-dev/cli/azd/pkg/config" + "github.com/azure/azure-dev/cli/azd/pkg/exec" + "github.com/azure/azure-dev/cli/azd/pkg/ioc" +) + +const extensionID = "microsoft.azd.emulators" + +const ( + defaultTimeout = 5 * time.Minute + defaultDirectory = "." + defaultUpstreamURL = "http://host.docker.internal:7071/runtime/webhooks/signalr" +) + +type launcher interface { + CheckDocker(context.Context) (emulator.DockerHost, error) + CheckRequirements(context.Context, emulator.Definition) error + Run(context.Context, emulator.Definition, emulator.Request) (emulator.Result, error) +} + +// NewRootCommand creates the emulators extension command tree for the supplied version. +func NewRootCommand(version string) *cobra.Command { + container := ioc.NewNestedContainer(nil) + container.MustRegisterSingleton(func() exec.CommandRunner { + return exec.NewCommandRunner(&exec.RunnerOptions{ + Stdin: strings.NewReader(""), Stdout: io.Discard, Stderr: io.Discard, + }) + }) + container.MustRegisterSingleton(func(runner exec.CommandRunner) (*emulator.Manager, error) { + directory, err := config.GetUserConfigDir() + if err != nil { + return nil, fmt.Errorf("resolve azd configuration directory: %w", err) + } + directory, err = filepath.Abs(filepath.Join(directory, "emulators")) + if err != nil { + return nil, err + } + return emulator.NewManager(runner, directory), nil + }) + resolveManager := func() (*emulator.Manager, error) { + var manager *emulator.Manager + if err := container.Resolve(&manager); err != nil { + return nil, err + } + return manager, nil + } + return newRootCommand(version, func() (launcher, error) { return resolveManager() }, + func(projectDir, environment string) (launcher, error) { + manager, err := resolveManager() + if err != nil { + return nil, err + } + return manager.ForProject(projectDir, environment), nil + }) +} + +func newRootCommand( + version string, resolve func() (launcher, error), resolveProject func(string, string) (launcher, error), +) *cobra.Command { + root, extCtx := azdext.NewExtensionRootCommand(azdext.ExtensionCommandOptions{ + Name: "emulators", Version: version, + Short: "Launch local Azure emulators and display connection information.", + Long: "Launch local Azure service emulators using Docker Compose. Commands return after the emulator is ready.\n" + + "Run the same command again to reuse its saved settings, or add --stop to remove the instance and its data.", + }) + root.SilenceUsage = true + root.SilenceErrors = true + root.CompletionOptions.DisableDefaultCmd = true + root.SetHelpCommand(&cobra.Command{Hidden: true}) + preRun := root.PersistentPreRunE + root.PersistentPreRunE = func(command *cobra.Command, args []string) error { + if preRun != nil { + if err := preRun(command, args); err != nil { + return err + } + } + var writer io.Writer = io.Discard + if extCtx.Debug && extCtx.OutputFormat != "none" { + writer = command.ErrOrStderr() + } + azdext.SetupLogging(azdext.LoggerOptions{Debug: extCtx.Debug, Writer: writer}) + return nil + } + for _, definition := range emulators.All() { + root.AddCommand(newEmulatorCommand(definition, extCtx, resolve)) + } + root.AddCommand(newProviderListener(resolve, resolveProject)) + root.AddCommand(&cobra.Command{ + Use: "metadata", Hidden: true, Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return json.NewEncoder(cmd.OutOrStdout()).Encode( + azdext.GenerateExtensionMetadata("1.0", extensionID, root)) + }, + }) + return root +} + +func newEmulatorCommand( + definition emulator.Definition, extCtx *azdext.ExtensionContext, resolve func() (launcher, error), +) *cobra.Command { + request := emulator.Request{Options: emulator.Options{Ports: map[string]int{}}} + command := &cobra.Command{ + Use: definition.Name, Short: definition.Description, Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + request.Changed = map[string]bool{} + for _, port := range definition.Ports { + value, err := cmd.Flags().GetInt(port.Flag) + if err != nil { + return err + } + request.Options.Ports[port.Flag] = value + request.Changed[port.Flag] = cmd.Flags().Changed(port.Flag) + } + for _, flag := range []string{"stop", "timeout", "accept-license", "directory", "upstream-url", "environment"} { + request.Changed[flag] = cmd.Flags().Changed(flag) + } + return runEmulator(cmd.Context(), cmd, extCtx.OutputFormat, resolve, definition, request) + }, + } + for _, port := range definition.Ports { + command.Flags().Int(port.Flag, port.Default, port.Description) + } + command.Flags().BoolVar(&request.Stop, "stop", false, "Stop and remove this emulator, its dependencies and local data") + command.Flags().DurationVar(&request.Timeout, "timeout", defaultTimeout, "Maximum time to launch or stop the emulator") + if len(definition.LicenseURLs) > 0 { + command.Flags().BoolVar(&request.AcceptLicense, "accept-license", false, + "Accept the emulator and dependency license terms") + } + if definition.HasDirectory { + command.Flags().StringVar(&request.Options.Directory, "directory", defaultDirectory, + "Static-content directory to serve read-only") + } + if definition.HasUpstream { + command.Flags().StringVar(&request.Options.UpstreamURL, "upstream-url", + defaultUpstreamURL, "Upstream URL reachable from inside the container") + } + return azdext.RegisterFlagOptions(command, azdext.FlagOptions{ + Name: "output", AllowedValues: []string{"default", "table", "json", "none"}, + }) +} + +func runEmulator( + ctx context.Context, + cmd *cobra.Command, + format string, + resolve func() (launcher, error), + definition emulator.Definition, + request emulator.Request, +) error { + if err := emulator.ValidateRequest(definition, request); err != nil { + return err + } + if definition.HasDirectory && !request.Stop { + absolute, err := filepath.Abs(request.Options.Directory) + if err != nil { + return fmt.Errorf("resolve --directory: %w", err) + } + request.Options.Directory = absolute + } + service, err := resolve() + if err != nil { + return err + } + if format != "none" { + action := "Starting" + if request.Stop { + action = "Stopping" + } + if _, err := fmt.Fprintf(cmd.ErrOrStderr(), "%s %s...\n", action, definition.DisplayName); err != nil { + return err + } + } + result, err := service.Run(ctx, definition, request) + if err != nil { + return err + } + return writeResult(cmd.OutOrStdout(), format, result) +} + +func writeResult(writer io.Writer, format string, result emulator.Result) error { + switch format { + case "none": + return nil + case "json": + encoder := json.NewEncoder(writer) + encoder.SetIndent("", " ") + return encoder.Encode(result) + default: + if _, err := fmt.Fprintf(writer, "%s: %s\n", result.Emulator, result.Status); err != nil { + return err + } + for _, connection := range result.Connections { + if _, err := fmt.Fprintf(writer, " %s: %s\n", connection.Name, connection.Value); err != nil { + return err + } + } + for _, note := range result.Notes { + if _, err := fmt.Fprintf(writer, "\n%s\n", note); err != nil { + return err + } + } + if result.Status == "running" { + _, err := fmt.Fprintf(writer, "\nStop and remove data: azd emulators %s --stop\n", result.Emulator) + return err + } + return nil + } +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/cmd/root_test.go b/cli/azd/extensions/microsoft.azd.emulators/internal/cmd/root_test.go new file mode 100644 index 00000000000..3b629734342 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/cmd/root_test.go @@ -0,0 +1,400 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package cmd + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "log" + "log/slog" + "os" + "path/filepath" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/structpb" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulators" + "github.com/azure/azure-dev/cli/azd/pkg/azdext" +) + +type fakeLauncher struct { + dockerHost emulator.DockerHost + dockerErr error + requirementsChecked []string + requirementFailure string + definition emulator.Definition + request emulator.Request + calls int + logMessage string +} + +func (f *fakeLauncher) CheckDocker(context.Context) (emulator.DockerHost, error) { + return f.dockerHost, f.dockerErr +} + +func (f *fakeLauncher) CheckRequirements(_ context.Context, definition emulator.Definition) error { + f.requirementsChecked = append(f.requirementsChecked, definition.Name) + if definition.Name == f.requirementFailure { + return fmt.Errorf("%s requires Docker Compose", definition.DisplayName) + } + return nil +} + +func (f *fakeLauncher) Run( + _ context.Context, definition emulator.Definition, request emulator.Request, +) (emulator.Result, error) { + f.calls++ + f.definition = definition + f.request = request + if f.logMessage != "" { + log.Print(f.logMessage) + } + if request.Stop { + return emulator.Result{Emulator: definition.Name, Status: "stopped", + RemovedConnectionNames: []string{"CONNECTION_STRING"}}, nil + } + return emulator.Result{ + Emulator: definition.Name, Status: "running", ProjectName: "test-project", + Connections: []emulator.Connection{{Name: "CONNECTION_STRING", Value: "Endpoint=localhost;"}}, + }, nil +} + +func testRoot(t *testing.T, service *fakeLauncher) (*cobra.Command, *bytes.Buffer, *bytes.Buffer) { + t.Helper() + logger, writer, flags := slog.Default(), log.Writer(), log.Flags() + t.Cleanup(func() { + slog.SetDefault(logger) + log.SetOutput(writer) + log.SetFlags(flags) + }) + root := newRootCommand("0.1.0", func() (launcher, error) { return service, nil }, nil) + stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{} + root.SetOut(stdout) + root.SetErr(stderr) + return root, stdout, stderr +} + +func TestEmulatorCommandPrintsJSONWithoutProgressContamination(t *testing.T) { + service := &fakeLauncher{} + root, stdout, stderr := testRoot(t, service) + root.SetArgs([]string{"servicebus", "--accept-license", "--port", "15672", "--output", "json", "--no-prompt"}) + require.NoError(t, root.ExecuteContext(t.Context())) + require.Equal(t, "servicebus", service.definition.Name) + require.Equal(t, 15672, service.request.Options.Ports["port"]) + require.True(t, service.request.AcceptLicense) + require.True(t, service.request.Changed["port"]) + + var result emulator.Result + require.NoError(t, json.Unmarshal(stdout.Bytes(), &result)) + require.Equal(t, "Endpoint=localhost;", result.Connections[0].Value) + require.Contains(t, stderr.String(), "Starting Azure Service Bus") +} + +func TestEmulatorCommandsExposeAllLaunchersAndMetadata(t *testing.T) { + root, stdout, _ := testRoot(t, &fakeLauncher{}) + require.NoError(t, azdext.ValidateNoReservedFlagConflicts(root)) + for _, definition := range emulators.All() { + command, _, err := root.Find([]string{definition.Name}) + require.NoError(t, err) + require.Equal(t, definition.Name, command.Name()) + require.NotNil(t, command.RunE) + } + root.SetArgs([]string{"metadata"}) + require.NoError(t, root.ExecuteContext(t.Context())) + require.True(t, json.Valid(stdout.Bytes())) + for _, definition := range emulators.All() { + require.Contains(t, stdout.String(), `"`+definition.Name+`"`) + } +} + +func TestEmulatorCommandRejectsDroppedFlagsAndInvalidInput(t *testing.T) { + for _, args := range [][]string{ + {"storage", "--stop", "--port", "10000"}, + {"signalr", "--stop", "--upstream-url", "http://localhost:7071"}, + {"servicebus", "--stop", "--accept-license=false"}, + {"storage", "--port", "0"}, + {"storage", "--port", "10001"}, + {"storage", "--timeout", "0s"}, + {"storage", "unexpected"}, + {"storage", "--output", "xml"}, + {"storage", "--environment", "dev"}, + } { + t.Run(args[0]+" "+args[1], func(t *testing.T) { + service := &fakeLauncher{} + root, stdout, _ := testRoot(t, service) + root.SetArgs(args) + require.Error(t, root.ExecuteContext(t.Context())) + require.Zero(t, service.calls) + require.Empty(t, stdout.String()) + }) + } +} + +func TestEmulatorCommandSuppressesAllOutputWhenRequested(t *testing.T) { + root, stdout, stderr := testRoot(t, &fakeLauncher{logMessage: "runner diagnostic"}) + root.SetArgs([]string{"storage", "--output", "none", "--debug"}) + require.NoError(t, root.ExecuteContext(t.Context())) + require.Empty(t, stdout.String()) + require.Empty(t, stderr.String()) +} + +func TestEmulatorCommandPrintsConnectionInfoToInjectedWriter(t *testing.T) { + root, stdout, _ := testRoot(t, &fakeLauncher{}) + root.SetArgs([]string{"storage"}) + require.NoError(t, root.ExecuteContext(t.Context())) + require.Contains(t, stdout.String(), "CONNECTION_STRING: Endpoint=localhost;") + require.Contains(t, stdout.String(), "azd emulators storage --stop") +} + +func TestEmulatorCommandKeepsDebugLogsOnInjectedErrorWriter(t *testing.T) { + root, stdout, stderr := testRoot(t, &fakeLauncher{logMessage: "runner diagnostic"}) + root.SetArgs([]string{"storage", "--output", "json", "--debug"}) + require.NoError(t, root.ExecuteContext(t.Context())) + require.True(t, json.Valid(stdout.Bytes())) + require.Contains(t, stderr.String(), "runner diagnostic") +} + +func TestEmulatorAddListenerIgnoresConnectionResetOnlyAfterSuccess(t *testing.T) { + err := fmt.Errorf("receiver error: stream receive failed: %w", + status.Error(codes.Unavailable, "error reading from server: connection reset by peer")) + + require.NoError(t, addListenerError(true, err)) + require.ErrorIs(t, addListenerError(false, err), err) +} + +func TestEmulatorAddListenerPreservesOtherUnavailableErrors(t *testing.T) { + err := fmt.Errorf("receiver error: stream receive failed: %w", + status.Error(codes.Unavailable, "connection refused")) + + require.ErrorIs(t, addListenerError(true, err), err) +} + +func TestEmulatorAddOffersTheEntireCatalog(t *testing.T) { + root, _, _ := testRoot(t, &fakeLauncher{}) + listen, _, err := root.Find([]string{"listen"}) + require.NoError(t, err) + require.Equal(t, "listen", listen.Name()) + require.True(t, listen.Hidden) + + definitions := emulators.All() + service := &fakeLauncher{dockerHost: emulator.DockerHost{Architecture: "amd64"}} + items := emulatorAddItems(t.Context(), definitions, func() (launcher, error) { return service, nil }) + require.Len(t, items, len(definitions)) + seen := map[string]bool{} + for i, item := range items { + require.Equal(t, definitions[i].Name, item.GetId()) + require.False(t, seen[item.GetId()]) + seen[item.GetId()] = true + require.Equal(t, definitions[i].DisplayName, item.GetDisplayName()) + require.Empty(t, item.GetDisabledReason()) + } +} + +func TestEmulatorAddDisablesAMD64OnlyItemsOnARM64(t *testing.T) { + service := &fakeLauncher{dockerHost: emulator.DockerHost{Architecture: "aarch64"}} + items := emulatorAddItems(t.Context(), emulators.All(), func() (launcher, error) { return service, nil }) + disabled := map[string]string{} + for _, item := range items { + if item.GetDisabledReason() != "" { + disabled[item.GetId()] = item.GetDisabledReason() + } + } + require.Len(t, disabled, 2) + require.Contains(t, disabled["servicebus"], "AMD64") + require.Contains(t, disabled["kusto"], "AMD64") +} + +func TestEmulatorAddDisablesItemsWithoutDockerPrerequisites(t *testing.T) { + for _, reason := range []string{"Docker is required to run emulators.", "`docker compose` is unavailable."} { + t.Run(reason, func(t *testing.T) { + service := &fakeLauncher{dockerErr: fmt.Errorf("%s", reason)} + definitions := emulators.All() + items := emulatorAddItems(t.Context(), definitions, func() (launcher, error) { return service, nil }) + require.Len(t, items, len(definitions)) + for _, item := range items { + require.Equal(t, reason, item.GetDisabledReason()) + } + }) + } +} + +func TestEmulatorAddOnlyWritesLayerConfig(t *testing.T) { + cloud := map[string]any{"name": "cloud", "provider": "bicep", "path": "infra"} + project := &emulatorAddProject{infra: map[string]any{"layers": []any{cloud}}} + require.NoError(t, addEmulator(t.Context(), project, nil, emulators.All(), "storage")) + require.NoError(t, addEmulator(t.Context(), project, nil, emulators.All(), "servicebus")) + require.Equal(t, []any{cloud, map[string]any{ + "name": "emulators", "provider": "emulators", "config": map[string]any{ + "storage": map[string]any{}, "servicebus": map[string]any{}, + }, + }}, project.infra["layers"]) + require.Equal(t, 2, project.writes) + require.Error(t, addEmulator(t.Context(), project, nil, emulators.All(), "storage")) + require.Equal(t, 2, project.writes) +} + +func TestEmulatorAddPreservesProjectLayers(t *testing.T) { + project := &emulatorAddProject{layers: []any{ + map[string]any{"name": "app", "infra": []any{map[string]any{"name": "cloud", "provider": "bicep"}}}, + }} + require.NoError(t, addEmulator(t.Context(), project, nil, emulators.All(), "storage")) + require.NoError(t, addEmulator(t.Context(), project, nil, emulators.All(), "appconfig")) + require.Equal(t, []any{ + map[string]any{"name": "app", "infra": []any{map[string]any{"name": "cloud", "provider": "bicep"}}}, + map[string]any{"name": "emulators", "infra": []any{map[string]any{ + "name": "emulators", "provider": "emulators", "config": map[string]any{ + "storage": map[string]any{}, "appconfig": map[string]any{}, + }, + }}}, + }, project.layers) + require.Nil(t, project.infra) +} + +func TestEmulatorLayerLaunchesOnlyDuringDeploy(t *testing.T) { + projectDir := t.TempDir() + require.NoError(t, os.Mkdir(filepath.Join(projectDir, "site output"), 0o700)) + service := &fakeLauncher{} + project := &emulatorAddProject{} + require.NoError(t, addEmulator(t.Context(), project, &emulatorAddPrompt{directory: "site output"}, + emulators.All(), "staticwebapps")) + layers, ok := project.infra["layers"].([]any) + require.True(t, ok) + require.Len(t, layers, 1) + layer, ok := layers[0].(map[string]any) + require.True(t, ok) + options, ok := layer["config"].(map[string]any) + require.True(t, ok) + config, err := structpb.NewStruct(options) + require.NoError(t, err) + provider := &emulatorProvider{ + definitions: emulators.All(), + currentEnvironment: func(context.Context) (string, error) { return "dev", nil }, + resolve: func(dir, env string) (launcher, error) { + require.Equal(t, projectDir, dir) + require.Equal(t, "dev", env) + return service, nil + }, + } + require.NoError(t, provider.Initialize(t.Context(), projectDir, &azdext.ProvisioningOptions{Config: config})) + _, err = provider.Preview(t.Context(), nil) + require.NoError(t, err) + require.Zero(t, service.calls) + deployed, err := provider.Deploy(t.Context(), nil) + require.NoError(t, err) + require.Equal(t, 1, service.calls) + require.Equal(t, "staticwebapps", service.definition.Name) + require.Equal(t, filepath.Join(projectDir, "site output"), service.request.Options.Directory) + require.True(t, service.request.Changed["directory"]) + outputs := deployed.GetDeployment().GetOutputs() + require.Len(t, outputs, 1) + const key = "AZD_EMULATOR_STATICWEBAPPS_CONNECTION_STRING" + require.Equal(t, "string", outputs[key].GetType()) + require.Equal(t, "Endpoint=localhost;", outputs[key].GetValue()) + destroyed, err := provider.Destroy(t.Context(), nil, nil) + require.NoError(t, err) + require.True(t, service.request.Stop) + require.Equal(t, []string{key}, destroyed.GetInvalidatedEnvKeys()) +} + +func TestEmulatorDeployHonorsExplicitLicenseDecline(t *testing.T) { + config, err := structpb.NewStruct(map[string]any{ + "appconfig": map[string]any{}, "servicebus": map[string]any{"acceptLicense": false}, + }) + require.NoError(t, err) + provider := &emulatorProvider{definitions: emulators.All()} + require.NoError(t, provider.Initialize(t.Context(), t.TempDir(), &azdext.ProvisioningOptions{Config: config})) + _, err = provider.Deploy(t.Context(), func(string) { t.Error("startup progress reported before license validation") }) + var local *azdext.LocalError + require.ErrorAs(t, err, &local) + require.Contains(t, local.Suggestion, "acceptLicense: true") +} + +func TestEmulatorDeployAcceptsLicenseByDefault(t *testing.T) { + config, err := structpb.NewStruct(map[string]any{"servicebus": map[string]any{}}) + require.NoError(t, err) + service := &fakeLauncher{} + provider := &emulatorProvider{ + definitions: emulators.All(), + currentEnvironment: func(context.Context) (string, error) { return "dev", nil }, + resolve: func(string, string) (launcher, error) { return service, nil }, + } + require.NoError(t, provider.Initialize(t.Context(), t.TempDir(), &azdext.ProvisioningOptions{Config: config})) + _, err = provider.Deploy(t.Context(), nil) + require.NoError(t, err) + require.Equal(t, 1, service.calls) + require.True(t, service.request.AcceptLicense) +} + +func TestEmulatorDeployChecksEverySelectedEmulatorBeforeStarting(t *testing.T) { + config, err := structpb.NewStruct(map[string]any{"appconfig": map[string]any{}, "servicebus": map[string]any{}}) + require.NoError(t, err) + service := &fakeLauncher{requirementFailure: "servicebus"} + provider := &emulatorProvider{ + definitions: emulators.All(), + currentEnvironment: func(context.Context) (string, error) { return "dev", nil }, + resolve: func(string, string) (launcher, error) { return service, nil }, + } + require.NoError(t, provider.Initialize(t.Context(), t.TempDir(), &azdext.ProvisioningOptions{Config: config})) + _, err = provider.Deploy(t.Context(), nil) + require.ErrorContains(t, err, "Azure Service Bus requires Docker Compose") + require.Equal(t, []string{"appconfig", "servicebus"}, service.requirementsChecked) + require.Zero(t, service.calls) +} + +type emulatorAddPrompt struct { + azdext.PromptServiceClient + directory string +} + +func (p *emulatorAddPrompt) Prompt( + _ context.Context, _ *azdext.PromptRequest, _ ...grpc.CallOption, +) (*azdext.PromptResponse, error) { + return &azdext.PromptResponse{Value: p.directory}, nil +} + +type emulatorAddProject struct { + azdext.ProjectServiceClient + infra map[string]any + layers []any + writes int +} + +func (p *emulatorAddProject) GetConfigValue( + _ context.Context, req *azdext.GetProjectConfigValueRequest, _ ...grpc.CallOption, +) (*azdext.GetProjectConfigValueResponse, error) { + var raw any + switch { + case req.Path == "layers" && p.layers != nil: + raw = p.layers + case req.Path == "infra" && p.infra != nil: + raw = p.infra + default: + return &azdext.GetProjectConfigValueResponse{}, nil + } + value, err := structpb.NewValue(raw) + return &azdext.GetProjectConfigValueResponse{Found: true, Value: value}, err +} + +func (p *emulatorAddProject) SetConfigValue( + _ context.Context, req *azdext.SetProjectConfigValueRequest, _ ...grpc.CallOption, +) (*azdext.EmptyResponse, error) { + p.writes++ + if req.Path == "layers" { + p.layers = req.Value.GetListValue().AsSlice() + return &azdext.EmptyResponse{}, nil + } + if p.infra == nil { + p.infra = map[string]any{} + } + p.infra["layers"] = req.Value.AsInterface() + return &azdext.EmptyResponse{}, nil +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulator/diagnostics.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulator/diagnostics.go new file mode 100644 index 00000000000..4375b868734 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulator/diagnostics.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulator + +import ( + "net/url" + "regexp" + "strings" +) + +var diagnosticURL = regexp.MustCompile(`(?i)https?://[^\s"'<>]+`) + +func sanitizeDiagnostic(message string, secrets []string) string { + for _, secret := range secrets { + if secret != "" { + message = strings.ReplaceAll(message, secret, "[redacted]") + } + } + return diagnosticURL.ReplaceAllStringFunc(message, func(value string) string { + parsed, err := url.Parse(value) + if err != nil { + return "[redacted URL]" + } + parsed.User = nil + parsed.RawQuery = "" + parsed.ForceQuery = false + parsed.Fragment = "" + parsed.RawFragment = "" + return parsed.String() + }) +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulator/manager.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulator/manager.go new file mode 100644 index 00000000000..0fdb60b8bfe --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulator/manager.go @@ -0,0 +1,519 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulator + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io" + "maps" + "net" + "net/http" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "time" + + "github.com/blang/semver/v4" + "github.com/gofrs/flock" + + "github.com/azure/azure-dev/cli/azd/pkg/azdext" + "github.com/azure/azure-dev/cli/azd/pkg/exec" +) + +const ( + codeInvalidOptions = "invalid_options" + codeLicenseNeeded = "license_not_accepted" + codeNoInstance = "instance_not_found" +) + +var emulatorName = regexp.MustCompile(`^[a-z][a-z0-9-]*$`) + +// Manager runs isolated Compose projects and preserves their connection settings. +type Manager struct { + runner exec.CommandRunner + stateDir string + client *http.Client + projectScoped bool +} + +type savedState struct { + Version int `json:"version"` + Emulator string `json:"emulator"` + ProjectName string `json:"projectName"` + Options Options `json:"options"` + Spec Spec `json:"spec"` +} + +// NewManager creates a launcher using the supplied command runner and private state directory. +func NewManager(runner exec.CommandRunner, stateDir string) *Manager { + return &Manager{ + runner: runner, stateDir: stateDir, + client: &http.Client{ + Timeout: 2 * time.Second, + // Emulator health checks must never leave the local host through a proxy or redirect. + Transport: &http.Transport{Proxy: nil}, + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { + return http.ErrUseLastResponse + }, + }, + } +} + +// ForProject returns a manager whose state is isolated from standalone instances and other environments. +func (m *Manager) ForProject(projectDir, environment string) *Manager { + scope := sha256.Sum256([]byte(projectDir + "\x00" + environment)) + project := NewManager(m.runner, filepath.Join(m.stateDir, "projects", fmt.Sprintf("%x", scope))) + project.projectScoped = true + return project +} + +func (m *Manager) stopCommand(name string) string { + if m.projectScoped { + return "azd down" + } + return "azd emulators " + name + " --stop" +} + +// IsInstanceMissing reports whether the emulator has no saved instance in this scope. +func IsInstanceMissing(err error) bool { + local, ok := errors.AsType[*azdext.LocalError](err) + return ok && local.Code == codeNoInstance +} + +// Run starts or stops the requested emulator and returns its verified connection information. +func (m *Manager) Run( + ctx context.Context, definition Definition, request Request, +) (result Result, returnErr error) { + if !emulatorName.MatchString(definition.Name) { + return Result{}, fmt.Errorf("invalid emulator name %q", definition.Name) + } + if err := ValidateRequest(definition, request); err != nil { + return Result{}, err + } + + ctx, cancel := context.WithTimeout(ctx, request.Timeout) + defer cancel() + + if err := os.MkdirAll(m.stateDir, 0o700); err != nil { + return Result{}, fmt.Errorf("create emulator state directory: %w", err) + } + lock := flock.New(filepath.Join(m.stateDir, definition.Name+".lock")) + locked, err := lock.TryLockContext(ctx, 100*time.Millisecond) + if err != nil { + return Result{}, fmt.Errorf("lock emulator state: %w", err) + } + if !locked { + return Result{}, fmt.Errorf("waiting for another %s command: %w", definition.Name, ctx.Err()) + } + defer func() { returnErr = errors.Join(returnErr, lock.Close()) }() + + statePath := filepath.Join(m.stateDir, definition.Name+".json") + state, err := m.loadState(statePath, definition.Name) + if err != nil { + return Result{}, err + } + + if request.Stop { + if state == nil { + return Result{}, validation(codeNoInstance, "No saved "+definition.DisplayName+" instance exists.", + "Start it with azd emulators "+definition.Name+".") + } + if _, err := m.CheckDocker(ctx); err != nil { + return Result{}, err + } + if _, err := m.compose(ctx, state, []string{"down", "--volumes"}); err != nil { + return Result{}, err + } + if err := os.Remove(statePath); err != nil { + return Result{}, fmt.Errorf("remove stopped emulator state: %w", err) + } + names := make([]string, 0, len(state.Spec.Connections)) + for _, connection := range state.Spec.Connections { + names = append(names, connection.Name) + } + return Result{ + Emulator: definition.Name, Status: "stopped", ProjectName: state.ProjectName, + RemovedConnectionNames: names, + }, nil + } + + if state != nil { + if err := checkChangedOptions(state.Options, request); err != nil { + return Result{}, err + } + } else { + if len(definition.LicenseURLs) > 0 && !request.AcceptLicense { + return Result{}, validation(codeLicenseNeeded, + "Starting "+definition.DisplayName+" requires acceptance of its license terms.", + "Review "+strings.Join(definition.LicenseURLs, ", ")+ + " and run again with --accept-license.") + } + spec, err := definition.Build(request.Options) + if err != nil { + return Result{}, err + } + state = &savedState{ + Version: 1, Emulator: definition.Name, ProjectName: m.projectName(definition.Name), + Options: request.Options, Spec: spec, + } + } + + if err := m.CheckRequirements(ctx, definition); err != nil { + return Result{}, err + } + data, err := json.MarshalIndent(state, "", " ") + if err != nil { + return Result{}, fmt.Errorf("encode emulator state: %w", err) + } + if state.Spec.Dockerfile != "" { + // Only the Dockerfile belongs in the build context, never state files or credentials. + directory := filepath.Join(m.stateDir, "build", definition.Name) + if err := os.MkdirAll(directory, 0o700); err != nil { + return Result{}, fmt.Errorf("create image build context: %w", err) + } + if err := azdext.WriteFileAtomic( + filepath.Join(directory, "Dockerfile"), []byte(state.Spec.Dockerfile), 0o600, + ); err != nil { + return Result{}, fmt.Errorf("write emulator Dockerfile: %w", err) + } + } + // Preserve enough information to stop partial launches and reuse generated passwords. + if err := azdext.WriteFileAtomic(statePath, data, 0o600); err != nil { + return Result{}, fmt.Errorf("save emulator state: %w", err) + } + if _, err := m.compose(ctx, state, []string{"up", "--detach"}); err != nil { + return Result{}, fmt.Errorf("%w\nClean up with %s.", err, m.stopCommand(definition.Name)) + } + if err := m.waitReady(ctx, state); err != nil { + return Result{}, fmt.Errorf( + "%w\nInspect containers with docker ps -a --filter label=com.docker.compose.project=%s."+ + "\nClean up with %s.", err, state.ProjectName, m.stopCommand(definition.Name)) + } + return Result{ + Emulator: definition.Name, Status: "running", ProjectName: state.ProjectName, + Connections: state.Spec.Connections, Notes: state.Spec.Notes, + }, nil +} + +// ValidateRequest rejects invalid ports, timeouts and explicitly conflicting flags. +func ValidateRequest(definition Definition, request Request) error { + if request.Changed["environment"] { + return validation(codeInvalidOptions, + "--environment is not supported. Emulator instances are shared across environments.", + "Omit --environment. Use a separate azd configuration directory when you need isolated instances.") + } + if request.Timeout <= 0 { + return validation(codeInvalidOptions, "--timeout must be greater than zero.", "Use --timeout 5m.") + } + if request.Stop { + for _, flag := range slices.Sorted(maps.Keys(request.Changed)) { + if request.Changed[flag] && flag != "stop" && flag != "timeout" { + return validation(codeInvalidOptions, "--"+flag+" cannot be used with --stop.", + "Use --stop alone, then supply launch options when starting the emulator.") + } + } + return nil + } + used := map[int]string{} + for _, port := range definition.Ports { + value := request.Options.Ports[port.Flag] + if value < 1 || value > 65535 { + return validation(codeInvalidOptions, "--"+port.Flag+" must be between 1 and 65535.", + "Choose an unused local port.") + } + if previous, exists := used[value]; exists { + return validation(codeInvalidOptions, "--"+port.Flag+" conflicts with --"+previous+".", + "Assign a different local port to each endpoint.") + } + used[value] = port.Flag + } + return nil +} + +func checkChangedOptions(saved Options, request Request) error { + for flag, port := range request.Options.Ports { + if request.Changed[flag] && saved.Ports[flag] != port { + return changedOption(flag) + } + } + if request.Changed["directory"] && saved.Directory != request.Options.Directory { + return changedOption("directory") + } + if request.Changed["upstream-url"] && saved.UpstreamURL != request.Options.UpstreamURL { + return changedOption("upstream-url") + } + return nil +} + +func changedOption(flag string) error { + return validation(codeInvalidOptions, "--"+flag+" differs from the saved instance configuration.", + "Stop the emulator with --stop before changing its launch options.") +} + +func validation(code, message, suggestion string) error { + return &azdext.LocalError{ + Code: code, Category: azdext.LocalErrorCategoryValidation, Message: message, Suggestion: suggestion, + } +} + +func (m *Manager) projectName(name string) string { + sum := sha256.Sum256([]byte(m.stateDir)) + return fmt.Sprintf("azd-emulators-%x-%s", sum[:6], name) +} + +func (m *Manager) loadState(path, name string) (*savedState, error) { + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("read emulator state: %w", err) + } + var state savedState + if err := json.Unmarshal(data, &state); err != nil { + return nil, fmt.Errorf("decode emulator state %q: %w", path, err) + } + if state.Version != 1 || state.Emulator != name || state.ProjectName != m.projectName(name) || + len(state.Spec.Compose.Services) == 0 || (len(state.Spec.Probes) == 0 && len(state.Spec.ExecProbe) == 0) { + return nil, fmt.Errorf("invalid emulator state in %q", path) + } + for _, service := range state.Spec.Compose.Services { + if service.Build != nil && + (service.Build.Context != "build/"+name || state.Spec.Dockerfile == "") { + return nil, fmt.Errorf("invalid emulator build context in %q", path) + } + } + return &state, nil +} + +// CheckRequirements checks the local Docker prerequisites for an emulator without installing anything. +func (m *Manager) CheckRequirements(ctx context.Context, definition Definition) error { + host, err := m.CheckDocker(ctx) + if err != nil { + return err + } + return host.CheckRequirements(definition) +} + +// DockerHost describes the Docker daemon used to run emulators. +type DockerHost struct { + Architecture string +} + +// CheckRequirements checks whether the daemon architecture supports the emulator. +func (h DockerHost) CheckRequirements(definition Definition) error { + if definition.RequiresAMD64 && h.Architecture != "amd64" && h.Architecture != "x86_64" { + return validation(codeInvalidOptions, definition.DisplayName+" requires an AMD64 Docker host.", + "Switch to a Docker context with an AMD64 daemon.") + } + return nil +} + +// CheckDocker checks the shared Docker prerequisites without installing anything. +func (m *Manager) CheckDocker(ctx context.Context) (DockerHost, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + if err := m.runner.ToolInPath("docker"); err != nil { + return DockerHost{}, &azdext.ToolError{ + Message: "Docker is required to run emulators.", Err: err, ToolName: "docker", + Kind: azdext.ToolErrorKindMissing, Suggestion: "Install Docker with Compose 2.23.1 or later.", + } + } + version, err := m.runDocker(ctx, []string{"compose", "version", "--short"}, nil, nil) + if err != nil { + if ctx.Err() != nil { + return DockerHost{}, fmt.Errorf("checking Docker Compose: %w", ctx.Err()) + } + return DockerHost{}, &azdext.ToolError{ + Message: "Docker Compose 2.23.1 or later is required. `docker compose` is unavailable.", + Err: err, + ToolName: "docker compose", + Kind: azdext.ToolErrorKindFailed, + Suggestion: "Install or repair the Docker Compose plugin, then run `docker compose version` to verify it.", + } + } + parsed, err := semver.ParseTolerant(strings.TrimSpace(version)) + if err != nil || parsed.LT(semver.MustParse("2.23.1")) { + return DockerHost{}, validation(codeInvalidOptions, "Docker Compose 2.23.1 or later is required.", + "Update the Docker Compose plugin.") + } + info, err := m.runDocker(ctx, []string{"info", "--format", "{{.OSType}} {{.Architecture}}"}, nil, nil) + if err != nil { + return DockerHost{}, &azdext.ToolError{ + Message: "Docker daemon is unavailable.", Err: err, ToolName: "docker", + Kind: azdext.ToolErrorKindFailed, Suggestion: "Start Docker or switch to a working Docker context.", + } + } + fields := strings.Fields(info) + if len(fields) != 2 { + return DockerHost{}, errors.New("could not determine the Docker daemon OS and architecture") + } + if fields[0] != "linux" { + return DockerHost{}, validation(codeInvalidOptions, "Emulators require Linux containers.", + "Switch Docker to Linux containers.") + } + return DockerHost{Architecture: fields[1]}, nil +} + +func (m *Manager) compose(ctx context.Context, state *savedState, args []string) (string, error) { + data, err := json.Marshal(state.Spec.Compose) + if err != nil { + return "", fmt.Errorf("encode Compose configuration: %w", err) + } + // All values are literal configuration, not references to the caller's environment. + data = bytes.ReplaceAll(data, []byte("$"), []byte("$$")) + command := []string{"compose", "--project-name", state.ProjectName, "--project-directory", m.stateDir, "-f", "-"} + command = append(command, args...) + output, err := m.runDocker(ctx, command, data, state.Spec.Secrets) + if toolErr, ok := errors.AsType[*azdext.ToolError](err); ok { + toolErr.Suggestion += " Clean up this instance with " + m.stopCommand(state.Emulator) + "." + } + return output, err +} + +func (m *Manager) runDocker( + ctx context.Context, args []string, input []byte, secrets []string, +) (string, error) { + result, err := m.runner.Run(ctx, exec.RunArgs{ + Cmd: "docker", Args: args, StdIn: bytes.NewReader(input), DebugLogging: new(false), + }) + if err != nil { + message := strings.TrimSpace(result.Stderr) + if message == "" { + message = err.Error() + } + return "", &azdext.ToolError{ + Message: "Docker failed: " + sanitizeDiagnostic(message, secrets), Err: err, + ToolName: "docker", Kind: azdext.ToolErrorKindFailed, ExitCode: new(result.ExitCode), + Suggestion: "Check that Docker is running, accessible, and includes the Compose plugin.", + } + } + return result.Stdout, nil +} + +func (m *Manager) waitReady(ctx context.Context, state *savedState) error { + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + var lastErr error + for { + running, err := m.checkContainers(ctx, state) + if err != nil { + return err + } + lastErr = fmt.Errorf("waiting for all emulator containers to run") + if running { + lastErr = m.checkEndpoints(ctx, state) + } + if lastErr == nil && len(state.Spec.ExecProbe) > 0 { + _, lastErr = m.compose(ctx, state, append([]string{"exec", "-T", "emulator"}, state.Spec.ExecProbe...)) + } + if lastErr == nil { + return nil + } + select { + case <-ctx.Done(): + return fmt.Errorf("%s did not become ready: %w: %w", state.Emulator, ctx.Err(), lastErr) + case <-ticker.C: + } + } +} + +func (m *Manager) checkContainers(ctx context.Context, state *savedState) (bool, error) { + output, err := m.compose(ctx, state, []string{"ps", "--all", "--format", "json"}) + if err != nil { + return false, err + } + statuses, err := parseContainerStatuses(output) + if err != nil { + return false, err + } + running := make(map[string]bool) + for _, status := range statuses { + if status.State == "exited" || status.State == "dead" { + return false, fmt.Errorf("%s container %s stopped with exit code %d", + state.Emulator, status.Service, status.ExitCode) + } + if status.State == "running" { + running[status.Service] = true + } + } + for service := range state.Spec.Compose.Services { + if !running[service] { + return false, nil + } + } + return true, nil +} + +type containerStatus struct { + Service string + State string + ExitCode int +} + +func parseContainerStatuses(output string) ([]containerStatus, error) { + var statuses []containerStatus + output = strings.TrimSpace(output) + if strings.HasPrefix(output, "[") { + if err := json.Unmarshal([]byte(output), &statuses); err != nil { + return nil, fmt.Errorf("decode Docker container status: %w", err) + } + return statuses, nil + } + decoder := json.NewDecoder(strings.NewReader(output)) + for { + var status containerStatus + if err := decoder.Decode(&status); err != nil { + if errors.Is(err, io.EOF) { + return statuses, nil + } + return nil, fmt.Errorf("decode Docker container status: %w", err) + } + statuses = append(statuses, status) + } +} + +func (m *Manager) checkEndpoints(ctx context.Context, state *savedState) error { + for _, port := range state.Options.Ports { + dialer := net.Dialer{Timeout: time.Second} + connection, err := dialer.DialContext(ctx, "tcp", fmt.Sprintf("127.0.0.1:%d", port)) + if err != nil { + return fmt.Errorf("waiting for port %d: %w", port, err) + } + if err := connection.Close(); err != nil { + return err + } + } + for _, probe := range state.Spec.Probes { + method := probe.Method + if method == "" { + method = http.MethodGet + } + request, err := http.NewRequestWithContext(ctx, method, probe.URL, strings.NewReader(probe.Body)) + if err != nil { + return fmt.Errorf("create readiness request: %w", err) + } + if probe.Body != "" { + request.Header.Set("Content-Type", "application/json") + } + response, err := m.client.Do(request) + if err != nil { + return fmt.Errorf("readiness request: %w", err) + } + if err := response.Body.Close(); err != nil { + return err + } + if response.StatusCode != probe.Status { + return fmt.Errorf("readiness check returned HTTP %d, expected %d", response.StatusCode, probe.Status) + } + } + return nil +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulator/manager_test.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulator/manager_test.go new file mode 100644 index 00000000000..d1d44738feb --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulator/manager_test.go @@ -0,0 +1,407 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulator + +import ( + "context" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/azure/azure-dev/cli/azd/pkg/azdext" + "github.com/azure/azure-dev/cli/azd/pkg/exec" +) + +type dockerCall struct { + args []string + input string +} + +type fakeDocker struct { + calls []dockerCall + version string + status string + info string + failCommand string + stderr string + missing bool +} + +func (f *fakeDocker) ToolInPath(_ string) error { + if f.missing { + return errors.New("docker not found") + } + return nil +} + +func (f *fakeDocker) Run(_ context.Context, args exec.RunArgs) (exec.RunResult, error) { + input, err := io.ReadAll(args.StdIn) + if err != nil { + return exec.RunResult{}, err + } + f.calls = append(f.calls, dockerCall{args: slices.Clone(args.Args), input: string(input)}) + if f.failCommand != "" && slices.Contains(args.Args, f.failCommand) { + return exec.RunResult{ExitCode: 1, Stderr: f.stderr}, errors.New("exit status 1") + } + if slices.Contains(args.Args, "version") { + version := f.version + if version == "" { + version = "2.23.1" + } + return exec.RunResult{Stdout: version}, nil + } + if slices.Contains(args.Args, "info") { + if f.info != "" { + return exec.RunResult{Stdout: f.info}, nil + } + return exec.RunResult{Stdout: "linux x86_64"}, nil + } + if slices.Contains(args.Args, "ps") { + status := f.status + if status == "" { + status = `{"Service":"emulator","State":"running","ExitCode":0}` + } + return exec.RunResult{Stdout: status}, nil + } + return exec.RunResult{}, nil +} + +func (f *fakeDocker) RunList(_ context.Context, _ []string, _ exec.RunArgs) (exec.RunResult, error) { + return exec.RunResult{}, errors.New("unexpected RunList call") +} + +func readyDefinition(t *testing.T, status int) (Definition, Request) { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { + writer.WriteHeader(status) + })) + t.Cleanup(server.Close) + _, portText, err := net.SplitHostPort(server.Listener.Addr().String()) + require.NoError(t, err) + port, err := strconv.Atoi(portText) + require.NoError(t, err) + definition := Definition{ + Name: "test", DisplayName: "Test emulator", Ports: []Port{{Flag: "port", Default: port}}, + Build: func(o Options) (Spec, error) { + return Spec{ + Compose: Compose{Services: map[string]Service{ + "emulator": {Image: "test/image:1", Ports: []string{o.Binding("port", 8080)}}, + }}, + Connections: []Connection{{Name: "ENDPOINT", Value: o.URL("port")}}, + Probes: []Probe{{URL: o.URL("port") + "/ready", Status: 200}}, + Secrets: []string{"generated-password"}, + }, nil + }, + } + return definition, Request{ + Options: Options{Ports: map[string]int{"port": port}}, + Changed: map[string]bool{}, Timeout: time.Second, + } +} + +func TestManagerStartsReusesAndStopsInstance(t *testing.T) { + definition, request := readyDefinition(t, 200) + buildCount := 0 + build := definition.Build + definition.Build = func(o Options) (Spec, error) { + buildCount++ + return build(o) + } + runner := &fakeDocker{} + directory := t.TempDir() + manager := NewManager(runner, directory) + + first, err := manager.Run(t.Context(), definition, request) + require.NoError(t, err) + require.Equal(t, "running", first.Status) + require.Equal(t, request.Options.URL("port"), first.Connections[0].Value) + statePath := filepath.Join(directory, "test.json") + before, err := os.ReadFile(statePath) + require.NoError(t, err) + + // Unspecified defaults must not replace the saved instance's chosen ports. + request.Options.Ports = map[string]int{"port": 1234} + again, err := manager.Run(t.Context(), definition, request) + require.NoError(t, err) + require.Equal(t, first, again) + require.Equal(t, 1, buildCount) + after, err := os.ReadFile(statePath) + require.NoError(t, err) + require.JSONEq(t, string(before), string(after)) + + stopped, err := manager.Run(t.Context(), definition, Request{Stop: true, Timeout: time.Second}) + require.NoError(t, err) + require.Equal(t, "stopped", stopped.Status) + require.Equal(t, []string{"ENDPOINT"}, stopped.RemovedConnectionNames) + require.Empty(t, stopped.Connections) + _, err = os.Stat(statePath) + require.ErrorIs(t, err, os.ErrNotExist) + require.Contains(t, runner.calls[len(runner.calls)-1].args, "down") + require.Contains(t, runner.calls[len(runner.calls)-1].args, "--volumes") +} + +func TestManagerRejectsExplicitChangesToSavedInstance(t *testing.T) { + definition, request := readyDefinition(t, 200) + runner := &fakeDocker{} + manager := NewManager(runner, t.TempDir()) + _, err := manager.Run(t.Context(), definition, request) + require.NoError(t, err) + count := len(runner.calls) + + request.Options.Ports = map[string]int{"port": 1234} + request.Changed["port"] = true + _, err = manager.Run(t.Context(), definition, request) + require.ErrorContains(t, err, "--port differs") + require.Len(t, runner.calls, count) +} + +func TestManagerRequiresLicenseOnlyForNewInstances(t *testing.T) { + definition, request := readyDefinition(t, 200) + definition.LicenseURLs = []string{"https://example.com/license"} + runner := &fakeDocker{} + manager := NewManager(runner, t.TempDir()) + + _, err := manager.Run(t.Context(), definition, request) + localErr, ok := errors.AsType[*azdext.LocalError](err) + require.True(t, ok) + require.Equal(t, codeLicenseNeeded, localErr.Code) + require.Empty(t, runner.calls) + + request.AcceptLicense = true + _, err = manager.Run(t.Context(), definition, request) + require.NoError(t, err) + request.AcceptLicense = false + _, err = manager.Run(t.Context(), definition, request) + require.NoError(t, err) +} + +func TestManagerWaitsForHealthyEndpoints(t *testing.T) { + definition, request := readyDefinition(t, 503) + request.Timeout = 50 * time.Millisecond + manager := NewManager(&fakeDocker{}, t.TempDir()) + + result, err := manager.Run(t.Context(), definition, request) + require.ErrorIs(t, err, context.DeadlineExceeded) + require.ErrorContains(t, err, "HTTP 503") + require.Empty(t, result.Connections) +} + +func TestManagerDoesNotMistakeExistingListenerForMissingContainer(t *testing.T) { + definition, request := readyDefinition(t, 200) + request.Timeout = 50 * time.Millisecond + manager := NewManager(&fakeDocker{status: "[]"}, t.TempDir()) + + _, err := manager.Run(t.Context(), definition, request) + require.ErrorIs(t, err, context.DeadlineExceeded) + require.ErrorContains(t, err, "waiting for all emulator containers") +} + +func TestManagerReportsExitedDependency(t *testing.T) { + definition, request := readyDefinition(t, 200) + manager := NewManager(&fakeDocker{ + status: `{"Service":"dependency","State":"exited","ExitCode":42}`, + }, t.TempDir()) + + _, err := manager.Run(t.Context(), definition, request) + require.ErrorContains(t, err, "dependency stopped with exit code 42") +} + +func TestManagerKeepsStateWhenLaunchOrStopFails(t *testing.T) { + definition, request := readyDefinition(t, 200) + runner := &fakeDocker{failCommand: "up", stderr: "image not found"} + directory := t.TempDir() + manager := NewManager(runner, directory) + + _, err := manager.Run(t.Context(), definition, request) + require.ErrorContains(t, err, "image not found") + statePath := filepath.Join(directory, "test.json") + require.FileExists(t, statePath) + + runner.failCommand = "down" + _, err = manager.Run(t.Context(), definition, Request{Stop: true, Timeout: time.Second}) + require.Error(t, err) + require.FileExists(t, statePath) + + runner.failCommand = "" + _, err = manager.Run(t.Context(), definition, Request{Stop: true, Timeout: time.Second}) + require.NoError(t, err) + require.NoFileExists(t, statePath) +} + +func TestManagerRejectsMissingDockerAndOldCompose(t *testing.T) { + for _, test := range []struct { + name string + runner *fakeDocker + want string + }{ + {name: "missing docker", runner: &fakeDocker{missing: true}, want: "Docker is required"}, + {name: "missing compose", runner: &fakeDocker{failCommand: "version"}, want: "`docker compose` is unavailable"}, + {name: "old compose", runner: &fakeDocker{version: "2.22.0"}, want: "Compose 2.23.1"}, + } { + t.Run(test.name, func(t *testing.T) { + definition, request := readyDefinition(t, 200) + _, err := NewManager(test.runner, t.TempDir()).Run(t.Context(), definition, request) + require.ErrorContains(t, err, test.want) + for _, call := range test.runner.calls { + require.Equal(t, []string{"compose", "version", "--short"}, call.args) + } + }) + } +} + +func TestManagerDoesNotInterpolateConfiguration(t *testing.T) { + definition, request := readyDefinition(t, 200) + build := definition.Build + definition.Build = func(o Options) (Spec, error) { + spec, err := build(o) + spec.Compose.Services["emulator"] = Service{ + Image: "test/image:1", Environment: map[string]string{"LITERAL": "${SECRET}"}, + } + + return spec, err + } + runner := &fakeDocker{} + _, err := NewManager(runner, t.TempDir()).Run(t.Context(), definition, request) + require.NoError(t, err) + var config Compose + for _, call := range runner.calls { + if slices.Contains(call.args, "up") { + require.NoError(t, json.Unmarshal([]byte(call.input), &config)) + } + } + require.Equal(t, "$${SECRET}", config.Services["emulator"].Environment["LITERAL"]) +} + +func TestManagerRejectsAMD64EmulatorBeforeComposeUpOnARM64(t *testing.T) { + definition, request := readyDefinition(t, 200) + definition.RequiresAMD64 = true + runner := &fakeDocker{info: "linux aarch64"} + _, err := NewManager(runner, t.TempDir()).Run(t.Context(), definition, request) + require.ErrorContains(t, err, "requires an AMD64 Docker host") + require.Len(t, runner.calls, 2) + require.Equal(t, []string{"compose", "version", "--short"}, runner.calls[0].args) + require.Equal(t, "info", runner.calls[1].args[0]) +} + +func TestManagerStagesOnlyDockerfileInIsolatedBuildContext(t *testing.T) { + definition, request := readyDefinition(t, 200) + build := definition.Build + definition.Build = func(o Options) (Spec, error) { + spec, err := build(o) + service := spec.Compose.Services["emulator"] + service.Build = &Build{Context: "build/test"} + spec.Compose.Services["emulator"] = service + spec.Dockerfile = "FROM test/image:1\n" + return spec, err + } + directory := t.TempDir() + manager := NewManager(&fakeDocker{}, directory) + _, err := manager.Run(t.Context(), definition, request) + require.NoError(t, err) + contextDirectory := filepath.Join(directory, "build", "test") + entries, err := os.ReadDir(contextDirectory) + require.NoError(t, err) + require.Len(t, entries, 1) + require.Equal(t, "Dockerfile", entries[0].Name()) + content, err := os.ReadFile(filepath.Join(contextDirectory, "Dockerfile")) + require.NoError(t, err) + require.Equal(t, "FROM test/image:1\n", string(content)) +} + +func TestManagerRedactsToolDiagnostics(t *testing.T) { + definition, request := readyDefinition(t, 200) + // #nosec G101 -- Fake credentials verify that diagnostics never disclose URL secrets. + manager := NewManager(&fakeDocker{ + failCommand: "up", + stderr: "pull https://alice:password@example.com/image?sig=sas-secret#private-fragment generated-password", + }, t.TempDir()) + + _, err := manager.Run(t.Context(), definition, request) + require.Error(t, err) + for _, secret := range []string{"alice", "password", "sas-secret", "private-fragment"} { + require.NotContains(t, err.Error(), secret) + } + require.Contains(t, err.Error(), "https://example.com/image") +} + +func TestManagerRejectsCorruptStateAndTraversal(t *testing.T) { + definition, request := readyDefinition(t, 200) + directory := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(directory, "test.json"), []byte("{"), 0o600)) + runner := &fakeDocker{} + manager := NewManager(runner, directory) + _, err := manager.Run(t.Context(), definition, request) + require.ErrorContains(t, err, "decode emulator state") + require.Empty(t, runner.calls) + + definition.Name = "../outside" + _, err = manager.Run(t.Context(), definition, request) + require.ErrorContains(t, err, "invalid emulator name") +} + +func TestManagerExecutesSQLReadinessCommand(t *testing.T) { + definition, request := readyDefinition(t, 200) + build := definition.Build + definition.Build = func(o Options) (Spec, error) { + spec, err := build(o) + spec.Probes = nil + spec.ExecProbe = []string{"sqlcmd", "-Q", "SELECT 1"} + return spec, err + } + runner := &fakeDocker{} + manager := NewManager(runner, t.TempDir()) + _, err := manager.Run(t.Context(), definition, request) + require.NoError(t, err) + require.True(t, slices.ContainsFunc(runner.calls, func(call dockerCall) bool { + return strings.HasSuffix(strings.Join(call.args, " "), "exec -T emulator sqlcmd -Q SELECT 1") + })) + _, err = manager.Run(t.Context(), definition, request) + require.NoError(t, err) + + runner.failCommand = "exec" + request.Timeout = 50 * time.Millisecond + _, err = manager.Run(t.Context(), definition, request) + require.ErrorIs(t, err, context.DeadlineExceeded) +} + +func TestValidateRequestRejectsInvalidAndConflictingOptions(t *testing.T) { + definition := Definition{Ports: []Port{{Flag: "port"}, {Flag: "other-port"}}} + for _, test := range []struct { + name string + request Request + want string + }{ + { + name: "invalid port", want: "between 1 and 65535", + request: Request{Options: Options{Ports: map[string]int{"port": 0}}, Timeout: time.Second}, + }, + { + name: "duplicate ports", want: "conflicts", + request: Request{ + Options: Options{Ports: map[string]int{"port": 1234, "other-port": 1234}}, Timeout: time.Second, + }, + }, + { + name: "stop ignores port", want: "--port cannot be used with --stop", + request: Request{Stop: true, Changed: map[string]bool{"port": true}, Timeout: time.Second}, + }, + {name: "invalid timeout", want: "--timeout", request: Request{}}, + } { + t.Run(test.name, func(t *testing.T) { + require.ErrorContains(t, ValidateRequest(definition, test.request), test.want) + }) + } +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulator/types.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulator/types.go new file mode 100644 index 00000000000..2acb9b9068a --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulator/types.go @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulator + +import ( + "fmt" + "time" +) + +// Definition describes an emulator command and builds its local configuration. +type Definition struct { + Name string + DisplayName string + Description string + Ports []Port + LicenseURLs []string + HasDirectory bool + HasUpstream bool + RequiresAMD64 bool + Build func(Options) (Spec, error) +} + +// Port describes a configurable host port and its command flag. +type Port struct { + Flag string + Default int + Description string +} + +// Options holds the settings used to create an emulator instance. +type Options struct { + // Ports maps command flag names to host ports. + Ports map[string]int `json:"ports"` + Directory string `json:"directory,omitempty"` + UpstreamURL string `json:"upstreamUrl,omitempty"` +} + +// URL returns a loopback HTTP endpoint for a configured port. +func (o Options) URL(flag string) string { + return fmt.Sprintf("http://127.0.0.1:%d", o.Ports[flag]) +} + +// Binding publishes a container port exclusively on the host's loopback interface. +func (o Options) Binding(flag string, containerPort int) string { + return fmt.Sprintf("127.0.0.1:%d:%d", o.Ports[flag], containerPort) +} + +// Request describes a launch or stop operation and explicitly supplied settings. +type Request struct { + Options Options + Changed map[string]bool + AcceptLicense bool + Stop bool + Timeout time.Duration +} + +// Connection is a named connection setting intended for the local application. +type Connection struct { + Name string `json:"name"` + Value string `json:"value"` +} + +// Result contains connection information for a ready emulator or a stop result. +type Result struct { + Emulator string `json:"emulator"` + Status string `json:"status"` + ProjectName string `json:"projectName"` + Connections []Connection `json:"connections,omitempty"` + Notes []string `json:"notes,omitempty"` + // RemovedConnectionNames identifies the environment outputs to invalidate after stopping an instance. + RemovedConnectionNames []string `json:"-"` +} + +// Spec contains the Compose configuration, readiness checks and connection settings. +type Spec struct { + Compose Compose `json:"compose"` + Connections []Connection `json:"connections"` + Notes []string `json:"notes,omitempty"` + Probes []Probe `json:"probes"` + // Dockerfile is the source for the main service's locally built image. + Dockerfile string `json:"dockerfile,omitempty"` + // ExecProbe is an optional readiness command executed inside the main container. + ExecProbe []string `json:"execProbe,omitempty"` + // Secrets contains generated values that must not appear in tool diagnostics. + Secrets []string `json:"secrets,omitempty"` +} + +// Compose is the subset of the Compose specification used by the launchers. +type Compose struct { + // Services maps stable service names to their container definitions. + Services map[string]Service `json:"services"` + // Configs maps configuration names to inline file contents. + Configs map[string]Config `json:"configs,omitempty"` +} + +// Service configures a container and any dependencies within its Compose project. +type Service struct { + Image string `json:"image,omitempty"` + Platform string `json:"platform,omitempty"` + Build *Build `json:"build,omitempty"` + Command []string `json:"command,omitempty"` + Entrypoint []string `json:"entrypoint,omitempty"` + Ports []string `json:"ports,omitempty"` + // Environment maps container environment variable names to their values. + Environment map[string]string `json:"environment,omitempty"` + DependsOn []string `json:"depends_on,omitempty"` + Configs []ConfigMount `json:"configs,omitempty"` + Volumes []Volume `json:"volumes,omitempty"` + ExtraHosts []string `json:"extra_hosts,omitempty"` +} + +// Build identifies the isolated context for a locally built emulator image. +type Build struct { + Context string `json:"context"` +} + +// Config contains an inline configuration file. +type Config struct { + Content string `json:"content"` +} + +// ConfigMount places a Compose configuration file inside a container. +type ConfigMount struct { + Source string `json:"source"` + Target string `json:"target"` +} + +// Volume describes a read-only host directory mounted into a container. +type Volume struct { + Type string `json:"type"` + Source string `json:"source"` + Target string `json:"target"` + ReadOnly bool `json:"read_only"` +} + +// Probe describes an HTTP readiness check on a loopback endpoint. +type Probe struct { + URL string `json:"url"` + Method string `json:"method,omitempty"` + Body string `json:"body,omitempty"` + Status int `json:"status"` +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/appconfig.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/appconfig.go new file mode 100644 index 00000000000..a5f77fafb0a --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/appconfig.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulators + +import "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" + +func appConfig() emulator.Definition { + return emulator.Definition{ + Name: "appconfig", DisplayName: "Azure App Configuration", + Description: "Launch App Configuration with its web UI and anonymous local authentication.", + Ports: []emulator.Port{ + {Flag: "port", Default: 8483, Description: "Host port for the API and web UI"}, + }, + Build: func(o emulator.Options) (emulator.Spec, error) { + return emulator.Spec{ + Compose: emulator.Compose{Services: map[string]emulator.Service{ + "emulator": { + Image: "mcr.microsoft.com/azure-app-configuration/app-configuration-emulator:1.2.0", + Ports: []string{o.Binding("port", 8483)}, + Environment: map[string]string{ + "Tenant:AnonymousAuthEnabled": "true", "Authentication:Anonymous:AnonymousUserRole": "Owner", + }, + }, + }}, + Connections: []emulator.Connection{ + {Name: "AZURE_APPCONFIG_ENDPOINT", Value: o.URL("port")}, + }, + Probes: []emulator.Probe{{URL: o.URL("port") + "/kv", Status: 200}}, + Notes: []string{ + "Use an SDK supporting anonymous authentication. No access key or Azure login is required.", + }, + }, nil + }, + } +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/catalog.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/catalog.go new file mode 100644 index 00000000000..9ccc7512789 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/catalog.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulators + +import "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" + +// These public development keys are defined by the upstream emulators, not production credentials. +const ( + storageKey = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==" + cosmosKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==" + realtimeKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGH" + azuriteImage = "mcr.microsoft.com/azure-storage/azurite:3.35.0" +) + +// All returns the available emulator commands, with a separate definition per service. +func All() []emulator.Definition { + return []emulator.Definition{ + storage(), cosmosDB(), serviceBus(), eventHubs(), appConfig(), kusto(), + durableTask(), signalR(), staticWebApps(), webPubSub(), sqlDB(), + } +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/catalog_test.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/catalog_test.go new file mode 100644 index 00000000000..099e3c8a551 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/catalog_test.go @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulators + +import ( + "encoding/base64" + "encoding/json" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" +) + +func TestLaunchersPublishLoopbackPortsAndUseConfiguredValues(t *testing.T) { + defaults := map[int]string{} + for _, definition := range All() { + t.Run(definition.Name, func(t *testing.T) { + options := emulator.Options{ + Ports: map[string]int{}, Directory: t.TempDir(), + UpstreamURL: "http://host.docker.internal:7071/runtime/webhooks/signalr", + } + for _, port := range definition.Ports { + require.NotContains(t, defaults, port.Default, "default ports must allow different emulators to coexist") + defaults[port.Default] = definition.Name + options.Ports[port.Flag] = port.Default + 10000 + } + spec, err := definition.Build(options) + require.NoError(t, err) + require.NotEmpty(t, spec.Connections) + require.True(t, len(spec.Probes) > 0 || len(spec.ExecProbe) > 0) + published := map[int]bool{} + for _, service := range spec.Compose.Services { + if service.Build != nil { + require.Equal(t, "build/"+definition.Name, service.Build.Context) + require.NotEmpty(t, spec.Dockerfile) + } + for _, port := range service.Ports { + require.True(t, strings.HasPrefix(port, "127.0.0.1:"), port) + } + for _, hostPort := range options.Ports { + for _, binding := range service.Ports { + if strings.Contains(binding, ":"+strconv.Itoa(hostPort)+":") { + published[hostPort] = true + } + } + } + for _, dependency := range service.DependsOn { + require.Contains(t, spec.Compose.Services, dependency) + } + for _, mount := range service.Configs { + require.Contains(t, spec.Compose.Configs, mount.Source) + } + } + for _, port := range options.Ports { + require.True(t, published[port], "configured port must be published") + } + for _, config := range spec.Compose.Configs { + require.True(t, json.Valid([]byte(config.Content))) + } + }) + } +} + +func TestStorageConnectionStringUsesAzuriteDevelopmentKey(t *testing.T) { + key, err := base64.StdEncoding.DecodeString(storageKey) + require.NoError(t, err) + require.Len(t, key, 64) + spec, err := storage().Build(emulator.Options{Ports: map[string]int{ + "port": 11000, "queue-port": 11001, "table-port": 11002, + }}) + require.NoError(t, err) + connection := spec.Connections[0].Value + require.Contains(t, connection, "BlobEndpoint=http://127.0.0.1:11000/devstoreaccount1") + require.Contains(t, connection, "QueueEndpoint=http://127.0.0.1:11001/devstoreaccount1") + require.Contains(t, connection, "TableEndpoint=http://127.0.0.1:11002/devstoreaccount1") +} + +func TestServiceBusUsesSameGeneratedPasswordForDependency(t *testing.T) { + spec, err := serviceBus().Build(emulator.Options{Ports: map[string]int{"port": 5674, "management-port": 5400}}) + require.NoError(t, err) + main := spec.Compose.Services["emulator"] + sql := spec.Compose.Services["mssql"] + require.NotEmpty(t, main.Environment["MSSQL_SA_PASSWORD"]) + require.Equal(t, main.Environment["MSSQL_SA_PASSWORD"], sql.Environment["MSSQL_SA_PASSWORD"]) + require.Empty(t, sql.Ports) + require.Contains(t, spec.Connections[0].Value, "localhost:5674") + require.Contains(t, spec.Connections[1].Value, "localhost:5400") +} + +func TestEventHubsUsesKafkaPortInSASLConnectionString(t *testing.T) { + spec, err := eventHubs().Build(emulator.Options{Ports: map[string]int{ + "port": 15673, "kafka-port": 19092, "health-port": 15301, + }}) + require.NoError(t, err) + settings := map[string]string{} + for _, connection := range spec.Connections { + settings[connection.Name] = connection.Value + } + require.Contains(t, settings["EVENTHUBS_CONNECTION_STRING"], "Endpoint=sb://localhost:15673;") + require.Contains(t, settings["KAFKA_SASL_PASSWORD"], "Endpoint=sb://localhost:19092;") + require.Equal(t, "localhost:19092", settings["KAFKA_BOOTSTRAP_SERVERS"]) +} + +func TestSignalRRejectsInvalidUpstreamWithoutDisclosingIt(t *testing.T) { + // #nosec G101 -- Fake credentials verify validation errors do not disclose input URLs. + _, err := signalR().Build(emulator.Options{UpstreamURL: "ftp://user:secret@example.com/?sig=private"}) + require.ErrorContains(t, err, "--upstream-url") + require.NotContains(t, err.Error(), "secret") + require.NotContains(t, err.Error(), "private") +} + +func TestStaticWebAppsRequiresExistingDirectory(t *testing.T) { + _, err := staticWebApps().Build(emulator.Options{Directory: "/path/that/does/not/exist"}) + require.ErrorContains(t, err, "static-content directory") +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/cosmosdb.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/cosmosdb.go new file mode 100644 index 00000000000..33f3fdc8547 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/cosmosdb.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulators + +import ( + "fmt" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" +) + +func cosmosDB() emulator.Definition { + return emulator.Definition{ + Name: "cosmosdb", DisplayName: "Azure Cosmos DB", + Description: "Launch the Cosmos DB vNext emulator for the NoSQL gateway API.", + Ports: []emulator.Port{ + {Flag: "port", Default: 8081, Description: "Host port for the HTTPS gateway"}, + {Flag: "explorer-port", Default: 1234, Description: "Host port for Data Explorer"}, + {Flag: "health-port", Default: 18081, Description: "Host port for readiness checks"}, + }, + Build: func(o emulator.Options) (emulator.Spec, error) { + endpoint := fmt.Sprintf("https://localhost:%d/", o.Ports["port"]) + return emulator.Spec{ + Compose: emulator.Compose{Services: map[string]emulator.Service{ + "emulator": { + Image: "mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:vnext-latest", + Command: []string{"--protocol", "https", "--explorer-protocol", "http"}, + Ports: []string{ + o.Binding("port", 8081), o.Binding("explorer-port", 1234), o.Binding("health-port", 8080), + }, + Environment: map[string]string{"ENABLE_TELEMETRY": "false"}, + }, + }}, + Connections: []emulator.Connection{ + {Name: "COSMOS_ENDPOINT", Value: endpoint}, + {Name: "COSMOS_KEY", Value: cosmosKey}, + {Name: "COSMOS_CONNECTION_STRING", + Value: "AccountEndpoint=" + endpoint + ";AccountKey=" + cosmosKey + ";"}, + {Name: "DATA_EXPLORER_URL", Value: o.URL("explorer-port")}, + }, + Probes: []emulator.Probe{{URL: o.URL("health-port") + "/ready", Status: 200}}, + Notes: []string{ + "Supports the NoSQL gateway API only. The vNext emulator does not enforce authentication.", + "The gateway uses a self-signed development certificate. Configure your SDK to trust it locally.", + }, + }, nil + }, + } +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/durabletask.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/durabletask.go new file mode 100644 index 00000000000..dd23d992398 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/durabletask.go @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulators + +import "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" + +func durableTask() emulator.Definition { + return emulator.Definition{ + Name: "durabletask", DisplayName: "Durable Task Scheduler", + Description: "Launch Durable Task Scheduler with the default task hub and dashboard.", + Ports: []emulator.Port{ + {Flag: "port", Default: 8080, Description: "Host port for the scheduler"}, + {Flag: "dashboard-port", Default: 8082, Description: "Host port for the dashboard"}, + }, + Build: func(o emulator.Options) (emulator.Spec, error) { + return emulator.Spec{ + Compose: emulator.Compose{Services: map[string]emulator.Service{ + "emulator": { + Image: "mcr.microsoft.com/dts/dts-emulator:latest", + Ports: []string{o.Binding("port", 8080), o.Binding("dashboard-port", 8082)}, + }, + }}, + Connections: []emulator.Connection{ + {Name: "DURABLE_TASK_SERVICE_CONNECTION_STRING", + Value: "Endpoint=" + o.URL("port") + ";TaskHub=default;Authentication=None"}, + {Name: "TASKHUB_NAME", Value: "default"}, + {Name: "DASHBOARD_URL", Value: o.URL("dashboard-port")}, + }, + Probes: []emulator.Probe{{URL: o.URL("dashboard-port"), Status: 200}}, + }, nil + }, + } +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/eventhubs.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/eventhubs.go new file mode 100644 index 00000000000..f52a4a3a738 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/eventhubs.go @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulators + +import ( + "fmt" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" +) + +func eventHubs() emulator.Definition { + return emulator.Definition{ + Name: "eventhubs", DisplayName: "Azure Event Hubs", + Description: "Launch Event Hubs with an event hub, consumer group and Azurite dependency.", + Ports: []emulator.Port{ + {Flag: "port", Default: 5673, Description: "Host port for AMQP"}, + {Flag: "kafka-port", Default: 9092, Description: "Host port for Kafka"}, + {Flag: "health-port", Default: 5301, Description: "Host port for readiness checks"}, + }, + LicenseURLs: []string{ + "https://github.com/Azure/azure-event-hubs-emulator-installer/blob/main/EMULATOR_EULA.md", + }, + Build: func(o emulator.Options) (emulator.Spec, error) { + connection := fmt.Sprintf(eventHubsConnectionFormat, o.Ports["port"]) + // The emulator advertises the Kafka broker using the endpoint supplied during SASL authentication. + kafkaConnection := fmt.Sprintf(eventHubsConnectionFormat, o.Ports["kafka-port"]) + return emulator.Spec{ + Compose: emulator.Compose{ + Services: map[string]emulator.Service{ + "emulator": { + Image: "mcr.microsoft.com/azure-messaging/eventhubs-emulator:latest", + Ports: []string{ + o.Binding("port", 5672), o.Binding("kafka-port", 9092), o.Binding("health-port", 5300), + }, + Environment: map[string]string{ + "ACCEPT_EULA": "Y", "BLOB_SERVER": "azurite", "METADATA_SERVER": "azurite", + }, + DependsOn: []string{"azurite"}, + Configs: []emulator.ConfigMount{ + {Source: "entities", Target: "/Eventhubs_Emulator/ConfigFiles/Config.json"}, + }, + }, + "azurite": {Image: azuriteImage}, + }, + Configs: map[string]emulator.Config{"entities": {Content: eventHubsConfig}}, + }, + Connections: []emulator.Connection{ + {Name: "EVENTHUBS_CONNECTION_STRING", Value: connection}, + {Name: "EVENTHUB_NAME", Value: "eh1"}, + {Name: "EVENTHUB_CONSUMER_GROUP", Value: "cg1"}, + {Name: "KAFKA_BOOTSTRAP_SERVERS", Value: fmt.Sprintf("localhost:%d", o.Ports["kafka-port"])}, + {Name: "KAFKA_SECURITY_PROTOCOL", Value: "SASL_PLAINTEXT"}, + {Name: "KAFKA_SASL_MECHANISM", Value: "PLAIN"}, + {Name: "KAFKA_SASL_USERNAME", Value: "$ConnectionString"}, + {Name: "KAFKA_SASL_PASSWORD", Value: kafkaConnection}, + }, + Probes: []emulator.Probe{{URL: o.URL("health-port") + "/health", Status: 200}}, + Notes: []string{ + "Data is not preserved across emulator restarts. Kafka supports producer and consumer APIs only.", + }, + }, nil + }, + } +} + +const eventHubsConnectionFormat = "Endpoint=sb://localhost:%d;SharedAccessKeyName=RootManageSharedAccessKey;" + + "SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;" + +const eventHubsConfig = `{ + "UserConfig": { + "NamespaceConfig": [{ + "Type": "EventHub", + "Name": "emulatorNs1", + "Entities": [{ + "Name": "eh1", + "PartitionCount": 2, + "ConsumerGroups": [{"Name": "cg1"}] + }] + }], + "LoggingConfig": {"Type": "Console"} + } +}` diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/kusto.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/kusto.go new file mode 100644 index 00000000000..b0a431d0c93 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/kusto.go @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulators + +import "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" + +func kusto() emulator.Definition { + return emulator.Definition{ + Name: "kusto", DisplayName: "Azure Data Explorer (Kusto)", + RequiresAMD64: true, + Description: "Launch the local Kusto query engine (requires x64).", + Ports: []emulator.Port{ + {Flag: "port", Default: 8085, Description: "Host port for the query and management APIs"}, + }, + LicenseURLs: []string{"https://aka.ms/adx.emulator.license"}, + Build: func(o emulator.Options) (emulator.Spec, error) { + return emulator.Spec{ + Compose: emulator.Compose{Services: map[string]emulator.Service{ + "emulator": { + Image: "mcr.microsoft.com/azuredataexplorer/kustainer-linux:latest", Platform: "linux/amd64", + Ports: []string{o.Binding("port", 8080)}, + Environment: map[string]string{"ACCEPT_EULA": "Y"}, + }, + }}, + Connections: []emulator.Connection{ + {Name: "KUSTO_ENDPOINT", Value: o.URL("port")}, + {Name: "KUSTO_CONNECTION_STRING", + Value: "Data Source=" + o.URL("port") + ";AAD Federated Security=False;"}, + }, + Probes: []emulator.Probe{{ + URL: o.URL("port") + "/v1/rest/mgmt", Method: "POST", Body: `{"csl":".show cluster"}`, Status: 200, + }}, + Notes: []string{ + "Requires an x64 CPU with SSE4.2 and AVX2. Managed ingestion and authentication are not available.", + `Create a database with: .create database emulator persist (@"/kustodata/db/md", @"/kustodata/db/data")`, + }, + }, nil + }, + } +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/servicebus.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/servicebus.go new file mode 100644 index 00000000000..f960d8404f8 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/servicebus.go @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulators + +import ( + "crypto/rand" + "fmt" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" +) + +func serviceBus() emulator.Definition { + return emulator.Definition{ + Name: "servicebus", DisplayName: "Azure Service Bus", + RequiresAMD64: true, + Description: "Launch Service Bus with a queue, topic, subscription and SQL Server dependency.", + Ports: []emulator.Port{ + {Flag: "port", Default: 5672, Description: "Host port for AMQP"}, + {Flag: "management-port", Default: 5300, Description: "Host port for administration and readiness checks"}, + }, + LicenseURLs: []string{ + "https://github.com/Azure/azure-service-bus-emulator-installer/blob/main/EMULATOR_EULA.txt", + "https://go.microsoft.com/fwlink/?LinkId=746388", + }, + Build: func(o emulator.Options) (emulator.Spec, error) { + password := "Aa1!" + rand.Text() + connection := func(port int) string { + return fmt.Sprintf("Endpoint=sb://localhost:%d;SharedAccessKeyName=RootManageSharedAccessKey;"+ + "SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;", port) + } + return emulator.Spec{ + Compose: emulator.Compose{ + Services: map[string]emulator.Service{ + "emulator": { + Image: "mcr.microsoft.com/azure-messaging/servicebus-emulator:2.0.0", + Ports: []string{o.Binding("port", 5672), o.Binding("management-port", 5300)}, + Environment: map[string]string{ + "ACCEPT_EULA": "Y", "SQL_SERVER": "mssql", "MSSQL_SA_PASSWORD": password, + }, + DependsOn: []string{"mssql"}, + Configs: []emulator.ConfigMount{ + {Source: "entities", Target: "/ServiceBus_Emulator/ConfigFiles/Config.json"}, + }, + }, + "mssql": { + Image: "mcr.microsoft.com/mssql/server:2022-latest", Platform: "linux/amd64", + Environment: map[string]string{"ACCEPT_EULA": "Y", "MSSQL_SA_PASSWORD": password}, + }, + }, + Configs: map[string]emulator.Config{"entities": {Content: serviceBusConfig}}, + }, + Connections: []emulator.Connection{ + {Name: "SERVICEBUS_CONNECTION_STRING", Value: connection(o.Ports["port"])}, + {Name: "SERVICEBUS_ADMIN_CONNECTION_STRING", Value: connection(o.Ports["management-port"])}, + {Name: "SERVICEBUS_QUEUE", Value: "queue.1"}, + {Name: "SERVICEBUS_TOPIC", Value: "topic.1"}, + {Name: "SERVICEBUS_SUBSCRIPTION", Value: "subscription.1"}, + }, + Probes: []emulator.Probe{{URL: o.URL("management-port") + "/health", Status: 200}}, + Secrets: []string{password}, + Notes: []string{ + "SQL Server requires x64 or an x64-capable container runtime.", + "Data is not preserved across emulator restarts. Administration requires a compatible .NET SDK.", + }, + }, nil + }, + } +} + +const serviceBusConfig = `{ + "UserConfig": { + "Namespaces": [{ + "Name": "sbemulatorns", + "Queues": [{ + "Name": "queue.1", + "Properties": { + "DeadLetteringOnMessageExpiration": false, + "DefaultMessageTimeToLive": "PT1H", + "DuplicateDetectionHistoryTimeWindow": "PT20S", + "ForwardDeadLetteredMessagesTo": "", + "ForwardTo": "", + "LockDuration": "PT1M", + "MaxDeliveryCount": 3, + "RequiresDuplicateDetection": false, + "RequiresSession": false + } + }], + "Topics": [{ + "Name": "topic.1", + "Properties": { + "DefaultMessageTimeToLive": "PT1H", + "DuplicateDetectionHistoryTimeWindow": "PT20S", + "RequiresDuplicateDetection": false + }, + "Subscriptions": [{ + "Name": "subscription.1", + "Properties": { + "DeadLetteringOnMessageExpiration": false, + "DefaultMessageTimeToLive": "PT1H", + "LockDuration": "PT1M", + "MaxDeliveryCount": 3, + "ForwardDeadLetteredMessagesTo": "", + "ForwardTo": "", + "RequiresSession": false + } + }] + }] + }], + "Logging": {"Type": "Console"} + } +}` diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/signalr.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/signalr.go new file mode 100644 index 00000000000..c8c46d659b4 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/signalr.go @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulators + +import ( + "encoding/json" + "fmt" + "net/url" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" +) + +func signalR() emulator.Definition { + return emulator.Definition{ + Name: "signalr", DisplayName: "Azure SignalR", + Description: "Launch the SignalR serverless emulator with a configurable upstream.", + Ports: []emulator.Port{ + {Flag: "port", Default: 8888, Description: "Host port for SignalR"}, + }, + HasUpstream: true, + Build: func(o emulator.Options) (emulator.Spec, error) { + upstream, err := url.Parse(o.UpstreamURL) + if err != nil || upstream.Host == "" || (upstream.Scheme != "http" && upstream.Scheme != "https") { + return emulator.Spec{}, fmt.Errorf("--upstream-url must be an absolute HTTP or HTTPS URL") + } + settings, err := json.Marshal(map[string]any{ + "UpstreamSettings": map[string]any{ + "Templates": []map[string]string{{ + "UrlTemplate": o.UpstreamURL, "EventPattern": "*", "HubPattern": "*", "CategoryPattern": "*", + }}, + }, + }) + if err != nil { + return emulator.Spec{}, fmt.Errorf("encode SignalR settings: %w", err) + } + return emulator.Spec{ + Compose: emulator.Compose{ + Services: map[string]emulator.Service{ + "emulator": { + Build: &emulator.Build{Context: "build/signalr"}, + Ports: []string{o.Binding("port", 8888)}, + Configs: []emulator.ConfigMount{ + {Source: "upstream", Target: "/app/settings.json"}, + }, + ExtraHosts: []string{"host.docker.internal:host-gateway"}, + }, + }, + Configs: map[string]emulator.Config{"upstream": {Content: string(settings)}}, + }, + Dockerfile: signalRDockerfile, + Connections: []emulator.Connection{ + {Name: "AzureSignalRConnectionString", Value: fmt.Sprintf( + "Endpoint=http://localhost;Port=%d;AccessKey=%s;Version=1.0;", o.Ports["port"], realtimeKey)}, + }, + Probes: []emulator.Probe{{URL: o.URL("port") + "/api/v1/health", Status: 200}}, + Secrets: []string{o.UpstreamURL}, + Notes: []string{ + "Only serverless scenarios with transient transport are supported.", + "The upstream URL is resolved inside the container. Use host.docker.internal to reach the host.", + }, + }, nil + }, + } +} + +const signalRDockerfile = `FROM mcr.microsoft.com/dotnet/sdk:8.0 +ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 +RUN dotnet tool install --tool-path /tools Microsoft.Azure.SignalR.Emulator --version 1.7.1 +WORKDIR /app +ENTRYPOINT ["/tools/asrs-emulator", "start", "--ip", "0.0.0.0", "--port", "8888", "--config", "/app/settings.json"] +` diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/sqldb.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/sqldb.go new file mode 100644 index 00000000000..01568c157fa --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/sqldb.go @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulators + +import ( + "crypto/rand" + "fmt" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" +) + +func sqlDB() emulator.Definition { + return emulator.Definition{ + Name: "sqldb", DisplayName: "Azure SQL Database (preview)", + Description: "Launch the preview local Azure SQL Database engine.", + Ports: []emulator.Port{ + {Flag: "port", Default: 1433, Description: "Host port for SQL connections"}, + }, + LicenseURLs: []string{"https://go.microsoft.com/fwlink/?LinkId=746388"}, + Build: func(o emulator.Options) (emulator.Spec, error) { + password := "Aa1!" + rand.Text() + return emulator.Spec{ + Compose: emulator.Compose{Services: map[string]emulator.Service{ + "emulator": { + Image: "mcr.microsoft.com/mssql/azure-sql-db-server:latest", + Ports: []string{o.Binding("port", 1433)}, + Environment: map[string]string{ + "ACCEPT_EULA": "Y", "MSSQL_SA_PASSWORD": password, "SQLCMDPASSWORD": password, + }, + }, + }}, + Connections: []emulator.Connection{ + {Name: "SQL_CONNECTION_STRING", Value: fmt.Sprintf( + "Server=localhost,%d;Database=master;User Id=sa;Password=%s;"+ + "Encrypt=True;TrustServerCertificate=True;", + o.Ports["port"], password)}, + {Name: "SQL_USER", Value: "sa"}, + {Name: "SQL_PASSWORD", Value: password}, + }, + ExecProbe: []string{ + "/opt/mssql-tools18/bin/sqlcmd", "-S", "localhost", "-U", "sa", "-C", "-b", "-Q", "SELECT 1", + }, + Secrets: []string{password}, + Notes: []string{ + "Preview of the real Azure SQL Database engine, not a complete managed-service replica.", + "The sa account and self-signed certificate trust are for local development only.", + }, + }, nil + }, + } +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/staticwebapps.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/staticwebapps.go new file mode 100644 index 00000000000..71f74fb660e --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/staticwebapps.go @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulators + +import ( + "fmt" + "os" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" +) + +func staticWebApps() emulator.Definition { + return emulator.Definition{ + Name: "staticwebapps", DisplayName: "Azure Static Web Apps", + Description: "Launch the Static Web Apps emulator for a local static-content directory.", + Ports: []emulator.Port{ + {Flag: "port", Default: 4280, Description: "Host port for the website"}, + }, + HasDirectory: true, + Build: func(o emulator.Options) (emulator.Spec, error) { + info, err := os.Stat(o.Directory) + if err != nil { + return emulator.Spec{}, fmt.Errorf("read static-content directory: %w", err) + } + if !info.IsDir() { + return emulator.Spec{}, fmt.Errorf("--directory must refer to a directory") + } + return emulator.Spec{ + Compose: emulator.Compose{Services: map[string]emulator.Service{ + "emulator": { + Build: &emulator.Build{Context: "build/staticwebapps"}, + Ports: []string{o.Binding("port", 4280)}, + Volumes: []emulator.Volume{ + {Type: "bind", Source: o.Directory, Target: "/app", ReadOnly: true}, + }, + }, + }}, + Dockerfile: staticWebAppsDockerfile, + Connections: []emulator.Connection{ + {Name: "APP_URL", Value: o.URL("port")}, + {Name: "CONTENT_DIRECTORY", Value: o.Directory}, + }, + Probes: []emulator.Probe{{URL: o.URL("port") + "/.auth/me", Status: 200}}, + Notes: []string{ + "Serves static files with local routing and mock authentication. API hosting is not included.", + }, + }, nil + }, + } +} + +const staticWebAppsDockerfile = `FROM node:22-bookworm-slim +RUN npm install --global @azure/static-web-apps-cli@2.1.0 +WORKDIR /app +ENTRYPOINT ["swa", "start", "/app", "--host", "0.0.0.0", "--port", "4280"] +` diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/storage.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/storage.go new file mode 100644 index 00000000000..f166cf11cec --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/storage.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulators + +import ( + "fmt" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" +) + +func storage() emulator.Definition { + return emulator.Definition{ + Name: "storage", DisplayName: "Azure Storage (Azurite)", + Description: "Launch Azurite for local Blob, Queue and Table Storage.", + Ports: []emulator.Port{ + {Flag: "port", Default: 10000, Description: "Host port for Blob Storage"}, + {Flag: "queue-port", Default: 10001, Description: "Host port for Queue Storage"}, + {Flag: "table-port", Default: 10002, Description: "Host port for Table Storage"}, + }, + Build: func(o emulator.Options) (emulator.Spec, error) { + blob := o.URL("port") + "/devstoreaccount1" + queue := o.URL("queue-port") + "/devstoreaccount1" + table := o.URL("table-port") + "/devstoreaccount1" + return emulator.Spec{ + Compose: emulator.Compose{Services: map[string]emulator.Service{ + "emulator": { + Image: azuriteImage, + Ports: []string{ + o.Binding("port", 10000), o.Binding("queue-port", 10001), o.Binding("table-port", 10002), + }, + }, + }}, + Connections: []emulator.Connection{ + {Name: "AZURE_STORAGE_CONNECTION_STRING", Value: fmt.Sprintf( + "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=%s;"+ + "BlobEndpoint=%s;QueueEndpoint=%s;TableEndpoint=%s;", storageKey, blob, queue, table)}, + {Name: "BLOB_ENDPOINT", Value: blob}, + {Name: "QUEUE_ENDPOINT", Value: queue}, + {Name: "TABLE_ENDPOINT", Value: table}, + }, + Probes: []emulator.Probe{{URL: blob + "?comp=list", Status: 403}}, + Notes: []string{ + "Table Storage support is preview. Azure Files and Data Lake Storage Gen2 are not emulated.", + }, + }, nil + }, + } +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/webpubsub.go b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/webpubsub.go new file mode 100644 index 00000000000..70e8dce031c --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/internal/emulators/webpubsub.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package emulators + +import ( + "fmt" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/emulator" +) + +func webPubSub() emulator.Definition { + return emulator.Definition{ + Name: "webpubsub", DisplayName: "Azure Web PubSub (preview)", + Description: "Launch the preview Web PubSub emulator for local WebSocket messaging.", + Ports: []emulator.Port{ + {Flag: "port", Default: 8084, Description: "Host port for Web PubSub"}, + }, + Build: func(o emulator.Options) (emulator.Spec, error) { + return emulator.Spec{ + Compose: emulator.Compose{Services: map[string]emulator.Service{ + "emulator": { + Build: &emulator.Build{Context: "build/webpubsub"}, + Ports: []string{o.Binding("port", 8080)}, + }, + }}, + Dockerfile: webPubSubDockerfile, + Connections: []emulator.Connection{ + {Name: "WEBPUBSUB_CONNECTION_STRING", Value: fmt.Sprintf( + "Endpoint=%s;AccessKey=%s;Version=1.0;", o.URL("port"), realtimeKey)}, + }, + Probes: []emulator.Probe{{URL: o.URL("port") + "/api/health", Method: "HEAD", Status: 200}}, + Notes: []string{ + "Preview. State is held in memory and message TTL expiration is not enforced.", + "Enable your SDK's local HTTP option (JavaScript: allowInsecureConnection: true).", + }, + }, nil + }, + } +} + +const webPubSubDockerfile = `FROM mcr.microsoft.com/dotnet/sdk:10.0 +ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 +RUN dotnet tool install --tool-path /tools Microsoft.Azure.WebPubSub.Emulator --version 1.0.0-beta.1 +WORKDIR /app +ENTRYPOINT ["/tools/awps-emulator", "--urls", "http://0.0.0.0:8080"] +` diff --git a/cli/azd/extensions/microsoft.azd.emulators/main.go b/cli/azd/extensions/microsoft.azd.emulators/main.go new file mode 100644 index 00000000000..6892a4a9dea --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/main.go @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package main + +import ( + _ "embed" + "strings" + + "github.com/azure/azure-dev/cli/azd/extensions/microsoft.azd.emulators/internal/cmd" + "github.com/azure/azure-dev/cli/azd/pkg/azdext" +) + +//go:embed version.txt +var version string + +func main() { + azdext.Run(cmd.NewRootCommand(strings.TrimSpace(version))) +} diff --git a/cli/azd/extensions/microsoft.azd.emulators/version.txt b/cli/azd/extensions/microsoft.azd.emulators/version.txt new file mode 100644 index 00000000000..6e8bf73aa55 --- /dev/null +++ b/cli/azd/extensions/microsoft.azd.emulators/version.txt @@ -0,0 +1 @@ +0.1.0 diff --git a/docs/architecture/extension-framework.md b/docs/architecture/extension-framework.md index f60d87617db..a644477bd53 100644 --- a/docs/architecture/extension-framework.md +++ b/docs/architecture/extension-framework.md @@ -223,6 +223,8 @@ for registration and provider requirements. First-party extensions live in `cli/azd/extensions/` and are registered in `cli/azd/extensions/registry.json`. +The alpha [Azure Emulators extension](../../cli/azd/extensions/microsoft.azd.emulators/README.md) uses `azd add` to declare local emulators in an infrastructure layer. Its provisioning provider starts them during `azd up`, using the same Docker Compose lifecycle manager as its standalone commands. It is currently built and installed locally, not published in the registry. + ## Detailed Reference - [Extension Framework Guide](../../cli/azd/docs/extensions/extension-framework.md) — Getting started diff --git a/docs/guides/creating-an-extension.md b/docs/guides/creating-an-extension.md index 19b99a22630..2f7174aef43 100644 --- a/docs/guides/creating-an-extension.md +++ b/docs/guides/creating-an-extension.md @@ -69,6 +69,8 @@ The handler owns the experience after selection. See the [SDK reference](../../cli/azd/docs/extensions/extension-sdk-reference.md#add-providers-beta) for an example and host version requirements. +For an example that declares infrastructure through an add provider and starts it through a provisioning provider, see the alpha [Azure Emulators extension](../../cli/azd/extensions/microsoft.azd.emulators/README.md). + ### 4. Build For infrastructure generation, declare `infra-generation-provider` in both diff --git a/docs/reference/feature-status.md b/docs/reference/feature-status.md index 60ce5fee6af..8296e75b95a 100644 --- a/docs/reference/feature-status.md +++ b/docs/reference/feature-status.md @@ -80,6 +80,7 @@ Current maturity status of Azure Developer CLI features. See [Feature Stages](.. | Deployment Preview (`deploy --preview`) | Beta | | Deployment Stacks | Alpha | | Extensions | Stable | +| [Azure Emulators extension](../../cli/azd/extensions/microsoft.azd.emulators/README.md) | Alpha | ## Extension gRPC Contracts