1# Copyright (C) 2014 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"""
17 Api for operator. Mainly commands to build CLI and
18 operator interface around them.
19"""
20import logging
21
22from ryu.services.protocols.bgp.api.base import ApiException
23from ryu.services.protocols.bgp.api.base import register
24from ryu.services.protocols.bgp.api.rpc_log_handler import RpcLogHandler
25from ryu.services.protocols.bgp.operator.command import Command
26from ryu.services.protocols.bgp.operator.command import STATUS_ERROR
27from ryu.services.protocols.bgp.operator.commands.clear import ClearCmd
28from ryu.services.protocols.bgp.operator.commands.set import SetCmd
29from ryu.services.protocols.bgp.operator.commands.show import ShowCmd
30from ryu.services.protocols.bgp.operator.internal_api import InternalApi
31
32LOG = logging.getLogger('bgpspeaker.api.rtconf')
33
34DEFAULT_LOG_FORMAT = '%(asctime)s %(levelname)s %(message)s'
35
36
37def _init_log_handler():
38    log_handler = RpcLogHandler()
39    log_handler.setLevel(logging.ERROR)
40    log_handler.formatter = logging.Formatter(DEFAULT_LOG_FORMAT)
41    return log_handler
42
43
44INTERNAL_API = InternalApi(_init_log_handler())
45
46
47class RootCmd(Command):
48    subcommands = {
49        'show': ShowCmd,
50        'set': SetCmd,
51        'clear': ClearCmd}
52
53
54def operator_run(cmd, **kwargs):
55    params = kwargs.get('params', [])
56    fmt = kwargs.get('format', 'json')
57    root = RootCmd(api=INTERNAL_API, resp_formatter_name=fmt)
58    ret, _ = root([cmd] + params)
59    if ret.status == STATUS_ERROR:
60        raise ApiException(str(ret.value))
61    return ret.value
62
63
64@register(name="operator.show")
65def operator_show(**kwargs):
66    return operator_run('show', **kwargs)
67
68
69@register(name="operator.set")
70def operator_set(**kwargs):
71    return operator_run('set', **kwargs)
72
73
74@register(name="operator.clear")
75def operator_clear(**kwargs):
76    return operator_run('clear', **kwargs)
77