-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamicProxyEip.go
383 lines (315 loc) · 8.81 KB
/
dynamicProxyEip.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package main
import (
"DynamicProxyEip/utils"
"bytes"
"encoding/json"
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vpc"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"strings"
"time"
)
var (
GODADDY_API_HOST string
GODADDY_DOMAIN string
GODADDY_DNS_NAME string
)
// check TCP Port
func checkTCPPort(address string) bool {
var conn net.Conn
var err error
for i:=0; i<3; i++ {
conn, err = net.DialTimeout("tcp", address, 3*time.Second)
if err != nil{
fmt.Println("could not connect to server: ", err)
}
time.Sleep(5*time.Second)
}
if err != nil{
return false
}
defer conn.Close()
return true
}
//根据实例id获取Eip
func getEip(err error, client *vpc.Client, instanceId string) (string,string) {
request := vpc.CreateDescribeEipAddressesRequest()
request.Status = "InUse"
request.AssociatedInstanceId = instanceId
request.AssociatedInstanceType = "EcsInstance"
response, err := client.DescribeEipAddresses(request)
if err != nil {
fmt.Print(err.Error())
}
if len(response.EipAddresses.EipAddress) > 0 {
eip := response.EipAddresses.EipAddress[0].IpAddress
allocationId := response.EipAddresses.EipAddress[0].AllocationId
return eip,allocationId
}
return "",""
}
//获取可用Eip
func getAvailableEip(err error, client *vpc.Client) (string,string) {
request := vpc.CreateDescribeEipAddressesRequest()
request.Status = "Available"
response, err := client.DescribeEipAddresses(request)
if err != nil {
fmt.Print(err.Error())
}
if len(response.EipAddresses.EipAddress) > 0 {
eip := response.EipAddresses.EipAddress[0].IpAddress
allocationId := response.EipAddresses.EipAddress[0].AllocationId
fmt.Printf("获取可用Eip: %s\n", eip)
return eip,allocationId
}
return "",""
}
//解绑eip
func unassociateEip(allocationId string, instanceId string, client *vpc.Client) error {
request := vpc.CreateUnassociateEipAddressRequest()
request.AllocationId = allocationId
request.InstanceId = instanceId
i := 0
for {
response, err := client.UnassociateEipAddress(request)
if err != nil {
if i < 10 {
i++
time.Sleep(1*time.Second)
continue
}
fmt.Printf("解绑eip失败: %s", response)
return err
}
fmt.Printf("解绑eip成功,allocationId: %s\n", allocationId)
return nil
}
}
//绑定eip
func associateEip(allocationId string, instanceId string, client *vpc.Client) error {
request := vpc.CreateAssociateEipAddressRequest()
request.AllocationId = allocationId
request.InstanceId = instanceId
i := 0
for {
response, err := client.AssociateEipAddress(request)
if err != nil {
if i < 10 {
i++
time.Sleep(1*time.Second)
continue
}
fmt.Printf("绑定eip失败: %s", response)
return err
}
fmt.Printf("绑定eip成功,allocationId: %s\n", allocationId)
return nil
}
}
//申请分配Eip
func allocateNewEip(err error, client *vpc.Client) (string,string) {
request := vpc.CreateAllocateEipAddressRequest()
request.AutoPay = "true"
request.Bandwidth = "2"
request.InternetChargeType = "PayByTraffic"
response, err := client.AllocateEipAddress(request)
if err != nil {
fmt.Print(err.Error())
}
eip := response.EipAddress
allocationId := response.AllocationId
return eip,allocationId
}
// 释放Eip
func releaseEip(allocationId string, client *vpc.Client) {
request := vpc.CreateReleaseEipAddressRequest()
request.AllocationId = allocationId
var err error
for i:=0;i<10;i++ {
var response *vpc.ReleaseEipAddressResponse
response, err = client.ReleaseEipAddress(request)
if !response.IsSuccess() {
i++
time.Sleep(2*time.Second)
fmt.Printf("释放eip异常,需要重试: %s\n", err.Error())
fmt.Printf(response.String() )
continue
}
fmt.Printf("释放eip成功,allocationId: %s\n", allocationId)
return
}
fmt.Printf("释放eip失败,allocationId: %s , error: ", allocationId, err)
}
// Record 解析记录结构体
type Record struct {
data string
name string
ttl int32
recordType string
}
func getDomainRecord() string {
req, err := http.NewRequest("GET",
"https://" + GODADDY_API_HOST + "/v1/domains/"+GODADDY_DOMAIN+"/records/A/"+GODADDY_DNS_NAME,
nil)
if err != nil {
fmt.Println(err)
panic(1)
}
req.Header.Set("Authorization", os.ExpandEnv("sso-key ${GODADDY_KEY}:${GODADDY_SECRET}"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
// handle err
fmt.Printf("%s", err)
}
bodyBytes, err2 := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err2 != nil {
fmt.Printf("%s", err2)
}
var Msg []map[string]string
json.Unmarshal([]byte(bodyBytes), &Msg)
fmt.Printf("%s.%s 解析信息:%s\n",GODADDY_DNS_NAME, GODADDY_DOMAIN ,Msg)
return Msg[0]["data"]
}
func updateDomainRecord(eip string){
body := fmt.Sprintf(`[{"data": "%s", "ttl": 600 }]`,eip)
fmt.Println(body)
req, err := http.NewRequest("PUT",
"https://" + GODADDY_API_HOST + "/v1/domains/"+GODADDY_DOMAIN+"/records/A/"+GODADDY_DNS_NAME,
bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println(err.Error())
panic(1)
}
req.Header.Set("Authorization", os.ExpandEnv("sso-key ${GODADDY_KEY}:${GODADDY_SECRET}"))
req.Header.Set("Content-Type", "application/json")
resp, err2 := http.DefaultClient.Do(req)
if err2 != nil {
fmt.Println(err2.Error())
panic(1)
}
bodyBytes, err3 := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err3 != nil {
fmt.Println(err3.Error())
panic(1)
}
fmt.Printf("更新 %s.%s %s 解析成功!\n",GODADDY_DNS_NAME, GODADDY_DOMAIN, string(bodyBytes))
defer resp.Body.Close()
}
// 检查自定义ss状态页
func checkSSStatus(ssStatusUrl string){
body,err := utils.HttpRequestExec("GET", ssStatusUrl,nil, "","")
if err != nil{
log.Printf("get %s err: %v", ssStatusUrl, err)
return
}
retStr := string(body)
if strings.TrimSpace(retStr) != "0" {
log.Fatalf("get %s is %v", ssStatusUrl, retStr)
}
fmt.Printf("get %s is %v\n", ssStatusUrl, retStr)
}
func main() {
regionId := os.Getenv("REGION_ID")
accessKeyId := os.Getenv("ACCESS_KEY_ID")
accessKeySecret := os.Getenv("ACCESS_KEY_SECRET")
instanceId := os.Getenv("INSTANCE_ID")
checkPort := os.Getenv("CHECK_PORT")
isCheckSSStatus := os.Getenv("IS_CHECK_SS_STATUS")
GODADDY_API_HOST = os.Getenv("GODADDY_API_HOST")
GODADDY_DOMAIN = os.Getenv("GODADDY_DOMAIN")
GODADDY_DNS_NAME = os.Getenv("GODADDY_DNS_NAME")
if GODADDY_API_HOST == "" {
log.Fatal("环境变量 GODADDY_API_HOST 不能为空!")
}
if GODADDY_DOMAIN == "" {
log.Fatal("环境变量 GODADDY_DOMAIN 不能为空!")
}
if GODADDY_DNS_NAME == "" {
log.Fatal("环境变量 GODADDY_DNS_NAME 不能为空!")
}
if regionId == "" {
log.Fatal("环境变量 REGION_ID 不能为空!")
}
if accessKeyId == "" {
log.Fatal("环境变量 ACCESS_KEY_ID 不能为空!")
}
if accessKeySecret == "" {
log.Fatal("环境变量 ACCESS_KEY_SECRET 不能为空!")
}
if instanceId == "" {
log.Fatal("环境变量 INSTANCE_ID 不能为空!")
}
if checkPort == "" {
log.Fatal("环境变量 CHECK_PORT 不能为空!")
}
client, err := vpc.NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret)
eip,allocationId := getEip(err, client,instanceId)
// 判断是否绑定了eip
if eip != "" {
//绑定了eip 则检查连通性
fmt.Println("Eip: ", eip)
fmt.Println("AllocationId: ", allocationId)
if isCheckSSStatus == "true" {
// 通过自定义的ss状态页检查ss是否启动状态
url:= fmt.Sprintf("http://%s:8100/status.txt", eip)
checkSSStatus(url)
}
if !checkTCPPort(eip+":"+checkPort) {
log.Println("连接", eip ,checkPort,"失败!")
// 需要开启容器特权,所以注释ping功能
//不能连接tcp端口,则解绑eip
err = unassociateEip(allocationId, instanceId, client)
if err != nil {
return
}
time.Sleep(time.Second)
// 释放eip
releaseEip(allocationId, client)
} else {
// 可以连接端口,则返回,什么也不操作
fmt.Printf("Eip: %s:%s 可以正常连接。\n",eip, checkPort)
// 获取解析信息
eip2 := getDomainRecord()
if eip != eip2 {
fmt.Println("Eip解析不同步,更新解析记录\n")
updateDomainRecord(eip)
}
return
}
}
// 获取可用Eip
eip,allocationId = getAvailableEip(err,client)
if eip == "" {
// 无可用Eip,申请新Eip
eip, allocationId = allocateNewEip(err, client)
if eip == "" {
fmt.Print("申请分配Eip错误。")
panic(1)
return
}
fmt.Printf("申请分配Eip: %s\n", eip)
}
// 绑定Eip
err = associateEip(allocationId, instanceId, client)
if err != nil {
fmt.Printf("绑定Eip错误: %s\n",err.Error())
panic(1)
return
}
fmt.Printf("绑定 eip %s 到实例 %s\n", eip, instanceId)
// 更新解析ip
updateDomainRecord(eip)
// 获取解析信息
getDomainRecord()
smtpTo := os.Getenv("SMTP_TO")
if smtpTo != "" {
utils.SendMail("代理EIP替换为: "+eip,"代理EIP替换为: "+eip)
}
}