/
vrouter-port-control
executable file
·171 lines (151 loc) · 6.22 KB
/
vrouter-port-control
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
#!/usr/bin/python
#
#Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
#
import sys
import argparse
import ConfigParser
import requests
import json
import os
import errno
import datetime
import re
sys.path.insert(1, sys.path[0]+'/../api-venv/lib/python2.7/site-packages')
from vnc_api.vnc_api import *
from requests.exceptions import ConnectionError
PORT_PATH="/var/lib/contrail/ports/"
PORT_IPC_VROUTER_AGENT_PORT=9091
class VrouterPortControl(object):
def __init__(self, args_str = None):
self._args = None
if not args_str:
args_str = ' '.join(sys.argv[1:])
self._parse_args(args_str)
#TODO:Move this to other place as it tries to create directory every time
self.CreateDirectoryTree(PORT_PATH)
port_type_value = 0
ret_code = 0
headers = {'content-type': 'application/json'}
base_url = "http://localhost:" + str(PORT_IPC_VROUTER_AGENT_PORT)
if self._args.oper == "add":
if self._args.port_type == "NovaVMPort":
port_type_value = 0
elif self._args.port_type == "NameSpacePort":
port_type_value = 1
u = self._args.vm_project_uuid
project_id = ""
if (u and (len(u) == 32)):
u = u[:8] + '-' + u[8:]
u = u[:13] + '-' + u[13:]
u = u[:18] + '-' + u[18:]
project_id = u[:23] + '-' + u[23:]
url = base_url + "/port"
payload = self.GetJSonDict(port_type_value, project_id)
json_dump = json.dumps(payload)
if not self._args.no_persist:
ret_code = self.WriteToFile(port_type_value, project_id)
try:
'''We post the request to agent even if WriteToFile has failed.
Agent will write to file if file is not already present
'''
r = requests.post(url, data=json_dump, headers=headers)
if r.status_code != 200:
ret_code = 1
except ConnectionError:
pass
elif self._args.oper == "delete":
if not self._args.no_persist:
self.DeleteFile()
url = base_url + "/port/" + self._args.uuid
try:
r = requests.delete(url, data=None, headers=headers);
if r.status_code != 200:
ret_code = 1
except ConnectionError:
pass
sys.exit(ret_code)
#end __init__
def _parse_args(self, args_str):
# Source any specified config/ini file
# Turn off help, so we print all options in response to -h
conf_parser = argparse.ArgumentParser(add_help = False)
args, remaining_argv = conf_parser.parse_known_args(
re.compile("\s+(?=\-\-)").split(args_str)
)
# Don't surpress add_help here so it will handle -h
parser = argparse.ArgumentParser(
# Inherit options from config_parser
parents=[conf_parser],
# print script description with -h/--help
description=__doc__,
# Don't mess with format of description
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
'--oper', choices=['add', 'delete'], help="Operation add/delete ")
parser.add_argument('--uuid', help="port UUID")
parser.add_argument('--instance_uuid', help="instance UUID")
parser.add_argument('--vn_uuid', help="VN UUID")
parser.add_argument('--vm_project_uuid', help="VM UUID")
parser.add_argument('--ip_address', help="IP Address")
parser.add_argument('--ipv6_address', help="IPv6 Address")
parser.add_argument('--vm_name', help="VM Name")
parser.add_argument('--mac', help="MAC address")
parser.add_argument('--tap_name', help="System name of interface")
parser.add_argument("--port_type", choices=['NovaVMPort', 'NameSpacePort'], help = "Port type")
parser.add_argument("--tx_vlan_id", type = int, help = "Transmit VLAN ID")
parser.add_argument("--rx_vlan_id", type = int, help = "Receive VLAN ID")
parser.add_argument("--no_persist", type = bool, help = "Dont't store port information in files", default=False)
parser.add_argument("--vif_type", choices=['VhostUser', 'Vrouter'], help = "VIF type")
self._args = parser.parse_args(remaining_argv)
#end _parse_args
def CreateDirectoryTree(self, path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else: raise
#end CreateDirectoryTree
def GetJSonDict(self, port_type, project_id):
data = {
"id" : self._args.uuid,
"instance-id" : self._args.instance_uuid,
"ip-address" : self._args.ip_address,
"ip6-address" : self._args.ipv6_address,
"vn-id" : self._args.vn_uuid,
"display-name": self._args.vm_name,
"vm-project-id" : project_id,
"mac-address" : self._args.mac,
"system-name" : self._args.tap_name,
"type" : port_type,
"rx-vlan-id" : self._args.rx_vlan_id,
"tx-vlan-id" : self._args.tx_vlan_id,
"author" : __file__,
"time" : str(datetime.datetime.now())
}
return data;
#end GetJSonDict
def WriteToFile(self, port_type, project_id):
filename = ("%s%s" %(PORT_PATH, self._args.uuid))
data = self.GetJSonDict(port_type, project_id)
try:
with open(filename, 'w') as outfile:
json.dump(data, outfile, True)
outfile.close()
except:
return 1
return 0
#end WriteToFile
def DeleteFile(self):
filename = ("%s%s" %(PORT_PATH, self._args.uuid))
if os.path.isfile(filename):
os.remove(filename)
#end DeleteFile
# end class VrouterPortControl
def main(args_str = None):
VrouterPortControl(args_str)
#end main
if __name__ == "__main__":
main()