Statistics
| Branch: | Tag: | Revision:

root / snf-deploy / snfdeploy / lib.py @ 4baa4696

History | View | Annotate | Download (7.5 kB)

1
#!/usr/bin/python
2

    
3
import json
4
import time
5
import ipaddr
6
import os
7
import signal
8
import ConfigParser
9
import sys
10
import re
11
import random
12
import subprocess
13
import shutil
14
import imp
15
import tempfile
16
from snfdeploy import massedit
17

    
18

    
19
HEADER = '\033[95m'
20
OKBLUE = '\033[94m'
21
OKGREEN = '\033[92m'
22
WARNING = '\033[93m'
23
FAIL = '\033[91m'
24
ENDC = '\033[0m'
25

    
26

    
27
def disable_color():
28
    global HEADER
29
    global OKBLUE
30
    global OKGREEN
31
    global WARNING
32
    global FAIL
33
    global ENDC
34

    
35
    HEADER = ''
36
    OKBLUE = ''
37
    OKGREEN = ''
38
    WARNING = ''
39
    FAIL = ''
40
    ENDC = ''
41

    
42

    
43
if not sys.stdout.isatty():
44
    disable_color()
45

    
46

    
47
class Host(object):
48
    def __init__(self, hostname, ip, mac, domain, os):
49
        self.hostname = hostname
50
        self.ip = ip
51
        self.mac = mac
52
        self.domain = domain
53
        self.os = os
54

    
55
    @property
56
    def fqdn(self):
57
        return self.hostname + "." + self.domain
58

    
59
    @property
60
    def arecord(self):
61
        return self.hostname + " IN A " + self.ip + "\n"
62

    
63
    @property
64
    def ptrrecord(self):
65
        return ".".join(raddr(self.ip)) + " IN PTR " + self.fqdn + ".\n"
66

    
67

    
68
class Alias(Host):
69
    def __init__(self, host, alias):
70
        super(Alias, self).__init__(host.hostname, host.ip, host.mac,
71
                                    host.domain, host.os)
72
        self.alias = alias
73

    
74
    @property
75
    def cnamerecord(self):
76
        return (self.alias + " IN CNAME " + self.hostname + "." +
77
                self.domain + ".\n")
78

    
79
    @property
80
    def fqdn(self):
81
        return self.alias + "." + self.domain
82

    
83

    
84
class Env(object):
85

    
86
    def evaluate(self, filename, section):
87
        for k, v in self.conf.get_section(filename, section):
88
            setattr(self, k, v)
89

    
90
    def __init__(self, conf):
91
        self.conf = conf
92
        for f, sections in conf.files.iteritems():
93
            for s in sections:
94
                self.evaluate(f, s)
95

    
96
        self.node2hostname = dict(conf.get_section("nodes", "hostnames"))
97
        self.node2ip = dict(conf.get_section("nodes", "ips"))
98
        self.node2mac = dict(conf.get_section("nodes", "macs"))
99
        self.node2os = dict(conf.get_section("nodes", "os"))
100
        self.hostnames = [self.node2hostname[n]
101
                          for n in self.nodes.split(",")]
102

    
103
        self.ips = [self.node2ip[n]
104
                    for n in self.nodes.split(",")]
105

    
106
        self.cluster_hostnames = [self.node2hostname[n]
107
                                  for n in self.cluster_nodes.split(",")]
108

    
109
        self.cluster_ips = [self.node2ip[n]
110
                            for n in self.cluster_nodes.split(",")]
111

    
112
        self.net = ipaddr.IPNetwork(self.subnet)
113

    
114
        self.nodes_info = {}
115
        self.hosts_info = {}
116
        self.ips_info = {}
117
        for node in self.nodes.split(","):
118
            host = Host(self.node2hostname[node],
119
                        self.node2ip[node],
120
                        self.node2mac[node], self.domain, self.node2os[node])
121

    
122
            self.nodes_info[node] = host
123
            self.hosts_info[host.hostname] = host
124
            self.ips_info[host.ip] = host
125

    
126
        self.cluster = Host(self.cluster_name, self.cluster_ip, None,
127
                            self.domain, None)
128
        self.master = self.nodes_info[self.master_node]
129

    
130
        self.roles = {}
131
        for role, node in conf.get_section("synnefo", "roles"):
132
            self.roles[role] = Alias(self.nodes_info[node], role)
133
            setattr(self, role, self.roles[role])
134

    
135

    
136
class Conf(object):
137

    
138
    files = {
139
        "nodes": ["network", "info"],
140
        "deploy": ["dirs", "packages", "keys", "options"],
141
        "vcluster": ["cluster", "image", "network"],
142
        "synnefo": ["cred", "synnefo", "roles"],
143
        "packages": ["debian", "ganeti", "synnefo", "other"],
144
        "ganeti": [],
145
    }
146

    
147
    def __init__(self, confdir, cluster_name):
148
        self.confdir = confdir
149
        self.files["ganeti"] = [cluster_name]
150
        for f in self.files.keys():
151
            setattr(self, f, self.read_config(f))
152

    
153
    def read_config(self, f):
154
        config = ConfigParser.ConfigParser()
155
        config.optionxform = str
156
        filename = os.path.join(self.confdir, f) + ".conf"
157
        config.read(filename)
158
        return config
159

    
160
    def set(self, conf, section, option, value):
161
        c = getattr(self, conf)
162
        c.set(section, option, value)
163

    
164
    def get(self, conf, section, option):
165
        c = getattr(self, conf)
166
        return c.get(section, option, True)
167

    
168
    def get_section(self, conf, section):
169
        c = getattr(self, conf)
170
        return c.items(section, True)
171

    
172
    def print_config(self):
173
        for f in self.files.keys():
174
            getattr(self, f).write(sys.stdout)
175

    
176
    def _configure(self, args):
177
        for f, sections in self.files.iteritems():
178
            for s in sections:
179
                for k, v in self.get_section(f, s):
180
                    if getattr(args, k, None):
181
                        self.set(f, s, k, getattr(args, k))
182

    
183
    @classmethod
184
    def configure(cls, confdir="/etc/snf-deploy",
185
                  cluster_name="ganeti1", args=None, autoconf=False):
186

    
187
        conf = cls(confdir, cluster_name)
188
        if args:
189
            conf._configure(args)
190
        if autoconf:
191
            conf.autoconf()
192

    
193
        return conf
194

    
195
    def autoconf(self):
196
        #domain = get_domain()
197
        #if domain:
198
        #    self.nodes.set("network", "domain", get_domain())
199
        # self.nodes.set("network", "subnet", "/".join(get_netinfo()))
200
        # self.nodes.set("network", "gateway", get_default_route()[0])
201
        self.nodes.set("hostnames", "node1", get_hostname())
202
        self.nodes.set("ips", "node1", get_netinfo()[0])
203
        self.nodes.set("info", "nodes", "node1")
204
        self.nodes.set("info", "public_iface", get_default_route()[1])
205

    
206

    
207
def debug(host, msg):
208

    
209
    print HEADER + host + \
210
        OKBLUE + ": " + msg + ENDC
211

    
212

    
213
def check_pidfile(pidfile):
214
    print("Checking pidfile " + pidfile)
215
    try:
216
        f = open(pidfile, "r")
217
        pid = f.readline()
218
        os.kill(int(pid), signal.SIGKILL)
219
        f.close()
220
        os.remove(pidfile)
221
        time.sleep(5)
222
    except:
223
        pass
224

    
225

    
226
def randomMAC():
227
    mac = [0x52, 0x54, 0x56,
228
           random.randint(0x00, 0xff),
229
           random.randint(0x00, 0xff),
230
           random.randint(0x00, 0xff)]
231
    return ':'.join(map(lambda x: "%02x" % x, mac))
232

    
233

    
234
def create_dir(d, clean=False):
235
    os.system("mkdir -p " + d)
236
    if clean:
237
        try:
238
            os.system("rm -f %s/*" % d)
239
        except:
240
            pass
241

    
242

    
243
def get_netinfo():
244
    _, pdev = get_default_route()
245
    r = re.compile(".*inet (\S+)/(\S+).*")
246
    s = subprocess.Popen(['ip', 'addr', 'show', 'dev', pdev],
247
                         stdout=subprocess.PIPE)
248

    
249
    for line in s.stdout.readlines():
250
        match = r.search(line)
251
        if match:
252
            ip, size = match.groups()
253
            break
254

    
255
    return ip, size
256

    
257

    
258
def get_hostname():
259
    s = subprocess.Popen(['hostname', '-s'], stdout=subprocess.PIPE)
260
    return s.stdout.readline().strip()
261

    
262

    
263
def get_domain():
264
    s = subprocess.Popen(['hostname', '-d'], stdout=subprocess.PIPE)
265
    return s.stdout.readline().strip()
266

    
267

    
268
def get_default_route():
269
    r = re.compile("default via (\S+) dev (\S+)")
270
    s = subprocess.Popen(['ip', 'route'], stdout=subprocess.PIPE)
271
    for line in s.stdout.readlines():
272
        match = r.search(line)
273
        if match:
274
            gw, dev = match.groups()
275
            break
276

    
277
    return (gw, dev)
278

    
279

    
280
def import_conf_file(filename, directory):
281
    return imp.load_module(filename, *imp.find_module(filename, [directory]))
282

    
283

    
284
def raddr(addr):
285
    return list(reversed(addr.replace("/", "-").split(".")))