/
sftptasks.go
300 lines (255 loc) · 8.17 KB
/
sftptasks.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package directdebit
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
mysql "github.com/go-sql-driver/mysql"
"github.com/masenocturnal/pipefire/internal/sftp"
)
//SftpConfig Required Params for transferring to or from an SFTP Server
type SftpConfig struct {
RemoteDir string `json:"remoteDir"`
LocalDir string `json:"localDir"`
Sftp sftp.Endpoint `json:"sftp"`
Enabled bool `json:"enabled"`
}
// get files from a particular endpoint
func (p *ddPipeline) sftpGet(conf *SftpConfig) error {
p.log.Infof("Begin sftpGet: %s ", conf.Sftp.Host)
sftp, err := sftp.NewConnection("From", conf.Sftp, p.log)
if err != nil {
return err
}
defer sftp.Close()
// grab all the files from the pickup directory
confirmations, errors := sftp.GetDir(conf.RemoteDir, conf.LocalDir)
if errors.Len() > 0 {
// show all errors
for temp := errors.Front(); temp != nil; temp = temp.Next() {
p.log.Error(temp.Value)
}
return fmt.Errorf("Error getting files from %s ", conf.RemoteDir)
}
for temp := confirmations.Front(); temp != nil; temp = temp.Next() {
result, _ := json.MarshalIndent(temp.Value, "", " ")
p.log.Info(string(result))
}
p.log.Info("sftpGet Complete")
return err
}
// sftpClean cleans the repote directory
func (p *ddPipeline) sftpClean(conf *SftpConfig) (err error) {
p.log.Infof("Begin sftpClean: %s", conf.Sftp.Host)
p.log.Debugf("Cleaning remote dir: %s ", conf.RemoteDir)
sftp, err := sftp.NewConnection(conf.Sftp.Host, conf.Sftp, p.log)
if err != nil {
return
}
defer sftp.Close()
err = sftp.CleanDir(conf.RemoteDir)
if err == nil {
p.log.Infof("sftpClean Complete: Removed files from: %s ", conf.RemoteDir)
}
return err
}
func (p *ddPipeline) sftpToSafe(conf *SftpConfig) (err error) {
p.log.Infof("Begin sftpToSafe: %s", conf.Sftp.Host)
p.log.Debugf("Sftp transfer from %s to %s @ %s ", conf.LocalDir, conf.RemoteDir, conf.Sftp.Host)
// ANZ SFTP is odd and requires us to establish new connections for
// each load
filesInDir, err := ioutil.ReadDir(conf.LocalDir)
if err != nil {
return
}
var sb strings.Builder
for _, file := range filesInDir {
sftp, e := sftp.NewConnection(conf.Sftp.Host, conf.Sftp, p.log)
if e != nil {
p.log.Errorf("Unable to connect to %s Error: %s ", conf.Sftp.Host, e.Error())
return e
}
lfp := filepath.Join(conf.LocalDir, file.Name())
rfp := filepath.Join(conf.RemoteDir, file.Name())
confirmation, err := sftp.SendFile(lfp, rfp)
if err != nil {
p.log.Errorf("Unable to Send File to %s Error: %s ", conf.Sftp.Host, err.Error())
}
result, _ := json.MarshalIndent(confirmation, "", " ")
sb.WriteString(string(result))
p.log.Info(sb.String())
sftp.Close()
}
p.log.Infof("sftpTo Complete, remote %s ", conf.RemoteDir)
return nil
}
// send files to a particular endpoint
func (p *ddPipeline) sftpTo(conf *SftpConfig) (err error) {
p.log.Infof("Begin sftpTo: %s", conf.Sftp.Host)
p.log.Debugf("Sftp transfer from %s to %s @ %s ", conf.LocalDir, conf.RemoteDir, conf.Sftp.Host)
// Record the files we are about to send so that we can ensure we never
// send the same file twice
// This is done as an atomic commit to avoid race conditions
if err := p.recordFilesToSend(conf.LocalDir, conf.Sftp.Host); err != nil {
return err
}
// establish the connection and bail if we can't get it
sftp, err := sftp.NewConnection(conf.Sftp.Host, conf.Sftp, p.log)
if err != nil {
return
}
defer sftp.Close()
dirList, _ := ioutil.ReadDir(conf.LocalDir)
if p.transferlog == nil || p.transferlog.Conn == nil {
return fmt.Errorf("Transfer log is unavailable, aborting")
}
// we want to examine each of these files to ensure they haven't been sent before
for _, file := range dirList {
cur := filepath.Join(conf.LocalDir, file.Name())
// create a synchronous transaction so that only 1 process can update the database at a time
tx := p.transferlog.Conn.BeginTx(context.Background(), &sql.TxOptions{Isolation: sql.LevelSerializable})
fileHash, err := hashFile(cur)
if err != nil {
return err
}
val, err := p.transferlog.FileAlreadySent(tx, fileHash, conf.Sftp.Host)
if err != nil {
tx.Rollback()
p.log.Errorf("Unable to confirm if file has been sent. Aborting . Err %s", err.Error())
// def don't want to send if we don't know if it's been sent.
return err
}
if val == true {
// don't transfer the file
p.log.Warnf("The file %s has already been sent. File will *NOT* be transferred ", cur)
tx.Rollback()
} else {
startTime := time.Now()
// attempt to transfer
confirmation, err := sftp.SendFile(cur, conf.RemoteDir)
if err != nil {
rec := &TransferRecord{
RemoteHost: conf.Sftp.Host,
// @todo see if this is populated TransferredFileHash: confirmation.TransferredHash,
TransferStart: startTime,
TransferEnd: time.Now(),
LocalFileHash: fileHash,
CorrelationID: p.correlationID,
TransferErrors: err.Error(),
}
p.transferlog.RecordError(tx, rec)
}
// log the confirmation
result, _ := json.MarshalIndent(confirmation, "", " ")
p.log.Info(string(result))
if confirmation != nil {
rec := &TransferRecord{
RemoteFileName: confirmation.RemoteFileName,
RemoteFilePath: confirmation.RemotePath,
RemoteFileSize: confirmation.RemoteSize,
RemoteHost: conf.Sftp.Host,
RecipientName: "",
SenderName: "",
TransferredFileHash: confirmation.TransferredHash,
TransferStart: startTime,
TransferEnd: time.Now(),
LocalFileHash: confirmation.LocalHash,
CorrelationID: p.correlationID,
}
if err := p.transferlog.Update(tx, rec); err != nil {
tx.RollbackUnlessCommitted()
}
tx.Commit()
} else {
p.log.Warnf("Didn't receive file transfer confirmation for %s", cur)
}
}
}
// try and list the directory
sftp.ListRemoteDir(conf.RemoteDir)
p.log.Infof("sftpTo Complete, remote %s ", conf.RemoteDir)
return nil
}
func (p *ddPipeline) recordFilesToSend(localDir string, remoteHost string) error {
// @todo validate config
// Record the files in the database so we can
// guard against sending them twice
// start the transaction
tx := p.transferlog.Conn.Begin()
// defer func() {
// if r := recover(); r != nil {
// tx.Rollback()
// }
// }()
// list all the files ine
filesInDir, err := ioutil.ReadDir(localDir)
if err != nil {
return err
}
if len(filesInDir) < 1 {
p.log.Warnf("No files to send in %s", localDir)
// it's not an error ...this can happen in multiple runs but there is
// no sense doing anything more
return nil
}
hostName, _ := os.Hostname()
for _, file := range filesInDir {
cur := filepath.Join(localDir, file.Name())
hash, err := hashFile(cur)
if err != nil {
return err
}
// add the record to the transferlog
record := &TransferRecord{
LocalFileSize: file.Size(),
LocalFileName: file.Name(),
LocalFilePath: cur,
RemoteHost: remoteHost,
LocalHostID: hostName,
CorrelationID: p.correlationID,
LocalFileHash: hash,
}
err = p.transferlog.Create(tx, record)
if err != nil {
dbErr := err.(*mysql.MySQLError)
if dbErr != nil {
switch dbErr.Number {
case 1062:
//. this is ok...if a previous attempt fails, we want to try again
p.log.Warnf("A process has previously attempted to transfer this file: %s", cur)
break
default:
tx.Rollback()
// something is wrong, we should stop
p.log.Error(dbErr.Error())
return fmt.Errorf("Unexpected error trying to record files to send")
}
} else {
tx.Rollback()
p.log.Errorf("Error when trying to reserve file sending entries. Error: %s", err.Error())
return err
}
}
}
tx.Commit()
return nil
}
// @ turn into a lib
func hashFile(filePath string) (string, error) {
data, err := ioutil.ReadFile(filePath)
if err != nil {
return "", fmt.Errorf("Can't hash %s bailing out. Error : %s", filePath, err.Error())
}
// @todo inject hashwriter to support other hash algorithms
hashWriter := sha256.New()
// calculate local checksum
_, err = hashWriter.Write(data)
return hex.EncodeToString(hashWriter.Sum(nil)), err
}