-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
_stack.py
848 lines (728 loc) 路 33.2 KB
/
_stack.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
# Copyright 2016-2022, Pulumi Corporation.
#
# 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 json
import os
import tempfile
import time
import threading
from concurrent import futures
from enum import Enum
from datetime import datetime
from typing import List, Any, Mapping, MutableMapping, Optional, Callable, Tuple
import grpc
from ._cmd import CommandResult, _run_pulumi_cmd, OnOutput
from ._config import ConfigValue, ConfigMap
from .errors import StackAlreadyExistsError, StackNotFoundError
from .events import OpMap, EngineEvent, SummaryEvent
from ._output import OutputMap
from ._server import LanguageServer
from ._workspace import Workspace, PulumiFn, Deployment
from ..runtime.settings import _GRPC_CHANNEL_OPTIONS
from ..runtime.proto import language_pb2_grpc
from ._representable import _Representable
_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
OnEvent = Callable[[EngineEvent], Any]
class ExecKind(str, Enum):
LOCAL = "auto.local"
INLINE = "auto.inline"
class StackInitMode(Enum):
CREATE = "create"
SELECT = "select"
CREATE_OR_SELECT = "create_or_select"
class UpdateSummary:
def __init__(
self,
# pre-update info
kind: str,
start_time: datetime,
message: str,
environment: Mapping[str, str],
config: Mapping[str, dict],
# post-update info
result: str,
end_time: Optional[datetime] = None,
version: Optional[int] = None,
deployment: Optional[str] = None,
resource_changes: Optional[OpMap] = None,
):
self.kind = kind
self.start_time = start_time
self.end_time = end_time
self.message = message
self.environment = environment
self.result = result
self.Deployment = deployment
self.resource_changes = resource_changes
self.version = version
self.config: ConfigMap = {}
for key in config:
config_value = config[key]
self.config[key] = ConfigValue(
value=config_value["value"], secret=config_value["secret"]
)
def __repr__(self):
return (
f"UpdateSummary(result={self.result!r}, version={self.version!r}, "
f"start_time={self.start_time!r}, end_time={self.end_time!r}, kind={self.kind!r}, "
f"message={self.message!r}, environment={self.environment!r}, "
f"resource_changes={self.resource_changes!r}, config={self.config!r}, Deployment={self.Deployment!r})"
)
class BaseResult(_Representable):
def __init__(self, stdout: str, stderr: str):
self.stdout = stdout
self.stderr = stderr
class PreviewResult(BaseResult):
def __init__(self, stdout: str, stderr: str, change_summary: OpMap):
super().__init__(stdout, stderr)
self.change_summary = change_summary
class UpResult(BaseResult):
def __init__(
self, stdout: str, stderr: str, summary: UpdateSummary, outputs: OutputMap
):
super().__init__(stdout, stderr)
self.outputs = outputs
self.summary = summary
class RefreshResult(BaseResult):
def __init__(self, stdout: str, stderr: str, summary: UpdateSummary):
super().__init__(stdout, stderr)
self.summary = summary
class DestroyResult(BaseResult):
def __init__(self, stdout: str, stderr: str, summary: UpdateSummary):
super().__init__(stdout, stderr)
self.summary = summary
class Stack:
@classmethod
def create(cls, stack_name: str, workspace: Workspace) -> "Stack":
"""
Creates a new stack using the given workspace, and stack name.
It fails if a stack with that name already exists.
:param stack_name: The name identifying the Stack
:param workspace: The Workspace the Stack was created from.
:return: Stack
"""
return Stack(stack_name, workspace, StackInitMode.CREATE)
@classmethod
def select(cls, stack_name: str, workspace: Workspace) -> "Stack":
"""
Selects stack using the given workspace, and stack name.
It returns an error if the given Stack does not exist.
:param stack_name: The name identifying the Stack
:param workspace: The Workspace the Stack was created from.
:return: Stack
"""
return Stack(stack_name, workspace, StackInitMode.SELECT)
@classmethod
def create_or_select(cls, stack_name: str, workspace: Workspace) -> "Stack":
"""
Tries to create a new stack using the given workspace and stack name if the stack does not already exist,
or falls back to selecting the existing stack. If the stack does not exist,
it will be created and selected.
:param stack_name: The name identifying the Stack
:param workspace: The Workspace the Stack was created from.
:return: Stack
"""
return Stack(stack_name, workspace, StackInitMode.CREATE_OR_SELECT)
def __init__(self, name: str, workspace: Workspace, mode: StackInitMode) -> None:
"""
Stack is an isolated, independently configurable instance of a Pulumi program.
Stack exposes methods for the full pulumi lifecycle (up/preview/refresh/destroy), as well as managing configuration.
Multiple Stacks are commonly used to denote different phases of development
(such as development, staging and production) or feature branches (such as feature-x-dev, jane-feature-x-dev).
"""
self.name = name
self.workspace = workspace
self._mode = mode
if not isinstance(name, str):
raise TypeError("name must be of type 'str'")
if not isinstance(workspace, Workspace):
raise TypeError("workspace must be of type 'Workspace'")
if not isinstance(mode, StackInitMode):
raise TypeError("mode must be of type 'StackInitMode'")
if mode is StackInitMode.CREATE:
workspace.create_stack(name)
elif mode is StackInitMode.SELECT:
workspace.select_stack(name)
elif mode is StackInitMode.CREATE_OR_SELECT:
try:
workspace.select_stack(name)
except StackNotFoundError:
workspace.create_stack(name)
def __repr__(self):
return f"Stack(stack_name={self.name!r}, workspace={self.workspace!r}, mode={self._mode!r})"
def __str__(self):
return f"Stack(stack_name={self.name!r}, workspace={self.workspace!r})"
def up(
self,
parallel: Optional[int] = None,
message: Optional[str] = None,
target: Optional[List[str]] = None,
policy_packs: Optional[List[str]] = None,
policy_pack_configs: Optional[List[str]] = None,
expect_no_changes: Optional[bool] = None,
diff: Optional[bool] = None,
target_dependents: Optional[bool] = None,
replace: Optional[List[str]] = None,
color: Optional[str] = None,
on_output: Optional[OnOutput] = None,
on_event: Optional[OnEvent] = None,
program: Optional[PulumiFn] = None,
plan: Optional[str] = None,
show_secrets: bool = True,
log_flow: Optional[bool] = None,
log_verbosity: Optional[int] = None,
log_to_std_err: Optional[bool] = None,
tracing: Optional[str] = None,
debug: Optional[bool] = None,
) -> UpResult:
"""
Creates or updates the resources in a stack by executing the program in the Workspace.
https://www.pulumi.com/docs/reference/cli/pulumi_up/
:param parallel: Parallel is the number of resource operations to run in parallel at once.
(1 for no parallelism). Defaults to unbounded (2147483647).
:param message: Message (optional) to associate with the update operation.
:param target: Specify an exclusive list of resource URNs to destroy.
:param expect_no_changes: Return an error if any changes occur during this update.
:param policy_packs: Run one or more policy packs as part of this update.
:param policy_pack_configs: Path to JSON file containing the config for the policy pack of the corresponding "--policy-pack" flag.
:param diff: Display operation as a rich diff showing the overall change.
:param target_dependents: Allows updating of dependent targets discovered but not specified in the Target list.
:param replace: Specify resources to replace.
:param on_output: A function to process the stdout stream.
:param on_event: A function to process structured events from the Pulumi event stream.
:param program: The inline program.
:param color: Colorize output. Choices are: always, never, raw, auto (default "auto")
:param plan: Plan specifies the path to an update plan to use for the update.
:param show_secrets: Include config secrets in the UpResult summary.
:param log_flow: Flow log settings to child processes (like plugins)
:param log_verbosity: Enable verbose logging (e.g., v=3); anything >3 is very verbose
:param log_to_std_err: Log to stderr instead of to files
:param tracing: Emit tracing to the specified endpoint. Use the file: scheme to write tracing data to a local file
:param debug: Print detailed debugging output during resource operations
:returns: UpResult
"""
# Disable unused-argument because pylint doesn't understand we process them in _parse_extra_args
# pylint: disable=unused-argument
program = program or self.workspace.program
extra_args = _parse_extra_args(**locals())
args = ["up", "--yes", "--skip-preview"]
args.extend(extra_args)
if plan is not None:
args.append("--plan")
args.append(plan)
kind = ExecKind.LOCAL.value
on_exit = None
if program:
kind = ExecKind.INLINE.value
server = grpc.server(
futures.ThreadPoolExecutor(
max_workers=4
), # pylint: disable=consider-using-with
options=_GRPC_CHANNEL_OPTIONS,
)
language_server = LanguageServer(program)
language_pb2_grpc.add_LanguageRuntimeServicer_to_server(
language_server, server
)
port = server.add_insecure_port(address="127.0.0.1:0")
server.start()
def on_exit_fn():
language_server.on_pulumi_exit()
server.stop(0)
on_exit = on_exit_fn
args.append(f"--client=127.0.0.1:{port}")
args.extend(["--exec-kind", kind])
log_watcher_thread = None
temp_dir = None
if on_event:
log_file, temp_dir = _create_log_file("up")
args.extend(["--event-log", log_file])
log_watcher_thread = threading.Thread(
target=_watch_logs, args=(log_file, on_event)
)
log_watcher_thread.start()
try:
up_result = self._run_pulumi_cmd_sync(args, on_output)
outputs = self.outputs()
summary = self.info(show_secrets)
assert summary is not None
finally:
_cleanup(temp_dir, log_watcher_thread, on_exit)
return UpResult(
stdout=up_result.stdout,
stderr=up_result.stderr,
summary=summary,
outputs=outputs,
)
def preview(
self,
parallel: Optional[int] = None,
message: Optional[str] = None,
target: Optional[List[str]] = None,
policy_packs: Optional[List[str]] = None,
policy_pack_configs: Optional[List[str]] = None,
expect_no_changes: Optional[bool] = None,
diff: Optional[bool] = None,
target_dependents: Optional[bool] = None,
replace: Optional[List[str]] = None,
color: Optional[str] = None,
on_output: Optional[OnOutput] = None,
on_event: Optional[OnEvent] = None,
program: Optional[PulumiFn] = None,
plan: Optional[str] = None,
log_flow: Optional[bool] = None,
log_verbosity: Optional[int] = None,
log_to_std_err: Optional[bool] = None,
tracing: Optional[str] = None,
debug: Optional[bool] = None,
) -> PreviewResult:
"""
Performs a dry-run update to a stack, returning pending changes.
https://www.pulumi.com/docs/reference/cli/pulumi_preview/
:param parallel: Parallel is the number of resource operations to run in parallel at once.
(1 for no parallelism). Defaults to unbounded (2147483647).
:param message: Message to associate with the preview operation.
:param target: Specify an exclusive list of resource URNs to update.
:param policy_packs: Run one or more policy packs as part of this update.
:param policy_pack_configs: Path to JSON file containing the config for the policy pack of the corresponding "--policy-pack" flag.
:param expect_no_changes: Return an error if any changes occur during this update.
:param diff: Display operation as a rich diff showing the overall change.
:param target_dependents: Allows updating of dependent targets discovered but not specified in the Target list.
:param replace: Specify resources to replace.
:param on_output: A function to process the stdout stream.
:param on_event: A function to process structured events from the Pulumi event stream.
:param program: The inline program.
:param color: Colorize output. Choices are: always, never, raw, auto (default "auto")
:param plan: Plan specifies the path where the update plan should be saved.
:param log_flow: Flow log settings to child processes (like plugins)
:param log_verbosity: Enable verbose logging (e.g., v=3); anything >3 is very verbose
:param log_to_std_err: Log to stderr instead of to files
:param tracing: Emit tracing to the specified endpoint. Use the file: scheme to write tracing data to a local file
:param debug: Print detailed debugging output during resource operations
:returns: PreviewResult
"""
# Disable unused-argument because pylint doesn't understand we process them in _parse_extra_args
# pylint: disable=unused-argument
program = program or self.workspace.program
extra_args = _parse_extra_args(**locals())
args = ["preview"]
args.extend(extra_args)
if plan is not None:
args.append("--save-plan")
args.append(plan)
kind = ExecKind.LOCAL.value
on_exit = None
if program:
kind = ExecKind.INLINE.value
server = grpc.server(
futures.ThreadPoolExecutor(
max_workers=4
), # pylint: disable=consider-using-with
options=_GRPC_CHANNEL_OPTIONS,
)
language_server = LanguageServer(program)
language_pb2_grpc.add_LanguageRuntimeServicer_to_server(
language_server, server
)
port = server.add_insecure_port(address="127.0.0.1:0")
server.start()
def on_exit_fn():
language_server.on_pulumi_exit()
server.stop(0)
on_exit = on_exit_fn
args.append(f"--client=127.0.0.1:{port}")
args.extend(["--exec-kind", kind])
log_file, temp_dir = _create_log_file("preview")
args.extend(["--event-log", log_file])
summary_events: List[SummaryEvent] = []
def on_event_callback(event: EngineEvent) -> None:
if event.summary_event:
summary_events.append(event.summary_event)
if on_event:
on_event(event)
# Start watching logs in a thread
log_watcher_thread = threading.Thread(
target=_watch_logs, args=(log_file, on_event_callback)
)
log_watcher_thread.start()
try:
preview_result = self._run_pulumi_cmd_sync(args, on_output)
finally:
_cleanup(temp_dir, log_watcher_thread, on_exit)
if not summary_events:
raise RuntimeError("summary event never found")
return PreviewResult(
stdout=preview_result.stdout,
stderr=preview_result.stderr,
change_summary=summary_events[0].resource_changes,
)
def refresh(
self,
parallel: Optional[int] = None,
message: Optional[str] = None,
target: Optional[List[str]] = None,
expect_no_changes: Optional[bool] = None,
color: Optional[str] = None,
on_output: Optional[OnOutput] = None,
on_event: Optional[OnEvent] = None,
show_secrets: bool = True,
log_flow: Optional[bool] = None,
log_verbosity: Optional[int] = None,
log_to_std_err: Optional[bool] = None,
tracing: Optional[str] = None,
debug: Optional[bool] = None,
) -> RefreshResult:
"""
Compares the current stack鈥檚 resource state with the state known to exist in the actual
cloud provider. Any such changes are adopted into the current stack.
:param parallel: Parallel is the number of resource operations to run in parallel at once.
(1 for no parallelism). Defaults to unbounded (2147483647).
:param message: Message (optional) to associate with the refresh operation.
:param target: Specify an exclusive list of resource URNs to refresh.
:param expect_no_changes: Return an error if any changes occur during this update.
:param on_output: A function to process the stdout stream.
:param on_event: A function to process structured events from the Pulumi event stream.
:param color: Colorize output. Choices are: always, never, raw, auto (default "auto")
:param show_secrets: Include config secrets in the RefreshResult summary.
:param log_flow: Flow log settings to child processes (like plugins)
:param log_verbosity: Enable verbose logging (e.g., v=3); anything >3 is very verbose
:param log_to_std_err: Log to stderr instead of to files
:param tracing: Emit tracing to the specified endpoint. Use the file: scheme to write tracing data to a local file
:param debug: Print detailed debugging output during resource operations
:returns: RefreshResult
"""
# Disable unused-argument because pylint doesn't understand we process them in _parse_extra_args
# pylint: disable=unused-argument
extra_args = _parse_extra_args(**locals())
args = ["refresh", "--yes", "--skip-preview"]
args.extend(extra_args)
kind = ExecKind.INLINE.value if self.workspace.program else ExecKind.LOCAL.value
args.extend(["--exec-kind", kind])
log_watcher_thread = None
temp_dir = None
if on_event:
log_file, temp_dir = _create_log_file("refresh")
args.extend(["--event-log", log_file])
log_watcher_thread = threading.Thread(
target=_watch_logs, args=(log_file, on_event)
)
log_watcher_thread.start()
try:
refresh_result = self._run_pulumi_cmd_sync(args, on_output)
finally:
_cleanup(temp_dir, log_watcher_thread)
summary = self.info(show_secrets)
assert summary is not None
return RefreshResult(
stdout=refresh_result.stdout, stderr=refresh_result.stderr, summary=summary
)
def destroy(
self,
parallel: Optional[int] = None,
message: Optional[str] = None,
target: Optional[List[str]] = None,
target_dependents: Optional[bool] = None,
color: Optional[str] = None,
on_output: Optional[OnOutput] = None,
on_event: Optional[OnEvent] = None,
show_secrets: bool = True,
log_flow: Optional[bool] = None,
log_verbosity: Optional[int] = None,
log_to_std_err: Optional[bool] = None,
tracing: Optional[str] = None,
debug: Optional[bool] = None,
) -> DestroyResult:
"""
Destroy deletes all resources in a stack, leaving all history and configuration intact.
:param parallel: Parallel is the number of resource operations to run in parallel at once.
(1 for no parallelism). Defaults to unbounded (2147483647).
:param message: Message (optional) to associate with the destroy operation.
:param target: Specify an exclusive list of resource URNs to destroy.
:param target_dependents: Allows updating of dependent targets discovered but not specified in the Target list.
:param on_output: A function to process the stdout stream.
:param on_event: A function to process structured events from the Pulumi event stream.
:param color: Colorize output. Choices are: always, never, raw, auto (default "auto")
:param show_secrets: Include config secrets in the DestroyResult summary.
:param log_flow: Flow log settings to child processes (like plugins)
:param log_verbosity: Enable verbose logging (e.g., v=3); anything >3 is very verbose
:param log_to_std_err: Log to stderr instead of to files
:param tracing: Emit tracing to the specified endpoint. Use the file: scheme to write tracing data to a local file
:param debug: Print detailed debugging output during resource operations
:returns: DestroyResult
"""
# Disable unused-argument because pylint doesn't understand we process them in _parse_extra_args
# pylint: disable=unused-argument
extra_args = _parse_extra_args(**locals())
args = ["destroy", "--yes", "--skip-preview"]
args.extend(extra_args)
kind = ExecKind.INLINE.value if self.workspace.program else ExecKind.LOCAL.value
args.extend(["--exec-kind", kind])
log_watcher_thread = None
temp_dir = None
if on_event:
log_file, temp_dir = _create_log_file("destroy")
args.extend(["--event-log", log_file])
log_watcher_thread = threading.Thread(
target=_watch_logs, args=(log_file, on_event)
)
log_watcher_thread.start()
try:
destroy_result = self._run_pulumi_cmd_sync(args, on_output)
finally:
_cleanup(temp_dir, log_watcher_thread)
summary = self.info(show_secrets)
assert summary is not None
return DestroyResult(
stdout=destroy_result.stdout, stderr=destroy_result.stderr, summary=summary
)
def get_config(self, key: str) -> ConfigValue:
"""
Returns the config value associated with the specified key.
:param key: The key for the config item to get.
:returns: ConfigValue
"""
return self.workspace.get_config(self.name, key)
def get_all_config(self) -> ConfigMap:
"""
Returns the full config map associated with the stack in the Workspace.
:returns: ConfigMap
"""
return self.workspace.get_all_config(self.name)
def set_config(self, key: str, value: ConfigValue) -> None:
"""
Sets a config key-value pair on the Stack in the associated Workspace.
:param key: The config key to add.
:param value: The config value to add.
"""
self.workspace.set_config(self.name, key, value)
def set_all_config(self, config: ConfigMap) -> None:
"""
Sets all specified config values on the stack in the associated Workspace.
:param config: A mapping of key to ConfigValue to set to config.
"""
self.workspace.set_all_config(self.name, config)
def remove_config(self, key: str) -> None:
"""
Removes the specified config key from the Stack in the associated Workspace.
:param key: The key to remove from config.
"""
self.workspace.remove_config(self.name, key)
def remove_all_config(self, keys: List[str]) -> None:
"""
Removes the specified config keys from the Stack in the associated Workspace.
:param keys: The keys to remove from config.
"""
self.workspace.remove_all_config(self.name, keys)
def refresh_config(self) -> None:
"""Gets and sets the config map used with the last update."""
self.workspace.refresh_config(self.name)
def outputs(self) -> OutputMap:
"""
Gets the current set of Stack outputs from the last Stack.up().
:returns: OutputMap
"""
return self.workspace.stack_outputs(self.name)
def history(
self,
page_size: Optional[int] = None,
page: Optional[int] = None,
show_secrets: bool = True,
) -> List[UpdateSummary]:
"""
Returns a list summarizing all previous and current results from Stack lifecycle operations
(up/preview/refresh/destroy).
:param page_size: Paginate history entries (used in combination with page), defaults to all.
:param page: Paginate history entries (used in combination with page_size), defaults to all.
:param show_secrets: Show config secrets when they appear in history.
:returns: List[UpdateSummary]
"""
args = ["stack", "history", "--json"]
if show_secrets:
args.append("--show-secrets")
if page_size is not None:
# default page=1 when page_size is set
if page is None:
page = 1
args.extend(["--page-size", str(page_size), "--page", str(page)])
result = self._run_pulumi_cmd_sync(args)
summary_list = json.loads(result.stdout)
summaries: List[UpdateSummary] = []
for summary_json in summary_list:
summary = UpdateSummary(
kind=summary_json["kind"],
start_time=datetime.strptime(
summary_json["startTime"], _DATETIME_FORMAT
),
message=summary_json["message"],
environment=summary_json["environment"],
config=summary_json["config"],
result=summary_json["result"],
end_time=datetime.strptime(summary_json["endTime"], _DATETIME_FORMAT)
if "endTime" in summary_json
else None,
version=summary_json["version"] if "version" in summary_json else None,
deployment=summary_json["Deployment"]
if "Deployment" in summary_json
else None,
resource_changes=summary_json["resourceChanges"]
if "resourceChanges" in summary_json
else None,
)
summaries.append(summary)
return summaries
def info(self, show_secrets=True) -> Optional[UpdateSummary]:
"""
Returns the current results from Stack lifecycle operations.
:returns: Optional[UpdateSummary]
"""
history = self.history(page_size=1, show_secrets=show_secrets)
if not history:
return None
return history[0]
def cancel(self) -> None:
"""
Cancel stops a stack's currently running update. It returns an error if no update is currently running.
Note that this operation is _very dangerous_, and may leave the stack in an inconsistent state
if a resource operation was pending when the update was canceled.
This command is not supported for local backends.
"""
self._run_pulumi_cmd_sync(["cancel", "--yes"])
def export_stack(self) -> Deployment:
"""
export_stack exports the deployment state of the stack.
This can be combined with Stack.import_state to edit a stack's state (such as recovery from failed deployments).
:returns: Deployment
"""
return self.workspace.export_stack(self.name)
def import_stack(self, state: Deployment) -> None:
"""
import_stack imports the specified deployment state into a pre-existing stack.
This can be combined with Stack.export_state to edit a stack's state (such as recovery from failed deployments).
:param state: The deployment state to import.
"""
return self.workspace.import_stack(self.name, state)
def _run_pulumi_cmd_sync(
self, args: List[str], on_output: Optional[OnOutput] = None
) -> CommandResult:
envs = {"PULUMI_DEBUG_COMMANDS": "true"}
if self.workspace.pulumi_home is not None:
envs = {**envs, "PULUMI_HOME": self.workspace.pulumi_home}
envs = {**envs, **self.workspace.env_vars}
additional_args = self.workspace.serialize_args_for_op(self.name)
args.extend(additional_args)
args.extend(["--stack", self.name])
result = _run_pulumi_cmd(args, self.workspace.work_dir, envs, on_output)
self.workspace.post_command_callback(self.name)
return result
def _parse_extra_args(**kwargs) -> List[str]:
extra_args: List[str] = []
message = kwargs.get("message")
expect_no_changes = kwargs.get("expect_no_changes")
diff = kwargs.get("diff")
replace = kwargs.get("replace")
target = kwargs.get("target")
policy_packs = kwargs.get("policy_packs")
policy_pack_configs = kwargs.get("policy_pack_configs")
target_dependents = kwargs.get("target_dependents")
parallel = kwargs.get("parallel")
color = kwargs.get("color")
log_flow = kwargs.get("log_flow")
log_verbosity = kwargs.get("log_verbosity")
log_to_std_err = kwargs.get("log_to_std_err")
tracing = kwargs.get("tracing")
debug = kwargs.get("debug")
if message:
extra_args.extend(["--message", message])
if expect_no_changes:
extra_args.append("--expect-no-changes")
if diff:
extra_args.append("--diff")
if replace:
for r in replace:
extra_args.extend(["--replace", r])
if target:
for t in target:
extra_args.extend(["--target", t])
if policy_packs:
for p in policy_packs:
extra_args.extend(["--policy-pack", p])
if policy_pack_configs:
for p in policy_pack_configs:
extra_args.extend(["--policy-pack-config", p])
if target_dependents:
extra_args.append("--target-dependents")
if parallel:
extra_args.extend(["--parallel", str(parallel)])
if color:
extra_args.extend(["--color", color])
if log_flow:
extra_args.extend(["--logflow"])
if log_verbosity:
extra_args.extend(["--verbose", log_verbosity])
if log_to_std_err:
extra_args.extend(["--logtostderr"])
if tracing:
extra_args.extend(["--tracing", tracing])
if debug:
extra_args.extend(["--debug"])
return extra_args
def fully_qualified_stack_name(org: str, project: str, stack: str) -> str:
"""
Returns a stack name formatted with the greatest possible specificity:
org/project/stack or user/project/stack
Using this format avoids ambiguity in stack identity guards creating or selecting the wrong stack.
Note that filestate backends (local file, S3, Azure Blob) do not support stack names in this
format, and instead only use the stack name without an org/user or project to qualify it.
See: https://github.com/pulumi/pulumi/issues/2522
:param org: The name of the org or user.
:param project: The name of the project.
:param stack: The name of the stack.
:returns: The fully qualified stack name.
"""
return f"{org}/{project}/{stack}"
def _create_log_file(command: str) -> Tuple[str, tempfile.TemporaryDirectory]:
log_dir = tempfile.TemporaryDirectory( # pylint: disable=consider-using-with
prefix=f"automation-logs-{command}-"
)
filepath = os.path.join(log_dir.name, "eventlog.txt")
# Open and close the file to ensure it exists before we start polling for logs
with open(filepath, "w+", encoding="utf-8"):
pass
return filepath, log_dir
def _watch_logs(filename: str, callback: OnEvent):
with open(filename, encoding="utf-8") as f:
while True:
line = f.readline()
# sleep if file hasn't been updated
if not line:
time.sleep(0.1)
continue
event = EngineEvent.from_json(json.loads(line))
callback(event)
# if this is the cancel event, stop watching logs.
if event.cancel_event:
break
def _cleanup(
temp_dir: Optional[tempfile.TemporaryDirectory],
thread: Optional[threading.Thread],
on_exit_fn: Optional[Callable[[], None]] = None,
) -> None:
# If there's an on_exit function, execute it (used in preview/up to shut down server)
if on_exit_fn:
on_exit_fn()
# If we started a thread to watch logs, wait for it to terminate, timing out after 5 seconds.
if thread:
thread.join(5)
# If we created a temp_dir for the logs, clean up.
if temp_dir:
temp_dir.cleanup()