### Development Setup Commands Source: https://github.com/assurrussa/dokploymigrator/blob/master/CONTRIBUTING.md Run these commands in order to verify the Go toolchain, run tests, lint, and build the project. The project intentionally keeps runtime dependencies small, with the Go service and CLI in `cmd/` and `internal/`, an embedded Web UI in `internal/server/static/`, Docker Compose deployment in `docker-compose.yml`, and a future Dokploy template draft in `templates/dokploy/`. ```sh go version make test make lint make build ``` -------------------------------- ### Example usage of RequireDokployDB Source: https://github.com/assurrussa/dokploymigrator Example showing how to call RequireDokployDB after loading configuration. If the DSN is missing, it logs a message indicating DB-less mode where the UI starts but migration actions are disabled. ```go cfg, err := config.Load() if err != nil { log.Fatal(err) } if err := cfg.RequireDokployDB(); err != nil { log.Printf("DB-less mode: %v (UI starts, migration actions disabled)", err) } ``` -------------------------------- ### OpenPostgres usage example Source: https://github.com/assurrussa/dokploymigrator Opens a Dokploy PostgreSQL adapter with a connection string and nil allowed hashes, then defers Close. Logs fatal on error. ```go adapter, err := dokploydb.OpenPostgres("postgres://dokploy:pw@dokploy-postgres:5432/dokploy?sslmode=disable", nil) if err != nil { log.Fatal(err) } defer adapter.Close() ``` -------------------------------- ### Example usage of s3backup.New Source: https://github.com/assurrussa/dokploymigrator Example of creating an S3 backup client with a custom endpoint, region, bucket, prefix, and credentials. The error is handled with log.Fatal. This example is from the documentation for the New function. ```go client, err := s3backup.New(ctx, s3backup.Config{ Endpoint: "https://s3.example.local", Region: "us-east-1", Bucket: "dokploy-backups", Prefix: "backups/", AccessKeyID: "AK...", SecretAccessKey: "secret", }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Full lifecycle example Source: https://github.com/assurrussa/dokploymigrator Shows the full server lifecycle: create a server with config, store, and manager, log the listening address, then call ListenAndServe with the handler and fatal on error. The example uses server.New and server.ListenAndServe. ```go srv := server.New(server.Config{...}, store, manager) log.Printf("listening on %s", addr) if err := server.ListenAndServe(ctx, addr, srv.Handler()); err != nil { log.Fatal(err) } ``` -------------------------------- ### Start local development stack with loopback override Source: https://github.com/assurrussa/dokploymigrator/blob/master/README.md Starts the Docker Compose stack for local host access, explicitly adding the loopback-only override file `docker-compose.local.yml`. Use only the main Compose file in Dokploy. ```sh docker compose -f docker-compose.yml -f docker-compose.local.yml up -d --build ``` -------------------------------- ### jobs subcommand example with limit and offset Source: https://github.com/assurrussa/dokploymigrator Example invocation listing 10 jobs starting at offset 0. ```sh dokploy-migrator jobs -limit 10 -offset 0 ``` -------------------------------- ### dokploy-migrator apply example Source: https://github.com/assurrussa/dokploymigrator Example invocation of the apply subcommand with a job ID, plan file, schema hash approval, and confirmation. ```sh dokploy-migrator apply -job job-123 -plan plan.json -schema-hash-approval abc123 -confirm APPLY ``` -------------------------------- ### Adapter.ListServerResources Source: https://github.com/assurrussa/dokploymigrator Lists all resources for a given server. Returns a slice of resource records. ```APIDOC ## Adapter.ListServerResources ### Description Lists all resources for a given server. ### Signature ```go func (a *Adapter) ListServerResources(serverID string) ([]Resource, error) ``` ### Parameters - **serverID** (string) - Required - The server ID. ### Returns - **resources** ([]Resource) - List of resources. - **error** (error) - Error if listing fails. ``` -------------------------------- ### Adapter.ListServers Source: https://github.com/assurrussa/dokploymigrator Lists all servers from the database. Returns a slice of server records. ```APIDOC ## Adapter.ListServers ### Description Lists all servers from the database. ### Signature ```go func (a *Adapter) ListServers() ([]Server, error) ``` ### Returns - **servers** ([]Server) - List of servers. - **error** (error) - Error if listing fails. ``` -------------------------------- ### Example: Creating a server with New Source: https://github.com/assurrussa/dokploymigrator Shows how to instantiate a Server using the New constructor with a Config built from external configuration values. ```go srv := server.New(server.Config{ BasicUser: cfg.BasicAuthUser, BasicPassword: cfg.BasicAuthPassword, AdminToken: cfg.AdminToken, DeadAfter: cfg.DeadAfter, }, store, manager) ``` -------------------------------- ### Adapter.BuildRetargetPlan Source: https://github.com/assurrussa/dokploymigrator Builds a retarget plan for moving resources from one server to another. Returns a plan that can be applied or rolled back. ```APIDOC ## Adapter.BuildRetargetPlan ### Description Builds a retarget plan for moving resources from one server to another. ### Signature ```go func (a *Adapter) BuildRetargetPlan(fromServerID string, toServerID string) (*RetargetPlan, error) ``` ### Parameters - **fromServerID** (string) - Required - The source server ID. - **toServerID** (string) - Required - The destination server ID. ### Returns - **plan** (*RetargetPlan) - The retarget plan. - **error** (error) - Error if building fails. ``` -------------------------------- ### dokploy-migrator rollback example Source: https://github.com/assurrussa/dokploymigrator Example invocation of the rollback subcommand with a job ID, plan file, and schema hash approval. ```sh dokploy-migrator rollback -job job-123 -plan plan.json -schema-hash-approval abc123 ``` -------------------------------- ### Adapter.ApplyRetargetPlan Source: https://github.com/assurrussa/dokploymigrator Applies a retarget plan to the database. This performs the actual updates to move resources. ```APIDOC ## Adapter.ApplyRetargetPlan ### Description Applies a retarget plan to the database. ### Signature ```go func (a *Adapter) ApplyRetargetPlan(plan *RetargetPlan) error ``` ### Parameters - **plan** (*RetargetPlan) - Required - The retarget plan to apply. ### Returns - **error** (error) - Error if applying fails. ``` -------------------------------- ### Example: calling Manager.Rollback Source: https://github.com/assurrussa/dokploymigrator Shows how to invoke the Rollback method with a job ID, migration plan, and RollbackOptions containing the current schema hash for approval. This example is from the Rollback method documentation. ```go err := manager.Rollback(ctx, job.ID, plan, jobs.RollbackOptions{ SchemaHashApproval: currentHash, }) ``` -------------------------------- ### Failed load example (missing required env) Source: https://github.com/assurrussa/dokploymigrator Handles the error from config.Load, logging a fatal message with the error. The comment shows an example error: "MIGRATOR_BASIC_USER and MIGRATOR_BASIC_PASSWORD are required". ```go package main import ( "log" "github.com/assurrussa/dokploymigrator/internal/config" ) func main() { cfg, err := config.Load() if err != nil { // e.g. "MIGRATOR_BASIC_USER and MIGRATOR_BASIC_PASSWORD are required" log.Fatalf("startup blocked: %v", err) } _ = cfg } ``` -------------------------------- ### Executor.Run error handling example Source: https://github.com/assurrussa/dokploymigrator Shows how to handle errors from Executor.Run, logging partial output on failure. Uses log.Printf and fmt.Print. ```go out, err := exec.Run(ctx, "docker ps --format '{{.Names}}'") if err != nil { log.Printf("remote command failed (partial output):\n%s", out) return } fmt.Print(string(out)) ``` -------------------------------- ### Example .env configuration from .env.example Source: https://github.com/assurrussa/dokploymigrator Environment variable defaults for the migrator. Set MIGRATOR_BASIC_PASSWORD and MIGRATOR_ADMIN_TOKEN for authentication; MIGRATOR_DEAD_AFTER controls the dead-after duration. DOKPLOY_* variables configure the Dokploy API connection and deployment path. MIGRATOR_SCHEMA_ALLOWLIST restricts schema operations. ```sh MIGRATOR_HTTP_PORT=8080 MIGRATOR_BASIC_USER=admin MIGRATOR_BASIC_PASSWORD= MIGRATOR_ADMIN_TOKEN= MIGRATOR_DEAD_AFTER=10m DOKPLOY_POSTGRES_DSN= DOKPLOY_API_BASE_URL= DOKPLOY_API_TOKEN= DOKPLOY_HEALTH_PATH=/health DOKPLOY_DEPLOY_PATH= MIGRATOR_SCHEMA_ALLOWLIST= ``` -------------------------------- ### Adapter.RollbackRetargetPlan Source: https://github.com/assurrussa/dokploymigrator Rolls back a retarget plan. This reverts the changes made by ApplyRetargetPlan. ```APIDOC ## Adapter.RollbackRetargetPlan ### Description Rolls back a retarget plan. ### Signature ```go func (a *Adapter) RollbackRetargetPlan(plan *RetargetPlan) error ``` ### Parameters - **plan** (*RetargetPlan) - Required - The retarget plan to roll back. ### Returns - **error** (error) - Error if rolling back fails. ``` -------------------------------- ### main entry point Source: https://github.com/assurrussa/dokploymigrator Entry behavior: run() installs a signal context (os.Interrupt, syscall.SIGTERM), selects the subcommand from os.Args[1], and returns an error for unknown commands (unknown command ""). ```go func main() { if err := run(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### ListCandidates usage example Source: https://github.com/assurrussa/dokploymigrator Shows how to call ListCandidates with a sample Resource, handle a possible error, and iterate over the returned candidates printing key, confidence, and size. ```go resource := model.Resource{ID: "postgres-uuid", Name: "pgsql", Type: model.ResourcePostgres} candidates, err := client.ListCandidates(ctx, resource) if err != nil { log.Printf("backup discovery failed: %v", err) } for _, c := range candidates { fmt.Printf("%s (confidence=%s, size=%d)\n", c.Key, c.Confidence, c.Size) } ``` -------------------------------- ### Run serve subcommand with custom address Source: https://github.com/assurrussa/dokploymigrator Starts the HTTP server and embedded UI. The -addr flag overrides the listen address; defaults to MIGRATOR_ADDR or :8080. Runs with requireDB=false, so the UI starts even without a Dokploy DB, but migration actions are disabled. ```sh dokploy-migrator serve -addr :9090 ``` -------------------------------- ### GET /api/jobs - curl Example Source: https://github.com/assurrussa/dokploymigrator Example curl command to fetch a page of job history with limit=50 and offset=50. Requires Basic Auth credentials (MIGRATOR_BASIC_USER and MIGRATOR_BASIC_PASSWORD). ```sh curl -fsS -u "$MIGRATOR_BASIC_USER:$MIGRATOR_BASIC_PASSWORD" \ "http://127.0.0.1:8080/api/jobs?limit=50&offset=50" ``` -------------------------------- ### Dial usage example Source: https://github.com/assurrussa/dokploymigrator Establishes an SSH connection to a target host. Requires valid PEM key bytes. On error, logs fatal; defer Close to release resources. ```go exec, err := sshrestore.Dial(ctx, sshrestore.Config{ Host: "10.0.0.5", Port: "22", User: "root", PrivateKey: pemBytes, Timeout: 20 * time.Second, }) if err != nil { log.Fatal(err) } defer exec.Close() ``` -------------------------------- ### Import dokploydb package Source: https://github.com/assurrussa/dokploymigrator Import the internal/dokploydb package to use the guarded Dokploy database adapter. ```go import "github.com/assurrussa/dokploymigrator/internal/dokploydb" ``` -------------------------------- ### OpenPostgres Source: https://github.com/assurrussa/dokploymigrator Opens a Dokploy PostgreSQL adapter using driver pgx. It accepts a connection string and a list of allowed schema fingerprints, returning an Adapter or an error. ```APIDOC ## OpenPostgres ### Description Opens a Dokploy PostgreSQL adapter using driver `pgx`. ### Signature ```go func OpenPostgres(dsn string, allowedHashes []string) (*Adapter, error) ``` ### Parameters - **dsn** (string) - Required - PostgreSQL connection string. - **allowedHashes** ([]string) - Required - Schema fingerprints to allow (blank entries dropped). ### Returns - **adapter** (*Adapter) - The opened adapter. - **error** (error) - Error if `sql.Open` fails. ### Errors - `open dokploy postgres: ` when `sql.Open` fails. ### Example ```go adapter, err := dokploydb.OpenPostgres("postgres://dokploy:pw@dokploy-postgres:5432/dokploy?sslmode=disable", nil) if err != nil { log.Fatal(err) } defer adapter.Close() ``` ``` -------------------------------- ### Adapter.SchemaFingerprint Source: https://github.com/assurrussa/dokploymigrator Computes a schema fingerprint for the database. This is used to validate that the database schema matches an allowed fingerprint. ```APIDOC ## Adapter.SchemaFingerprint ### Description Computes a schema fingerprint for the database. ### Signature ```go func (a *Adapter) SchemaFingerprint() (string, error) ``` ### Returns - **fingerprint** (string) - The schema fingerprint. - **error** (error) - Error if computation fails. ``` -------------------------------- ### BuildVolumeRestoreCommand usage example Source: https://github.com/assurrussa/dokploymigrator Calls BuildVolumeRestoreCommand with a host archive path, target volume name, and helper image. The resulting command mounts the backup directory read-only and extracts the archive into the volume. ```go cmd, err := sshrestore.BuildVolumeRestoreCommand("/tmp/backups/pg.tar.gz", "pg_data", "alpine:3.23.5") // -> docker run --rm -v /tmp/backups:/backup:ro -v pg_data:/restore alpine:3.23.5 sh -c 'tar -xzf /backup/pg.tar.gz -C /restore' ``` -------------------------------- ### Open function usage example Source: https://github.com/assurrussa/dokploymigrator Shows how to call state.Open with a context and a database path, handle the error with log.Fatalf, and defer the store's Close method. ```go ctx := context.Background() store, err := state.Open(ctx, "/data/dokploy-migrator.sqlite") if err != nil { log.Fatalf("open state: %v", err) } defer store.Close() ``` -------------------------------- ### BuildDBRestoreCommand usage example Source: https://github.com/assurrussa/dokploymigrator Calls BuildDBRestoreCommand with a .gz dump path, a container name to inherit volumes from, and a restore command. The generated command decompresses the dump and pipes it to the restore command. ```go cmd, err := sshrestore.BuildDBRestoreCommand( "/tmp/backups/db.sql.gz", "dokploy-postgres", "psql -U dokploy -d dokploy", ) ``` -------------------------------- ### Adapter struct definition Source: https://github.com/assurrussa/dokploymigrator Defines the Adapter type with a PostgreSQL handle, allowlisted schema fingerprints, and the retargetable table list. ```go type Adapter struct { db *sql.DB allowedHashes map[string]struct{} requiredTables []string } ``` -------------------------------- ### ApplyRetargetPlan without explicit approval Source: https://github.com/assurrussa/dokploymigrator Calls ApplyRetargetPlan with an empty approval string. Returns "schema approval is required..." unless the allowlist covers the current hash. ```go err := adapter.ApplyRetargetPlan(ctx, plan, "") // no explicit approval if err != nil { // returns "schema approval is required..." unless allowlist covers current hash. } ``` -------------------------------- ### Manager.Plan usage example Source: https://github.com/assurrussa/dokploymigrator Calls Plan with a dead recovery mode and logs a fatal error if it fails. On success prints the plan ID, row count, and schema hash. ```go job, plan, err := manager.Plan(ctx, srcID, targetID, model.ModeDeadRecovery) if err != nil { log.Fatalf("plan failed: %v", err) } fmt.Printf("plan %s has %d rows, schemaHash %s\n", plan.ID, len(plan.Rows), plan.SchemaHash) ``` -------------------------------- ### OpenPostgres function signature Source: https://github.com/assurrussa/dokploymigrator Opens a Dokploy PostgreSQL adapter using driver pgx. Returns an error prefixed with 'open dokploy postgres:' when sql.Open fails. ```go func OpenPostgres(dsn string, allowedHashes []string) (*Adapter, error) ``` -------------------------------- ### NormalizeMigrationMode usage example Source: https://github.com/assurrussa/dokploymigrator Shows how to call NormalizeMigrationMode. An empty string normalizes to ModeDeadRecovery with ok true; an unknown mode returns ok false, so callers reject the mode before persisting a job. ```go normalized, ok := model.NormalizeMigrationMode("") // normalized == model.ModeDeadRecovery, ok == true normalized, ok = model.NormalizeMigrationMode(model.MigrationMode("bad_mode")) // ok == false, so callers reject the mode before persisting a job. ``` -------------------------------- ### Adapter.ValidateSchema Source: https://github.com/assurrussa/dokploymigrator Validates that the current database schema matches one of the allowed fingerprints. Returns an error if the schema is not allowed. ```APIDOC ## Adapter.ValidateSchema ### Description Validates that the current database schema matches one of the allowed fingerprints. ### Signature ```go func (a *Adapter) ValidateSchema() error ``` ### Returns - **error** (error) - Error if schema is not allowed. ``` -------------------------------- ### ApplyRetargetPlan with schema approval Source: https://github.com/assurrussa/dokploymigrator Applies a reviewed plan by passing plan.SchemaHash as the schema approval. On failure, the error may include a message like "retarget application/uuid affected 2 rows". ```go err := adapter.ApplyRetargetPlan(ctx, plan, plan.SchemaHash) if err != nil { // e.g. "retarget application/uuid affected 2 rows" log.Printf("apply failed: %v", err) } ``` -------------------------------- ### Manager.Apply usage example with error handling Source: https://github.com/assurrussa/dokploymigrator Applies a plan with schema hash approval and confirmation text "APPLY". Checks for the unexported errApplyConfirmationMissing error; since it is unexported, compare the message or avoid setting the wrong text. ```go err := manager.Apply(ctx, job.ID, plan, jobs.ApplyOptions{ SchemaHashApproval: plan.SchemaHash, ConfirmationText: "APPLY", }) if errors.Is(err, errApplyConfirmationMissing) { log.Fatal("confirmation text must be exactly APPLY") } ``` -------------------------------- ### RollbackRetargetPlan method signature Source: https://github.com/assurrussa/dokploymigrator Declares the RollbackRetargetPlan method on Adapter. Reverses metadata changes by swapping source/target and each row's oldServerId/newServerId, reversing row order, then delegating to ApplyRetargetPlan. Schema approval rules are identical to apply. ```go func (a *Adapter) RollbackRetargetPlan( ctx context.Context, plan model.MigrationPlan, schemaHashApproval string, ) error ``` -------------------------------- ### GET / Source: https://github.com/assurrussa/dokploymigrator Serves the embedded static files (index.html, app.js, style.css) via http.FileServer. Requires basic authentication. ```APIDOC ## [GET] / ### Description Serves the embedded static files (`internal/server/static/{index.html,app.js,style.css}`) via `http.FileServer`. ### Method GET ### Endpoint / ### Response #### Success Response (200) - Static files served. #### Failure Response (401) - Basic authentication required. ``` -------------------------------- ### Validate Dokploy Template Compose Configuration Source: https://github.com/assurrussa/dokploymigrator/blob/master/docs/dokploy-template.md Run this command to validate the draft Dokploy template's docker-compose configuration using the example environment file. It checks the Compose file syntax and variable substitution without deploying. ```sh docker compose --env-file templates/dokploy/env.example -f templates/dokploy/docker-compose.yml config ``` -------------------------------- ### GET /api/jobs Source: https://github.com/assurrussa/dokploymigrator Lists jobs with pagination support. Requires admin token. Supports limit and offset query parameters. ```APIDOC ## GET /api/jobs ### Description Returns a paginated list of jobs. ### Method GET ### Endpoint /api/jobs ### Parameters #### Query Parameters - **limit** (integer) - Optional - Maximum number of jobs to return (default 50, max 50) - **offset** (integer) - Optional - Number of jobs to skip (default 0) ### Response #### Success Response (200) - **jobs** (array) - List of job objects - **total** (integer) - Total number of jobs - **limit** (integer) - The limit used - **offset** (integer) - The offset used - **protectedCount** (integer) - Number of protected jobs (always 50) ``` -------------------------------- ### Set required environment variables for Dokploy Migrator Source: https://github.com/assurrussa/dokploymigrator/blob/master/README.md Configure the mandatory environment variables before deploying as a Docker Compose app in Dokploy. The container refuses to start without Basic Auth credentials and an admin token. Keep the Container Port set to 8080 in Dokploy Domains. ```sh MIGRATOR_BASIC_USER=admin MIGRATOR_BASIC_PASSWORD= MIGRATOR_ADMIN_TOKEN= DOKPLOY_POSTGRES_DSN=postgres://dokploy:@dokploy-postgres:5432/dokploy?sslmode=disable ``` -------------------------------- ### GET /api/jobs - Success Response JSON Source: https://github.com/assurrussa/dokploymigrator Example 200 response body for the paginated job history endpoint. The response contains a jobs array of state.Job objects, total count, limit, offset, and protectedCount which is always 50 (constant protectedJobCount). ```json { "jobs": [ ... ], "total": 12, "limit": 50, "offset": 0, "protectedCount": 50 } ``` -------------------------------- ### GET /api/servers Source: https://github.com/assurrussa/dokploymigrator Lists all servers managed by the migrator. Requires admin token. Database failures result in a 503 Service Unavailable response. ```APIDOC ## GET /api/servers ### Description Returns the list of servers. ### Method GET ### Endpoint /api/servers ### Response #### Success Response (200) - **servers** (array) - List of server objects #### Error Response (503) - **error** (string) - Error message ``` -------------------------------- ### ListenAndServe function signature Source: https://github.com/assurrussa/dokploymigrator Starts an http.Server (ReadHeaderTimeout = 5s) and blocks until the context is cancelled or the server errors. On context cancellation it calls Shutdown with a 5-second timeout (httpShutdownTimeout). Returns error: 'shutdown http server: ' on graceful shutdown failure, 'err' on non-ErrServerClosed ListenAndServe error, or nil on successful shutdown or http.ErrServerClosed. Source: internal/server/server.go lines 298–318. ```go func ListenAndServe(ctx context.Context, addr string, handler http.Handler) error ``` -------------------------------- ### DELETE /api/jobs/{id} - curl Example Source: https://github.com/assurrussa/dokploymigrator Example curl command to delete a job by ID. Requires Basic Auth credentials and an admin token (X-Migrator-Admin-Token header). The job ID must not be among the newest 50 protected jobs, otherwise a 409 error is returned. ```sh curl -fsS -X DELETE \ -u "$MIGRATOR_BASIC_USER:$MIGRATOR_BASIC_PASSWORD" \ -H "X-Migrator-Admin-Token: $MIGRATOR_ADMIN_TOKEN" \ "http://127.0.0.1:8080/api/jobs/job-1720000000000000000" ``` -------------------------------- ### GET /api/servers Source: https://github.com/assurrussa/dokploymigrator Lists servers. No admin token required. ```APIDOC ## [GET] /api/servers ### Description Lists servers. No admin token required. ### Method GET ### Endpoint /api/servers ### Response #### Success Response (200) - Array of servers. #### Failure Response (401) - Unauthorized. #### Failure Response (503) - Service unavailable. ``` -------------------------------- ### GET /api/jobs Source: https://github.com/assurrussa/dokploymigrator Lists jobs with paging. No admin token required. ```APIDOC ## [GET] /api/jobs ### Description Lists jobs with paging. No admin token required. ### Method GET ### Endpoint /api/jobs ### Response #### Success Response (200) - Paged object. #### Failure Response (401) - Unauthorized. #### Failure Response (500) - Internal server error. ``` -------------------------------- ### Verify named resources after apply with psql Source: https://github.com/assurrussa/dokploymigrator/blob/master/docs/operations.md Run after applying the migration to check that named resources (frontend, backend, pgsql, redis) now point to the expected server. Uses the dokploy-network and postgres:18 image; requires PGPASSWORD and the Dokploy PostgreSQL credentials. ```shell docker run --rm --network dokploy-network \ -e PGPASSWORD="$PASS" \ postgres:18 \ psql -h dokploy-postgres -U dokploy -d dokploy \ -v ON_ERROR_STOP=1 -P pager=off \ -c " select 'application' as type, \"name\", \"serverId\" from \"application\" where \"name\" = 'frontend' union all select 'compose', \"name\", \"serverId\" from \"compose\" where \"name\" = 'backend' union all select 'postgres', \"name\", \"serverId\" from \"postgres\" where \"name\" = 'pgsql' union all select 'redis', \"name\", \"serverId\" from \"redis\" where \"name\" = 'redis'; " ``` -------------------------------- ### CLI Apply Source: https://github.com/assurrussa/dokploymigrator/blob/master/docs/operations.md Applies a migration plan using the CLI. Requires explicit schema hash approval or the schema hash must be in the allowlist. ```APIDOC ## CLI Apply ### Description Applies a migration plan using the CLI. Requires explicit schema hash approval or the schema hash must be in the allowlist. ### Method CLI ### Command `dokploy-migrator apply` ### Parameters - `-job` (string) - Required - The job ID. - `-plan` (string) - Required - Path to the plan file. - `-schema-hash-approval` (string) - Optional - The schema hash to approve. If omitted, the current schema hash must be in `MIGRATOR_SCHEMA_ALLOWLIST`. - `-confirm` (string) - Required - Confirmation flag, set to `APPLY`. ### Request Example ```sh dokploy-migrator apply \ -job "$JOB_ID" \ -plan plan.json \ -schema-hash-approval "$SCHEMA_HASH" \ -confirm APPLY ``` ``` -------------------------------- ### GET /api/health Source: https://github.com/assurrussa/dokploymigrator Health check endpoint. Returns status ok. No admin token required. ```APIDOC ## [GET] /api/health ### Description Health check endpoint. Returns status ok. No admin token required. ### Method GET ### Endpoint /api/health ### Response #### Success Response (200) - **status** (string) - `"ok"` #### Failure Response (401) - Unauthorized. ``` -------------------------------- ### New(ctx context.Context, cfg Config) (*Client, error) Source: https://github.com/assurrussa/dokploymigrator Creates an S3 backup client. Requires a non-empty Bucket, defaults Region to us-east-1, and builds a static credentials provider if either credential is set. ```APIDOC ## New(ctx context.Context, cfg Config) (*Client, error) ### Description Creates an S3 backup client. Requires a non-empty `Bucket`. Defaults `Region` to `us-east-1`. If either credential is set, builds a static credentials provider. ### Parameters - **ctx** (context.Context) - Required - Context for the operation. - **cfg** (Config) - Required - Configuration for the client. ### Returns - **client** (*Client) - The created S3 backup client. - **error** (error) - Error if creation fails. ### Errors - `s3 bucket is required` - when `cfg.Bucket == ""`. - `load aws config: ` - when `config.LoadDefaultConfig` fails. ### Request Example ```go client, err := s3backup.New(ctx, s3backup.Config{ Endpoint: "https://s3.example.local", Region: "us-east-1", Bucket: "dokploy-backups", Prefix: "backups/", AccessKeyID: "AK...", SecretAccessKey: "secret", }) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### curl GET /api/servers Source: https://github.com/assurrussa/dokploymigrator Lists Dokploy servers with status and resource counts. Basic Auth only. ```sh curl -fsS -u "$MIGRATOR_BASIC_USER:$MIGRATOR_BASIC_PASSWORD" http://127.0.0.1:8080/api/servers ``` -------------------------------- ### BuildDBRestoreCommand Source: https://github.com/assurrussa/dokploymigrator Returns a Docker command that feeds a gzip'd dump to a database restore container. The command uses the format: docker run --rm --volumes-from -v :/backup:ro alpine:3.23.5 sh -c 'gzip -dc /backup/ | '. The image is always the default alpine:3.23.5. ```APIDOC ## Function `BuildDBRestoreCommand` ### Description Returns a Docker command that feeds a gzip'd dump to a database restore container. ### Signature ```go func BuildDBRestoreCommand(archivePath string, containerName string, restoreCommand string) (string, error) ``` ### Parameters - **archivePath** (string) - Required - Host path to the `.gz` dump. - **containerName** (string) - Required - Container to inherit volumes from. - **restoreCommand** (string) - Required - Restore command receiving the decompressed stream. ### Returns - **string** - The Docker command string. - **error** - Returns `archive path, container name, and restore command are required` when any is empty. ### Example ```go cmd, err := sshrestore.BuildDBRestoreCommand( "/tmp/backups/db.sql.gz", "dokploy-postgres", "psql -U dokploy -d dokploy", ) ``` ``` -------------------------------- ### GET /api/servers Source: https://github.com/assurrussa/dokploymigrator Lists Dokploy servers with status and resource counts. Requires HTTP Basic Auth only. ```APIDOC ## [GET] /api/servers ### Description Lists Dokploy servers with status and resource counts. Basic Auth only. ### Method GET ### Endpoint /api/servers ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **id** (string) - Server ID (or `__dokploy_local__`). - **name** (string) - Display name. - **status** (string) - `online` / `offline` / `unknown`. - **lastSeenAt** (string, RFC3339) - Last activity; omitted when nil. - **resourceCount** (integer) - Attached supported resource count. #### Error Response (503) - **error** (string) - Error message when the DB adapter is missing or fails. ### Request Example ```sh curl -fsS -u "$MIGRATOR_BASIC_USER:$MIGRATOR_BASIC_PASSWORD" http://127.0.0.1:8080/api/servers ``` ``` -------------------------------- ### curl GET /api/health Source: https://github.com/assurrussa/dokploymigrator Liveness probe request using Basic Auth credentials from environment variables. ```sh curl -fsS -u "$MIGRATOR_BASIC_USER:$MIGRATOR_BASIC_PASSWORD" http://127.0.0.1:8080/api/health ``` -------------------------------- ### GET /api/jobs Source: https://github.com/assurrussa/dokploymigrator/blob/master/docs/operations.md Lists a page of job history. The API returns jobs in pages of 50 records, with the newest 50 jobs protected from deletion. ```APIDOC ## [GET] /api/jobs ### Description Lists a page of job history. The API returns jobs in pages of 50 records, with the newest 50 jobs protected from deletion. ### Method GET ### Endpoint /api/jobs ### Parameters #### Query Parameters - **limit** (integer) - Optional - Number of records to return (e.g., 50). - **offset** (integer) - Optional - Number of records to skip (e.g., 50). ### Response #### Success Response (200) - **jobs** (array) - List of job records. ### Request Example ```sh curl -fsS \ -u "$MIGRATOR_BASIC_USER:$MIGRATOR_BASIC_PASSWORD" \ "https://migrator.example.com/api/jobs?limit=50&offset=50" ``` ``` -------------------------------- ### GET /api/health Source: https://github.com/assurrussa/dokploymigrator Liveness probe endpoint that returns a fixed status field. Requires HTTP Basic Auth but no admin token. ```APIDOC ## [GET] /api/health ### Description Liveness probe. Basic Auth required. No admin token. ### Method GET ### Endpoint /api/health ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **status** (string) - Fixed value `ok`. ### Request Example ```sh curl -fsS -u "$MIGRATOR_BASIC_USER:$MIGRATOR_BASIC_PASSWORD" http://127.0.0.1:8080/api/health ``` #### Response Example ```json {"status":"ok"} ``` ``` -------------------------------- ### Adapter.Close Source: https://github.com/assurrussa/dokploymigrator Closes the underlying PostgreSQL database handle. This method is part of the Adapter type and should be called when the adapter is no longer needed. ```APIDOC ## Adapter.Close ### Description Closes the underlying PostgreSQL database handle. ### Signature ```go func (a *Adapter) Close() error ``` ### Returns - **error** (error) - Error if closing fails. ### Example ```go defer adapter.Close() ``` ``` -------------------------------- ### Environment configuration variables Source: https://github.com/assurrussa/dokploymigrator/blob/master/README.md Lists all environment variables used by the migrator. `MIGRATOR_ADDR` sets the listen address, `MIGRATOR_STATE_PATH` the SQLite state file, `MIGRATOR_BASIC_USER`/`MIGRATOR_BASIC_PASSWORD` basic auth credentials, `MIGRATOR_ADMIN_TOKEN` an admin token, `DOKPLOY_POSTGRES_DSN` the Postgres DSN, `MIGRATOR_SCHEMA_ALLOWLIST` a schema allowlist, `MIGRATOR_DEAD_AFTER` the dead-server threshold (default `10m`), `DOKPLOY_API_BASE_URL` the Dokploy API base (optional, used only for reachability checks), `DOKPLOY_API_TOKEN` the API token, `DOKPLOY_HEALTH_PATH` the health path (default `/health`), and `DOKPLOY_DEPLOY_PATH` the deploy path. ```sh MIGRATOR_ADDR=:8080 MIGRATOR_STATE_PATH=/data/dokploy-migrator.sqlite MIGRATOR_BASIC_USER=admin MIGRATOR_BASIC_PASSWORD= MIGRATOR_ADMIN_TOKEN= DOKPLOY_POSTGRES_DSN= MIGRATOR_SCHEMA_ALLOWLIST= MIGRATOR_DEAD_AFTER=10m DOKPLOY_API_BASE_URL= DOKPLOY_API_TOKEN= DOKPLOY_HEALTH_PATH=/health DOKPLOY_DEPLOY_PATH= ``` -------------------------------- ### APIClient.Health Source: https://github.com/assurrussa/dokploymigrator Checks the health of the Dokploy API by issuing a GET request to the health endpoint. Returns an error if the request fails or the status is non-2xx. ```APIDOC ## [GET] baseURL+healthPath ### Description Issues a `GET baseURL+healthPath` and treats any non-2xx status or transport failure as an error. Adds `Authorization: Bearer ` when a token is set. ### Method GET ### Endpoint `baseURL+healthPath` ### Parameters #### Headers - **Authorization** (string) - Optional - Bearer token, added when a token is set. ### Response #### Success Response (2xx) - No content or empty body. #### Error Response - **Non-2xx status** - Returns an error with message `dokploy health returned HTTP `. - **Transport error** - Returns an error with message `call Dokploy health: `. - **Request construction failure** - Returns an error with message `build health request: `. - **Base URL not configured** - Returns an error with message `dokploy API base URL is not configured` when `baseURL == ""`. ### Request Example ```go client := jobs.NewAPIClient("http://dokploy:3000/api", "tok", "/health", "/deploy") if err := client.Health(ctx); err != nil { log.Printf("Dokploy unreachable: %v", err) } ``` ``` -------------------------------- ### New Source: https://github.com/assurrussa/dokploymigrator Constructs a new S3 backup Client from the provided Config. It sets up the AWS S3 client with the configured endpoint, region, and static credentials, and normalizes the prefix. ```APIDOC ## New ### Description Constructs a new S3 backup Client from the provided Config. It sets up the AWS S3 client with the configured endpoint, region, and static credentials, and normalizes the prefix. ### Method Constructor ### Parameters - **config** (Config) - Required - Configuration for the S3 client. ### Returns - **Client** - A new S3 backup client. - **error** - An error if the client could not be created. ``` -------------------------------- ### GET /api/jobs Source: https://github.com/assurrussa/dokploymigrator Retrieves a paginated list of job history. Requires Basic Auth. Supports limit and offset query parameters for pagination. ```APIDOC ## GET /api/jobs ### Description Paginated job history. Basic Auth only. ### Method GET ### Endpoint /api/jobs ### Parameters #### Query Parameters - **limit** (integer) - Optional - Page size. Default: 50, Max: 50. Non-positive → default; above max → clamped. - **offset** (integer) - Optional - Jobs to skip in newest-first order. Default: 0. Negative → 0. ### Response #### Success Response (200) - **jobs** (array of state.Job) - List of jobs. - **total** (integer) - Total number of jobs. - **limit** (integer) - The limit used. - **offset** (integer) - The offset used. - **protectedCount** (integer) - Always 50 (constant protectedJobCount). #### state.Job schema - **id** (string) - Job ID. - **sourceServerId** (string) - Source server. - **targetServerId** (string) - Target server. - **mode** (string) - Migration mode string. - **status** (string) - pending/running/paused/succeeded/failed/rolled_back. - **checkpoint** (string) - Job checkpoint. - **createdAt** (string, RFC3339) - Creation time. - **updatedAt** (string, RFC3339) - Last update time. #### Failure Response (500) - **error** (string) - Error message on store errors. ### Request Example ```sh curl -fsS -u "$MIGRATOR_BASIC_USER:$MIGRATOR_BASIC_PASSWORD" \ "http://127.0.0.1:8080/api/jobs?limit=50&offset=50" ``` #### Response Example ```json { "jobs": [ ... ], "total": 12, "limit": 50, "offset": 0, "protectedCount": 50 } ``` ``` -------------------------------- ### GET /api/health success response Source: https://github.com/assurrussa/dokploymigrator Fixed JSON body returned on a successful liveness probe. Basic Auth required, no admin token. ```json {"status":"ok"} ``` -------------------------------- ### GET /api/health Source: https://github.com/assurrussa/dokploymigrator Health check endpoint that returns service status. No admin token is required to access this endpoint. ```APIDOC ## GET /api/health ### Description Returns the health status of the server. ### Method GET ### Endpoint /api/health ### Response #### Success Response (200) - **status** (string) - Always "ok" #### Response Example ```json {"status":"ok"} ``` ``` -------------------------------- ### POST /api/apply Source: https://github.com/assurrussa/dokploymigrator/blob/master/docs/operations.md Applies a reviewed dry-run plan to migrate Dokploy metadata. Requires HTTP Basic Auth and X-Migrator-Admin-Token. The request body must include the job ID, the complete plan from the dry-run, schema hash approval, and confirmation text 'APPLY'. ```APIDOC ## POST /api/apply ### Description Applies the reviewed dry-run plan to migrate Dokploy metadata. This endpoint requires HTTP Basic Auth and `X-Migrator-Admin-Token`. Send `Content-Type: application/json` with the JSON body. ### Method POST ### Endpoint /api/apply ### Parameters #### Request Body - **jobId** (string) - Required - The ID of the dry-run job. - **plan** (object) - Required - The complete plan returned by the dry-run. Must include all fields: id, sourceServerId, targetServerId, createdAt, schemaHash, and rows. - **plan.id** (string) - Required - Plan ID from the dry-run. - **plan.sourceServerId** (string) - Required - Source server ID. - **plan.targetServerId** (string) - Required - Target server ID (e.g., `__dokploy_local__`). - **plan.createdAt** (string) - Required - Creation timestamp of the plan. - **plan.schemaHash** (string) - Required - Schema hash from the dry-run. - **plan.rows** (array) - Required - Nonempty subset of the original plan rows. Do not fabricate or alter rows. - **plan.rows[].table** (string) - Required - Table name. - **plan.rows[].idColumn** (string) - Required - ID column name. - **plan.rows[].id** (string) - Required - Row ID. - **plan.rows[].name** (string) - Required - Row name. - **plan.rows[].oldServerId** (string) - Required - Old server ID. - **plan.rows[].newServerId** (string) - Required - New server ID. - **schemaHashApproval** (string) - Required - The reviewed schema hash. Leave empty only if `MIGRATOR_SCHEMA_ALLOWLIST` contains that hash. - **confirmationText** (string) - Required - Must be exactly `APPLY`. ### Response #### Success Response (200) - **status** (string) - Always `applied`. ### Request Example ```json { "jobId": "job-from-dry-run", "plan": { "id": "plan-from-dry-run", "sourceServerId": "source-server-id", "targetServerId": "__dokploy_local__", "createdAt": "2026-01-01T00:00:00Z", "schemaHash": "schema-hash-from-dry-run", "rows": [ { "table": "application", "idColumn": "applicationId", "id": "application-id-from-dry-run", "name": "application-name-from-dry-run", "oldServerId": "source-server-id", "newServerId": "__dokploy_local__" } ] }, "schemaHashApproval": "schema-hash-from-dry-run", "confirmationText": "APPLY" } ``` ### Response Example ```json {"status":"applied"} ``` ``` -------------------------------- ### Handle state.ErrJobNotFound with errors.Is Source: https://github.com/assurrussa/dokploymigrator Use errors.Is to check for the exported sentinel error state.ErrJobNotFound. The example shows a not-found path and a fallback that logs the error with log.Printf. ```go import "github.com/assurrussa/dokploymigrator/internal/state" if err := store.GetJob(ctx, id); err != nil { if errors.Is(err, state.ErrJobNotFound) { // not found path } else { log.Printf("store error: %v", err) } } ``` -------------------------------- ### Function New signature Source: https://github.com/assurrussa/dokploymigrator Declares the New constructor that creates a Server from a Config, state store, and job manager. ```go func New(cfg Config, store *state.Store, manager *jobs.Manager) *Server ``` -------------------------------- ### Executor.Run method signature Source: https://github.com/assurrussa/dokploymigrator Executes a remote command and returns combined stdout+stderr. Sends ssh.SIGKILL if the context is cancelled. Returns an error on non-zero exit or cancellation. ```go func (e *Executor) Run(ctx context.Context, command string) ([]byte, error) ``` -------------------------------- ### Build Dokploy PostgreSQL DSN Source: https://github.com/assurrussa/dokploymigrator/blob/master/docs/operations.md Constructs the PostgreSQL connection string using the password from the previous step. The DSN uses database/user dokploy and disables SSL. ```shell printf 'postgres://dokploy:%s@dokploy-postgres:5432/dokploy?sslmode=disable\n' "$PASS" ``` -------------------------------- ### POST /api/plan request body Source: https://github.com/assurrussa/dokploymigrator/blob/master/docs/operations.md JSON body for creating a dry-run plan. Requires HTTP Basic Auth and X-Migrator-Admin-Token. The endpoint creates a job and stores the plan without applying writes. `sourceServerId` and `targetServerId` must select different servers; `__dokploy_local__` is a marker for local server. Omitted `mode` defaults to `dead_recovery`. ```json { "sourceServerId": "source-server-id", "targetServerId": "__dokploy_local__", "mode": "dead_recovery" } ``` -------------------------------- ### Executor struct definition Source: https://github.com/assurrussa/dokploymigrator Holds the SSH client for running restore commands on the target server. ```go type Executor struct { client *ssh.Client } ```