-
Notifications
You must be signed in to change notification settings - Fork 42
/
etcd.py
executable file
·165 lines (141 loc) · 4.46 KB
/
etcd.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
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
import json
import logging
import pycurl
import re
import requests
import socket
import sys
import unittest
from StringIO import StringIO
class EtcdError(BaseException):
#Generic etcd error
pass
class Etcd(object):
def __init__(self, logger, server=None):
if server:
self.server = server
else:
self.server = socket.gethostname()
self.url = 'http://%(hostname)s:4001/v2/keys' % {
'hostname': self.server}
self.logger = logger
def set_key(self, key, value):
url = '%(base)s/%(key)s' % {
'base': self.url,
'key': key
}
data = 'value=%s' % value
self.logger.debug("Saving data: %(data)s to %(url)s" %{
'data': data,
'url': url
})
storage = StringIO()
curl = pycurl.Curl()
curl.setopt(curl.URL, url)
curl.setopt(curl.POSTFIELDS, data)
curl.setopt(pycurl.FOLLOWLOCATION, 1)
curl.setopt(pycurl.MAXREDIRS, 5)
curl.setopt(curl.WRITEFUNCTION, storage.write)
curl.setopt(pycurl.CUSTOMREQUEST, "PUT")
curl.perform()
response = curl.getinfo(pycurl.HTTP_CODE)
curl.close()
if response == requests.codes.ok:
return True
elif response == requests.codes.created:
return True
else:
self.logger.error("ETCD returned %(status)s %(text)s" % {
'status': response,
'text': storage.getvalue()})
return None
def get_key(self, key):
url = '%(base)s/%(key)s' % {
'base': self.url,
'key': key
}
self.logger.debug('Getting url: ' + url)
response = requests.get(url)
self.logger.debug('Response: ' + response.text)
res = json.loads(response.text)
if isinstance(res, list):
raise ValueError('Key "%s" is a directory, expecting leaf (use \
list_directory() to get directory listing).' % key)
#Check to see if Etcd returned an error
if 'errorCode' in res:
raise EtcdError(res['errorCode'], res['message'])
try:
return str(res['node']['value'])
except KeyError:
#Fallback on v1 functionality
return str(res['value'])
def delete_key(self, key):
url = '%(base)s/%(key)s' % {
'base': self.url,
'key': key
}
response = requests.delete(url)
if response.status_code == requests.codes.ok:
return response.text
else:
response.raise_for_status()
return None
def list_directory(self, path):
url = '%(base)s/%(path)s' % {
'base': self.url,
'path': path
}
response = requests.get(url)
if response.status_code == requests.codes.ok:
directory_list = []
json_txt = json.loads(response.text)
try:
for entry in json_txt['node']['nodes']:
directory_list.append(str(entry['key']))
return directory_list
except KeyError:
self.logger.error("Key ['node']['nodes'] not found in %(data)s" %{
'data': json_txt
})
else:
response.raise_for_status()
return None
def get_machines(self):
url = '%(base)s/_etcd/machines' % {
'base': self.url}
res = json.loads(requests.get(url).text)
#Check to see if Etcd returned an error
if 'errorCode' in res:
raise EtcdError(res['errorCode'], res['message'])
server_list = []
for entry in res:
server_list.append(str(entry['value']))
return server_list
class TestEtcd(unittest.TestCase):
def setUp(self):
logger = logging.getLogger()
stream = logging.StreamHandler(sys.stdout)
stream.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
stream.setFormatter(formatter)
logger.addHandler(stream)
self.etcd = Etcd(logger)
def test_a_setkey(self):
ret = self.etcd.set_key('message', 'Hello World')
self.assertTrue(ret)
def test_b_getkey(self):
self.etcd.set_key('message', 'Hello World')
text = self.etcd.get_key('message')
self.assertEqual(text, 'Hello World')
def test_c_deletekey(self):
#Set the key first before deleting it
self.etcd.set_key('message', 'Hello World')
text = self.etcd.delete_key('message')
regex = re.compile(r'{"action":"delete","node":{"key":"/message",'
'"modifiedIndex":\d+,"createdIndex":\d+},"prevNode":{"key":"/message"'
',"value":"Hello World","modifiedIndex":\d+,"createdIndex":\d+}}')
self.assertRegexpMatches(text, regex)
def test_d_directorylist(self):
#List a directory in Etcd
dir_list = self.etcd.list_directory('formations/cholcomb')
self.assertIsInstance(dir_list, list)