image.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package docker
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. fw "git.buran.team/main/fairwind"
  8. mobyregistry "github.com/moby/moby/api/types/registry"
  9. moby "github.com/moby/moby/client"
  10. )
  11. type Image struct {
  12. ctx context.Context
  13. log *fw.Log
  14. client *Docker
  15. registry *Registry
  16. tag string
  17. version string
  18. pull bool
  19. }
  20. func NewImage(ctx context.Context, log *fw.Log, client *Docker, registry *Registry, tag string, version string, pull bool) *Image {
  21. return &Image{
  22. ctx: ctx,
  23. log: log,
  24. client: client,
  25. registry: registry,
  26. tag: tag,
  27. version: version,
  28. pull: pull,
  29. }
  30. }
  31. func (this *Image) Registry() *Registry {
  32. return this.registry
  33. }
  34. func (this *Image) Name() string {
  35. return fmt.Sprintf("%s/%s:%s", this.registry.address, this.tag, this.version)
  36. }
  37. func (this *Image) Tag() string {
  38. return this.tag
  39. }
  40. func (this *Image) Version() string {
  41. return this.version
  42. }
  43. func (this *Image) Pull() error {
  44. if !this.pull {
  45. return nil
  46. }
  47. credentials, err := credentialsToString(
  48. this.registry.login,
  49. this.registry.password,
  50. )
  51. if err != nil {
  52. return fmt.Errorf("can't pull image: %w", err)
  53. }
  54. response, err := this.client.Docker.ImagePull(
  55. this.ctx,
  56. this.Name(),
  57. moby.ImagePullOptions{
  58. RegistryAuth: credentials,
  59. },
  60. )
  61. if err != nil {
  62. return fmt.Errorf("can't pull image: %w", err)
  63. }
  64. err = response.Wait(this.ctx)
  65. if err != nil {
  66. return fmt.Errorf("can't pull image: %w", err)
  67. }
  68. return nil
  69. }
  70. func credentialsToString(login string, password string) (string, error) {
  71. encodedJSON, err := json.Marshal(
  72. &mobyregistry.AuthConfig{
  73. Username: login,
  74. Password: password,
  75. },
  76. )
  77. if err != nil {
  78. return "", fmt.Errorf("can't serialize credentials: %w", err)
  79. }
  80. authStr := base64.URLEncoding.EncodeToString(encodedJSON)
  81. return authStr, nil
  82. }