summaryrefslogtreecommitdiffstats
path: root/clover/collector/db/cassops.py
blob: 6553cffdd5ec1849b29e6dcabd7bc0f529e531ea (plain)
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
# Copyright (c) Authors of Clover
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0

from cassandra.cluster import Cluster
from cassandra.query import BatchStatement
import logging

CASSANDRA_HOSTS = ['cassandra.default']


class CassandraOps:

    def __init__(self, hosts, port=9042, keyspace='visibility'):
        logging.basicConfig(filename='cassops.log',
                            level=logging.DEBUG)
        cluster = Cluster(hosts, port=port)
        self.session = cluster.connect()
        self.keyspace = keyspace

    def truncate(self, tables=['traces', 'metrics', 'spans']):
        self.session.set_keyspace(self.keyspace)
        try:
            for table in tables:
                self.session.execute("""
                        TRUNCATE %s
                        """ % table)
        except Exception as e:
            logging.debug(e)

    def init_visibility(self):
        try:
            self.session.execute("""
                    CREATE KEYSPACE %s
                    WITH replication = { 'class': 'SimpleStrategy',
                    'replication_factor': '1' }
                    """ % self.keyspace)
        except Exception as e:
            logging.debug(e)

        self.session.set_keyspace(self.keyspace)

        try:
            self.session.execute("""
                    CREATE TABLE IF NOT EXISTS traces (
                        traceid text,
                        processes list<text>,
                        PRIMARY KEY (traceid)
                    )
                    """)

            self.session.execute("""
                    CREATE TABLE IF NOT EXISTS spans (
                        spanid text,
                        traceid text,
                        duration int,
                        start_time int,
                        processid text,
                        operation_name text,
                        node_id text,
                        http_url text,
                        upstream_cluster text,
                        PRIMARY KEY (spanid, traceid)
                    )
                    """)

            self.session.execute("""
                    CREATE TABLE IF NOT EXISTS metrics (
                        m_name text,
                        m_value text,
                        m_time text,
                        service text,
                        monitor_time timestamp,
                        PRIMARY KEY (m_name, monitor_time)
                    )
                    """)
        except Exception as e:
            logging.debug(e)

    def set_prepared(self):
        self.session.set_keyspace(self.keyspace)
        self.insert_tracing_stmt = self.session.prepare(
            """
            INSERT INTO spans (spanid, traceid, duration, operation_name,
            node_id, http_url, upstream_cluster)
            VALUES (?, ?, ?, ?, ?, ?, ?)
            """
        )
        self.insert_metric_stmt = self.session.prepare(
            """
            INSERT INTO metrics
            (m_name, m_value, m_time, service, monitor_time)
            VALUES (?, ?, ?, ?, toTimestamp(now()))
            """
        )

    def set_batch(self):
        self.batch = BatchStatement()

    def execute_batch(self):
        self.session.execute(self.batch)

    def insert_tracing(self, table, traceid, s, tags):
        self.session.set_keyspace(self.keyspace)
        if 'upstream_cluster' not in tags:
            logging.debug('NO UPSTREAM_CLUSTER KEY')
            tags['upstream_cluster'] = 'none'
        try:
            self.batch.add(self.insert_tracing_stmt,
                           (s['spanID'], traceid, s['duration'],
                            s['operationName'], tags['node_id'],
                            tags['http.url'], tags['upstream_cluster']))
        except Exception as e:
            logging.debug('{} {} {} {} {} {} {}'.format(s['spanID'], traceid,
                          s['duration'], s['operationName'], tags['node_id'],
                          tags['http.url'], tags['upstream_cluster']))
            logging.debug(e)

    def insert_trace(self, traceid, processes):
        self.session.set_keyspace(self.keyspace)
        self.session.execute(
            """
            INSERT INTO traces (traceid, processes)
            VALUES (%s, %s)
            """,
            (traceid,  processes)
        )

    def insert_metric(self, m_name, m_value, m_time, service):
        self.session.set_keyspace(self.keyspace)
        self.batch.add(self.insert_metric_stmt,
                       (m_name, m_value, m_time, service))


def main():
    cass = CassandraOps(CASSANDRA_HOSTS)
    cass.init_visibility()


if __name__ == '__main__':
    main()