1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
|
package deployer
import (
"encoding/base64"
"encoding/json"
"fmt"
"sync"
"github.com/google/uuid"
"github.com/moby/moby/api/types/registry"
"github.com/moby/moby/client"
)
type DockerDeployer struct {
client *client.Client
deployJobs map[string]*DeployJob
deployJobsMutex sync.RWMutex
containerCreateMutex sync.Mutex
instancerDomain string
registryURL string
registryUsername string
registryPassword string
proxyContainerName string
imagePrefix string
}
type DeployJob struct {
DeployChan chan DeployStatus
deployKey string
challenge string
team string
}
func New(registryURL, registryUsername, registryPassword, instancerDomain, imagePrefix, proxyContainerName string) (DockerDeployer, error) {
c, err := client.New(client.FromEnv)
if err != nil {
return DockerDeployer{}, fmt.Errorf("docker client error: %w", err)
}
return DockerDeployer{
client: c,
deployJobs: make(map[string]*DeployJob),
registryURL: registryURL,
registryUsername: registryUsername,
registryPassword: registryPassword,
instancerDomain: instancerDomain,
imagePrefix: imagePrefix,
proxyContainerName: proxyContainerName,
}, nil
}
func (d *DockerDeployer) GetJob(deployKey string) *DeployJob {
d.deployJobsMutex.RLock()
defer d.deployJobsMutex.RUnlock()
return d.deployJobs[deployKey]
}
func (d *DockerDeployer) registryLogin() string {
options := registry.AuthConfig{
ServerAddress: d.registryURL,
Username: d.registryUsername,
Password: d.registryPassword,
}
encodedJSON, err := json.Marshal(options)
if err != nil {
panic(err)
}
return base64.StdEncoding.EncodeToString(encodedJSON)
}
func (d *DockerDeployer) createDeployJob(challenge, team string) (string, *DeployJob) {
d.deployJobsMutex.Lock()
defer d.deployJobsMutex.Unlock()
deploymentKey := uuid.New().String()
deploymentChan := make(chan DeployStatus)
job := &DeployJob{
DeployChan: deploymentChan,
deployKey: deploymentKey,
challenge: challenge,
team: team,
}
d.deployJobs[deploymentKey] = job
return deploymentKey, job
}
func (d *DockerDeployer) writeDeployChannel(deploymentKey string, status DeployStatus) {
d.deployJobsMutex.RLock()
defer d.deployJobsMutex.RUnlock()
job := d.deployJobs[deploymentKey]
if job == nil || job.DeployChan == nil {
return
}
job.DeployChan <- status
if status.Status == statusSuccess || status.Status == statusError {
job.DeployChan <- DeployStatus{Status: "done", Message: "done"}
close(job.DeployChan)
//TODO cleanup
}
}
|