forked from ji-it/CloudTides
-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.go
258 lines (218 loc) · 6.03 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/Shopify/sarama"
"golang.org/x/crypto/ssh"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"strings"
"sync"
"time"
)
func failOnError(err error, msg string) {
if err != nil {
log.Panicf("%s: %s", msg, err)
}
}
var sshPool sync.Map
type Operate struct {
Op string
Token string
Data string
CMD string
SshType string
Host string `yaml:"host"`
User string `yaml:"user"`
Pass string `yaml:"pass"`
Port string `yaml:"port"`
}
type Host struct {
Host string `yaml:"host"`
User string `yaml:"user"`
Pass string `yaml:"pass"`
Port string `yaml:"port"`
}
var url string
var mqHost string
var mqTopic string
var consumer sarama.Consumer
// Callback func
type ConsumerCallback func(data []byte)
// Init Consumer
func InitConsumer(hosts string) {
config := sarama.NewConfig()
client, err := sarama.NewClient(strings.Split(hosts, ","), config)
failOnError(err, "unable to create kafka client")
consumer, err = sarama.NewConsumerFromClient(client)
failOnError(err, "NewAsyncProducerFromClient Err")
log.Print("lalala for try")
}
func LoopConsumer(topic string, callback ConsumerCallback) {
partitionConsumer, err := consumer.ConsumePartition(topic, 0, sarama.OffsetNewest)
failOnError(err, "unable to create partitionConsumer")
defer partitionConsumer.Close()
for {
msg := <-partitionConsumer.Messages()
if callback != nil {
callback(msg.Value)
}
}
}
func Close() {
if consumer != nil {
consumer.Close()
}
}
func TopicCallBack(msg []byte) {
log.Printf("Received a message: %s", msg)
op := &Operate{}
err := json.Unmarshal(msg, op)
failOnError(err, "Failed convert JSON string to struct")
rand.Seed(time.Now().Unix())
for i := 0; i < 10; i++ {
log.Println(rand.Intn(len(hosts)))
}
host := hosts[rand.Intn(len(hosts))]
var combo []byte
if op.Op == "delete" {
combo, err = execCmd(op.Host, op.User, op.Pass, op.SshType, op.Port, op.CMD)
} else {
combo, err = execCmd(host.Host, host.User, host.Pass, op.SshType, host.Port, op.CMD)
}
failOnError(err, "Failed to connect host by ssh")
log.Printf("Received a combo: %s", combo)
//SSHHost string
//SSHUser string
//SSHPassword string
//SSHPort string
var values map[string]string
if op.Op == "delete" {
values = map[string]string{"combo": string(combo),
"token": op.Token,
"ssh_host": op.Host,
"ssh_user": op.User,
"ssh_password": op.Pass,
"ssh_port": op.Port,
}
} else {
values = map[string]string{"combo": string(combo),
"token": op.Token,
"ssh_host": host.Host,
"ssh_user": host.User,
"ssh_password": host.Pass,
"ssh_port": host.Port,
}
}
if err != nil {
values["error"] = err.Error()
} else {
values["error"] = ""
}
log.Printf("Received a values: %v", values)
jsonData, err := json.Marshal(values)
failOnError(err, "Failed to convent json")
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
failOnError(err, "Failed to connect host")
log.Printf("Received a resp: %s", resp.Status)
}
var hosts []*Host
func init() {
mqHost = os.Getenv("MQ_HOST")
mqTopic = os.Getenv("AGENT_NAME")
url = os.Getenv("SERVER_URL")
InitConsumer(mqHost)
yamlFile, err := ioutil.ReadFile("hosts.yaml")
if err != nil{
log.Print("read file hosts.yaml wrong")
}
log.Print(string(yamlFile))
log.Print(string(yamlFile))
err = yaml.Unmarshal(yamlFile, &hosts)
failOnError(err, "Failed to Unmarshal")
log.Print(hosts[0])
log.Print(hosts[0])
}
func main() {
log.Print("MQ host tryyy", mqHost)
forever := make(chan bool)
LoopConsumer(mqTopic, TopicCallBack)
log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
Close()
}
func execCmd(sshHost, SshUser, SshPassword, sshType, sshPort, cmd string) ([]byte, error) {
sshConfig := &ssh.ClientConfig{
Timeout: time.Second,
User: SshUser,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
if sshType == "password" {
sshConfig.Auth = []ssh.AuthMethod{ssh.Password(SshPassword)}
} else {
sshConfig.Auth = []ssh.AuthMethod{publicKeyAuthFunc(SshPassword)}
}
session := getSession(sshHost, sshPort, sshConfig)
log.Println("cmd ", cmd)
return session.CombinedOutput(cmd)
}
func publicKeyAuthFunc(kPath string) ssh.AuthMethod {
key, err := ioutil.ReadFile(kPath)
if err != nil {
log.Println("ssh key file read failed", err)
}
// Create the Signer for this private key.
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
log.Println("ssh key signer failed", err)
}
return ssh.PublicKeys(signer)
}
func getSession(sshHost string, sshPort string, config *ssh.ClientConfig) (session *ssh.Session) {
addr := fmt.Sprintf("%s:%s", sshHost, sshPort)
log.Println("ssh addr ", addr)
sshClientStock, has := sshPool.Load(addr)
var sshClient *ssh.Client
if !has {
sshClient, err := ssh.Dial("tcp", addr, config)
if err != nil {
log.Println("created ssh client failed", err)
if err := sshClient.Close(); err != nil {
log.Println("close ssh client failed", err)
}
} else {
log.Println("existing sshClient")
sshPool.Store(addr, sshClient)
}
} else {
log.Println("map existing sshClient")
sshClient = sshClientStock.(*ssh.Client)
}
defer func(addr string) {
err := recover()
if err != nil {
log.Println("recover ", err)
sshClient, err := ssh.Dial("tcp", addr, config)
log.Println("defer", err)
log.Println("defer existing sshClient")
sshPool.Delete(addr)
sshPool.Store(addr, sshClient)
session, err = sshClient.NewSession()
log.Println("defer", err)
}
}(addr)
//create ssh-session
session, err := sshClient.NewSession()
if err != nil {
log.Println("created session failed", err)
if err := session.Close(); err != nil {
log.Println("close session failed", err)
}
}
return session
}