/
client.go
266 lines (228 loc) · 7.21 KB
/
client.go
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package main
import (
"errors"
"fmt"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"strings"
"time"
)
type DockerDeployClient struct {
Mode string
SSHPort int
SSHUser string
SSHHost string
SSHPassword string
ProjectName string
ComposeFile string
StartTime int
RemoteWorkingDir string
LocalWorkingDir string
LocalArtifact string
ServiceDiscoveryPort int
ClearVolumes bool
config *ssh.ClientConfig
sshClient *ssh.Client
}
func (c *DockerDeployClient) connect() error {
c.config = &ssh.ClientConfig{
User: c.SSHUser,
Auth: []ssh.AuthMethod{
ssh.Password(c.SSHPassword),
},
}
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", c.SSHHost, c.SSHPort), c.config)
if err != nil {
return err
}
c.sshClient = client
return nil
}
func (c *DockerDeployClient) disconnect() error {
return c.sshClient.Close()
}
func (c *DockerDeployClient) executeCommand(command string, sudo bool) (string, error) {
session, err := c.sshClient.NewSession()
if err != nil {
return "", err
}
defer session.Close()
if sudo {
session.Stdin = strings.NewReader(fmt.Sprintf("%v\n", c.SSHPassword))
}
output, err := session.CombinedOutput(command)
log.Printf("Command: %v", command)
log.Printf("Output: %v", string(output))
if err != nil {
return "", errors.New(fmt.Sprintf("%v: %v", err.Error(), string(output)))
}
return string(output), nil
}
func (c *DockerDeployClient) findLocalArtifact() error {
if c.LocalArtifact != "" {
if _, err := os.Stat(c.LocalArtifact); err != nil {
return errors.New(fmt.Sprintf("Could not find artifact at %v.", c.LocalArtifact))
}
if path.Ext(c.LocalArtifact) != ".zip" {
return errors.New(fmt.Sprintf("Given artifact %v is no zip file.", c.LocalArtifact))
}
log.Printf("Local artifact found: %v", c.LocalArtifact)
return nil
}
if c.LocalWorkingDir == "" {
return errors.New("No local working directory specified.")
}
if _, err := os.Stat(c.LocalWorkingDir); err != nil {
return errors.New(fmt.Sprintf("Local working directory \"%v\" does not exist!", c.LocalWorkingDir))
}
d, err := os.Open(c.LocalWorkingDir)
if err != nil {
return errors.New(fmt.Sprintf("Could not open local working directory: %v", err.Error()))
}
defer d.Close()
files, err := d.Readdir(-1)
if err != nil {
return err
}
for _, file := range files {
if file.Mode().IsRegular() {
fpath := path.Join(c.LocalWorkingDir, file.Name())
if path.Ext(fpath) == ".zip" {
c.LocalArtifact = fpath
log.Printf("Local artifact found: %v", c.LocalArtifact)
return nil
}
}
}
return errors.New(fmt.Sprintf("Could not find local artifact in working directory %v", c.LocalWorkingDir))
}
func (c *DockerDeployClient) unzipArtifact() error {
output, err := c.executeCommand("which unzip", false)
if err != nil {
return errors.New(fmt.Sprintf("Unzip not installed. %v", output))
}
output, err = c.executeCommand(fmt.Sprintf("cd %v && unzip -o %v && rm %v", c.RemoteWorkingDir, path.Base(c.LocalArtifact), path.Base(c.LocalArtifact)), false)
if err != nil {
return errors.New(fmt.Sprintf("Could not unzip artifact: %v %v", err.Error(), output))
}
return nil
}
func (c *DockerDeployClient) copyArtifact() error {
err := c.copyFile(c.LocalArtifact, path.Join(c.RemoteWorkingDir, path.Base(c.LocalArtifact)))
return err
}
func (c *DockerDeployClient) copyFile(source string, target string) error {
sftp, err := sftp.NewClient(c.sshClient)
if err != nil {
log.Fatalf("Could not initialize SFTP connection: %v", err)
}
defer sftp.Close()
tf, err := sftp.Create(target)
if err != nil {
return err
}
defer tf.Close()
sf, err := os.Open(source)
if err != nil {
return err
}
defer sf.Close()
n, err := io.Copy(tf, sf)
if err != nil {
return err
}
log.Printf("Artifact from %v to %v copied. %v Bytes transferred.", source, target, n)
return nil
}
func (c *DockerDeployClient) prepareRemoteWorkdir() error {
if c.RemoteWorkingDir == "" {
return errors.New("No remote working directory specified.")
}
subfolder := strings.TrimSuffix(path.Base(c.LocalArtifact), path.Ext(c.LocalArtifact))
c.RemoteWorkingDir = path.Join(c.RemoteWorkingDir, subfolder)
command := fmt.Sprintf("mkdir -p %s && cd %s && pwd && rm -rf *", c.RemoteWorkingDir, c.RemoteWorkingDir)
_, err := c.executeCommand(command, false)
if err != nil {
return err
}
return nil
}
func (c *DockerDeployClient) checkDockerInstallation() error {
output, err := c.executeCommand("which docker", false)
if err != nil {
return errors.New(fmt.Sprintf("Docker not installed. %v", output))
}
output, err = c.executeCommand("which docker-compose", false)
if err != nil {
return errors.New(fmt.Sprintf("Docker Compose not installed. %v", output))
}
if c.ComposeFile == "" {
return errors.New("No compose file specified.")
}
if c.ProjectName == "" {
return errors.New("No project name specified.")
}
return nil
}
func (c *DockerDeployClient) stopComposition() error {
_, err := c.executeCommand(fmt.Sprintf("cd %v && sudo -S docker-compose -p %v -f %v stop", c.RemoteWorkingDir, c.ProjectName, c.ComposeFile), true)
return err
}
func (c *DockerDeployClient) removeComposition() error {
var err error = nil
if c.ClearVolumes {
_, err = c.executeCommand(fmt.Sprintf("cd %v && sudo -S docker-compose -p %v -f %v rm -v --force", c.RemoteWorkingDir, c.ProjectName, c.ComposeFile), true)
} else {
_, err = c.executeCommand(fmt.Sprintf("cd %v && sudo -S docker-compose -p %v -f %v rm --force", c.RemoteWorkingDir, c.ProjectName, c.ComposeFile), true)
}
return err
}
func (c *DockerDeployClient) buildComposition() error {
_, err := c.executeCommand(fmt.Sprintf("cd %v && sudo -S docker-compose -p %v -f %v build", c.RemoteWorkingDir, c.ProjectName, c.ComposeFile), true)
return err
}
func (c *DockerDeployClient) runComposition() error {
_, err := c.executeCommand(fmt.Sprintf("cd %v && sudo -S docker-compose -p %v -f %v up -d", c.RemoteWorkingDir, c.ProjectName, c.ComposeFile), true)
return err
}
func (c *DockerDeployClient) serviceDiscoveryTest() error {
iterations := 0
var response []byte
ticks := time.Duration(c.StartTime/5) * time.Second
for _ = range time.Tick(ticks) {
iterations += 1
if iterations >= 6 {
break
}
res, err := http.Get(fmt.Sprintf("http://%v:%d/api/projectUp/%v", c.SSHHost, c.ServiceDiscoveryPort, c.ProjectName))
if err != nil {
log.Printf("#%d: Service Discovery is not reachable: %v", iterations, err.Error())
continue
}
response, err = ioutil.ReadAll(res.Body)
res.Body.Close()
if err == nil && string(response) == "true" {
log.Printf("#%d: Composition was started: %d %v", iterations, res.StatusCode, string(response))
return nil
}
log.Printf("#%d: Composition could not be started: %d %v", iterations, res.StatusCode, string(response))
}
return errors.New("Service Discovery test failed.")
}
func (c *DockerDeployClient) remoteCleanUp() error {
if c.RemoteWorkingDir == "" {
return errors.New("No remote working directory specified.")
}
command := fmt.Sprintf("rm -rf %s", c.RemoteWorkingDir)
_, err := c.executeCommand(command, false)
if err != nil {
return err
}
return nil
}