Skip to content

Commit

Permalink
feat: remove docker image on uninstall
Browse files Browse the repository at this point in the history
Fixes #86
  • Loading branch information
agaffney committed Mar 6, 2024
1 parent 05c3a09 commit a7f6f3a
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 19 deletions.
31 changes: 25 additions & 6 deletions pkgmgr/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,10 +330,7 @@ func (d *DockerService) refresh() error {

func (d *DockerService) getClient() (*client.Client, error) {
if d.client == nil {
tmpClient, err := client.NewClientWithOpts(
client.WithAPIVersionNegotiation(),
client.WithHostFromEnv(),
)
tmpClient, err := NewDockerClient()
if err != nil {
return nil, err
}
Expand All @@ -342,10 +339,32 @@ func (d *DockerService) getClient() (*client.Client, error) {
return d.client, nil
}

func NewDockerClient() (*client.Client, error) {
tmpClient, err := client.NewClientWithOpts(
client.WithAPIVersionNegotiation(),
client.WithHostFromEnv(),
)
if err != nil {
return nil, err
}
return tmpClient, nil
}

func CheckDockerConnectivity() error {
tmpDockerService := &DockerService{}
if _, err := tmpDockerService.getClient(); err != nil {
if _, err := NewDockerClient(); err != nil {
return errors.New(dockerInstallError)
}
return nil
}

func RemoveDockerImage(image string) error {
client, err := NewDockerClient()
if err != nil {
return err
}
_, err = client.ImageRemove(context.Background(), image, types.ImageRemoveOptions{})
if err != nil {
return err
}
return nil
}
40 changes: 27 additions & 13 deletions pkgmgr/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -323,22 +323,36 @@ func (p *PackageInstallStepDocker) install(cfg Config, pkgName string) error {
}

func (p *PackageInstallStepDocker) uninstall(cfg Config, pkgName string) error {
// Nothing to uninstall if we were only fetching the image
if p.PullOnly {
return nil
}
containerName := fmt.Sprintf("%s-%s", pkgName, p.ContainerName)
svc, err := NewDockerServiceFromContainerName(containerName, cfg.Logger)
if err != nil {
return err
}
if running, _ := svc.Running(); running {
if err := svc.Stop(); err != nil {
if !p.PullOnly {
containerName := fmt.Sprintf("%s-%s", pkgName, p.ContainerName)
svc, err := NewDockerServiceFromContainerName(containerName, cfg.Logger)
if err != nil {
return err
}
if running, _ := svc.Running(); running {
if err := svc.Stop(); err != nil {
return err
}
}
if err := svc.Remove(); err != nil {
return err
}
}
if err := svc.Remove(); err != nil {
return err
if err := RemoveDockerImage(p.Image); err != nil {
cfg.Logger.Debug(
fmt.Sprintf(
"failed to delete image %q: %s",
p.Image,
err,
),
)
} else {
cfg.Logger.Debug(
fmt.Sprintf(
"removed unused image %q",
p.Image,
),
)
}
return nil
}
Expand Down

0 comments on commit a7f6f3a

Please sign in to comment.