Skip to content

Commit 48c2d8c

Browse files
Merge pull request #38 from tianxiaoliang/master
refactor
2 parents 1cf3c68 + 6d5f7b5 commit 48c2d8c

File tree

22 files changed

+547
-310
lines changed

22 files changed

+547
-310
lines changed

cse_collector.go

Lines changed: 0 additions & 27 deletions
This file was deleted.

cse_reporter.go

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package metricsink
2+
3+
// Forked from github.com/afex/hystrix-go
4+
// Some parts of this file have been modified to make it functional in this package
5+
6+
import (
7+
"crypto/tls"
8+
"github.com/go-chassis/go-chassis/core/common"
9+
"github.com/go-chassis/go-chassis/third_party/forked/afex/hystrix-go/hystrix"
10+
"github.com/go-mesh/openlogging"
11+
"net/http"
12+
"sync"
13+
"time"
14+
)
15+
16+
var initOnce = sync.Once{}
17+
18+
// CseCollectorConfig is a struct to keep monitoring information
19+
type CseCollectorConfig struct {
20+
// CseMonitorAddr is the http address of the csemonitor server
21+
CseMonitorAddr string
22+
// Headers for csemonitor server
23+
Header http.Header
24+
// TickInterval specifies the period that this collector will send metrics to the server.
25+
TimeInterval time.Duration
26+
// Config structure to configure a TLS client for sending Metric data
27+
TLSConfig *tls.Config
28+
29+
Env string
30+
}
31+
32+
func init() {
33+
hystrix.InstallReporter("CSE Monitoring", reportMetricsToCSEDashboard)
34+
}
35+
36+
var reporter *Reporter
37+
38+
//GetReporter get reporter singleton
39+
func GetReporter() (*Reporter, error) {
40+
var errResult error
41+
initOnce.Do(func() {
42+
monitorServerURL, err := getMonitorEndpoint()
43+
if err != nil {
44+
openlogging.GetLogger().Warnf("Get Monitoring URL failed, CSE monitoring function disabled, err: %v", err)
45+
errResult = err
46+
}
47+
openlogging.GetLogger().Infof("init monitoring client : %s", monitorServerURL)
48+
tlsConfig, err := getTLSForClient(monitorServerURL)
49+
if err != nil {
50+
openlogging.GetLogger().Errorf("Get %s.%s TLS config failed,error : %s", monitorServerURL, common.Consumer, err)
51+
errResult = err
52+
}
53+
reporter, err = NewReporter(&CseCollectorConfig{
54+
CseMonitorAddr: monitorServerURL,
55+
Header: getAuthHeaders(),
56+
TLSConfig: tlsConfig,
57+
})
58+
if err != nil {
59+
openlogging.Error("new reporter failed", openlogging.WithTags(openlogging.Tags{
60+
"err": err.Error(),
61+
}))
62+
errResult = err
63+
}
64+
})
65+
return reporter, errResult
66+
}
67+
68+
//reportMetricsToCSEDashboard use send metrics to cse dashboard
69+
func reportMetricsToCSEDashboard(cb *hystrix.CircuitBreaker) error {
70+
r, err := GetReporter()
71+
if err != nil {
72+
return err
73+
}
74+
r.Send(cb)
75+
return nil
76+
}

csemonitor.go

Lines changed: 31 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,12 @@
11
package metricsink
22

33
import (
4-
"crypto/tls"
5-
"net/http"
6-
"os"
7-
"time"
8-
94
"github.com/go-chassis/go-archaius"
105
chassisRuntime "github.com/go-chassis/go-chassis/pkg/runtime"
116
"github.com/go-chassis/go-chassis/third_party/forked/afex/hystrix-go/hystrix"
127
"github.com/go-mesh/openlogging"
8+
"github.com/huaweicse/cse-collector/pkg/monitoring"
9+
"os"
1310
"runtime"
1411
)
1512

@@ -18,71 +15,51 @@ var IsMonitoringConnected bool
1815

1916
// Reporter is a struct to store the registry address and different monitoring information
2017
type Reporter struct {
21-
CseMonitorAddr string
22-
Header http.Header
23-
Interval time.Duration
24-
Percentiles []float64
25-
TLSConfig *tls.Config
26-
app string
27-
version string
28-
service string
29-
environment string
30-
serviceID string
31-
metricsAPI *CseMonitorClient
18+
environment string
19+
c *monitoring.CseMonitorClient
3220
}
3321

3422
// NewReporter creates a new monitoring object for CSE type collections
35-
func NewReporter(addr string, header http.Header, interval time.Duration, tls *tls.Config, app, version, service, env string) *Reporter {
36-
reporter := &Reporter{
37-
CseMonitorAddr: addr,
38-
Header: header,
39-
Interval: interval,
40-
Percentiles: []float64{0.5, 0.75, 0.95, 0.99, 0.999},
41-
TLSConfig: tls,
42-
app: app,
43-
version: version,
44-
service: service,
45-
environment: env,
46-
}
47-
metricsAPI, err := NewCseMonitorClient(reporter.Header, reporter.CseMonitorAddr, reporter.TLSConfig, "v2")
23+
func NewReporter(config *CseCollectorConfig) (*Reporter, error) {
24+
c, err := monitoring.NewCseMonitorClient(config.Header, config.CseMonitorAddr, config.TLSConfig)
4825
if err != nil {
4926
openlogging.GetLogger().Errorf("Get cse monitor client failed:%s", err)
27+
return nil, err
5028
}
51-
reporter.metricsAPI = metricsAPI
5229
IsMonitoringConnected = true
53-
return reporter
30+
return &Reporter{
31+
environment: config.Env,
32+
c: c,
33+
}, nil
5434
}
5535

56-
// Run creates a go_routine which runs continuously and capture the monitoring data
57-
func (reporter *Reporter) Run(cb *hystrix.CircuitBreaker) {
58-
ticker := time.Tick(reporter.Interval)
59-
60-
for range ticker {
61-
if archaius.GetBool("cse.monitor.client.enable", true) {
62-
reporter.serviceID = chassisRuntime.ServiceID
63-
monitorData := reporter.getData(cb, reporter.app, reporter.version,
64-
reporter.service, reporter.environment, reporter.serviceID, chassisRuntime.InstanceID)
65-
err := reporter.metricsAPI.PostMetrics(monitorData)
66-
if err != nil {
67-
openlogging.GetLogger().Warnf("Unable to report to monitoring server, err: %v", err)
68-
}
36+
//Send send metrics to monitoring service
37+
func (reporter *Reporter) Send(cb *hystrix.CircuitBreaker) {
38+
if archaius.GetBool("cse.monitor.client.enable", true) {
39+
monitorData := reporter.getData(cb)
40+
openlogging.Debug("send metrics", openlogging.WithTags(openlogging.Tags{
41+
"data": monitorData,
42+
}))
43+
err := reporter.c.PostMetrics(monitorData)
44+
if err != nil {
45+
openlogging.GetLogger().Warnf("unable to report to monitoring server, err: %v", err)
6946
}
7047
}
7148
}
7249

73-
func (reporter *Reporter) getData(cb *hystrix.CircuitBreaker,
74-
app, version, service, env, serviceID, instanceID string) MonitorData {
75-
var monitorData = NewMonitorData()
76-
monitorData.AppID = app
77-
monitorData.Version = version
78-
monitorData.Name = service
79-
monitorData.ServiceID = serviceID
80-
monitorData.InstanceID = instanceID
81-
monitorData.Environment = env
50+
func (reporter *Reporter) getData(cb *hystrix.CircuitBreaker) monitoring.MonitorData {
51+
var monitorData = monitoring.NewMonitorData()
52+
monitorData.AppID = chassisRuntime.App
53+
monitorData.Version = chassisRuntime.Version
54+
monitorData.Name = chassisRuntime.ServiceName
55+
monitorData.ServiceID = chassisRuntime.ServiceID
56+
monitorData.InstanceID = chassisRuntime.InstanceID
57+
58+
monitorData.Environment = reporter.environment
8259
monitorData.Instance, _ = os.Hostname()
8360
monitorData.Memory = getProcessInfo()
8461
monitorData.Thread = threadCreateProfile.Count()
8562
monitorData.CPU = float64(runtime.NumCPU())
86-
monitorData.appendInterfaceInfo(cb.Name, cb.Metrics.DefaultCollector())
63+
monitorData.AppendInterfaceInfo(cb)
8764
return *monitorData
8865
}

example/README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
2+
3+
4+
## build
5+
```shell
6+
cd example
7+
export GOPROXY=https://goproxy.io
8+
export REPO=swr.cn-east-2.myhuaweicloud.com/tian
9+
build_image.sh
10+
```
11+
12+
13+
14+

example/build_image.sh

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#!/bin/bash
2+
3+
4+
export ROOT=$PWD
5+
cd order
6+
set -e
7+
set -x
8+
#GO111MODULE=on go mod vendor
9+
build_image(){
10+
cd ${ROOT}/$1
11+
CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main
12+
sudo docker build --build-arg VERSION=$2 -t ${REPO}/$1:$2 .
13+
sudo docker push ${REPO}/$1:$2
14+
}
15+
16+
build_image order 1.0.0
17+
build_image restaurant 1.0.0
18+
build_image restaurant 1.0.1

example/order/Dockerfile

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
FROM alpine:latest
2+
WORKDIR /opt/order
3+
COPY conf /opt/order/conf
4+
COPY main /opt/order
5+
ENTRYPOINT ["/opt/order/main"]

example/order/conf/chassis.yaml

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
#APPLICATION_ID: CSE optional
3+
cse:
4+
service:
5+
registry:
6+
address: http://127.0.0.1:30100
7+
protocols:
8+
rest:
9+
listenAddress: 0.0.0.0:5000
10+
advertiseAddress: 127.0.0.1:5000
11+
handler:
12+
chain:
13+
Consumer:
14+
default: router,bizkeeper-consumer,loadbalance,transport

example/order/conf/lager.yaml

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
# LoggerLevel: |DEBUG|INFO|WARN|ERROR|FATAL
3+
logger_level: DEBUG
4+
5+
# LoggerFile: used to output the name of log.可配置绝对路径,也可以配置用于拼接CHASSIS_HOME的相对路径。
6+
logger_file: log/chassis.log
7+
8+
# LogFormatText:设定日志的输出格式是 json 还是 plaintext (类似于log4j),默认为 false,不建议修改,如果开发过程中想本地查看日志的话,
9+
# 可以设定 LoggerFile 和 LogFormatText 为 true,这样会输出类似于 log4j 格式的本地日志。
10+
log_format_text: false
11+
12+
#rollingPolicy daily/size;用于配置根据时间,还是根据大小进行日志rotate操作。
13+
rollingPolicy: size
14+
15+
# MaxDaily of a log file before rotate. By D Days.;日志rotate时间配置,单位"day"。
16+
log_rotate_date: 1
17+
18+
# MaxSize of a log file before rotate. By M Bytes.;日志rotate文件大小配置,单位"MB"。
19+
log_rotate_size: 10
20+
21+
# Max counts to keep of a log's backup files.日志最大存储数量,单位“个”。
22+
log_backup_count: 7
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
#微服务的私有属性
3+
service_description:
4+
name: order
5+
version: 1.0.0

example/order/main.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package main
2+
3+
import (
4+
"github.com/go-chassis/go-chassis"
5+
"github.com/go-mesh/openlogging"
6+
_ "github.com/huaweicse/auth/adaptor/gochassis"
7+
_ "github.com/huaweicse/cse-collector"
8+
"github.com/huaweicse/cse-collector/example/order/resource"
9+
"log"
10+
"os"
11+
)
12+
13+
//if you use go run main.go instead of binary run, plz export CHASSIS_HOME=/{path}/{to}/rest/client/
14+
15+
func main() {
16+
envs := os.Environ()
17+
for _, e := range envs {
18+
log.Println(e)
19+
}
20+
chassis.RegisterSchema("rest", &resource.OrderResource{})
21+
//Init framework
22+
if err := chassis.Init(); err != nil {
23+
openlogging.Error("Init failed." + err.Error())
24+
return
25+
}
26+
27+
err := chassis.Run()
28+
if err != nil {
29+
panic(err)
30+
}
31+
}

0 commit comments

Comments
 (0)