nectar-osc 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nectar_osc/__init__.py ADDED
File without changes
nectar_osc/compute.py ADDED
@@ -0,0 +1,121 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+ # not use this file except in compliance with the License. You may obtain
3
+ # a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+ # License for the specific language governing permissions and limitations
11
+ # under the License.
12
+ #
13
+
14
+ import json
15
+ import six
16
+ import sys
17
+
18
+ from novaclient import exceptions as n_exc
19
+ from prettytable import PrettyTable
20
+
21
+
22
+ def _format_instance(d, style=None):
23
+ """Pretty print instance info for the command line"""
24
+ pt = PrettyTable(['Property', 'Value'], caching=False)
25
+ pt.align = 'l'
26
+ for k, v in sorted(d.items()):
27
+ # convert dict to str to check length
28
+ if isinstance(v, (dict, list)):
29
+ v = json.dumps(v)
30
+ # if value has a newline, add in multiple rows
31
+ # e.g. fault with stacktrace
32
+ if v and isinstance(v, six.string_types) and (r'\n' in v or '\r' in v):
33
+ # '\r' would break the table, so remove it.
34
+ if '\r' in v:
35
+ v = v.replace('\r', '')
36
+ lines = v.strip().split(r'\n')
37
+ col1 = k
38
+ for line in lines:
39
+ pt.add_row([col1, line])
40
+ col1 = ''
41
+ else:
42
+ if v is None:
43
+ v = '-'
44
+ pt.add_row([k, v])
45
+
46
+ if style == 'html':
47
+ output = '<b>Instance details</b>'
48
+ output += pt.get_html_string(
49
+ attributes={
50
+ 'border': 1,
51
+ 'style': 'border-width: 1px; border-collapse: collapse;',
52
+ }
53
+ )
54
+ else:
55
+ output = 'Instance details:\n'
56
+ output += pt.get_string()
57
+ return output
58
+
59
+
60
+ def show_instance(clients, instance_id, style=None):
61
+ try:
62
+ instance = clients.compute.servers.get(instance_id)
63
+ except n_exc.NotFound:
64
+ print(f"Instance {instance_id} not found")
65
+ sys.exit(1)
66
+
67
+ info = instance._info.copy()
68
+ for network_label, address_list in instance.networks.items():
69
+ info[f'{network_label} network'] = ', '.join(address_list)
70
+
71
+ flavor = info.get('flavor', {})
72
+ flavor_id = flavor.get('id', '')
73
+
74
+ try:
75
+ info['flavor'] = (
76
+ f'{clients.compute.flavors.get(flavor_id).name} ({flavor_id})'
77
+ )
78
+ except Exception:
79
+ info['flavor'] = '{} ({})'.format("Flavor not found", flavor_id)
80
+
81
+ # Image
82
+ image = info.get('image', {})
83
+ if image:
84
+ image_id = image.get('id', '')
85
+ try:
86
+ img = clients.image.images.get(image_id)
87
+ nectar_build = img.get('nectar_build', 'N/A')
88
+ info['image'] = (
89
+ f'{img.name} ({img.id}, NeCTAR Build {nectar_build})'
90
+ )
91
+ except Exception:
92
+ info['image'] = f'Image not found ({image_id})'
93
+
94
+ else: # Booted from volume
95
+ info['image'] = "Attempt to boot from volume - no image supplied"
96
+
97
+ # Tenant
98
+ project_id = info.get('tenant_id')
99
+ if project_id:
100
+ try:
101
+ project = clients.identity.projects.get(project_id)
102
+ info['tenant_id'] = f'{project.name} ({project.id})'
103
+ except Exception:
104
+ pass
105
+
106
+ # User
107
+ user_id = info.get('user_id')
108
+ if user_id:
109
+ try:
110
+ user = clients.identity.users.get(user_id)
111
+ info['user_id'] = f'{user.name} ({user.id})'
112
+ except Exception:
113
+ pass
114
+
115
+ # Remove stuff
116
+ info.pop('links', None)
117
+ info.pop('addresses', None)
118
+ info.pop('hostId', None)
119
+ info.pop('security_groups', None)
120
+
121
+ return _format_instance(info, style=style)
nectar_osc/config.py ADDED
@@ -0,0 +1,62 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+ # not use this file except in compliance with the License. You may obtain
3
+ # a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+ # License for the specific language governing permissions and limitations
11
+ # under the License.
12
+ #
13
+
14
+ import sys
15
+
16
+ from oslo_config import cfg
17
+ from oslo_config import generator
18
+ from pathlib import Path
19
+
20
+
21
+ homedir = str(Path.home())
22
+ if not Path(homedir).exists():
23
+ print(f'config dir {homedir} doesnt exist')
24
+ sys.exit(1)
25
+
26
+
27
+ freshdesk_opts = [
28
+ cfg.StrOpt('api_key', help='your freshdesk api key'),
29
+ cfg.IntOpt(
30
+ 'email_config_id',
31
+ default='6000071619',
32
+ help='freshdesk email config id',
33
+ ),
34
+ cfg.IntOpt('group_id', default='6000208874', help='freshdesk group id'),
35
+ cfg.StrOpt(
36
+ 'domain', default='dhdnectar.freshdesk.com', help='freshdesk domain'
37
+ ),
38
+ ]
39
+
40
+ cfg.CONF.register_opts(freshdesk_opts, group='freshdesk')
41
+
42
+
43
+ def list_opts():
44
+ return [
45
+ ('freshdesk', freshdesk_opts),
46
+ ]
47
+
48
+
49
+ def init():
50
+ try:
51
+ cfg.CONF(
52
+ [],
53
+ project='nectar-osc',
54
+ default_config_files=['~/.nectar-osc.conf'],
55
+ )
56
+ except cfg.ConfigFilesNotFoundError:
57
+ print('generating config file ~/.nectar-osc.conf')
58
+ conf = cfg.ConfigOpts()
59
+ generator.register_cli_opts(conf)
60
+ conf.namespace = ['nectar_osc']
61
+ with open(homedir + '/' + '.nectar-osc.conf', 'w') as conf_file:
62
+ generator.generate(conf, conf_file)
@@ -0,0 +1,59 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+ # not use this file except in compliance with the License. You may obtain
3
+ # a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+ # License for the specific language governing permissions and limitations
11
+ # under the License.
12
+ #
13
+
14
+ import sys
15
+
16
+ try:
17
+ from freshdesk.v2 import api
18
+ except ImportError:
19
+ api = None
20
+
21
+ from nectar_osc import config
22
+ from oslo_config import cfg
23
+
24
+
25
+ CONF = cfg.CONF
26
+
27
+
28
+ def get_client():
29
+ if not api:
30
+ print(
31
+ "To use this tool, you will need to also install the"
32
+ "python-freshdesk package: \n"
33
+ " $ pip install python-freshdesk"
34
+ )
35
+ sys.exit(1)
36
+
37
+ msg = '\n'.join(
38
+ [
39
+ 'No Freshdesk api key found in your config file.',
40
+ '',
41
+ 'To find your Freshdesk API key by following the guide here:',
42
+ 'https://support.freshdesk.com/support/solutions/'
43
+ 'articles/215517-how-to-find-your-api-key',
44
+ '',
45
+ 'Then add the following config to your configuration',
46
+ 'file (~/.nectar-osc.conf):',
47
+ '',
48
+ ' [freshdesk]',
49
+ ' api_key = <your api key>',
50
+ ]
51
+ )
52
+
53
+ config.init()
54
+
55
+ if not CONF.freshdesk.api_key:
56
+ print(msg)
57
+ sys.exit(1)
58
+
59
+ return api.API(CONF.freshdesk.domain, CONF.freshdesk.api_key)
nectar_osc/identity.py ADDED
@@ -0,0 +1,26 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+ # not use this file except in compliance with the License. You may obtain
3
+ # a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+ # License for the specific language governing permissions and limitations
11
+ # under the License.
12
+ #
13
+
14
+
15
+ def get_tenant_managers_emails(identity, instance):
16
+ """Build a list of email addresses"""
17
+ email_addresses = []
18
+ project = identity.projects.get(instance.tenant_id)
19
+ role = identity.roles.find(name='TenantManager')
20
+ ras = identity.role_assignments.list(
21
+ project=project, role=role, include_names=True
22
+ )
23
+ for ra in ras:
24
+ u = identity.users.get(ra.user['id'])
25
+ email_addresses.append(u.email)
26
+ return email_addresses
nectar_osc/network.py ADDED
@@ -0,0 +1,128 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+ # not use this file except in compliance with the License. You may obtain
3
+ # a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+ # License for the specific language governing permissions and limitations
11
+ # under the License.
12
+ #
13
+
14
+ from prettytable import PrettyTable
15
+
16
+ from neutronclient.v2_0 import client as nclient
17
+
18
+
19
+ def _get_sg_remote(rule):
20
+ if rule['remote_ip_prefix']:
21
+ remote = '{} (CIDR)'.format(rule['remote_ip_prefix'])
22
+ elif rule['remote_group_id']:
23
+ remote = '{} (group)'.format(rule['remote_group_id'])
24
+ else:
25
+ remote = None
26
+ return remote
27
+
28
+
29
+ def _get_sg_protocol_port(rule):
30
+ proto = rule['protocol']
31
+ port_min = rule['port_range_min']
32
+ port_max = rule['port_range_max']
33
+ if proto in ('tcp', 'udp'):
34
+ if port_min and port_min == port_max:
35
+ protocol_port = f'{port_min}/{proto}'
36
+ elif port_min:
37
+ protocol_port = f'{port_min}-{port_max}/{proto}'
38
+ else:
39
+ protocol_port = proto
40
+ elif proto == 'icmp':
41
+ icmp_opts = []
42
+ if port_min is not None:
43
+ icmp_opts.append(f'type:{port_min}')
44
+ if port_max is not None:
45
+ icmp_opts.append(f'code:{port_max}')
46
+
47
+ if icmp_opts:
48
+ protocol_port = 'icmp ({})'.format(', '.join(icmp_opts))
49
+ else:
50
+ protocol_port = 'icmp'
51
+ elif proto is not None:
52
+ # port_range_min/max are not recognized for protocol
53
+ # other than TCP, UDP and ICMP.
54
+ protocol_port = proto
55
+ else:
56
+ protocol_port = None
57
+ return protocol_port
58
+
59
+
60
+ def _format_sg_rule(rule):
61
+ formatted = []
62
+ for field in [
63
+ 'direction',
64
+ 'ethertype',
65
+ ('protocol_port', _get_sg_protocol_port),
66
+ 'remote_ip_prefix',
67
+ 'remote_group_id',
68
+ ]:
69
+ if isinstance(field, tuple):
70
+ field, get_method = field
71
+ data = get_method(rule)
72
+ else:
73
+ data = rule[field]
74
+ if not data:
75
+ continue
76
+ if field in ('remote_ip_prefix', 'remote_group_id'):
77
+ data = f'{field}: {data}'
78
+ formatted.append(data)
79
+ return ', '.join(formatted)
80
+
81
+
82
+ def _format_sg_rules(secgroup):
83
+ try:
84
+ return '\n'.join(
85
+ sorted(
86
+ [
87
+ _format_sg_rule(rule)
88
+ for rule in secgroup['security_group_rules']
89
+ ]
90
+ )
91
+ )
92
+ except Exception:
93
+ return ''
94
+
95
+
96
+ def _format_secgroups(security_groups, style=None):
97
+ pt = PrettyTable(['ID', 'Name', 'Rules'], caching=False)
98
+ pt.align = 'l'
99
+
100
+ for sg in security_groups['security_groups']:
101
+ pt.add_row([sg['id'], sg['name'], _format_sg_rules(sg)])
102
+
103
+ if style == 'html':
104
+ output = '<b>Security Groups</b>'
105
+ output += pt.get_html_string(
106
+ attributes={
107
+ 'border': 1,
108
+ 'style': 'border-width: 1px; border-collapse: collapse;',
109
+ }
110
+ )
111
+ else:
112
+ output = 'Security Groups:\n'
113
+ output += pt.get_string()
114
+ return output
115
+
116
+
117
+ def show_instance_security_groups(clients, instance_id, style=None):
118
+ nc = nclient.Client(session=clients.session)
119
+
120
+ ports = nc.list_ports(device_id=instance_id)
121
+ sg_ids = [
122
+ sg
123
+ for sgs in [p['security_groups'] for p in ports['ports']]
124
+ for sg in sgs
125
+ ]
126
+ security_groups = nc.list_security_groups(id=sg_ids)
127
+
128
+ return _format_secgroups(security_groups, style=style)
nectar_osc/plugin.py ADDED
@@ -0,0 +1,48 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+ # not use this file except in compliance with the License. You may obtain
3
+ # a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+ # License for the specific language governing permissions and limitations
11
+ # under the License.
12
+ #
13
+
14
+
15
+ DEFAULT_API_VERSION = '1'
16
+
17
+ # Required by the OSC plugin interface
18
+ API_NAME = 'nectar'
19
+ API_VERSION_OPTION = 'nectar'
20
+ API_VERSIONS = {
21
+ '1': 'nectar_osc.v1.client.Client',
22
+ }
23
+
24
+
25
+ # Required by the OSC plugin interface
26
+ def make_client(instance):
27
+ """Returns a client to the ClientManager
28
+
29
+ Called to instantiate the requested client version. instance has
30
+ any available auth info that may be required to prepare the client.
31
+
32
+ :param ClientManager instance: The ClientManager that owns the new client
33
+ """
34
+ return None
35
+
36
+
37
+ # Required by the OSC plugin interface
38
+ def build_option_parser(parser):
39
+ """Hook to add global options
40
+
41
+ Called from openstackclient.shell.OpenStackShell.__init__()
42
+ after the builtin parser has been initialized. This is
43
+ where a plugin can add global options such as an API version setting.
44
+
45
+ :param argparse.ArgumentParser parser: The parser object that has been
46
+ initialized by OpenStackShell.
47
+ """
48
+ return parser
nectar_osc/rating.py ADDED
@@ -0,0 +1,60 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+ # not use this file except in compliance with the License. You may obtain
3
+ # a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+ # License for the specific language governing permissions and limitations
11
+ # under the License.
12
+ #
13
+
14
+ import logging
15
+
16
+ from osc_lib.command import command
17
+ from osc_lib import utils as osc_utils
18
+ from oslo_config import cfg
19
+
20
+
21
+ CONF = cfg.CONF
22
+
23
+
24
+ class ListFlavors(command.Lister):
25
+ """List Flavors with rating."""
26
+
27
+ log = logging.getLogger(__name__ + '.ListFlavors')
28
+
29
+ def get_parser(self, prog_name):
30
+ parser = super().get_parser(prog_name)
31
+ parser.add_argument(
32
+ '--all', action='store_true', help=('Display All flavors')
33
+ )
34
+ return parser
35
+
36
+ def take_action(self, parsed_args):
37
+ self.log.debug('take_action(%s)', parsed_args)
38
+ compute_client = self.app.client_manager.compute
39
+ rating_client = self.app.client_manager.rating
40
+ flavor_kwargs = {}
41
+ if parsed_args.all:
42
+ flavor_kwargs['is_public'] = None
43
+ flavors = compute_client.flavors.list(**flavor_kwargs)
44
+ groups = rating_client.rating.hashmap.get_group()['groups']
45
+ group_id = None
46
+ for g in groups:
47
+ if g.get('name') == 'instance_uptime_flavor_id':
48
+ group_id = g.get('group_id')
49
+ break
50
+ mappings = rating_client.rating.hashmap.get_group_mappings(
51
+ group_id=group_id
52
+ )['mappings']
53
+ mappings = {m.get('value'): m.get('cost') for m in mappings}
54
+ for f in flavors:
55
+ f.rate = mappings.get(f.id)
56
+ columns = ['id', 'name', 'rate']
57
+ return (
58
+ columns,
59
+ (osc_utils.get_item_properties(f, columns) for f in flavors),
60
+ )
nectar_osc/security.py ADDED
@@ -0,0 +1,315 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+ # not use this file except in compliance with the License. You may obtain
3
+ # a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+ # License for the specific language governing permissions and limitations
11
+ # under the License.
12
+ #
13
+
14
+ import logging
15
+ import sys
16
+
17
+ from novaclient import exceptions as n_exc
18
+ from osc_lib.command import command
19
+ from oslo_config import cfg
20
+
21
+ from nectar_osc import compute
22
+ from nectar_osc import freshdesk
23
+ from nectar_osc import identity
24
+ from nectar_osc import network
25
+
26
+
27
+ CONF = cfg.CONF
28
+
29
+
30
+ class SecurityCommand(command.Command):
31
+ """security top class"""
32
+
33
+ def get_parser(self, prog_name):
34
+ parser = super().get_parser(prog_name)
35
+ parser.add_argument(
36
+ '--no-dry-run', action='store_true', help=('Really perform action')
37
+ )
38
+ parser.add_argument(
39
+ 'id', metavar='<instance_id>', help=('Instance uuid')
40
+ )
41
+
42
+ return parser
43
+
44
+
45
+ class LockInstance(SecurityCommand):
46
+ """pause and lock an instance"""
47
+
48
+ log = logging.getLogger(__name__ + '.Security.LockInstance')
49
+
50
+ def get_parser(self, prog_name):
51
+ parser = super().get_parser(prog_name)
52
+ parser.add_argument(
53
+ '--cc',
54
+ metavar='<email>',
55
+ help=('Extra email address to add to cc list'),
56
+ )
57
+ return parser
58
+
59
+ def take_action(self, parsed_args):
60
+ self.log.debug('take_action(%s)', parsed_args)
61
+ clients = self.app.client_manager
62
+
63
+ fd = freshdesk.get_client()
64
+
65
+ if not parsed_args.no_dry_run:
66
+ print('Running in dry-run mode (use --no-dry-run to action)')
67
+
68
+ try:
69
+ instance = clients.compute.servers.get(parsed_args.id)
70
+ except n_exc.NotFound:
71
+ print(f'Instance {parsed_args.id} not found')
72
+ sys.exit(1)
73
+
74
+ # Pause and lock instance
75
+ if not parsed_args.no_dry_run:
76
+ if instance.status != 'ACTIVE':
77
+ print(f'Instance state {instance.status}, will not pause')
78
+ else:
79
+ print(f'Would pause and lock instance {instance.id}')
80
+ else:
81
+ if instance.status != 'ACTIVE':
82
+ print(
83
+ f'Instance not in ACTIVE state ({instance.status}), '
84
+ 'skipping'
85
+ )
86
+ else:
87
+ print(f'Pausing instance {instance.id}')
88
+ instance.pause()
89
+
90
+ print(f'Locking instance {instance.id}')
91
+ instance.lock()
92
+
93
+ # Process ticket
94
+ ticket_id = None
95
+ ticket_url = instance.metadata.get('security_ticket')
96
+ if ticket_url:
97
+ print(f'Found existing ticket: {ticket_url}')
98
+ ticket_id = int(ticket_url.split('/')[-1])
99
+
100
+ if not parsed_args.no_dry_run:
101
+ print(f'Would set ticket #{ticket_id} status to open/urgent')
102
+ else:
103
+ # Set ticket status, priority and reply
104
+ print('Replying to ticket with action details')
105
+ action = (
106
+ f'Instance <b>{instance.name} ({instance.id})</b>'
107
+ ' has been <b>paused and '
108
+ 'locked</b>'
109
+ )
110
+ fd.comments.create_reply(ticket_id, action)
111
+ print(f'Setting ticket #{ticket_id} status to open/urgent')
112
+ fd.tickets.update_ticket(ticket_id, status=6, priority=4)
113
+ else:
114
+ project = clients.identity.projects.get(instance.tenant_id)
115
+ user = clients.identity.users.get(instance.user_id)
116
+ email = user.email or 'no-reply@nectar.org.au'
117
+ name = getattr(user, 'full_name', email)
118
+ cc_emails = identity.get_tenant_managers_emails(
119
+ clients.identity, instance
120
+ )
121
+ if parsed_args.cc:
122
+ cc_emails.append(parsed_args.cc)
123
+
124
+ # Create ticket if none exist, and add instance info
125
+ subject = (
126
+ f'Security incident for instance {instance.name} '
127
+ f'({instance.id})'
128
+ )
129
+ body = '<br />\n'.join(
130
+ [
131
+ 'Dear Nectar Research Cloud User, ',
132
+ '',
133
+ '',
134
+ 'We have reason to believe that cloud instance: '
135
+ f'<b>{instance.name} ({instance.id})</b>',
136
+ f'in the project <b>{project.name}</b>',
137
+ f'created by <b>{email}</b>',
138
+ 'has been involved in a security incident, ',
139
+ 'and has been locked.',
140
+ '',
141
+ 'We have opened this helpdesk ticket to track the ',
142
+ 'details and the progress of the resolution of this ',
143
+ 'issue.',
144
+ '',
145
+ 'Please reply to this email if you have any questions or ',
146
+ 'concerns.',
147
+ '',
148
+ 'Thanks, ',
149
+ 'Nectar Research Cloud Team',
150
+ ]
151
+ )
152
+
153
+ if not parsed_args.no_dry_run:
154
+ print('Would create ticket with details:')
155
+ print(f' To: {name} <{email}>')
156
+ print(f' CC: {", ".join(cc_emails)}')
157
+ print(f' Subject: {subject}')
158
+
159
+ print('Would add instance details to ticket:')
160
+ print(compute.show_instance(clients, instance.id))
161
+ print(
162
+ network.show_instance_security_groups(clients, instance.id)
163
+ )
164
+ else:
165
+ print('Creating new Freshdesk ticket')
166
+ ticket = fd.tickets.create_outbound_email(
167
+ name=name,
168
+ description=body,
169
+ subject=subject,
170
+ email=email,
171
+ cc_emails=cc_emails,
172
+ email_config_id=CONF.freshdesk.email_config_id,
173
+ group_id=CONF.freshdesk.group_id,
174
+ priority=4,
175
+ status=2,
176
+ tags=['security'],
177
+ )
178
+ ticket_id = ticket.id
179
+
180
+ # Use friendly domain name if using prod
181
+ if fd.domain == 'dhdnectar.freshdesk.com':
182
+ domain = 'support.ehelp.edu.au'
183
+ else:
184
+ domain = fd.domain
185
+
186
+ ticket_url = f'https://{domain}/helpdesk/tickets/{ticket_id}'
187
+ clients.compute.servers.set_meta(
188
+ instance.id, {'security_ticket': ticket_url}
189
+ )
190
+ print(f'Ticket #{ticket_id} has been created: {ticket_url}')
191
+
192
+ # Add a private note with instance details
193
+ print('Adding instance information to ticket')
194
+ instance_info = compute.show_instance(
195
+ clients, instance.id, style='html'
196
+ )
197
+ sg_info = network.show_instance_security_groups(
198
+ clients, instance.id, style='html'
199
+ )
200
+ body = '<br/><br/>'.join([instance_info, sg_info])
201
+ fd.comments.create_note(ticket_id, body)
202
+
203
+
204
+ class UnlockInstance(SecurityCommand):
205
+ """unlock an instance"""
206
+
207
+ log = logging.getLogger(__name__ + '.Security.UnlockInstance')
208
+
209
+ def take_action(self, parsed_args):
210
+ self.log.debug('take_action(%s)', parsed_args)
211
+ clients = self.app.client_manager
212
+
213
+ fd = freshdesk.get_client()
214
+
215
+ """unlock an instance"""
216
+ if not parsed_args.no_dry_run:
217
+ print('Running in dry-run mode (use --no-dry-run to action)')
218
+
219
+ try:
220
+ instance = clients.compute.servers.get(parsed_args.id)
221
+ except n_exc.NotFound:
222
+ print(f'Instance {parsed_args.id} not found')
223
+ sys.exit(1)
224
+
225
+ ticket_id = None
226
+ ticket_url = instance.metadata.get('security_ticket')
227
+ if ticket_url:
228
+ print(f'Found ticket: {ticket_url}')
229
+ ticket_id = int(ticket_url.split('/')[-1])
230
+ else:
231
+ if parsed_args.no_dry_run is True:
232
+ print('No ticket found in instance metadata!')
233
+ sys.exit(1)
234
+
235
+ if instance.status == 'PAUSED':
236
+ if not parsed_args.no_dry_run:
237
+ print(f'Would unpause and unlock instance {instance.id}')
238
+ print('Would reply to ticket')
239
+ print('Would resolve ticket')
240
+ else:
241
+ print(f'Unpausing instance {instance.id}')
242
+ instance.unpause()
243
+
244
+ print(f'Unlocking instance {instance.id}')
245
+ instance.unlock()
246
+
247
+ # Add reply to user
248
+ print('Replying to ticket with action details')
249
+ action = (
250
+ f'Instance <b>{instance.name} ({instance.id})</b>'
251
+ ' has been <b>unpaused and unlocked</b>'
252
+ )
253
+ fd.comments.create_reply(ticket_id, action)
254
+
255
+ # Set ticket status=resolved
256
+ print(f'Setting ticket #{ticket_id} status to resolved')
257
+ fd.tickets.update_ticket(ticket_id, status=4)
258
+ else:
259
+ print(f"Instance {ticket_id} is not locked, won't unlock")
260
+
261
+
262
+ class DeleteInstance(SecurityCommand):
263
+ """delete an instance"""
264
+
265
+ log = logging.getLogger(__name__ + '.Security.DeleteInstance')
266
+
267
+ def take_action(self, parsed_args):
268
+ self.log.debug('take_action(%s)', parsed_args)
269
+ clients = self.app.client_manager
270
+
271
+ fd = freshdesk.get_client()
272
+
273
+ """delete an instance"""
274
+ if not parsed_args.no_dry_run:
275
+ print('Running in dry-run mode (use --no-dry-run to action)')
276
+
277
+ try:
278
+ instance = clients.compute.servers.get(parsed_args.id)
279
+ except n_exc.NotFound:
280
+ print(f'Instance {parsed_args.id} not found')
281
+ sys.exit(1)
282
+
283
+ ticket_id = None
284
+ ticket_url = instance.metadata.get('security_ticket')
285
+ if ticket_url:
286
+ print(f'Found ticket: {ticket_url}')
287
+ ticket_id = int(ticket_url.split('/')[-1])
288
+ else:
289
+ if parsed_args.no_dry_run is True:
290
+ print('No ticket found in instance metadata!')
291
+ sys.exit(1)
292
+
293
+ # DELETE!!!
294
+ if instance.status == 'PAUSED':
295
+ if not parsed_args.no_dry_run:
296
+ print(f'Would delete instance {instance.id}')
297
+ print('Would reply to ticket')
298
+ print('Would resolve ticket')
299
+ else:
300
+ print(f'Deleting instance {instance.id})')
301
+ instance.delete()
302
+
303
+ # Add reply to user
304
+ print('Updating ticket with action')
305
+ action = (
306
+ f'Instance <b>{instance.name} ({instance.id})</b>'
307
+ ' has been <b>deleted.</b>'
308
+ )
309
+ fd.comments.create_reply(ticket_id, action)
310
+
311
+ # Set ticket status=resolved
312
+ print(f'Resolving ticket #{ticket_id}')
313
+ fd.tickets.update_ticket(ticket_id, status=4)
314
+ else:
315
+ print(f"Instance {instance.id} is not locked, won't delete")
nectar_osc/show.py ADDED
@@ -0,0 +1,69 @@
1
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+ # not use this file except in compliance with the License. You may obtain
3
+ # a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+ # License for the specific language governing permissions and limitations
11
+ # under the License.
12
+ #
13
+
14
+ import logging
15
+ import sys
16
+
17
+ from novaclient import exceptions as n_exc
18
+ from osc_lib.command import command
19
+
20
+ from nectar_osc import compute
21
+ from nectar_osc import network
22
+
23
+
24
+ class ShowCommand(command.Command):
25
+ """show top class"""
26
+
27
+ def get_parser(self, prog_name):
28
+ parser = super().get_parser(prog_name)
29
+ parser.add_argument(
30
+ 'id', metavar='<server>', help=('Server (name or ID)')
31
+ )
32
+
33
+ return parser
34
+
35
+
36
+ class ShowInstance(ShowCommand):
37
+ """show instance details"""
38
+
39
+ log = logging.getLogger(__name__ + '.Show.ShowInstance')
40
+
41
+ def take_action(self, parsed_args):
42
+ self.log.debug('take_action(%s)', parsed_args)
43
+ clients = self.app.client_manager
44
+
45
+ try:
46
+ instance = clients.compute.servers.get(parsed_args.id)
47
+ except n_exc.NotFound:
48
+ print(f'Server {parsed_args.id} not found')
49
+ sys.exit(1)
50
+
51
+ print(compute.show_instance(clients, instance.id))
52
+
53
+
54
+ class ShowSecuritygroups(ShowCommand):
55
+ """show instance security group details"""
56
+
57
+ log = logging.getLogger(__name__ + '.Show.ShowSecuritygroups')
58
+
59
+ def take_action(self, parsed_args):
60
+ self.log.debug('take_action(%s)', parsed_args)
61
+ clients = self.app.client_manager
62
+
63
+ try:
64
+ instance = clients.compute.servers.get(parsed_args.id)
65
+ except n_exc.NotFound:
66
+ print(f'Server {parsed_args.id} not found')
67
+ sys.exit(1)
68
+
69
+ print(network.show_instance_security_groups(clients, instance.id))
@@ -0,0 +1,176 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
@@ -0,0 +1,32 @@
1
+ Metadata-Version: 2.1
2
+ Name: nectar-osc
3
+ Version: 1.0.0
4
+ Summary: OpenStack client plugin for misc Nectar tooling
5
+ Home-page: https://github.com/NeCTAR-RC/python-nectar-osc
6
+ Author: ARDC Nectar Cloud Services
7
+ Author-email: coreservices@ardc.edu.au
8
+ License: Apache-2.0
9
+ Keywords: varroa
10
+ Classifier: Environment :: OpenStack
11
+ Classifier: Intended Audience :: Information Technology
12
+ Classifier: Intended Audience :: System Administrators
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ License-File: LICENSE
21
+ Requires-Dist: oslo.config
22
+ Requires-Dist: oslo.utils
23
+ Requires-Dist: osc-lib
24
+ Requires-Dist: python-freshdesk
25
+ Requires-Dist: python-openstackclient
26
+ Requires-Dist: python-neutronclient
27
+ Requires-Dist: pbr>=3.0.0
28
+
29
+ # Nectar Openstack Client Plugin
30
+
31
+ Provides some helpers for nectar cloud.
32
+
@@ -0,0 +1,17 @@
1
+ nectar_osc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ nectar_osc/compute.py,sha256=9q9OXimI6Ae8_P6koRKksJKoAumCSXPLDaYwf_y-4R0,3809
3
+ nectar_osc/config.py,sha256=2I1_6O0G-G5ntyAjZ2awh3Q_oPe36blVxxMRi4_-mR0,1798
4
+ nectar_osc/freshdesk.py,sha256=WzH6PHxFcyNz5LWQf2jT4zUdPNJwVSV2409c6ohdyA8,1659
5
+ nectar_osc/identity.py,sha256=1D7h8aS4lWnXx9xZ3OYCRpwL21JuB-JAvokwx5lQ6Y4,1030
6
+ nectar_osc/network.py,sha256=CzTdzyGnkIi1oa_Q8A2aGFRVztjBRybbTvWhV_wGSzI,3789
7
+ nectar_osc/plugin.py,sha256=zo9jdrhdKqzkE1jH4Y9UhwY1lCERWKg632-LsBWVfrY,1549
8
+ nectar_osc/rating.py,sha256=5nez4Le3HgvEgMshyvPRvj-QFhji1k9I_0XlDa40AMA,2084
9
+ nectar_osc/security.py,sha256=_UVAzNU_qjS-p702L_DBt0GQ-WBKO4cUHpdkmEcKItU,11554
10
+ nectar_osc/show.py,sha256=OLfxysAv8WgG_jAuuTiYIKi4aDId-Wg0-kMIRx0m6BQ,2093
11
+ nectar_osc-1.0.0.dist-info/LICENSE,sha256=XfKg2H1sVi8OoRxoisUlMqoo10TKvHmU_wU39ks7MyA,10143
12
+ nectar_osc-1.0.0.dist-info/METADATA,sha256=60YwjSaiAccBiHv8abQXbKrFxCssWoSV1n2wsFOrr_o,1093
13
+ nectar_osc-1.0.0.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
14
+ nectar_osc-1.0.0.dist-info/entry_points.txt,sha256=heMhpO1n6fFVP4mas8DKUjwHakpuMgjD3ehJ0WLTLQE,511
15
+ nectar_osc-1.0.0.dist-info/pbr.json,sha256=E-9l_DOHMyCWoh8QgZAvuvgU5FjQXlaXqe_H4KPOt6s,46
16
+ nectar_osc-1.0.0.dist-info/top_level.txt,sha256=WFMtCn5VNuvseahg_hiry5fqRoLwnsnHQvQuHAj4cmQ,11
17
+ nectar_osc-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,13 @@
1
+ [openstack.cli.extension]
2
+ nectar = nectar_osc.osc.plugin
3
+
4
+ [openstack.nectar.v1]
5
+ nectar flavor list = nectar_osc.rating:ListFlavors
6
+ nectar security instance delete = nectar_osc.security:DeleteInstance
7
+ nectar security instance lock = nectar_osc.security:LockInstance
8
+ nectar security instance unlock = nectar_osc.security:UnlockInstance
9
+ nectar server securitygroups = nectar_osc.show:ShowSecuritygroups
10
+ nectar server show = nectar_osc.show:ShowInstance
11
+
12
+ [oslo.config.opts]
13
+ nectar_osc = nectar_osc.config:list_opts
@@ -0,0 +1 @@
1
+ {"git_version": "c7e762b", "is_release": true}
@@ -0,0 +1 @@
1
+ nectar_osc