-
Notifications
You must be signed in to change notification settings - Fork 0
/
polling_input.go
218 lines (193 loc) · 5.78 KB
/
polling_input.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
/***** BEGIN LICENSE BLOCK *****
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# The Initial Developer of the Original Code is the Mozilla Foundation.
# Portions created by the Initial Developer are Copyright (C) 2014-2015
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Chance Zibolski (chance.zibolski@gmail.com)
# Rob Miller (rmiller@mozilla.com)
#
# ***** END LICENSE BLOCK *****/
package heka_sftp_polling_input
import (
"archive/tar"
"compress/gzip"
"fmt"
"github.com/mozilla-services/heka/message"
"github.com/mozilla-services/heka/pipeline"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"time"
)
type SftpPollingInput struct {
*SftpPollingInputConfig
stop chan bool
runner pipeline.InputRunner
hostname string
client *sftp.Client
conn *ssh.Client
}
type SftpPollingInputConfig struct {
TickerInterval uint `toml:"ticker_interval"`
Repeat bool `toml:"repeat"`
RepeatMarkDir string `toml:"repeat_mark_dir"`
Suffix string `toml:"suffix"`
MaxPacket int `toml:"max_packet"`
Host string `toml:"host"`
Port int `toml:"port"`
User string `toml:"user"`
Pass string `toml:"password"`
Compress bool `toml:"compress"`
Dir string `toml:"dir"`
}
func (input *SftpPollingInput) ConfigStruct() interface{} {
return &SftpPollingInputConfig{
TickerInterval: uint(5),
Repeat: false,
MaxPacket: 1 << 15,
Port: 22,
RepeatMarkDir: "dir_polling_input_repeat_mark",
}
}
func (input *SftpPollingInput) Init(config interface{}) (err error) {
conf := config.(*SftpPollingInputConfig)
input.SftpPollingInputConfig = conf
input.stop = make(chan bool)
addr := fmt.Sprintf("%s:%d", conf.Host, conf.Port)
var auths []ssh.AuthMethod
if conf.Pass != "" {
auths = append(auths, ssh.Password(conf.Pass))
}
sss_config := ssh.ClientConfig{
User: conf.User,
Auth: auths,
}
if input.conn, err = ssh.Dial("tcp", addr, &sss_config); err == nil {
if input.client, err = sftp.NewClient(input.conn, sftp.MaxPacket(conf.MaxPacket)); err == nil {
} else {
log.Fatalf("unable to start sftp subsytem: %v", err)
}
} else {
log.Fatalf("unable to connect to [%s]: %v", addr, err)
}
return
}
func (input *SftpPollingInput) Stop() {
input.conn.Close()
input.client.Close()
close(input.stop)
}
func (input *SftpPollingInput) packDecorator(pack *pipeline.PipelinePack) {
pack.Message.SetType("heka.sftp.polling")
}
func (input *SftpPollingInput) Run(runner pipeline.InputRunner,
helper pipeline.PluginHelper) error {
input.runner = runner
input.hostname = helper.PipelineConfig().Hostname()
tickChan := runner.Ticker()
sRunner := runner.NewSplitterRunner("")
if !sRunner.UseMsgBytes() {
sRunner.SetPackDecorator(input.packDecorator)
}
for {
select {
case <-input.stop:
return nil
case <-tickChan:
}
runner.LogMessage("start polling from sftp")
if err := input.polling(func(f io.ReadSeeker, name string) error {
return input.read(f, name, runner)
}); err != nil {
runner.LogError(err)
return nil
}
}
}
func (input *SftpPollingInput) polling(fn func(io.ReadSeeker, string) error) error {
if infos, err := input.client.ReadDir(input.Dir); err == nil {
for _, info := range infos {
if (!info.IsDir()) && (input.SftpPollingInputConfig.Suffix == "" || strings.HasSuffix(info.Name(), input.SftpPollingInputConfig.Suffix)) {
mark := filepath.Join(input.SftpPollingInputConfig.RepeatMarkDir, input.Dir, info.Name()+".ok")
if !input.SftpPollingInputConfig.Repeat {
if _, err := os.Stat(mark); !os.IsNotExist(err) {
return fmt.Errorf("repeat file %s", info.Name())
}
}
dir := filepath.Dir(mark)
if err = os.MkdirAll(dir, 0774); err != nil {
return fmt.Errorf("Error opening file: %s", err.Error())
} else {
if err := ioutil.WriteFile(mark, []byte(time.Now().String()), 0664); err != nil {
return err
}
}
f, err := input.client.Open(filepath.Join(input.Dir, info.Name()))
if err != nil {
return fmt.Errorf("Error opening remote file: %s", err.Error())
}
defer f.Close()
err = fn(f, info.Name())
}
}
}
return nil
}
func (input *SftpPollingInput) read(file io.ReadSeeker, name string, runner pipeline.InputRunner) (err error) {
sRunner := runner.NewSplitterRunner(name)
if !sRunner.UseMsgBytes() {
sRunner.SetPackDecorator(func(pack *pipeline.PipelinePack) {
pack.Message.SetType("heka.sftp.polling")
pack.Message.SetHostname(input.hostname)
if field, err := message.NewField("file_name", name, ""); err == nil {
pack.Message.AddField(field)
}
return
})
}
if input.SftpPollingInputConfig.Compress && input.SftpPollingInputConfig.Suffix == ".gz" {
var fileReader *gzip.Reader
if fileReader, err = gzip.NewReader(file); err == nil {
defer fileReader.Close()
tarBallReader := tar.NewReader(fileReader)
for {
if header, err := tarBallReader.Next(); err == nil {
// get the individual filename and extract to the current directory
switch header.Typeflag {
case tar.TypeReg:
split(runner, sRunner, tarBallReader)
}
} else {
break
}
}
}
} else {
split(runner, sRunner, file)
}
return
}
func split(runner pipeline.InputRunner, sRunner pipeline.SplitterRunner, reader io.Reader) {
var err error
for err == nil {
err = sRunner.SplitStream(reader, nil)
if err != io.EOF && err != nil {
runner.LogError(fmt.Errorf("Error reading file: %s", err.Error()))
}
}
}
func init() {
pipeline.RegisterPlugin("SftpPollingInput", func() interface{} {
return new(SftpPollingInput)
})
}