| 1 |
# Copyright DataStax, Inc. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
from collections import Counter |
| 16 |
import datetime |
| 17 |
import json |
| 18 |
import logging |
| 19 |
import multiprocessing |
| 20 |
import random |
| 21 |
import platform |
| 22 |
import socket |
| 23 |
import ssl |
| 24 |
import sys |
| 25 |
from threading import Event, Thread |
| 26 |
import time |
| 27 |
|
| 28 |
from cassandra.policies import HostDistance |
| 29 |
from cassandra.util import ms_timestamp_from_datetime |
| 30 |
from cassandra.datastax.insights.registry import insights_registry |
| 31 |
from cassandra.datastax.insights.serializers import initialize_registry |
| 32 |
|
| 33 |
log = logging.getLogger(__name__) |
| 34 |
|
| 35 |
|
| 36 |
class MonitorReporter(Thread): |
| 37 |
|
| 38 |
def __init__(self, interval_sec, session): |
| 39 |
""" |
| 40 |
takes an int indicating interval between requests, a function returning |
| 41 |
the connection to be used, and the timeout per request |
| 42 |
""" |
| 43 |
# Thread is an old-style class so we can't super() |
| 44 |
Thread.__init__(self, name='monitor_reporter') |
| 45 |
|
| 46 |
initialize_registry(insights_registry) |
| 47 |
|
| 48 |
self._interval, self._session = interval_sec, session |
| 49 |
|
| 50 |
self._shutdown_event = Event() |
| 51 |
self.daemon = True |
| 52 |
self.start() |
| 53 |
|
| 54 |
def run(self): |
| 55 |
self._send_via_rpc(self._get_startup_data()) |
| 56 |
|
| 57 |
# introduce some jitter -- send up to 1/10 of _interval early |
| 58 |
self._shutdown_event.wait(self._interval * random.uniform(.9, 1)) |
| 59 |
|
| 60 |
while not self._shutdown_event.is_set(): |
| 61 |
start_time = time.time() |
| 62 |
|
| 63 |
self._send_via_rpc(self._get_status_data()) |
| 64 |
|
| 65 |
elapsed = time.time() - start_time |
| 66 |
self._shutdown_event.wait(max(self._interval - elapsed, 0.01)) |
| 67 |
|
| 68 |
# TODO: redundant with ConnectionHeartbeat.ShutdownException |
| 69 |
class ShutDownException(Exception): |
| 70 |
pass |
| 71 |
|
| 72 |
def _send_via_rpc(self, data): |
| 73 |
try: |
| 74 |
self._session.execute( |
| 75 |
"CALL InsightsRpc.reportInsight(%s)", (json.dumps(data),) |
| 76 |
) |
| 77 |
log.debug('Insights RPC data: {}'.format(data)) |
| 78 |
except Exception as e: |
| 79 |
log.debug('Insights RPC send failed with {}'.format(e)) |
| 80 |
log.debug('Insights RPC data: {}'.format(data)) |
| 81 |
|
| 82 |
def _get_status_data(self): |
| 83 |
cc = self._session.cluster.control_connection |
| 84 |
|
| 85 |
connected_nodes = { |
| 86 |
host.address: { |
| 87 |
'connections': state['open_count'], |
| 88 |
'inFlightQueries': state['in_flights'] |
| 89 |
} |
| 90 |
for (host, state) in self._session.get_pool_state().items() |
| 91 |
} |
| 92 |
|
| 93 |
return { |
| 94 |
'metadata': { |
| 95 |
# shared across drivers; never change |
| 96 |
'name': 'driver.status', |
| 97 |
# format version |
| 98 |
'insightMappingId': 'v1', |
| 99 |
'insightType': 'EVENT', |
| 100 |
# since epoch |
| 101 |
'timestamp': ms_timestamp_from_datetime(datetime.datetime.utcnow()), |
| 102 |
'tags': { |
| 103 |
'language': 'python' |
| 104 |
} |
| 105 |
}, |
| 106 |
# // 'clientId', 'sessionId' and 'controlConnection' are mandatory |
| 107 |
# // the rest of the properties are optional |
| 108 |
'data': { |
| 109 |
# // 'clientId' must be the same as the one provided in the startup message |
| 110 |
'clientId': str(self._session.cluster.client_id), |
| 111 |
# // 'sessionId' must be the same as the one provided in the startup message |
| 112 |
'sessionId': str(self._session.session_id), |
| 113 |
'controlConnection': cc._connection.host if cc._connection else None, |
| 114 |
'connectedNodes': connected_nodes |
| 115 |
} |
| 116 |
} |
| 117 |
|
| 118 |
def _get_startup_data(self): |
| 119 |
cc = self._session.cluster.control_connection |
| 120 |
try: |
| 121 |
local_ipaddr = cc._connection._socket.getsockname()[0] |
| 122 |
except Exception as e: |
| 123 |
local_ipaddr = None |
| 124 |
log.debug('Unable to get local socket addr from {}: {}'.format(cc._connection, e)) |
| 125 |
hostname = socket.getfqdn() |
| 126 |
|
| 127 |
host_distances_counter = Counter( |
| 128 |
self._session.cluster.profile_manager.distance(host) |
| 129 |
for host in self._session.hosts |
| 130 |
) |
| 131 |
host_distances_dict = { |
| 132 |
'local': host_distances_counter[HostDistance.LOCAL], |
| 133 |
'remote': host_distances_counter[HostDistance.REMOTE], |
| 134 |
'ignored': host_distances_counter[HostDistance.IGNORED] |
| 135 |
} |
| 136 |
|
| 137 |
try: |
| 138 |
compression_type = cc._connection._compression_type |
| 139 |
except AttributeError: |
| 140 |
compression_type = 'NONE' |
| 141 |
|
| 142 |
cert_validation = None |
| 143 |
try: |
| 144 |
if self._session.cluster.ssl_context: |
| 145 |
if isinstance(self._session.cluster.ssl_context, ssl.SSLContext): |
| 146 |
cert_validation = self._session.cluster.ssl_context.verify_mode == ssl.CERT_REQUIRED |
| 147 |
else: # pyopenssl |
| 148 |
from OpenSSL import SSL |
| 149 |
cert_validation = self._session.cluster.ssl_context.get_verify_mode() != SSL.VERIFY_NONE |
| 150 |
elif self._session.cluster.ssl_options: |
| 151 |
cert_validation = self._session.cluster.ssl_options.get('cert_reqs') == ssl.CERT_REQUIRED |
| 152 |
except Exception as e: |
| 153 |
log.debug('Unable to get the cert validation: {}'.format(e)) |
| 154 |
|
| 155 |
uname_info = platform.uname() |
| 156 |
|
| 157 |
return { |
| 158 |
'metadata': { |
| 159 |
'name': 'driver.startup', |
| 160 |
'insightMappingId': 'v1', |
| 161 |
'insightType': 'EVENT', |
| 162 |
'timestamp': ms_timestamp_from_datetime(datetime.datetime.utcnow()), |
| 163 |
'tags': { |
| 164 |
'language': 'python' |
| 165 |
}, |
| 166 |
}, |
| 167 |
'data': { |
| 168 |
'driverName': 'DataStax Python Driver', |
| 169 |
'driverVersion': sys.modules['cassandra'].__version__, |
| 170 |
'clientId': str(self._session.cluster.client_id), |
| 171 |
'sessionId': str(self._session.session_id), |
| 172 |
'applicationName': self._session.cluster.application_name or 'python', |
| 173 |
'applicationNameWasGenerated': not self._session.cluster.application_name, |
| 174 |
'applicationVersion': self._session.cluster.application_version, |
| 175 |
'contactPoints': self._session.cluster._endpoint_map_for_insights, |
| 176 |
'dataCenters': list(set(h.datacenter for h in self._session.cluster.metadata.all_hosts() |
| 177 |
if (h.datacenter and |
| 178 |
self._session.cluster.profile_manager.distance(h) == HostDistance.LOCAL))), |
| 179 |
'initialControlConnection': cc._connection.host if cc._connection else None, |
| 180 |
'protocolVersion': self._session.cluster.protocol_version, |
| 181 |
'localAddress': local_ipaddr, |
| 182 |
'hostName': hostname, |
| 183 |
'executionProfiles': insights_registry.serialize(self._session.cluster.profile_manager), |
| 184 |
'configuredConnectionLength': host_distances_dict, |
| 185 |
'heartbeatInterval': self._session.cluster.idle_heartbeat_interval, |
| 186 |
'compression': compression_type.upper() if compression_type else 'NONE', |
| 187 |
'reconnectionPolicy': insights_registry.serialize(self._session.cluster.reconnection_policy), |
| 188 |
'sslConfigured': { |
| 189 |
'enabled': bool(self._session.cluster.ssl_options or self._session.cluster.ssl_context), |
| 190 |
'certValidation': cert_validation |
| 191 |
}, |
| 192 |
'authProvider': { |
| 193 |
'type': (self._session.cluster.auth_provider.__class__.__name__ |
| 194 |
if self._session.cluster.auth_provider else |
| 195 |
None) |
| 196 |
}, |
| 197 |
'otherOptions': { |
| 198 |
}, |
| 199 |
'platformInfo': { |
| 200 |
'os': { |
| 201 |
'name': uname_info.system, |
| 202 |
'version': uname_info.release, |
| 203 |
'arch': uname_info.machine |
| 204 |
}, |
| 205 |
'cpus': { |
| 206 |
'length': multiprocessing.cpu_count(), |
| 207 |
'model': platform.processor() |
| 208 |
}, |
| 209 |
'runtime': { |
| 210 |
'python': sys.version, |
| 211 |
'event_loop': self._session.cluster.connection_class.__name__ |
| 212 |
} |
| 213 |
}, |
| 214 |
'periodicStatusInterval': self._interval |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
def stop(self): |
| 219 |
log.debug("Shutting down Monitor Reporter") |
| 220 |
self._shutdown_event.set() |
| 221 |
self.join() |