terraform-provider-docker/internal/provider/resource_docker_plugin_funcs.go
Manuel Vogel 0588c2071b
chore/refactor tests (#201)
* chore: format test configs for datasources

* chore: outlines load test config helper and structure

* docs(contributing): add command for resouce tests

to have an example of the regex

* refactor: move container test configs into separate files

* fix: add insecure_skip_verify for image pulls

to fix the local test setup with invalid certs

* chore(ci): remove insecure registry adaption

* chore: regenerate website

* chore: update gitignore for scipts/testing dir

* fix: replace nodejs services with go versions

* fix: move testing program versions in separate files

* test: reactivate flaky test from travis

* chore: fix linter on all go files

* fix(linter): testing go servers

* chore(ci): add env for go version

* chore(ci): name workflow steps

also moves description of available docker versions in to acc dockerfile

* Revert "test: reactivate flaky test from travis"

This reverts commit b02654acc4d6b7d02c8f3ba090e6a3f248741b10.

* docs: fix provider-ssh example

* chore: use alpine als final image for tests

* refactor: move test configs from folder into testname.tf files

* refactor: image delete log is now debug and indented

* refactor: image test config into seprate files

* refactor: move network test config into seperate files

* refactor: move plugin test config into seperate files

* chore: rename registry image test file

* refactor: move registry_image test config into seperate files

* chore: format secret test configs

* refactor: inline volume test configs

* fix: remove unused volume label test function

* refactor: move service test configs into seperate files

* test: reactivate and fix service test

* chore: simplify insecure skip verify add to http client

* chore(ci): debug into service test

* chore(ci): add testacc setup

* chore: format tf config for provider test

* chore(ci): add debug output for config.json

* fix: check service auth for emptyness

* fix: remove re-read of provider auth config

because the bug occured only in CI as the meta object might be GCd

* test: pass auth to service instead of provider

* chore: reactivate all acc tests

* test: outlines service inspect json check for full spec

* test: add service inspect json checks

* test: finish service inspect json checks

* chore(service): move test helper to end to of the file

* chore: move mapEquals to test helpers

* test: add json inspect for config

* chore: add debug inspect log for plugin, secret and volume

* test: add json inspect for secret

* test: add json inspect for image

* test: add json inspect for network

* test: add json inspect for plugin

* test: add json inspect for volume

* test: inline ds plugin test configs

* test: inline network configs

* test: move ds reg image configs into separate files

* test: reactivates container upload checks

* chore: adapt issues ref from old to new xw repo

* fix: reactivate network ingress test

and provide helpers for removing the default ingress network and leaving the swamr

* docs: rerun website gen

* test: fix reg image build and keep test

* chore: add name to todo

* chore: move ds network and plugin specs to file

* chore: format provider test spec

* chore: use simpler error message for empty strings
2021-05-31 16:11:49 +09:00

268 lines
7.9 KiB
Go

package provider
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"strings"
"github.com/docker/distribution/reference"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceDockerPluginCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ProviderConfig).DockerClient
ctx := context.Background()
pluginName := d.Get("name").(string)
alias := d.Get("alias").(string)
log.Printf("[DEBUG] Install a Docker plugin " + pluginName)
opts := types.PluginInstallOptions{
RemoteRef: pluginName,
AcceptAllPermissions: d.Get("grant_all_permissions").(bool),
Disabled: !d.Get("enabled").(bool),
// TODO suzuki-shunsuke: support other settings
Args: getDockerPluginEnv(d.Get("env")),
}
if v, ok := d.GetOk("grant_permissions"); ok {
opts.AcceptPermissionsFunc = getDockerPluginGrantPermissions(v)
}
body, err := client.PluginInstall(ctx, alias, opts)
if err != nil {
return fmt.Errorf("install a Docker plugin "+pluginName+": %w", err)
}
_, _ = ioutil.ReadAll(body)
key := pluginName
if alias != "" {
key = alias
}
plugin, _, err := client.PluginInspectWithRaw(ctx, key)
if err != nil {
return fmt.Errorf("inspect a Docker plugin "+key+": %w", err)
}
setDockerPlugin(d, plugin)
return nil
}
func resourceDockerPluginRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ProviderConfig).DockerClient
ctx := context.Background()
pluginID := d.Id()
plugin, _, err := client.PluginInspectWithRaw(ctx, pluginID)
if err != nil {
log.Printf("[DEBUG] Inspect a Docker plugin "+pluginID+": %w", err)
d.SetId("")
return nil
}
jsonObj, _ := json.MarshalIndent(plugin, "", "\t")
log.Printf("[DEBUG] Docker plugin inspect from readFunc: %s", jsonObj)
setDockerPlugin(d, plugin)
return nil
}
func resourceDockerPluginDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ProviderConfig).DockerClient
ctx := context.Background()
pluginID := d.Id()
log.Printf("[DEBUG] Remove a Docker plugin " + pluginID)
if err := client.PluginRemove(ctx, pluginID, types.PluginRemoveOptions{
Force: d.Get("force_destroy").(bool),
}); err != nil {
return fmt.Errorf("remove the Docker plugin "+pluginID+": %w", err)
}
return nil
}
// Helpers
func getDockerPluginEnv(src interface{}) []string {
if src == nil {
return nil
}
b := src.(*schema.Set)
envs := make([]string, b.Len())
for i, a := range b.List() {
envs[i] = a.(string)
}
return envs
}
func dockerPluginGrantPermissionsSetFunc(v interface{}) int {
return schema.HashString(v.(map[string]interface{})["name"].(string))
}
func complementTag(image string) string {
if strings.Contains(image, ":") {
return image
}
return image + ":latest"
}
func normalizePluginName(name string) (string, error) {
ref, err := reference.ParseAnyReference(name)
if err != nil {
return "", fmt.Errorf("parse the plugin name: %w", err)
}
return complementTag(ref.String()), nil
}
func diffSuppressFuncPluginName(k, oldV, newV string, d *schema.ResourceData) bool {
o, err := normalizePluginName(oldV)
if err != nil {
return false
}
n, err := normalizePluginName(newV)
if err != nil {
return false
}
return o == n
}
func validateFuncPluginName(val interface{}, key string) (warns []string, errs []error) {
if _, err := normalizePluginName(val.(string)); err != nil {
return warns, append(errs, fmt.Errorf("%s is invalid: %w", key, err))
}
return
}
func getDockerPluginGrantPermissions(src interface{}) func(types.PluginPrivileges) (bool, error) {
grantPermissionsSet := src.(*schema.Set)
grantPermissions := make(map[string]map[string]struct{}, grantPermissionsSet.Len())
for _, b := range grantPermissionsSet.List() {
c := b.(map[string]interface{})
name := c["name"].(string)
values := c["value"].(*schema.Set)
grantPermission := make(map[string]struct{}, values.Len())
for _, value := range values.List() {
grantPermission[value.(string)] = struct{}{}
}
grantPermissions[name] = grantPermission
}
return func(privileges types.PluginPrivileges) (bool, error) {
for _, privilege := range privileges {
grantPermission, nameOK := grantPermissions[privilege.Name]
if !nameOK {
log.Print("[DEBUG] to install the plugin, the following permissions are required: " + privilege.Name)
return false, nil
}
for _, value := range privilege.Value {
if _, ok := grantPermission[value]; !ok {
log.Print("[DEBUG] to install the plugin, the following permissions are required: " + privilege.Name + " " + value)
return false, nil
}
}
}
return true, nil
}
}
func setDockerPlugin(d *schema.ResourceData, plugin *types.Plugin) {
d.SetId(plugin.ID)
d.Set("plugin_reference", plugin.PluginReference)
d.Set("alias", plugin.Name)
d.Set("name", plugin.PluginReference)
d.Set("enabled", plugin.Enabled)
// TODO suzuki-shunsuke support other settings
// https://docs.docker.com/engine/reference/commandline/plugin_set/#extended-description
// source of mounts .Settings.Mounts
// path of devices .Settings.Devices
// args .Settings.Args
d.Set("env", plugin.Settings.Env)
}
func disablePlugin(ctx context.Context, d *schema.ResourceData, cl *client.Client) error {
pluginID := d.Id()
log.Printf("[DEBUG] Disable a Docker plugin " + pluginID)
if err := cl.PluginDisable(ctx, pluginID, types.PluginDisableOptions{
Force: d.Get("force_disable").(bool),
}); err != nil {
return fmt.Errorf("disable the Docker plugin "+pluginID+": %w", err)
}
return nil
}
func enablePlugin(ctx context.Context, d *schema.ResourceData, cl *client.Client) error {
pluginID := d.Id()
log.Print("[DEBUG] Enable a Docker plugin " + pluginID)
if err := cl.PluginEnable(ctx, pluginID, types.PluginEnableOptions{
Timeout: d.Get("enable_timeout").(int),
}); err != nil {
return fmt.Errorf("enable the Docker plugin "+pluginID+": %w", err)
}
return nil
}
func pluginSet(ctx context.Context, d *schema.ResourceData, cl *client.Client) error {
pluginID := d.Id()
log.Printf("[DEBUG] Update settings of a Docker plugin " + pluginID)
// currently, only environment variables are supported.
// TODO support other args
// https://docs.docker.com/engine/reference/commandline/plugin_set/#extended-description
// source of mounts .Settings.Mounts
// path of devices .Settings.Devices
// args .Settings.Args
if err := cl.PluginSet(ctx, pluginID, getDockerPluginEnv(d.Get("env"))); err != nil {
return fmt.Errorf("modifiy settings for the Docker plugin "+pluginID+": %w", err)
}
return nil
}
func pluginUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) (gErr error) {
cl := meta.(*ProviderConfig).DockerClient
o, n := d.GetChange("enabled")
oldEnabled, newEnabled := o.(bool), n.(bool)
if d.HasChange("env") {
if oldEnabled {
// To update the plugin settings, the plugin must be disabled
if err := disablePlugin(ctx, d, cl); err != nil {
return err
}
if newEnabled {
defer func() {
if err := enablePlugin(ctx, d, cl); err != nil {
if gErr == nil {
gErr = err
return
}
}
}()
}
}
if err := pluginSet(ctx, d, cl); err != nil {
return err
}
if !oldEnabled && newEnabled {
if err := enablePlugin(ctx, d, cl); err != nil {
return err
}
}
return nil
}
// update only "enabled"
if d.HasChange("enabled") {
if newEnabled {
if err := enablePlugin(ctx, d, cl); err != nil {
return err
}
} else {
if err := disablePlugin(ctx, d, cl); err != nil {
return err
}
}
}
return nil
}
func resourceDockerPluginUpdate(d *schema.ResourceData, meta interface{}) error {
ctx := context.Background()
if err := pluginUpdate(ctx, d, meta); err != nil {
return err
}
// call the read function to update the resource's state.
// https://learn.hashicorp.com/tutorials/terraform/provider-update?in=terraform/providers#implement-update
return resourceDockerPluginRead(d, meta)
}