├── LICENSE ├── README.md ├── docker ├── Dockerfile ├── build.sh ├── entrypoint.sh └── faketsdb ├── influxdb.go ├── main.go ├── semaphore.go ├── tcp_server.go ├── tsdb_server.go └── tsdb_test.go /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # faketsdb 2 | Forward data to InfluxDB with fake OpenTSDB protocol in Open-Falcon 3 | 4 | ## Usage 5 | ```sh 6 | go get github.com/51idc/faketsdb 7 | ``` 8 | 9 | ## Open-Falcon Transfer 10 | // cfg.json 11 | ``` 12 | { 13 | //..... 14 | "tsdb": { 15 | "enabled": false, # don't forget turn enable 16 | "batch": 200, 17 | "connTimeout": 1000, 18 | "callTimeout": 5000, 19 | "maxConns": 32, 20 | "maxIdle": 32, 21 | "retry": 3, 22 |        "address": "127.0.0.1:8088"   # modify here 8089(default) 23 | } 24 | } 25 | ``` 26 | 27 | ## Helper 28 | ```sh 29 | 🍺 eagle [~] → faketsdb -h 30 | Usage of faketsdb: 31 | -cache int 32 | Number of batch items send to influx. (default 3) 33 | -debug 34 | Enable debug mode. 35 | -influxAddr string 36 | InfluxDB HTTP API address. (default "http://127.0.0.1:8086") 37 | -influxDatabase string 38 | InfluxDB Database. (default "test") 39 | -port int 40 | Fake proxy listen port. (default 8089) 41 | ``` 42 | 43 | ## Daemon 44 | 45 | Recommended Supervisor 46 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:jessie 2 | 3 | ADD faketsdb /usr/local/bin 4 | ADD entrypoint.sh /usr/local/bin/entrypoint.sh 5 | 6 | RUN ln -s /usr/local/bin/faketsdb /faketsdb 7 | RUN ln -s /usr/local/bin/entrypoint.sh /entrypoint.sh 8 | 9 | RUN chmod +x /usr/local/bin/faketsdb 10 | RUN chmod +x /usr/local/bin/entrypoint.sh 11 | 12 | RUN rm -rf /etc/localtime && ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime 13 | 14 | CMD [ "/entrypoint.sh" ] 15 | -------------------------------------------------------------------------------- /docker/build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | pwd=$(pwd) 4 | 5 | cd .. 6 | 7 | env GOOS=linux \ 8 | GOARCH=amd64 \ 9 | go build -o docker/faketsdb . 10 | -------------------------------------------------------------------------------- /docker/entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | if [ ! $PORT ]; then 4 | PORT=8089 5 | fi 6 | 7 | if [ ! $CACHE ]; then 8 | CACHE=200 9 | fi 10 | 11 | if [ ! $INFLUXDB_ADDR ]; then 12 | INFLUXDB_ADDR=http://influxdb:8086 13 | fi 14 | 15 | if [ ! $INFLUXDB_DATABASE ]; then 16 | INFLUXDB_DATABASE=test 17 | fi 18 | 19 | 20 | if [ ! $DEBUG ]; then 21 | DEBUG='-debug' 22 | fi 23 | 24 | faketsdb \ 25 | $DEBUG \ 26 | -port=$PORT \ 27 | -cache=$CACHE \ 28 | -influxAddr=$INFLUXDB_ADDR \ 29 | -influxDatabase=$INFLUXDB_DATABASE -------------------------------------------------------------------------------- /docker/faketsdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anchnet/faketsdb/e757084308f85abc2fc47d0bc07ae70da342702d/docker/faketsdb -------------------------------------------------------------------------------- /influxdb.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/influxdata/influxdb/client/v2" 7 | ) 8 | 9 | var influxDBChan = make(chan *client.Point, 10) 10 | var influxRevciver *InfluxDBReciver 11 | 12 | type InfluxDBReciver struct { 13 | address string 14 | cache int 15 | } 16 | 17 | func NewInfluxDBReciver(addr string, cache int) *InfluxDBReciver { 18 | return &InfluxDBReciver{address: addr, cache: cache} 19 | } 20 | 21 | func (r *InfluxDBReciver) AddBatchPoint(ps []*client.Point) error { 22 | bp, err := client.NewBatchPoints(client.BatchPointsConfig{ 23 | Database: influxDatabase, 24 | }) 25 | if err != nil { 26 | log.Fatal(err) 27 | } 28 | bp.AddPoints(ps) 29 | 30 | client, err := client.NewHTTPClient(client.HTTPConfig{ 31 | Addr: r.address, 32 | }) 33 | if err != nil { 34 | log.Fatalf("Faile to NewHTTPClient: %s", err.Error()) 35 | } 36 | defer client.Close() 37 | 38 | return client.Write(bp) 39 | } 40 | 41 | func (r *InfluxDBReciver) ListenTask() { 42 | go func() { 43 | var ( 44 | n = 0 45 | points = make([]*client.Point, r.cache) 46 | ) 47 | for { 48 | points[n] = <-influxDBChan 49 | if n == r.cache-1 { 50 | if err := influxRevciver.AddBatchPoint(points); err != nil { 51 | log.Printf("Failed AddBatchPoint: %s", err.Error()) 52 | } 53 | n = 0 54 | continue 55 | } 56 | n++ 57 | } 58 | }() 59 | } 60 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "os" 7 | "strings" 8 | ) 9 | 10 | var ( 11 | // FakeTSDB listen port 12 | port = 8089 13 | 14 | // Forward to influxDB http api 15 | influxAddress = "http://127.0.0.1:8086" 16 | 17 | cache = 3 18 | 19 | influxDatabase = "test" 20 | 21 | debug = false 22 | ) 23 | 24 | func init() { 25 | flag.IntVar(&port, "port", port, "Fake proxy listen port.") 26 | flag.IntVar(&cache, "cache", cache, "Number of batch items send to influx.") 27 | flag.StringVar(&influxAddress, "influxAddr", influxAddress, "InfluxDB HTTP API address.") 28 | flag.StringVar(&influxDatabase, "influxDatabase", influxDatabase, "InfluxDB Database.") 29 | flag.BoolVar(&debug, "debug", debug, "Enable debug mode.") 30 | flag.Parse() 31 | 32 | if !strings.HasPrefix(influxAddress, "http://") && !strings.HasPrefix(influxAddress, "https://") { 33 | fmt.Println("ERROR: influxAddress must contain a prefix http[s]://") 34 | os.Exit(1) 35 | } 36 | 37 | influxRevciver = NewInfluxDBReciver(influxAddress, cache) 38 | influxRevciver.ListenTask() 39 | } 40 | 41 | func main() { 42 | NewTSDBServer(fmt.Sprintf("0.0.0.0:%d", port), influxAddress).TcpServer.Listen() 43 | } 44 | -------------------------------------------------------------------------------- /semaphore.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type Semaphore struct { 4 | bufSize int 5 | channel chan int8 6 | } 7 | 8 | func NewSemaphore(concurrencyNum int) *Semaphore { 9 | return &Semaphore{channel: make(chan int8, concurrencyNum), bufSize: concurrencyNum} 10 | } 11 | 12 | func (this *Semaphore) TryAcquire() bool { 13 | select { 14 | case this.channel <- int8(0): 15 | return true 16 | default: 17 | return false 18 | } 19 | } 20 | 21 | func (this *Semaphore) Acquire() { 22 | this.channel <- int8(0) 23 | } 24 | 25 | func (this *Semaphore) Release() { 26 | <-this.channel 27 | } 28 | 29 | func (this *Semaphore) AvailablePermits() int { 30 | return this.bufSize - len(this.channel) 31 | } 32 | -------------------------------------------------------------------------------- /tcp_server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "log" 6 | "net" 7 | ) 8 | 9 | // Client holds info about connection 10 | type Client struct { 11 | conn net.Conn 12 | Server *server 13 | } 14 | 15 | // TCP server 16 | type server struct { 17 | address string // Address to open connection: localhost:9999 18 | onNewClientCallback func(c *Client) 19 | onClientConnectionClosed func(c *Client, err error) 20 | onNewMessage func(c *Client, message string) 21 | } 22 | 23 | // Read client data from channel 24 | func (c *Client) listen() { 25 | reader := bufio.NewReader(c.conn) 26 | for { 27 | message, err := reader.ReadString('\n') 28 | if err != nil { 29 | c.conn.Close() 30 | c.Server.onClientConnectionClosed(c, err) 31 | return 32 | } 33 | c.Server.onNewMessage(c, message) 34 | } 35 | } 36 | 37 | // Send text message to client 38 | func (c *Client) Send(message string) error { 39 | _, err := c.conn.Write([]byte(message)) 40 | return err 41 | } 42 | 43 | // Send bytes to client 44 | func (c *Client) SendBytes(b []byte) error { 45 | _, err := c.conn.Write(b) 46 | return err 47 | } 48 | 49 | func (c *Client) Conn() net.Conn { 50 | return c.conn 51 | } 52 | 53 | func (c *Client) Close() error { 54 | return c.conn.Close() 55 | } 56 | 57 | // Called right after server starts listening new client 58 | func (s *server) OnNewClient(callback func(c *Client)) { 59 | s.onNewClientCallback = callback 60 | } 61 | 62 | // Called right after connection closed 63 | func (s *server) OnClientConnectionClosed(callback func(c *Client, err error)) { 64 | s.onClientConnectionClosed = callback 65 | } 66 | 67 | // Called when Client receives new message 68 | func (s *server) OnNewMessage(callback func(c *Client, message string)) { 69 | s.onNewMessage = callback 70 | } 71 | 72 | // Start network server 73 | func (s *server) Listen() { 74 | listener, err := net.Listen("tcp", s.address) 75 | if err != nil { 76 | log.Fatal("Error starting TCP server.") 77 | } 78 | defer listener.Close() 79 | 80 | for { 81 | conn, _ := listener.Accept() 82 | client := &Client{ 83 | conn: conn, 84 | Server: s, 85 | } 86 | go client.listen() 87 | s.onNewClientCallback(client) 88 | } 89 | } 90 | 91 | // Creates new tcp server instance 92 | func NewTCPServer(address string) *server { 93 | log.Println("Creating TCP server with address", address) 94 | server := &server{ 95 | address: address, 96 | } 97 | 98 | server.OnNewClient(func(c *Client) {}) 99 | server.OnNewMessage(func(c *Client, message string) {}) 100 | server.OnClientConnectionClosed(func(c *Client, err error) {}) 101 | 102 | return server 103 | } 104 | -------------------------------------------------------------------------------- /tsdb_server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "log" 7 | "strconv" 8 | "strings" 9 | "time" 10 | 11 | "github.com/influxdata/influxdb/client/v2" 12 | ) 13 | 14 | type TsdbItem struct { 15 | Metric string `json:"metric"` 16 | Tags map[string]string `json:"tags"` 17 | Value float64 `json:"value"` 18 | Timestamp int64 `json:"timestamp"` 19 | } 20 | 21 | func (this *TsdbItem) String() string { 22 | return fmt.Sprintf( 23 | "", 24 | this.Metric, 25 | this.Tags, 26 | this.Value, 27 | this.Timestamp, 28 | ) 29 | } 30 | 31 | func (this *TsdbItem) TsdbString() (s string) { 32 | s = fmt.Sprintf("put %s %d %.3f ", this.Metric, this.Timestamp, this.Value) 33 | 34 | for k, v := range this.Tags { 35 | key := strings.ToLower(strings.Replace(k, " ", "_", -1)) 36 | value := strings.Replace(v, " ", "_", -1) 37 | s += key + "=" + value + " " 38 | } 39 | 40 | return s 41 | } 42 | 43 | var ErrInvalidProtocol = errors.New("Invalid protocol") 44 | 45 | func ParseTSDBItem(str string) (*TsdbItem, error) { 46 | segments := strings.Split(str, " ") 47 | if len(segments) < 5 { 48 | return nil, errors.New("Invalid protocol: number of segments less than 5.") 49 | } 50 | 51 | if operate := strings.ToLower(segments[0]); operate != "put" { 52 | return nil, errors.New("Invalid protocol: only suppurt \"put\" operate, " + operate + " given.") 53 | } 54 | 55 | item := &TsdbItem{ 56 | Metric: segments[1], 57 | } 58 | 59 | var err error 60 | item.Timestamp, err = strconv.ParseInt(segments[2], 10, 64) 61 | if err != nil { 62 | return nil, errors.New("Invalid protocol: failed to parse timestamp [" + segments[2] + "], " + err.Error()) 63 | } 64 | 65 | item.Value, err = strconv.ParseFloat(segments[3], 64) 66 | if err != nil { 67 | return nil, errors.New("Invalid protocol: failed to parse value [" + segments[3] + "], " + err.Error()) 68 | } 69 | 70 | item.Tags = make(map[string]string) 71 | 72 | for i, pair := range segments { 73 | if i < 4 || len(pair) == 0 { 74 | // Skip top 4 elements and last one 75 | continue 76 | } 77 | 78 | tmp := strings.Split(pair, "=") 79 | if len(tmp) != 2 { 80 | continue 81 | } 82 | item.Tags[tmp[0]] = tmp[1] 83 | } 84 | 85 | return item, nil 86 | } 87 | 88 | type TSDBServer struct { 89 | TcpServer *server 90 | } 91 | 92 | func NewTSDBServer(address, influxAddr string) *TSDBServer { 93 | tsdbServer := &TSDBServer{} 94 | 95 | tcpServ := NewTCPServer(address) 96 | tcpServ.OnNewClient(tsdbServer.OnConnected) 97 | tcpServ.OnNewMessage(tsdbServer.OnMessage) 98 | tsdbServer.TcpServer = tcpServ 99 | 100 | return tsdbServer 101 | } 102 | 103 | func (s *TSDBServer) OnConnected(c *Client) { 104 | //c.Send("Hello\n") 105 | } 106 | 107 | var sema = NewSemaphore(2000) 108 | 109 | func (s *TSDBServer) OnMessage(c *Client, message string) { 110 | 111 | sema.Acquire() 112 | go func(message string) { 113 | defer sema.Release() 114 | 115 | item, err := ParseTSDBItem(message) 116 | if err != nil { 117 | log.Printf("ERROR: %s", err.Error()) 118 | return 119 | } 120 | 121 | if debug { 122 | log.Printf("Message: %s\n", item) 123 | } 124 | 125 | fields := map[string]interface{}{"value": item.Value} 126 | t := time.Unix(item.Timestamp, 0) 127 | 128 | point, err := client.NewPoint(item.Metric, item.Tags, fields, t) 129 | if err != nil { 130 | log.Printf("ERROR: failed to NewPoint %s\n", err.Error()) 131 | return 132 | } 133 | influxDBChan <- point 134 | }(message) 135 | 136 | } 137 | -------------------------------------------------------------------------------- /tsdb_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "math/rand" 6 | "net" 7 | "testing" 8 | ) 9 | 10 | func TestParseTSDBItem(t *testing.T) { 11 | item := &TsdbItem{ 12 | Metric: "sys.cpu.nice", 13 | Tags: map[string]string{ 14 | "host": "web01", 15 | "host2": "web02", 16 | }, 17 | Value: 42.5, 18 | Timestamp: 1365465600, 19 | } 20 | 21 | bufferStr := item.TsdbString() 22 | 23 | t.Log(bufferStr) 24 | 25 | if item, err := ParseTSDBItem(bufferStr); err != nil { 26 | t.Error(err) 27 | } else { 28 | t.Logf("%+v", item) 29 | } 30 | } 31 | 32 | func BenchmarkPutMessage(b *testing.B) { 33 | 34 | conn, err := net.Dial("tcp", "127.0.0.1:8089") 35 | if err != nil { 36 | b.Fatal(err) 37 | } 38 | 39 | defer conn.Close() 40 | 41 | item := &TsdbItem{ 42 | Metric: "sys.cpu.nice", 43 | Tags: map[string]string{ 44 | "host": "web01", 45 | "host2": "web02", 46 | }, 47 | Value: 42.5, 48 | Timestamp: 1365465600, 49 | } 50 | 51 | for i := 0; i < b.N; i++ { 52 | item.Timestamp = item.Timestamp + int64(i) 53 | item.Value = rand.Float64() 54 | 55 | var tsdbBuffer bytes.Buffer 56 | tsdbBuffer.WriteString(item.TsdbString()) 57 | tsdbBuffer.WriteString("\n") 58 | 59 | conn.Write(tsdbBuffer.Bytes()) 60 | } 61 | 62 | } 63 | --------------------------------------------------------------------------------