forked from adejoux/nmon2influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnmon_files.go
286 lines (249 loc) · 6.62 KB
/
nmon_files.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
// nmon2influxdb
// import nmon data in InfluxDB
// author: adejoux@djouxtech.net
package main
import (
"bufio"
"compress/gzip"
"crypto/sha1"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"path"
"regexp"
"sort"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
var remoteFileRegexp = regexp.MustCompile(`(\S+):(\S+)`)
var remoteUserRegexp = regexp.MustCompile(`(\S+)@(\S+)`)
const gzipfile = ".gz"
const size = 64000
// NmonFile structure used to select nmon files to import
type NmonFile struct {
Name string
FileType string
Host string
SSHUser string
SSHKey string
checksum string
lines []string
}
// NmonFiles array of NmonFile
type NmonFiles []NmonFile
//Add a file in the NmonFIles structure
func (nmonFiles *NmonFiles) Add(file string, fileType string) {
*nmonFiles = append(*nmonFiles, NmonFile{Name: file, FileType: fileType})
}
//AddRemote a remote file in the NmonFIles structure
func (nmonFiles *NmonFiles) AddRemote(file string, fileType string, host string, user string, key string) {
*nmonFiles = append(*nmonFiles, NmonFile{Name: file, FileType: fileType, Host: host, SSHUser: user, SSHKey: key})
}
//Valid returns only valid fiels for nmon import
func (nmonFiles *NmonFiles) Valid() (validFiles NmonFiles) {
for _, v := range *nmonFiles {
if v.FileType == ".nmon" || v.FileType == gzipfile {
validFiles = append(validFiles, v)
}
}
return validFiles
}
// FileScanner struct to manage
type FileScanner struct {
*os.File
*bufio.Scanner
}
// RemoteFileScanner struct for remote files
type RemoteFileScanner struct {
*sftp.File
*bufio.Scanner
}
// GetRemoteScanner open an nmon file based on file extension and provides a bufio Scanner
func (nmonFile *NmonFile) GetRemoteScanner() (*RemoteFileScanner, error) {
sftpConn := InitSFTP(nmonFile.SSHUser, nmonFile.Host, nmonFile.SSHKey)
file, err := sftpConn.Open(nmonFile.Name)
if err != nil {
return nil, err
}
if nmonFile.FileType == gzipfile {
gr, err := gzip.NewReader(file)
if err != nil {
return nil, err
}
reader := bufio.NewReader(gr)
return &RemoteFileScanner{file, bufio.NewScanner(reader)}, nil
}
reader := bufio.NewReader(file)
return &RemoteFileScanner{file, bufio.NewScanner(reader)}, nil
}
//Checksum generates SHA1 file checksum
func (nmonFile *NmonFile) Checksum() (fileHash string) {
if len(nmonFile.checksum) > 0 {
return nmonFile.checksum
}
var result []byte
if len(nmonFile.Host) > 0 {
scanner, err := nmonFile.GetRemoteScanner()
check(err)
scanner.Seek(-1024, 2)
hash := sha1.New()
if _, err = io.Copy(hash, scanner); err != nil {
return
}
fileHash = hex.EncodeToString(hash.Sum(result))
} else {
scanner, err := nmonFile.GetScanner()
check(err)
scanner.Seek(-1024, 2)
hash := sha1.New()
if _, err = io.Copy(hash, scanner); err != nil {
return
}
fileHash = hex.EncodeToString(hash.Sum(result))
}
nmonFile.checksum = fileHash
return
}
// GetScanner open an nmon file based on file extension and provides a bufio Scanner
func (nmonFile *NmonFile) GetScanner() (*FileScanner, error) {
file, err := os.Open(nmonFile.Name)
if err != nil {
return nil, err
}
if nmonFile.FileType == gzipfile {
gr, err := gzip.NewReader(file)
if err != nil {
return nil, err
}
reader := bufio.NewReader(gr)
return &FileScanner{file, bufio.NewScanner(reader)}, nil
}
reader := bufio.NewReader(file)
return &FileScanner{file, bufio.NewScanner(reader)}, nil
}
// Parse parameters
func (nmonFiles *NmonFiles) Parse(args []string, sshUser string, key string) {
for _, param := range args {
if remoteFileRegexp.MatchString(param) {
matched := remoteFileRegexp.FindStringSubmatch(param)
host := matched[1]
if remoteUserRegexp.MatchString(host) {
hostMatched := remoteUserRegexp.FindStringSubmatch(host)
sshUser = hostMatched[1]
host = hostMatched[2]
}
matchedParam := matched[2]
sftpConn := InitSFTP(sshUser, host, key)
paraminfo, err := sftpConn.Stat(matchedParam)
check(err)
if err != nil {
if os.IsNotExist(err) {
fmt.Printf("%s doesn't exist ! skipped.\n", param)
}
continue
}
if paraminfo.IsDir() {
entries, err := sftpConn.ReadDir(matchedParam)
check(err)
for _, entry := range entries {
if !entry.IsDir() {
file := path.Join(matchedParam, entry.Name())
nmonFiles.AddRemote(file, path.Ext(file), host, sshUser, key)
}
}
sftpConn.Close()
continue
}
nmonFiles.AddRemote(matchedParam, path.Ext(matchedParam), host, sshUser, key)
sftpConn.Close()
continue
}
paraminfo, err := os.Stat(param)
if err != nil {
if os.IsNotExist(err) {
fmt.Printf("%s doesn't exist ! skipped.\n", param)
}
continue
}
if paraminfo.IsDir() {
entries, err := ioutil.ReadDir(param)
check(err)
for _, entry := range entries {
if !entry.IsDir() {
file := path.Join(param, entry.Name())
nmonFiles.Add(file, path.Ext(file))
}
}
continue
}
nmonFiles.Add(param, path.Ext(param))
}
}
//SSHConfig contains SSH parameters
type SSHConfig struct {
User string
Key string
}
//InitSFTP init sftp session
func InitSFTP(sshUser string, host string, key string) *sftp.Client {
var auths []ssh.AuthMethod
if !IsNotFile(key) {
pemBytes, err := ioutil.ReadFile(key)
if err != nil {
log.Fatal(err)
}
signer, err := ssh.ParsePrivateKey(pemBytes)
if err != nil {
log.Fatalf("parse key failed:%v", err)
}
auths = append(auths, ssh.PublicKeys(signer))
}
// ssh agent support
if aconn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(aconn).Signers))
}
config := &ssh.ClientConfig{
User: sshUser,
Auth: auths,
}
sshhost := fmt.Sprintf("%s:22", host)
conn, err := ssh.Dial("tcp", sshhost, config)
if err != nil {
log.Fatalf("dial failed:%v", err)
}
c, err := sftp.NewClient(conn, sftp.MaxPacket(size))
if err != nil {
log.Fatalf("unable to start sftp subsytem: %v", err)
}
return c
}
//Content returns the nmon files content sorted in an slice of string format
func (nmonFile *NmonFile) Content() []string {
if len(nmonFile.lines) > 0 {
return nmonFile.lines
}
if len(nmonFile.Host) > 0 {
scanner, err := nmonFile.GetRemoteScanner()
check(err)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
nmonFile.lines = append(nmonFile.lines, scanner.Text())
}
scanner.Close()
} else {
scanner, err := nmonFile.GetScanner()
check(err)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
nmonFile.lines = append(nmonFile.lines, scanner.Text())
}
scanner.Close()
}
sort.Strings(nmonFile.lines)
return nmonFile.lines
}