-
Notifications
You must be signed in to change notification settings - Fork 184
/
server.go
1310 lines (1149 loc) · 30.8 KB
/
server.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package teaconfigs
import (
"errors"
"github.com/TeaWeb/build/internal/teaconfigs/api"
"github.com/TeaWeb/build/internal/teaconfigs/notices"
"github.com/TeaWeb/build/internal/teaconfigs/shared"
"github.com/TeaWeb/build/internal/teaconst"
"github.com/TeaWeb/build/internal/teaevents"
"github.com/TeaWeb/build/internal/teautils"
"github.com/TeaWeb/build/internal/teawaf"
"github.com/iwind/TeaGo/rands"
"gopkg.in/yaml.v3"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/files"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/logs"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
"github.com/iwind/TeaGo/utils/string"
"net/http"
"regexp"
"strconv"
"strings"
)
// 服务配置
type ServerConfig struct {
shared.HeaderList `yaml:",inline"`
FastcgiList `yaml:",inline"`
RewriteList `yaml:",inline"`
BackendList `yaml:",inline"`
On bool `yaml:"on" json:"on"`
Id string `yaml:"id" json:"id"` // ID
TeaVersion string `yaml:"teaVersion" json:"teaVersion"` // Tea版本
Description string `yaml:"description" json:"description"` // 描述
Name []string `yaml:"name" json:"name"` // 域名
Http bool `yaml:"http" json:"http"` // 是否支持HTTP
RedirectToHttps bool `yaml:"redirectToHttps" json:"redirectToHttps"` // 是否自动跳转到Https
IsDefault bool `yaml:"isDefault" json:"isDefault"` // 是否默认的服务,找不到匹配域名时有限使用此配置
// 监听地址
Listen []string `yaml:"listen" json:"listen"`
Root string `yaml:"root" json:"root"` // 资源根目录
Index []string `yaml:"index" json:"index"` // 默认文件
Charset string `yaml:"charset" json:"charset"` // 字符集
Locations []*LocationConfig `yaml:"locations" json:"locations"` // 地址配置
MaxBodySize string `yaml:"maxBodySize" json:"maxBodySize"` // 请求body最大尺寸
GzipLevel1 uint8 `yaml:"gzipLevel" json:"gzipLevel"` // deprecated in v0.1.8: Gzip压缩级别
GzipMinLength1 string `yaml:"gzipMinLength" json:"gzipMinLength"` // deprecated in v0.1.8: 需要压缩的最小内容尺寸
Gzip *GzipConfig `yaml:"gzip" json:"gzip"`
// 访问日志
AccessLog []*AccessLogConfig `yaml:"accessLog" json:"accessLog"` // 访问日志配置
DisableAccessLog1 bool `yaml:"disableAccessLog" json:"disableAccessLog"` // deprecated: 是否禁用访问日志
AccessLogFields1 []int `yaml:"accessLogFields" json:"accessLogFields"` // deprecated: 访问日志保留的字段,如果为nil,则表示没有设置
// 统计
DisableStat bool `yaml:"disableStat" json:"disableStat"` // 是否禁用统计
// SSL
SSL *SSLConfig `yaml:"ssl" json:"ssl"`
// TCP,如果有此配置的说明为TCP代理
TCP *TCPConfig `yaml:"tcp" json:"tcp"`
// ForwardHTTP,如果有此配置的说明为正向HTTP代理
ForwardHTTP *ForwardHTTPConfig `yaml:"forwardHTTP" json:"forwardHTTP"`
// 参考:http://nginx.org/en/docs/http/ngx_http_access_module.html
Allow []string `yaml:"allow" json:"allow"` //TODO
Deny []string `yaml:"deny" json:"deny"` //TODO
Filename string `yaml:"filename" json:"filename"` // 配置文件名
Proxy string `yaml:"proxy" json:"proxy"` // 代理配置 TODO
CachePolicy string `yaml:"cachePolicy" json:"cachePolicy"` // 缓存策略
CacheOn bool `yaml:"cacheOn" json:"cacheOn"` // 缓存是否打开
cachePolicy *shared.CachePolicy
WAFOn bool `yaml:"wafOn" json:"wafOn"` // 是否启用
WafId string `yaml:"wafId" json:"wafId"` // WAF ID
waf *teawaf.WAF // waf object
// API相关
API *api.APIConfig `yaml:"api" json:"api"` // API配置
// 看板
RealtimeBoard *Board `yaml:"realtimeBoard" json:"realtimeBoard"` // 即时看板
StatBoard *Board `yaml:"statBoard" json:"statBoard"` // 统计看板
StatItems []string `yaml:"statItems" json:"statItems"` // 统计指标
// 是否开启静态文件加速
CacheStatic bool `yaml:"cacheStatic" json:"cacheStatic"`
// 请求分组
RequestGroups []*RequestGroup `yaml:"requestGroups" json:"requestGroups"` // 请求条件分组
defaultRequestGroup *RequestGroup
hasRequestGroupFilters bool
Pages []*PageConfig `yaml:"pages" json:"pages"` // 特殊页,更高级的需求应该通过Location来设置
Shutdown *ShutdownConfig `yaml:"shutdown" json:"shutdown"` // 关闭页
ShutdownPageOn1 bool `yaml:"shutdownPageOn" json:"shutdownPageOn"` // deprecated: v0.1.8, 是否开启临时关闭页面
ShutdownPage1 string `yaml:"shutdownPage" json:"shutdownPage"` // deprecated: v0.1.8, 临时关闭页面
Version int `yaml:"version" json:"version"` // 版本
// 隧道相关
Tunnel *TunnelConfig `yaml:"tunnel" json:"tunnel"`
// 通知设置
NoticeSetting map[notices.NoticeLevel][]*notices.NoticeReceiver `yaml:"noticeSetting" json:"noticeSetting"`
// 通知条目设置
NoticeItems struct {
BackendDown *notices.Item `yaml:"backendDown" json:"backendDown"`
BackendUp *notices.Item `yaml:"backendUp" json:"backendUp"`
} `yaml:"noticeItems" json:"noticeItems"`
maxBodySize int64
}
// 从目录中加载配置
func LoadServerConfigsFromDir(dirPath string) []*ServerConfig {
servers := []*ServerConfig{}
dir := files.NewFile(dirPath)
subFiles := dir.Glob("*.proxy.conf")
for _, configFile := range subFiles {
reader, err := configFile.Reader()
if err != nil {
logs.Error(err)
continue
}
// sample
if configFile.Name() == "server.sample.www.proxy.conf" {
_ = reader.Close()
continue
}
config := &ServerConfig{}
err = reader.ReadYAML(config)
if err != nil {
_ = reader.Close()
continue
}
config.Filename = configFile.Name()
// API
if config.API == nil {
config.API = api.NewAPIConfig()
}
servers = append(servers, config)
_ = reader.Close()
}
return servers
}
// 取得一个新的服务配置
func NewServerConfig() *ServerConfig {
server := &ServerConfig{
On: true,
Id: rands.HexString(16),
API: api.NewAPIConfig(),
CacheOn: true,
WAFOn: true,
}
server.SetupNoticeItems()
return server
}
// 从配置文件中读取配置信息
func NewServerConfigFromFile(filename string) (*ServerConfig, error) {
if len(filename) == 0 {
return nil, errors.New("filename should not be empty")
}
reader, err := files.NewReader(Tea.ConfigFile(filename))
if err != nil {
return nil, err
}
defer func() {
_ = reader.Close()
}()
config := &ServerConfig{}
err = reader.ReadYAML(config)
if err != nil {
return nil, err
}
config.compatible()
config.Filename = filename
// 初始化
if len(config.Locations) == 0 {
config.Locations = []*LocationConfig{}
}
if config.API == nil {
config.API = api.NewAPIConfig()
}
if config.Headers == nil {
config.Headers = []*shared.HeaderConfig{}
}
if config.IgnoreHeaders == nil {
config.IgnoreHeaders = []string{}
}
return config, nil
}
// 通过ID读取配置信息
func NewServerConfigFromId(serverId string) *ServerConfig {
if len(serverId) == 0 {
return nil
}
filename := "server." + serverId + ".proxy.conf"
file := files.NewFile(Tea.ConfigFile(filename))
if !file.Exists() {
// 遍历查找
for _, server := range LoadServerConfigsFromDir(Tea.ConfigDir()) {
if server.Id == serverId {
server.compatible()
return server
}
}
return nil
}
data, err := file.ReadAll()
if err != nil {
logs.Error(err)
return nil
}
server := &ServerConfig{}
err = yaml.Unmarshal(data, server)
if err != nil {
logs.Error(err)
return nil
}
server.compatible()
return server
}
// 校验配置
func (this *ServerConfig) Validate() error {
// 兼容设置
this.compatible()
// 最大Body尺寸
maxBodySize, _ := stringutil.ParseFileSize(this.MaxBodySize)
this.maxBodySize = int64(maxBodySize)
// gzip
if this.Gzip != nil {
err := this.Gzip.Validate()
if err != nil {
return err
}
}
// ssl
if this.SSL != nil {
err := this.SSL.Validate()
if err != nil {
return err
}
}
// backends
err := this.ValidateBackends()
if err != nil {
return err
}
// locations
for _, location := range this.Locations {
// 复制request group
location.requestGroups = []*RequestGroup{}
if len(location.Backends) > 0 {
for _, group := range this.RequestGroups {
location.AddRequestGroup(group.Copy())
}
}
err := location.Validate()
if err != nil {
return err
}
}
// fastcgi
err = this.ValidateFastcgi()
if err != nil {
return err
}
// rewrite rules
err = this.ValidateRewriteRules()
if err != nil {
return err
}
// headers
err = this.ValidateHeaders()
if err != nil {
return err
}
// 校验缓存配置
if len(this.CachePolicy) > 0 && this.CacheOn {
policy := shared.NewCachePolicyFromFile(this.CachePolicy)
if policy != nil {
err := policy.Validate()
if err != nil {
return err
}
this.cachePolicy = policy
}
}
// waf
if len(this.WafId) > 0 && this.WAFOn {
waf := SharedWAFList().FindWAF(this.WafId)
if waf != nil {
err := waf.Init()
if err != nil {
return err
}
this.waf = waf
}
}
// api
if this.API == nil {
this.API = api.NewAPIConfig()
}
err = this.API.Validate()
if err != nil {
return err
}
// request groups
for _, group := range this.RequestGroups {
group.Backends = []*BackendConfig{}
group.Scheduling = this.Scheduling
if group.IsDefault {
this.defaultRequestGroup = group
}
for _, backend := range this.Backends {
if len(backend.RequestGroupIds) == 0 && group.IsDefault {
group.AddBackend(backend)
} else if backend.HasRequestGroupId(group.Id) {
group.AddBackend(backend)
}
}
err := group.Validate()
if err != nil {
return err
}
if group.HasFilters() {
this.hasRequestGroupFilters = true
}
}
// pages
for _, page := range this.Pages {
err := page.Validate()
if err != nil {
return err
}
}
// shutdown
if this.Shutdown != nil {
err = this.Shutdown.Validate()
if err != nil {
return err
}
}
// tunnel
if this.Tunnel != nil {
err = this.Tunnel.Validate()
if err != nil {
return err
}
}
// access log
if this.AccessLog != nil {
for _, a := range this.AccessLog {
err = a.Validate()
if err != nil {
return err
}
}
}
// tcp
if this.TCP != nil {
err = this.TCP.Validate()
if err != nil {
return err
}
}
return nil
}
// 版本相关兼容性
func (this *ServerConfig) compatible() {
// 版本相关
if len(this.TeaVersion) == 0 {
// cache 默认值
this.CacheOn = true
// waf 默认值
this.WAFOn = true
}
// v0.1.3
if stringutil.VersionCompare(this.TeaVersion, "0.1.3") < 0 {
// waf 默认值
this.WAFOn = true
}
// v0.1.5
if len(this.TeaVersion) == 0 || stringutil.VersionCompare(this.TeaVersion, "0.1.5") <= 0 {
if len(this.AccessLog) == 0 {
this.AccessLog = []*AccessLogConfig{
{
Id: rands.HexString(16),
On: !this.DisableAccessLog1,
Fields: this.AccessLogFields1,
Status1: true,
Status2: true,
Status3: true,
Status4: true,
Status5: true,
},
}
}
}
// v0.1.8
if stringutil.VersionCompare(this.TeaVersion, "0.1.8") < 0 {
// gzip
if this.GzipLevel1 > 0 {
this.Gzip = &GzipConfig{
Level: int8(this.GzipLevel1),
MinLength: this.GzipMinLength1,
}
this.GzipLevel1 = 0
}
// pages
for _, page := range this.Pages {
page.NewStatus = 200
}
// shutdown
if this.ShutdownPageOn1 {
shutdown := NewShutdownConfig()
shutdown.On = true
shutdown.URL = this.ShutdownPage1
shutdown.Status = 200
this.Shutdown = shutdown
}
}
for _, location := range this.Locations {
location.Compatible(this.TeaVersion)
}
}
// 最大Body尺寸
func (this *ServerConfig) MaxBodyBytes() int64 {
return this.maxBodySize
}
// 添加域名
func (this *ServerConfig) AddName(name ...string) {
this.Name = append(this.Name, name...)
}
// 添加监听地址
func (this *ServerConfig) AddListen(address string) {
this.Listen = append(this.Listen, address)
}
// 分解所有监听地址
func (this *ServerConfig) ParseListenAddresses() []string {
result := []string{}
var reg = regexp.MustCompile(`\[\s*(\d+)\s*[,:-]\s*(\d+)\s*]$`)
for _, addr := range this.Listen {
match := reg.FindStringSubmatch(addr)
if len(match) == 0 {
result = append(result, addr)
} else {
min := types.Int(match[1])
max := types.Int(match[2])
if min > max {
min, max = max, min
}
for i := min; i <= max; i++ {
newAddr := reg.ReplaceAllString(addr, ":"+strconv.Itoa(i))
result = append(result, newAddr)
}
}
}
return result
}
// 获取某个位置上的配置
func (this *ServerConfig) LocationAtIndex(index int) *LocationConfig {
if index < 0 {
return nil
}
if index >= len(this.Locations) {
return nil
}
location := this.Locations[index]
err := location.Validate()
if err != nil {
logs.Error(err)
}
return location
}
// 保存
func (this *ServerConfig) Save() error {
shared.Locker.Lock()
defer shared.Locker.WriteUnlockNotify()
if len(this.Filename) == 0 {
return errors.New("'filename' should be specified")
}
this.TeaVersion = teaconst.TeaVersion
this.Version++
writer, err := files.NewWriter(Tea.ConfigFile(this.Filename))
if err != nil {
return err
}
_, err = writer.WriteYAML(this)
_ = writer.Close()
return err
}
// 删除
func (this *ServerConfig) Delete() error {
if len(this.Filename) == 0 {
return errors.New("'filename' should be specified")
}
// 删除key
if this.SSL != nil {
err := this.SSL.DeleteFiles()
if err != nil {
logs.Error(err)
}
}
return files.NewFile(Tea.ConfigFile(this.Filename)).Delete()
}
// 判断是否和域名匹配
func (this *ServerConfig) MatchName(name string) (matchedName string, matched bool) {
isMatched := teautils.MatchDomains(this.Name, name)
if isMatched {
return name, true
}
return
}
// 取得第一个非泛解析的域名
func (this *ServerConfig) FirstName() string {
for _, name := range this.Name {
if strings.Contains(name, "*") {
continue
}
return name
}
return ""
}
// 添加路径规则
func (this *ServerConfig) AddLocation(location *LocationConfig) {
this.Locations = append(this.Locations, location)
}
// 缓存策略
func (this *ServerConfig) CachePolicyObject() *shared.CachePolicy {
return this.cachePolicy
}
// WAF策略
func (this *ServerConfig) WAF() *teawaf.WAF {
return this.waf
}
// 根据Id查找Location
func (this *ServerConfig) FindLocation(locationId string) *LocationConfig {
for _, location := range this.Locations {
if location.Id == locationId {
err := location.Validate()
if err != nil {
logs.Error(err)
}
return location
}
}
return nil
}
// 删除Location
func (this *ServerConfig) RemoveLocation(locationId string) {
result := []*LocationConfig{}
for _, location := range this.Locations {
if location.Id == locationId {
continue
}
result = append(result, location)
}
this.Locations = result
}
// 查找HeaderList
func (this *ServerConfig) FindHeaderList(locationId string, backendId string, rewriteId string, fastcgiId string) (headerList shared.HeaderListInterface, err error) {
if len(rewriteId) > 0 { // Rewrite
if len(locationId) > 0 { // Server > Location > Rewrite
location := this.FindLocation(locationId)
if location == nil {
err = errors.New("找不到要修改的location")
return
}
rewrite := location.FindRewriteRule(rewriteId)
if rewrite == nil {
err = errors.New("找不到要修改的rewrite")
return
}
headerList = rewrite
} else { // Server > Rewrite
rewrite := this.FindRewriteRule(rewriteId)
if rewrite == nil {
err = errors.New("找不到要修改的rewrite")
return
}
headerList = rewrite
}
} else if len(fastcgiId) > 0 { // Fastcgi
if len(locationId) > 0 { // Server > Location > Fastcgi
location := this.FindLocation(locationId)
if location == nil {
err = errors.New("找不到要修改的location")
return
}
fastcgi := location.FindFastcgi(fastcgiId)
if fastcgi == nil {
err = errors.New("找不到要修改的Fastcgi")
return
}
headerList = fastcgi
} else { // Server > Fastcgi
fastcgi := this.FindFastcgi(fastcgiId)
if fastcgi == nil {
err = errors.New("找不到要修改的Fastcgi")
return
}
headerList = fastcgi
}
} else if len(backendId) > 0 { // Backend
if len(locationId) > 0 { // Server > Location > Backend
location := this.FindLocation(locationId)
if location == nil {
err = errors.New("找不到要修改的location")
return
}
backend := location.FindBackend(backendId)
if backend == nil {
err = errors.New("找不到要修改的Backend")
return
}
headerList = backend
} else { // Server > Backend
backend := this.FindBackend(backendId)
if backend == nil {
err = errors.New("找不到要修改的Backend")
return
}
headerList = backend
}
} else if len(locationId) > 0 { // Location
location := this.FindLocation(locationId)
if location == nil {
err = errors.New("找不到要修改的location")
return
}
headerList = location
} else { // Server
headerList = this
}
return
}
// 查找FastcgiList
func (this *ServerConfig) FindFastcgiList(locationId string) (fastcgiList FastcgiListInterface, err error) {
if len(locationId) > 0 {
location := this.FindLocation(locationId)
if location == nil {
err = errors.New("找不到要修改的location")
return
}
fastcgiList = location
return
}
fastcgiList = this
return
}
// 查找重写规则
func (this *ServerConfig) FindRewriteList(locationId string) (rewriteList RewriteListInterface, err error) {
if len(locationId) > 0 {
location := this.FindLocation(locationId)
if location == nil {
err = errors.New("找不到要修改的location")
return
}
rewriteList = location
return
}
rewriteList = this
return
}
// 查找后端服务器列表
func (this *ServerConfig) FindBackendList(locationId string, websocket bool) (backendList BackendListInterface, err error) {
if len(locationId) > 0 {
location := this.FindLocation(locationId)
if location == nil {
err = errors.New("找不到要修改的location")
return
}
if websocket {
if location.Websocket == nil {
err = errors.New("websocket未设置")
return
}
return location.Websocket, nil
} else {
return location, nil
}
}
return this, nil
}
// 移动位置
func (this *ServerConfig) MoveLocation(fromIndex int, toIndex int) {
if fromIndex < 0 || fromIndex >= len(this.Locations) {
return
}
if toIndex < 0 || toIndex >= len(this.Locations) {
return
}
if fromIndex == toIndex {
return
}
location := this.Locations[fromIndex]
newList := []*LocationConfig{}
for i := 0; i < len(this.Locations); i++ {
if i == fromIndex {
continue
}
if fromIndex > toIndex && i == toIndex {
newList = append(newList, location)
}
newList = append(newList, this.Locations[i])
if fromIndex < toIndex && i == toIndex {
newList = append(newList, location)
}
}
this.Locations = newList
}
// 是否在引用某个代理
func (this *ServerConfig) RefersProxy(proxyId string) (description string, referred bool) {
if this.Proxy == proxyId {
return "server", true
}
for _, l := range this.Locations {
if l.RefersProxy(proxyId) {
return l.Pattern, true
}
}
for _, r := range this.Rewrite {
if r.RefersProxy(proxyId) {
return r.Pattern, true
}
}
return "", false
}
// 添加请求分组
func (this *ServerConfig) AddRequestGroup(group *RequestGroup) {
this.RequestGroups = append(this.RequestGroups, group)
}
// 删除请求分组
func (this *ServerConfig) RemoveRequestGroup(groupId string) {
result := []*RequestGroup{}
for _, g := range this.RequestGroups {
if g.Id == groupId {
continue
}
result = append(result, g)
}
this.RequestGroups = result
}
// 查找请求分组
func (this *ServerConfig) FindRequestGroup(groupId string) *RequestGroup {
for _, g := range this.RequestGroups {
if g.Id == groupId {
return g
}
}
return nil
}
// 使用请求匹配分组
func (this *ServerConfig) MatchRequestGroup(formatter func(source string) string) *RequestGroup {
if !this.hasRequestGroupFilters {
return nil
}
for _, group := range this.RequestGroups {
if group.HasFilters() && group.Match(formatter) {
return group
}
}
return nil
}
// 取得下一个可用的后端服务
func (this *ServerConfig) NextBackend(call *shared.RequestCall) *BackendConfig {
if this.hasRequestGroupFilters {
group := this.MatchRequestGroup(call.Formatter)
if group != nil {
// request
if group.HasRequestHeaders() {
for _, h := range group.RequestHeaders {
if h.HasVariables() {
call.Request.Header.Set(h.Name, call.Formatter(h.Value))
} else {
call.Request.Header.Set(h.Name, h.Value)
}
}
}
// response
if group.HasResponseHeaders() {
call.AddResponseCall(func(resp http.ResponseWriter) {
// TODO 应用ignore headers
for _, h := range group.ResponseHeaders {
resp.Header().Set(h.Name, call.Formatter(h.Value))
}
})
}
return group.BackendList.NextBackend(call)
}
}
// 默认分组
if this.defaultRequestGroup != nil {
// request
if this.defaultRequestGroup.HasRequestHeaders() {
for _, h := range this.defaultRequestGroup.RequestHeaders {
if h.HasVariables() {
call.Request.Header.Set(h.Name, call.Formatter(h.Value))
} else {
call.Request.Header.Set(h.Name, h.Value)
}
}
}
// response
if this.defaultRequestGroup.HasResponseHeaders() {
call.AddResponseCall(func(resp http.ResponseWriter) {
for _, h := range this.defaultRequestGroup.ResponseHeaders {
// TODO 应用ignore headers
resp.Header().Set(h.Name, call.Formatter(h.Value))
}
})
}
return this.defaultRequestGroup.NextBackend(call)
}
return this.BackendList.NextBackend(call)
}
// 取得下一个可用的后端服务,并排除某个后端
func (this *ServerConfig) NextBackendIgnore(call *shared.RequestCall, backendIds []string) *BackendConfig {
if this.hasRequestGroupFilters {
group := this.MatchRequestGroup(call.Formatter)
if group != nil {
// request
if group.HasRequestHeaders() {
for _, h := range group.RequestHeaders {
if h.HasVariables() {
call.Request.Header.Set(h.Name, call.Formatter(h.Value))
} else {
call.Request.Header.Set(h.Name, h.Value)
}
}
}
// response
if group.HasResponseHeaders() {
call.AddResponseCall(func(resp http.ResponseWriter) {
// TODO 应用ignore headers
for _, h := range group.ResponseHeaders {
resp.Header().Set(h.Name, call.Formatter(h.Value))
}
})
}
backendList := group.BackendList.CloneBackendList()
backendList.DeleteBackends(backendIds)
backendList.SetupScheduling(false)
return backendList.NextBackend(call)
}
}
// 默认分组
if this.defaultRequestGroup != nil {
// request
if this.defaultRequestGroup.HasRequestHeaders() {
for _, h := range this.defaultRequestGroup.RequestHeaders {
if h.HasVariables() {
call.Request.Header.Set(h.Name, call.Formatter(h.Value))
} else {
call.Request.Header.Set(h.Name, h.Value)
}
}
}
// response
if this.defaultRequestGroup.HasResponseHeaders() {
call.AddResponseCall(func(resp http.ResponseWriter) {
for _, h := range this.defaultRequestGroup.ResponseHeaders {
// TODO 应用ignore headers
resp.Header().Set(h.Name, call.Formatter(h.Value))
}
})
}
backendList := this.defaultRequestGroup.CloneBackendList()
backendList.DeleteBackends(backendIds)
backendList.SetupScheduling(false)
return backendList.NextBackend(call)
}
backendList := this.BackendList.CloneBackendList()
backendList.DeleteBackends(backendIds)
backendList.SetupScheduling(false)
return backendList.NextBackend(call)
}
// 设置调度算法
func (this *ServerConfig) SetupScheduling(isBackup bool) {
for _, group := range this.RequestGroups {
group.SetupScheduling(isBackup)
}
this.BackendList.SetupScheduling(isBackup)
}