Skip to content

GlobalJobPreLoad

OpenPypeVersion

Fake semver version class for OpenPype version purposes.

The version

Source code in client/ayon_deadline/repository/custom/plugins/GlobalJobPreLoad.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
class OpenPypeVersion:
    """Fake semver version class for OpenPype version purposes.

    The version
    """
    def __init__(self, major, minor, patch, prerelease, origin=None):
        self.major = major
        self.minor = minor
        self.patch = patch
        self.prerelease = prerelease

        is_valid = True
        if major is None or minor is None or patch is None:
            is_valid = False
        self.is_valid = is_valid

        if origin is None:
            base = "{}.{}.{}".format(str(major), str(minor), str(patch))
            if not prerelease:
                origin = base
            else:
                origin = "{}-{}".format(base, str(prerelease))

        self.origin = origin

    @classmethod
    def from_string(cls, version):
        """Create an object of version from string.

        Args:
            version (str): Version as a string.

        Returns:
            Union[OpenPypeVersion, None]: Version object if input is nonempty
                string otherwise None.
        """

        if not version:
            return None
        valid_parts = VERSION_REGEX.findall(version)
        if len(valid_parts) != 1:
            # Return invalid version with filled 'origin' attribute
            return cls(None, None, None, None, origin=str(version))

        # Unpack found version
        major, minor, patch, pre, post = valid_parts[0]
        prerelease = pre
        # Post release is not important anymore and should be considered as
        #   part of prerelease
        # - comparison is implemented to find suitable build and builds should
        #       never contain prerelease part so "not proper" parsing is
        #       acceptable for this use case.
        if post:
            prerelease = "{}+{}".format(pre, post)

        return cls(
            int(major), int(minor), int(patch), prerelease, origin=version
        )

    def has_compatible_release(self, other):
        """Version has compatible release as other version.

        Both major and minor versions must be exactly the same. In that case
        a build can be considered as release compatible with any version.

        Args:
            other (OpenPypeVersion): Other version.

        Returns:
            bool: Version is release compatible with other version.
        """

        if self.is_valid and other.is_valid:
            return self.major == other.major and self.minor == other.minor
        return False

    def __bool__(self):
        return self.is_valid

    def __repr__(self):
        return "<{} {}>".format(self.__class__.__name__, self.origin)

    def __eq__(self, other):
        if not isinstance(other, self.__class__):
            return self.origin == other
        return self.origin == other.origin

    def __lt__(self, other):
        if not isinstance(other, self.__class__):
            return None

        if not self.is_valid:
            return True

        if not other.is_valid:
            return False

        if self.origin == other.origin:
            return None

        same_major = self.major == other.major
        if not same_major:
            return self.major < other.major

        same_minor = self.minor == other.minor
        if not same_minor:
            return self.minor < other.minor

        same_patch = self.patch == other.patch
        if not same_patch:
            return self.patch < other.patch

        if not self.prerelease:
            return False

        if not other.prerelease:
            return True

        pres = [self.prerelease, other.prerelease]
        pres.sort()
        return pres[0] == self.prerelease

from_string(version) classmethod

Create an object of version from string.

Parameters:

Name Type Description Default
version str

Version as a string.

required

Returns:

Type Description

Union[OpenPypeVersion, None]: Version object if input is nonempty string otherwise None.

Source code in client/ayon_deadline/repository/custom/plugins/GlobalJobPreLoad.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
@classmethod
def from_string(cls, version):
    """Create an object of version from string.

    Args:
        version (str): Version as a string.

    Returns:
        Union[OpenPypeVersion, None]: Version object if input is nonempty
            string otherwise None.
    """

    if not version:
        return None
    valid_parts = VERSION_REGEX.findall(version)
    if len(valid_parts) != 1:
        # Return invalid version with filled 'origin' attribute
        return cls(None, None, None, None, origin=str(version))

    # Unpack found version
    major, minor, patch, pre, post = valid_parts[0]
    prerelease = pre
    # Post release is not important anymore and should be considered as
    #   part of prerelease
    # - comparison is implemented to find suitable build and builds should
    #       never contain prerelease part so "not proper" parsing is
    #       acceptable for this use case.
    if post:
        prerelease = "{}+{}".format(pre, post)

    return cls(
        int(major), int(minor), int(patch), prerelease, origin=version
    )

has_compatible_release(other)

Version has compatible release as other version.

Both major and minor versions must be exactly the same. In that case a build can be considered as release compatible with any version.

Parameters:

Name Type Description Default
other OpenPypeVersion

Other version.

required

Returns:

Name Type Description
bool

Version is release compatible with other version.

Source code in client/ayon_deadline/repository/custom/plugins/GlobalJobPreLoad.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def has_compatible_release(self, other):
    """Version has compatible release as other version.

    Both major and minor versions must be exactly the same. In that case
    a build can be considered as release compatible with any version.

    Args:
        other (OpenPypeVersion): Other version.

    Returns:
        bool: Version is release compatible with other version.
    """

    if self.is_valid and other.is_valid:
        return self.major == other.major and self.minor == other.minor
    return False

get_ayon_executable()

Return AYON Executable from Event Plug-in Settings

Returns:

Type Description

list[str]: AYON executable paths.

Raises:

Type Description
RuntimeError

When no path configured at all.

Source code in client/ayon_deadline/repository/custom/plugins/GlobalJobPreLoad.py
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
def get_ayon_executable():
    """Return AYON Executable from Event Plug-in Settings

    Returns:
        list[str]: AYON executable paths.

    Raises:
        RuntimeError: When no path configured at all.

    """
    config = RepositoryUtils.GetPluginConfig("Ayon")
    exe_list = config.GetConfigEntryWithDefault("AyonExecutable", "")

    if not exe_list:
        raise RuntimeError(
            "Path to AYON executable not configured."
            "Please set it in AYON Deadline Plugin."
        )

    # clean '\ ' for MacOS pasting
    if platform.system().lower() == "darwin":
        exe_list = exe_list.replace("\\ ", " ")

    # Expand user paths
    expanded_paths = []
    for path in exe_list.split(";"):
        if path.startswith("~"):
            path = os.path.expanduser(path)
        expanded_paths.append(path)
    return ";".join(expanded_paths)

get_openpype_executable()

Return OpenPype Executable from Event Plug-in Settings

Source code in client/ayon_deadline/repository/custom/plugins/GlobalJobPreLoad.py
193
194
195
196
197
198
199
200
201
202
203
204
def get_openpype_executable():
    """Return OpenPype Executable from Event Plug-in Settings"""
    config = RepositoryUtils.GetPluginConfig("OpenPype")
    exe_list = config.GetConfigEntryWithDefault("OpenPypeExecutable", "")
    dir_list = config.GetConfigEntryWithDefault(
        "OpenPypeInstallationDirs", "")

    # clean '\ ' for MacOS pasting
    if platform.system().lower() == "darwin":
        exe_list = exe_list.replace("\\ ", " ")
        dir_list = dir_list.replace("\\ ", " ")
    return exe_list, dir_list

get_openpype_version_from_path(path, build=True)

Get OpenPype version from provided path. path (str): Path to scan. build (bool, optional): Get only builds, not sources

Returns:

Type Description

Union[OpenPypeVersion, None]: version of OpenPype if found.

Source code in client/ayon_deadline/repository/custom/plugins/GlobalJobPreLoad.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def get_openpype_version_from_path(path, build=True):
    """Get OpenPype version from provided path.
         path (str): Path to scan.
         build (bool, optional): Get only builds, not sources

    Returns:
        Union[OpenPypeVersion, None]: version of OpenPype if found.
    """

    # fix path for application bundle on macos
    if platform.system().lower() == "darwin":
        path = os.path.join(path, "MacOS")

    version_file = os.path.join(path, "openpype", "version.py")
    if not os.path.isfile(version_file):
        return None

    # skip if the version is not build
    exe = os.path.join(path, "openpype_console.exe")
    if platform.system().lower() in ["linux", "darwin"]:
        exe = os.path.join(path, "openpype_console")

    # if only builds are requested
    if build and not os.path.isfile(exe):  # noqa: E501
        print("   ! path is not a build: {}".format(path))
        return None

    version = {}
    with open(version_file, "r") as vf:
        exec(vf.read(), version)

    version_str = version.get("__version__")
    if version_str:
        return OpenPypeVersion.from_string(version_str)
    return None

handle_credentials(job)

Returns a tuple of values for AYON_SERVER_URL and AYON_API_KEY

AYON_API_KEY might be overridden directly from job environments. Or specific AYON_SERVER_URL might be attached to job to pick corespondent AYON_API_KEY from plugin configuration.

Source code in client/ayon_deadline/repository/custom/plugins/GlobalJobPreLoad.py
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
def handle_credentials(job):
    """Returns a tuple of values for AYON_SERVER_URL and AYON_API_KEY

    AYON_API_KEY might be overridden directly from job environments.
    Or specific AYON_SERVER_URL might be attached to job to pick corespondent
    AYON_API_KEY from plugin configuration.
    """
    config = RepositoryUtils.GetPluginConfig("Ayon")
    ayon_server_url = config.GetConfigEntryWithDefault("AyonServerUrl", "")
    ayon_api_key = config.GetConfigEntryWithDefault("AyonApiKey", "")

    job_ayon_server_url = job.GetJobEnvironmentKeyValue("AYON_SERVER_URL")
    job_ayon_api_key = job.GetJobEnvironmentKeyValue("AYON_API_KEY")

    # API key submitted with job environment will always take priority
    if job_ayon_api_key:
        ayon_api_key = job_ayon_api_key

    # Allow custom AYON API key per server URL if server URL is submitted
    # along with the job. The custom API keys can be configured on the
    # Deadline Repository AYON Plug-in settings, in the format of
    # `SERVER:PORT@APIKEY` per line.
    elif job_ayon_server_url and job_ayon_server_url != ayon_server_url:
        api_key = _get_ayon_api_key_from_additional_servers(
            config, job_ayon_server_url)
        if api_key:
            ayon_api_key = api_key
            print(">>> Using API key from Additional AYON Servers.")
        else:
            print(
                ">>> AYON Server URL submitted with job "
                f"'{job_ayon_server_url}' has no API key defined "
                "in AYON Deadline plugin configuration,"
                " `Additional AYON Servers` section."
                " Use Deadline monitor to modify the values."
                "Falling back to `AYON API key` set in `AYON Credentials`"
                " section of AYON plugin configuration."
            )
        ayon_server_url = job_ayon_server_url
    if not all([ayon_server_url, ayon_api_key]):
        raise RuntimeError(
            "Missing required values for server url and api key. "
            "Please fill in AYON Deadline plugin or provide by "
            "AYON_SERVER_URL and AYON_API_KEY"
        )
    return ayon_server_url, ayon_api_key

inject_ayon_environment(deadlinePlugin)

Pull env vars from AYON and push them to rendering process.

Used for correct paths, configuration from AYON etc.

Source code in client/ayon_deadline/repository/custom/plugins/GlobalJobPreLoad.py
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
def inject_ayon_environment(deadlinePlugin):
    """ Pull env vars from AYON and push them to rendering process.

        Used for correct paths, configuration from AYON etc.
    """
    job = deadlinePlugin.GetJob()

    print(">>> Injecting AYON environments ...")
    try:
        exe_list = get_ayon_executable()
        exe = FileUtils.SearchFileList(exe_list)

        if not exe:
            raise RuntimeError((
               "AYON executable was not found in the semicolon "
               "separated list \"{}\"."
               "The path to the render executable can be configured"
               " from the Plugin Configuration in the Deadline Monitor."
            ).format(exe_list))

        print("--- AYON executable: {}".format(exe))

        ayon_bundle_name = job.GetJobEnvironmentKeyValue("AYON_BUNDLE_NAME")
        if not ayon_bundle_name:
            raise RuntimeError(
                "Missing env var in job properties AYON_BUNDLE_NAME"
            )

        ayon_server_url, ayon_api_key = handle_credentials(job)

        site_id = os.environ.get("AYON_SITE_ID")
        shared_env_group = None
        if site_id:
            hash_base = f"{site_id}|{getpass.getuser()}"
            hash_sha256 = sha256(hash_base.encode())
            shared_env_group = hash_sha256.hexdigest()[-10:]
        # drive caching of environment variables with env var
        # it is recommended to use same value AYON_SITE_ID for 'same'
        # render nodes (eg. same OS etc.)
        if shared_env_group:
            print(">>> Caching of environment file will be used.")
            output_dir = _get_output_dir(job)
            environment_file_name = f"env_{job.JobId}_{shared_env_group}.json"
            export_dir_url = os.path.join(
                output_dir,
                ".ayon_env_cache"
            )

            if not os.path.exists(export_dir_url):
                os.makedirs(export_dir_url, exist_ok=True)

            export_path = os.path.join(
                export_dir_url,
                environment_file_name)
            _wait_for_in_progress(job, export_path)
        else:
            # no caching - default behavior
            temp_file_name = "{}_{}.json".format(
                datetime.utcnow().strftime("%Y%m%d%H%M%S%f"),
                str(uuid.uuid1())
            )
            export_path = os.path.join(tempfile.gettempdir(), temp_file_name)

        if not os.path.exists(export_path):
            print(
                f">>> '{export_path}' with extracted environment doesn't "
                "exist yet, running extraction process..."
            )
            temp_export_path = f"{export_path}.tmp"
            with open(temp_export_path, "w"):
                pass
            try:
                _extract_environments(
                    ayon_server_url,
                    ayon_api_key,
                    ayon_bundle_name,
                    deadlinePlugin,
                    exe,
                    temp_export_path,
                    job
                )
                if (not os.path.exists(export_path) and
                        os.path.exists(temp_export_path)):
                    print(f"Creating env var file {export_path}")
                    os.rename(temp_export_path, export_path)
            finally:
                if os.path.exists(temp_export_path):
                    os.remove(temp_export_path)

        print(f">>> Loading file '{export_path}' ...")
        with open(export_path) as fp:
            contents = json.load(fp)

        for key, value in sorted(contents.items()):
            deadlinePlugin.SetProcessEnvironmentVariable(key, value)

        if "PATH" in contents:
            # Set os.environ[PATH] so studio settings' path entries
            # can be used to define search path for executables.
            print(f">>> Setting 'PATH' Environment to: {contents['PATH']}")
            os.environ["PATH"] = contents["PATH"]

        script_url = job.GetJobPluginInfoKeyValue("ScriptFilename")
        if script_url:
            script_url = script_url.format(**contents).replace("\\", "/")
            print(">>> Setting script path {}".format(script_url))
            job.SetJobPluginInfoKeyValue("ScriptFilename", script_url)

        print(">> Injection end.")
    except Exception as e:
        if hasattr(e, "output"):
            print(">>> Exception {}".format(e.output))
        import traceback
        print(traceback.format_exc())
        print("!!! Injection failed.")
        raise

inject_openpype_environment(deadlinePlugin)

Pull env vars from OpenPype and push them to rendering process.

Used for correct paths, configuration from OpenPype etc.

Source code in client/ayon_deadline/repository/custom/plugins/GlobalJobPreLoad.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
def inject_openpype_environment(deadlinePlugin):
    """ Pull env vars from OpenPype and push them to rendering process.

        Used for correct paths, configuration from OpenPype etc.
    """
    job = deadlinePlugin.GetJob()

    print(">>> Injecting OpenPype environments ...")
    try:
        exe_list, dir_list = get_openpype_executable()
        exe = FileUtils.SearchFileList(exe_list)

        requested_version = job.GetJobEnvironmentKeyValue("OPENPYPE_VERSION")
        if requested_version:
            exe = get_requested_openpype_executable(
                exe, dir_list, requested_version
            )
            if exe is None:
                raise RuntimeError((
                    "Cannot find compatible version available for version {}"
                    " requested by the job. Please add it through plugin"
                    " configuration in Deadline or install it to configured"
                    " directory."
                ).format(requested_version))

        if not exe:
            raise RuntimeError((
                "OpenPype executable was not found in the semicolon "
                "separated list \"{}\"."
                "The path to the render executable can be configured"
                " from the Plugin Configuration in the Deadline Monitor."
            ).format(";".join(exe_list)))

        print("--- OpenPype executable: {}".format(exe))

        # tempfile.TemporaryFile cannot be used because of locking
        temp_file_name = "{}_{}.json".format(
            datetime.utcnow().strftime("%Y%m%d%H%M%S%f"),
            str(uuid.uuid1())
        )
        export_path = os.path.join(tempfile.gettempdir(), temp_file_name)
        print(">>> Temporary path: {}".format(export_path))

        args = [
            "--headless",
            "extractenvironments",
            export_path
        ]

        add_kwargs = {
            "project": job.GetJobEnvironmentKeyValue("AVALON_PROJECT"),
            "asset": job.GetJobEnvironmentKeyValue("AVALON_ASSET"),
            "task": job.GetJobEnvironmentKeyValue("AVALON_TASK"),
            "app": job.GetJobEnvironmentKeyValue("AVALON_APP_NAME"),
            "envgroup": "farm"
        }

        # use legacy IS_TEST env var to mark automatic tests for OP
        if job.GetJobEnvironmentKeyValue("IS_TEST"):
            args.append("--automatic-tests")

        if all(add_kwargs.values()):
            for key, value in add_kwargs.items():
                args.extend(["--{}".format(key), value])
        else:
            raise RuntimeError((
                "Missing required env vars: AVALON_PROJECT, AVALON_ASSET,"
                " AVALON_TASK, AVALON_APP_NAME"
            ))

        openpype_mongo = job.GetJobEnvironmentKeyValue("OPENPYPE_MONGO")
        if openpype_mongo:
            # inject env var for OP extractenvironments
            # SetEnvironmentVariable is important, not SetProcessEnv...
            deadlinePlugin.SetEnvironmentVariable("OPENPYPE_MONGO",
                                                  openpype_mongo)

        if not os.environ.get("OPENPYPE_MONGO"):
            print(">>> Missing OPENPYPE_MONGO env var, process won't work")

        os.environ["AVALON_TIMEOUT"] = "5000"

        args_str = subprocess.list2cmdline(args)
        print(">>> Executing: {} {}".format(exe, args_str))
        process_exitcode = deadlinePlugin.RunProcess(
            exe, args_str, os.path.dirname(exe), -1
        )

        if process_exitcode != 0:
            raise RuntimeError(
                "Failed to run OpenPype process to extract environments."
            )

        print(">>> Loading file ...")
        with open(export_path) as fp:
            contents = json.load(fp)

        for key, value in sorted(contents.items()):
            deadlinePlugin.SetProcessEnvironmentVariable(key, value)

        if "PATH" in contents:
            # Set os.environ[PATH] so studio settings' path entries
            # can be used to define search path for executables.
            print(f">>> Setting 'PATH' Environment to: {contents['PATH']}")
            os.environ["PATH"] = contents["PATH"]

        script_url = job.GetJobPluginInfoKeyValue("ScriptFilename")
        if script_url:
            script_url = script_url.format(**contents).replace("\\", "/")
            print(">>> Setting script path {}".format(script_url))
            job.SetJobPluginInfoKeyValue("ScriptFilename", script_url)

        print(">>> Removing temporary file")
        os.remove(export_path)

        print(">> Injection end.")
    except Exception as e:
        if hasattr(e, "output"):
            print(">>> Exception {}".format(e.output))
        import traceback
        print(traceback.format_exc())
        print("!!! Injection failed.")
        raise

inject_render_job_id(deadlinePlugin)

Inject dependency ids to publish process as env var for validation.

Source code in client/ayon_deadline/repository/custom/plugins/GlobalJobPreLoad.py
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
def inject_render_job_id(deadlinePlugin):
    """Inject dependency ids to publish process as env var for validation."""
    print(">>> Injecting render job id ...")
    job = deadlinePlugin.GetJob()

    dependency_ids = job.JobDependencyIDs
    print(">>> Dependency IDs: {}".format(dependency_ids))
    render_job_ids = ",".join(dependency_ids)
    deadlinePlugin.SetProcessEnvironmentVariable(
        "RENDER_JOB_IDS", render_job_ids
    )

    ayon_server_url, ayon_api_key = handle_credentials(job)

    credentials = {
        "AYON_SERVER_URL": ayon_server_url,
        "AYON_API_KEY": ayon_api_key
    }
    for env, val in credentials.items():
        job.SetJobEnvironmentKeyValue(env, val)
    print(">>> Injection end.")