Skip to content

flayer.providers.yandex_lifecycle

Module source

flayer.providers.yandex_lifecycle

Bounded Yandex mutations with explicit ownership and recoverable uncertain outcomes.

MAX_USER_DATA_BYTES module-attribute

MAX_USER_DATA_BYTES = 262144

USERNAME_PATTERN module-attribute

USERNAME_PATTERN = re.compile('[a-z_][a-z0-9_-]{0,31}\\Z')

SHA256_PATTERN module-attribute

SHA256_PATTERN = re.compile('[a-f0-9]{64}\\Z')

OPERATION_ID_PATTERN module-attribute

OPERATION_ID_PATTERN = re.compile('[a-f0-9]{32}\\Z')

RESOURCE_NAME_PATTERN module-attribute

RESOURCE_NAME_PATTERN = re.compile('[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?\\Z')

REQUIRED_PARAMETERS module-attribute

REQUIRED_PARAMETERS: dict[ResourceKind, frozenset[str]] = {ResourceKind.NETWORK: frozenset(), ResourceKind.SUBNET: frozenset({'zone_id', 'ipv4_cidr', 'network_dependency'}), ResourceKind.SECURITY_GROUP: frozenset({'network_dependency', 'rules'}), ResourceKind.ADDRESS: frozenset({'zone_id'}), ResourceKind.DISK: frozenset({'zone_id', 'image_id', 'size_gib'}), ResourceKind.INSTANCE: frozenset({'zone_id', 'cores', 'memory_gib', 'boot_disk_dependency', 'subnet_dependency', 'security_group_dependency', 'address_dependency', 'ssh_public_key'})}

OPTIONAL_PARAMETERS module-attribute

OPTIONAL_PARAMETERS: dict[ResourceKind, frozenset[str]] = {ResourceKind.NETWORK: frozenset(), ResourceKind.SUBNET: frozenset(), ResourceKind.SECURITY_GROUP: frozenset(), ResourceKind.ADDRESS: frozenset(), ResourceKind.DISK: frozenset({'type'}), ResourceKind.INSTANCE: frozenset({'ssh_username', 'user_data_file', 'user_data_sha256', 'platform_id', 'core_fraction'})}

DEPENDENCY_KINDS module-attribute

DEPENDENCY_KINDS = {'network_dependency': ResourceKind.NETWORK, 'boot_disk_dependency': ResourceKind.DISK, 'subnet_dependency': ResourceKind.SUBNET, 'security_group_dependency': ResourceKind.SECURITY_GROUP, 'address_dependency': ResourceKind.ADDRESS}

KNOWN_STATUSES module-attribute

KNOWN_STATUSES = frozenset({'UNKNOWN', 'ACTIVE', 'CREATING', 'PROVISIONING', 'READY', 'RUNNING', 'STARTING', 'STOPPING', 'STOPPED', 'RESTARTING', 'UPDATING', 'DELETING', 'ERROR', 'FAILED'})

USER_DATA_FIELDS module-attribute

USER_DATA_FIELDS = frozenset({'ssh_pwauth', 'disable_root', 'users', 'package_update', 'package_upgrade', 'packages', 'write_files', 'runcmd'})

YandexLifecycleProvider

YandexLifecycleProvider(settings: YandexCloudSettings, runner: CommandRunner | None = None)

Bases: YandexCloudProvider

Create and delete an explicit six-kind subset using existing read-only observation.

Source code in installed/flayer/providers/yandex.py
127
128
129
130
131
132
133
134
def __init__(
    self, settings: YandexCloudSettings, runner: CommandRunner | None = None
) -> None:
    """Construct a provider without executing commands or reading credential files."""

    self._settings = settings
    self._runner = runner if runner is not None else SubprocessCommandRunner()
    self._identity = ProviderIdentity(PROVIDER_ID, settings.folder_id, "cli-profile")

Capabilities property

Capabilities: frozenset[ProviderCapability]

Advertise implemented mutations without promising credentials or account permission.

ValidateSpec

ValidateSpec(spec: ResourceSpec) -> None

Validate the complete supported option/dependency subset without cloud access.

Source code in installed/flayer/providers/yandex_lifecycle.py
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
def ValidateSpec(self, spec: ResourceSpec) -> None:
    """Validate the complete supported option/dependency subset without cloud access."""

    failure = False

    try:
        if not isinstance(spec, ResourceSpec):
            raise ValueError("Lifecycle requests require ResourceSpec")

        if RESOURCE_NAME_PATTERN.fullmatch(spec.name) is None:
            raise ValueError("Resource name violates provider naming requirements")

        options = dict(spec.parameters)
        required = REQUIRED_PARAMETERS[spec.kind]

        if not required <= options.keys() or options.keys() - required - OPTIONAL_PARAMETERS[
            spec.kind
        ]:
            raise ValueError("Unsupported lifecycle options")

        expected: set[str] = set()

        for key in options:
            if key in DEPENDENCY_KINDS:
                dependency = _String(options[key])
                ValidateName(dependency, "dependency")
                expected.add(dependency)

        dependency_options = sum(key in DEPENDENCY_KINDS for key in options)

        if expected != set(spec.dependencies) or len(expected) != dependency_options:
            raise ValueError("Dependencies must match explicit typed dependency options")

        if "zone_id" in options:
            ValidateIdentifier(_String(options["zone_id"]))

        if spec.kind == ResourceKind.SUBNET:
            ipaddress.IPv4Network(_String(options["ipv4_cidr"]), strict=True)

        elif spec.kind == ResourceKind.SECURITY_GROUP:
            _Rules(options["rules"])

        elif spec.kind == ResourceKind.DISK:
            ValidateIdentifier(_String(options["image_id"]))
            _Integer(options["size_gib"], 10, 1024)

            if options.get("type", "network-ssd") not in {"network-ssd", "network-hdd"}:
                raise ValueError("Unsupported boot disk type")

        elif spec.kind == ResourceKind.INSTANCE:
            ValidateComputeShape(options)
            _PublicKey(options["ssh_public_key"])

            if USERNAME_PATTERN.fullmatch(_String(options.get("ssh_username", "yc-user"))) is None:
                raise ValueError("Unsupported SSH username")

            if ("user_data_file" in options) != ("user_data_sha256" in options):
                raise ValueError("Initialization file requires its immutable content digest")

            if "user_data_file" in options:
                path = Path(_String(options["user_data_file"]))

                if not str(path) or ".." in path.parts or "\x00" in str(path):
                    raise ValueError("Initialization file path is unsafe")

                if SHA256_PATTERN.fullmatch(_String(options["user_data_sha256"])) is None:
                    raise ValueError("Initialization digest must be SHA256")

    except (ValueError, TypeError, KeyError):
        failure = True

    if failure:
        raise MutationError(ProviderErrorCode.UNSUPPORTED, "validate-spec", False)

GetResource

GetResource(reference: ResourceReference) -> ProviderResource

Use the scoped base adapter while restricting observed lifecycle fields.

Source code in installed/flayer/providers/yandex_lifecycle.py
369
370
371
372
def GetResource(self, reference: ResourceReference) -> ProviderResource:
    """Use the scoped base adapter while restricting observed lifecycle fields."""

    return self._ValidateObservation(super().GetResource(reference))

FindResource

FindResource(spec: ResourceSpec, identity: StackIdentity) -> ProviderResource | None

Reconcile exact logical ownership; duplicates and changed desired content conflict.

Source code in installed/flayer/providers/yandex_lifecycle.py
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
def FindResource(
    self, spec: ResourceSpec, identity: StackIdentity
) -> ProviderResource | None:
    """Reconcile exact logical ownership; duplicates and changed desired content conflict."""

    self.ValidateSpec(spec)
    self._ValidateIdentity(identity)
    labels = identity.OwnershipLabels()
    labels[LOGICAL_ID_LABEL] = spec.logical_id
    ownership = tuple(sorted(labels.items()))
    matches = tuple(
        resource for resource in self.ListResources(spec.kind) if resource.HasLabels(ownership)
    )

    if len(matches) > 1:
        raise ProviderError(ProviderErrorCode.CONFLICT, "find")

    if not matches:
        return None

    resource = self._ValidateObservation(matches[0])

    if not resource.HasLabels(spec.OwnershipLabels(identity)) or resource.name != spec.name:
        raise ProviderError(ProviderErrorCode.CONFLICT, "find")

    options = dict(spec.parameters)

    if "zone_id" in options and self._ResourceZone(resource) != options["zone_id"]:
        raise ProviderError(ProviderErrorCode.SCOPE_MISMATCH, "find")

    return resource

CreateResource

CreateResource(spec: ResourceSpec, identity: StackIdentity, dependencies: Mapping[str, ProviderResource], operation_id: str) -> ProviderResource

Create once with stable ownership labels and an explicit, separately owned boot disk.

Source code in installed/flayer/providers/yandex_lifecycle.py
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
def CreateResource(
    self, spec: ResourceSpec, identity: StackIdentity,
    dependencies: Mapping[str, ProviderResource], operation_id: str,
) -> ProviderResource:
    """Create once with stable ownership labels and an explicit, separately owned boot disk."""

    self.ValidateSpec(spec)
    self._ValidateIdentity(identity)

    if not isinstance(operation_id, str) or OPERATION_ID_PATTERN.fullmatch(operation_id) is None:
        raise MutationError(ProviderErrorCode.UNSUPPORTED, "operation-id", False)

    options = dict(spec.parameters)
    content: bytes | None = None
    existing: ProviderResource | None = None
    arguments: tuple[str, ...] = ()
    preflight_failure: ProviderErrorCode | None = None

    try:
        content = self._ReadUserData(
            Path(_String(options["user_data_file"])), _String(options["user_data_sha256"])
        ) if "user_data_file" in options else None
        existing = self.FindResource(spec, identity)

        if existing is None:
            refreshed = self._Dependencies(spec, identity, dependencies)
            arguments = self._Arguments(spec, refreshed)

    except MutationError:
        raise

    except ProviderError as error:
        preflight_failure = error.code

    except Exception:
        preflight_failure = ProviderErrorCode.COMMAND_FAILED

    if preflight_failure is not None:
        raise MutationError(preflight_failure, "create", False)

    if existing is not None:
        return existing

    creation_labels = (*spec.OwnershipLabels(identity), (OPERATION_ID_LABEL, operation_id))
    labels = ",".join(f"{key}={value}" for key, value in creation_labels)
    command = (*self._CommandForKind(spec.kind), "create", "--name", spec.name, "--labels", labels)
    temporary_path: str | None = None
    mutation_started = False
    failure: ProviderErrorCode | None = None
    created: ProviderResource | None = None

    try:
        if content is not None:
            with tempfile.NamedTemporaryFile(mode="wb", delete=False) as destination:
                temporary_path = destination.name
                destination.write(content)
                destination.flush()
                os.fsync(destination.fileno())

            arguments = (*arguments, "--metadata-from-file", f"user-data={temporary_path}")

        mutation_started = True
        result = self._MutationRun((*command, *arguments), "create")

        try:
            payload: object = json.loads(result.stdout)

        except (ValueError, RecursionError):
            failure = ProviderErrorCode.INVALID_RESPONSE

        else:
            resource = self._ValidateObservation(self._NormalizeResource(payload, spec.kind, "create"))

            if not resource.HasLabels(creation_labels) or resource.name != spec.name:
                failure = ProviderErrorCode.SCOPE_MISMATCH

            elif "zone_id" in options and resource.zone_id != options["zone_id"]:
                failure = ProviderErrorCode.SCOPE_MISMATCH

            else:
                created = resource

    except MutationError:
        raise

    except ProviderError as error:
        failure = error.code

    except (OSError, ValueError):
        failure = ProviderErrorCode.COMMAND_FAILED

    finally:
        if temporary_path is not None:
            try:
                os.unlink(temporary_path)

            except FileNotFoundError:
                pass

            except OSError:
                failure = ProviderErrorCode.COMMAND_FAILED

    if failure is None and created is not None:
        return created

    raise MutationError(failure or ProviderErrorCode.INVALID_RESPONSE, "create", mutation_started)

DeleteResource

DeleteResource(reference: ResourceReference, identity: StackIdentity, logical_id: str, operation_id: str | None = None) -> None

Observe and verify ownership before exact-ID deletion, then confirm absence once.

Source code in installed/flayer/providers/yandex_lifecycle.py
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
def DeleteResource(
    self, reference: ResourceReference, identity: StackIdentity, logical_id: str,
    operation_id: str | None = None,
) -> None:
    """Observe and verify ownership before exact-ID deletion, then confirm absence once."""

    self._ValidateIdentity(identity)
    ValidateName(logical_id, "delete.logical_id")
    labels = identity.OwnershipLabels()
    labels[LOGICAL_ID_LABEL] = logical_id

    if operation_id is not None:
        if not isinstance(operation_id, str) or OPERATION_ID_PATTERN.fullmatch(operation_id) is None:
            raise MutationError(ProviderErrorCode.UNSUPPORTED, "operation-id", False)

        labels[OPERATION_ID_LABEL] = operation_id

    try:
        resource = self.GetResource(reference)

    except ProviderError as error:
        if error.code == ProviderErrorCode.NOT_FOUND:
            return

        raise

    if not resource.HasLabels(tuple(sorted(labels.items()))):
        raise MutationError(ProviderErrorCode.SCOPE_MISMATCH, "delete", False)

    command = self._CommandForKind(reference.kind)
    self._MutationRun((*command, "delete", "--id", reference.resource_id), "delete")
    failure = ProviderErrorCode.CONFLICT

    try:
        self.GetResource(reference)

    except ProviderError as error:
        if error.code == ProviderErrorCode.NOT_FOUND:
            return

        failure = error.code

    raise MutationError(failure, "delete", True)

ValidateComputeShape

ValidateComputeShape(options: Mapping[str, JsonValue]) -> None

Validate the supported Intel shapes without consulting a cloud account.

Source code in installed/flayer/providers/yandex_lifecycle.py
 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
def ValidateComputeShape(options: Mapping[str, JsonValue]) -> None:
    """Validate the supported Intel shapes without consulting a cloud account."""

    cores = _Integer(options["cores"], 2, 32)
    memory = _Integer(options["memory_gib"], 1, 128)

    if "platform_id" not in options and "core_fraction" not in options:
        return

    if "platform_id" not in options or "core_fraction" not in options:
        raise ValueError("Specify platform_id and core_fraction together")

    platform = _String(options["platform_id"])
    fractions = {"standard-v1": (5, 20, 100), "standard-v2": (5, 20, 50, 100),
                 "standard-v3": (20, 50, 100)}
    fraction = _Integer(options["core_fraction"], 1, 100)

    if platform not in fractions or fraction not in fractions[platform]:
        raise ValueError("Unsupported platform_id/core_fraction combination")

    if _String(options.get("zone_id", "")).startswith("kz1-") and platform != "standard-v3":
        raise ValueError("Kazakhstan deployments require platform_id standard-v3")

    if fraction == 100:
        valid_cores = (*range(2, 17, 2), 20, 24, 28, 32)
        ratios = tuple(float(value) for value in range(1, 9 if platform == "standard-v1" else 17))

    else:
        valid_cores = (2, 4)
        ratios = tuple(value / 2 for value in range(1, 5 if fraction == 5 else 9))

        if platform == "standard-v2" and fraction == 5:
            ratios = (0.25, *ratios)

    if cores not in valid_cores or memory / cores not in ratios:
        raise ValueError("Unsupported vCPU/RAM combination for the selected platform and core_fraction")