2 from ncclient import manager
3 from ncclient.transport.errors import AuthenticationError, SSHError
4 from lxml import etree as ET
5 from django.conf import settings
7 from django.core.cache import cache
13 LOG_FILENAME = os.path.join(settings.LOG_FILE_LOCATION, 'celery_jobs.log')
15 #FORMAT = '%(asctime)s %(levelname)s: %(message)s'
16 #logging.basicConfig(format=FORMAT)
17 formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
19 logger = logging.getLogger(__name__)
20 logger.setLevel(logging.DEBUG)
21 handler = logging.FileHandler(LOG_FILENAME)
22 handler.setFormatter(formatter)
23 logger.addHandler(handler)
25 def fod_unknown_host_cb(host, fingerprint):
28 class Retriever(object):
29 def __init__(self, device=settings.NETCONF_DEVICE, username=settings.NETCONF_USER, password=settings.NETCONF_PASS, filter=settings.ROUTES_FILTER, route_name=None, xml=None):
31 self.username = username
32 self.password = password
36 self.filter = settings.ROUTE_FILTER%route_name
39 with manager.connect(host=self.device, port=830, username=self.username, password=self.password, unknown_host_cb=fod_unknown_host_cb) as m:
40 xmlconfig = m.get_config(source='running', filter=('subtree',self.filter)).data_xml
43 def proccess_xml(self):
47 xmlconfig = self.fetch_xml()
49 parser.confile = xmlconfig
50 device = parser.export()
53 def fetch_device(self):
54 device = cache.get("device")
55 logger.info("[CACHE] hit! got device")
59 device = self.proccess_xml()
60 if device.routing_options:
61 cache.set("device", device, 3600)
62 logger.info("[CACHE] miss, setting device")
67 class Applier(object):
68 def __init__(self, route_objects = [], route_object=None, device=settings.NETCONF_DEVICE, username=settings.NETCONF_USER, password=settings.NETCONF_PASS):
69 self.route_object = route_object
70 self.route_objects = route_objects
72 self.username = username
73 self.password = password
75 def to_xml(self, operation=None):
76 logger.info("Operation: %s"%operation)
78 logger.info("Generating XML config")
79 route_obj = self.route_object
83 flow.routes.append(route)
84 device.routing_options.append(flow)
85 route.name = route_obj.name
86 if operation == "delete":
87 logger.info("Requesting a delete operation")
88 route.operation = operation
89 device = device.export(netconf_config=True)
90 return ET.tostring(device)
92 route.match['source'].append(route_obj.source)
93 if route_obj.destination:
94 route.match['destination'].append(route_obj.destination)
95 if route_obj.protocol:
96 route.match['protocol'].append(route_obj.protocol)
99 for port in route_obj.port.all():
100 route.match['port'].append(port.port)
104 if route_obj.destinationport:
105 for port in route_obj.destinationport.all():
106 route.match['destination-port'].append(port.port)
110 if route_obj.sourceport:
111 for port in route_obj.sourceport.all():
112 route.match['source-port'].append(port.port)
115 if route_obj.icmpcode:
116 route.match['icmp-code'].append(route_obj.icmpcode)
117 if route_obj.icmptype:
118 route.match['icmp-type'].append(route_obj.icmptype)
119 if route_obj.tcpflag:
120 route.match['tcp-flags'].append(route_obj.tcpflag)
123 for dscp in route_obj.dscp.all():
124 route.match['dscp'].append(dscp.dscp)
127 if route_obj.fragmenttype:
128 route.match['fragment'].append(route_obj.fragmenttype)
129 for thenaction in route_obj.then.all():
130 if thenaction.action_value:
131 route.then[thenaction.action] = thenaction.action_value
133 route.then[thenaction.action] = True
134 if operation == "replace":
135 logger.info("Requesting a replace operation")
136 route.operation = operation
137 device = device.export(netconf_config=True)
138 return ET.tostring(device)
142 def delete_routes(self):
143 if self.route_objects:
144 logger.info("Generating XML config")
147 for route_object in self.route_objects:
148 route_obj = route_object
150 flow.routes.append(route)
151 route.name = route_obj.name
152 route.operation = 'delete'
153 device.routing_options.append(flow)
154 device = device.export(netconf_config=True)
155 return ET.tostring(device)
159 def apply(self, configuration = None, operation=None):
161 if not configuration:
162 configuration = self.to_xml(operation=operation)
163 edit_is_successful = False
164 commit_confirmed_is_successful = False
165 commit_is_successful = False
167 with manager.connect(host=self.device, port=830, username=self.username, password=self.password, unknown_host_cb=fod_unknown_host_cb) as m:
168 assert(":candidate" in m.server_capabilities)
169 with m.locked(target='candidate'):
172 edit_response = m.edit_config(target='candidate', config=configuration, test_option='test-then-set')
173 edit_is_successful, reason = is_successful(edit_response)
174 logger.info("Successfully edited @ %s" % self.device)
175 if not edit_is_successful:
177 except Exception as e:
178 cause="Caught edit exception: %s %s" %(e,reason)
179 cause=cause.replace('\n', '')
183 if edit_is_successful:
185 commit_confirmed_response = m.commit(confirmed=True, timeout=settings.COMMIT_CONFIRMED_TIMEOUT)
186 commit_confirmed_is_successful, reason = is_successful(commit_confirmed_response)
188 if not commit_confirmed_is_successful:
191 logger.info("Successfully confirmed committed @ %s" % self.device)
192 if not settings.COMMIT:
193 return True, "Successfully confirmed committed"
194 except Exception as e:
195 cause="Caught commit confirmed exception: %s %s" %(e,reason)
196 cause=cause.replace('\n', '')
200 if edit_is_successful and commit_confirmed_is_successful:
202 commit_response = m.commit(confirmed=False)
203 commit_is_successful, reason = is_successful(commit_response)
204 logger.info("Successfully committed @ %s" % self.device)
205 newconfig = m.get_config(source='running', filter=('subtree',settings.ROUTES_FILTER)).data_xml
206 retrieve = Retriever(xml=newconfig)
207 logger.info("[CACHE] caching device configuration")
208 cache.set("device", retrieve.proccess_xml(), 3600)
210 if not commit_is_successful:
213 logger.info("Successfully cached device configuration")
214 return True, "Successfully committed"
215 except Exception as e:
216 cause="Caught commit exception: %s %s" %(e,reason)
217 cause=cause.replace('\n', '')
221 return False, "No configuration was supplied"
223 def is_successful(response):
224 from StringIO import StringIO
225 doc = parsexml_(StringIO(response))
226 rootNode = doc.getroot()
227 success_list = rootNode.xpath("//*[local-name()='ok']")
228 if len(success_list)>0:
232 reason_list = rootNode.xpath("//*[local-name()='error-message']")
233 for reason in reason_list:
234 reason_return = "%s %s" %(reason_return, reason.text)
235 return False, reason_return
238 def parsexml_(*args, **kwargs):
239 if 'parser' not in kwargs:
240 kwargs['parser'] = ET.ETCompatXMLParser()
241 doc = ET.parse(*args, **kwargs)