info: improve handling of empty Info

Before this change, the function could print an error in some cases, for example;

```bash
docker -H tcp://127.0.0.1:2375 info --format '{{.LoggingDriver}}'

template: :1:2: executing "" at <.LoggingDriver>: reflect: indirection through nil pointer to embedded struct field Info
```

With this patch applied, the error is handled gracefully, and when failing to
connect with the daemon, the error is logged;

```bash
docker -H tcp://127.0.0.1:2375 info --format '{{.LoggingDriver}}'
Cannot connect to the Docker daemon at tcp://127.0.0.1:2375. Is the docker daemon running?

docker -H tcp://127.0.0.1:2375 info --format '{{json .}}'
Cannot connect to the Docker daemon at tcp://127.0.0.1:2375. Is the docker daemon running?
{"ID":"","Containers":0,"..."}}
```

Note that the connection error is also included in the JSON `ServerErrors` field,
so that the information does not get lost, even if STDERR would be redirected;

```bash
docker -H tcp://127.0.0.1:2375 info --format '{{json .ServerErrors}}' 2> /dev/null
["Cannot connect to the Docker daemon at tcp://127.0.0.1:2375. Is the docker daemon running?"]
```

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2022-05-06 16:15:20 +02:00
parent 4cc4385075
commit e96e17d102
No known key found for this signature in database
GPG Key ID: 76698F39D527CE8C
1 changed files with 7 additions and 5 deletions

View File

@ -67,11 +67,12 @@ func NewInfoCommand(dockerCli command.Cli) *cobra.Command {
}
func runInfo(cmd *cobra.Command, dockerCli command.Cli, opts *infoOptions) error {
var info info
info.ClientInfo = &clientInfo{
info := info{
ClientInfo: &clientInfo{
Context: dockerCli.CurrentContext(),
Debug: debug.IsEnabled(),
},
Info: &types.Info{},
}
if plugins, err := pluginmanager.ListPlugins(dockerCli, cmd.Root()); err == nil {
info.ClientInfo.Plugins = plugins
@ -84,6 +85,7 @@ func runInfo(cmd *cobra.Command, dockerCli command.Cli, opts *infoOptions) error
if dinfo, err := dockerCli.Client().Info(ctx); err == nil {
info.Info = &dinfo
} else {
fmt.Fprintln(dockerCli.Err(), err)
info.ServerErrors = append(info.ServerErrors, err.Error())
}
}