9e5e0abb462cd425e223034d16447acae4ad9ec7
[osm/vim-emu.git] / src / emuvim / cli / rest / compute.py
1 """
2 Copyright (c) 2015 SONATA-NFV and Paderborn University
3 ALL RIGHTS RESERVED.
4
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16
17 Neither the name of the SONATA-NFV [, ANY ADDITIONAL AFFILIATION]
18 nor the names of its contributors may be used to endorse or promote
19 products derived from this software without specific prior written
20 permission.
21
22 This work has been performed in the framework of the SONATA project,
23 funded by the European Commission under Grant number 671517 through
24 the Horizon 2020 and 5G-PPP programmes. The authors would like to
25 acknowledge the contributions of their colleagues of the SONATA
26 partner consortium (www.sonata-nfv.eu).
27 """
28 from requests import get, put, delete
29 from tabulate import tabulate
30 import pprint
31 import argparse
32 import json
33 from subprocess import Popen
34
35 pp = pprint.PrettyPrinter(indent=4)
36
37
38 class RestApiClient():
39 def __init__(self):
40 self.cmds = {}
41
42 def execute_command(self, args):
43 if getattr(self, args["command"]) is not None:
44 # call the local method with the same name as the command arg
45 getattr(self, args["command"])(args)
46 else:
47 print("Command not implemented.")
48
49 def start(self, args):
50
51 req = {'image': args.get("image"),
52 'command': args.get("docker_command"),
53 'network': args.get("network")}
54
55 response = put("%s/restapi/compute/%s/%s" %
56 (args.get("endpoint"),
57 args.get("datacenter"),
58 args.get("name")),
59 json=req)
60
61 pp.pprint(response.json())
62
63 def stop(self, args):
64
65 response = delete("%s/restapi/compute/%s/%s" %
66 (args.get("endpoint"),
67 args.get("datacenter"),
68 args.get("name")))
69 pp.pprint(response.json())
70
71 def list(self, args):
72
73 list = get('%s/restapi/compute/%s' % (args.get("endpoint"), args.get('datacenter'))).json()
74
75 table = []
76 for c in list:
77 # for each container add a line to the output table
78 if len(c) > 1:
79 name = c[0]
80 status = c[1]
81 #eth0ip = status.get("docker_network", "-")
82 netw_list = [netw_dict['intf_name'] for netw_dict in status.get("network")]
83 dc_if_list = [netw_dict['dc_portname'] for netw_dict in status.get("network")]
84 table.append([status.get("datacenter"),
85 name,
86 status.get("image"),
87 ','.join(netw_list),
88 ','.join(dc_if_list)])
89 #status.get("state").get("Status")]
90
91 headers = ["Datacenter",
92 "Container",
93 "Image",
94 "Interface list",
95 "Datacenter interfaces"]
96 print(tabulate(table, headers=headers, tablefmt="grid"))
97
98 def status(self, args):
99
100 list = get("%s/restapi/compute/%s/%s" %
101 (args.get("endpoint"),
102 args.get("datacenter"),
103 args.get("name"))).json()
104
105 pp.pprint(list)
106
107 def xterm(self, args):
108 vnf_names = args.get("vnf_names")
109 for vnf_name in vnf_names:
110 Popen(['xterm', '-xrm', 'XTerm.vt100.allowTitleOps: false', '-T', vnf_name,
111 '-e', "docker exec -it mn.{0} /bin/bash".format(vnf_name)])
112
113 parser = argparse.ArgumentParser(description="""son-emu compute
114
115 Examples:
116 - son-emu-cli compute start -d dc2 -n client -i sonatanfv/sonata-iperf3-vnf
117 - son-emu-cli list
118 - son-emu-cli compute status -d dc2 -n client
119 """, formatter_class=argparse.RawTextHelpFormatter)
120 parser.add_argument(
121 "command",
122 choices=['start', 'stop', 'list', 'status', 'xterm'],
123 help="Action to be executed.")
124 parser.add_argument(
125 "vnf_names",
126 nargs='*',
127 help="vnf names to open an xterm for")
128 parser.add_argument(
129 "--datacenter", "-d", dest="datacenter",
130 help="Data center to which the command should be applied.")
131 parser.add_argument(
132 "--name", "-n", dest="name",
133 help="Name of compute instance e.g. 'vnf1'.")
134 parser.add_argument(
135 "--image", "-i", dest="image",
136 help="Name of container image to be used e.g. 'ubuntu:trusty'")
137 parser.add_argument(
138 "--dcmd", "-c", dest="docker_command",
139 help="Startup command of the container e.g. './start.sh'")
140 parser.add_argument(
141 "--net", dest="network",
142 help="Network properties of a compute instance e.g. \
143 '(id=input,ip=10.0.10.3/24),(id=output,ip=10.0.10.4/24)' for multiple interfaces.")
144 parser.add_argument(
145 "--endpoint", "-e", dest="endpoint",
146 default="http://127.0.0.1:5001",
147 help="UUID of the plugin to be manipulated.")
148
149
150 def main(argv):
151 args = vars(parser.parse_args(argv))
152 c = RestApiClient()
153 c.execute_command(args)