File: bandwidth.py

package info (click to toggle)
python-softlayer 6.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 5,100 kB
  • sloc: python: 53,771; makefile: 289; sh: 57
file content (256 lines) | stat: -rw-r--r-- 9,185 bytes parent folder | download
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
"""Metric Utilities"""
import datetime
import itertools
import sys

import click

from SoftLayer.CLI.command import SLCommand as SLCommand
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer import utils


# pylint: disable=unused-argument
def _validate_datetime(ctx, param, value):
    try:
        return datetime.datetime.strptime(value, "%Y-%m-%d")
    except (ValueError, TypeError):
        pass

    try:
        return datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
    except (ValueError, TypeError) as ex:
        message = "not in the format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'"
        raise click.BadParameter(message) from ex


def _get_pooled_bandwidth(env, start, end):
    call = env.client.call('Account', 'getVirtualDedicatedRacks',
                           iter=True,
                           mask='id,name,metricTrackingObjectId')
    types = [
        {'keyName': 'PUBLICIN',
         'name': 'publicIn',
         'summaryType': 'sum'},
        {'keyName': 'PUBLICOUT',
         'name': 'publicOut',
         'summaryType': 'sum'},
        {'keyName': 'PRIVATEIN',
         'name': 'privateIn',
         'summaryType': 'sum'},
        {'keyName': 'PRIVATEOUT',
         'name': 'privateOut',
         'summaryType': 'sum'},
    ]

    with click.progressbar(list(call),
                           label='Calculating for bandwidth pools',
                           file=sys.stderr) as pools:
        for pool in pools:
            metric_tracking_id = pool.get('metricTrackingObjectId')

            if metric_tracking_id is None:
                continue

            pool_detail = {
                'id': pool.get('id'),
                'type': 'pool',
                'name': pool.get('name'),
                'data': []
            }
            bw_data = env.client.call(
                'Metric_Tracking_Object',
                'getSummaryData',
                start.strftime('%Y-%m-%d %H:%M:%S %Z'),
                end.strftime('%Y-%m-%d %H:%M:%S %Z'),
                types,
                300,
                id=metric_tracking_id,
            )
            pool_detail['data'] = bw_data

            yield pool_detail


def _get_hardware_bandwidth(env, start, end):
    hw_call = env.client.call(
        'Account', 'getHardware',
        iter=True,
        mask='id,hostname,metricTrackingObject.id,'
             'virtualRack[id,bandwidthAllotmentTypeId,name]')
    types = [
        {'keyName': 'PUBLICIN',
         'name': 'publicIn',
         'summaryType': 'counter'},
        {'keyName': 'PUBLICOUT',
         'name': 'publicOut',
         'summaryType': 'counter'},
        {'keyName': 'PRIVATEIN',
         'name': 'privateIn',
         'summaryType': 'counter'},
        {'keyName': 'PRIVATEOUT',
         'name': 'privateOut',
         'summaryType': 'counter'},
    ]

    with click.progressbar(list(hw_call),
                           label='Calculating for hardware',
                           file=sys.stderr) as hws:
        for instance in hws:
            if not utils.lookup(instance, 'metricTrackingObject', 'id'):
                continue

            pool_name = None
            if utils.lookup(instance,
                            'virtualRack',
                            'bandwidthAllotmentTypeId') == 2:
                pool_name = utils.lookup(instance, 'virtualRack', 'name')

            yield {
                'id': instance['id'],
                'type': 'hardware',
                'name': instance['hostname'],
                'pool': pool_name,
                'data': env.client.call(
                    'Metric_Tracking_Object',
                    'getSummaryData',
                    start.strftime('%Y-%m-%d %H:%M:%S %Z'),
                    end.strftime('%Y-%m-%d %H:%M:%S %Z'),
                    types,
                    3600,
                    id=instance['metricTrackingObject']['id'],
                ),
            }


def _get_virtual_bandwidth(env, start, end):
    call = env.client.call(
        'Account', 'getVirtualGuests',
        iter=True,
        mask='id,hostname,metricTrackingObjectId,'
             'virtualRack[id,bandwidthAllotmentTypeId,name]')
    types = [
        {'keyName': 'PUBLICIN_NET_OCTET',
         'name': 'publicIn_net_octet',
         'summaryType': 'sum'},
        {'keyName': 'PUBLICOUT_NET_OCTET',
         'name': 'publicOut_net_octet',
         'summaryType': 'sum'},
        {'keyName': 'PRIVATEIN_NET_OCTET',
         'name': 'privateIn_net_octet',
         'summaryType': 'sum'},
        {'keyName': 'PRIVATEOUT_NET_OCTET',
         'name': 'privateOut_net_octet',
         'summaryType': 'sum'},
    ]

    with click.progressbar(list(call),
                           label='Calculating for virtual',
                           file=sys.stderr) as vms:
        for instance in vms:
            metric_tracking_id = utils.lookup(instance,
                                              'metricTrackingObjectId')

            if metric_tracking_id is None:
                continue

            pool_name = None
            if utils.lookup(instance,
                            'virtualRack',
                            'bandwidthAllotmentTypeId') == 2:
                pool_name = utils.lookup(instance, 'virtualRack', 'name')

            yield {
                'id': instance['id'],
                'type': 'virtual',
                'name': instance['hostname'],
                'pool': pool_name,
                'data': env.client.call(
                    'Metric_Tracking_Object',
                    'getSummaryData',
                    start.strftime('%Y-%m-%d %H:%M:%S %Z'),
                    end.strftime('%Y-%m-%d %H:%M:%S %Z'),
                    types,
                    3600,
                    id=metric_tracking_id,
                ),
            }


@click.command(cls=SLCommand, short_help="Bandwidth report for every pool/server")
@click.option('--start', callback=_validate_datetime,
              default=(datetime.datetime.now() - datetime.timedelta(days=30)).strftime('%Y-%m-%d'),
              help="datetime in the format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'")
@click.option('--end', callback=_validate_datetime, default=datetime.datetime.now().strftime('%Y-%m-%d'),
              help="datetime in the format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'")
@click.option('--sortby', help='Column to sort by', default='hostname', show_default=True)
@click.option('--virtual', is_flag=True, default=False,
              help='Show only the bandwidth summary for each virtual server')
@click.option('--server', is_flag=True, default=False,
              help='Show only the bandwidth summary for each hardware server')
@click.option('--pool', is_flag=True, default=False,
              help='Show only the bandwidth pool summary.')
@environment.pass_env
def cli(env, start, end, sortby, virtual, server, pool):
    """Bandwidth report for every pool/server.

    This reports on the total data transfered for each virtual sever, hardware
    server and bandwidth pool.
    """

    env.err('Generating bandwidth report for %s to %s' % (start, end))

    table = formatting.Table([
        'type',
        'hostname',
        'public_in',
        'public_out',
        'private_in',
        'private_out',
        'pool',
    ])
    table.sortby = sortby

    def f_type(key, results):
        "Filter metric data by type"
        return (result['counter'] for result in results
                if result['type'] == key)

    def _input_to_table(item):
        "Input metric data to table"
        pub_in = int(sum(f_type('publicIn_net_octet', item['data'])))
        pub_out = int(sum(f_type('publicOut_net_octet', item['data'])))
        pri_in = int(sum(f_type('privateIn_net_octet', item['data'])))
        pri_out = int(sum(f_type('privateOut_net_octet', item['data'])))
        table.add_row([
            item['type'],
            item['name'],
            formatting.b_to_gb(pub_in),
            formatting.b_to_gb(pub_out),
            formatting.b_to_gb(pri_in),
            formatting.b_to_gb(pri_out),
            item.get('pool') or formatting.blank(),
        ])

    try:
        if virtual:
            for item in itertools.chain(_get_pooled_bandwidth(env, start, end),
                                        _get_virtual_bandwidth(env, start, end)):
                _input_to_table(item)
        elif server:
            for item in itertools.chain(_get_pooled_bandwidth(env, start, end),
                                        _get_hardware_bandwidth(env, start, end)):
                _input_to_table(item)
        elif pool:
            for item in _get_pooled_bandwidth(env, start, end):
                _input_to_table(item)
        else:
            for item in itertools.chain(_get_pooled_bandwidth(env, start, end),
                                        _get_hardware_bandwidth(env, start, end),
                                        _get_virtual_bandwidth(env, start, end)):
                _input_to_table(item)
    except KeyboardInterrupt:
        env.err("Printing collected results and then aborting.")

    env.out(env.fmt(table))