This repository has been archived by the owner on Nov 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
hana.go
245 lines (205 loc) · 6.43 KB
/
hana.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
/*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package hana
import (
"bytes"
"database/sql"
"encoding/gob"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
log "github.com/sirupsen/logrus"
"github.com/SAP/go-hdb/driver"
"github.com/intelsdi-x/snap/control/plugin"
"github.com/intelsdi-x/snap/control/plugin/cpolicy"
"github.com/intelsdi-x/snap/core"
"github.com/intelsdi-x/snap/core/ctypes"
)
const (
name = "hana"
version = 6
pluginType = plugin.PublisherPluginType
)
type HANAPublisher struct {
}
func NewHANAPublisher() *HANAPublisher {
return &HANAPublisher{}
}
// Publish sends data to a HANA server
func (s *HANAPublisher) Publish(contentType string, content []byte, config map[string]ctypes.ConfigValue) error {
logger := log.New()
logger.Println("Publishing started")
var metrics []plugin.MetricType
switch contentType {
case plugin.SnapGOBContentType:
dec := gob.NewDecoder(bytes.NewBuffer(content))
if err := dec.Decode(&metrics); err != nil {
logger.Printf("Error decoding: error=%v content=%v", err, content)
return err
}
default:
logger.Printf("Error unknown content type '%v'", contentType)
return errors.New(fmt.Sprintf("Unknown content type '%s'", contentType))
}
logger.Printf("publishing %v to %v", metrics, config)
// Open connection and ping to make sure it works
username := config["username"].(ctypes.ConfigValueStr).Value
password := config["password"].(ctypes.ConfigValueStr).Value
host := config["host"].(ctypes.ConfigValueStr).Value
database := config["database"].(ctypes.ConfigValueStr).Value
port := config["port"].(ctypes.ConfigValueStr).Value
tableName := config["tablename"].(ctypes.ConfigValueStr).Value
tableColumns := "(timestamp VARCHAR(200), source VARCHAR(200), key VARCHAR(200), value VARCHAR(200))"
db, err := sql.Open(driver.DriverName, "hdb://"+username+":"+password+"@"+host+":"+port+"/"+database)
defer db.Close()
if err != nil {
logger.Printf("Error: %v", err)
return err
}
err = db.Ping()
if err != nil {
logger.Printf("Error: %v", err)
return err
}
// Create the table if it's not already there
_, err = db.Exec("DROP PROCEDURE ifexists")
if err != nil {
logger.Printf("Error while dropping procedure: %v", err)
}
createTableStr :=
"CREATE PROCEDURE ifexists( ) LANGUAGE SQLSCRIPT AS myrowid integer;\n" +
"BEGIN\n" +
" myrowid := 0;\n" +
" SELECT COUNT(*) INTO myrowid FROM \"PUBLIC\".\"M_TABLES\" " +
" WHERE schema_name = '" + database + "' AND table_name = '" + tableName + "';\n" +
" IF :myrowid = 0 THEN\n" +
" exec 'CREATE COLUMN TABLE \"" + database + "\".\"" + tableName + "\" " + tableColumns + "';\n " +
" END IF;\n" +
"END;"
_, err = db.Exec(createTableStr)
if err != nil {
logger.Printf("Error while creating procedure: %v", err)
logger.Printf("Query: %v", createTableStr)
}
_, err = db.Exec("CALL ifexists")
if err != nil {
logger.Printf("Error while invoking procedure: %v", err)
return err
}
// Put the values into the database with the current time
tableValues := "VALUES( ?, ?, ?, ? )"
insert, err := db.Prepare("INSERT INTO " + database + "." + tableName + " " + tableValues)
if err != nil {
logger.Printf("Error: %v", err)
logger.Printf("tablename: " + database + "." + tableName + ", tableValues: " + tableValues)
return err
}
var key, value string
for _, m := range metrics {
key = sliceToString(m.Namespace().Strings())
value, err = interfaceToString(m.Data())
if err != nil {
logger.Printf("Error: %v", err)
return err
}
_, err = insert.Exec(m.Timestamp(), m.Tags()[core.STD_TAG_PLUGIN_RUNNING_ON], key, value)
if err != nil {
logger.Printf("Error: %v", err)
return err
}
}
return nil
}
func Meta() *plugin.PluginMeta {
return plugin.NewPluginMeta(name, version, pluginType, []string{plugin.SnapGOBContentType}, []string{plugin.SnapGOBContentType})
}
func (f *HANAPublisher) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) {
cp := cpolicy.New()
config := cpolicy.NewPolicyNode()
host, err := cpolicy.NewStringRule("host", true, "root")
handleErr(err)
host.Description = "HANA host to which we will connect"
port, err := cpolicy.NewStringRule("port", true, "30017")
handleErr(err)
port.Description = "HANA port to which we will connect"
username, err := cpolicy.NewStringRule("username", true, "root")
handleErr(err)
username.Description = "Username to login to the HANA server"
password, err := cpolicy.NewStringRule("password", true, "root")
handleErr(err)
password.Description = "Password to login to the HANA server"
database, err := cpolicy.NewStringRule("database", true, "SNAP_TEST")
handleErr(err)
database.Description = "The HANA database that data will be pushed to"
tableName, err := cpolicy.NewStringRule("tablename", true, "info")
handleErr(err)
tableName.Description = "The HANA table within the database where information will be stored"
config.Add(
host,
username,
password,
database,
port,
tableName,
)
cp.Add([]string{""}, config)
return cp, nil
}
func handleErr(e error) {
if e != nil {
panic(e)
}
}
func sliceToString(slice []string) string {
return strings.Join(slice, ", ")
}
// Supported types: []string, []int, int, uint64, float32, float64, string
func interfaceToString(face interface{}) (string, error) {
var (
ret string
err error
)
switch val := face.(type) {
case []string:
ret = sliceToString(val)
case []int:
length := len(val)
if length == 0 {
return ret, err
}
ret = strconv.Itoa(val[0])
if length == 1 {
return ret, err
}
for i := 1; i < length; i++ {
ret += ", "
ret += strconv.Itoa(val[i])
}
case int:
ret = strconv.Itoa(val)
case uint64:
ret = strconv.FormatUint(val, 10)
case float32:
ret = strconv.FormatFloat(float64(val), 'E', -1, 32)
case float64:
ret = strconv.FormatFloat(val, 'E', -1, 64)
case string:
ret = val
default:
err = errors.New("Unsupported type: " + reflect.TypeOf(face).String())
}
return ret, err
}