~rajarammallya/network-service/melange_framework

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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

# Interactive shell based on Django:
#
# Copyright (c) 2005, the Lawrence Journal-World
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#     1. Redistributions of source code must retain the above copyright notice,
#        this list of conditions and the following disclaimer.
#
#     2. Redistributions in binary form must reproduce the above copyright
#        notice, this list of conditions and the following disclaimer in the
#        documentation and/or other materials provided with the distribution.
#
#     3. Neither the name of Django nor the names of its contributors may be
#        used to endorse or promote products derived from this software without
#        specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


"""
  CLI interface for IPAM.
"""
import logging
import os
import sys
import json
import optparse

# If ../melange/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
                                   os.pardir,
                                   os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'melange', '__init__.py')):
    sys.path.insert(0, possible_topdir)

from melange import version
from gettext import gettext as _
from melange.common.client import Client
from melange.common.utils import Method, remove_nones


class Resource(object):
    port = 9292
    host = "0.0.0.0"

    def __init__(self, path, name):
        self.path = path
        self.name = name

    def create(self, **kwargs):
        return self.request("POST", self.path,
                            body=json.dumps({self.name: kwargs}))

    def update(self, id, **kwargs):
        return self.request("PUT", self._member_path(id),
                            body=json.dumps({self.name: remove_nones(kwargs)}))

    def all(self):
        return self.request("GET", self.path)

    def find(self, id):
        return self.request("GET", self._member_path(id))

    def delete(self, id):
        return self.request("DELETE", self._member_path(id))

    def _member_path(self, id):
        return "{0}/{1}".format(self.path, id)

    def request(self, method, path, body_params=None, **kwargs):
        client = Client(host=self.host, port=self.port)
        kwargs['headers'] = {'X_ROLE': "Admin",
                             'Content-Type': "application/json"}
        response = client.do_request(method, path, **kwargs)
        return json.loads(response.read() or "{}")


class IpBlockCommands(object):

    def __init__(self, block):
        self.block = block

    def create(self, cidr, network_id=None, policy_id=None):
        print self.block.create(cidr=cidr, network_id=network_id,
                                        policy_id=policy_id)

    def list(self):
        print self.block.all()

    def show(self, id):
        print self.block.find(id)

    def delete(self, id):
        print self.block.delete(id)


class PolicyCommands(object):

    def create(self, name, description=None):
        print Policy.create(name=name, description=description)

    def update(self, id, name, description=None):
        print Policy.update(id, name=name, description=description)

    def list(self):
        print Policy.all()

    def show(self, id):
        print Policy.find(id)

    def delete(self, id):
        print Policy.delete(id)


class TenantIpBlockCommands(object):

    def _block(self, tenant_id):
        return Resource("/v0.1/ipam/tenants/{0}/private_ip_blocks"\
                             .format(tenant_id), "ip_block")

    def create(self, tenant_id, cidr, network_id=None, policy_id=None):
        print self._block(tenant_id).create(cidr=cidr, network_id=network_id,
                                        policy_id=policy_id)

    def list(self, tenant_id):
        print self._block(tenant_id).all()

    def show(self, tenant_id, id):
        print self._block(tenant_id).find(id)

    def delete(self, tenant_id, id):
        print self._block(tenant_id).delete(id)


GlobalPrivateIpBlock = Resource("/v0.1/ipam/private_ip_blocks", 'ip_block')
PublicIpBlock = Resource("/v0.1/ipam/public_ip_blocks", 'ip_block')
Policy = Resource("/v0.1/ipam/policies", 'policy')


CATEGORIES = [('public_ip_block', IpBlockCommands(PublicIpBlock)),
              ('private_ip_block', IpBlockCommands(GlobalPrivateIpBlock)),
              ('tenant_ip_block', TenantIpBlockCommands()),
              ('policy', PolicyCommands())]


def lazy_match(name, key_value_tuples):
    """Finds all objects that have a key that case insensitively contains
    [name] key_value_tuples is a list of tuples of the form (key, value)
    returns a list of tuples of the form (key, value)"""
    result = []
    for (k, v) in key_value_tuples:
        if k.lower().find(name.lower()) == 0:
            result.append((k, v))
    if len(result) == 0:
        print "%s does not match any options:" % name
        for k, _v in key_value_tuples:
            print "\t%s" % k
        sys.exit(2)
    if len(result) > 1:
        print "%s matched multiple options:" % name
        for k, _v in result:
            print "\t%s" % k
        sys.exit(2)
    return result


def methods_of(obj):
    """Get all callable methods of an object that don't start with underscore
    returns a list of tuples of the form (method_name, method)"""
    result = []
    for i in dir(obj):
        if callable(getattr(obj, i)) and not i.startswith('_'):
            result.append((i, getattr(obj, i)))
    return result


def create_options(parser):
    """
    Sets up the CLI and config-file options that may be
    parsed and program commands.

    :param parser: The option parser
    """
    parser.add_option('-v', '--verbose', default=False, action="store_true",
                      help="Print more verbose output")
    parser.add_option('-H', '--host', metavar="ADDRESS", default="0.0.0.0",
                      help="Address of Melange API host. "
                           "Default: %default")
    parser.add_option('-p', '--port', dest="port", metavar="PORT",
                      type=int, default=9292,
                      help="Port the Melange API host listens on. "
                           "Default: %default")


def parse_options(parser, cli_args):
    """
    Returns the parsed CLI options, command to run and its arguments, merged
    with any same-named options found in a configuration file

    :param parser: The option parser
    """
    (options, args) = parser.parse_args(cli_args)
    if not args:
        parser.print_usage()
        sys.exit(2)
    return (options, args)


def usage():
    usage = """
%prog category action [args] [options]"

Available categories:

    """
    for k, _v in CATEGORIES:
        usage = usage + ("\t%s\n" % k)

    return usage


def main():
    oparser = optparse.OptionParser(version='%%prog %s'
                                    % version.version_string(),
                                    usage=usage().strip())
    create_options(oparser)
    (options, args) = parse_options(oparser, sys.argv[1:])

    Resource.host, Resource.port = options.host, options.port
    script_name = os.path.basename(sys.argv[0])

    category = args.pop(0)
    matches = lazy_match(category, CATEGORIES)
    # instantiate the command group object
    category, command_object = matches[0]
    actions = methods_of(command_object)
    if len(args) < 1:
        print "Usage: " + script_name + " category action [<args>]"
        print _("Available actions for %s category:") % category
        for k, _v in actions:
            print "\t%s" % k
        sys.exit(2)
    action = args.pop(0)
    matches = lazy_match(action, actions)
    action, fn = matches[0]
    # call the action with the remaining arguments
    try:
        fn(*args)
        sys.exit(0)
    except TypeError:
        print _("Possible wrong number of arguments supplied")
        print "Usage: %s %s %s" % (script_name, category, Method(fn))
        if options.verbose:
            raise
        sys.exit(2)
    except Exception:
        print _("Command failed, please check log for more info")
        raise


if __name__ == '__main__':
    main()