backing up
[vsorcdistro/.git] / ryu / build / lib.linux-armv7l-2.7 / ryu / tests / integrated / common / ryubgp.py
1 # Copyright (C) 2016 Nippon Telegraph and Telephone Corporation.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #    http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 from __future__ import absolute_import
17
18 import logging
19 import os
20 import time
21
22 from . import docker_base as base
23
24 LOG = logging.getLogger(__name__)
25
26
27 class RyuBGPContainer(base.BGPContainer):
28
29     WAIT_FOR_BOOT = 1
30     SHARED_VOLUME = '/etc/ryu'
31
32     def __init__(self, name, asn, router_id, ctn_image_name):
33         super(RyuBGPContainer, self).__init__(name, asn, router_id,
34                                               ctn_image_name)
35         self.RYU_CONF = os.path.join(self.config_dir, 'ryu.conf')
36         self.SHARED_RYU_CONF = os.path.join(self.SHARED_VOLUME, 'ryu.conf')
37         self.SHARED_BGP_CONF = os.path.join(self.SHARED_VOLUME, 'bgp_conf.py')
38         self.shared_volumes.append((self.config_dir, self.SHARED_VOLUME))
39
40     def _create_config_ryu(self):
41         c = base.CmdBuffer()
42         c << '[DEFAULT]'
43         c << 'verbose=True'
44         c << 'log_file=/etc/ryu/manager.log'
45         with open(self.RYU_CONF, 'w') as f:
46             LOG.info("[%s's new config]" % self.name)
47             LOG.info(str(c))
48             f.writelines(str(c))
49
50     def _create_config_ryu_bgp(self):
51         c = base.CmdBuffer()
52         c << 'import os'
53         c << ''
54         c << 'BGP = {'
55         c << "    'local_as': %s," % str(self.asn)
56         c << "    'router_id': '%s'," % self.router_id
57         c << "    'neighbors': ["
58         c << "        {"
59         for peer, info in self.peers.items():
60             n_addr = info['neigh_addr'].split('/')[0]
61             c << "            'address': '%s'," % n_addr
62             c << "            'remote_as': %s," % str(peer.asn)
63             c << "            'enable_ipv4': True,"
64             c << "            'enable_ipv6': True,"
65             c << "            'enable_vpnv4': True,"
66             c << "            'enable_vpnv6': True,"
67             c << '        },'
68             c << '    ],'
69         c << "    'routes': ["
70         for route in self.routes.values():
71             c << "        {"
72             c << "            'prefix': '%s'," % route['prefix']
73             c << "        },"
74         c << "    ],"
75         c << "}"
76         log_conf = """LOGGING = {
77
78     # We use python logging package for logging.
79     'version': 1,
80     'disable_existing_loggers': False,
81
82     'formatters': {
83         'verbose': {
84             'format': '%(levelname)s %(asctime)s %(module)s ' +
85                       '[%(process)d %(thread)d] %(message)s'
86         },
87         'simple': {
88             'format': '%(levelname)s %(asctime)s %(module)s %(lineno)s ' +
89                       '%(message)s'
90         },
91         'stats': {
92             'format': '%(message)s'
93         },
94     },
95
96     'handlers': {
97         # Outputs log to console.
98         'console': {
99             'level': 'DEBUG',
100             'class': 'logging.StreamHandler',
101             'formatter': 'simple'
102         },
103         'console_stats': {
104             'level': 'DEBUG',
105             'class': 'logging.StreamHandler',
106             'formatter': 'stats'
107         },
108         # Rotates log file when its size reaches 10MB.
109         'log_file': {
110             'level': 'DEBUG',
111             'class': 'logging.handlers.RotatingFileHandler',
112             'filename': os.path.join('.', 'bgpspeaker.log'),
113             'maxBytes': '10000000',
114             'formatter': 'verbose'
115         },
116         'stats_file': {
117             'level': 'DEBUG',
118             'class': 'logging.handlers.RotatingFileHandler',
119             'filename': os.path.join('.', 'statistics_bgps.log'),
120             'maxBytes': '10000000',
121             'formatter': 'stats'
122         },
123     },
124
125     # Fine-grained control of logging per instance.
126     'loggers': {
127         'bgpspeaker': {
128             'handlers': ['console', 'log_file'],
129             'handlers': ['console'],
130             'level': 'DEBUG',
131             'propagate': False,
132         },
133         'stats': {
134             'handlers': ['stats_file', 'console_stats'],
135             'level': 'INFO',
136             'propagate': False,
137             'formatter': 'stats',
138         },
139     },
140
141     # Root loggers.
142     'root': {
143         'handlers': ['console', 'log_file'],
144         'level': 'DEBUG',
145         'propagate': True,
146     },
147 }"""
148         c << log_conf
149         with open(os.path.join(self.config_dir, 'bgp_conf.py'), 'w') as f:
150             LOG.info("[%s's new config]", self.name)
151             LOG.info(str(c))
152             f.writelines(str(c))
153
154     def create_config(self):
155         self._create_config_ryu()
156         self._create_config_ryu_bgp()
157
158     def is_running_ryu(self):
159         results = self.exec_on_ctn('ps ax')
160         running = False
161         for line in results.split('\n')[1:]:
162             if 'ryu-manager' in line:
163                 running = True
164         return running
165
166     def start_ryubgp(self, check_running=True, retry=False):
167         if check_running:
168             if self.is_running_ryu():
169                 return True
170         result = False
171         if retry:
172             try_times = 3
173         else:
174             try_times = 1
175         cmd = "ryu-manager --verbose "
176         cmd += "--config-file %s " % self.SHARED_RYU_CONF
177         cmd += "--bgp-app-config-file %s " % self.SHARED_BGP_CONF
178         cmd += "ryu.services.protocols.bgp.application"
179         for _ in range(try_times):
180             self.exec_on_ctn(cmd, detach=True)
181             if self.is_running_ryu():
182                 result = True
183                 break
184             time.sleep(1)
185         return result
186
187     def stop_ryubgp(self, check_running=True, retry=False):
188         if check_running:
189             if not self.is_running_ryu():
190                 return True
191         result = False
192         if retry:
193             try_times = 3
194         else:
195             try_times = 1
196         for _ in range(try_times):
197             cmd = '/usr/bin/pkill ryu-manager -SIGTERM'
198             self.exec_on_ctn(cmd)
199             if not self.is_running_ryu():
200                 result = True
201                 break
202             time.sleep(1)
203         return result
204
205     def run(self, wait=False, w_time=WAIT_FOR_BOOT):
206         w_time = super(RyuBGPContainer,
207                        self).run(wait=wait, w_time=self.WAIT_FOR_BOOT)
208         return w_time
209
210     def reload_config(self):
211         self.stop_ryubgp(retry=True)
212         self.start_ryubgp(retry=True)