1 | #!/usr/bin/env python
|
---|
2 | # -*- coding: utf-8 -*-
|
---|
3 | #
|
---|
4 | # Script for importing nodes from yaml information generated by gformat.py
|
---|
5 | #
|
---|
6 | # Example: $ ~/wleiden/node-config/genesis/tools/gformat.py full-export |
|
---|
7 | # ./manage.py import_nodes -
|
---|
8 | #
|
---|
9 | # Rick van der Zwet <info@rickvanderzwet.nl>
|
---|
10 | #
|
---|
11 | from django.core.management.base import BaseCommand,CommandError
|
---|
12 | from django.db.utils import IntegrityError
|
---|
13 | from optparse import OptionParser, make_option
|
---|
14 | from gheat.models import *
|
---|
15 | import os
|
---|
16 | import sys
|
---|
17 | import logging
|
---|
18 | import yaml
|
---|
19 |
|
---|
20 | from select import select
|
---|
21 | from collections import defaultdict
|
---|
22 |
|
---|
23 | logger = logging.getLogger(__name__)
|
---|
24 | logger.setLevel(logging.INFO)
|
---|
25 |
|
---|
26 |
|
---|
27 | class Command(BaseCommand):
|
---|
28 | args = '[<filename>]'
|
---|
29 | help = 'Specify - to read from stdin'
|
---|
30 | option_list = BaseCommand.option_list + (
|
---|
31 | make_option('-g', '--debug', dest='debug', default='False', help="Debug", action="store_true"),
|
---|
32 | )
|
---|
33 |
|
---|
34 | def handle(self, *args, **options):
|
---|
35 | if options['debug']:
|
---|
36 | logger.setLevel(logging.DEBUG)
|
---|
37 | if len(args) == 0:
|
---|
38 | self.print_help(sys.argv[0],sys.argv[1])
|
---|
39 | raise CommandError("Not all arguments are provided")
|
---|
40 |
|
---|
41 | filename = args[0]
|
---|
42 | timeout = 2
|
---|
43 | if filename == '-':
|
---|
44 | rlist, _, _ = select([sys.stdin], [], [], timeout)
|
---|
45 | if rlist:
|
---|
46 | fh = sys.stdin
|
---|
47 | else:
|
---|
48 | raise CommandError("No stdin input specified within %s seconds" % timeout)
|
---|
49 | else:
|
---|
50 | if not os.path.isfile(filename):
|
---|
51 | raise CommandError("yaml file '%s' does not exists" % filename)
|
---|
52 | fh = open(filename,'r')
|
---|
53 |
|
---|
54 | hosts = yaml.load(fh)
|
---|
55 | for host,items in hosts.iteritems():
|
---|
56 | for iface_key in [x for x in items.keys() if x.startswith('iface_')]:
|
---|
57 | if items[iface_key].has_key('ssid'):
|
---|
58 | org = Organization.get_by_ssid(items[iface_key]['ssid'])
|
---|
59 | if org: break
|
---|
60 | logger.error("NO Organization for SSID '%s'", items[iface_key]['ssid'])
|
---|
61 |
|
---|
62 | if not org:
|
---|
63 | logger.warning("NO Organization for Node '%s'", host)
|
---|
64 |
|
---|
65 | node, created = Node.objects.get_or_create(name=host)
|
---|
66 | node.latitude = items['latitude']
|
---|
67 | node.longitude = items['longitude']
|
---|
68 | node.organization = org
|
---|
69 | node.save()
|
---|
70 | if created:
|
---|
71 | logger.info("Created Node '%s'", node)
|
---|
72 | logger.info("Processed %s items", len(hosts))
|
---|
73 |
|
---|