-
Notifications
You must be signed in to change notification settings - Fork 227
/
models.py
2213 lines (1867 loc) · 84.5 KB
/
models.py
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2010-2011 OpenStack Foundation
# Copyright 2013-2014 Rackspace Hosting
# 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.
"""Model classes that form the core of instances functionality."""
import base64
import json
import os.path
import re
from datetime import datetime
from datetime import timedelta
from novaclient import exceptions as nova_exceptions
from oslo_config.cfg import NoSuchOptError
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import netutils
from sqlalchemy import func
from trove.backup.models import Backup
from trove.common import cfg
from trove.common import clients
from trove.common import crypto_utils as cu
from trove.common import exception
from trove.common.i18n import _
from trove.common import neutron
from trove.common import notification
from trove.common import server_group as srv_grp
from trove.common import template
from trove.common import timeutils
from trove.common.trove_remote import create_trove_client
from trove.common import utils
from trove.configuration.models import Configuration
from trove.datastore import models as datastore_models
from trove.datastore.models import DatastoreVersionMetadata as dvm
from trove.datastore.models import DBDatastoreVersionMetadata
from trove.db import get_db_api
from trove.db import models as dbmodels
from trove.extensions.security_group.models import SecurityGroup
from trove.instance import service_status as srvstatus
from trove.instance.tasks import InstanceTask
from trove.instance.tasks import InstanceTasks
from trove.module import models as module_models
from trove.module import views as module_views
from trove.quota.quota import run_with_quotas
from trove.taskmanager import api as task_api
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
# Invalid states to contact the agent
AGENT_INVALID_STATUSES = ["BUILD", "REBOOT", "RESIZE", "PROMOTE", "EJECT",
"UPGRADE"]
def ip_visible(ip, white_list_regex, black_list_regex):
if re.search(white_list_regex, ip) and not re.search(black_list_regex, ip):
return True
return False
def load_server(context, instance_id, server_id, region_name):
"""
Loads a server or raises an exception.
:param context: request context used to access nova
:param instance_id: the trove instance id corresponding to the nova server
(informational only)
:param server_id: the compute instance id which will be retrieved from nova
:type context: trove.common.context.TroveContext
:type instance_id: unicode
:type server_id: unicode
:rtype: novaclient.v2.servers.Server
"""
client = clients.create_nova_client(context, region_name=region_name)
try:
server = client.servers.get(server_id)
except nova_exceptions.NotFound:
LOG.error("Could not find nova server_id(%s).", server_id)
raise exception.ComputeInstanceNotFound(instance_id=instance_id,
server_id=server_id)
except nova_exceptions.ClientException as e:
raise exception.TroveError(str(e))
return server
class InstanceStatus(object):
HEALTHY = "HEALTHY"
ACTIVE = "ACTIVE"
BLOCKED = "BLOCKED"
BUILD = "BUILD"
FAILED = "FAILED"
REBOOT = "REBOOT"
RESIZE = "RESIZE"
BACKUP = "BACKUP"
SHUTDOWN = "SHUTDOWN"
ERROR = "ERROR"
RESTART_REQUIRED = "RESTART_REQUIRED"
PROMOTE = "PROMOTE"
EJECT = "EJECT"
UPGRADE = "UPGRADE"
DETACH = "DETACH"
def validate_volume_size(size):
if size is None:
raise exception.VolumeSizeNotSpecified()
max_size = CONF.max_accepted_volume_size
if int(size) > max_size:
msg = ("Volume 'size' cannot exceed maximum "
"of %d GB, %s cannot be accepted."
% (max_size, size))
raise exception.VolumeQuotaExceeded(msg)
def load_simple_instance_server_status(context, db_info):
"""Loads a server or raises an exception."""
if 'BUILDING' == db_info.task_status.action:
db_info.server_status = "BUILD"
else:
client = clients.create_nova_client(context, db_info.region_id)
try:
server = client.servers.get(db_info.compute_instance_id)
db_info.server_status = server.status
except nova_exceptions.NotFound:
db_info.server_status = "SHUTDOWN"
def load_simple_instance_addresses(context, db_info):
"""Get addresses of the instance from Neutron."""
if 'BUILDING' == db_info.task_status.action and not db_info.cluster_id:
db_info.addresses = []
return
addresses = []
user_ports = []
client = clients.create_neutron_client(context, db_info.region_id)
ports = neutron.get_instance_ports(client, db_info.compute_instance_id)
for port in ports:
if port['network_id'] not in CONF.management_networks:
LOG.debug('Found user port %s for instance %s', port['id'],
db_info.id)
user_ports.append(port['id'])
for ip in port['fixed_ips']:
# TODO(lxkong): IPv6 is not supported
if netutils.is_valid_ipv4(ip.get('ip_address')):
addresses.append(
{
'address': ip['ip_address'],
'type': 'private',
'network': port['network_id']
}
)
fips = neutron.get_port_fips(client, port['id'])
if len(fips) == 0:
continue
fip = fips[0]
addresses.append(
{'address': fip['floating_ip_address'], 'type': 'public'})
db_info.ports = user_ports
db_info.addresses = addresses
class SimpleInstance(object):
"""A simple view of an instance.
This gets loaded directly from the local database, so its cheaper than
creating the fully loaded Instance. As the name implies this class knows
nothing of the underlying Nova Compute Instance (i.e. server)
-----------
| |
| i |
| t n |
| r s ---------------------
| o t | datastore/guest |
| v a ---------------------
| e n |
| c |
| e |
| |
-----------
"""
def __init__(self, context, db_info, datastore_status, root_password=None,
ds_version=None, ds=None, locality=None):
"""
:type context: trove.common.context.TroveContext
:type db_info: trove.instance.models.DBInstance
:type datastore_status: trove.instance.models.InstanceServiceStatus
:type root_password: str
"""
self.context = context
self.db_info = db_info
self.datastore_status = datastore_status
self.root_pass = root_password
self._fault = None
self._fault_loaded = False
self.ds_version = None
self.ds = None
self.locality = locality
self.slave_list = None
if ds_version is None and self.db_info.datastore_version_id:
self.ds_version = (datastore_models.DatastoreVersion.
load_by_uuid(self.db_info.datastore_version_id))
if ds is None and self.ds_version:
self.ds = (datastore_models.Datastore.
load(self.ds_version.datastore_id))
def __repr__(self, *args, **kwargs):
return "%s(%s)" % (self.name, self.id)
@property
def addresses(self):
if hasattr(self.db_info, 'addresses'):
return self.db_info.addresses
else:
return None
@property
def ports(self):
if hasattr(self.db_info, 'ports'):
return self.db_info.ports
else:
return None
@property
def created(self):
return self.db_info.created
@property
def dns_ip_address(self):
"""Returns the IP address to be used with DNS."""
ips = self.get_visible_ip_addresses()
if ips:
# FIXME
return ips[0]
@property
def flavor_id(self):
# Flavor ID is a str in the 1.0 API.
return str(self.db_info.flavor_id)
@property
def hostname(self):
return self.db_info.hostname
def get_visible_ip_addresses(self):
"""Returns IPs that will be visible to the user."""
if not self.addresses:
return None
IPs = []
for address in self.addresses:
if CONF.ip_regex and CONF.black_list_regex:
if not ip_visible(address['address'], CONF.ip_regex,
CONF.black_list_regex):
continue
IPs.append(address)
return IPs
@property
def id(self):
return self.db_info.id
@property
def type(self):
return self.db_info.type
@property
def tenant_id(self):
return self.db_info.tenant_id
@property
def is_building(self):
return self.status in [InstanceStatus.BUILD]
@property
def is_error(self):
return self.status in [InstanceStatus.ERROR]
@property
def is_datastore_running(self):
"""True if the service status indicates datastore is up and running."""
return self.datastore_status.status in MYSQL_RESPONSIVE_STATUSES
def datastore_status_matches(self, service_status):
return self.datastore_status.status == service_status
@property
def name(self):
return self.db_info.name
@property
def server_id(self):
return self.db_info.compute_instance_id
@property
def slave_of_id(self):
return self.db_info.slave_of_id
@property
def datastore_status(self):
"""
Returns the Service Status for this instance. For example, the status
of the mysql datastore which is running on the server...not the server
status itself.
:return: the current status of the datastore
:rtype: trove.instance.models.InstanceServiceStatus
"""
return self.__datastore_status
@datastore_status.setter
def datastore_status(self, datastore_status):
if datastore_status and not isinstance(datastore_status,
InstanceServiceStatus):
raise ValueError(_("datastore_status must be of type "
"InstanceServiceStatus. Got %s instead.") %
datastore_status.__class__.__name__)
self.__datastore_status = datastore_status
@property
def operating_status(self):
"""operating_status is the database service status."""
task_status = self.db_info.task_status
server_status = self.db_info.server_status
ds_status = self.datastore_status.status
if (task_status != InstanceTasks.NONE or server_status != 'ACTIVE'):
return ""
return repr(ds_status)
@property
def status(self):
"""The server status of the database instance.
- The task action is considered first.
- If it's performing backup or not.
- Then server status
- Otherwise, unknown
"""
LOG.debug(f"Getting instance status for {self.id}, "
f"task status: {self.db_info.task_status}, "
f"datastore status: {self.datastore_status.status}, "
f"server status: {self.db_info.server_status}")
task_status = self.db_info.task_status
server_status = self.db_info.server_status
# Check for taskmanager errors.
if task_status.is_error:
return InstanceStatus.ERROR
action = task_status.action
# Check for taskmanager status.
if InstanceTasks.BUILDING.action == action:
if 'ERROR' == server_status:
return InstanceStatus.ERROR
return InstanceStatus.BUILD
if InstanceTasks.REBOOTING.action == action:
return InstanceStatus.REBOOT
if InstanceTasks.RESIZING.action == action:
return InstanceStatus.RESIZE
if InstanceTasks.UPGRADING.action == action:
return InstanceStatus.UPGRADE
if InstanceTasks.RESTART_REQUIRED.action == action:
return InstanceStatus.RESTART_REQUIRED
if InstanceTasks.PROMOTING.action == action:
return InstanceStatus.PROMOTE
if InstanceTasks.EJECTING.action == action:
return InstanceStatus.EJECT
if InstanceTasks.LOGGING.action == action:
return InstanceStatus.LOGGING
if InstanceTasks.DETACHING.action == action:
return InstanceStatus.DETACH
# Report as Shutdown while deleting, unless there's an error.
if InstanceTasks.DELETING.action == action:
if server_status in ["ACTIVE", "SHUTDOWN", "DELETED"]:
return InstanceStatus.SHUTDOWN
else:
LOG.error("While shutting down instance (%(instance)s): "
"server had status (%(status)s).",
{'instance': self.id, 'status': server_status})
return InstanceStatus.ERROR
# Check if there is a backup running for this instance
if Backup.running(self.id):
return InstanceStatus.BACKUP
# Check for server status.
if server_status in ["BUILD", "ERROR", "REBOOT", "RESIZE", "ACTIVE",
"SHUTDOWN"]:
return server_status
# As far as Trove is concerned, Nova instances in VERIFY_RESIZE should
# still appear as though they are in RESIZE.
if server_status in ["VERIFY_RESIZE"]:
return InstanceStatus.RESIZE
return "UNKNOWN"
@property
def updated(self):
return self.db_info.updated
@property
def service_status_updated(self):
return self.datastore_status.updated_at
@property
def volume_id(self):
return self.db_info.volume_id
@property
def volume_size(self):
return self.db_info.volume_size
@property
def datastore_version(self):
return self.ds_version
@property
def datastore(self):
return self.ds
@property
def volume_support(self):
if self.datastore_version:
return CONF.get(self.datastore_version.manager).volume_support
return None
@property
def device_path(self):
if self.datastore_version:
return CONF.get(self.datastore_version.manager).device_path
return None
@property
def root_password(self):
return self.root_pass
@property
def fault(self):
# Fault can be non-existent, so we have a loaded flag
if not self._fault_loaded:
try:
self._fault = DBInstanceFault.find_by(instance_id=self.id)
# Get rid of the stack trace if we're not admin
if not self.context.is_admin:
self._fault.details = None
except exception.ModelNotFoundError:
pass
self._fault_loaded = True
return self._fault
@property
def configuration(self):
if self.db_info.configuration_id is not None:
return Configuration.load(self.context,
self.db_info.configuration_id)
@property
def slaves(self):
if self.slave_list is None:
self.slave_list = DBInstance.find_all(tenant_id=self.tenant_id,
slave_of_id=self.id,
deleted=False).all()
return self.slave_list
@property
def cluster_id(self):
return self.db_info.cluster_id
@property
def shard_id(self):
return self.db_info.shard_id
@property
def region_name(self):
return self.db_info.region_id
@property
def encrypted_rpc_messaging(self):
return True if self.db_info.encrypted_key is not None else False
@property
def access(self):
if hasattr(self.db_info, 'access'):
if type(self.db_info.access) == str:
return json.loads(self.db_info.access)
return self.db_info.access
else:
return None
class DetailInstance(SimpleInstance):
"""A detailed view of an Instance.
This loads a SimpleInstance and then adds additional data for the
instance from the guest.
"""
def __init__(self, context, db_info, datastore_status):
super(DetailInstance, self).__init__(context, db_info,
datastore_status)
self._volume_used = None
self._volume_total = None
@property
def volume_used(self):
return self._volume_used
@volume_used.setter
def volume_used(self, value):
self._volume_used = value
@property
def volume_total(self):
return self._volume_total
@volume_total.setter
def volume_total(self, value):
self._volume_total = value
def get_db_info(context, id, cluster_id=None, include_deleted=False):
"""
Retrieves an instance of the managed datastore from the persisted
storage based on the ID and Context
:param context: the context which owns the instance
:type context: trove.common.context.TroveContext
:param id: the unique ID of the instance
:type id: unicode or str
:param cluster_id: the unique ID of the cluster
:type cluster_id: unicode or str
:return: a record of the instance as its state exists in persisted storage
:rtype: trove.instance.models.DBInstance
"""
if context is None:
raise TypeError(_("Argument context not defined."))
elif id is None:
raise TypeError(_("Argument id not defined."))
args = {'id': id}
if cluster_id is not None:
args['cluster_id'] = cluster_id
if not include_deleted:
args['deleted'] = False
try:
db_info = DBInstance.find_by(context=context, **args)
except exception.NotFound:
raise exception.NotFound(uuid=id)
return db_info
def load_any_instance(context, id, load_server=True):
# Try to load an instance with a server.
# If that fails, try to load it without the server.
try:
return load_instance(BuiltInstance, context, id,
needs_server=load_server)
except exception.UnprocessableEntity:
LOG.warning("Could not load instance %s.", id)
return load_instance(FreshInstance, context, id, needs_server=False)
def load_instance(cls, context, id, needs_server=False,
include_deleted=False):
db_info = get_db_info(context, id, include_deleted=include_deleted)
if not needs_server:
# TODO(tim.simpson): When we have notifications this won't be
# necessary and instead we'll just use the server_status field from
# the instance table.
load_simple_instance_server_status(context, db_info)
load_simple_instance_addresses(context, db_info)
server = None
else:
try:
server = load_server(context, db_info.id,
db_info.compute_instance_id,
region_name=db_info.region_id)
db_info.server_status = server.status
load_simple_instance_addresses(context, db_info)
except exception.ComputeInstanceNotFound:
LOG.error("Could not load compute instance %s.",
db_info.compute_instance_id)
raise exception.UnprocessableEntity("Instance %s is not ready." %
id)
service_status = InstanceServiceStatus.find_by(instance_id=id)
LOG.debug("Instance %(instance_id)s service status is %(service_status)s.",
{'instance_id': id, 'service_status': service_status.status})
return cls(context, db_info, server, service_status)
def update_service_status(task_status, service_status, ins_id):
"""Update service status as needed."""
RESTART_REQUIRED = srvstatus.ServiceStatuses.RESTART_REQUIRED
if (task_status == InstanceTasks.NONE and
service_status.status != RESTART_REQUIRED and
not service_status.is_uptodate()):
LOG.warning('Guest agent heartbeat for instance %s has expried',
ins_id)
service_status.status = \
srvstatus.ServiceStatuses.FAILED_TIMEOUT_GUESTAGENT
def load_instance_with_info(cls, context, ins_id, cluster_id=None):
db_info = get_db_info(context, ins_id, cluster_id)
service_status = InstanceServiceStatus.find_by(instance_id=ins_id)
update_service_status(db_info.task_status, service_status, ins_id)
load_simple_instance_server_status(context, db_info)
load_simple_instance_addresses(context, db_info)
instance = cls(context, db_info, service_status)
load_guest_info(instance, context, ins_id)
load_server_group_info(instance, context)
return instance
def load_guest_info(instance, context, id):
if instance.status not in AGENT_INVALID_STATUSES:
guest = clients.create_guest_client(context, id)
try:
volume_info = guest.get_volume_info()
instance.volume_used = volume_info['used']
instance.volume_total = volume_info['total']
except Exception as e:
LOG.exception(e)
return instance
def load_server_group_info(instance, context):
instance_id = instance.slave_of_id if instance.slave_of_id else instance.id
server_group = srv_grp.ServerGroup.load(context, instance_id)
if server_group:
instance.locality = srv_grp.ServerGroup.get_locality(server_group)
class BaseInstance(SimpleInstance):
"""Represents an instance.
-----------
| |
| i ---------------------
| t n | compute instance |
| r s ---------------------
| o t |
| v a |
| e n ---------------------
| c | datastore/guest |
| e ---------------------
| |
-----------
"""
def __init__(self, context, db_info, server, datastore_status):
"""
Creates a new initialized representation of an instance composed of its
state in the database and its state from Nova
:param context: the request context which contains the tenant that owns
this instance
:param db_info: the current state of this instance as it exists in the
db
:param server: the current state of this instance as it exists in the
Nova
:param datastore_status: the current state of the datastore on this
instance at it exists in the db
:type context: trove.common.context.TroveContext
:type db_info: trove.instance.models.DBInstance
:type server: novaclient.v2.servers.Server
:typdatastore_statusus: trove.instance.models.InstanceServiceStatus
"""
super(BaseInstance, self).__init__(context, db_info, datastore_status)
self.server = server
self._guest = None
self._nova_client = None
self._volume_client = None
self._neutron_client = None
self._server_group = None
self._server_group_loaded = False
def get_guest(self):
return clients.create_guest_client(self.context, self.db_info.id)
def delete(self):
def _delete_resources():
if self.is_building:
raise exception.UnprocessableEntity(
"Instance %s is not ready. (Status is %s)." %
(self.id, self.status))
LOG.debug("Deleting instance with compute id = %s.",
self.db_info.compute_instance_id)
from trove.cluster.models import is_cluster_deleting
if (self.db_info.cluster_id is not None and not
is_cluster_deleting(context=self.context,
cluster_id=self.db_info.cluster_id)):
raise exception.ClusterInstanceOperationNotSupported()
if self.slaves:
LOG.warning("Detach replicas before deleting replica source.")
raise exception.ReplicaSourceDeleteForbidden(
_("Detach replicas before deleting replica source."))
self.update_db(task_status=InstanceTasks.DELETING,
configuration_id=None)
task_api.API(self.context).delete_instance(self.id)
flavor = self.get_flavor()
deltas = {'instances': -1, 'ram': -flavor.ram}
if self.volume_support:
deltas['volumes'] = -self.volume_size
return run_with_quotas(self.tenant_id,
deltas,
_delete_resources)
def server_status_matches(self, expected_status, server=None):
if not server:
server = self.server
return server.status.upper() in (
status.upper() for status in expected_status)
def _delete_resources(self, deleted_at):
"""Delete the openstack resources related to an instance.
Deleting the instance should not break or raise exceptions because
the end users want their instances to be deleted anyway. Cloud operator
should consider the way to clean up orphan resources afterwards, e.g.
using the naming convention.
"""
LOG.info("Starting to delete resources for instance %s", self.id)
old_server = None
if self.server_id:
# Stop db
try:
old_server = self.nova_client.servers.get(self.server_id)
# The server may have already been marked as 'SHUTDOWN'
# but check for 'ACTIVE' in case of any race condition
# We specifically don't want to attempt to stop db if
# the server is in 'ERROR' or 'FAILED" state, as it will
# result in a long timeout
if self.server_status_matches(['ACTIVE', 'SHUTDOWN'],
server=self):
LOG.debug("Stopping datastore on instance %s before "
"deleting any resources.", self.id)
self.guest.stop_db()
except Exception as e:
LOG.warning("Failed to stop the database before attempting "
"to delete trove instance %s, error: %s", self.id,
str(e))
# Nova VM
if old_server:
try:
LOG.info("Deleting server for instance %s", self.id)
self.server.delete()
except Exception as e:
LOG.warning("Failed to delete compute server %s",
self.server_id, str(e))
# Neutron ports (floating IP)
try:
ret = self.neutron_client.list_ports(name='trove-%s' % self.id)
ports = ret.get("ports", [])
for port in ports:
LOG.info("Deleting port %s for instance %s", port["id"],
self.id)
neutron.delete_port(self.neutron_client, port["id"])
except Exception as e:
LOG.warning("Failed to delete ports for instance %s, "
"error: %s", self.id, str(e))
# Neutron security groups
try:
name = "%s-%s" % (CONF.trove_security_group_name_prefix, self.id)
ret = self.neutron_client.list_security_groups(name=name)
sgs = ret.get("security_groups", [])
for sg in sgs:
LOG.info("Deleting security group %s for instance %s",
sg["id"], self.id)
self.neutron_client.delete_security_group(sg["id"])
except Exception as e:
LOG.warning("Failed to delete security groups for instance %s, "
"error: %s", self.id, str(e))
# DNS resources, e.g. Designate
try:
dns_support = CONF.trove_dns_support
if dns_support:
dns_api = clients.create_dns_client(self.context)
dns_api.delete_instance_entry(instance_id=self.id)
except Exception as e:
LOG.warning("Failed to delete dns entry of instance %s, error: %s",
self.id, str(e))
# Nova server group
try:
srv_grp.ServerGroup.delete(self.context, self.server_group)
except Exception as e:
LOG.warning("Failed to delete server group for %s, error: %s",
self.id, str(e))
def server_is_finished():
try:
server = self.nova_client.servers.get(self.server_id)
LOG.debug(f"Compute server {self.server_id} status "
f"{server.status}")
return False
except nova_exceptions.NotFound:
return True
if old_server:
try:
LOG.info("Waiting for compute server %s removal for "
"instance %s", self.server_id, self.id)
utils.poll_until(server_is_finished, sleep_time=2,
time_out=CONF.server_delete_time_out)
except exception.PollTimeOut:
LOG.warning("Failed to delete instance %(instance_id)s: "
"Timeout deleting compute server %(vm_id)s",
{'instance_id': self.id, 'vm_id': self.server_id})
# Cinder volume.
vols = self.volume_client.volumes.list(
search_opts={'name': f'trove-{self.id}'})
for vol in vols:
LOG.info(f"Deleting volume {vol.id} for instance {self.id}")
try:
vol.delete()
except Exception as e:
LOG.warning(f"Failed to delete volume {vol.id}({vol.status}) "
f"for instance {self.id}, error: {str(e)}")
notification.TroveInstanceDelete(
instance=self,
deleted_at=timeutils.isotime(deleted_at),
server=old_server
).notify()
LOG.info("Finished to delete resources for instance %s", self.id)
def delete_async(self):
deleted_at = timeutils.utcnow()
self._delete_resources(deleted_at)
LOG.debug("Setting instance %s to be deleted.", self.id)
# Also set FOREIGN KEY fields to NULL
self.update_db(deleted=True, deleted_at=deleted_at,
task_status=InstanceTasks.NONE,
datastore_version_id=None,
configuration_id=None,
slave_of_id=None,
cluster_id=None)
self.set_servicestatus_deleted()
self.set_instance_fault_deleted()
if CONF.trove_security_groups_support:
# Delete associated security group for backward compatibility
SecurityGroup.delete_for_instance(self.db_info.id, self.context,
self.db_info.region_id)
@property
def guest(self):
if not self._guest:
self._guest = self.get_guest()
return self._guest
@property
def nova_client(self):
if not self._nova_client:
self._nova_client = clients.create_nova_client(
self.context, region_name=self.db_info.region_id)
return self._nova_client
def update_db(self, **values):
self.db_info = DBInstance.find_by(id=self.id, deleted=False)
if 'access' in values and type(values['access'] != str):
values['access'] = json.dumps(values['access'])
for key in values:
setattr(self.db_info, key, values[key])
self.db_info.save()
def set_servicestatus_deleted(self):
del_instance = InstanceServiceStatus.find_by(instance_id=self.id)
del_instance.set_status(srvstatus.ServiceStatuses.DELETED)
del_instance.save()
def set_servicestatus_restart(self):
del_instance = InstanceServiceStatus.find_by(instance_id=self.id)
del_instance.set_status(srvstatus.ServiceStatuses.RESTARTING)
del_instance.save()
def set_instance_fault_deleted(self):
try:
del_fault = DBInstanceFault.find_by(instance_id=self.id)
del_fault.deleted = True
del_fault.deleted_at = datetime.utcnow()
del_fault.save()
except exception.ModelNotFoundError:
pass
def get_flavor(self):
return self.nova_client.flavors.get(self.flavor_id)
@property
def volume_client(self):
if not self._volume_client:
self._volume_client = clients.create_cinder_client(
self.context, region_name=self.db_info.region_id)
return self._volume_client
@property
def neutron_client(self):
if not self._neutron_client:
self._neutron_client = clients.create_neutron_client(
self.context, region_name=self.db_info.region_id)
return self._neutron_client
@property
def user_neutron_client(self):
if not self._user_neutron_client:
self._user_neutron_client = clients.neutron_client(
self.context, region_name=self.db_info.region_id)
return self._user_neutron_client
def reset_task_status(self):
self.update_db(task_status=InstanceTasks.NONE)
@property
def server_group(self):
# The server group could be empty, so we need a flag to cache it
if not self._server_group_loaded:
self._server_group = srv_grp.ServerGroup.load(self.context,
self.id)
self._server_group_loaded = True
return self._server_group
def prepare_cloud_config(self, files):
# This method returns None if the files argument is None
userdata = None
if files:
userdata = (
"#cloud-config\n"
"write_files:\n"
)
injected_config_owner = CONF.get('injected_config_owner')
injected_config_group = CONF.get('injected_config_group')
for filename, content in files.items():
ud = encodeutils.safe_encode(content)
body_userdata = (
"- encoding: b64\n"
" owner: %s:%s\n"
" path: %s\n"
" content: %s\n" % (
injected_config_owner, injected_config_group, filename,
encodeutils.safe_decode(base64.b64encode(ud)))
)
userdata = userdata + body_userdata
return userdata if userdata else ""
def get_injected_files(self,
datastore_manager,
datastore_version,
**kwargs):
injected_config_location = CONF.get('injected_config_location')
guest_info = CONF.get('guest_info')