1 import json
2 import re
3 import sys
4 from collections.abc import Callable, Mapping
5 from functools import partial
6 from typing import TYPE_CHECKING, Any
7 from xml.dom.minidom import parseString
8
9 import pcs.lib.pacemaker.live as lib_pacemaker
10 import pcs.lib.resource_agent as lib_ra
11 from pcs import constraint, utils
12 from pcs.cli.cluster_property.output import PropertyConfigurationFacade
13 from pcs.cli.common.errors import CmdLineInputError
14 from pcs.cli.common.output import format_wrap_for_terminal
15 from pcs.cli.common.parse_args import (
16 FUTURE_OPTION,
17 FUTURE_OPTION_DEPRECATION_WARNING,
18 OUTPUT_FORMAT_VALUE_CMD,
19 OUTPUT_FORMAT_VALUE_JSON,
20 OUTPUT_FORMAT_VALUE_TEXT,
21 Argv,
22 InputModifiers,
23 KeyValueParser,
24 get_rule_str,
25 group_by_keywords,
26 wait_to_timeout,
27 )
28 from pcs.cli.common.tools import print_to_stderr, timeout_to_seconds_legacy
29 from pcs.cli.nvset import filter_out_expired_nvset, nvset_dto_list_to_lines
30 from pcs.cli.reports.output import deprecation_warning, error, warn
31 from pcs.cli.reports.processor import (
32 ReportProcessorToConsole,
33 report_and_exit_on_error,
34 )
35 from pcs.cli.resource.common import check_is_not_stonith
36 from pcs.cli.resource.output import (
37 operation_defaults_to_cmd,
38 resource_agent_metadata_to_text,
39 resource_defaults_to_cmd,
40 )
41 from pcs.cli.resource.parse_args import (
42 get_wait_timeout_deprecated,
43 parse_bundle_create_options,
44 parse_bundle_reset_options,
45 parse_bundle_update_options,
46 parse_clone,
47 parse_create,
48 )
49 from pcs.cli.resource_agent import find_single_agent
50 from pcs.common import const, pacemaker, reports
51 from pcs.common.interface import dto
52 from pcs.common.pacemaker.defaults import CibDefaultsDto
53 from pcs.common.pacemaker.resource.operations import (
54 OCF_CHECK_LEVEL_INSTANCE_ATTRIBUTE_NAME,
55 )
56 from pcs.lib.cib import const as cib_const
57 from pcs.lib.cib.resource import guest_node, operations, primitive
58 from pcs.lib.cib.tools import get_resources
59 from pcs.lib.commands.resource import (
60 _get_nodes_to_validate_against,
61 _validate_guest_change,
62 )
63 from pcs.lib.errors import LibraryError
64 from pcs.lib.pacemaker.values import is_true, validate_id
65 from pcs.settings import (
66 pacemaker_wait_timeout_status as PACEMAKER_WAIT_TIMEOUT_STATUS,
67 )
68
69 if TYPE_CHECKING:
70 from pcs.common.resource_agent.dto import ResourceAgentNameDto
71
72 RESOURCE_RELOCATE_CONSTRAINT_PREFIX = "pcs-relocate-"
73
74
75 def _detect_guest_change(
76 meta_attributes: Mapping[str, str], allow_not_suitable_command: bool
77 ) -> None:
78 """
79 Commandline options:
80 * -f - CIB file
81 """
82 if not guest_node.is_node_name_in_options(meta_attributes):
83 return
84
85 env = utils.get_lib_env()
86 cib = env.get_cib()
87 (
88 existing_nodes_names,
89 existing_nodes_addrs,
90 report_list,
91 ) = _get_nodes_to_validate_against(env, cib)
92 if env.report_processor.report_list(
93 report_list
94 + _validate_guest_change(
95 cib,
96 existing_nodes_names,
97 existing_nodes_addrs,
98 meta_attributes,
99 allow_not_suitable_command,
100 detect_remove=True,
101 )
102 ).has_errors:
103 raise LibraryError()
104
105
106 def resource_utilization_cmd(
107 lib: Any, argv: Argv, modifiers: InputModifiers
108 ) -> None:
109 """
110 Options:
111 * -f - CIB file
112 """
113 modifiers.ensure_only_supported("-f")
114 resource_id = None
115 if argv:
116 resource_id = argv.pop(0)
117 check_is_not_stonith(lib, [resource_id])
118 utils.print_warning_if_utilization_attrs_has_no_effect(
119 PropertyConfigurationFacade.from_properties_dtos(
120 lib.cluster_property.get_properties(),
121 lib.cluster_property.get_properties_metadata(),
122 )
123 )
124 if not resource_id:
125 print_resources_utilization()
126 return
127 if argv:
128 set_resource_utilization(resource_id, argv)
129 else:
130 print_resource_utilization(resource_id)
131
132
133 def _defaults_set_create_cmd(
134 lib_command: Callable[..., Any], argv: Argv, modifiers: InputModifiers
135 ) -> None:
136 modifiers.ensure_only_supported("-f", "--force")
137
138 groups = group_by_keywords(
139 argv, {"meta", "rule"}, implicit_first_keyword="options"
140 )
141 groups.ensure_unique_keywords()
142 force_flags = set()
143 if modifiers.get("--force"):
144 force_flags.add(reports.codes.FORCE)
145
146 lib_command(
147 KeyValueParser(groups.get_args_flat("meta")).get_unique(),
148 KeyValueParser(groups.get_args_flat("options")).get_unique(),
149 nvset_rule=get_rule_str(groups.get_args_flat("rule")),
150 force_flags=force_flags,
151 )
152
153
154 def resource_defaults_set_create_cmd(
155 lib: Any, argv: Argv, modifiers: InputModifiers
156 ) -> None:
157 """
158 Options:
159 * -f - CIB file
160 * --force - allow unknown options
161 """
162 return _defaults_set_create_cmd(
163 lib.cib_options.resource_defaults_create, argv, modifiers
164 )
165
166
167 def resource_op_defaults_set_create_cmd(
168 lib: Any, argv: Argv, modifiers: InputModifiers
169 ) -> None:
170 """
171 Options:
172 * -f - CIB file
173 * --force - allow unknown options
174 """
175 return _defaults_set_create_cmd(
176 lib.cib_options.operation_defaults_create, argv, modifiers
177 )
178
179
180 def _filter_defaults(
181 cib_defaults_dto: CibDefaultsDto, include_expired: bool
182 ) -> CibDefaultsDto:
183 return CibDefaultsDto(
184 instance_attributes=(
185 cib_defaults_dto.instance_attributes
186 if include_expired
187 else filter_out_expired_nvset(cib_defaults_dto.instance_attributes)
188 ),
189 meta_attributes=(
190 cib_defaults_dto.meta_attributes
191 if include_expired
192 else filter_out_expired_nvset(cib_defaults_dto.meta_attributes)
193 ),
194 )
195
196
197 def _defaults_config_cmd(
198 lib_command: Callable[[bool], CibDefaultsDto],
199 defaults_to_cmd: Callable[[CibDefaultsDto], list[list[str]]],
200 argv: Argv,
201 modifiers: InputModifiers,
202 ) -> None:
203 """
204 Options:
205 * -f - CIB file
206 * --all - display all nvsets including the ones with expired rules
207 * --full - verbose output
208 * --no-expire-check -- disable evaluating whether rules are expired
209 * --output-format - supported formats: text, cmd, json
210 """
211 if argv:
212 raise CmdLineInputError()
213 modifiers.ensure_only_supported(
214 "-f",
215 "--all",
216 "--full",
217 "--no-expire-check",
218 output_format_supported=True,
219 )
220 modifiers.ensure_not_mutually_exclusive("--all", "--no-expire-check")
221 output_format = modifiers.get_output_format()
222 if (
223 modifiers.is_specified("--full")
224 and output_format != OUTPUT_FORMAT_VALUE_TEXT
225 ):
226 raise CmdLineInputError(
227 f"option '--full' is not compatible with '{output_format}' output format."
228 )
229 cib_defaults_dto = _filter_defaults(
230 lib_command(not modifiers.get("--no-expire-check")),
231 bool(modifiers.get("--all")),
232 )
233 if output_format == OUTPUT_FORMAT_VALUE_CMD:
234 output = ";\n".join(
235 " \\\n".join(cmd) for cmd in defaults_to_cmd(cib_defaults_dto)
236 )
237 elif output_format == OUTPUT_FORMAT_VALUE_JSON:
238 output = json.dumps(dto.to_dict(cib_defaults_dto))
239 else:
240 output = "\n".join(
241 nvset_dto_list_to_lines(
242 cib_defaults_dto.meta_attributes,
243 nvset_label="Meta Attrs",
244 with_ids=bool(modifiers.get("--full")),
245 )
246 )
247 if output:
248 print(output)
249
250
251 def resource_defaults_config_cmd(
252 lib: Any, argv: Argv, modifiers: InputModifiers
253 ) -> None:
254 """
255 Options:
256 * -f - CIB file
257 * --full - verbose output
258 """
259 return _defaults_config_cmd(
260 lib.cib_options.resource_defaults_config,
261 resource_defaults_to_cmd,
262 argv,
263 modifiers,
264 )
265
266
267 def resource_op_defaults_config_cmd(
268 lib: Any, argv: Argv, modifiers: InputModifiers
269 ) -> None:
270 """
271 Options:
272 * -f - CIB file
273 * --full - verbose output
274 """
275 return _defaults_config_cmd(
276 lib.cib_options.operation_defaults_config,
277 operation_defaults_to_cmd,
278 argv,
279 modifiers,
280 )
281
282
283 def _defaults_set_remove_cmd(
284 lib_command: Callable[..., Any], argv: Argv, modifiers: InputModifiers
285 ) -> None:
286 """
287 Options:
288 * -f - CIB file
289 """
290 modifiers.ensure_only_supported("-f")
291 lib_command(argv)
292
293
294 def resource_defaults_set_remove_cmd(
295 lib: Any, argv: Argv, modifiers: InputModifiers
296 ) -> None:
297 """
298 Options:
299 * -f - CIB file
300 """
301 return _defaults_set_remove_cmd(
302 lib.cib_options.resource_defaults_remove, argv, modifiers
303 )
304
305
306 def resource_op_defaults_set_remove_cmd(
307 lib: Any, argv: Argv, modifiers: InputModifiers
308 ) -> None:
309 """
310 Options:
311 * -f - CIB file
312 """
313 return _defaults_set_remove_cmd(
314 lib.cib_options.operation_defaults_remove, argv, modifiers
315 )
316
317
318 def _defaults_set_update_cmd(
319 lib_command: Callable[..., Any], argv: Argv, modifiers: InputModifiers
320 ) -> None:
321 """
322 Options:
323 * -f - CIB file
324 """
325 modifiers.ensure_only_supported("-f")
326 if not argv:
327 raise CmdLineInputError()
328
329 set_id = argv[0]
330 groups = group_by_keywords(argv[1:], {"meta"})
331 groups.ensure_unique_keywords()
332 lib_command(
333 set_id, KeyValueParser(groups.get_args_flat("meta")).get_unique()
334 )
335
336
337 def resource_defaults_set_update_cmd(
338 lib: Any, argv: Argv, modifiers: InputModifiers
339 ) -> None:
340 """
341 Options:
342 * -f - CIB file
343 """
344 return _defaults_set_update_cmd(
345 lib.cib_options.resource_defaults_update, argv, modifiers
346 )
347
348
349 def resource_op_defaults_set_update_cmd(
350 lib: Any, argv: Argv, modifiers: InputModifiers
351 ) -> None:
352 """
353 Options:
354 * -f - CIB file
355 """
356 return _defaults_set_update_cmd(
357 lib.cib_options.operation_defaults_update, argv, modifiers
358 )
359
360
361 def resource_defaults_update_cmd(
362 lib: Any,
363 argv: Argv,
364 modifiers: InputModifiers,
365 ) -> None:
366 """
367 Options:
368 * -f - CIB file
369 """
370 del modifiers
371 return lib.cib_options.resource_defaults_update(
372 None, KeyValueParser(argv).get_unique()
373 )
374
375
376 def resource_op_defaults_update_cmd(
377 lib: Any,
378 argv: Argv,
379 modifiers: InputModifiers,
380 ) -> None:
381 """
382 Options:
383 * -f - CIB file
384 """
385 del modifiers
386 return lib.cib_options.operation_defaults_update(
387 None, KeyValueParser(argv).get_unique()
388 )
389
390
391 def op_add_cmd(lib: Any, argv: Argv, modifiers: InputModifiers) -> None:
392 """
393 Options:
394 * -f - CIB file
395 * --force - allow unknown options
396 """
397 if not argv:
398 raise CmdLineInputError()
399 check_is_not_stonith(lib, [argv[0]], "pcs stonith op add")
400 resource_op_add(lib.env.report_processor, argv, modifiers)
401
402
403 def resource_op_add(
404 report_processor: ReportProcessorToConsole,
405 argv: Argv,
406 modifiers: InputModifiers,
407 ) -> None:
408 """
409 Commandline options:
410 * -f - CIB file
411 * --force - allow unknown options
412 """
413 modifiers.ensure_only_supported("-f", "--force")
414 if not argv:
415 raise CmdLineInputError()
416 res_id = argv.pop(0)
417
418 # Check if we need to upgrade cib schema.
419 # To do that, argv must be parsed, which is duplication of parsing in
420 # resource_operation_add. But we need to upgrade the cib first before
421 # calling that function. Hopefully, this will be fixed in the new pcs
422 # architecture.
423
424 # argv[0] is an operation name
425 dom = None
426 op_properties = utils.convert_args_to_tuples(argv[1:])
427 for key, value in op_properties:
428 if key == "on-fail" and value == "demote":
429 dom = utils.cluster_upgrade_to_version(
430 const.PCMK_ON_FAIL_DEMOTE_CIB_VERSION
431 )
432 break
433 if dom is None:
434 dom = utils.get_cib_dom()
435
436 res_el = utils.dom_get_resource(dom, res_id)
437 if not res_el:
438 utils.err("Unable to find resource: %s" % res_id)
439
440 agent_name = _get_resource_agent_name_from_rsc_el(res_el)
441 try:
442 agent_facade = _get_resource_agent_facade(agent_name)
443 except lib_ra.ResourceAgentError as e:
444 if bool(modifiers.get("--force")):
445 severity = reports.ReportItemSeverity.warning()
446 agent_facade = _get_void_resource_agent_facade(agent_name)
447 else:
448 severity = reports.ReportItemSeverity.error(reports.codes.FORCE)
449 report_and_exit_on_error(
450 report_processor,
451 [lib_ra.resource_agent_error_to_report_item(e, severity)],
452 )
453
454 allowed_operation_name_list = [
455 op.name for op in agent_facade.metadata.actions
456 ]
457 utils.replace_cib_configuration(
458 resource_operation_add(
459 report_processor,
460 dom,
461 res_id,
462 argv,
463 allowed_operation_name_list=allowed_operation_name_list,
464 )
465 )
466
467
468 def op_delete_cmd(lib: Any, argv: Argv, modifiers: InputModifiers) -> None:
469 """
470 Options:
471 * -f - CIB file
472 """
473 modifiers.ensure_only_supported("-f")
474 if not argv:
475 raise CmdLineInputError()
476 resource_id = argv.pop(0)
477 check_is_not_stonith(lib, [resource_id], "pcs stonith op delete")
478 resource_operation_remove(resource_id, argv)
479
480
481 def parse_resource_options(
482 argv: Argv,
483 ) -> tuple[list[str], list[list[str]], list[str]]:
484 """
485 Commandline options: no options
486 """
487 ra_values = []
488 op_values: list[list[str]] = []
489 meta_values = []
490 op_args = False
491 meta_args = False
492 for arg in argv:
493 if arg == "op":
494 op_args = True
495 meta_args = False
496 op_values.append([])
497 elif arg == "meta":
498 meta_args = True
499 op_args = False
500 elif op_args:
501 if arg == "op":
502 op_values.append([])
503 elif "=" not in arg and op_values[-1]:
504 op_values.append([])
505 op_values[-1].append(arg)
506 else:
507 op_values[-1].append(arg)
508 elif meta_args:
509 if "=" in arg:
510 meta_values.append(arg)
511 else:
512 ra_values.append(arg)
513 return ra_values, op_values, meta_values
514
515
516 def resource_list_available(
517 lib: Any, argv: Argv, modifiers: InputModifiers
518 ) -> None:
519 """
520 Options:
521 * --nodesc - don't display description
522 """
523 modifiers.ensure_only_supported("--nodesc")
524 if len(argv) > 1:
525 raise CmdLineInputError()
526
527 search = argv[0] if argv else None
528 agent_list = lib.resource_agent.list_agents(
529 not modifiers.get("--nodesc"), search
530 )
531
532 if not agent_list:
533 if search:
534 utils.err("No resource agents matching the filter.")
535 utils.err(
536 "No resource agents available. Do you have resource agents installed?"
537 )
538
539 for agent_info in agent_list:
540 name = agent_info["name"]
541 shortdesc = agent_info["shortdesc"]
542 if shortdesc:
543 normalized_desc = " ".join(shortdesc.split())
544 print(
545 "\n".join(
546 format_wrap_for_terminal(f"{name} - {normalized_desc}")
547 )
548 )
549 else:
550 print(name)
551
552
553 def resource_list_options(
554 lib: Any, argv: Argv, modifiers: InputModifiers
555 ) -> None:
556 """
557 Options:
558 * --full - show advanced
559 """
560 modifiers.ensure_only_supported("--full")
561 if len(argv) != 1:
562 raise CmdLineInputError()
563
564 agent_name_str = argv[0]
565 agent_name: ResourceAgentNameDto
566 if ":" in agent_name_str:
567 agent_name = lib.resource_agent.get_structured_agent_name(
568 agent_name_str
569 )
570 else:
571 agent_name = find_single_agent(
572 lib.resource_agent.get_agents_list().names, agent_name_str
573 )
574 if agent_name.standard == "stonith":
575 error(
576 reports.messages.CommandArgumentTypeMismatch(
577 "stonith / fence agents"
578 ).message
579 + " Please use 'pcs stonith describe' instead."
580 )
581 print(
582 "\n".join(
583 resource_agent_metadata_to_text(
584 lib.resource_agent.get_agent_metadata(agent_name),
585 lib.resource_agent.get_agent_default_operations(
586 agent_name
587 ).operations,
588 verbose=modifiers.is_specified("--full"),
589 )
590 )
591 )
592
593
594 def resource_create(lib: Any, argv: Argv, modifiers: InputModifiers) -> None: # noqa: PLR0912
595 """
596 Options:
597 * --agent-validation - use agent self validation of instance attributes
598 * --force - allow not existing agent, invalid operations or invalid
599 instance attributes, allow not suitable command
600 * --disabled - created resource will be disabled
601 * --no-default-ops - do not add default operations
602 * --wait
603 * -f - CIB file
604 * --future - no longer has any effect, only prints a deprecation warning
605 """
606 modifiers.ensure_only_supported(
607 "--agent-validation",
608 "--force",
609 "--disabled",
610 "--no-default-ops",
611 "--wait",
612 "-f",
613 FUTURE_OPTION,
614 hint_syntax_changed="1.0",
615 )
616 modifiers.ensure_not_mutually_exclusive("-f", "--wait")
617 # deprecated in the first version of 0.12
618 wait_timeout = get_wait_timeout_deprecated(
619 lib.env.report_processor, modifiers
620 )
621 if modifiers.is_specified(FUTURE_OPTION):
622 deprecation_warning(FUTURE_OPTION_DEPRECATION_WARNING)
623
624 if len(argv) < 2:
625 raise CmdLineInputError()
626
627 ra_id = argv[0]
628 ra_type = argv[1]
629
630 parts = parse_create(argv[2:])
631
632 defined_options = set()
633 if parts.bundle_id:
634 defined_options.add("bundle")
635 if parts.clone:
636 defined_options.add("clone")
637 if parts.promotable:
638 defined_options.add("promotable")
639 if parts.group:
640 defined_options.add("group")
641 if len(defined_options) > 1:
642 raise CmdLineInputError(
643 "you can specify only one of clone, promotable, bundle or group"
644 )
645
646 if parts.group:
647 if parts.group.after_resource and parts.group.before_resource:
648 raise CmdLineInputError(
649 "you cannot specify both 'before' and 'after'"
650 )
651
652 if parts.promotable and "promotable" in parts.promotable.meta_attrs:
653 raise CmdLineInputError(
654 "you cannot specify both promotable option and promotable keyword"
655 )
656
657 settings = dict(
658 allow_absent_agent=modifiers.get("--force"),
659 allow_invalid_operation=modifiers.get("--force"),
660 allow_invalid_instance_attributes=modifiers.get("--force"),
661 ensure_disabled=modifiers.get("--disabled"),
662 use_default_operations=not modifiers.get("--no-default-ops"),
663 allow_not_suitable_command=modifiers.get("--force"),
664 enable_agent_self_validation=modifiers.get("--agent-validation"),
665 )
666
667 if parts.clone:
668 lib.resource.create_as_clone(
669 ra_id,
670 ra_type,
671 parts.primitive.operations,
672 parts.primitive.meta_attrs,
673 parts.primitive.instance_attrs,
674 parts.clone.meta_attrs,
675 clone_id=parts.clone.clone_id,
676 allow_incompatible_clone_meta_attributes=modifiers.get("--force"),
677 **settings,
678 )
679 elif parts.promotable:
680 lib.resource.create_as_clone(
681 ra_id,
682 ra_type,
683 parts.primitive.operations,
684 parts.primitive.meta_attrs,
685 parts.primitive.instance_attrs,
686 dict(**parts.promotable.meta_attrs, promotable="true"),
687 clone_id=parts.promotable.clone_id,
688 allow_incompatible_clone_meta_attributes=modifiers.get("--force"),
689 **settings,
690 )
691 elif parts.bundle_id:
692 settings["allow_not_accessible_resource"] = modifiers.get("--force")
693 lib.resource.create_into_bundle(
694 ra_id,
695 ra_type,
696 parts.primitive.operations,
697 parts.primitive.meta_attrs,
698 parts.primitive.instance_attrs,
699 parts.bundle_id,
700 **settings,
701 )
702 elif parts.group:
703 adjacent_resource_id = None
704 put_after_adjacent = False
705 if parts.group.after_resource:
706 adjacent_resource_id = parts.group.after_resource
707 put_after_adjacent = True
708 if parts.group.before_resource:
709 adjacent_resource_id = parts.group.before_resource
710 put_after_adjacent = False
711
712 lib.resource.create_in_group(
713 ra_id,
714 ra_type,
715 parts.group.group_id,
716 parts.primitive.operations,
717 parts.primitive.meta_attrs,
718 parts.primitive.instance_attrs,
719 adjacent_resource_id=adjacent_resource_id,
720 put_after_adjacent=put_after_adjacent,
721 **settings,
722 )
723 else:
724 lib.resource.create(
725 ra_id,
726 ra_type,
727 parts.primitive.operations,
728 parts.primitive.meta_attrs,
729 parts.primitive.instance_attrs,
730 **settings,
731 )
732
733 if wait_timeout >= 0:
734 lib.cluster.wait_for_pcmk_idle(wait_timeout)
735
736
737 def _parse_resource_move_ban(
738 argv: Argv,
739 ) -> tuple[str, str | None, str | None]:
740 resource_id = argv.pop(0)
741 node = None
742 lifetime = None
743 while argv:
744 arg = argv.pop(0)
745 if arg.startswith("lifetime="):
746 if lifetime:
747 raise CmdLineInputError()
748 lifetime = arg.split("=")[1]
749 if lifetime and lifetime[0] in list("0123456789"):
750 lifetime = "P" + lifetime
751 elif not node:
752 node = arg
753 else:
754 raise CmdLineInputError()
755 return resource_id, node, lifetime
756
757
758 def resource_move_with_constraint(
759 lib: Any, argv: Argv, modifiers: InputModifiers
760 ) -> None:
761 """
762 Options:
763 * -f - CIB file
764 * --promoted - limit the constraint to the Promoted role
765 * --wait - wait for the cluster to settle
766 """
767 modifiers.ensure_only_supported("-f", "--promoted", "--wait")
768 modifiers.ensure_not_mutually_exclusive("-f", "--wait")
769 # deprecated in the first version of 0.12
770 wait_timeout = get_wait_timeout_deprecated(
771 lib.env.report_processor, modifiers
772 )
773
774 if not argv:
775 raise CmdLineInputError("must specify a resource to move")
776 if len(argv) > 3:
777 raise CmdLineInputError()
778 resource_id, node, lifetime = _parse_resource_move_ban(argv)
779
780 lib.resource.move(
781 resource_id,
782 node=node,
783 master=modifiers.is_specified("--promoted"),
784 lifetime=lifetime,
785 )
786
787 if wait_timeout >= 0:
788 lib.cluster.wait_for_pcmk_idle(wait_timeout)
789
790
791 def resource_move(lib: Any, argv: Argv, modifiers: InputModifiers) -> None:
792 """
793 Options:
794 * --promoted
795 * --strict
796 * --wait
797 """
798 modifiers.ensure_only_supported(
799 "--promoted", "--strict", "--wait", hint_syntax_changed="0.12"
800 )
801
802 if not argv:
803 raise CmdLineInputError("must specify a resource to move")
804 resource_id = argv.pop(0)
805 node = None
806 if argv:
807 node = argv.pop(0)
808 if argv:
809 raise CmdLineInputError()
810
811 lib.resource.move_autoclean(
812 resource_id,
813 node=node,
814 master=modifiers.is_specified("--promoted"),
815 wait_timeout=wait_to_timeout(modifiers.get("--wait")),
816 strict=modifiers.get("--strict"),
817 )
818
819
820 def resource_ban(lib: Any, argv: Argv, modifiers: InputModifiers) -> None:
821 """
822 Options:
823 * -f - CIB file
824 * --promoted - limit the constraint to the Promoted role
825 * --wait - wait for the cluster to settle
826 """
827 modifiers.ensure_only_supported("-f", "--promoted", "--wait")
828 modifiers.ensure_not_mutually_exclusive("-f", "--wait")
829 # deprecated in the first version of 0.12
830 wait_timeout = get_wait_timeout_deprecated(
831 lib.env.report_processor, modifiers
832 )
833
834 if not argv:
835 raise CmdLineInputError("must specify a resource to ban")
836 if len(argv) > 3:
837 raise CmdLineInputError()
838 resource_id, node, lifetime = _parse_resource_move_ban(argv)
839
840 lib.resource.ban(
841 resource_id,
842 node=node,
843 master=modifiers.is_specified("--promoted"),
844 lifetime=lifetime,
845 )
846
847 if wait_timeout >= 0:
848 lib.cluster.wait_for_pcmk_idle(wait_timeout)
849
850
851 def resource_unmove_unban(
852 lib: Any, argv: Argv, modifiers: InputModifiers
853 ) -> None:
854 """
855 Options:
856 * --expired - only remove constraints which have already expired
857 * -f - CIB file
858 * --promoted - only remove constraints for Promoted role
859 * --wait - wait for the cluster to settle
860 """
861 modifiers.ensure_only_supported("-f", "--expired", "--promoted", "--wait")
862 modifiers.ensure_not_mutually_exclusive("-f", "--wait")
863 # deprecated in the first version of 0.12
864 wait_timeout = get_wait_timeout_deprecated(
865 lib.env.report_processor, modifiers
866 )
867
868 if not argv:
869 raise CmdLineInputError("must specify a resource to clear")
870 if len(argv) > 2:
871 raise CmdLineInputError()
872 resource_id = argv.pop(0)
873 node = argv.pop(0) if argv else None
874
875 lib.resource.unmove_unban(
876 resource_id,
877 node=node,
878 master=modifiers.is_specified("--promoted"),
879 expired=modifiers.is_specified("--expired"),
880 )
881
882 if wait_timeout >= 0:
883 lib.cluster.wait_for_pcmk_idle(wait_timeout)
884
885
886 def resource_standards(lib: Any, argv: Argv, modifiers: InputModifiers) -> None:
887 """
888 Options: no options
889 """
890 modifiers.ensure_only_supported()
891 if argv:
892 raise CmdLineInputError()
893
894 standards = lib.resource_agent.list_standards()
895
896 if standards:
897 print("\n".join(standards))
898 else:
899 utils.err("No standards found")
900
901
902 def resource_providers(lib: Any, argv: Argv, modifiers: InputModifiers) -> None:
903 """
904 Options: no options
905 """
906 modifiers.ensure_only_supported()
907 if argv:
908 raise CmdLineInputError()
909
910 providers = lib.resource_agent.list_ocf_providers()
911
912 if providers:
913 print("\n".join(providers))
914 else:
915 utils.err("No OCF providers found")
916
917
918 def resource_agents(lib: Any, argv: Argv, modifiers: InputModifiers) -> None:
919 """
920 Options: no options
921 """
922 modifiers.ensure_only_supported()
923 if len(argv) > 1:
924 raise CmdLineInputError()
925
926 standard = argv[0] if argv else None
927
928 agents = lib.resource_agent.list_agents_for_standard_and_provider(standard)
929
930 if agents:
931 print("\n".join(agents))
932 else:
933 utils.err(
934 "No agents found{0}".format(
935 " for {0}".format(argv[0]) if argv else ""
936 )
937 )
938
939
940 def update_cmd(lib: Any, argv: Argv, modifiers: InputModifiers) -> None:
941 """
942 Options:
943 * -f - CIB file
944 * --agent-validation - use agent self validation of instance attributes
945 * --wait
946 * --force - allow invalid options, do not fail if not possible to get
947 agent metadata, allow not suitable command
948 """
949 if not argv:
950 raise CmdLineInputError()
951 check_is_not_stonith(lib, [argv[0]], "pcs stonith update")
952 resource_update(lib.env.report_processor, argv, modifiers)
953
954
955 # Update a resource, removing any args that are empty and adding/updating
956 # args that are not empty
957 def resource_update( # noqa: PLR0912, PLR0915
958 report_processor: ReportProcessorToConsole,
959 args: Argv,
960 modifiers: InputModifiers,
961 ) -> None:
962 """
963 Commandline options:
964 * -f - CIB file
965 * --agent-validation - use agent self validation of instance attributes
966 * --wait
967 * --force - allow invalid options, do not fail if not possible to get
968 agent metadata, allow not suitable command
969 """
970 modifiers.ensure_only_supported(
971 "-f", "--wait", "--force", "--agent-validation"
972 )
973 if len(args) < 2:
974 raise CmdLineInputError()
975 res_id = args.pop(0)
976
977 # Extract operation arguments
978 ra_values, op_values, meta_values = parse_resource_options(args)
979
980 wait = False
981 wait_timeout = None
982 if modifiers.is_specified("--wait"):
983 # deprecated in the first version of 0.12
984 report_processor.report(
985 reports.ReportItem.deprecation(
986 reports.messages.ResourceWaitDeprecated()
987 )
988 )
989 wait_timeout = utils.validate_wait_get_timeout()
990 wait = True
991
992 # Check if we need to upgrade cib schema.
993 # To do that, argv must be parsed, which is duplication of parsing below.
994 # But we need to upgrade the cib first before calling that function.
995 # Hopefully, this will be fixed in the new pcs architecture.
996
997 cib_upgraded = False
998 for op_argv in op_values:
999 if cib_upgraded:
1000 break
1001 if len(op_argv) < 2:
1002 continue
1003 # argv[0] is an operation name
1004 op_vars = utils.convert_args_to_tuples(op_argv[1:])
1005 for key, value in op_vars:
1006 if key == "on-fail" and value == "demote":
1007 utils.cluster_upgrade_to_version(
1008 const.PCMK_ON_FAIL_DEMOTE_CIB_VERSION
1009 )
1010 cib_upgraded = True
1011 break
1012
1013 cib_xml = utils.get_cib()
1014 dom = utils.get_cib_dom(cib_xml=cib_xml)
1015
1016 resource = utils.dom_get_resource(dom, res_id)
1017 if not resource:
1018 clone = utils.dom_get_clone(dom, res_id)
1019 master = utils.dom_get_master(dom, res_id)
1020 if clone or master:
1021 if master:
1022 clone = transform_master_to_clone(master)
1023 clone_child = utils.dom_elem_get_clone_ms_resource(clone)
1024 if clone_child:
1025 child_id = clone_child.getAttribute("id")
1026 new_args = ["meta"] + ra_values + meta_values
1027 for op_args in op_values:
1028 if op_args:
1029 new_args += ["op"] + op_args
1030 return resource_update_clone(
1031 report_processor,
1032 dom,
1033 clone,
1034 child_id,
1035 new_args,
1036 wait,
1037 wait_timeout,
1038 )
1039 utils.err("Unable to find resource: %s" % res_id)
1040
1041 params = utils.convert_args_to_tuples(ra_values)
1042
1043 agent_name = _get_resource_agent_name_from_rsc_el(resource)
1044 try:
1045 agent_facade = _get_resource_agent_facade(agent_name)
1046 allowed_operation_name_list = [
1047 op.name for op in agent_facade.metadata.actions
1048 ]
1049 report_list = primitive.validate_resource_instance_attributes_update(
1050 utils.cmd_runner(),
1051 agent_facade,
1052 dict(params),
1053 res_id,
1054 get_resources(lib_pacemaker.get_cib(cib_xml)),
1055 force=bool(modifiers.get("--force")),
1056 enable_agent_self_validation=bool(
1057 modifiers.get("--agent-validation")
1058 ),
1059 )
1060 if report_list:
1061 report_and_exit_on_error(report_processor, report_list)
1062 except lib_ra.ResourceAgentError as e:
1063 report_and_exit_on_error(
1064 report_processor,
1065 [
1066 lib_ra.resource_agent_error_to_report_item(
1067 e,
1068 reports.get_severity(
1069 reports.codes.FORCE, bool(modifiers.get("--force"))
1070 ),
1071 )
1072 ],
1073 )
1074 # If --force is not specified, report_and_exit_on_error raises, and the
1075 # command ends. Otherwise we continue with a void agent facade.
1076 agent_facade = _get_void_resource_agent_facade(agent_name)
1077 allowed_operation_name_list = [
1078 op.name for op in agent_facade.metadata.actions
1079 ]
1080
1081 utils.dom_update_instance_attr(resource, params)
1082
1083 remote_node_name = utils.dom_get_resource_remote_node_name(resource)
1084
1085 # The "remote-node" meta attribute makes sense (and causes creation of
1086 # inner pacemaker resource) only for primitive. The meta attribute
1087 # "remote-node" has no special meaning for clone/master. So there is no
1088 # need for checking this attribute in clone/master.
1089 #
1090 # It is ok to not to check it until this point in this function:
1091 # 1) Only master/clone element is updated if the parameter "res_id" is an id
1092 # of the clone/master element. In that case another function is called and
1093 # the code path does not reach this point.
1094 # 2) No persistent changes happened until this line if the parameter
1095 # "res_id" is an id of the primitive.
1096 meta_options = KeyValueParser(meta_values).get_unique()
1097 if remote_node_name != guest_node.get_guest_option_value(meta_options):
1098 _detect_guest_change(
1099 meta_options,
1100 bool(modifiers.get("--force")),
1101 )
1102
1103 # TODO: validation should be added after migrating the command to the new
1104 # architecture
1105 if any(meta_options.values()):
1106 command = "stonith" if agent_name.is_stonith else "resource"
1107 warn(
1108 "Meta attributes are not validated by this command. For "
1109 f"validation, please use 'pcs {command} meta' instead."
1110 )
1111
1112 utils.dom_update_meta_attr(
1113 resource, utils.convert_args_to_tuples(meta_values)
1114 )
1115
1116 operations_el = resource.getElementsByTagName("operations")
1117 if not operations_el:
1118 operations_el = dom.createElement("operations")
1119 resource.appendChild(operations_el)
1120 else:
1121 operations_el = operations_el[0]
1122
1123 get_role = partial(
1124 pacemaker.role.get_value_for_cib,
1125 is_latest_supported=utils.isCibVersionSatisfied(
1126 dom, const.PCMK_NEW_ROLES_CIB_VERSION
1127 ),
1128 )
1129 for op_argv in op_values:
1130 if not op_argv:
1131 continue
1132
1133 op_name = op_argv[0]
1134 if op_name.find("=") != -1:
1135 utils.err(
1136 "%s does not appear to be a valid operation action" % op_name
1137 )
1138
1139 if len(op_argv) < 2:
1140 continue
1141
1142 op_role = ""
1143 op_vars = utils.convert_args_to_tuples(op_argv[1:])
1144
1145 for key, value in op_vars:
1146 if key == "role":
1147 op_role = get_role(value)
1148 break
1149
1150 updating_op = None
1151 updating_op_before = None
1152 for existing_op in operations_el.getElementsByTagName("op"):
1153 if updating_op:
1154 updating_op_before = existing_op
1155 break
1156 existing_op_name = existing_op.getAttribute("name")
1157 existing_op_role = get_role(existing_op.getAttribute("role"))
1158 if existing_op_role == op_role and existing_op_name == op_name:
1159 updating_op = existing_op
1160 continue
1161
1162 if updating_op:
1163 updating_op.parentNode.removeChild(updating_op)
1164 dom = resource_operation_add(
1165 report_processor,
1166 dom,
1167 res_id,
1168 op_argv,
1169 validate_strict=False,
1170 before_op=updating_op_before,
1171 allowed_operation_name_list=allowed_operation_name_list,
1172 )
1173
1174 utils.replace_cib_configuration(dom)
1175
1176 if (
1177 remote_node_name
1178 and remote_node_name
1179 != utils.dom_get_resource_remote_node_name(resource)
1180 ):
1181 # if the resource was a remote node and it is not anymore, (or its name
1182 # changed) we need to tell pacemaker about it
1183 output, retval = utils.run(
1184 ["crm_node", "--force", "--remove", remote_node_name]
1185 )
1186
1187 if modifiers.is_specified("--wait"):
1188 args = ["crm_resource", "--wait"]
1189 if wait_timeout:
1190 args.extend(["--timeout=%s" % wait_timeout])
1191 output, retval = utils.run(args)
1192 running_on = utils.resource_running_on(res_id)
1193 if retval == 0:
1194 print_to_stderr(running_on["message"])
1195 else:
1196 msg = []
1197 if retval == PACEMAKER_WAIT_TIMEOUT_STATUS:
1198 msg.append("waiting timeout")
1199 msg.append(running_on["message"])
1200 if retval != 0 and output:
1201 msg.append("\n" + output)
1202 utils.err("\n".join(msg).strip())
1203 return None
1204
1205
1206 def resource_update_clone(
1207 report_processor, dom, clone, res_id, args, wait, wait_timeout
1208 ):
1209 """
1210 Commandline options:
1211 * -f - CIB file
1212 """
1213 dom, dummy_clone_id = resource_clone_create(
1214 report_processor, dom, [res_id] + args, update_existing=True
1215 )
1216
1217 utils.replace_cib_configuration(dom)
1218
1219 if wait:
1220 args = ["crm_resource", "--wait"]
1221 if wait_timeout:
1222 args.extend(["--timeout=%s" % wait_timeout])
1223 output, retval = utils.run(args)
1224 running_on = utils.resource_running_on(clone.getAttribute("id"))
1225 if retval == 0:
1226 print_to_stderr(running_on["message"])
1227 else:
1228 msg = []
1229 if retval == PACEMAKER_WAIT_TIMEOUT_STATUS:
1230 msg.append("waiting timeout")
1231 msg.append(running_on["message"])
1232 if retval != 0 and output:
1233 msg.append("\n" + output)
1234 utils.err("\n".join(msg).strip())
1235
1236 return dom
1237
1238
1239 def transform_master_to_clone(master_element):
1240 # create a new clone element with the same id
1241 dom = master_element.ownerDocument
1242 clone_element = dom.createElement("clone")
1243 clone_element.setAttribute("id", master_element.getAttribute("id"))
1244 # place it next to the master element
1245 master_element.parentNode.insertBefore(clone_element, master_element)
1246 # move all master's children to the clone
1247 while master_element.firstChild:
1248 clone_element.appendChild(master_element.firstChild)
1249 # remove the master
1250 master_element.parentNode.removeChild(master_element)
1251 # set meta to make the clone promotable
1252 utils.dom_update_meta_attr(clone_element, [("promotable", "true")])
1253 return clone_element
1254
1255
1256 def resource_operation_add( # noqa: PLR0912, PLR0915
1257 report_processor,
1258 dom,
1259 res_id,
1260 argv,
1261 validate_strict=True,
1262 before_op=None,
1263 allowed_operation_name_list=None,
1264 ):
1265 """
1266 Commandline options:
1267 * --force
1268 """
1269 if not argv:
1270 raise CmdLineInputError()
1271
1272 res_el = utils.dom_get_resource(dom, res_id)
1273 if not res_el:
1274 utils.err("Unable to find resource: %s" % res_id)
1275
1276 op_name = argv.pop(0)
1277 op_properties = utils.convert_args_to_tuples(argv)
1278
1279 if "=" in op_name:
1280 utils.err("%s does not appear to be a valid operation action" % op_name)
1281
1282 op_dict = dict(op_properties)
1283 if "name" in op_dict and op_dict["name"] != op_name:
1284 raise CmdLineInputError(
1285 "duplicate option 'name' with different values "
1286 f"'{op_name}' and '{op_dict['name']}'"
1287 )
1288 op_dict["name"] = op_name
1289
1290 normalized = operations.operations_to_normalized([op_dict])
1291 report_list = operations.validate_operation_list(
1292 normalized,
1293 allowed_operation_name_list or [],
1294 allow_invalid="--force" in utils.pcs_options,
1295 )
1296 if report_list:
1297 report_and_exit_on_error(report_processor, report_list)
1298
1299 new_role_names_supported = utils.isCibVersionSatisfied(
1300 dom, const.PCMK_NEW_ROLES_CIB_VERSION
1301 )
1302 op_normalized = operations.normalized_to_operations(
1303 normalized, new_role_names_supported
1304 )[0]
1305 op_properties = sorted(op_normalized.items())
1306
1307 interval = None
1308 for key, val in op_properties:
1309 if key == "interval":
1310 interval = val
1311 break
1312 if not interval:
1313 interval = "60s" if op_name == "monitor" else "0s"
1314 op_properties.append(("interval", interval))
1315
1316 generate_id = True
1317 for name, value in op_properties:
1318 if name == "id":
1319 op_id = value
1320 generate_id = False
1321 id_valid, id_error = utils.validate_xml_id(value, "operation id")
1322 if not id_valid:
1323 utils.err(id_error)
1324 if utils.does_id_exist(dom, value):
1325 utils.err(
1326 "id '%s' is already in use, please specify another one"
1327 % value
1328 )
1329 if generate_id:
1330 op_id = "%s-%s-interval-%s" % (res_id, op_name, interval)
1331 op_id = utils.find_unique_id(dom, op_id)
1332
1333 op_el = dom.createElement("op")
1334 op_el.setAttribute("id", op_id)
1335 for key, val in op_properties:
1336 if key == OCF_CHECK_LEVEL_INSTANCE_ATTRIBUTE_NAME:
1337 attrib_el = dom.createElement("instance_attributes")
1338 attrib_el.setAttribute(
1339 "id", utils.find_unique_id(dom, "params-" + op_id)
1340 )
1341 op_el.appendChild(attrib_el)
1342 nvpair_el = dom.createElement("nvpair")
1343 nvpair_el.setAttribute("name", key)
1344 nvpair_el.setAttribute("value", val)
1345 nvpair_el.setAttribute(
1346 "id", utils.find_unique_id(dom, "-".join((op_id, key, val)))
1347 )
1348 attrib_el.appendChild(nvpair_el)
1349 else:
1350 op_el.setAttribute(key, val)
1351
1352 operations_el = res_el.getElementsByTagName("operations")
1353 if not operations_el:
1354 operations_el = dom.createElement("operations")
1355 res_el.appendChild(operations_el)
1356 else:
1357 operations_el = operations_el[0]
1358 duplicate_op_list = utils.operation_exists(operations_el, op_el)
1359 if duplicate_op_list:
1360 utils.err(
1361 "operation %s with interval %ss already specified for %s:\n%s"
1362 % (
1363 op_el.getAttribute("name"),
1364 timeout_to_seconds_legacy(op_el.getAttribute("interval")),
1365 res_id,
1366 "\n".join(
1367 [operation_to_string(op) for op in duplicate_op_list]
1368 ),
1369 )
1370 )
1371 if validate_strict and "--force" not in utils.pcs_options:
1372 duplicate_op_list = utils.operation_exists_by_name(
1373 operations_el, op_el
1374 )
1375 if duplicate_op_list:
1376 msg = (
1377 "operation {action} already specified for {res}"
1378 + ", use --force to override:\n{op}"
1379 )
1380 utils.err(
1381 msg.format(
1382 action=op_el.getAttribute("name"),
1383 res=res_id,
1384 op="\n".join(
1385 [
1386 operation_to_string(op)
1387 for op in duplicate_op_list
1388 ]
1389 ),
1390 )
1391 )
1392
1393 operations_el.insertBefore(op_el, before_op)
1394 return dom
1395
1396
1397 def resource_operation_remove(res_id: str, argv: Argv) -> None: # noqa: PLR0912
1398 """
1399 Commandline options:
1400 * -f - CIB file
1401 """
1402 # if no args, then we're removing an operation id
1403
1404 # Do not ever remove an operations element, even if it is empty. There may
1405 # be ACLs set in pacemaker which allow "write" for op elements (adding,
1406 # changing and removing) but not operations elements. In such a case,
1407 # removing an operations element would cause the whole change to be
1408 # rejected by pacemaker with a "permission denied" message.
1409 # https://bugzilla.redhat.com/show_bug.cgi?id=1642514
1410
1411 dom = utils.get_cib_dom()
1412 if not argv:
1413 for operation in dom.getElementsByTagName("op"):
1414 if operation.getAttribute("id") == res_id:
1415 parent = operation.parentNode
1416 parent.removeChild(operation)
1417 utils.replace_cib_configuration(dom)
1418 return
1419 utils.err("unable to find operation id: %s" % res_id)
1420
1421 original_argv = " ".join(argv)
1422
1423 op_name = argv.pop(0)
1424 resource_el = None
1425
1426 for resource in dom.getElementsByTagName("primitive"):
1427 if resource.getAttribute("id") == res_id:
1428 resource_el = resource
1429 break
1430
1431 if not resource_el:
1432 utils.err("Unable to find resource: %s" % res_id)
1433 # return to let mypy know that resource_el is not None anymore
1434 return
1435
1436 remove_all = False
1437 if not argv:
1438 remove_all = True
1439
1440 op_properties = utils.convert_args_to_tuples(argv)
1441 op_properties.append(("name", op_name))
1442 found_match = False
1443 for op in resource_el.getElementsByTagName("op"):
1444 temp_properties = []
1445 for attr_name in op.attributes.keys(): # noqa: SIM118, attributes is not a dict
1446 if attr_name == "id":
1447 continue
1448 temp_properties.append(
1449 (attr_name, op.attributes.get(attr_name).nodeValue)
1450 )
1451
1452 if remove_all and op.attributes["name"].value == op_name:
1453 found_match = True
1454 parent = op.parentNode
1455 parent.removeChild(op)
1456 elif not set(op_properties) ^ set(temp_properties):
1457 found_match = True
1458 parent = op.parentNode
1459 parent.removeChild(op)
1460 break
1461
1462 if not found_match:
1463 utils.err("Unable to find operation matching: %s" % original_argv)
1464
1465 utils.replace_cib_configuration(dom)
1466
1467
1468 def resource_group_rm_cmd(
1469 lib: Any, argv: Argv, modifiers: InputModifiers
1470 ) -> None:
1471 """
1472 Options:
1473 * --wait
1474 * -f - CIB file
1475 """
1476 modifiers.ensure_only_supported("--wait", "-f")
1477 if not argv:
1478 raise CmdLineInputError()
1479 group_name = argv.pop(0)
1480 resource_ids = argv
1481
1482 cib_dom = resource_group_rm(utils.get_cib_dom(), group_name, resource_ids)
1483
1484 if modifiers.is_specified("--wait"):
1485 # deprecated in the first version of 0.12
1486 lib.env.report_processor.report(
1487 reports.ReportItem.deprecation(
1488 reports.messages.ResourceWaitDeprecated()
1489 )
1490 )
1491 wait_timeout = utils.validate_wait_get_timeout()
1492
1493 utils.replace_cib_configuration(cib_dom)
1494
1495 if modifiers.is_specified("--wait"):
1496 args = ["crm_resource", "--wait"]
1497 if wait_timeout:
1498 args.extend(["--timeout=%s" % wait_timeout])
1499 output, retval = utils.run(args)
1500 if retval != 0:
1501 msg = []
1502 if retval == PACEMAKER_WAIT_TIMEOUT_STATUS:
1503 msg.append("waiting timeout")
1504 if output:
1505 msg.append("\n" + output)
1506 utils.err("\n".join(msg).strip())
1507
1508
1509 def resource_group_add_cmd(
1510 lib: Any, argv: Argv, modifiers: InputModifiers
1511 ) -> None:
1512 """
1513 Options:
1514 * --wait
1515 * -f - CIB file
1516 * --after - place a resource in a group after the specified resource in
1517 the group
1518 * --before - place a resource in a group before the specified resource in
1519 the group
1520 """
1521 modifiers.ensure_only_supported("--wait", "-f", "--after", "--before")
1522 if len(argv) < 2:
1523 raise CmdLineInputError()
1524
1525 group_name = argv.pop(0)
1526 resource_names = argv
1527 adjacent_name = None
1528 after_adjacent = True
1529 if modifiers.is_specified("--after") and modifiers.is_specified("--before"):
1530 raise CmdLineInputError("you cannot specify both --before and --after")
1531 if modifiers.is_specified("--after"):
1532 adjacent_name = modifiers.get("--after")
1533 after_adjacent = True
1534 elif modifiers.is_specified("--before"):
1535 adjacent_name = modifiers.get("--before")
1536 after_adjacent = False
1537
1538 lib.resource.group_add(
1539 group_name,
1540 resource_names,
1541 adjacent_resource_id=adjacent_name,
1542 put_after_adjacent=after_adjacent,
1543 wait=modifiers.get("--wait"),
1544 )
1545
1546
1547 def resource_clone(
1548 lib: Any, argv: Argv, modifiers: InputModifiers, promotable: bool = False
1549 ) -> None:
1550 """
1551 Options:
1552 * --wait
1553 * -f - CIB file
1554 * --force - allow to clone stonith resource
1555 """
1556 modifiers.ensure_only_supported("-f", "--force", "--wait")
1557 if not argv:
1558 raise CmdLineInputError()
1559
1560 res = argv[0]
1561 check_is_not_stonith(lib, [res])
1562 cib_dom = utils.get_cib_dom()
1563
1564 if modifiers.is_specified("--wait"):
1565 # deprecated in the first version of 0.12
1566 lib.env.report_processor.report(
1567 reports.ReportItem.deprecation(
1568 reports.messages.ResourceWaitDeprecated()
1569 )
1570 )
1571 wait_timeout = utils.validate_wait_get_timeout()
1572
1573 force_flags = set()
1574 if modifiers.get("--force"):
1575 force_flags.add(reports.codes.FORCE)
1576
1577 cib_dom, clone_id = resource_clone_create(
1578 lib.env.report_processor,
1579 cib_dom,
1580 argv,
1581 promotable=promotable,
1582 force_flags=force_flags,
1583 )
1584 cib_dom = constraint.constraint_resource_update(res, cib_dom)
1585 utils.replace_cib_configuration(cib_dom)
1586
1587 if modifiers.is_specified("--wait"):
1588 args = ["crm_resource", "--wait"]
1589 if wait_timeout:
1590 args.extend(["--timeout=%s" % wait_timeout])
1591 output, retval = utils.run(args)
1592 running_on = utils.resource_running_on(clone_id)
1593 if retval == 0:
1594 print_to_stderr(running_on["message"])
1595 else:
1596 msg = []
1597 if retval == PACEMAKER_WAIT_TIMEOUT_STATUS:
1598 msg.append("waiting timeout")
1599 msg.append(running_on["message"])
1600 if output:
1601 msg.append("\n" + output)
1602 utils.err("\n".join(msg).strip())
1603
1604
1605 def _resource_is_ocf(resource_el) -> bool:
1606 return resource_el.getAttribute("class") == "ocf"
1607
1608
1609 def _get_resource_agent_name_from_rsc_el(
1610 resource_el,
1611 ) -> lib_ra.ResourceAgentName:
1612 return lib_ra.ResourceAgentName(
1613 resource_el.getAttribute("class"),
1614 resource_el.getAttribute("provider"),
1615 resource_el.getAttribute("type"),
1616 )
1617
1618
1619 def _get_resource_agent_facade(
1620 resource_agent: lib_ra.ResourceAgentName,
1621 ) -> lib_ra.ResourceAgentFacade:
1622 return lib_ra.ResourceAgentFacadeFactory(
1623 utils.cmd_runner(), utils.get_report_processor()
1624 ).facade_from_parsed_name(resource_agent)
1625
1626
1627 def _get_void_resource_agent_facade(
1628 resource_agent: lib_ra.ResourceAgentName,
1629 ) -> lib_ra.ResourceAgentFacade:
1630 return lib_ra.ResourceAgentFacadeFactory(
1631 utils.cmd_runner(), utils.get_report_processor()
1632 ).void_facade_from_parsed_name(resource_agent)
1633
1634
1635 def resource_clone_create( # noqa: PLR0912
1636 report_processor,
1637 cib_dom,
1638 argv,
1639 update_existing=False,
1640 promotable=False,
1641 force_flags=(),
1642 ):
1643 """
1644 Commandline options:
1645 * --force - allow to clone stonith resource
1646 """
1647 name = argv.pop(0)
1648
1649 resources_el = cib_dom.getElementsByTagName("resources")[0]
1650 element = utils.dom_get_resource(resources_el, name) or utils.dom_get_group(
1651 resources_el, name
1652 )
1653 if not element:
1654 utils.err("unable to find group or resource: %s" % name)
1655
1656 if element.parentNode.tagName == "bundle":
1657 utils.err("cannot clone bundle resource")
1658
1659 if not update_existing:
1660 if utils.dom_get_resource_clone(
1661 cib_dom, name
1662 ) or utils.dom_get_resource_masterslave(cib_dom, name):
1663 utils.err("%s is already a clone resource" % name)
1664
1665 if utils.dom_get_group_clone(
1666 cib_dom, name
1667 ) or utils.dom_get_group_masterslave(cib_dom, name):
1668 utils.err("cannot clone a group that has already been cloned")
1669 else:
1670 if element.parentNode.tagName != "clone":
1671 utils.err("%s is not currently a clone" % name)
1672 clone = element.parentNode
1673
1674 # If element is currently in a group and it's the last member, we get rid
1675 # of the group
1676 if (
1677 element.parentNode.tagName == "group"
1678 and element.parentNode.getElementsByTagName("primitive").length <= 1
1679 ):
1680 element.parentNode.parentNode.removeChild(element.parentNode)
1681
1682 if element.getAttribute("class") == "stonith":
1683 report_and_exit_on_error(
1684 report_processor,
1685 [
1686 reports.ReportItem(
1687 severity=reports.item.get_severity(
1688 reports.codes.FORCE,
1689 is_forced=reports.codes.FORCE in force_flags,
1690 ),
1691 message=reports.messages.CloningStonithResourcesHasNoEffect(
1692 [name]
1693 ),
1694 )
1695 ],
1696 )
1697
1698 parts = parse_clone(argv, promotable=promotable)
1699 _check_clone_incompatible_options_child(
1700 element,
1701 parts.meta_attrs,
1702 report_processor,
1703 force=reports.codes.FORCE in force_flags,
1704 )
1705
1706 if not update_existing:
1707 clone_id = parts.clone_id
1708 if clone_id is not None:
1709 report_list = []
1710 validate_id(clone_id, reporter=report_list)
1711 if report_list:
1712 raise CmdLineInputError("invalid id '{}'".format(clone_id))
1713 if utils.does_id_exist(cib_dom, clone_id):
1714 raise CmdLineInputError(
1715 "id '{}' already exists".format(clone_id),
1716 )
1717 else:
1718 clone_id = utils.find_unique_id(cib_dom, name + "-clone")
1719 clone = cib_dom.createElement("clone")
1720 clone.setAttribute("id", clone_id)
1721 clone.appendChild(element)
1722 resources_el.appendChild(clone)
1723
1724 # TODO: validation should be added after migrating the command to the new
1725 # architecture
1726 if any(
1727 value
1728 for name, value in parts.meta_attrs.items()
1729 if name != "promotable" or not promotable
1730 ):
1731 warn(
1732 reports.messages.MetaAttrsNotValidatedUnsupportedType(
1733 [cib_const.TAG_RESOURCE_CLONE]
1734 ).message
1735 )
1736 utils.dom_update_meta_attr(clone, sorted(parts.meta_attrs.items()))
1737
1738 return cib_dom, clone.getAttribute("id")
1739
1740
1741 def _check_clone_incompatible_options_child(
1742 child_el,
1743 clone_meta_attrs: Mapping[str, str],
1744 report_processor,
1745 force: bool = False,
1746 ):
1747 report_list = []
1748 if child_el.tagName == "primitive":
1749 report_list = _check_clone_incompatible_options_primitive(
1750 child_el, clone_meta_attrs, force=force
1751 )
1752 elif child_el.tagName == "group":
1753 group_id = child_el.getAttribute("id")
1754 for primitive_el in utils.get_group_children_el_from_el(child_el):
1755 report_list.extend(
1756 _check_clone_incompatible_options_primitive(
1757 primitive_el,
1758 clone_meta_attrs,
1759 group_id=group_id,
1760 force=force,
1761 )
1762 )
1763 if report_list:
1764 report_and_exit_on_error(report_processor, report_list)
1765
1766
1767 def _check_clone_incompatible_options_primitive(
1768 primitive_el,
1769 clone_meta_attrs: Mapping[str, str],
1770 group_id: str | None = None,
1771 force: bool = False,
1772 ) -> reports.ReportItemList:
1773 resource_agent_name = _get_resource_agent_name_from_rsc_el(primitive_el)
1774 primitive_id = primitive_el.getAttribute("id")
1775 if not _resource_is_ocf(primitive_el):
1776 for incompatible_attribute in ("globally-unique", "promotable"):
1777 if is_true(clone_meta_attrs.get(incompatible_attribute, "0")):
1778 return [
1779 reports.ReportItem.error(
1780 reports.messages.ResourceCloneIncompatibleMetaAttributes(
1781 incompatible_attribute,
1782 resource_agent_name.to_dto(),
1783 resource_id=primitive_id,
1784 group_id=group_id,
1785 )
1786 )
1787 ]
1788 else:
1789 try:
1790 resource_agent_facade = _get_resource_agent_facade(
1791 resource_agent_name
1792 )
1793 except lib_ra.ResourceAgentError as e:
1794 return [
1795 lib_ra.resource_agent_error_to_report_item(
1796 e, reports.get_severity(reports.codes.FORCE, force)
1797 )
1798 ]
1799 if resource_agent_facade.metadata.ocf_version == "1.1" and (
1800 is_true(clone_meta_attrs.get("promotable", "0"))
1801 and not resource_agent_facade.metadata.provides_promotability
1802 ):
1803 return [
1804 reports.ReportItem(
1805 reports.get_severity(reports.codes.FORCE, force),
1806 reports.messages.ResourceCloneIncompatibleMetaAttributes(
1807 "promotable",
1808 resource_agent_name.to_dto(),
1809 resource_id=primitive_id,
1810 group_id=group_id,
1811 ),
1812 )
1813 ]
1814 return []
1815
1816
1817 def resource_clone_master_remove(
1818 lib: Any, argv: Argv, modifiers: InputModifiers
1819 ) -> None:
1820 """
1821 Options:
1822 * -f - CIB file
1823 * --wait
1824 """
1825 modifiers.ensure_only_supported("-f", "--wait")
1826 if len(argv) != 1:
1827 raise CmdLineInputError()
1828
1829 name = argv.pop()
1830 dom = utils.get_cib_dom()
1831 resources_el = dom.documentElement.getElementsByTagName("resources")[0]
1832
1833 # get the resource no matter if user entered a clone or a cloned resource
1834 resource = (
1835 utils.dom_get_resource(resources_el, name)
1836 or utils.dom_get_group(resources_el, name)
1837 or utils.dom_get_clone_ms_resource(resources_el, name)
1838 )
1839 if not resource:
1840 utils.err("could not find resource: %s" % name)
1841 resource_id = resource.getAttribute("id")
1842 clone = utils.dom_get_resource_clone_ms_parent(resources_el, resource_id)
1843 if not clone:
1844 utils.err("'%s' is not a clone resource" % name)
1845
1846 if modifiers.is_specified("--wait"):
1847 # deprecated in the first version of 0.12
1848 lib.env.report_processor.report(
1849 reports.ReportItem.deprecation(
1850 reports.messages.ResourceWaitDeprecated()
1851 )
1852 )
1853 wait_timeout = utils.validate_wait_get_timeout()
1854
1855 # if user requested uncloning a resource contained in a cloned group
1856 # remove the resource from the group and leave the clone itself alone
1857 # unless the resource is the last one in the group
1858 clone_child = utils.dom_get_clone_ms_resource(
1859 resources_el, clone.getAttribute("id")
1860 )
1861 if (
1862 clone_child.tagName == "group"
1863 and resource.tagName != "group"
1864 and len(clone_child.getElementsByTagName("primitive")) > 1
1865 ):
1866 resource_group_rm(dom, clone_child.getAttribute("id"), [resource_id])
1867 else:
1868 remove_resource_references(dom, clone.getAttribute("id"))
1869 clone.parentNode.appendChild(resource)
1870 clone.parentNode.removeChild(clone)
1871 utils.replace_cib_configuration(dom)
1872
1873 if modifiers.is_specified("--wait"):
1874 args = ["crm_resource", "--wait"]
1875 if wait_timeout:
1876 args.extend(["--timeout=%s" % wait_timeout])
1877 output, retval = utils.run(args)
1878 running_on = utils.resource_running_on(resource_id)
1879 if retval == 0:
1880 print_to_stderr(running_on["message"])
1881 else:
1882 msg = []
1883 if retval == PACEMAKER_WAIT_TIMEOUT_STATUS:
1884 msg.append("waiting timeout")
1885 msg.append(running_on["message"])
1886 if output:
1887 msg.append("\n" + output)
1888 utils.err("\n".join(msg).strip())
1889
1890
1891 def stonith_level_rm_device(cib_dom, stn_id):
1892 """
1893 Commandline options: no options
1894 """
1895 topology_el_list = cib_dom.getElementsByTagName("fencing-topology")
1896 if not topology_el_list:
1897 return cib_dom
1898 topology_el = topology_el_list[0]
1899 for level_el in topology_el.getElementsByTagName("fencing-level"):
1900 device_list = level_el.getAttribute("devices").split(",")
1901 if stn_id in device_list:
1902 new_device_list = [dev for dev in device_list if dev != stn_id]
1903 if new_device_list:
1904 level_el.setAttribute("devices", ",".join(new_device_list))
1905 else:
1906 level_el.parentNode.removeChild(level_el)
1907 if not topology_el.getElementsByTagName("fencing-level"):
1908 topology_el.parentNode.removeChild(topology_el)
1909 return cib_dom
1910
1911
1912 def remove_resource_references(
1913 dom, resource_id, output=False, constraints_element=None
1914 ):
1915 """
1916 Commandline options: no options
1917 NOTE: -f - will be used only if dom will be None
1918 """
1919 for obj_ref in dom.getElementsByTagName("obj_ref"):
1920 if obj_ref.getAttribute("id") == resource_id:
1921 tag = obj_ref.parentNode
1922 tag.removeChild(obj_ref)
1923 if tag.getElementsByTagName("obj_ref").length == 0:
1924 remove_resource_references(
1925 dom,
1926 tag.getAttribute("id"),
1927 output=output,
1928 )
1929 tag.parentNode.removeChild(tag)
1930 constraint.remove_constraints_containing(
1931 resource_id, output, constraints_element, dom
1932 )
1933 stonith_level_rm_device(dom, resource_id)
1934
1935 for permission in dom.getElementsByTagName("acl_permission"):
1936 if permission.getAttribute("reference") == resource_id:
1937 permission.parentNode.removeChild(permission)
1938
1939 return dom
1940
1941
1942 # This removes a resource from a group, but keeps it in the config
1943 def resource_group_rm(cib_dom, group_name, resource_ids):
1944 """
1945 Commandline options: no options
1946 """
1947 dom = cib_dom.getElementsByTagName("configuration")[0]
1948
1949 all_resources = len(resource_ids) == 0
1950
1951 group_match = utils.dom_get_group(dom, group_name)
1952 if not group_match:
1953 utils.err("Group '%s' does not exist" % group_name)
1954
1955 resources_to_move = []
1956 if all_resources:
1957 resources_to_move.extend(
1958 list(group_match.getElementsByTagName("primitive"))
1959 )
1960 else:
1961 for resource_id in resource_ids:
1962 resource = utils.dom_get_resource(group_match, resource_id)
1963 if resource:
1964 resources_to_move.append(resource)
1965 else:
1966 utils.err(
1967 "Resource '%s' does not exist in group '%s'"
1968 % (resource_id, group_name)
1969 )
1970
1971 # If the group is in a clone, we don't delete the clone as there may be
1972 # constraints associated with it which the user may want to keep. However,
1973 # there may be several resources in the group. In that case there is no way
1974 # to figure out which one of them should stay in the clone. So we forbid
1975 # removing all resources from a cloned group unless there is just one
1976 # resource.
1977 # This creates an inconsistency:
1978 # - consider a cloned group with two resources
1979 # - move one resource from the group - it becomes a primitive
1980 # - move the last resource from the group - it stays in the clone
1981 # So far there has been no request to change this behavior. Unless there is
1982 # a request / reason to change it, we'll keep it that way.
1983 is_cloned_group = group_match.parentNode.tagName in ["clone", "master"]
1984 res_in_group = len(group_match.getElementsByTagName("primitive"))
1985 if (
1986 is_cloned_group
1987 and res_in_group > 1
1988 and len(resources_to_move) == res_in_group
1989 ):
1990 utils.err("Cannot remove all resources from a cloned group")
1991 target_node = group_match.parentNode
1992 if is_cloned_group and res_in_group > 1:
1993 target_node = dom.getElementsByTagName("resources")[0]
1994 for resource in resources_to_move:
1995 resource.parentNode.removeChild(resource)
1996 target_node.appendChild(resource)
1997
1998 if not group_match.getElementsByTagName("primitive"):
1999 group_match.parentNode.removeChild(group_match)
2000 remove_resource_references(dom, group_name, output=True)
2001
2002 return cib_dom
2003
2004
2005 def resource_group_list(
2006 lib: Any, argv: Argv, modifiers: InputModifiers
2007 ) -> None:
2008 """
2009 Options:
2010 * -f - CIB file
2011 """
2012 del lib
2013 modifiers.ensure_only_supported("-f")
2014 if argv:
2015 raise CmdLineInputError()
2016 group_xpath = "//group"
2017 group_xml = utils.get_cib_xpath(group_xpath)
2018
2019 # If no groups exist, we silently return
2020 if group_xml == "":
2021 return
2022
|
CID (unavailable; MK=be579b78ae5a93e59e5244e356de61d7) (#1 of 1): XML external entity processing enabled (SIGMA.xml_external_entity_enabled): |
|
(1) Event Sigma main event: |
The application uses Python's built in `xml` module which does not properly handle erroneous or maliciously constructed data, making the application vulnerable to one or more types of XML attacks. |
|
(2) Event remediation: |
Avoid using the `xml` module. Consider using the `defusedxml` module or similar which safely prevents all XML entity attacks. |
2023 element = parseString(group_xml).documentElement
2024 # If there is more than one group returned it's wrapped in an xpath-query
2025 # element
2026 # Ignoring mypy errors in this very old code. So far, nobody reported a bug
2027 # related to these lines.
2028 if element.tagName == "xpath-query": # type: ignore
2029 elements = element.getElementsByTagName("group") # type: ignore
2030 else:
2031 elements = [element]
2032
2033 for e in elements:
2034 line_parts = [e.getAttribute("id") + ":"]
2035 line_parts.extend(
2036 resource.getAttribute("id")
2037 for resource in e.getElementsByTagName("primitive")
2038 )
2039 print(" ".join(line_parts))
2040
2041
2042 def resource_status( # noqa: PLR0912, PLR0915
2043 lib: Any, argv: Argv, modifiers: InputModifiers, stonith: bool = False
2044 ) -> None:
2045 """
2046 Options:
2047 * -f - CIB file
2048 * --hide-inactive - print only active resources
2049 """
2050 del lib
2051 modifiers.ensure_only_supported("-f", "--hide-inactive")
2052 if len(argv) > 2:
2053 raise CmdLineInputError()
2054
2055 monitor_command = ["crm_mon", "--one-shot"]
2056 if not modifiers.get("--hide-inactive"):
2057 monitor_command.append("--inactive")
2058
2059 resource_or_tag_id = None
2060 node = None
2061 crm_mon_err_msg = "unable to get cluster status from crm_mon\n"
2062 if argv:
2063 for arg in argv[:]:
2064 if "=" not in arg:
2065 resource_or_tag_id = arg
2066 crm_mon_err_msg = f"unable to get status of '{resource_or_tag_id}' from crm_mon\n"
2067 monitor_command.extend(
2068 [
2069 "--include",
2070 "none,resources",
2071 "--resource",
2072 resource_or_tag_id,
2073 ]
2074 )
2075 argv.remove(arg)
2076 break
2077 parser = KeyValueParser(argv)
2078 parser.check_allowed_keys({"node"})
2079 node = parser.get_unique().get("node")
2080 if node == "":
2081 utils.err("missing value of 'node' option")
2082 if node:
2083 monitor_command.extend(["--node", node])
2084
2085 output, retval = utils.run(monitor_command)
2086 if retval != 0:
2087 utils.err(crm_mon_err_msg + output.rstrip())
2088 preg = re.compile(r".*(stonith:.*)")
2089 resources_header = False
2090 in_resources = False
2091 has_resources = False
2092 no_resources_line = (
2093 "NO stonith devices configured"
2094 if stonith
2095 else "NO resources configured"
2096 )
2097 no_active_resources_msg = "No active resources"
2098 for line in output.split("\n"):
2099 if line in (
2100 " * No active resources", # pacemaker >= 2.0.3 with --hide-inactive
2101 "No active resources", # pacemaker < 2.0.3 with --hide-inactive
2102 ):
2103 print(no_active_resources_msg)
2104 return
2105 if line in (
2106 " * No resources", # pacemaker >= 2.0.3
2107 "No resources", # pacemaker < 2.0.3
2108 ):
2109 if resource_or_tag_id and not node:
2110 utils.err(
2111 f"resource or tag id '{resource_or_tag_id}' not found"
2112 )
2113 if not node:
2114 print(no_resources_line)
2115 else:
2116 print(no_active_resources_msg)
2117 return
2118 if line in (
2119 "Full List of Resources:", # pacemaker >= 2.0.3
2120 "Active Resources:", # pacemaker >= 2.0.3 with --hide-inactive
2121 ):
2122 in_resources = True
2123 continue
2124 if line in (
2125 "Full list of resources:", # pacemaker < 2.0.3
2126 "Active resources:", # pacemaker < 2.0.3 with --hide-inactive
2127 ):
2128 resources_header = True
2129 continue
2130 if line == "":
2131 if resources_header:
2132 resources_header = False
2133 in_resources = True
2134 elif in_resources:
2135 if not has_resources:
2136 print(no_resources_line)
2137 return
2138 continue
2139 if in_resources:
2140 if resource_or_tag_id:
2141 has_resources = True
2142 print(line)
2143 continue
2144 if (
2145 not preg.match(line)
2146 and not stonith
2147 or preg.match(line)
2148 and stonith
2149 ):
2150 has_resources = True
2151 print(line)
2152
2153
2154 def resource_disable_cmd(
2155 lib: Any, argv: Argv, modifiers: InputModifiers
2156 ) -> None:
2157 """
2158 Options:
2159 * -f - CIB file
2160 * --brief - show brief output of --simulate
2161 * --safe - only disable if no other resource gets stopped or demoted
2162 * --simulate - do not push the CIB, print its effects
2163 * --no-strict - allow disable if other resource is affected
2164 * --wait
2165 """
2166 if not argv:
2167 raise CmdLineInputError("You must specify resource(s) to disable")
2168 check_is_not_stonith(lib, argv, "pcs stonith disable")
2169 resource_disable_common(lib, argv, modifiers)
2170
2171
2172 def resource_disable_common(
2173 lib: Any, argv: Argv, modifiers: InputModifiers
2174 ) -> None:
2175 """
2176 Commandline options:
2177 * -f - CIB file
2178 * --force - allow to disable the last stonith resource in the cluster
2179 * --brief - show brief output of --simulate
2180 * --safe - only disable if no other resource gets stopped or demoted
2181 * --simulate - do not push the CIB, print its effects
2182 * --no-strict - allow disable if other resource is affected
2183 * --wait
2184 """
2185 modifiers.ensure_only_supported(
2186 "-f",
2187 "--force",
2188 "--brief",
2189 "--safe",
2190 "--simulate",
2191 "--no-strict",
2192 "--wait",
2193 )
2194 modifiers.ensure_not_mutually_exclusive("-f", "--simulate", "--wait")
2195 modifiers.ensure_not_incompatible("--simulate", {"-f", "--safe", "--wait"})
2196 modifiers.ensure_not_incompatible("--safe", {"-f", "--simulate"})
2197 modifiers.ensure_not_incompatible("--no-strict", {"-f"})
2198
2199 if not argv:
2200 raise CmdLineInputError("You must specify resource(s) to disable")
2201
2202 if modifiers.get("--simulate"):
2203 result = lib.resource.disable_simulate(
2204 argv, not modifiers.get("--no-strict")
2205 )
2206 if modifiers.get("--brief"):
2207 # if the result is empty, printing it would produce a new line,
2208 # which is not wanted
2209 if result["other_affected_resource_list"]:
2210 print("\n".join(result["other_affected_resource_list"]))
2211 return
2212 print(result["plaintext_simulated_status"])
2213 return
2214 if modifiers.get("--safe") or modifiers.get("--no-strict"):
2215 if modifiers.get("--brief"):
2216 # Brief mode skips simulation output by setting the report processor
2217 # to ignore info reports which contain crm_simulate output and
2218 # resource status in this command
2219 lib.env.report_processor.suppress_reports_of_severity(
2220 [reports.ReportItemSeverity.INFO]
2221 )
2222 lib.resource.disable_safe(
2223 argv,
2224 not modifiers.get("--no-strict"),
2225 modifiers.get("--wait"),
2226 )
2227 return
2228 if modifiers.get("--brief"):
2229 raise CmdLineInputError(
2230 "'--brief' cannot be used without '--simulate' or '--safe'"
2231 )
2232 force_flags = set()
2233 if modifiers.get("--force"):
2234 force_flags.add(reports.codes.FORCE)
2235 lib.resource.disable(argv, modifiers.get("--wait"), force_flags)
2236
2237
2238 def resource_safe_disable_cmd(
2239 lib: Any, argv: Argv, modifiers: InputModifiers
2240 ) -> None:
2241 """
2242 Options:
2243 * --brief - show brief output of --simulate
2244 * --force - skip checks for safe resource disable
2245 * --no-strict - allow disable if other resource is affected
2246 * --simulate - do not push the CIB, print its effects
2247 * --wait
2248 """
2249 modifiers.ensure_only_supported(
2250 "--brief", "--force", "--no-strict", "--simulate", "--wait"
2251 )
2252 modifiers.ensure_not_incompatible("--force", {"--no-strict", "--simulate"})
2253 custom_options = {}
2254 if modifiers.get("--force"):
2255 warn(
2256 "option '--force' is specified therefore checks for disabling "
2257 "resource safely will be skipped"
2258 )
2259 elif not modifiers.get("--simulate"):
2260 custom_options["--safe"] = True
2261 resource_disable_cmd(
2262 lib,
2263 argv,
2264 modifiers.get_subset(
2265 "--wait", "--no-strict", "--simulate", "--brief", **custom_options
2266 ),
2267 )
2268
2269
2270 def resource_enable_cmd(
2271 lib: Any, argv: Argv, modifiers: InputModifiers
2272 ) -> None:
2273 """
2274 Options:
2275 * --wait
2276 * -f - CIB file
2277 """
2278 modifiers.ensure_only_supported("--wait", "-f")
2279 if not argv:
2280 raise CmdLineInputError("You must specify resource(s) to enable")
2281 resources = argv
2282 check_is_not_stonith(lib, resources, "pcs stonith enable")
2283 lib.resource.enable(resources, modifiers.get("--wait"))
2284
2285
2286 def resource_restart_cmd(
2287 lib: Any, argv: Argv, modifiers: InputModifiers
2288 ) -> None:
2289 """
2290 Options:
2291 * --wait
2292 """
2293 modifiers.ensure_only_supported("--wait")
2294
2295 if not argv:
2296 raise CmdLineInputError(
2297 "You must specify a resource to restart",
2298 show_both_usage_and_message=True,
2299 )
2300 resource = argv.pop(0)
2301 node = argv.pop(0) if argv else None
2302 if argv:
2303 raise CmdLineInputError()
2304
2305 timeout = (
2306 modifiers.get("--wait") if modifiers.is_specified("--wait") else None
2307 )
2308
2309 lib.resource.restart(resource, node, timeout)
2310
2311 print_to_stderr(f"{resource} successfully restarted")
2312
2313
2314 def resource_force_action( # noqa: PLR0912
2315 lib: Any, argv: Argv, modifiers: InputModifiers, action: str
2316 ) -> None:
2317 """
2318 Options:
2319 * --force
2320 * --full - more verbose output
2321 """
2322 modifiers.ensure_only_supported("--force", "--full")
2323 action_command = {
2324 "debug-start": "--force-start",
2325 "debug-stop": "--force-stop",
2326 "debug-promote": "--force-promote",
2327 "debug-demote": "--force-demote",
2328 "debug-monitor": "--force-check",
2329 }
2330
2331 if action not in action_command:
2332 raise CmdLineInputError()
2333 if not argv:
2334 utils.err("You must specify a resource to {0}".format(action))
2335 if len(argv) != 1:
2336 raise CmdLineInputError()
2337
2338 resource = argv[0]
2339 check_is_not_stonith(lib, [resource])
2340 dom = utils.get_cib_dom()
2341
2342 if not (
2343 utils.dom_get_any_resource(dom, resource)
2344 or utils.dom_get_bundle(dom, resource)
2345 ):
2346 utils.err(
2347 "unable to find a resource/clone/group/bundle: {0}".format(resource)
2348 )
2349 bundle_el = utils.dom_get_bundle(dom, resource)
2350 if bundle_el:
2351 bundle_resource = utils.dom_get_resource_bundle(bundle_el)
2352 if bundle_resource:
2353 utils.err(
2354 "unable to {0} a bundle, try the bundle's resource: {1}".format(
2355 action, bundle_resource.getAttribute("id")
2356 )
2357 )
2358 else:
2359 utils.err("unable to {0} a bundle".format(action))
2360 if utils.dom_get_group(dom, resource):
2361 group_resources = utils.get_group_children(resource)
2362 utils.err(
2363 (
2364 "unable to {0} a group, try one of the group's resource(s) ({1})"
2365 ).format(action, ",".join(group_resources))
2366 )
2367 if utils.dom_get_clone(dom, resource) or utils.dom_get_master(
2368 dom, resource
2369 ):
2370 clone_resource = utils.dom_get_clone_ms_resource(dom, resource)
2371 utils.err(
2372 "unable to {0} a clone, try the clone's resource: {1}".format(
2373 action, clone_resource.getAttribute("id")
2374 )
2375 )
2376
2377 args = ["crm_resource", "-r", resource, action_command[action]]
2378 if modifiers.get("--full"):
2379 # set --verbose twice to get a reasonable amount of debug messages
2380 args.extend(["--verbose"] * 2)
2381 if modifiers.get("--force"):
2382 args.append("--force")
2383 output, retval = utils.run(args)
2384
2385 if "doesn't support group resources" in output:
2386 utils.err("groups are not supported")
2387 sys.exit(retval)
2388 if "doesn't support stonith resources" in output:
2389 utils.err("stonith devices are not supported")
2390 sys.exit(retval)
2391
2392 print(output.rstrip())
2393 sys.exit(retval)
2394
2395
2396 def resource_manage_cmd(
2397 lib: Any, argv: Argv, modifiers: InputModifiers
2398 ) -> None:
2399 """
2400 Options:
2401 * -f - CIB file
2402 * --monitor - enable monitor operation of specified resources
2403 """
2404 modifiers.ensure_only_supported("-f", "--monitor")
2405 if not argv:
2406 raise CmdLineInputError("You must specify resource(s) to manage")
2407 resources = argv
2408 check_is_not_stonith(lib, resources)
2409 lib.resource.manage(resources, with_monitor=modifiers.get("--monitor"))
2410
2411
2412 def resource_unmanage_cmd(
2413 lib: Any, argv: Argv, modifiers: InputModifiers
2414 ) -> None:
2415 """
2416 Options:
2417 * -f - CIB file
2418 * --monitor - bisable monitor operation of specified resources
2419 """
2420 modifiers.ensure_only_supported("-f", "--monitor")
2421 if not argv:
2422 raise CmdLineInputError("You must specify resource(s) to unmanage")
2423 resources = argv
2424 check_is_not_stonith(lib, resources)
2425 lib.resource.unmanage(resources, with_monitor=modifiers.get("--monitor"))
2426
2427
2428 def resource_failcount_show(
2429 lib: Any, argv: Argv, modifiers: InputModifiers
2430 ) -> None:
2431 """
2432 Options:
2433 * --full
2434 * -f - CIB file
2435 """
2436 modifiers.ensure_only_supported("-f", "--full")
2437
2438 resource = argv.pop(0) if argv and "=" not in argv[0] else None
2439 parser = KeyValueParser(argv)
2440 parser.check_allowed_keys({"node", "operation", "interval"})
2441 parsed_options = parser.get_unique()
2442
2443 node = parsed_options.get("node")
2444 operation = parsed_options.get("operation")
2445 interval = parsed_options.get("interval")
2446 result_lines = []
2447 failures_data = lib.resource.get_failcounts(
2448 resource=resource, node=node, operation=operation, interval=interval
2449 )
2450
2451 if not failures_data:
2452 result_lines.append(
2453 __headline_resource_failures(
2454 True, resource, node, operation, interval
2455 )
2456 )
2457 print("\n".join(result_lines))
2458 return
2459
2460 resource_list = sorted({fail["resource"] for fail in failures_data})
2461 for current_resource in resource_list:
2462 result_lines.append(
2463 __headline_resource_failures(
2464 False, current_resource, node, operation, interval
2465 )
2466 )
2467 resource_failures = [
2468 fail
2469 for fail in failures_data
2470 if fail["resource"] == current_resource
2471 ]
2472 node_list = sorted({fail["node"] for fail in resource_failures})
2473 for current_node in node_list:
2474 node_failures = [
2475 fail
2476 for fail in resource_failures
2477 if fail["node"] == current_node
2478 ]
2479 if modifiers.get("--full"):
2480 result_lines.append(f" {current_node}:")
2481 operation_list = sorted(
2482 {fail["operation"] for fail in node_failures}
2483 )
2484 for current_operation in operation_list:
2485 operation_failures = [
2486 fail
2487 for fail in node_failures
2488 if fail["operation"] == current_operation
2489 ]
2490 interval_list = sorted(
2491 {fail["interval"] for fail in operation_failures},
2492 # pacemaker's definition of infinity
2493 key=lambda x: 1000000 if x == "INFINITY" else x,
2494 )
2495 for current_interval in interval_list:
2496 interval_failures = [
2497 fail
2498 for fail in operation_failures
2499 if fail["interval"] == current_interval
2500 ]
2501 failcount, dummy_last_failure = __aggregate_failures(
2502 interval_failures
2503 )
2504 result_lines.append(
2505 f" {current_operation} {current_interval}ms: {failcount}"
2506 )
2507 else:
2508 failcount, dummy_last_failure = __aggregate_failures(
2509 node_failures
2510 )
2511 result_lines.append(f" {current_node}: {failcount}")
2512 print("\n".join(result_lines))
2513
2514
2515 def __aggregate_failures(failure_list):
2516 """
2517 Commandline options: no options
2518 """
2519 last_failure = 0
2520 fail_count = 0
2521 for failure in failure_list:
2522 # infinity is a maximal value and cannot be increased
2523 if fail_count != "INFINITY":
2524 if failure["fail_count"] == "INFINITY":
2525 fail_count = failure["fail_count"]
2526 else:
2527 fail_count += failure["fail_count"]
2528 last_failure = max(last_failure, failure["last_failure"])
2529 return fail_count, last_failure
2530
2531
2532 def __headline_resource_failures(empty, resource, node, operation, interval):
2533 """
2534 Commandline options: no options
2535 """
2536 headline_parts = []
2537 if empty:
2538 headline_parts.append("No failcounts")
2539 else:
2540 headline_parts.append("Failcounts")
2541 if operation:
2542 headline_parts.append("for operation '{operation}'")
2543 if interval:
2544 headline_parts.append("with interval '{interval}'")
2545 if resource:
2546 headline_parts.append("of" if operation else "for")
2547 headline_parts.append("resource '{resource}'")
2548 if node:
2549 headline_parts.append("on node '{node}'")
2550 return " ".join(headline_parts).format(
2551 node=node, resource=resource, operation=operation, interval=interval
2552 )
2553
2554
2555 def operation_to_string(op_el):
2556 """
2557 Commandline options: no options
2558 """
2559 parts = []
2560 parts.append(op_el.getAttribute("name"))
2561 for name, value in sorted(op_el.attributes.items()):
2562 if name in ["id", "name"]:
2563 continue
2564 parts.append(name + "=" + value)
2565 parts.extend(
2566 f"{nvpair.getAttribute('name')}={nvpair.getAttribute('value')}"
2567 for nvpair in op_el.getElementsByTagName("nvpair")
2568 )
2569 parts.append("(" + op_el.getAttribute("id") + ")")
2570 return " ".join(parts)
2571
2572
2573 def resource_cleanup(lib: Any, argv: Argv, modifiers: InputModifiers) -> None:
2574 """
2575 Options: no options
2576 """
2577 del lib
2578 modifiers.ensure_only_supported("--strict")
2579 resource = argv.pop(0) if argv and "=" not in argv[0] else None
2580 parser = KeyValueParser(argv)
2581 parser.check_allowed_keys({"node", "operation", "interval"})
2582 parsed_options = parser.get_unique()
2583
2584 print_to_stderr(
2585 lib_pacemaker.resource_cleanup(
2586 utils.cmd_runner(),
2587 resource=resource,
2588 node=parsed_options.get("node"),
2589 operation=parsed_options.get("operation"),
2590 interval=parsed_options.get("interval"),
2591 strict=bool(modifiers.get("--strict")),
2592 )
2593 )
2594
2595
2596 def resource_refresh(lib: Any, argv: Argv, modifiers: InputModifiers) -> None:
2597 """
2598 Options:
2599 * --force - do refresh even though it may be time consuming
2600 """
2601 del lib
2602 modifiers.ensure_only_supported(
2603 "--force",
2604 "--strict",
2605 hint_syntax_changed=(
2606 "0.11" if modifiers.is_specified("--full") else None
2607 ),
2608 )
2609 resource = argv.pop(0) if argv and "=" not in argv[0] else None
2610 parser = KeyValueParser(argv)
2611 parser.check_allowed_keys({"node"})
2612 parsed_options = parser.get_unique()
2613 print_to_stderr(
2614 lib_pacemaker.resource_refresh(
2615 utils.cmd_runner(),
2616 resource=resource,
2617 node=parsed_options.get("node"),
2618 strict=bool(modifiers.get("--strict")),
2619 force=bool(modifiers.get("--force")),
2620 )
2621 )
2622
2623
2624 def resource_relocate_show_cmd(
2625 lib: Any, argv: Argv, modifiers: InputModifiers
2626 ) -> None:
2627 """
2628 Options: no options
2629 """
2630 del lib
2631 modifiers.ensure_only_supported()
2632 if argv:
2633 raise CmdLineInputError()
2634 resource_relocate_show(utils.get_cib_dom())
2635
2636
2637 def resource_relocate_dry_run_cmd(
2638 lib: Any, argv: Argv, modifiers: InputModifiers
2639 ) -> None:
2640 """
2641 Options:
2642 * -f - CIB file
2643 """
2644 modifiers.ensure_only_supported("-f")
2645 if argv:
2646 check_is_not_stonith(lib, argv)
2647 resource_relocate_run(utils.get_cib_dom(), argv, dry=True)
2648
2649
2650 def resource_relocate_run_cmd(
2651 lib: Any, argv: Argv, modifiers: InputModifiers
2652 ) -> None:
2653 """
2654 Options: no options
2655 """
2656 modifiers.ensure_only_supported()
2657 if argv:
2658 check_is_not_stonith(lib, argv)
2659 resource_relocate_run(utils.get_cib_dom(), argv, dry=False)
2660
2661
2662 def resource_relocate_clear_cmd(
2663 lib: Any, argv: Argv, modifiers: InputModifiers
2664 ) -> None:
2665 """
2666 Options:
2667 * -f - CIB file
2668 """
2669 del lib
2670 modifiers.ensure_only_supported("-f")
2671 if argv:
2672 raise CmdLineInputError()
2673 utils.replace_cib_configuration(
2674 resource_relocate_clear(utils.get_cib_dom())
2675 )
2676
2677
2678 def resource_relocate_set_stickiness(cib_dom, resources=None):
2679 """
2680 Commandline options: no options
2681 """
2682 resources = [] if resources is None else resources
2683 cib_dom = cib_dom.cloneNode(True) # do not change the original cib
2684 resources_found = set()
2685 updated_resources = set()
2686 # set stickiness=0
2687 for tagname in ("master", "clone", "group", "primitive"):
2688 for res_el in cib_dom.getElementsByTagName(tagname):
2689 if resources and res_el.getAttribute("id") not in resources:
2690 continue
2691 resources_found.add(res_el.getAttribute("id"))
2692 res_and_children = (
2693 [res_el]
2694 + res_el.getElementsByTagName("group")
2695 + res_el.getElementsByTagName("primitive")
2696 )
2697 updated_resources.update(
2698 [el.getAttribute("id") for el in res_and_children]
2699 )
2700 for res_or_child in res_and_children:
2701 meta_attributes = utils.dom_prepare_child_element(
2702 res_or_child,
2703 "meta_attributes",
2704 res_or_child.getAttribute("id") + "-meta_attributes",
2705 )
2706 utils.dom_update_nv_pair(
2707 meta_attributes,
2708 "resource-stickiness",
2709 "0",
2710 meta_attributes.getAttribute("id") + "-",
2711 )
2712 # resources don't exist
2713 if resources:
2714 resources_not_found = set(resources) - resources_found
2715 if resources_not_found:
2716 for res_id in resources_not_found:
2717 utils.err(
2718 "unable to find a resource/clone/group: {0}".format(res_id),
2719 False,
2720 )
2721 sys.exit(1)
2722 return cib_dom, updated_resources
2723
2724
2725 def resource_relocate_get_locations(cib_dom, resources=None):
2726 """
2727 Commandline options:
2728 * --force - allow constraint on any resource, may not have any effective
2729 as an invalid constraint is ignored anyway
2730 """
2731 resources = [] if resources is None else resources
2732 updated_cib, updated_resources = resource_relocate_set_stickiness(
2733 cib_dom, resources
2734 )
2735 dummy_simout, transitions, new_cib = utils.simulate_cib(updated_cib)
2736 operation_list = utils.get_operations_from_transitions(transitions)
2737 locations = utils.get_resources_location_from_operations(
2738 new_cib, operation_list
2739 )
2740 # filter out non-requested resources
2741 if not resources:
2742 return list(locations.values())
2743 return [
2744 val
2745 for val in locations.values()
2746 if val["id"] in updated_resources
2747 or val["id_for_constraint"] in updated_resources
2748 ]
2749
2750
2751 def resource_relocate_show(cib_dom):
2752 """
2753 Commandline options: no options
2754 """
2755 updated_cib, dummy_updated_resources = resource_relocate_set_stickiness(
2756 cib_dom
2757 )
2758 simout, dummy_transitions, dummy_new_cib = utils.simulate_cib(updated_cib)
2759 in_status = False
2760 in_status_resources = False
2761 in_transitions = False
2762 for line in simout.split("\n"):
2763 if line.strip() == "Current cluster status:":
2764 in_status = True
2765 in_status_resources = False
2766 in_transitions = False
2767 elif line.strip() == "Transition Summary:":
2768 in_status = False
2769 in_status_resources = False
2770 in_transitions = True
2771 print()
2772 elif line.strip() == "":
2773 if in_status:
2774 in_status = False
2775 in_status_resources = True
2776 in_transitions = False
2777 else:
2778 in_status = False
2779 in_status_resources = False
2780 in_transitions = False
2781 if in_status or in_status_resources or in_transitions:
2782 print(line)
2783
2784
2785 def resource_relocate_location_to_str(location):
2786 """
2787 Commandline options: no options
2788 """
2789 message = (
2790 "Creating location constraint: {res} prefers {node}=INFINITY{role}"
2791 )
2792 if "start_on_node" in location:
2793 return message.format(
2794 res=location["id_for_constraint"],
2795 node=location["start_on_node"],
2796 role="",
2797 )
2798 if "promote_on_node" in location:
2799 return message.format(
2800 res=location["id_for_constraint"],
2801 node=location["promote_on_node"],
2802 role=f" role={const.PCMK_ROLE_PROMOTED}",
2803 )
2804 return ""
2805
2806
2807 def resource_relocate_run(cib_dom, resources=None, dry=True): # noqa: PLR0912
2808 """
2809 Commandline options:
2810 * -f - CIB file, explicitly forbids -f if dry is False
2811 * --force - allow constraint on any resource, may not have any effective
2812 as an invalid copnstraint is ignored anyway
2813 """
2814 resources = [] if resources is None else resources
2815 was_error = False
2816 anything_changed = False
2817 if not dry and utils.usefile:
2818 utils.err("This command cannot be used with -f")
2819
2820 # create constraints
2821 cib_dom, constraint_el = constraint.getCurrentConstraints(cib_dom)
2822 for location in resource_relocate_get_locations(cib_dom, resources):
2823 if not ("start_on_node" in location or "promote_on_node" in location):
2824 continue
2825 anything_changed = True
2826 print_to_stderr(resource_relocate_location_to_str(location))
2827 constraint_id = utils.find_unique_id(
2828 cib_dom,
2829 RESOURCE_RELOCATE_CONSTRAINT_PREFIX + location["id_for_constraint"],
2830 )
2831 new_constraint = cib_dom.createElement("rsc_location")
2832 new_constraint.setAttribute("id", constraint_id)
2833 new_constraint.setAttribute("rsc", location["id_for_constraint"])
2834 new_constraint.setAttribute("score", "INFINITY")
2835 if "promote_on_node" in location:
2836 new_constraint.setAttribute("node", location["promote_on_node"])
2837 new_constraint.setAttribute(
2838 "role",
2839 pacemaker.role.get_value_for_cib(
2840 const.PCMK_ROLE_PROMOTED,
2841 utils.isCibVersionSatisfied(
2842 cib_dom, const.PCMK_NEW_ROLES_CIB_VERSION
2843 ),
2844 ),
2845 )
2846 elif "start_on_node" in location:
2847 new_constraint.setAttribute("node", location["start_on_node"])
2848 constraint_el.appendChild(new_constraint)
2849 if not anything_changed:
2850 return
2851 if not dry:
2852 utils.replace_cib_configuration(cib_dom)
2853
2854 # wait for resources to move
2855 print_to_stderr("\nWaiting for resources to move...\n")
2856 if not dry:
2857 output, retval = utils.run(["crm_resource", "--wait"])
2858 if retval != 0:
2859 was_error = True
2860 if retval == PACEMAKER_WAIT_TIMEOUT_STATUS:
2861 utils.err("waiting timeout", False)
2862 else:
2863 utils.err(output, False)
2864
2865 # remove constraints
2866 resource_relocate_clear(cib_dom)
2867 if not dry:
2868 utils.replace_cib_configuration(cib_dom)
2869
2870 if was_error:
2871 sys.exit(1)
2872
2873
2874 def resource_relocate_clear(cib_dom):
2875 """
2876 Commandline options: no options
2877 """
2878 for constraint_el in cib_dom.getElementsByTagName("constraints"):
2879 for location_el in constraint_el.getElementsByTagName("rsc_location"):
2880 location_id = location_el.getAttribute("id")
2881 if location_id.startswith(RESOURCE_RELOCATE_CONSTRAINT_PREFIX):
2882 print_to_stderr("Removing constraint {0}".format(location_id))
2883 location_el.parentNode.removeChild(location_el)
2884 return cib_dom
2885
2886
2887 def set_resource_utilization(resource_id: str, argv: Argv) -> None:
2888 """
2889 Commandline options:
2890 * -f - CIB file
2891 """
2892 cib = utils.get_cib_dom()
2893 resource_el = utils.dom_get_resource(cib, resource_id)
2894 if resource_el is None:
2895 utils.err("Unable to find a resource: {0}".format(resource_id))
2896 utils.dom_update_utilization(resource_el, KeyValueParser(argv).get_unique())
2897 utils.replace_cib_configuration(cib)
2898
2899
2900 def print_resource_utilization(resource_id: str) -> None:
2901 """
2902 Commandline options:
2903 * -f - CIB file
2904 """
2905 cib = utils.get_cib_dom()
2906 resource_el = utils.dom_get_resource(cib, resource_id)
2907 if resource_el is None:
2908 utils.err("Unable to find a resource: {0}".format(resource_id))
2909 utilization = utils.get_utilization_str(resource_el)
2910
2911 print("Resource Utilization:")
2912 print(" {0}: {1}".format(resource_id, utilization))
2913
2914
2915 def print_resources_utilization() -> None:
2916 """
2917 Commandline options:
2918 * -f - CIB file
2919 """
2920 cib = utils.get_cib_dom()
2921 utilization = {}
2922 for resource_el in cib.getElementsByTagName("primitive"):
2923 utilization_str = utils.get_utilization_str(resource_el)
2924 if utilization_str:
2925 utilization[resource_el.getAttribute("id")] = utilization_str
2926
2927 print("Resource Utilization:")
2928 for resource in sorted(utilization):
2929 print(" {0}: {1}".format(resource, utilization[resource]))
2930
2931
2932 def resource_bundle_create_cmd(
2933 lib: Any, argv: Argv, modifiers: InputModifiers
2934 ) -> None:
2935 """
2936 Options:
2937 * --force - allow unknown options
2938 * --disabled - create as a stopped bundle
2939 * --wait
2940 * -f - CIB file
2941 """
2942 modifiers.ensure_only_supported("--force", "--disabled", "--wait", "-f")
2943 if not argv:
2944 raise CmdLineInputError()
2945
2946 bundle_id = argv[0]
2947 parts = parse_bundle_create_options(argv[1:])
2948 lib.resource.bundle_create(
2949 bundle_id,
2950 parts.container_type,
2951 container_options=parts.container,
2952 network_options=parts.network,
2953 port_map=parts.port_map,
2954 storage_map=parts.storage_map,
2955 meta_attributes=parts.meta_attrs,
2956 force_options=modifiers.get("--force"),
2957 ensure_disabled=modifiers.get("--disabled"),
2958 wait=modifiers.get("--wait"),
2959 )
2960
2961
2962 def resource_bundle_reset_cmd(
2963 lib: Any, argv: Argv, modifiers: InputModifiers
2964 ) -> None:
2965 """
2966 Options:
2967 * --force - allow unknown options
2968 * --disabled - create as a stopped bundle
2969 * --wait
2970 * -f - CIB file
2971 """
2972 modifiers.ensure_only_supported("--force", "--disabled", "--wait", "-f")
2973 if not argv:
2974 raise CmdLineInputError()
2975
2976 bundle_id = argv[0]
2977 parts = parse_bundle_reset_options(argv[1:])
2978 lib.resource.bundle_reset(
2979 bundle_id,
2980 container_options=parts.container,
2981 network_options=parts.network,
2982 port_map=parts.port_map,
2983 storage_map=parts.storage_map,
2984 meta_attributes=parts.meta_attrs,
2985 force_options=modifiers.get("--force"),
2986 ensure_disabled=modifiers.get("--disabled"),
2987 wait=modifiers.get("--wait"),
2988 )
2989
2990
2991 def resource_bundle_update_cmd(
2992 lib: Any, argv: Argv, modifiers: InputModifiers
2993 ) -> None:
2994 """
2995 Options:
2996 * --force - allow unknown options
2997 * --wait
2998 * -f - CIB file
2999 """
3000 modifiers.ensure_only_supported("--force", "--wait", "-f")
3001 if not argv:
3002 raise CmdLineInputError()
3003
3004 bundle_id = argv[0]
3005 parts = parse_bundle_update_options(argv[1:])
3006 lib.resource.bundle_update(
3007 bundle_id,
3008 container_options=parts.container,
3009 network_options=parts.network,
3010 port_map_add=parts.port_map_add,
3011 port_map_remove=parts.port_map_remove,
3012 storage_map_add=parts.storage_map_add,
3013 storage_map_remove=parts.storage_map_remove,
3014 meta_attributes=parts.meta_attrs,
3015 force_options=modifiers.get("--force"),
3016 wait=modifiers.get("--wait"),
3017 )
3018