forked from draios/sysdig-kube-watcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kubewatcher.py
84 lines (69 loc) · 2.26 KB
/
kubewatcher.py
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
import os
import requests
import json
import sys
import time
import traceback
from sdcclient import SdcClient
from kube_obj_parser import KubeObjParser, KubeURLParser, Logger
def log(str, severity='info'):
Logger.log(str, severity)
sys.stdout.flush()
log("Kubewatcher Starting")
DEFAULT_SDC_URL = 'https://app.sysdigcloud.com'
SDC_URL = os.getenv('SDC_URL')
if not SDC_URL:
log('No SDC_URL specified. Defaulting to ' + DEFAULT_SDC_URL + '.', 'info')
os.environ['SDC_URL'] = DEFAULT_SDC_URL
SDC_ADMIN_TOKEN = os.getenv('SDC_ADMIN_TOKEN')
if not SDC_ADMIN_TOKEN:
log('Did not find API Token for an Admin user at env variable "SDC_ADMIN_TOKEN". Exiting.', 'error')
sys.exit(1)
DEFAULT_TEAM_PREFIX = ''
team_prefix = os.getenv('TEAM_PREFIX', DEFAULT_TEAM_PREFIX)
KUBE_URL = os.getenv('KUBE_URL')
if not KUBE_URL:
log('Did not find Kubernetes API server URL at env variable "KUBE_URL". Will attempt to autodiscover.', 'info')
#
# Instantiate the customer admin SDC client
#
log('SDC_URL = ' + SDC_URL, 'info')
ca_sdclient = SdcClient(SDC_ADMIN_TOKEN, SDC_URL)
res = ca_sdclient.get_user_info()
if res[0] == False:
Logger.log('Can\'t retrieve info for Sysdig Cloud Admin user: ' + res[1] + '. Exiting.', 'error')
sys.exit(1)
customer_id = res[1]['user']['username']
#
# Allocate the parsers.
# Note: the parsers keep state, so we allocate them during startup and then we
# use them in the main loop
#
urlparser_ns = KubeURLParser('namespace', ca_sdclient, customer_id, SDC_URL, team_prefix)
urlparser_depl = KubeURLParser('deployment', ca_sdclient, customer_id, SDC_URL, team_prefix)
urlparser_srvc = KubeURLParser('service', ca_sdclient, customer_id, SDC_URL, team_prefix)
#
# MAIN LOOP
#
while True:
log("Reading the Kubernetes API")
try:
#
# Parse the namespaces
#
urlparser_ns.parse(KUBE_URL, '/api/v1/namespaces')
#
# Parse the deployments
#
urlparser_depl.parse(KUBE_URL, '/apis/extensions/v1beta1/deployments')
#
# Parse the services
#
urlparser_srvc.parse(KUBE_URL, '/api/v1/services')
except:
log(sys.exc_info()[1], 'error')
traceback.print_exc()
#
# Sleep a bit before checking again for changes
#
time.sleep(2)