zerigodns / zerigodns / api.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
''' Copyright 2009 Peter Sanchez <petersanchez@gmail.com>.  
    See BSD-LICENSE for license information.
    
    Classes used to interact with Zerigo DNS API
'''
import base64
import httplib
import urlparse
from urllib import urlencode
from zerigodns.parser import Parser


class ZerigoError(Exception):
    pass


class ZerigoNotFound(Exception):
    pass
    

class ZerigoDNS(object):
    ''' Base class to interact with ZerigoDNS API.
    '''
    vals = {}
    def __init__(self, user, key, data=None, is_secure=True, is_debug=False):
        self.api_host = 'ns.zerigo.com'
        self.api_path = '/api/1.1/'
        self.is_secure = is_secure
        self.is_debug = is_debug
        self.set_credentials(user, key)
        self.count = 0
        self.parser = Parser()
        self.errors = []
        self.xml_skip = []
        self.element = ''
        self.response_headers = {}
        
        if isinstance(data, dict):
            self.load(data)
    
    def _is_protected(self, name):
        protected = [
            'api_host', 'api_path', 'is_secure', 'parser', 'count',
            'vals', 'errors', 'xml_skip', 'user', 'key', 'element',
            'response_headers', 'is_debug',
        ]
        return (name in protected)
    
    def __setattr__(self, name, val):
        if self._is_protected(name):
            super(ZerigoDNS, self).__setattr__(name, val)
        else:
            name = name.replace('_', '-')
            self.vals[name] = val
    
    def __delattr__(self, name):
        if not self._is_protected(name):
            del self.vals[name]
    
    def __getattribute__(self, name):
        if name == 'vals':
            return super(ZerigoDNS, self).__getattribute__(name)
        else:
            try:
                _name = name.replace('_', '-')
                return self.vals[_name]
            except KeyError:
                return super(ZerigoDNS, self).__getattribute__(name)
    
    def load(self, data, reset=True):
        if reset:
            self.vals = {}  # Reset vals

        for k, v in data.iteritems():
            setattr(self, k, v)
    
    def set_credentials(self, user, key):
        ''' Set access credentials. '''
        self.user = user
        self.key = key
    
    def get_auth_header(self):
        base64str = base64.b64encode('%s:%s' % (self.user, self.key))
        return {
            'Authorization': 'Basic %s' % base64str,
            'Accept': 'application/xml',
        }
    
    def send_request(self, method='GET', id=None, path=None, 
                                request=None, headers={}, opts={}):
        ''' Construct and send request to Zerigo servers.
        '''
        self.errors = []
        if path is not None:
            # Path over-rides element & id
            call_path = urlparse.urljoin(self.api_path, path)
        else:
            if id is not None:
                call_path = urlparse.urljoin(
                    self.api_path,
                    '%s/%s.xml' % (self.element, str(id)),
                )
            else:
                call_path = urlparse.urljoin(
                    self.api_path,
                    '%s.xml' % self.element,
                )
            
        if opts:
            call_path += '?%s' % urlencode(opts)
        
        if self.is_secure:
            conn = httplib.HTTPSConnection(self.api_host)
        else:
            conn = httplib.HTTPConnection(self.api_host)

        req_headers = self.get_auth_header()
        req_headers.update(headers)
        if method in ('POST', 'PUT'):
            req_headers['Content-Type'] = 'application/xml'
        
        if self.is_debug:
            print 'DEBUG (method): ', method
            print 'DEBUG (path): ', call_path
            print 'DEBUG (headers): ', req_headers
            print 'DEBUG (request): ', request

        conn.request(method, call_path, request, req_headers)
        res = conn.getresponse()
        data = res.read()
        conn.close()
        
        # Handle header data
        self.response_headers.update(res.getheaders())
        self.count = int(res.getheader('X-Query-Count', 0))
        
        if self.is_debug:
            print 'DEBUG (response data): ', data
            print 'DEBUG (response headers): ', self.response_headers
            print 'DEBUG (response code): %i - %s' % (res.status, res.reason)

        if res.status >= 200 and res.status <= 299:
            return data

        if res.status == 422:
            self.errors = self.parse_errors(data)
            return None
        elif res.status == 404:
            raise ZerigoNotFound('Not found')
        else:
            raise ZerigoError('Error: [%i] %s' % (res.status, res.reason))
    
    def parse(self, data):
        return self.parser.parse(data)
    
    def parse_errors(self, data):
        return self.parser.parse_errors(data)
    
    def get_xml_data(self):
        ''' Clean out items that should be skipped.
        '''
        vals = self.vals.copy()
        for name in self.xml_skip:
            try:
                vals.pop(name)
            except KeyError:
                pass
        return vals
    
    def _to_xml(self, data):
        return self.parser.build_request_string(data)
    
    def to_xml(self):
        raise ZerigoError('Not Implemented')
    
    def get_public_ip(self):
        api_path = 'tools/public_ipv4.xml'
        ip_hash = self.parse(
            self.send_request(path=api_path)
        )
        return ip_hash.get('ipv4')
    
    def update_count(self, opts={}):
        if isinstance(self, NSHost):
            if not opts.has_key('zone_id'):
                try:
                    opts['zone_id'] = self.zone_id
                except AttributeError:
                    raise ZerigoError(
                        'Cannot update host count without valid zone id'
                    )

        api_path = '%s/count.xml' % self.element
        data = self.parse(self.send_request(path=api_path, opts=opts))
        self.count = int(data['count'])
        return self.count
    
    def get_blank(self):
        api_path = '%s/new.xml' % self.element
        return self.parse(self.send_request(path=api_path))
    
    def has_errors(self):
        return (len(self.errors) > 0)
    
    def get_errors(self):
        return self.errors
    
    def destroy(self):
        if not hasattr(self, 'id'):
            raise ZerigoError('Cannot destroy without a valid id')
        self.send_request(method='DELETE', id=self.id)
        return (not self.has_errors())
    
    def save(self):
        data = self.to_xml()
        if not hasattr(self, 'id'):
            # Create new instance
            result = self.send_request(method='POST', request=data)
            if not self.has_errors():
                self.load(
                    self.parse(result)[
                        self.element[:-1].replace('_', '-')
                    ]
                )
                loc = self.response_headers.get('Location', None)
                if loc is not None:
                    p = urlparse.urlparse(loc)
                    new_id = int(p.path.split('/')[-2])
                    self.id = new_id
                        
                if not hasattr(self, 'id'):
                    # Second check, sanity purposes
                    raise ZerigoError(
                        'Create was successful but unable to determine the id'
                    )
        else:
            # Update current instance
            result = self.send_request(
                method='PUT',
                id=self.id,
                request=data,
            )

        return (not self.has_errors())


class ZoneHostList(list):
    ''' Wrapper around list to paginate through a Zerigo zone's 
        host list.
    '''
    _paginate_by = 100

    def __init__(self, zone, *args, **kwargs):
        self._zone = zone
        self._host_paginator = NSHost(
            zone.user,
            zone.key,
            is_secure=zone.is_secure,
            is_debug=zone.is_debug,
        )
        super(ZoneHostList, self).__init__(*args, **kwargs)
        if self.cur_count == 0 and self.host_count > 0:
            self.load()

    @property
    def host_count(self):
        return self._zone.hosts_count

    @property
    def cur_count(self):
        return len(self)

    @property
    def paginate_by(self):
        if self._paginate_by <= 0:
            self._paginate_by = 100
        elif self._paginate_by > 1000:
            self._paginate_by = 1000
        return self._paginate_by

    @property
    def cur_page(self):
        return (self.cur_count / self.paginate_by) + 1

    @property
    def next_page(self):
        if self.cur_count < self.host_count:
            if self.cur_count == 0:
                return self.cur_page
            return self.cur_page + 1
        return -1

    @property
    def num_pages(self):
        return (self.host_count / self.paginate_by) + 1

    @property
    def all_pages(self):
        return [(x + 1) for x in range(self.num_pages)]

    def load(self):
        if self.next_page > 0:
            hosts = self._host_paginator.find_all(
                self._zone, {
                    'page': self.next_page,
                    'per_page': self.paginate_by,
                },
            )
            self.extend(hosts)
            return hosts
        return []

    def load_all(self):
        host_tmp = self.load()
        while host_tmp:
            host_tmp = self.load()
        return True


class NSZone(ZerigoDNS):
    ''' Class to manage zone entries 
    '''
    def __init__(self, *args, **kwargs):
        super(NSZone, self).__init__(*args, **kwargs)
        self.xml_skip = (
            'id', 'customer-id', 'created-at', 'updated-at', 'hosts',
        )
        self.element = 'zones'
    
    def __setattr__(self, name, val):
        if name == 'hosts' and isinstance(val, (list, tuple)):
            # Add hosts as NSHost objects
            self.vals[name] = ZoneHostList(
                self,
                [NSHost(
                    self.user,
                    self.key,
                    data=zdata['host'],
                    is_secure=self.is_secure,
                    is_debug=self.is_debug,
                ) for zdata in val],
            )
        else:
            super(NSZone, self).__setattr__(name, val)

    def load(self, data, reset=True):
        super(NSZone, self).load(data, reset=reset)
        host_count = getattr(self, 'host_count', 0)
        if 'hosts' not in self.vals and host_count > 0:
            setattr(self, 'hosts', ZoneHostList(self))
    
    def to_xml(self):
        return self._to_xml({'zone': self.get_xml_data()})
    
    def build_blank_zone(self):
        self.load(self.get_blank()['zone'])
    
    def create(self, data, load_blank=False):
        if data.has_key('zone'):
            data = data.get('zone')
        zone = NSZone(
            self.user,
            self.key,
            data=data,
            is_secure=self.is_secure,
            is_debug=self.is_debug,
        )
        if load_blank:
            zone.build_blank_zone()
            zone.load(data, reset=False)
        zone.save()
        return zone
    
    def create_host(self, data, load_blank=False):
        if not hasattr(self, 'id'):
            raise ZerigoError('Cannot add host without a valid zone id')
        
        if data.has_key('host'):
            data = data.get('host')
        host = NSHost(
            self.user,
            self.key,
            data=data,
            is_secure=self.is_secure,
            is_debug=self.is_debug,
        )
        return host.create(data, self.id, load_blank)
    
    def find_all(self, opts={}):
        return self.zones(opts=opts)
    
    def zones(self, opts={}):
        xml = self.send_request(opts=opts)
        data = self.parse(xml)
        return [
            NSZone(
                self.user,
                self.key,
                data=zdata['zone'],
                is_secure=self.is_secure,
                is_debug=self.is_debug,
            ) for zdata in data.get('zones', [])
        ]
    
    def reload(self):
        if not hasattr(self, 'id'):
            raise ZerigoError('Cannot retrieve zone without a valid id')
        xml = self.send_request(method='GET', id=self.id)
        data = self.parse(xml)
        self.load(data['zone'])
        return self
    
    def find(self, id):
        zone = NSZone(
            self.user,
            self.key,
            data={'id': id,},
            is_secure=self.is_secure,
            is_debug=self.is_debug
        )
        zone.reload()
        return zone
    
    def find_by_domain(self, domain):
        zone = NSZone(
            self.user,
            self.key,
            is_secure=self.is_secure,
            is_debug=self.is_debug
        )
        xml = zone.send_request(method='GET', id=domain)
        data = self.parse(xml)
        zone.load(data['zone'])
        return zone
    
    def find_by_hostname(self, hostname):
        host = NSHost(
            self.user,
            self.key,
            is_secure=self.is_secure,
            is_debug=self.is_debug,
        )
        fqdn = '%s.%s' % (hostname, self.domain)
        return host.find_by_hostname(fqdn, self)


class NSHost(ZerigoDNS):
    ''' Class to manage host entries 
    '''
    def __init__(self, *args, **kwargs):
        super(NSHost, self).__init__(*args, **kwargs)
        self.xml_skip = ('id', 'created-at', 'updated-at',)
        self.element = 'hosts'
    
    def _get_zone_id(self, zone_id):
        return zone_id.id if isinstance(zone_id, NSZone) else zone_id
    
    def to_xml(self):
        return self._to_xml({'host': self.get_xml_data()})
    
    def build_blank_host(self):
        self.load(self.get_blank()['host'])
    
    def create(self, data, zone_id=None, load_blank=False):
        if data.has_key('host'):
            data = data.get('host')
        if zone_id is not None:
            data['zone_id'] = self._get_zone_id(zone_id)
        host = NSHost(
            self.user,
            self.key,
            data=data,
            is_secure=self.is_secure,
            is_debug=self.is_debug,
        )
        if load_blank:
            host.build_blank_host()
            host.load(data, reset=False)
        host.save()
        return host
    
    def find_all(self, zone_id, opts={}):
        opts['zone_id'] = self._get_zone_id(zone_id)
        return self.hosts(opts=opts)

    def hosts(self, opts={}):
        if not opts.has_key('zone_id'):
            opts['zone_id'] = self.zone_id
        else:
            opts['zone_id'] = self._get_zone_id(opts['zone_id'])
        xml = self.send_request(method='GET', opts=opts)
        data = self.parse(xml)
        return [
            NSHost(
                self.user,
                self.key,
                data=zdata['host'],
                is_secure=self.is_secure,
                is_debug=self.is_debug,
            ) for zdata in data.get('hosts', [])
        ]
    
    def find(self, id, zone_id):
        zone_id = self._get_zone_id(zone_id)
        host = NSHost(
            self.user,
            self.key,
            data={'id': id, 'zone_id': zone_id,},
            is_secure=self.is_secure,
            is_debug=self.is_debug,
        )
        host.reload()
        return host
    
    def reload(self):
        if not hasattr(self, 'id'):
            raise ZerigoError('Cannot retrieve host without a valid id')
        xml = self.send_request(method='GET', id=self.id)
        data = self.parse(xml)
        self.load(data['host'])
        return self
    
    def find_by_hostname(self, hostname, zone_id):
        zone_id = self._get_zone_id(zone_id)
        host = NSHost(
            self.user,
            self.key,
            data={'zone_id': zone_id,},
            is_secure=self.is_secure,
            is_debug=self.is_debug
        )
        xml = host.send_request(method='GET', opts={'fqdn': hostname})
        data = self.parse(xml)
        return [
            NSHost(
                self.user,
                self.key,
                data=zdata['host'],
                is_secure=self.is_secure,
                is_debug=self.is_debug,
            ) for zdata in data.get('hosts', [])
        ]


class NSZoneTemplate(ZerigoDNS):
    ''' Class to manage zone templates 
    '''
    def __init__(self, *args, **kwargs):
        super(NSZoneTemplate, self).__init__(*args, **kwargs)
        self.xml_skip = ('id', 'created-at', 'updated-at', 'host-templates',)
        self.element = 'zone_templates'
    
    def __setattr__(self, name, val):
        if name == 'host-templates' and isinstance(val, (list, tuple)):
            # Add host-templates as NSHostTemplate objects
            self.vals[name] = [
                NSHostTemplate(
                    self.user,
                    self.key,
                    data=zdata['host-template'],
                    is_secure=self.is_secure,
                    is_debug=self.is_debug,
                ) for zdata in val
            ]
        else:
            super(NSZoneTemplate, self).__setattr__(name, val)
    
    def to_xml(self):
        return self._to_xml({'zone-template': self.get_xml_data()})

    def build_blank_template(self):
        self.load(self.get_blank()['zone-template'])
    
    def create(self, data, load_blank=False):
        if data.has_key('zone-template'):
            data = data.get('zone-template')
        template = NSZoneTemplate(
            self.user,
            self.key,
            data=data,
            is_secure=self.is_secure,
            is_debug=self.is_debug,
        )
        if load_blank:
            template.build_blank_template()
            template.load(data, reset=False)
        template.save()
        return template
    
    def create_host_template(self, data, load_blank=False):
        if not hasattr(self, 'id'):
            raise ZerigoError(
                'Cannot add host template without a valid zone template id'
            )

        if data.has_key('host-template'):
            data = data.get('host-template')
        host = NSHostTemplate(
            self.user,
            self.key,
            data=data,
            is_secure=self.is_secure,
            is_debug=self.is_debug,
        )
        return host.create(data, self.id, load_blank)
    
    def find_all(self, opts={}):
        return self.templates(opts=opts)

    def templates(self, opts={}):
        xml = self.send_request(opts=opts)
        data = self.parse(xml)
        return [
            NSZoneTemplate(
                self.user,
                self.key,
                data=zdata['zone-template'],
                is_secure=self.is_secure,
                is_debug=self.is_debug,
            ) for zdata in data.get('zone-templates', [])
        ]

    def reload(self):
        if not hasattr(self, 'id'):
            raise ZerigoError(
                'Cannot retrieve zone template without a valid id'
            )
        xml = self.send_request(method='GET', id=self.id)
        data = self.parse(xml)
        self.load(data['zone-template'])
        return self

    def find(self, id):
        zone = NSZoneTemplate(
            self.user,
            self.key,
            data={'id': id,},
            is_secure=self.is_secure,
            is_debug=self.is_debug
        )
        zone.reload()
        return zone


class NSHostTemplate(ZerigoDNS):
    ''' Class to manage host templates 
    '''
    def __init__(self, *args, **kwargs):
        super(NSHostTemplate, self).__init__(*args, **kwargs)
        self.xml_skip = ('id', 'created-at', 'updated-at',)
        self.element = 'host_templates'

    def _get_zone_template_id(self, zone_id):
        return zone_id.id if isinstance(zone_id, NSZoneTemplate) else zone_id

    def to_xml(self):
        return self._to_xml({'host-template': self.get_xml_data()})

    def build_blank_template(self):
        self.load(self.get_blank()['host-template'])
    
    def create(self, data, zone_id=None, load_blank=False):
        if data.has_key('host-template'):
            data = data.get('host-template')
        if zone_id is not None:
            data['zone_template_id'] = self._get_zone_template_id(zone_id)
        host = NSHostTemplate(
            self.user,
            self.key,
            data=data,
            is_secure=self.is_secure,
            is_debug=self.is_debug,
        )
        if load_blank:
            host.build_blank_host()
            host.load(data, reset=False)
        host.save()
        return host
    
    def find_all(self, zone_id, opts={}):
        opts['zone_template_id'] = self._get_zone_template_id(zone_id)
        return self.templates(opts=opts)

    def templates(self, opts={}):
        if not opts.has_key('zone_template_id'):
            opts['zone_template_id'] = self.zone_template_id
        else:
            opts['zone_template_id'] = \
                    self._get_zone_template_id(opts['zone_template_id'])
        xml = self.send_request(method='GET', opts=opts)
        data = self.parse(xml)
        return [
            NSHostTemplate(
                self.user,
                self.key,
                data=zdata['host-template'],
                is_secure=self.is_secure,
                is_debug=self.is_debug,
            ) for zdata in data.get('host-templates', [])
        ]

    def find(self, id, zone_id):
        zone_id = self._get_zone_template_id(zone_id)
        host = NSHostTemplate(
            self.user,
            self.key,
            data={'id': id, 'zone_template_id': zone_id,},
            is_secure=self.is_secure,
            is_debug=self.is_debug,
        )
        host.reload()
        return host

    def reload(self):
        if not hasattr(self, 'id'):
            raise ZerigoError('Cannot retrieve host without a valid id')
        xml = self.send_request(method='GET', id=self.id)
        data = self.parse(xml)
        self.load(data['host-template'])
        return self
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.