/
service.py
2422 lines (2062 loc) · 101 KB
/
service.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
#
# 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.
import collections
import datetime
import functools
import itertools
import os
import pydoc
import signal
import socket
import sys
import eventlet
from oslo_config import cfg
from oslo_context import context as oslo_context
from oslo_log import log as logging
import oslo_messaging as messaging
from oslo_serialization import jsonutils
from oslo_service import service
from oslo_service import threadgroup
from oslo_utils import timeutils
from oslo_utils import uuidutils
from osprofiler import profiler
import webob
from heat.common import context
from heat.common import environment_format as env_fmt
from heat.common import environment_util as env_util
from heat.common import exception
from heat.common.i18n import _
from heat.common import identifier
from heat.common import messaging as rpc_messaging
from heat.common import policy
from heat.common import service_utils
from heat.engine import api
from heat.engine import attributes
from heat.engine.cfn import template as cfntemplate
from heat.engine import clients
from heat.engine import environment
from heat.engine.hot import functions as hot_functions
from heat.engine import parameter_groups
from heat.engine import properties
from heat.engine import resources
from heat.engine import service_software_config
from heat.engine import stack as parser
from heat.engine import stack_lock
from heat.engine import stk_defn
from heat.engine import support
from heat.engine import template as templatem
from heat.engine import template_files
from heat.engine import update
from heat.engine import worker
from heat.objects import event as event_object
from heat.objects import resource as resource_objects
from heat.objects import service as service_objects
from heat.objects import snapshot as snapshot_object
from heat.objects import stack as stack_object
from heat.rpc import api as rpc_api
from heat.rpc import worker_api as rpc_worker_api
cfg.CONF.import_opt('engine_life_check_timeout', 'heat.common.config')
cfg.CONF.import_opt('max_resources_per_stack', 'heat.common.config')
cfg.CONF.import_opt('max_stacks_per_tenant', 'heat.common.config')
cfg.CONF.import_opt('enable_stack_abandon', 'heat.common.config')
cfg.CONF.import_opt('enable_stack_adopt', 'heat.common.config')
cfg.CONF.import_opt('convergence_engine', 'heat.common.config')
# Time to wait for a stack to stop when cancelling running threads, before
# giving up on being able to start a delete.
STOP_STACK_TIMEOUT = 30
LOG = logging.getLogger(__name__)
class ThreadGroupManager(object):
def __init__(self):
super(ThreadGroupManager, self).__init__()
self.groups = {}
self.msg_queues = collections.defaultdict(list)
# Create dummy service task, because when there is nothing queued
# on any of the service's ThreadGroups, the process exits.
self.add_timer(None, self._service_task)
def _service_task(self):
"""Dummy task which gets queued on the service.Service threadgroup.
Without this, service.Service sees nothing running i.e has nothing to
wait() on, so the process exits. This could also be used to trigger
periodic non-stack-specific housekeeping tasks.
"""
pass
def _serialize_profile_info(self):
prof = profiler.get()
trace_info = None
if prof:
trace_info = {
"hmac_key": prof.hmac_key,
"base_id": prof.get_base_id(),
"parent_id": prof.get_id()
}
return trace_info
def _start_with_trace(self, cnxt, trace, func, *args, **kwargs):
if trace:
profiler.init(**trace)
if cnxt is not None:
cnxt.update_store()
return func(*args, **kwargs)
def start(self, stack_id, func, *args, **kwargs):
"""Run the given method in a sub-thread."""
if stack_id not in self.groups:
self.groups[stack_id] = threadgroup.ThreadGroup()
def log_exceptions(gt):
try:
gt.wait()
except Exception:
LOG.exception('Unhandled error in asynchronous task')
except BaseException:
pass
req_cnxt = oslo_context.get_current()
th = self.groups[stack_id].add_thread(self._start_with_trace, req_cnxt,
self._serialize_profile_info(),
func, *args, **kwargs)
th.link(log_exceptions)
return th
def start_with_lock(self, cnxt, stack, engine_id, func, *args, **kwargs):
"""Run the method in sub-thread after acquiring the stack lock.
Release the lock when the thread finishes.
:param cnxt: RPC context
:param stack: Stack to be operated on
:type stack: heat.engine.parser.Stack
:param engine_id: The UUID of the engine/worker acquiring the lock
:param func: Callable to be invoked in sub-thread
:type func: function or instancemethod
:param args: Args to be passed to func
:param kwargs: Keyword-args to be passed to func.
"""
lock = stack_lock.StackLock(cnxt, stack.id, engine_id)
with lock.thread_lock():
th = self.start_with_acquired_lock(stack, lock,
func, *args, **kwargs)
return th
def start_with_acquired_lock(self, stack, lock, func, *args, **kwargs):
"""Run the given method in a sub-thread with an existing stack lock.
Release the provided lock when the thread finishes.
:param stack: Stack to be operated on
:type stack: heat.engine.parser.Stack
:param lock: The acquired stack lock
:type lock: heat.engine.stack_lock.StackLock
:param func: Callable to be invoked in sub-thread
:type func: function or instancemethod
:param args: Args to be passed to func
:param kwargs: Keyword-args to be passed to func
"""
def _force_exit(*args):
LOG.info('Graceful exit timeout exceeded, forcing exit.')
os._exit(-1)
def release(gt):
"""Callback function that will be passed to GreenThread.link().
Persist the stack state to COMPLETE and FAILED close to
releasing the lock to avoid race conditions.
"""
if stack is not None and stack.defer_state_persist():
stack.persist_state_and_release_lock(lock.engine_id)
notify = kwargs.get('notify')
if notify is not None and not notify.signalled():
notify.signal()
else:
try:
lock.release()
except Exception:
# allow up to 5 seconds for sys.exit to gracefully shutdown
signal.signal(signal.SIGALRM, _force_exit)
signal.alarm(5)
LOG.exception("FATAL. Failed stack_lock release. Exiting")
sys.exit(-1)
# Link to self to allow the stack to run tasks
stack.thread_group_mgr = self
th = self.start(stack.id, func, *args, **kwargs)
th.link(release)
return th
def add_timer(self, stack_id, func, *args, **kwargs):
"""Define a periodic task in the stack threadgroups.
The task is run in a separate greenthread.
Periodicity is cfg.CONF.periodic_interval
"""
if stack_id not in self.groups:
self.groups[stack_id] = threadgroup.ThreadGroup()
self.groups[stack_id].add_timer(cfg.CONF.periodic_interval,
func, None, *args, **kwargs)
def add_msg_queue(self, stack_id, msg_queue):
self.msg_queues[stack_id].append(msg_queue)
def remove_msg_queue(self, gt, stack_id, msg_queue):
for q in self.msg_queues.pop(stack_id, []):
if q is not msg_queue:
self.add_msg_queue(stack_id, q)
def stop_timers(self, stack_id):
if stack_id in self.groups:
self.groups[stack_id].stop_timers()
def stop(self, stack_id, graceful=False):
"""Stop any active threads on a stack."""
if stack_id in self.groups:
self.msg_queues.pop(stack_id, None)
threadgroup = self.groups.pop(stack_id)
threads = threadgroup.threads[:]
threadgroup.stop(graceful)
threadgroup.wait()
# Wait for link()ed functions (i.e. lock release)
links_done = dict((th, False) for th in threads)
def mark_done(gt, th):
links_done[th] = True
for th in threads:
th.link(mark_done, th)
while not all(links_done.values()):
eventlet.sleep()
def send(self, stack_id, message):
for msg_queue in self.msg_queues.get(stack_id, []):
msg_queue.put_nowait(message)
class NotifyEvent(object):
def __init__(self):
self._queue = eventlet.queue.LightQueue(1)
self._signalled = False
def signalled(self):
return self._signalled
def signal(self):
"""Signal the event."""
if self._signalled:
return
self._signalled = True
self._queue.put(None)
# Yield control so that the waiting greenthread will get the message
# as soon as possible, so that the API handler can respond to the user.
# Another option would be to set the queue length to 0 (which would
# cause put() to block until the event has been seen, but many unit
# tests run in a single greenthread and would thus deadlock.
eventlet.sleep(0)
def wait(self):
"""Wait for the event."""
try:
# There's no timeout argument to eventlet.event.Event available
# until eventlet 0.22.1, so use a queue.
self._queue.get(timeout=cfg.CONF.rpc_response_timeout)
except eventlet.queue.Empty:
LOG.warning('Timed out waiting for operation to start')
@profiler.trace_cls("rpc")
class EngineListener(object):
"""Listen on an AMQP queue named for the engine.
Allows individual engines to communicate with each other for multi-engine
support.
"""
ACTIONS = (STOP_STACK, SEND) = ('stop_stack', 'send')
def __init__(self, host, engine_id, thread_group_mgr):
self.thread_group_mgr = thread_group_mgr
self.engine_id = engine_id
self.host = host
self._server = None
def start(self):
self.target = messaging.Target(
server=self.engine_id,
topic=rpc_api.LISTENER_TOPIC)
self._server = rpc_messaging.get_rpc_server(self.target, self)
self._server.start()
def stop(self):
if self._server is not None:
LOG.debug("Attempting to stop engine listener...")
try:
self._server.stop()
self._server.wait()
LOG.info("Engine listener is stopped successfully")
except Exception as e:
LOG.error("Failed to stop engine listener, %s", e)
def listening(self, ctxt):
"""Respond to a watchdog request.
Respond affirmatively to confirm that the engine performing the action
is still alive.
"""
return True
def stop_stack(self, ctxt, stack_identity):
"""Stop any active threads on a stack."""
stack_id = stack_identity['stack_id']
self.thread_group_mgr.stop(stack_id)
def send(self, ctxt, stack_identity, message):
stack_id = stack_identity['stack_id']
self.thread_group_mgr.send(stack_id, message)
@profiler.trace_cls("rpc")
class EngineService(service.ServiceBase):
"""Manages the running instances from creation to destruction.
All the methods in here are called from the RPC backend. This is
all done dynamically so if a call is made via RPC that does not
have a corresponding method here, an exception will be thrown when
it attempts to call into this class. Arguments to these methods
are also dynamically added and will be named as keyword arguments
by the RPC caller.
"""
RPC_API_VERSION = '1.36'
def __init__(self, host, topic):
resources.initialise()
self.host = host
self.topic = topic
self.binary = 'heat-engine'
self.hostname = socket.gethostname()
# The following are initialized here, but assigned in start() which
# happens after the fork when spawning multiple worker processes
self.listener = None
self.worker_service = None
self.engine_id = None
self.thread_group_mgr = None
self.target = None
self.service_id = None
self.manage_thread_grp = None
self._rpc_server = None
self.software_config = service_software_config.SoftwareConfigService()
self.resource_enforcer = policy.ResourceEnforcer()
if cfg.CONF.trusts_delegated_roles:
LOG.warning('The default value of "trusts_delegated_roles" '
'option in heat.conf is changed to [] in Kilo '
'and heat will delegate all roles of trustor. '
'Please keep the same if you do not want to '
'delegate subset roles when upgrading.')
def start(self):
self.engine_id = service_utils.generate_engine_id()
if self.thread_group_mgr is None:
self.thread_group_mgr = ThreadGroupManager()
self.listener = EngineListener(self.host, self.engine_id,
self.thread_group_mgr)
LOG.debug("Starting listener for engine %s", self.engine_id)
self.listener.start()
self.worker_service = worker.WorkerService(
host=self.host,
topic=rpc_worker_api.TOPIC,
engine_id=self.engine_id,
thread_group_mgr=self.thread_group_mgr
)
self.worker_service.start()
target = messaging.Target(
version=self.RPC_API_VERSION, server=self.host,
topic=self.topic)
self.target = target
self._rpc_server = rpc_messaging.get_rpc_server(target, self)
self._rpc_server.start()
self._client = rpc_messaging.get_rpc_client(
version=self.RPC_API_VERSION)
self._configure_db_conn_pool_size()
self.service_manage_cleanup()
if self.manage_thread_grp is None:
self.manage_thread_grp = threadgroup.ThreadGroup()
self.manage_thread_grp.add_timer(cfg.CONF.periodic_interval,
self.service_manage_report)
self.manage_thread_grp.add_thread(self.reset_stack_status)
def _configure_db_conn_pool_size(self):
# bug #1491185
# Set the DB max_overflow to match the thread pool size.
# The overflow connections are automatically closed when they are
# not used; setting it is better than setting DB max_pool_size.
worker_pool_size = cfg.CONF.executor_thread_pool_size
# Update max_overflow only if it is not adequate
if ((cfg.CONF.database.max_overflow is None) or
(cfg.CONF.database.max_overflow < worker_pool_size)):
cfg.CONF.set_override('max_overflow', worker_pool_size,
group='database')
def _stop_rpc_server(self):
# Stop rpc connection at first for preventing new requests
if self._rpc_server is None:
return
LOG.debug("Attempting to stop engine service...")
try:
self._rpc_server.stop()
self._rpc_server.wait()
LOG.info("Engine service is stopped successfully")
except Exception as e:
LOG.error("Failed to stop engine service, %s", e)
def stop(self):
self._stop_rpc_server()
if self.listener:
self.listener.stop()
if self.worker_service:
self.worker_service.stop()
# Wait for all active threads to be finished
if self.thread_group_mgr:
for stack_id in list(self.thread_group_mgr.groups.keys()):
# Ignore dummy service task
if stack_id == cfg.CONF.periodic_interval:
continue
LOG.info("Waiting stack %s processing to be finished",
stack_id)
# Stop threads gracefully
self.thread_group_mgr.stop(stack_id, True)
LOG.info("Stack %s processing was finished", stack_id)
if self.manage_thread_grp:
self.manage_thread_grp.stop()
ctxt = context.get_admin_context()
service_objects.Service.delete(ctxt, self.service_id)
LOG.info('Service %s is deleted', self.service_id)
# Terminate the engine process
LOG.info("All threads were gone, terminating engine")
def wait(self):
pass
def reset(self):
logging.setup(cfg.CONF, 'heat')
@context.request_context
def identify_stack(self, cnxt, stack_name):
"""The full stack identifier for a single, live stack with stack_name.
:param cnxt: RPC context.
:param stack_name: Name or UUID of the stack to look up.
"""
s = None
if uuidutils.is_uuid_like(stack_name):
s = stack_object.Stack.get_by_id(
cnxt,
stack_name,
show_deleted=True,
eager_load=False)
# may be the name is in uuid format, so if get by id returns None,
# we should get the info by name again
if not s:
s = stack_object.Stack.get_by_name(cnxt, stack_name)
if not s:
raise exception.EntityNotFound(entity='Stack', name=stack_name)
return dict(s.identifier())
def _get_stack(self, cnxt, stack_identity, show_deleted=False):
identity = identifier.HeatIdentifier(**stack_identity)
s = stack_object.Stack.get_by_id(
cnxt,
identity.stack_id,
show_deleted=show_deleted)
if s is None:
raise exception.EntityNotFound(entity='Stack',
name=identity.stack_name)
if not cnxt.is_admin and cnxt.tenant_id not in (
identity.tenant, s.stack_user_project_id):
# The DB API should not allow this, but sanity-check anyway..
raise exception.InvalidTenant(target=identity.tenant,
actual=cnxt.tenant_id)
if identity.path or s.name != identity.stack_name:
raise exception.EntityNotFound(entity='Stack',
name=identity.stack_name)
return s
@context.request_context
def show_stack(self, cnxt, stack_identity, resolve_outputs=True):
"""Return detailed information about one or all stacks.
:param cnxt: RPC context.
:param stack_identity: Name of the stack you want to show, or None
to show all
:param resolve_outputs: If True, outputs for given stack/stacks will
be resolved
"""
if stack_identity is not None:
db_stack = self._get_stack(cnxt, stack_identity, show_deleted=True)
stacks = [parser.Stack.load(cnxt, stack=db_stack)]
else:
stacks = parser.Stack.load_all(cnxt)
def show(stack):
if resolve_outputs:
for res in stack._explicit_dependencies():
ensure_cache = stack.convergence and res.id is not None
node_data = res.node_data(for_resources=ensure_cache,
for_outputs=True)
stk_defn.update_resource_data(stack.defn, res.name,
node_data)
# Cases where stored attributes may not exist for a
# resource:
# * The resource is an AutoScalingGroup that received a
# signal
# * Near simultaneous updates (say by an update and a
# signal)
# * The first time resolving a pre-Pike stack
if ensure_cache:
res.store_attributes()
return api.format_stack(stack, resolve_outputs=resolve_outputs)
return [show(stack) for stack in stacks]
def get_revision(self, cnxt):
return cfg.CONF.revision['heat_revision']
@context.request_context
def list_stacks(self, cnxt, limit=None, marker=None, sort_keys=None,
sort_dir=None, filters=None, tenant_safe=True,
show_deleted=False, show_nested=False, show_hidden=False,
tags=None, tags_any=None, not_tags=None,
not_tags_any=None):
"""Returns attributes of all stacks.
It supports pagination (``limit`` and ``marker``),
sorting (``sort_keys`` and ``sort_dir``) and filtering (``filters``)
of the results.
:param cnxt: RPC context
:param limit: the number of stacks to list (integer or string)
:param marker: the ID of the last item in the previous page
:param sort_keys: an array of fields used to sort the list
:param sort_dir: the direction of the sort ('asc' or 'desc')
:param filters: a dict with attribute:value to filter the list
:param tenant_safe: DEPRECATED, if true, scope the request by
the current tenant
:param show_deleted: if true, show soft-deleted stacks
:param show_nested: if true, show nested stacks
:param show_hidden: if true, show hidden stacks
:param tags: show stacks containing these tags. If multiple tags
are passed, they will be combined using the boolean AND expression
:param tags_any: show stacks containing these tags. If multiple tags
are passed, they will be combined using the boolean OR expression
:param not_tags: show stacks not containing these tags. If multiple
tags are passed, they will be combined using the boolean AND
expression
:param not_tags_any: show stacks not containing these tags. If
multiple tags are passed, they will be combined using the boolean
OR expression
:returns: a list of formatted stacks
"""
if filters is not None:
filters = api.translate_filters(filters)
if not tenant_safe:
cnxt = context.get_admin_context()
stacks = stack_object.Stack.get_all(
cnxt,
limit=limit,
sort_keys=sort_keys,
marker=marker,
sort_dir=sort_dir,
filters=filters,
show_deleted=show_deleted,
show_nested=show_nested,
show_hidden=show_hidden,
tags=tags,
tags_any=tags_any,
not_tags=not_tags,
not_tags_any=not_tags_any)
return [api.format_stack_db_object(stack) for stack in stacks]
@context.request_context
def count_stacks(self, cnxt, filters=None, tenant_safe=True,
show_deleted=False, show_nested=False, show_hidden=False,
tags=None, tags_any=None, not_tags=None,
not_tags_any=None):
"""Return the number of stacks that match the given filters.
:param cnxt: RPC context.
:param filters: a dict of ATTR:VALUE to match against stacks
:param tenant_safe: DEPRECATED, if true, scope the request by
the current tenant
:param show_deleted: if true, count will include the deleted stacks
:param show_nested: if true, count will include nested stacks
:param show_hidden: if true, count will include hidden stacks
:param tags: count stacks containing these tags. If multiple tags
are passed, they will be combined using the boolean AND expression
:param tags_any: count stacks containing these tags. If multiple tags
are passed, they will be combined using the boolean OR expression
:param not_tags: count stacks not containing these tags. If multiple
tags are passed, they will be combined using the boolean AND
expression
:param not_tags_any: count stacks not containing these tags. If
multiple tags are passed, they will be combined using the boolean
OR expression
:returns: an integer representing the number of matched stacks
"""
if not tenant_safe:
cnxt = context.get_admin_context()
return stack_object.Stack.count_all(
cnxt,
filters=filters,
show_deleted=show_deleted,
show_nested=show_nested,
show_hidden=show_hidden,
tags=tags,
tags_any=tags_any,
not_tags=not_tags,
not_tags_any=not_tags_any)
def _validate_deferred_auth_context(self, cnxt, stack):
if cfg.CONF.deferred_auth_method != 'password':
return
if not stack.requires_deferred_auth():
return
if cnxt.username is None:
raise exception.MissingCredentialError(required='X-Auth-User')
if cnxt.password is None:
raise exception.MissingCredentialError(required='X-Auth-Key')
def _validate_new_stack(self, cnxt, stack_name, parsed_template):
# We'll check that the stack name is unique in the tenant while
# storing it in the database to avoid races, but also check it here
# before validating so we can fail early.
if stack_object.Stack.get_by_name(cnxt, stack_name):
raise exception.StackExists(stack_name=stack_name)
# Do not stack limit check for admin since admin can see all stacks.
if not cnxt.is_admin:
tenant_limit = cfg.CONF.max_stacks_per_tenant
if stack_object.Stack.count_all(cnxt) >= tenant_limit:
message = _("You have reached the maximum stacks per tenant, "
"%d. Please delete some stacks.") % tenant_limit
raise exception.RequestLimitExceeded(message=message)
self._validate_template(cnxt, parsed_template)
def _validate_template(self, cnxt, parsed_template):
try:
parsed_template.validate()
except AssertionError:
raise
except Exception as ex:
raise exception.StackValidationFailed(message=str(ex))
max_resources = cfg.CONF.max_resources_per_stack
if max_resources == -1:
return
num_resources = len(parsed_template[parsed_template.RESOURCES])
if num_resources > max_resources:
message = exception.StackResourceLimitExceeded.msg_fmt
raise exception.RequestLimitExceeded(message=message)
def _parse_template_and_validate_stack(self, cnxt, stack_name, template,
params, files, environment_files,
files_container, args,
owner_id=None, nested_depth=0,
user_creds_id=None,
stack_user_project_id=None,
convergence=False,
parent_resource_name=None,
template_id=None):
common_params = api.extract_args(args)
# If it is stack-adopt, use parameters from adopt_stack_data
if rpc_api.PARAM_ADOPT_STACK_DATA in common_params:
if not cfg.CONF.enable_stack_adopt:
raise exception.NotSupported(feature='Stack Adopt')
# Override the params with values given with -P option
new_params = {}
if 'environment' in common_params[rpc_api.PARAM_ADOPT_STACK_DATA]:
new_params = common_params[rpc_api.PARAM_ADOPT_STACK_DATA][
'environment'].get(rpc_api.STACK_PARAMETERS, {}).copy()
new_params.update(params.get(rpc_api.STACK_PARAMETERS, {}))
params[rpc_api.STACK_PARAMETERS] = new_params
if template_id is not None:
tmpl = templatem.Template.load(cnxt, template_id)
else:
if files_container:
files = template_files.get_files_from_container(
cnxt, files_container, files)
tmpl = templatem.Template(template, files=files)
env_util.merge_environments(environment_files, files,
params, tmpl.all_param_schemata(files))
tmpl.env = environment.Environment(params)
self._validate_new_stack(cnxt, stack_name, tmpl)
stack = parser.Stack(cnxt, stack_name, tmpl,
owner_id=owner_id,
nested_depth=nested_depth,
user_creds_id=user_creds_id,
stack_user_project_id=stack_user_project_id,
convergence=convergence,
parent_resource=parent_resource_name,
**common_params)
self.resource_enforcer.enforce_stack(stack, is_registered_policy=True)
self._validate_deferred_auth_context(cnxt, stack)
is_root = stack.nested_depth == 0
stack.validate()
# For the root stack, log a summary of the TemplateResources loaded
if is_root:
tmpl.env.registry.log_resource_info(prefix=stack_name)
return stack
@context.request_context
def preview_stack(self, cnxt, stack_name, template, params, files,
args, environment_files=None, files_container=None):
"""Simulate a new stack using the provided template.
Note that at this stage the template has already been fetched from the
heat-api process if using a template-url.
:param cnxt: RPC context.
:param stack_name: Name of the stack you want to create.
:param template: Template of stack you want to create.
:param params: Stack Input Params
:param files: Files referenced from the template
:param args: Request parameters/args passed from API
:param environment_files: optional ordered list of environment file
names included in the files dict
:type environment_files: list or None
:param files_container: optional swift container name
"""
LOG.info('previewing stack %s', stack_name)
conv_eng = cfg.CONF.convergence_engine
stack = self._parse_template_and_validate_stack(cnxt,
stack_name,
template,
params,
files,
environment_files,
files_container,
args,
convergence=conv_eng)
return api.format_stack_preview(stack)
@context.request_context
def create_stack(self, cnxt, stack_name, template, params, files,
args, environment_files=None,
files_container=None, owner_id=None,
nested_depth=0, user_creds_id=None,
stack_user_project_id=None, parent_resource_name=None,
template_id=None):
"""Create a new stack using the template provided.
Note that at this stage the template has already been fetched from the
heat-api process if using a template-url.
:param cnxt: RPC context.
:param stack_name: Name of the stack you want to create.
:param template: Template of stack you want to create.
:param params: Stack Input Params
:param files: Files referenced from the template
:param args: Request parameters/args passed from API
:param environment_files: optional ordered list of environment file
names included in the files dict
:type environment_files: list or None
:param files_container: optional swift container name
:param owner_id: parent stack ID for nested stacks, only expected when
called from another heat-engine (not a user option)
:param nested_depth: the nested depth for nested stacks, only expected
when called from another heat-engine
:param user_creds_id: the parent user_creds record for nested stacks
:param stack_user_project_id: the parent stack_user_project_id for
nested stacks
:param parent_resource_name: the parent resource name
:param template_id: the ID of a pre-stored template in the DB
"""
LOG.info('Creating stack %s', stack_name)
def _create_stack_user(stack):
if not stack.stack_user_project_id:
try:
stack.create_stack_user_project_id()
except exception.AuthorizationFailure as ex:
stack.state_set(stack.action, stack.FAILED,
str(ex))
def _stack_create(stack, msg_queue=None):
# Create/Adopt a stack, and create the periodic task if successful
if stack.adopt_stack_data:
stack.adopt()
elif stack.status != stack.FAILED:
stack.create(msg_queue=msg_queue)
convergence = cfg.CONF.convergence_engine
stack = self._parse_template_and_validate_stack(
cnxt, stack_name, template, params, files, environment_files,
files_container, args, owner_id, nested_depth,
user_creds_id, stack_user_project_id, convergence,
parent_resource_name, template_id)
stack_id = stack.store()
if cfg.CONF.reauthentication_auth_method == 'trusts':
stack = parser.Stack.load(
cnxt, stack_id=stack_id, use_stored_context=True)
_create_stack_user(stack)
if convergence:
action = stack.CREATE
if stack.adopt_stack_data:
action = stack.ADOPT
stack.thread_group_mgr = self.thread_group_mgr
stack.converge_stack(template=stack.t, action=action)
else:
msg_queue = eventlet.queue.LightQueue()
th = self.thread_group_mgr.start_with_lock(cnxt, stack,
self.engine_id,
_stack_create, stack,
msg_queue=msg_queue)
th.link(self.thread_group_mgr.remove_msg_queue,
stack.id, msg_queue)
self.thread_group_mgr.add_msg_queue(stack.id, msg_queue)
return dict(stack.identifier())
def _prepare_stack_updates(self, cnxt, current_stack,
template, params, environment_files,
files, files_container,
args, template_id=None):
"""Return the current and updated stack for a given transition.
Changes *will not* be persisted, this is a helper method for
update_stack and preview_update_stack.
:param cnxt: RPC context.
:param stack: A stack to be updated.
:param template: Template of stack you want to update to.
:param params: Stack Input Params
:param files: Files referenced from the template
:param args: Request parameters/args passed from API
:param template_id: the ID of a pre-stored template in the DB
"""
# Now parse the template and any parameters for the updated
# stack definition. If PARAM_EXISTING is specified, we merge
# any environment provided into the existing one and attempt
# to use the existing stack template, if one is not provided.
if args.get(rpc_api.PARAM_EXISTING, False):
assert template_id is None, \
"Cannot specify template_id with PARAM_EXISTING"
if template is not None:
new_template = template
elif (current_stack.convergence or
current_stack.status == current_stack.COMPLETE):
# If convergence is enabled, or the stack is complete, we can
# just use the current template...
new_template = current_stack.t.t
else:
# ..but if it's FAILED without convergence things may be in an
# inconsistent state, so we try to fall back on a stored copy
# of the previous template
if current_stack.prev_raw_template_id is not None:
# Use the stored previous template
prev_t = templatem.Template.load(
cnxt, current_stack.prev_raw_template_id)
new_template = prev_t.t
else:
# Nothing we can do, the failed update happened before
# we started storing prev_raw_template_id
LOG.error('PATCH update to FAILED stack only '
'possible if convergence enabled or '
'previous template stored')
msg = _('PATCH update to non-COMPLETE stack')
raise exception.NotSupported(feature=msg)
new_files = current_stack.t.files
if files_container:
files = template_files.get_files_from_container(
cnxt, files_container, files)
new_files.update(files or {})
tmpl = templatem.Template(new_template, files=new_files)
env_util.merge_environments(environment_files, new_files,
params, tmpl.all_param_schemata(files))
existing_env = current_stack.env.env_as_dict()
existing_params = existing_env[env_fmt.PARAMETERS]
clear_params = set(args.get(rpc_api.PARAM_CLEAR_PARAMETERS, []))
retained = dict((k, v) for k, v in existing_params.items()
if k not in clear_params)
existing_env[env_fmt.PARAMETERS] = retained
new_env = environment.Environment(existing_env)
new_env.load(params)
for key in list(new_env.params.keys()):
if key not in tmpl.param_schemata():
new_env.params.pop(key)
tmpl.env = new_env
else:
if template_id is not None:
tmpl = templatem.Template.load(cnxt, template_id)
else:
if files_container:
files = template_files.get_files_from_container(
cnxt, files_container, files)
tmpl = templatem.Template(template, files=files)
env_util.merge_environments(environment_files,
files, params,
tmpl.all_param_schemata(files))
tmpl.env = environment.Environment(params)
max_resources = cfg.CONF.max_resources_per_stack
if max_resources != -1 and len(tmpl[tmpl.RESOURCES]) > max_resources:
raise exception.RequestLimitExceeded(
message=exception.StackResourceLimitExceeded.msg_fmt)
stack_name = current_stack.name
current_kwargs = current_stack.get_kwargs_for_cloning()
common_params = api.extract_args(args)
common_params.setdefault(rpc_api.PARAM_TIMEOUT,
current_stack.timeout_mins)
common_params.setdefault(rpc_api.PARAM_DISABLE_ROLLBACK,
current_stack.disable_rollback)
common_params.setdefault(rpc_api.PARAM_CONVERGE,
current_stack.converge)
if args.get(rpc_api.PARAM_EXISTING, False):
if rpc_api.STACK_TAGS not in common_params:
common_params[rpc_api.STACK_TAGS] = current_stack.tags
current_kwargs.update(common_params)
updated_stack = parser.Stack(cnxt, stack_name, tmpl,
**current_kwargs)
invalid_params = current_stack.parameters.immutable_params_modified(
updated_stack.parameters, tmpl.env.params)
if invalid_params:
raise exception.ImmutableParameterModified(*invalid_params)
self.resource_enforcer.enforce_stack(updated_stack,
is_registered_policy=True)
updated_stack.parameters.set_stack_id(current_stack.identifier())
self._validate_deferred_auth_context(cnxt, updated_stack)
updated_stack.validate()
return tmpl, current_stack, updated_stack
@context.request_context
def update_stack(self, cnxt, stack_identity, template, params,