5
5
"fmt"
6
6
"github.com/weibocom/motan-go/endpoint"
7
7
vlog "github.com/weibocom/motan-go/log"
8
+ "github.com/weibocom/motan-go/meta"
9
+ "github.com/weibocom/motan-go/provider"
8
10
"gopkg.in/yaml.v2"
9
11
"io/ioutil"
10
12
"net"
@@ -193,6 +195,8 @@ func (a *Agent) StartMotanAgentFromConfig(config *cfg.Config) {
193
195
return
194
196
}
195
197
fmt .Println ("init agent context success." )
198
+ // initialize meta package
199
+ meta .Initialize (a .Context )
196
200
a .initParam ()
197
201
a .SetSanpshotConf ()
198
202
a .initAgentURL ()
@@ -225,7 +229,7 @@ func (a *Agent) StartMotanAgentFromConfig(config *cfg.Config) {
225
229
226
230
func (a * Agent ) startRegistryFailback () {
227
231
vlog .Infoln ("start agent failback" )
228
- ticker := time .NewTicker (registry .DefaultFailbackInterval * time .Millisecond )
232
+ ticker := time .NewTicker (time . Duration ( registry .GetFailbackInterval ()) * time .Millisecond )
229
233
defer ticker .Stop ()
230
234
for range ticker .C {
231
235
a .registryLock .Lock ()
@@ -265,22 +269,8 @@ func (a *Agent) GetRegistryStatus() []map[string]*motan.RegistryStatus {
265
269
}
266
270
267
271
func (a * Agent ) registerStatusSampler () {
268
- metrics .RegisterStatusSampleFunc ("memory" , func () int64 {
269
- p , _ := process .NewProcess (int32 (os .Getpid ()))
270
- memInfo , err := p .MemoryInfo ()
271
- if err != nil {
272
- return 0
273
- }
274
- return int64 (memInfo .RSS >> 20 )
275
- })
276
- metrics .RegisterStatusSampleFunc ("cpu" , func () int64 {
277
- p , _ := process .NewProcess (int32 (os .Getpid ()))
278
- cpuPercent , err := p .CPUPercent ()
279
- if err != nil {
280
- return 0
281
- }
282
- return int64 (cpuPercent )
283
- })
272
+ metrics .RegisterStatusSampleFunc ("memory" , GetRssMemory )
273
+ metrics .RegisterStatusSampleFunc ("cpu" , GetCpuPercent )
284
274
metrics .RegisterStatusSampleFunc ("goroutine_count" , func () int64 {
285
275
return int64 (runtime .NumGoroutine ())
286
276
})
@@ -289,6 +279,24 @@ func (a *Agent) registerStatusSampler() {
289
279
})
290
280
}
291
281
282
+ func GetRssMemory () int64 {
283
+ p , _ := process .NewProcess (int32 (os .Getpid ()))
284
+ memInfo , err := p .MemoryInfo ()
285
+ if err != nil {
286
+ return 0
287
+ }
288
+ return int64 (memInfo .RSS >> 20 )
289
+ }
290
+
291
+ func GetCpuPercent () int64 {
292
+ p , _ := process .NewProcess (int32 (os .Getpid ()))
293
+ cpuPercent , err := p .CPUPercent ()
294
+ if err != nil {
295
+ return 0
296
+ }
297
+ return int64 (cpuPercent )
298
+ }
299
+
292
300
func (a * Agent ) initStatus () {
293
301
if a .recover {
294
302
a .recoverStatus ()
@@ -371,7 +379,7 @@ func (a *Agent) initParam() {
371
379
port = defaultPort
372
380
}
373
381
374
- mPort := * motan .Mport
382
+ mPort := motan .GetMport ()
375
383
if mPort == 0 {
376
384
if envMPort , ok := os .LookupEnv ("mport" ); ok {
377
385
if envMPortInt , err := strconv .Atoi (envMPort ); err == nil {
@@ -629,6 +637,7 @@ func (a *Agent) initAgentURL() {
629
637
} else {
630
638
agentURL .Parameters [motan .ApplicationKey ] = agentURL .Group
631
639
}
640
+ motan .SetApplication (agentURL .Parameters [motan .ApplicationKey ])
632
641
if agentURL .Group == "" {
633
642
agentURL .Group = defaultAgentGroup
634
643
agentURL .Parameters [motan .ApplicationKey ] = defaultAgentGroup
@@ -652,8 +661,9 @@ func (a *Agent) initAgentURL() {
652
661
func (a * Agent ) startAgent () {
653
662
url := a .agentURL .Copy ()
654
663
url .Port = a .port
664
+ url .Protocol = mserver .Motan2
655
665
handler := & agentMessageHandler {agent : a }
656
- server := & mserver. MotanServer { URL : url }
666
+ server := defaultExtFactory . GetServer ( url )
657
667
server .SetMessageHandler (handler )
658
668
vlog .Infof ("Motan agent is started. port:%d" , a .port )
659
669
fmt .Println ("Motan agent start." )
@@ -673,7 +683,7 @@ func (a *Agent) registerAgent() {
673
683
if agentURL .Host == "" {
674
684
agentURL .Host = motan .GetLocalIP ()
675
685
}
676
- if registryURL , regexit := a .Context .RegistryURLs [reg ]; regexit {
686
+ if registryURL , regExist := a .Context .RegistryURLs [reg ]; regExist {
677
687
registry := a .extFactory .GetRegistry (registryURL )
678
688
if registry != nil {
679
689
vlog .Infof ("agent register in registry:%s, agent url:%s" , registry .GetURL ().GetIdentity (), agentURL .GetIdentity ())
@@ -697,6 +707,16 @@ type agentMessageHandler struct {
697
707
agent * Agent
698
708
}
699
709
710
+ func (a * agentMessageHandler ) GetName () string {
711
+ return "agentMessageHandler"
712
+ }
713
+
714
+ func (a * agentMessageHandler ) GetRuntimeInfo () map [string ]interface {} {
715
+ info := map [string ]interface {}{}
716
+ info [motan .RuntimeMessageHandlerTypeKey ] = a .GetName ()
717
+ return info
718
+ }
719
+
700
720
func (a * agentMessageHandler ) clusterCall (request motan.Request , ck string , motanCluster * cluster.MotanCluster ) (res motan.Response ) {
701
721
// fill default request info
702
722
fillDefaultReqInfo (request , motanCluster .GetURL ())
@@ -747,8 +767,8 @@ func (a *agentMessageHandler) httpCall(request motan.Request, ck string, httpClu
747
767
}
748
768
httpRequest := fasthttp .AcquireRequest ()
749
769
httpResponse := fasthttp .AcquireResponse ()
770
+ // do not release http response
750
771
defer fasthttp .ReleaseRequest (httpRequest )
751
- defer fasthttp .ReleaseResponse (httpResponse )
752
772
httpRequest .Header .Del ("Host" )
753
773
httpRequest .SetHost (originalService )
754
774
httpRequest .URI ().SetPath (request .GetMethod ())
@@ -886,6 +906,9 @@ func (a *Agent) unavailableAllServices() {
886
906
func (a * Agent ) doExportService (url * motan.URL ) {
887
907
a .svcLock .Lock ()
888
908
defer a .svcLock .Unlock ()
909
+ if _ , ok := a .serviceExporters .Load (url .GetIdentityWithRegistry ()); ok {
910
+ return
911
+ }
889
912
890
913
globalContext := a .Context
891
914
exporter := & mserver.DefaultExporter {}
@@ -932,11 +955,38 @@ func (a *Agent) doExportService(url *motan.URL) {
932
955
}
933
956
934
957
type serverAgentMessageHandler struct {
935
- providers * motan.CopyOnWriteMap
958
+ providers * motan.CopyOnWriteMap
959
+ frameworkProviders * motan.CopyOnWriteMap
960
+ }
961
+
962
+ func (sa * serverAgentMessageHandler ) GetName () string {
963
+ return "serverAgentMessageHandler"
964
+ }
965
+
966
+ func (sa * serverAgentMessageHandler ) GetRuntimeInfo () map [string ]interface {} {
967
+ info := map [string ]interface {}{}
968
+ info [motan .RuntimeMessageHandlerTypeKey ] = sa .GetName ()
969
+ providersInfo := map [string ]interface {}{}
970
+ sa .providers .Range (func (k , v interface {}) bool {
971
+ provider , ok := v .(motan.Provider )
972
+ if ! ok {
973
+ return true
974
+ }
975
+ providersInfo [k .(string )] = provider .GetRuntimeInfo ()
976
+ return true
977
+ })
978
+ info [motan .RuntimeProvidersKey ] = providersInfo
979
+ return info
936
980
}
937
981
938
982
func (sa * serverAgentMessageHandler ) Initialize () {
939
983
sa .providers = motan .NewCopyOnWriteMap ()
984
+ sa .frameworkProviders = motan .NewCopyOnWriteMap ()
985
+ sa .initFrameworkServiceProvider ()
986
+ }
987
+
988
+ func (sa * serverAgentMessageHandler ) initFrameworkServiceProvider () {
989
+ sa .frameworkProviders .Store (meta .MetaServiceName , & provider.MetaProvider {})
940
990
}
941
991
942
992
func getServiceKey (group , path string ) string {
@@ -954,15 +1004,22 @@ func (sa *serverAgentMessageHandler) Call(request motan.Request) (res motan.Resp
954
1004
group = request .GetAttachment (motan .GroupKey )
955
1005
}
956
1006
serviceKey := getServiceKey (group , request .GetServiceName ())
1007
+ if mfs := request .GetAttachment (mpro .MFrameworkService ); mfs != "" {
1008
+ if fp , ok := sa .frameworkProviders .Load (request .GetServiceName ()); ok {
1009
+ return fp .(motan.Provider ).Call (request )
1010
+ }
1011
+ //throw specific exception to avoid triggering forced fusing on the client side。
1012
+ return motan .BuildExceptionResponse (request .GetRequestID (), & motan.Exception {ErrCode : 501 , ErrMsg : motan .ServiceNotSupport , ErrType : motan .ServiceException })
1013
+ }
957
1014
if p := sa .providers .LoadOrNil (serviceKey ); p != nil {
958
1015
p := p .(motan.Provider )
959
1016
res = p .Call (request )
960
1017
res .GetRPCContext (true ).GzipSize = int (p .GetURL ().GetIntValue (motan .GzipSizeKey , 0 ))
961
1018
return res
962
1019
}
963
- vlog .Errorf ("not found provider for %s" , motan .GetReqInfo (request ))
1020
+ vlog .Errorf ("%s%s, %s" , motan . ProviderNotExistPrefix , serviceKey , motan .GetReqInfo (request ))
964
1021
atomic .AddInt64 (& notFoundProviderCount , 1 )
965
- return motan .BuildExceptionResponse (request .GetRequestID (), & motan.Exception {ErrCode : 500 , ErrMsg : "not found provider for " + serviceKey , ErrType : motan .ServiceException })
1022
+ return motan .BuildExceptionResponse (request .GetRequestID (), & motan.Exception {ErrCode : motan . EProviderNotExist , ErrMsg : motan . ProviderNotExistPrefix + serviceKey , ErrType : motan .ServiceException })
966
1023
}
967
1024
968
1025
func (sa * serverAgentMessageHandler ) AddProvider (p motan.Provider ) error {
@@ -1119,13 +1176,12 @@ func (a *Agent) startMServer() {
1119
1176
for kk , vv := range v {
1120
1177
handlers [kk ] = vv
1121
1178
}
1122
-
1123
1179
}
1124
1180
}
1125
1181
for k , v := range handlers {
1126
1182
a .mhandle (k , v )
1127
1183
}
1128
-
1184
+ var mPort int
1129
1185
var managementListener net.Listener
1130
1186
if managementUnixSockAddr := a .agentURL .GetParam (motan .ManagementUnixSockKey , "" ); managementUnixSockAddr != "" {
1131
1187
listener , err := motan .ListenUnixSock (managementUnixSockAddr )
@@ -1159,19 +1215,21 @@ func (a *Agent) startMServer() {
1159
1215
managementListener = motan.TCPKeepAliveListener {TCPListener : listener .(* net.TCPListener )}
1160
1216
break
1161
1217
}
1218
+ mPort = a .mport
1162
1219
if managementListener == nil {
1163
1220
vlog .Warningf ("start management server failed for port range %s" , startAndPortStr )
1164
1221
return
1165
1222
}
1166
1223
} else {
1167
1224
listener , err := net .Listen ("tcp" , ":" + strconv .Itoa (a .mport ))
1225
+ mPort = a .mport
1168
1226
if err != nil {
1169
1227
vlog .Infof ("listen manage port %d failed:%s" , a .mport , err .Error ())
1170
1228
return
1171
1229
}
1172
1230
managementListener = motan.TCPKeepAliveListener {TCPListener : listener .(* net.TCPListener )}
1173
1231
}
1174
-
1232
+ motan . SetMport ( mPort )
1175
1233
vlog .Infof ("start listen manage for address: %s" , managementListener .Addr ().String ())
1176
1234
err := http .Serve (managementListener , nil )
1177
1235
if err != nil {
@@ -1191,8 +1249,10 @@ func (a *Agent) mhandle(k string, h http.Handler) {
1191
1249
setAgentLock .Unlock ()
1192
1250
}
1193
1251
http .HandleFunc (k , func (w http.ResponseWriter , r * http.Request ) {
1252
+ vlog .Infof ("mport request: %s, address: %s" , r .URL .Path , r .RemoteAddr )
1194
1253
if ! PermissionCheck (r ) {
1195
1254
w .Write ([]byte ("need permission!" ))
1255
+ vlog .Warningf ("mport request no permission: %s, address: %s" , r .URL .Path , r .RemoteAddr )
1196
1256
return
1197
1257
}
1198
1258
defer func () {
0 commit comments