Files
dokku/plugins/registry/subcommands.go
T
Jose Diaz-Gonzalez 9df45f6a6e fix: serialize concurrent property updates
Concurrent commands for the same app could each read a setting, change it, and write it back, so all of them exited successfully while silently dropping changes made by the others. Updates to app settings are now serialized so every change is kept, and readers never see a partially written value.
2026-10-21 21:21:57 -04:00

248 lines
6.8 KiB
Go

package registry
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/dokku/dokku/plugins/common"
)
// readPasswordFromStdin reads a registry password from stdin
func readPasswordFromStdin() (string, error) {
stdin, err := io.ReadAll(os.Stdin)
if err != nil {
return "", err
}
return strings.TrimSpace(string(stdin)), nil
}
// CommandAuthStatus reports whether the stored registry credential matches the
// requested state, communicating the result via the exit code alone
func CommandAuthStatus(appName string, server string, username string, password string, passwordStdin bool) error {
if passwordStdin {
if username == "" {
return InvalidAuthStatusArguments("Missing username argument")
}
stdin, err := readPasswordFromStdin()
if err != nil {
return InvalidAuthStatusArguments(err.Error())
}
password = stdin
}
if server == "" {
return InvalidAuthStatusArguments("Missing server argument")
}
if username != "" && password == "" {
return InvalidAuthStatusArguments("Missing password argument")
}
if username == "" && password != "" {
return InvalidAuthStatusArguments("Missing username argument")
}
configPath := GetGlobalRegistryConfigPath()
if appName != "" {
if err := common.VerifyAppName(appName); err != nil {
// a missing app carries its own exit code, while an invalid name is
// a malformed call and must not be reported as a missing credential
if _, ok := err.(common.ErrWithExitCode); ok {
return err
}
return InvalidAuthStatusArguments(err.Error())
}
configPath = GetAppRegistryConfigPath(appName)
}
contents, err := os.ReadFile(configPath)
if err != nil && !os.IsNotExist(err) {
return &common.ExitCodeError{
Code: authStatusUnknown,
Message: fmt.Sprintf("Unable to read the docker config: %s", err.Error()),
}
}
code, message := checkAuthStatus(authStatusInput{
ConfigBytes: contents,
Server: server,
Username: username,
Password: password,
})
if code == authStatusMatch {
return nil
}
return &common.ExitCodeError{Code: code, Message: message}
}
// InvalidAuthStatusArguments reports a registry:auth-status call that could not be checked
func InvalidAuthStatusArguments(message string) error {
return &common.ExitCodeError{Code: authStatusInvalidArguments, Message: message}
}
// CommandLogin logs a user into the specified server
func CommandLogin(appName string, server string, username string, password string, passwordStdin bool) error {
if passwordStdin {
stdin, err := readPasswordFromStdin()
if err != nil {
return err
}
password = stdin
}
if server == "" {
return errors.New("Missing server argument")
}
if username == "" {
return errors.New("Missing username argument")
}
if password == "" {
return errors.New("Missing password argument")
}
server = normalizeRegistryServer(server)
buffer := bytes.Buffer{}
buffer.Write([]byte(password + "\n"))
env := map[string]string{}
if appName != "" {
if err := common.VerifyAppName(appName); err != nil {
return err
}
configDir := GetAppRegistryConfigDir(appName)
if err := os.MkdirAll(configDir, 0700); err != nil {
return fmt.Errorf("Unable to create registry config directory: %w", err)
}
env["DOCKER_CONFIG"] = GetAppRegistryConfigDir(appName)
}
result, err := execDockerConfigCommand(env["DOCKER_CONFIG"], common.ExecCommandInput{
Command: common.DockerBin(),
Args: []string{"login", "--username", username, "--password-stdin", server},
Env: env,
Stdin: &buffer,
})
if err != nil {
return fmt.Errorf("Unable to run docker login: %w", err)
}
if result.ExitCode != 0 {
return fmt.Errorf("Unable to run docker login: %s", result.StderrContents())
}
if appName != "" {
common.LogWarn(fmt.Sprintf("Login Succeeded for %s", appName))
} else {
common.LogWarn("Login Succeeded for global registry")
}
// todo: change the signature of the trigger to include the app name
_, err = common.CallPlugnTrigger(common.PlugnTriggerInput{
Trigger: "post-registry-login",
Args: []string{server, username},
StreamStdio: true,
Env: map[string]string{
"DOCKER_REGISTRY_PASS": password,
},
})
if err != nil {
return err
}
return nil
}
// CommandLogout logs a user out from the specified server
func CommandLogout(appName string, server string) error {
if server == "" {
return errors.New("Missing server argument")
}
// docker only erases the exact auths key it is given, and stores Docker Hub
// under the index server address rather than the hostname logged in with, so
// a logout for docker.io has to name that address to remove anything
server = dockerAuthKey(server)
env := map[string]string{}
if appName != "" {
if err := common.VerifyAppName(appName); err != nil {
return err
}
configDir := GetAppRegistryConfigDir(appName)
if !common.DirectoryExists(configDir) {
return fmt.Errorf("No registry credentials found for app %s", appName)
}
env["DOCKER_CONFIG"] = GetAppRegistryConfigDir(appName)
}
result, err := execDockerConfigCommand(env["DOCKER_CONFIG"], common.ExecCommandInput{
Command: common.DockerBin(),
Args: []string{"logout", server},
Env: env,
})
if err != nil {
return fmt.Errorf("Unable to run docker logout: %w", err)
}
if result.ExitCode != 0 {
return fmt.Errorf("Unable to run docker logout: %s", result.StderrContents())
}
return nil
}
// CommandReport displays a registry report for one or more apps
func CommandReport(appName string, format string, infoFlag string) error {
if len(appName) == 0 {
apps, err := common.DokkuApps()
if err != nil {
if errors.Is(err, common.NoAppsExist) {
common.LogWarn(err.Error())
return nil
}
return err
}
for _, appName := range apps {
if err := ReportSingleApp(appName, format, infoFlag); err != nil {
return err
}
}
return nil
}
return ReportSingleApp(appName, format, infoFlag)
}
// CommandSet set or clear a registry property for an app
func CommandSet(appName string, property string, value string) error {
common.CommandPropertySet("registry", appName, property, value, DefaultProperties, GlobalProperties)
return nil
}
// execDockerConfigCommand runs a docker command that rewrites the credentials
// file in configDir. docker merges the file it reads with the change it makes,
// so the directory stays locked for the whole command to keep concurrent logins
// and logouts for one app from dropping each other's credentials. An empty
// configDir means docker's own config, which is left unlocked.
func execDockerConfigCommand(configDir string, input common.ExecCommandInput) (common.ExecCommandResponse, error) {
if configDir == "" {
return common.CallExecCommand(input)
}
var result common.ExecCommandResponse
err := common.LockDirectory(configDir, func() error {
var err error
result, err = common.CallExecCommand(input)
return err
})
return result, err
}