sensordatastore.cpp 7.57 KB
Newer Older
1
2
3
4
5
6
7
8
/*
 * sensordatastore.cpp
 *
 *  Created on: Jul 24, 2013
 *      Author: Axel Auweter
 */

#include <boost/lexical_cast.hpp>
9
#include <dcdbendian.h>
10
11
12
13
14
15

#include "sensordatastore_internal.h"

string SensorDataStoreImpl::sidConvert(SensorId *sid)
{
    uint64_t ll[2];
16
17
    ll[0] = Endian::hostToBE(sid->raw[0]);
    ll[1] = Endian::hostToBE(sid->raw[1]);
18
19
20
21
22
    return string((char*)ll, 16);
}

string SensorDataStoreImpl::int64Convert(uint64_t n)
{
23
    n = Endian::hostToBE(n);
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
    return string((char*)&n, 8);
}

void SensorDataStoreImpl::connect(string hostname, int port)
{
    sock = boost::shared_ptr<TSocket>(new TSocket(hostname, port));
    tr = boost::shared_ptr<TFramedTransport>(new TFramedTransport(sock));
    prot = boost::shared_ptr<TBinaryProtocol>(new TBinaryProtocol(tr));
    
    myClient = new CassandraClient(prot);
    tr->open();
    
    myClient->describe_cluster_name(clusterName);
    cout << "Connected to cluster: " << clusterName << "\n";
}

void SensorDataStoreImpl::updateKeySpaces()
{
    myClient->describe_keyspaces(keySpaces);
}

bool SensorDataStoreImpl::existsKeyspace(string name)
{
    updateKeySpaces();
    for (std::vector<KsDef>::iterator it = keySpaces.begin(); it != keySpaces.end(); ++it) {
        if ((*it).name.compare(name) == 0)
            return true;
    }
    return false;
}

/*
 * Create the keyspace that contains all the sensor data.
 * We are using CQL3 to do this as its syntax is less likely
 * to change in future versions than the native API.
 */
void SensorDataStoreImpl::createKeyspace(string name, int replicationFactor)
{
    CqlResult res;
    string query;
    string rFact = boost::lexical_cast<string>(replicationFactor);
    
    if(validateName(name)) {
        query = "CREATE KEYSPACE " + name + " WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '" + rFact + "' };";
        myClient->execute_cql3_query(res, query, Compression::NONE, ConsistencyLevel::ONE);
    }
}

void SensorDataStoreImpl::selectKeyspace(string name)
{
    CqlResult res;
    string query;
    
    if (validateName(name)) {
        query = "USE " + name + ";";
        myClient->execute_cql3_query(res, query, Compression::NONE, ConsistencyLevel::ONE);
        
        updateKeySpaces();
        for (std::vector<KsDef>::iterator it = keySpaces.begin(); it != keySpaces.end(); ++it) {
            if ((*it).name.compare(name) == 0)
                currentKeySpace = *it;
        }
    }
}

bool SensorDataStoreImpl::existsColumnFamilies()
{
    for (std::vector<CfDef>::iterator it = currentKeySpace.cf_defs.begin(); it != currentKeySpace.cf_defs.end(); ++it) {
        if ((*it).name.compare("sensordata") == 0)
            return true;
    }
    return false;
}

void SensorDataStoreImpl::createColumnFamilies()
{
    CqlResult res;
    string query;
    
    query = "CREATE TABLE sensordata ( sid blob, ts bigint, value bigint, PRIMARY KEY (sid, ts)) WITH COMPACT STORAGE;";
    myClient->execute_cql3_query(res, query, Compression::NONE, ConsistencyLevel::ONE);
}

bool SensorDataStoreImpl::validateName(string name)
{
    /*
     * Make sure name only consists of alphabetical characters (super ugly)...
     */
    class {
    public:
        static bool check(char c) {
            return !isalpha(c);
        }
    } isNotAlpha;
    
    if (find_if(name.begin(), name.end(), isNotAlpha.check) == name.end())
        return true;
    else
        return false;
}

void SensorDataStoreImpl::init(string hostname, int port) {
    
    /*
     * Open the connection to the Cassandra database and
     * create the necessary keyspace and column family.
     */
    try {
        connect(hostname, port);
        
        if (!existsKeyspace(KEYSPACE_NAME)) {
            cout << "Creating Keyspace " << KEYSPACE_NAME << "...\n";
            createKeyspace(KEYSPACE_NAME, 1);
        }
        
        selectKeyspace(KEYSPACE_NAME);
        
Axel Auweter's avatar
Axel Auweter committed
141
        if (!(currentKeySpace.name.compare(KEYSPACE_NAME) == 0)) {
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
            cout << "Cannot select keyspace " << KEYSPACE_NAME << "\n";
            exit(EXIT_FAILURE);
        }
        
        if (!existsColumnFamilies()) {
            cout << "Creating Column Families...\n";
            createColumnFamilies();
        }
    }
    catch(const TTransportException& te){
        cout << "TP Exception: " << te.what() << "[" << te.getType() << "]\n";
        exit(EXIT_FAILURE);
    }
    catch(const InvalidRequestException& ire){
        cout << "IRE Exception: " << ire.what() << "[" << ire.why << "]\n";
        exit(EXIT_FAILURE);
    }
    catch(const NotFoundException& nfe){
        cout << "NF Exception: " <<  nfe.what() << "\n";
        exit(EXIT_FAILURE);
    }
}

bool SensorDataStoreImpl::topicToSid(SensorId* sid, string topic)
{
    uint64_t pos = 0;
    const char* buf = topic.c_str();
    sid->raw[0] = 0;
    sid->raw[1] = 0;
    while (*buf) {
        if (*buf >= '0' && *buf <= '9') {
            sid->raw[pos / 64] |= (((uint64_t)(*buf - '0')) << (60-(pos%64)));
            pos += 4;
        }
        else if (*buf >= 'A' && *buf <= 'F') {
            sid->raw[pos / 64] |= (((uint64_t)(*buf - 'A' + 0xa)) << (60-(pos%64)));
            pos += 4;
        }
        else if (*buf >= 'a' && *buf <= 'f') {
            sid->raw[pos / 64] |= (((uint64_t)(*buf - 'a' + 0xa)) << (60-(pos%64)));
            pos += 4;
        }
        buf++;
    }
    return pos == 128;
}

void SensorDataStoreImpl::insert(SensorId* sid, uint64_t ts, uint64_t value)
{
    try {
        ColumnParent cparent;
        Column c;
        string key, name, cvalue;
        
        cparent.column_family = "sensordata";
        
        /*
         * Convert to Cassandra formats and assign
         * Cassandra-internal timestamp.
         */
        key = sidConvert(sid);
        name = int64Convert(ts);
        cvalue = int64Convert(value);
        
        c.name = name;
        c.value = cvalue;
        c.__isset.value = true;
        c.timestamp = ts/1000;
        c.__isset.timestamp = true;
        
        /*
         * Call Hector to do the insert.
         */
        myClient->insert(key, cparent, c, ConsistencyLevel::ONE);
    }
    /*
     * TODO: All caught exceptions should be handled more gracefully
     * as we would like to keep the CollectAgent running as long as
     * possible.
     */
    catch(const TTransportException& te){
        cout << "TP Exception: " << te.what() << "[" << te.getType() << "]\n";
        exit(EXIT_FAILURE);
    }
    catch(const InvalidRequestException& ire){
        cout << "IRE Exception: " << ire.what() << "[" << ire.why << "]\n";
        exit(EXIT_FAILURE);
    }
    catch(const NotFoundException& nfe){
        cout << "NF Exception: " <<  nfe.what() << "\n";
        exit(EXIT_FAILURE);
    }
}

SensorDataStoreImpl::SensorDataStoreImpl()
{
}

SensorDataStoreImpl::~SensorDataStoreImpl()
{
    /*
     * Clean up...
     */
    if (myClient)
        delete myClient;
}

void SensorDataStore::init(string hostname, int port)
{
    /* Allocate new SensorDataStoreImpl Object if necessary */
    if (!impl) {
        impl = new SensorDataStoreImpl();
    }
    
    /* Call impl's init function */
    impl->init(hostname, port);
}

bool SensorDataStore::topicToSid(SensorId* sid, std::string topic)
{
    return impl->topicToSid(sid, topic);
}

void SensorDataStore::insert(SensorId* sid, uint64_t ts, uint64_t value)
{
    impl->insert(sid, ts, value);
}

SensorDataStore::SensorDataStore()
{
    impl = nullptr;
    init("localhost", 9160);
}

SensorDataStore::SensorDataStore(string hostname, int port)
{
    impl = nullptr;
    init(hostname, port);
}

SensorDataStore::~SensorDataStore()
{
    /*
     * Clean up...
     */
    if (impl)
        delete impl;
}