Skip to content

control

AYONDistribution

Distribution control.

Receive information from server what addons and dependency packages should be available locally and prepare/validate their distribution.

Arguments are available for testing of the class.

Parameters:

Name Type Description Default
addon_dirpath Optional[str]

Where addons will be stored.

None
dependency_dirpath Optional[str]

Where dependencies will be stored.

None
dist_factory Optional[DownloadFactory]

Factory which cares about downloading of items based on source type.

None
installers_info Optional[list[dict[str, Any]]]

List of prepared installers' info.

NOT_SET
addons_info Optional[list[dict[str, Any]]]

List of prepared addons' info.

NOT_SET
dependency_packages_info Optional[list[dict[str, Any]]]

Info about packages from server.

NOT_SET
bundles_info Optional[dict[str, Any]]

Info about bundles.

NOT_SET
studio_bundle_name Optional[str]

Name of studio bundle to use.

NOT_SET
project_bundle_name Optional[str]

Name of project bundle to use.

NOT_SET
project_name Optional[str]

Name of project for which project bundle can be auto-detected.

NOT_SET
use_staging Optional[bool]

Use staging versions of an addon. If not passed, 'is_staging_enabled' is used as default value.

None
use_dev Optional[bool]

Use develop versions of an addon. If not passed, 'is_dev_mode_enabled' is used as default value.

None
skip_installer_dist bool

Skip installer distribution. This is for testing purposes and for running from code.

False
Source code in common/ayon_common/distribution/control.py
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
class AYONDistribution:
    """Distribution control.

    Receive information from server what addons and dependency packages
    should be available locally and prepare/validate their distribution.

    Arguments are available for testing of the class.

    Args:
        addon_dirpath (Optional[str]): Where addons will be stored.
        dependency_dirpath (Optional[str]): Where dependencies will be stored.
        dist_factory (Optional[DownloadFactory]): Factory which cares about
            downloading of items based on source type.
        installers_info (Optional[list[dict[str, Any]]]): List of prepared
            installers' info.
        addons_info (Optional[list[dict[str, Any]]]): List of prepared
            addons' info.
        dependency_packages_info (Optional[list[dict[str, Any]]]): Info
            about packages from server.
        bundles_info (Optional[dict[str, Any]]): Info about
            bundles.
        studio_bundle_name (Optional[str]): Name of studio bundle to use.
        project_bundle_name (Optional[str]): Name of project bundle to use.
        project_name (Optional[str]): Name of project for which project bundle
            can be auto-detected.
        use_staging (Optional[bool]): Use staging versions of an addon.
            If not passed, 'is_staging_enabled' is used as default value.
        use_dev (Optional[bool]): Use develop versions of an addon.
            If not passed, 'is_dev_mode_enabled' is used as default value.
        skip_installer_dist (bool): Skip installer distribution. This
            is for testing purposes and for running from code.

    """
    def __init__(
        self,
        addon_dirpath: Optional[str] = None,
        dependency_dirpath: Optional[str] = None,
        dist_factory: Optional[DownloadFactory] = None,
        installers_info: Optional[list[dict[str, Any]]] = NOT_SET,
        addons_info: Optional[list[dict[str, Any]]] = NOT_SET,
        dependency_packages_info: Optional[list[dict[str, Any]]] = NOT_SET,
        bundles_info: Optional[list[dict[str, Any]]] = NOT_SET,
        studio_bundle_name: Optional[str] = NOT_SET,
        project_bundle_name: Optional[str] = NOT_SET,
        project_name: Optional[str] = NOT_SET,
        use_staging: Optional[bool] = None,
        use_dev: Optional[bool] = None,
        active_user: Optional[bool] = None,
        skip_installer_dist: bool = False,
    ):
        self._log = None

        self._dist_started = False

        self._addons_dirpath = addon_dirpath or get_addons_dir()
        self._dependency_dirpath = dependency_dirpath or get_dependencies_dir()
        self._dist_factory = (
            dist_factory or get_default_download_factory()
        )

        if studio_bundle_name is NOT_SET:
            studio_bundle_name = (
                os.environ.get("AYON_STUDIO_BUNDLE_NAME") or NOT_SET
            )

        if project_bundle_name is NOT_SET:
            project_bundle_name = (
                os.environ.get("AYON_BUNDLE_NAME") or NOT_SET
            )

        if project_name is NOT_SET:
            project_name = os.environ.get("AYON_PROJECT_NAME") or NOT_SET

        # Where addon zip files and dependency packages are downloaded
        self._dist_download_dirs = []
        self._dist_unzip_dirs = []

        self._dist_addons_unzip_temp = os.path.join(
            self._addons_dirpath, ".unzip_temp"
        )
        self._dist_dep_packages_unzip_temp = os.path.join(
            self._dependency_dirpath, ".unzip_temp"
        )

        self._installers_info = installers_info
        self._installer_items = NOT_SET
        self._expected_installer_version = NOT_SET
        self._installer_item = NOT_SET
        self._installer_executable = NOT_SET
        self._skip_installer_dist = skip_installer_dist
        self._installer_filepath = None
        self._installer_dist_error = None

        # Raw addons data from server
        self._addons_info = addons_info
        # Prepared data as Addon objects
        self._addon_items = NOT_SET
        # Distrubtion items of addons
        #   - only those addons and versions that should be distributed
        self._addon_dist_items = NOT_SET

        # Raw dependency packages data from server
        self._dependency_packages_info = dependency_packages_info
        # Prepared dependency packages as objects
        self._dependency_packages_items = NOT_SET
        # Dependency package item that should be used
        self._dependency_package_item = NOT_SET
        # Distribution item of dependency package
        self._dependency_dist_item = NOT_SET

        # Raw bundles data from server
        self._bundles_info = bundles_info
        # Bundles as objects
        self._bundle_items = NOT_SET

        # Bundle that should be used in production
        self._studio_production_bundle = NOT_SET
        # Bundle that should be used in staging
        self._studio_staging_bundle = NOT_SET
        # Bundle that should be used in dev
        self._studio_dev_bundle = NOT_SET
        # Boolean that defines if staging bundle should be used
        self._use_staging = use_staging
        self._use_dev = use_dev
        self._active_user = active_user

        # Specific bundle name should be used
        self._studio_bundle_name = studio_bundle_name
        self._project_bundle_name = project_bundle_name
        self._project_name = project_name

        # Final bundles that will be used
        self._studio_bundle = NOT_SET
        self._project_bundle = NOT_SET

    @property
    def active_user(self) -> str:
        if self._active_user is None:
            user = ayon_api.get_user()
            self._active_user = user["name"]
        return self._active_user

    @property
    def use_staging(self) -> bool:
        """Staging version of a bundle should be used.

        This value is completely ignored if specific bundle name should
            be used.

        Returns:
            bool: True if staging version should be used.

        """
        if self._use_staging is None:
            self._use_staging = is_staging_enabled()

        if self._use_staging and self.use_dev:
            self._use_staging = False
        return self._use_staging

    @property
    def use_dev(self) -> bool:
        """Develop version of a bundle should be used.

        This value is completely ignored if specific bundle name should
            be used.

        Returns:
            bool: True if staging version should be used.

        """
        if self._use_dev is None:
            if self._studio_bundle_name is NOT_SET:
                self._use_dev = is_dev_mode_enabled()
            else:
                bundle = next(
                    (
                        bundle
                        for bundle in self.bundle_items
                        if bundle.name == self._studio_bundle_name
                    ),
                    None
                )
                if bundle is not None:
                    self._use_dev = bundle.is_dev
                else:
                    self._use_dev = False
        return self._use_dev

    @property
    def log(self) -> logging.Logger:
        """Helper to access logger.

        Returns:
             logging.Logger: Logger instance.

        """
        if self._log is None:
            self._log = logging.getLogger(self.__class__.__name__)
        return self._log

    @property
    def bundles_info(self) -> list[dict[str, Any]]:
        """

        Returns:
            list[dict[str, Any]]: Bundles information from server.

        """
        if self._bundles_info is NOT_SET:
            self._bundles_info = ayon_api.get_bundles()["bundles"]
        return self._bundles_info

    @property
    def bundle_items(self) -> list[Bundle]:
        """

        Returns:
            list[Bundle]: List of bundles info.

        """
        if self._bundle_items is NOT_SET:
            self._bundle_items = [
                Bundle.from_dict(info)
                for info in self.bundles_info
            ]
        return self._bundle_items

    @property
    def studio_production_bundle(self) -> Optional[Bundle]:
        """

        Returns:
            Optional[Bundle]: Bundle that should be used in production.

        """
        if self._studio_production_bundle is NOT_SET:
            self._prepare_bundles()
        return self._studio_production_bundle

    @property
    def studio_staging_bundle(self) -> Optional[Bundle]:
        """

        Returns:
            Optional[Bundle]: Bundle that should be used in staging.

        """
        if self._studio_staging_bundle is NOT_SET:
            self._prepare_bundles()
        return self._studio_staging_bundle

    @property
    def studio_dev_bundle(self) -> Optional[Bundle]:
        """

        Returns:
            Optional[Bundle]: Bundle that should be used in dev.

        """
        if self._studio_dev_bundle is NOT_SET:
            self._prepare_bundles()
        return self._studio_dev_bundle

    @property
    def studio_bundle_to_use(self) -> Optional[Bundle]:
        """

        Returns:
            Optional[Bundle]: Bundle that should be used in distribution.

        """
        if self._studio_bundle is not NOT_SET:
            return self._studio_bundle

        self._prepare_bundles()
        if self._studio_bundle_name is NOT_SET:
            if self.use_staging:
                self._studio_bundle = self.studio_staging_bundle
            elif self.use_dev:
                self._studio_bundle = self.studio_dev_bundle
            else:
                self._studio_bundle = self.studio_production_bundle
            return self._studio_bundle

        bundle = next(
            (
                bundle
                for bundle in self.bundle_items
                if bundle.name == self._studio_bundle_name
            ),
            None
        )
        if bundle is None:
            raise BundleNotFoundError(self._studio_bundle_name)
        self._studio_bundle = bundle
        return self._studio_bundle

    @property
    def project_bundle_to_use(self) -> Optional[Bundle]:
        """Bundle that will be used for distribution.

        Bundle that should be used can be affected by 'project_bundle_name',
            'project_name', 'studio_bundle_name' or 'use_staging'.

        Returns:
            Optional[Bundle]: Bundle that will be used for distribution
                or None.

        Raises:
            BundleNotFoundError: When bundle name to use is defined
                but is not available on server.

        """
        if not self._project_bundle:
            # Force to use studio bundle as project bundle in dev mode
            studio_bundle = self.studio_bundle_to_use
            if not studio_bundle or studio_bundle.is_dev:
                self._project_bundle = studio_bundle
                return self._project_bundle

            project_bundle = self._get_project_bundle()
            # Auto-fix 'AYON_BUNDLE_NAME' filled with studio bundle name
            if project_bundle and not project_bundle.is_project_bundle:
                project_bundle = None

            if not project_bundle:
                project_bundle = self.studio_bundle_to_use
            self._project_bundle = project_bundle
        return self._project_bundle

    @property
    def project_bundle_name_to_use(self) -> Optional[str]:
        """Name of bundle that will be used for distribution.

        Returns:
            Optional[str]: Name of bundle that will be used for
                distribution.

        """
        bundle = self.project_bundle_to_use
        return None if bundle is None else bundle.name

    @property
    def installers_info(self) -> list[dict[str, Any]]:
        """Installers information from server.

        Returns:
            list[dict[str, Any]]: Installers information from server.

        """
        if self._installers_info is NOT_SET:
            self._installers_info = ayon_api.get_installers()["installers"]
        return self._installers_info

    @property
    def installer_items(self) -> list[Installer]:
        """Installers as objects.

        Returns:
            list[Installer]: List of installers info from server.

        """
        if self._installer_items is NOT_SET:
            self._installer_items = [
                Installer.from_dict(info)
                for info in self.installers_info
            ]
        return self._installer_items

    @property
    def expected_installer_version(self) -> Optional[str]:
        """Excepted installer version.

        Returns:
            Optional[str]: Expected installer version or None defined by
                bundle that should be used.

        """
        if self._expected_installer_version is not NOT_SET:
            return self._expected_installer_version

        bundle = self.project_bundle_to_use
        version = None if bundle is None else bundle.installer_version
        self._expected_installer_version = version
        return version

    @property
    def need_installer_change(self) -> bool:
        """Installer should be changed.

        Current installer is using different version than what is expected
            by bundle.

        Returns:
            bool: True if installer should be changed.

        """
        if self._skip_installer_dist:
            return False

        version = os.getenv("AYON_VERSION")
        return version != self.expected_installer_version

    @property
    def need_installer_distribution(self) -> bool:
        """Installer distribution is needed.

        Todos:
            Add option to skip if running from code?

        Returns:
            bool: True if installer distribution is needed.

        """
        if not self.need_installer_change:
            return False

        return self.installer_executable is None

    @property
    def installer_dist_error(self) -> Optional[str]:
        """Installer distribution error message.

        Returns:
              Optional[str]: Error that happened during installer
                distribution.

        """
        return self._installer_dist_error

    @property
    def installer_filepath(self) -> Optional[str]:
        """Path to a distribution package/installer.

        This can be used as reference for user where to find downloaded
            installer on disk and distribute it manually.

        Returns:
            Optional[str]: Path to installer.

        """
        return self._installer_filepath

    @property
    def installer_executable(self) -> Optional[str]:
        """Path to installer executable that should be used.

        Notes:
            The 'installer_executable' is maybe confusing naming. It might be
                called 'ayon_executable'?

        Returns:
            Optional[str]: Path to installer executable that should be
                used. None if executable is not found and must be distributed
                or bundle does not have defined an installer to use.

        """
        if self._installer_executable is not NOT_SET:
            return self._installer_executable

        path = None
        if not self.need_installer_change:
            self._installer_executable = sys.executable
            return self._installer_executable

        # Compare existing executable with current executable
        current_executable = sys.executable
        # Use 'ayon.exe' for executable lookup on Windows
        root, filename = os.path.split(current_executable)
        if filename == "ayon_console.exe":
            current_executable = os.path.join(root, "ayon.exe")

        # TODO look to expected target install directory too
        executables_info = get_executables_info_by_version(
            self.expected_installer_version)
        for executable_info in executables_info:
            executable_path = executable_info.get("executable")
            if (
                not os.path.exists(executable_path)
                or executable_path == current_executable
            ):
                continue
            path = executable_path
            break

        # Make sure current executable filename is used on Windows
        if path and filename == "ayon_console.exe":
            path = os.path.join(os.path.dirname(path), filename)

        if path:
            self._installer_executable = path
            return path

        # Guess based on "expected" path of the version
        # - is used if the AYON is already installed at target location but is
        #   missing in the metadata file
        current_version = os.environ["AYON_VERSION"]
        platform_name = platform.system().lower()
        if platform_name in {"windows", "linux"}:
            executable_dir, exe_name = os.path.split(sys.executable)
            install_root, dirname = os.path.split(executable_dir)
            if current_version in dirname:
                new_dirname = dirname.replace(
                    current_version,
                    self.expected_installer_version
                )
                executable = os.path.join(
                    install_root, new_dirname, exe_name
                )
                if os.path.exists(executable):
                    path = executable

        elif platform_name == "darwin":
            app_name = f"AYON {self.expected_installer_version}.app"
            excutable = f"/Applications/{app_name}/Contents/MacOS/ayon"
            if os.path.exists(excutable):
                path = excutable

        self._installer_executable = path
        return path

    @property
    def installer_item(self):
        """Installer item that should be used for distribution.

        Returns:
            Union[Installer, None]: Installer information item.

        """
        if self._installer_item is not NOT_SET:
            return self._installer_item

        final_item = None
        expected_version = self.expected_installer_version
        if expected_version:
            final_item = next(
                (
                    item
                    for item in self.installer_items
                    if (
                        item.version == expected_version
                        and item.platform_name == platform.system().lower()
                    )
                ),
                None
            )

        self._installer_item = final_item
        return final_item

    def distribute_installer(self):
        """Distribute installer."""

        installer_item = self.installer_item
        if installer_item is None:
            self._installer_executable = None
            self._installer_dist_error = (
                f"Bundle '{self.project_bundle_name_to_use}'"
                " does not have set installer version to use."
            )
            return

        downloader_data = {
            "type": "installer",
            "version": installer_item.version,
            "filename": installer_item.filename,
        }

        tmp_used = False
        downloads_dir = get_downloads_dir()
        if not downloads_dir or not os.path.exists(downloads_dir):
            tmp_used = True
            downloads_dir = tempfile.mkdtemp(prefix="ayon_installer")
            change_permissions_recursive(downloads_dir)

        dist_item = None
        try:
            dist_item = InstallerDistributionItem(
                tmp_used,
                downloads_dir,
                UpdateState.OUTDATED,
                installer_item.checksum,
                installer_item.checksum_algorithm,
                self._dist_factory,
                list(installer_item.sources),
                downloader_data,
                f"Installer {installer_item.version}",
            )

            if (
                platform.system().lower() != "windows"
                and dist_item.is_missing_permissions
            ):
                self._installer_dist_error = (
                    "Your user does not have required permissions to update"
                    " AYON launcher."
                    " Please contact your administrator, or use user"
                    " with permissions."
                )
                return

            for result in dist_item.distribute():
                if result:
                    break

            self._installer_executable = dist_item.executable
            if dist_item.installer_error is not None:
                self._installer_dist_error = dist_item.installer_error

            elif dist_item.state == UpdateState.MISS_SOURCE_FILES:
                self._installer_dist_error = (
                    "Couldn't find valid installer source for required"
                    f" AYON launcher version {installer_item.version}."
                )

            elif not self._installer_executable:
                self._installer_dist_error = (
                    "Couldn't find installed AYON launcher."
                    " Please try to launch AYON manually."
                )

        except Exception:
            self.log.warning(
                "Installer distribution failed do to unknown reasons.",
                exc_info=True
            )
            self._installer_dist_error = (
                f"Distribution of AYON launcher {installer_item.version}"
                " failed with unexpected reason."
            )

        finally:
            if dist_item is not None:
                self._installer_filepath = dist_item.installer_path

            if tmp_used and os.path.exists(downloads_dir):
                shutil.rmtree(downloads_dir)

    @property
    def addons_info(self) -> dict[str, dict[str, Any]]:
        """Server information about available addons.

        Returns:
            dict[str, dict[str, Any]]: Addon info by addon name.

        """
        if self._addons_info is NOT_SET:
            # Use details to get information about client.zip
            server_info = ayon_api.get_addons_info(details=True)
            self._addons_info = server_info["addons"]
        return self._addons_info

    @property
    def addon_items(self) -> dict[str, AddonInfo]:
        """Information about available addons on server.

        Addons may require distribution of files. For those addons will be
        created 'DistributionItem' handling distribution itself.

        Returns:
            dict[str, AddonInfo]: Addon info object by addon name.

        """
        if self._addon_items is NOT_SET:
            addons_info = {}
            for addon in self.addons_info:
                addon_info = AddonInfo.from_dict(addon)
                addons_info[addon_info.name] = addon_info
            self._addon_items = addons_info
        return self._addon_items

    @property
    def dependency_packages_info(self) -> list[dict[str, Any]]:
        """Server information about available dependency packages.

        Notes:
            For testing purposes it is possible to pass dependency packages
                information to '__init__'.

        Returns:
            list[dict[str, Any]]: Dependency packages information.

        """
        if self._dependency_packages_info is NOT_SET:
            self._dependency_packages_info = (
                ayon_api.get_dependency_packages())["packages"]
        return self._dependency_packages_info

    @property
    def dependency_packages_items(self) -> dict[str, DependencyItem]:
        """Dependency packages as objects.

        Returns:
            dict[str, DependencyItem]: Dependency packages as objects by name.

        """
        if self._dependency_packages_items is NOT_SET:
            dependenc_package_items = {}
            for item in self.dependency_packages_info:
                item = DependencyItem.from_dict(item)
                dependenc_package_items[item.filename] = item
            self._dependency_packages_items = dependenc_package_items
        return self._dependency_packages_items

    @property
    def dependency_package_item(self) -> Optional[DependencyItem]:
        """Dependency package item that should be used by bundle.

        Returns:
            Optional[DependencyItem]: None if bundle does not have
                specified dependency package.

        """
        if self._dependency_package_item is NOT_SET:
            dependency_package_item = None
            bundle = self.project_bundle_to_use
            if bundle is not None:
                package_name = bundle.dependency_packages.get(
                    platform.system().lower()
                )
                dependency_package_item = self.dependency_packages_items.get(
                    package_name)
            self._dependency_package_item = dependency_package_item
        return self._dependency_package_item

    def get_addon_dist_items(self) -> list[dict[str, Any]]:
        """Addon distribution items.

        These items describe source files required by addon to be available on
        machine. Each item may have 0-n source information from where can be
        obtained. If file is already available it's state will be 'UPDATED'.

        Example output:
            [
                {
                    "dist_item": DistributionItem,
                    "addon_name": str,
                    "addon_version": str,
                    "addon_item": AddonInfo,
                    "addon_version_item": AddonVersionInfo
                }, {
                    ...
                }
            ]

        Returns:
             list[dict[str, Any]]: Distribution items with addon version item.

        """
        if self._addon_dist_items is NOT_SET:
            self._addon_dist_items = (
                self._prepare_current_addon_dist_items())
        return self._addon_dist_items

    def get_dependency_dist_item(self) -> Optional[DistributionItem]:
        """Dependency package distribution item.

        Item describe source files required by server to be available on
        machine. Item may have 0-n source information from where can be
        obtained. If file is already available it's state will be 'UPDATED'.

        'None' is returned if server does not have defined any dependency
        package.

        Returns:
            Optional[DistributionItem]: Dependency item or None if server
                does not have specified any dependency package.

        """
        if self._dependency_dist_item is NOT_SET:
            self._dependency_dist_item = self._prepare_dependency_progress()
        return self._dependency_dist_item

    def get_dependency_metadata_filepath(self) -> str:
        """Path to distribution metadata file.

        Metadata contain information about distributed packages, used source,
        expected file hash and time when file was distributed.

        Returns:
            str: Path to a file where dependency package metadata are stored.

        """
        return os.path.join(self._dependency_dirpath, "dependency.json")

    def get_addons_metadata_filepath(self) -> str:
        """Path to addons metadata file.

        Metadata contain information about distributed addons, used sources,
        expected file hashes and time when files were distributed.

        Returns:
            str: Path to a file where addons metadata are stored.

        """
        return os.path.join(self._addons_dirpath, "addons.json")

    @staticmethod
    def read_metadata_file(
        filepath: str,
        default_value: Optional[Any] = None,
    ) -> dict[str, Any]:
        """Read json file from path.

        Method creates the file when does not exist with default value.

        Args:
            filepath (str): Path to json file.
            default_value (Union[Dict[str, Any], List[Any], None]): Default
                value if the file is not available (or valid).

        Returns:
            Union[Dict[str, Any], List[Any]]: Value from file.
        """

        if default_value is None:
            default_value = {}

        if not os.path.exists(filepath):
            return default_value

        try:
            with open(filepath, "r") as stream:
                data = json.load(stream)
        except ValueError:
            data = default_value
        return data

    @staticmethod
    def save_metadata_file(filepath: str, data: dict[str, Any]):
        """Store data to json file.

        Method creates the file when does not exist.

        Args:
            filepath (str): Path to json file.
            data (dict[str, Any]): Data to store into file.

        """
        dirpath = os.path.dirname(filepath)
        os.makedirs(dirpath, exist_ok=True)
        try:
            os.chmod(dirpath, 0o777)
        except PermissionError:
            print(f"Failed to change permissions for {dirpath}.")
        with open(filepath, "w") as stream:
            json.dump(data, stream, indent=4)

        change_permissions_recursive(dirpath)

    def get_dependency_metadata(self) -> dict[str, Any]:
        filepath = self.get_dependency_metadata_filepath()
        return self.read_metadata_file(filepath, {})

    def update_dependency_metadata(
        self, package_name: str, data: dict[str, Any]
    ):
        dependency_metadata = self.get_dependency_metadata()
        dependency_metadata[package_name] = data
        filepath = self.get_dependency_metadata_filepath()
        self.save_metadata_file(filepath, dependency_metadata)

    def get_addons_metadata(self) -> dict[str, Any]:
        filepath = self.get_addons_metadata_filepath()
        return self.read_metadata_file(filepath, {})

    def update_addons_metadata(self, addons_information: dict[str, Any]):
        if not addons_information:
            return
        addons_metadata = self.get_addons_metadata()
        for addon_name, version_value in addons_information.items():
            if addon_name not in addons_metadata:
                addons_metadata[addon_name] = {}
            for addon_version, version_data in version_value.items():
                addons_metadata[addon_name][addon_version] = version_data

        filepath = self.get_addons_metadata_filepath()
        self.save_metadata_file(filepath, addons_metadata)

    def finish_distribution(self):
        """Store metadata about distributed items."""
        for tmp_dir in (
            self._dist_download_dirs + self._dist_unzip_dirs
        ):
            if os.path.exists(tmp_dir):
                with suppress(Exception):
                    shutil.rmtree(tmp_dir)

        stored_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        # TODO store dependencies info inside dependencies folder instead
        #   of having one file
        # - the file can be used to track progress and find out if other
        #   process is already working on distribution
        dependency_dist_item = self.get_dependency_dist_item()
        if (
            dependency_dist_item is not None
            and dependency_dist_item.need_distribution
            and dependency_dist_item.state == UpdateState.UPDATED
        ):
            package = self.dependency_package_item
            source = dependency_dist_item.used_source
            if source is not None:
                data = {
                    "source": source,
                    "checksum": dependency_dist_item.checksum,
                    "checksum_algorithm": (
                        dependency_dist_item.checksum_algorithm),
                    "distributed_dt": stored_time
                }
                self.update_dependency_metadata(package.filename, data)

        # TODO store addon info inside addon folder instead of having one
        #   of having one file
        # - the file can be used to track progress and find out if other
        #   process is already working on distribution
        addons_info = {}
        for item in self.get_addon_dist_items():
            dist_item = item["dist_item"]
            if (
                not dist_item.need_distribution
                or dist_item.state != UpdateState.UPDATED
            ):
                continue

            source_data = dist_item.used_source
            if not source_data:
                continue

            addon_name = item["addon_name"]
            addon_version = item["addon_version"]
            addons_info.setdefault(addon_name, {})
            addons_info[addon_name][addon_version] = {
                "source": source_data,
                "checksum": dist_item.checksum,
                "checksum_algorithm": dist_item.checksum_algorithm,
                "distributed_dt": stored_time
            }

        self.update_addons_metadata(addons_info)

        _cleanup_dist_download_dirs()
        _cleanup_dist_expire_dirs(self._dist_addons_unzip_temp)
        _cleanup_dist_expire_dirs(self._dist_dep_packages_unzip_temp)

    def get_all_distribution_items(self) -> list[DistributionItem]:
        """Distribution items required by server.

        Items contain dependency package item and all addons that are enabled
        and have distribution requirements.

        Items can be already available on machine.

        Returns:
            list[DistributionItem]: Distribution items required by server.

        """
        output = [
            item["dist_item"]
            for item in self.get_addon_dist_items()
        ]
        dependency_dist_item = self.get_dependency_dist_item()
        if dependency_dist_item is not None:
            output.insert(0, dependency_dist_item)

        return output

    @property
    def need_distribution(self) -> bool:
        """Distribution is needed.

        Returns:
            bool: True if any distribution is needed.

        """
        if self.need_installer_change:
            if self.need_installer_distribution:
                return True
            return False

        for item in self.get_all_distribution_items():
            if item.need_distribution:
                return True
        return False

    @property
    def is_missing_permissions(self):
        # Do not validate installer (launcher) distribution as that is
        #   reported with '_installer_dist_error'
        for item in self.get_all_distribution_items():
            if item.need_distribution and item.is_missing_permissions:
                return True
        return False

    def distribute(self):
        """Distribute all missing items.

        Method will try to distribute all items that are required by server.

        This method does not handle failed items. To validate the result call
        'validate_distribution' when this method finishes.

        """
        if self._dist_started:
            raise RuntimeError("Distribution already started")
        self._dist_started = True

        if self.need_installer_change:
            if self.need_installer_distribution:
                self.distribute_installer()
            return

        dist_items = []
        for dist_item in self.get_all_distribution_items():
            if not dist_item.is_distributed():
                dist_items.append(dist_item)
                _create_dist_expire_file(dist_item.download_dirpath)

        running_items = collections.deque()
        for item in dist_items:
            running_items.append(item.distribute())

        if running_items:
            running_items.append(None)

        try:
            while running_items:
                running_item = running_items.popleft()
                if running_item is None:
                    if running_items:
                        running_items.append(None)
                        time.sleep(0.02)
                    continue

                if not next(running_item):
                    running_items.append(running_item)

        finally:
            self.finish_distribution()

    def validate_distribution(self):
        """Check if all required distribution items are distributed.

        Raises:
            RuntimeError: Any of items is not available.

        """
        invalid = []
        dependency_package = self.get_dependency_dist_item()
        if (
            dependency_package is not None
            and dependency_package.state != UpdateState.UPDATED
        ):
            invalid.append("Dependency package")

        for item in self.get_addon_dist_items():
            dist_item = item["dist_item"]
            if dist_item.state != UpdateState.UPDATED:
                invalid.append(item["addon_name"])

        if not invalid:
            return

        raise RuntimeError("Failed to distribute {}".format(
            ", ".join([f'"{item}"' for item in invalid])
        ))

    def get_sys_paths(self) -> list[str]:
        """Get all paths to python packages that should be added to path.

        These packages will be added only to 'sys.path' and not into
        'PYTHONPATH', so they won't be available in subprocesses.

        Todos:
            This is not yet implemented. The goal is that dependency
                package will contain also 'build' python
                dependencies (OpenTimelineIO, Pillow, etc.).

        Returns:
            list[str]: Paths that should be added to 'sys.path'.

        """
        output = []
        dependency_dist_item = self.get_dependency_dist_item()
        if dependency_dist_item is not None:
            runtime_dir = None
            target_dirpath = dependency_dist_item.target_dirpath
            if target_dirpath:
                runtime_dir = os.path.join(target_dirpath, "runtime")

            if runtime_dir and os.path.exists(runtime_dir):
                output.append(runtime_dir)
        return output

    def get_python_paths(self) -> list[str]:
        """Get all paths to python packages that should be added to python.

        These paths lead to addon directories and python dependencies in
        dependency package.

        Returns:
            List[str]: Paths that should be added to 'sys.path' and
                'PYTHONPATH'.

        """
        output = []
        for item in self.get_addon_dist_items():
            dist_item = item["dist_item"]
            if dist_item.state != UpdateState.UPDATED:
                continue
            target_dirpath = dist_item.target_dirpath
            if target_dirpath and os.path.exists(target_dirpath):
                output.append(target_dirpath)

        output.extend(self._get_dev_sys_paths())

        dependency_dist_item = self.get_dependency_dist_item()
        if dependency_dist_item is not None:
            dependencies_dir = None
            target_dirpath = dependency_dist_item.target_dirpath
            if target_dirpath:
                dependencies_dir = os.path.join(target_dirpath, "dependencies")

            if dependencies_dir and os.path.exists(dependencies_dir):
                output.append(dependencies_dir)
        return output

    def _get_dev_sys_paths(self) -> list[str]:
        output = []
        if not self.use_dev:
            return output

        addon_versions = {}
        dev_addons = {}
        bundle = self.project_bundle_to_use
        if bundle is not None:
            dev_addons = bundle.addons_dev_info
            addon_versions = bundle.addon_versions

        for addon_name, _ in self.addon_items.items():
            addon_version = addon_versions.get(addon_name)
            # Addon is not in bundle -> Skip
            if addon_version is None:
                continue

            dev_addon_info = dev_addons.get(addon_name)
            if dev_addon_info is not None and dev_addon_info.enabled:
                try:
                    output.append(
                        os.path.expandvars(dev_addon_info.path.format_map(os.environ))
                    )
                except (KeyError, ValueError):
                    msg = (
                        f"Failed to format path '{dev_addon_info.path}'"
                        f" for addon '{addon_name}'."
                    )
                    self.log.warning(msg)
                    raise RuntimeError(msg)

        return output

    def _prepare_bundles(self):
        studio_production_bundle = None
        studio_staging_bundle = None
        studio_dev_bundle = None
        for bundle in self.bundle_items:
            if bundle.is_project_bundle:
                continue

            if bundle.is_production:
                studio_production_bundle = bundle
            if bundle.is_staging:
                studio_staging_bundle = bundle
            if bundle.is_dev and bundle.active_dev_user == self.active_user:
                studio_dev_bundle = bundle

        self._studio_production_bundle = studio_production_bundle
        self._studio_staging_bundle = studio_staging_bundle
        self._studio_dev_bundle = studio_dev_bundle

    def _prepare_current_addon_dist_items(self) -> list[dict[str, Any]]:
        addons_metadata = self.get_addons_metadata()
        output = []
        addon_versions = {}
        dev_addons = {}
        bundle = self.project_bundle_to_use
        if bundle is not None:
            dev_addons = bundle.addons_dev_info
            addon_versions = bundle.addon_versions

        unzip_temp = os.path.join(self._addons_dirpath, ".unzip_temp")
        if not os.path.exists(unzip_temp):
            os.makedirs(unzip_temp, exist_ok=True)
            try:
                os.chmod(unzip_temp, 0o777)
                change_permissions_recursive(unzip_temp)
            except PermissionError:
                self.log.warning(
                    "Cannot change permissions for "
                    "addons unzip temp directory."
                )

        for addon_name, addon_item in self.addon_items.items():
            # Dev mode can redirect addon directory elsewhere
            if self.use_dev:
                dev_addon_info = dev_addons.get(addon_name)
                if dev_addon_info is not None and dev_addon_info.enabled:
                    continue

            addon_version = addon_versions.get(addon_name)
            # Addon is not in bundle -> Skip
            if addon_version is None:
                continue

            addon_version_item = addon_item.versions.get(addon_version)
            # Addon version is not available in addons info
            # - TODO handle this case (raise error, skip, store, report, ...)
            if addon_version_item is None:
                print(
                    f"Version '{addon_version}' of addon '{addon_name}'"
                    " is not available on server."
                )
                continue

            if not addon_version_item.require_distribution:
                continue
            full_name = addon_version_item.full_name
            addon_dest = os.path.join(self._addons_dirpath, full_name)
            self.log.debug(f"Checking {full_name} in {addon_dest}")
            progress_info = _read_progress_file(addon_dest)
            state = UpdateState.OUTDATED
            if progress_info:
                if progress_info.get("state") == DistFileStates.done.value:
                    state = UpdateState.UPDATED
            else:
                addon_in_metadata = (
                    addon_name in addons_metadata
                    and addon_version_item.version in (
                        addons_metadata[addon_name]
                    )
                )
                if addon_in_metadata and os.path.isdir(addon_dest):
                    self.log.debug(
                        f"Addon version folder {addon_dest} already exists."
                    )
                    state = UpdateState.UPDATED
                    # Auto-create addons dist file extracted with old versions
                    _create_progress_file(
                        addon_dest,
                        uuid.uuid4().hex,
                        addon_version_item.checksum,
                        addon_version_item.checksum_algorithm,
                    )

            download_dir = _get_dist_download_dir(uuid.uuid4().hex)
            unzip_dir = os.path.join(unzip_temp, uuid.uuid4().hex)
            self._dist_download_dirs.append(download_dir)
            self._dist_unzip_dirs.append(unzip_dir)
            downloader_data = {
                "type": "addon",
                "name": addon_name,
                "version": addon_version
            }
            dist_item = DistributionItem(
                addon_dest,
                unzip_dir,
                download_dirpath=download_dir,
                state=state,
                checksum=addon_version_item.checksum,
                checksum_algorithm=addon_version_item.checksum_algorithm,
                factory=self._dist_factory,
                sources=list(addon_version_item.sources),
                downloader_data=downloader_data,
                item_label=full_name,
                progress_dir=addon_dest,
                logger=self.log
            )
            output.append({
                "dist_item": dist_item,
                "addon_name": addon_name,
                "addon_version": addon_version,
                "addon_item": addon_item,
                "addon_version_item": addon_version_item,
            })
        return output

    def _prepare_dependency_progress(self) -> Optional[DistributionItem]:
        package = self.dependency_package_item
        if package is None:
            return None

        metadata = self.get_dependency_metadata()
        downloader_data = {
            "type": "dependency_package",
            "name": package.filename,
            "platform": package.platform_name
        }
        package_dir = os.path.join(
            self._dependency_dirpath, package.filename
        )
        # Future compatibility for dependency packages without .zip in dirname
        new_basename = os.path.splitext(package.filename)[0]
        new_package_dir = os.path.join(self._dependency_dirpath, new_basename)

        download_dir = _get_dist_download_dir(uuid.uuid4().hex)
        unzip_dir = os.path.join(self._dependency_dirpath, uuid.uuid4().hex)
        self._dist_download_dirs.append(download_dir)
        self._dist_unzip_dirs.append(unzip_dir)

        self.log.debug(f"Checking {package.filename} in {package_dir}")
        state = UpdateState.OUTDATED
        progress_info = _read_progress_file(package_dir)
        new_progress_info = _read_progress_file(new_package_dir)
        if progress_info:
            if progress_info.get("state") == DistFileStates.done.value:
                state = UpdateState.UPDATED

        elif new_progress_info:
            if new_progress_info.get("state") == DistFileStates.done.value:
                state = UpdateState.UPDATED
                package_dir = new_package_dir

        elif (
            os.path.isdir(package_dir)
            and package.filename in metadata
        ):
            state = UpdateState.UPDATED
            # Autofix dependency packages extracted with old versions
            _create_progress_file(
                package_dir,
                uuid.uuid4().hex,
                package.checksum,
                package.checksum_algorithm,
            )

        return DistributionItem(
            package_dir,
            unzip_dir,
            download_dirpath=download_dir,
            state=state,
            checksum=package.checksum,
            checksum_algorithm=package.checksum_algorithm,
            factory=self._dist_factory,
            sources=package.sources,
            downloader_data=downloader_data,
            item_label=os.path.splitext(package.filename)[0],
            progress_dir=package_dir,
            logger=self.log,
        )

    def _get_project_bundle(self) -> Optional[Bundle]:
        if self._project_bundle is not NOT_SET:
            return self._project_bundle

        if self.studio_bundle_to_use is None:
            self._project_bundle = None
            return None

        # Project bundle is set and is same as studio bundle
        studio_bundle_name = self.studio_bundle_to_use.name
        if self._project_bundle_name == studio_bundle_name:
            self._project_bundle = None
            return None

        if (
            not self._project_bundle_name
            and self._project_name is not NOT_SET
        ):
            project = ayon_api.get_project(self._project_name)
            project_bundles = project["data"].get("bundle", {})
            bundle_name = None
            if self.use_staging:
                bundle_name = project_bundles.get("staging")
            elif not self.use_dev:
                bundle_name = project_bundles.get("production")

            if bundle_name:
                self._project_bundle_name = bundle_name

        if not self._project_bundle_name:
            self._project_bundle = None
            return None

        bundle = next(
            (
                bundle
                for bundle in self.bundle_items
                if bundle.name == self._project_bundle_name
            ),
            None
        )
        if bundle is None:
            raise BundleNotFoundError(self._project_bundle_name)

        key_values = {
            "summary": "true",
            "bundle_name": studio_bundle_name,
            "project_bundle_name": self._project_bundle_name,
        }
        query = urlencode(key_values)

        response = ayon_api.get(f"settings?{query}")
        # NOTE This does modify the bundle data
        # - should be fine as it really does fill up the project bundle
        bundle.addon_versions = {
            addon["name"]: addon["version"]
            for addon in response.data["addons"]
        }

        self._project_bundle = bundle
        return bundle

addon_items property

Information about available addons on server.

Addons may require distribution of files. For those addons will be created 'DistributionItem' handling distribution itself.

Returns:

Type Description
dict[str, AddonInfo]

dict[str, AddonInfo]: Addon info object by addon name.

addons_info property

Server information about available addons.

Returns:

Type Description
dict[str, dict[str, Any]]

dict[str, dict[str, Any]]: Addon info by addon name.

bundle_items property

Returns:

Type Description
list[Bundle]

list[Bundle]: List of bundles info.

bundles_info property

Returns:

Type Description
list[dict[str, Any]]

list[dict[str, Any]]: Bundles information from server.

dependency_package_item property

Dependency package item that should be used by bundle.

Returns:

Type Description
Optional[DependencyItem]

Optional[DependencyItem]: None if bundle does not have specified dependency package.

dependency_packages_info property

Server information about available dependency packages.

Notes

For testing purposes it is possible to pass dependency packages information to 'init'.

Returns:

Type Description
list[dict[str, Any]]

list[dict[str, Any]]: Dependency packages information.

dependency_packages_items property

Dependency packages as objects.

Returns:

Type Description
dict[str, DependencyItem]

dict[str, DependencyItem]: Dependency packages as objects by name.

expected_installer_version property

Excepted installer version.

Returns:

Type Description
Optional[str]

Optional[str]: Expected installer version or None defined by bundle that should be used.

installer_dist_error property

Installer distribution error message.

Returns:

Type Description
Optional[str]

Optional[str]: Error that happened during installer distribution.

installer_executable property

Path to installer executable that should be used.

Notes

The 'installer_executable' is maybe confusing naming. It might be called 'ayon_executable'?

Returns:

Type Description
Optional[str]

Optional[str]: Path to installer executable that should be used. None if executable is not found and must be distributed or bundle does not have defined an installer to use.

installer_filepath property

Path to a distribution package/installer.

This can be used as reference for user where to find downloaded installer on disk and distribute it manually.

Returns:

Type Description
Optional[str]

Optional[str]: Path to installer.

installer_item property

Installer item that should be used for distribution.

Returns:

Type Description

Union[Installer, None]: Installer information item.

installer_items property

Installers as objects.

Returns:

Type Description
list[Installer]

list[Installer]: List of installers info from server.

installers_info property

Installers information from server.

Returns:

Type Description
list[dict[str, Any]]

list[dict[str, Any]]: Installers information from server.

log property

Helper to access logger.

Returns:

Type Description
Logger

logging.Logger: Logger instance.

need_distribution property

Distribution is needed.

Returns:

Name Type Description
bool bool

True if any distribution is needed.

need_installer_change property

Installer should be changed.

Current installer is using different version than what is expected by bundle.

Returns:

Name Type Description
bool bool

True if installer should be changed.

need_installer_distribution property

Installer distribution is needed.

Todos

Add option to skip if running from code?

Returns:

Name Type Description
bool bool

True if installer distribution is needed.

project_bundle_name_to_use property

Name of bundle that will be used for distribution.

Returns:

Type Description
Optional[str]

Optional[str]: Name of bundle that will be used for distribution.

project_bundle_to_use property

Bundle that will be used for distribution.

Bundle that should be used can be affected by 'project_bundle_name', 'project_name', 'studio_bundle_name' or 'use_staging'.

Returns:

Type Description
Optional[Bundle]

Optional[Bundle]: Bundle that will be used for distribution or None.

Raises:

Type Description
BundleNotFoundError

When bundle name to use is defined but is not available on server.

studio_bundle_to_use property

Returns:

Type Description
Optional[Bundle]

Optional[Bundle]: Bundle that should be used in distribution.

studio_dev_bundle property

Returns:

Type Description
Optional[Bundle]

Optional[Bundle]: Bundle that should be used in dev.

studio_production_bundle property

Returns:

Type Description
Optional[Bundle]

Optional[Bundle]: Bundle that should be used in production.

studio_staging_bundle property

Returns:

Type Description
Optional[Bundle]

Optional[Bundle]: Bundle that should be used in staging.

use_dev property

Develop version of a bundle should be used.

This value is completely ignored if specific bundle name should be used.

Returns:

Name Type Description
bool bool

True if staging version should be used.

use_staging property

Staging version of a bundle should be used.

This value is completely ignored if specific bundle name should be used.

Returns:

Name Type Description
bool bool

True if staging version should be used.

distribute()

Distribute all missing items.

Method will try to distribute all items that are required by server.

This method does not handle failed items. To validate the result call 'validate_distribution' when this method finishes.

Source code in common/ayon_common/distribution/control.py
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
def distribute(self):
    """Distribute all missing items.

    Method will try to distribute all items that are required by server.

    This method does not handle failed items. To validate the result call
    'validate_distribution' when this method finishes.

    """
    if self._dist_started:
        raise RuntimeError("Distribution already started")
    self._dist_started = True

    if self.need_installer_change:
        if self.need_installer_distribution:
            self.distribute_installer()
        return

    dist_items = []
    for dist_item in self.get_all_distribution_items():
        if not dist_item.is_distributed():
            dist_items.append(dist_item)
            _create_dist_expire_file(dist_item.download_dirpath)

    running_items = collections.deque()
    for item in dist_items:
        running_items.append(item.distribute())

    if running_items:
        running_items.append(None)

    try:
        while running_items:
            running_item = running_items.popleft()
            if running_item is None:
                if running_items:
                    running_items.append(None)
                    time.sleep(0.02)
                continue

            if not next(running_item):
                running_items.append(running_item)

    finally:
        self.finish_distribution()

distribute_installer()

Distribute installer.

Source code in common/ayon_common/distribution/control.py
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
def distribute_installer(self):
    """Distribute installer."""

    installer_item = self.installer_item
    if installer_item is None:
        self._installer_executable = None
        self._installer_dist_error = (
            f"Bundle '{self.project_bundle_name_to_use}'"
            " does not have set installer version to use."
        )
        return

    downloader_data = {
        "type": "installer",
        "version": installer_item.version,
        "filename": installer_item.filename,
    }

    tmp_used = False
    downloads_dir = get_downloads_dir()
    if not downloads_dir or not os.path.exists(downloads_dir):
        tmp_used = True
        downloads_dir = tempfile.mkdtemp(prefix="ayon_installer")
        change_permissions_recursive(downloads_dir)

    dist_item = None
    try:
        dist_item = InstallerDistributionItem(
            tmp_used,
            downloads_dir,
            UpdateState.OUTDATED,
            installer_item.checksum,
            installer_item.checksum_algorithm,
            self._dist_factory,
            list(installer_item.sources),
            downloader_data,
            f"Installer {installer_item.version}",
        )

        if (
            platform.system().lower() != "windows"
            and dist_item.is_missing_permissions
        ):
            self._installer_dist_error = (
                "Your user does not have required permissions to update"
                " AYON launcher."
                " Please contact your administrator, or use user"
                " with permissions."
            )
            return

        for result in dist_item.distribute():
            if result:
                break

        self._installer_executable = dist_item.executable
        if dist_item.installer_error is not None:
            self._installer_dist_error = dist_item.installer_error

        elif dist_item.state == UpdateState.MISS_SOURCE_FILES:
            self._installer_dist_error = (
                "Couldn't find valid installer source for required"
                f" AYON launcher version {installer_item.version}."
            )

        elif not self._installer_executable:
            self._installer_dist_error = (
                "Couldn't find installed AYON launcher."
                " Please try to launch AYON manually."
            )

    except Exception:
        self.log.warning(
            "Installer distribution failed do to unknown reasons.",
            exc_info=True
        )
        self._installer_dist_error = (
            f"Distribution of AYON launcher {installer_item.version}"
            " failed with unexpected reason."
        )

    finally:
        if dist_item is not None:
            self._installer_filepath = dist_item.installer_path

        if tmp_used and os.path.exists(downloads_dir):
            shutil.rmtree(downloads_dir)

finish_distribution()

Store metadata about distributed items.

Source code in common/ayon_common/distribution/control.py
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
def finish_distribution(self):
    """Store metadata about distributed items."""
    for tmp_dir in (
        self._dist_download_dirs + self._dist_unzip_dirs
    ):
        if os.path.exists(tmp_dir):
            with suppress(Exception):
                shutil.rmtree(tmp_dir)

    stored_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # TODO store dependencies info inside dependencies folder instead
    #   of having one file
    # - the file can be used to track progress and find out if other
    #   process is already working on distribution
    dependency_dist_item = self.get_dependency_dist_item()
    if (
        dependency_dist_item is not None
        and dependency_dist_item.need_distribution
        and dependency_dist_item.state == UpdateState.UPDATED
    ):
        package = self.dependency_package_item
        source = dependency_dist_item.used_source
        if source is not None:
            data = {
                "source": source,
                "checksum": dependency_dist_item.checksum,
                "checksum_algorithm": (
                    dependency_dist_item.checksum_algorithm),
                "distributed_dt": stored_time
            }
            self.update_dependency_metadata(package.filename, data)

    # TODO store addon info inside addon folder instead of having one
    #   of having one file
    # - the file can be used to track progress and find out if other
    #   process is already working on distribution
    addons_info = {}
    for item in self.get_addon_dist_items():
        dist_item = item["dist_item"]
        if (
            not dist_item.need_distribution
            or dist_item.state != UpdateState.UPDATED
        ):
            continue

        source_data = dist_item.used_source
        if not source_data:
            continue

        addon_name = item["addon_name"]
        addon_version = item["addon_version"]
        addons_info.setdefault(addon_name, {})
        addons_info[addon_name][addon_version] = {
            "source": source_data,
            "checksum": dist_item.checksum,
            "checksum_algorithm": dist_item.checksum_algorithm,
            "distributed_dt": stored_time
        }

    self.update_addons_metadata(addons_info)

    _cleanup_dist_download_dirs()
    _cleanup_dist_expire_dirs(self._dist_addons_unzip_temp)
    _cleanup_dist_expire_dirs(self._dist_dep_packages_unzip_temp)

get_addon_dist_items()

Addon distribution items.

These items describe source files required by addon to be available on machine. Each item may have 0-n source information from where can be obtained. If file is already available it's state will be 'UPDATED'.

Example output

[ { "dist_item": DistributionItem, "addon_name": str, "addon_version": str, "addon_item": AddonInfo, "addon_version_item": AddonVersionInfo }, { ... } ]

Returns:

Type Description
list[dict[str, Any]]

list[dict[str, Any]]: Distribution items with addon version item.

Source code in common/ayon_common/distribution/control.py
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
def get_addon_dist_items(self) -> list[dict[str, Any]]:
    """Addon distribution items.

    These items describe source files required by addon to be available on
    machine. Each item may have 0-n source information from where can be
    obtained. If file is already available it's state will be 'UPDATED'.

    Example output:
        [
            {
                "dist_item": DistributionItem,
                "addon_name": str,
                "addon_version": str,
                "addon_item": AddonInfo,
                "addon_version_item": AddonVersionInfo
            }, {
                ...
            }
        ]

    Returns:
         list[dict[str, Any]]: Distribution items with addon version item.

    """
    if self._addon_dist_items is NOT_SET:
        self._addon_dist_items = (
            self._prepare_current_addon_dist_items())
    return self._addon_dist_items

get_addons_metadata_filepath()

Path to addons metadata file.

Metadata contain information about distributed addons, used sources, expected file hashes and time when files were distributed.

Returns:

Name Type Description
str str

Path to a file where addons metadata are stored.

Source code in common/ayon_common/distribution/control.py
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
def get_addons_metadata_filepath(self) -> str:
    """Path to addons metadata file.

    Metadata contain information about distributed addons, used sources,
    expected file hashes and time when files were distributed.

    Returns:
        str: Path to a file where addons metadata are stored.

    """
    return os.path.join(self._addons_dirpath, "addons.json")

get_all_distribution_items()

Distribution items required by server.

Items contain dependency package item and all addons that are enabled and have distribution requirements.

Items can be already available on machine.

Returns:

Type Description
list[DistributionItem]

list[DistributionItem]: Distribution items required by server.

Source code in common/ayon_common/distribution/control.py
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
def get_all_distribution_items(self) -> list[DistributionItem]:
    """Distribution items required by server.

    Items contain dependency package item and all addons that are enabled
    and have distribution requirements.

    Items can be already available on machine.

    Returns:
        list[DistributionItem]: Distribution items required by server.

    """
    output = [
        item["dist_item"]
        for item in self.get_addon_dist_items()
    ]
    dependency_dist_item = self.get_dependency_dist_item()
    if dependency_dist_item is not None:
        output.insert(0, dependency_dist_item)

    return output

get_dependency_dist_item()

Dependency package distribution item.

Item describe source files required by server to be available on machine. Item may have 0-n source information from where can be obtained. If file is already available it's state will be 'UPDATED'.

'None' is returned if server does not have defined any dependency package.

Returns:

Type Description
Optional[DistributionItem]

Optional[DistributionItem]: Dependency item or None if server does not have specified any dependency package.

Source code in common/ayon_common/distribution/control.py
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
def get_dependency_dist_item(self) -> Optional[DistributionItem]:
    """Dependency package distribution item.

    Item describe source files required by server to be available on
    machine. Item may have 0-n source information from where can be
    obtained. If file is already available it's state will be 'UPDATED'.

    'None' is returned if server does not have defined any dependency
    package.

    Returns:
        Optional[DistributionItem]: Dependency item or None if server
            does not have specified any dependency package.

    """
    if self._dependency_dist_item is NOT_SET:
        self._dependency_dist_item = self._prepare_dependency_progress()
    return self._dependency_dist_item

get_dependency_metadata_filepath()

Path to distribution metadata file.

Metadata contain information about distributed packages, used source, expected file hash and time when file was distributed.

Returns:

Name Type Description
str str

Path to a file where dependency package metadata are stored.

Source code in common/ayon_common/distribution/control.py
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
def get_dependency_metadata_filepath(self) -> str:
    """Path to distribution metadata file.

    Metadata contain information about distributed packages, used source,
    expected file hash and time when file was distributed.

    Returns:
        str: Path to a file where dependency package metadata are stored.

    """
    return os.path.join(self._dependency_dirpath, "dependency.json")

get_python_paths()

Get all paths to python packages that should be added to python.

These paths lead to addon directories and python dependencies in dependency package.

Returns:

Type Description
list[str]

List[str]: Paths that should be added to 'sys.path' and 'PYTHONPATH'.

Source code in common/ayon_common/distribution/control.py
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
def get_python_paths(self) -> list[str]:
    """Get all paths to python packages that should be added to python.

    These paths lead to addon directories and python dependencies in
    dependency package.

    Returns:
        List[str]: Paths that should be added to 'sys.path' and
            'PYTHONPATH'.

    """
    output = []
    for item in self.get_addon_dist_items():
        dist_item = item["dist_item"]
        if dist_item.state != UpdateState.UPDATED:
            continue
        target_dirpath = dist_item.target_dirpath
        if target_dirpath and os.path.exists(target_dirpath):
            output.append(target_dirpath)

    output.extend(self._get_dev_sys_paths())

    dependency_dist_item = self.get_dependency_dist_item()
    if dependency_dist_item is not None:
        dependencies_dir = None
        target_dirpath = dependency_dist_item.target_dirpath
        if target_dirpath:
            dependencies_dir = os.path.join(target_dirpath, "dependencies")

        if dependencies_dir and os.path.exists(dependencies_dir):
            output.append(dependencies_dir)
    return output

get_sys_paths()

Get all paths to python packages that should be added to path.

These packages will be added only to 'sys.path' and not into 'PYTHONPATH', so they won't be available in subprocesses.

Todos

This is not yet implemented. The goal is that dependency package will contain also 'build' python dependencies (OpenTimelineIO, Pillow, etc.).

Returns:

Type Description
list[str]

list[str]: Paths that should be added to 'sys.path'.

Source code in common/ayon_common/distribution/control.py
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
def get_sys_paths(self) -> list[str]:
    """Get all paths to python packages that should be added to path.

    These packages will be added only to 'sys.path' and not into
    'PYTHONPATH', so they won't be available in subprocesses.

    Todos:
        This is not yet implemented. The goal is that dependency
            package will contain also 'build' python
            dependencies (OpenTimelineIO, Pillow, etc.).

    Returns:
        list[str]: Paths that should be added to 'sys.path'.

    """
    output = []
    dependency_dist_item = self.get_dependency_dist_item()
    if dependency_dist_item is not None:
        runtime_dir = None
        target_dirpath = dependency_dist_item.target_dirpath
        if target_dirpath:
            runtime_dir = os.path.join(target_dirpath, "runtime")

        if runtime_dir and os.path.exists(runtime_dir):
            output.append(runtime_dir)
    return output

read_metadata_file(filepath, default_value=None) staticmethod

Read json file from path.

Method creates the file when does not exist with default value.

Parameters:

Name Type Description Default
filepath str

Path to json file.

required
default_value Union[Dict[str, Any], List[Any], None]

Default value if the file is not available (or valid).

None

Returns:

Type Description
dict[str, Any]

Union[Dict[str, Any], List[Any]]: Value from file.

Source code in common/ayon_common/distribution/control.py
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
@staticmethod
def read_metadata_file(
    filepath: str,
    default_value: Optional[Any] = None,
) -> dict[str, Any]:
    """Read json file from path.

    Method creates the file when does not exist with default value.

    Args:
        filepath (str): Path to json file.
        default_value (Union[Dict[str, Any], List[Any], None]): Default
            value if the file is not available (or valid).

    Returns:
        Union[Dict[str, Any], List[Any]]: Value from file.
    """

    if default_value is None:
        default_value = {}

    if not os.path.exists(filepath):
        return default_value

    try:
        with open(filepath, "r") as stream:
            data = json.load(stream)
    except ValueError:
        data = default_value
    return data

save_metadata_file(filepath, data) staticmethod

Store data to json file.

Method creates the file when does not exist.

Parameters:

Name Type Description Default
filepath str

Path to json file.

required
data dict[str, Any]

Data to store into file.

required
Source code in common/ayon_common/distribution/control.py
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
@staticmethod
def save_metadata_file(filepath: str, data: dict[str, Any]):
    """Store data to json file.

    Method creates the file when does not exist.

    Args:
        filepath (str): Path to json file.
        data (dict[str, Any]): Data to store into file.

    """
    dirpath = os.path.dirname(filepath)
    os.makedirs(dirpath, exist_ok=True)
    try:
        os.chmod(dirpath, 0o777)
    except PermissionError:
        print(f"Failed to change permissions for {dirpath}.")
    with open(filepath, "w") as stream:
        json.dump(data, stream, indent=4)

    change_permissions_recursive(dirpath)

validate_distribution()

Check if all required distribution items are distributed.

Raises:

Type Description
RuntimeError

Any of items is not available.

Source code in common/ayon_common/distribution/control.py
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
def validate_distribution(self):
    """Check if all required distribution items are distributed.

    Raises:
        RuntimeError: Any of items is not available.

    """
    invalid = []
    dependency_package = self.get_dependency_dist_item()
    if (
        dependency_package is not None
        and dependency_package.state != UpdateState.UPDATED
    ):
        invalid.append("Dependency package")

    for item in self.get_addon_dist_items():
        dist_item = item["dist_item"]
        if dist_item.state != UpdateState.UPDATED:
            invalid.append(item["addon_name"])

    if not invalid:
        return

    raise RuntimeError("Failed to distribute {}".format(
        ", ".join([f'"{item}"' for item in invalid])
    ))

BaseDistributionItem

Bases: ABC

Distribution item with sources and target directories.

Distribution item can be an installer, addon or dependency package. Distribution item can be already distributed and don't need any progression. The item keeps track of the progress. The reason is to be able to use the distribution items as source data for UI without implementing the same logic.

Distribution is "state" based. Distribution can be 'UPDATED' or 'OUTDATED' at the initialization. If item is 'UPDATED' the distribution is skipped and 'OUTDATED' will trigger the distribution process.

Because the distribution may have multiple sources each source has own progress item.

Parameters:

Name Type Description Default
download_dirpath str

Path to directory where file is unzipped.

required
state UpdateState

Initial state (UpdateState.UPDATED or UpdateState.OUTDATED).

required
checksum Optional[str]

Hash of file for validation.

required
checksum_algorithm Optional[str]

Algorithm used to generate the hash.

required
factory DownloadFactory

Downloaders factory object.

required
sources List[SourceInfo]

Possible sources to receive the distribution item.

required
downloader_data Dict[str, Any]

More information for downloaders.

required
item_label str

Label used in log outputs (and in UI).

required
progress_dir Optional[str]

Directory where progress is stored for other processes.

None
logger Optional[Logger]

Logger object.

None
change_permissions bool

Change permissions of download directory.

True
Source code in common/ayon_common/distribution/control.py
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
class BaseDistributionItem(ABC):
    """Distribution item with sources and target directories.

    Distribution item can be an installer, addon or dependency package.
    Distribution item can be already distributed and don't need any
    progression. The item keeps track of the progress. The reason is to be
    able to use the distribution items as source data for UI without
    implementing the same logic.

    Distribution is "state" based. Distribution can be 'UPDATED' or 'OUTDATED'
    at the initialization. If item is 'UPDATED' the distribution is skipped
    and 'OUTDATED' will trigger the distribution process.

    Because the distribution may have multiple sources each source has own
    progress item.

    Args:
        download_dirpath (str): Path to directory where file is unzipped.
        state (UpdateState): Initial state (UpdateState.UPDATED or
            UpdateState.OUTDATED).
        checksum (Optional[str]): Hash of file for validation.
        checksum_algorithm (Optional[str]): Algorithm used to generate the hash.
        factory (DownloadFactory): Downloaders factory object.
        sources (List[SourceInfo]): Possible sources to receive the
            distribution item.
        downloader_data (Dict[str, Any]): More information for downloaders.
        item_label (str): Label used in log outputs (and in UI).
        progress_dir (Optional[str]): Directory where progress is stored for
            other processes.
        logger (Optional[logging.Logger]): Logger object.
        change_permissions (bool): Change permissions of download directory.

    """
    def __init__(
        self,
        download_dirpath: str,
        state: UpdateState,
        checksum: Optional[str],
        checksum_algorithm: Optional[str],
        factory: DownloadFactory,
        sources: list[SourceInfo],
        downloader_data: dict[str, Any],
        item_label: str,
        progress_dir: Optional[str] = None,
        logger: Optional[logging.Logger] = None,
        change_permissions: bool = True,
    ):
        if logger is None:
            logger = logging.getLogger(self.__class__.__name__)
        self.log: logging.Logger = logger
        self.state: UpdateState = state
        self.download_dirpath: str = download_dirpath
        self.checksum: Optional[str] = checksum
        self.checksum_algorithm: Optional[str] = checksum_algorithm
        self.factory: DownloadFactory = factory
        self.sources = self._prepare_sources(sources)
        self.downloader_data: dict[str, Any] = downloader_data
        self.item_label: str = item_label
        self._change_permissions = change_permissions

        self._need_distribution = state != UpdateState.UPDATED
        self._current_source_progress = None
        self._used_source_progress = None
        self._used_source = None
        self._dist_started = False

        self._progress_id = uuid.uuid4().hex
        self._progress_dir = progress_dir

        self._error_msg = None
        self._error_detail = None

    @staticmethod
    def _prepare_sources(sources: list[SourceInfo]):
        return [
            (source, DistributeTransferProgress())
            for source in sources
        ]

    @property
    def need_distribution(self) -> bool:
        """Need distribution based on initial state.

        Returns:
            bool: Need distribution.

        """
        return self._need_distribution

    @property
    def current_source_progress(self) -> Optional[DistributeTransferProgress]:
        """Currently processed source progress object.

        Returns:
            Optional[DistributeTransferProgress]: Transfer progress or None.

        """
        return self._current_source_progress

    @property
    def used_source_progress(self) -> Optional[DistributeTransferProgress]:
        """Transfer progress that successfully distributed the item.

        Returns:
            Optional[DistributeTransferProgress]: Transfer progress or None.

        """
        return self._used_source_progress

    @property
    def used_source(self) -> Optional[dict[str, Any]]:
        """Data of source item.

        Returns:
            Optional[dict[str, Any]]: SourceInfo data or None.

        """
        return self._used_source

    @property
    def error_message(self) -> Optional[str]:
        """Reason why distribution item failed.

        Returns:
            Optional[str]: Error message.
        """

        return self._error_msg

    @property
    def error_detail(self) -> Optional[str]:
        """Detailed reason why distribution item failed.

        Returns:
            Optional[str]: Detailed information (maybe traceback).
        """

        return self._error_detail

    @property
    @abstractmethod
    def is_missing_permissions(self) -> bool:
        pass

    def _pre_source_process(self):
        if not os.path.exists(self.download_dirpath):
            os.makedirs(self.download_dirpath, exist_ok=True)
            try:
                os.chmod(self.download_dirpath, 0o777)
            except PermissionError:
                self.log.warning(
                    f"{self.item_label}: Permission denied for"
                    f" {self.download_dirpath}"
                )

        if self._change_permissions:
            change_permissions_recursive(self.download_dirpath)

    def _receive_file(
        self,
        source_data: dict[str, Any],
        source_progress: DistributeTransferProgress,
        downloader: SourceDownloader,
    ) -> Optional[str]:
        """Receive source filepath using source data and downloader.

        Args:
            source_data (dict[str, Any]): Source information.
            source_progress (DistributeTransferProgress): Object where to
                track process of a source.
            downloader (SourceDownloader): Downloader object which should care
                about receiving file from source.

        Returns:
            Optional[str]: Filepath to received file from source.

        """
        download_dirpath = self.download_dirpath

        try:
            filepath = downloader.download(
                source_data,
                download_dirpath,
                self.downloader_data,
                source_progress.transfer_progress,
            )
        except Exception:
            message = "Failed to download source"
            source_progress.set_failed(message)
            self.log.warning(
                f"{self.item_label}: {message}",
                exc_info=True
            )
            return None

        source_progress.set_hash_check_started()
        try:
            # WARNING This condition was added because addons don't have
            #   information about checksum at the moment.
            # TODO remove once addon can supply checksum.
            if self.checksum:
                downloader.check_hash(
                    filepath, self.checksum, self.checksum_algorithm
                )
            else:
                # Fill checksum automatically based on downloaded file
                # - still better than nothing
                if not self.checksum_algorithm:
                    self.checksum_algorithm = "sha256"
                self.checksum = calculate_file_checksum(
                    filepath, self.checksum_algorithm
                )

        except Exception:
            message = "File hash does not match"
            source_progress.set_failed(message)
            self.log.warning(
                f"{self.item_label}: {message}",
                exc_info=True
            )
            return None
        source_progress.set_hash_check_finished()
        return filepath

    def _post_source_process(
        self,
        filepath: str,
        source_data: dict[str, Any],
        source_progress: DistributeTransferProgress,
        downloader: SourceDownloader,
    ) -> Generator[Optional[bool], None, None]:
        """Process source after it is downloaded and validated.

        Override this method if downloaded file needs more logic to do, like
            extraction.

        This part will mark source as updated and will trigger cleanup of
        source files via downloader (e.g. to remove downloaded file).

        Args:
            filepath (str): Path to a downloaded source.
            source_data (dict[str, Any]): Source information data.
            source_progress (DistributeTransferProgress): Source progress.
            downloader (SourceDownloader): Object which cared about download
                of file.

        Returns:
            Generator[Optional[bool], None, None]: Post processing finished
                in a way that it is not needed to process other possible
                sources. Does not mean that it was successful. If yields None
                then is still working.

        """
        if filepath:
            self.state = UpdateState.UPDATED
            self._used_source = source_data

        downloader.cleanup(
            source_data,
            self.download_dirpath,
            self.downloader_data
        )
        yield bool(filepath)

    def _process_source(
        self,
        source: SourceInfo,
        source_progress: DistributeTransferProgress,
    ) -> Generator[Optional[bool], None, None]:
        """Process single source item.

        Cares about download, validate and process source.

        Args:
            source (SourceInfo): Source information.
            source_progress (DistributeTransferProgress): Object to keep track
                about process of a source.

        Returns:
            Generator[Optional[bool], None, None]: Source was processed so
                any other sources can be skipped. Does not have to be
                successfull. Is still working if yields None.

        """
        self._current_source_progress = source_progress
        source_progress.set_started()

        self._pre_source_process()
        try:
            downloader = self.factory.get_downloader(source.type)
        except Exception:
            message = f"Unknown downloader {source.type}"
            source_progress.set_failed(message)
            self.log.warning(message, exc_info=True)
            yield False
            return

        try:
            source_data = dataclasses.asdict(source)
            filepath = self._receive_file(
                source_data,
                source_progress,
                downloader
            )

            yield from self._post_source_process(
                filepath, source_data, source_progress, downloader
            )

        except Exception:
            message = "Failed to process source"
            source_progress.set_failed(message)
            self.log.warning(
                f"{self.item_label}: {message}",
                exc_info=True
            )
            yield False

    def _set_progress_state(self, state: DistFileStates):
        if not self._progress_dir:
            return

        progress_info = _read_progress_file(self._progress_dir)
        if progress_info.get("progress_id") != self._progress_id:
            # Ignore if wanted to set 'failed' state
            if state == DistFileStates.failed:
                return
            raise DistributionProgressInterupted(
                "Different process took over progress file."
            )

        progress_info["state"] = state.value
        if state == DistFileStates.done:
            # Update checksum if it was not set from server information
            if not progress_info["checksum"] and self.checksum:
                progress_info["checksum"] = self.checksum
                progress_info["checksum_algorithm"] = self.checksum_algorithm
            progress_info["dist_finished"] = (
                datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            )

        _store_progress_file(self._progress_dir, progress_info)

    def _distribute(self) -> Generator[bool, None, None]:
        if not self.sources:
            message = (
                f"{self.item_label}: Don't have"
                " any sources to download from."
            )
            self.log.error(message)
            self._error_msg = message
            self.state = UpdateState.MISS_SOURCE_FILES
            yield True
            return

        # Progress file
        # - Check if other process/machine already started the job
        if self._progress_dir:
            result = False
            for result in _wait_for_other_process(
                self._progress_dir,
                self._progress_id,
                self.log
            ):
                if result is not None:
                    # Give other distribution items option to start waiting
                    #   cycle
                    yield False
                    break
                yield False

            if result is True:
                self.state = UpdateState.UPDATED
                self.log.info(f"{self.item_label}: Already distributed")
                yield True
                return

            _create_progress_file(
                self._progress_dir,
                self._progress_id,
                self.checksum,
                self.checksum_algorithm,
            )

        # Download
        for source, source_progress in self.sources:
            yield False
            result = False
            for result in self._process_source(source, source_progress):
                if result is not None:
                    break

            if result:
                break

        last_progress = self._current_source_progress
        self._current_source_progress = None
        if self.state == UpdateState.UPDATED:
            self._set_progress_state(DistFileStates.done)
            self._used_source_progress = last_progress
            self.log.info(f"{self.item_label}: Distributed")
        else:
            self._set_progress_state(DistFileStates.failed)
            self.log.error(f"{self.item_label}: Failed to distribute")
            self._error_msg = "Failed to receive or install source files"
        yield True

    def _post_distribute(self):
        pass

    def is_distributed(self):
        if not self.need_distribution:
            return True
        return self.state == UpdateState.UPDATED

    def distribute(self) -> Generator[bool, None, None]:
        """Execute distribution logic."""
        if self.is_distributed() or self._dist_started:
            yield True
            return

        self._dist_started = True
        try:
            try:
                for result in self._distribute():
                    if result:
                        break
                    yield False

            except DistributionProgressInterupted:
                wait_result = False
                for wait_result in _wait_for_other_process(
                    self._progress_dir, self._progress_id, self.log
                ):
                    if wait_result is not None:
                        break
                    yield False

                if wait_result:
                    self.state = UpdateState.UPDATED
                else:
                    self.state = UpdateState.UPDATE_FAILED
                    self._error_msg = (
                        "Other process took over distribution and failed."
                    )
                    self._error_detail = (
                        "Please try to start AYON again and contact"
                        " administrator if issue persist."
                    )
                    self.log.error(
                        f"{self.item_label}: {self._error_msg}"
                    )

        except Exception as exc:
            self.state = UpdateState.UPDATE_FAILED
            self._error_msg = str(exc)
            self._error_detail = "".join(
                traceback.format_exception(*sys.exc_info())
            )
            self.log.error(
                f"{self.item_label}: Distibution failed",
                exc_info=True
            )

        finally:
            if self.state == UpdateState.OUTDATED:
                self.state = UpdateState.UPDATE_FAILED
                self._error_msg = "Distribution failed"

            self._post_distribute()
            yield True

current_source_progress property

Currently processed source progress object.

Returns:

Type Description
Optional[DistributeTransferProgress]

Optional[DistributeTransferProgress]: Transfer progress or None.

error_detail property

Detailed reason why distribution item failed.

Returns:

Type Description
Optional[str]

Optional[str]: Detailed information (maybe traceback).

error_message property

Reason why distribution item failed.

Returns:

Type Description
Optional[str]

Optional[str]: Error message.

need_distribution property

Need distribution based on initial state.

Returns:

Name Type Description
bool bool

Need distribution.

used_source property

Data of source item.

Returns:

Type Description
Optional[dict[str, Any]]

Optional[dict[str, Any]]: SourceInfo data or None.

used_source_progress property

Transfer progress that successfully distributed the item.

Returns:

Type Description
Optional[DistributeTransferProgress]

Optional[DistributeTransferProgress]: Transfer progress or None.

distribute()

Execute distribution logic.

Source code in common/ayon_common/distribution/control.py
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
def distribute(self) -> Generator[bool, None, None]:
    """Execute distribution logic."""
    if self.is_distributed() or self._dist_started:
        yield True
        return

    self._dist_started = True
    try:
        try:
            for result in self._distribute():
                if result:
                    break
                yield False

        except DistributionProgressInterupted:
            wait_result = False
            for wait_result in _wait_for_other_process(
                self._progress_dir, self._progress_id, self.log
            ):
                if wait_result is not None:
                    break
                yield False

            if wait_result:
                self.state = UpdateState.UPDATED
            else:
                self.state = UpdateState.UPDATE_FAILED
                self._error_msg = (
                    "Other process took over distribution and failed."
                )
                self._error_detail = (
                    "Please try to start AYON again and contact"
                    " administrator if issue persist."
                )
                self.log.error(
                    f"{self.item_label}: {self._error_msg}"
                )

    except Exception as exc:
        self.state = UpdateState.UPDATE_FAILED
        self._error_msg = str(exc)
        self._error_detail = "".join(
            traceback.format_exception(*sys.exc_info())
        )
        self.log.error(
            f"{self.item_label}: Distibution failed",
            exc_info=True
        )

    finally:
        if self.state == UpdateState.OUTDATED:
            self.state = UpdateState.UPDATE_FAILED
            self._error_msg = "Distribution failed"

        self._post_distribute()
        yield True

DistributeTransferProgress

Progress of single source item in 'DistributionItem'.

The item is to keep track of single source item.

Source code in common/ayon_common/distribution/control.py
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
class DistributeTransferProgress:
    """Progress of single source item in 'DistributionItem'.

    The item is to keep track of single source item.
    """

    def __init__(self):
        self._transfer_progress = ayon_api.TransferProgress()
        self._started = False
        self._failed = False
        self._fail_reason = None
        self._unzip_started = False
        self._unzip_finished = False
        self._hash_check_started = False
        self._hash_check_finished = False

    def set_started(self):
        """Call when source distribution starts."""

        self._started = True

    def set_failed(self, reason: str):
        """Set source distribution as failed.

        Args:
            reason (str): Error message why the transfer failed.

        """
        self._failed = True
        self._fail_reason = reason

    def set_hash_check_started(self):
        """Call just before hash check starts."""

        self._hash_check_started = True

    def set_hash_check_finished(self):
        """Call just after hash check finishes."""

        self._hash_check_finished = True

    def set_unzip_started(self):
        """Call just before unzip starts."""

        self._unzip_started = True

    def set_unzip_finished(self):
        """Call just after unzip finishes."""

        self._unzip_finished = True

    @property
    def is_running(self) -> bool:
        """Source distribution is in progress.

        Returns:
            bool: Transfer is in progress.
        """

        return bool(
            self._started
            and not self._failed
            and not self._hash_check_finished
        )

    @property
    def transfer_progress(self) -> ayon_api.TransferProgress:
        """Source file 'download' progress tracker.

        Returns:
            ayon_api.TransferProgress: Content download progress.

        """
        return self._transfer_progress

    @property
    def started(self) -> bool:
        return self._started

    @property
    def hash_check_started(self) -> bool:
        return self._hash_check_started

    @property
    def hash_check_finished(self) -> bool:
        return self._hash_check_finished

    @property
    def unzip_started(self) -> bool:
        return self._unzip_started

    @property
    def unzip_finished(self) -> bool:
        return self._unzip_finished

    @property
    def failed(self) -> bool:
        return self._failed or self._transfer_progress.failed

    @property
    def fail_reason(self) -> Optional[str]:
        return self._fail_reason or self._transfer_progress.fail_reason

is_running property

Source distribution is in progress.

Returns:

Name Type Description
bool bool

Transfer is in progress.

transfer_progress property

Source file 'download' progress tracker.

Returns:

Type Description
TransferProgress

ayon_api.TransferProgress: Content download progress.

set_failed(reason)

Set source distribution as failed.

Parameters:

Name Type Description Default
reason str

Error message why the transfer failed.

required
Source code in common/ayon_common/distribution/control.py
453
454
455
456
457
458
459
460
461
def set_failed(self, reason: str):
    """Set source distribution as failed.

    Args:
        reason (str): Error message why the transfer failed.

    """
    self._failed = True
    self._fail_reason = reason

set_hash_check_finished()

Call just after hash check finishes.

Source code in common/ayon_common/distribution/control.py
468
469
470
471
def set_hash_check_finished(self):
    """Call just after hash check finishes."""

    self._hash_check_finished = True

set_hash_check_started()

Call just before hash check starts.

Source code in common/ayon_common/distribution/control.py
463
464
465
466
def set_hash_check_started(self):
    """Call just before hash check starts."""

    self._hash_check_started = True

set_started()

Call when source distribution starts.

Source code in common/ayon_common/distribution/control.py
448
449
450
451
def set_started(self):
    """Call when source distribution starts."""

    self._started = True

set_unzip_finished()

Call just after unzip finishes.

Source code in common/ayon_common/distribution/control.py
478
479
480
481
def set_unzip_finished(self):
    """Call just after unzip finishes."""

    self._unzip_finished = True

set_unzip_started()

Call just before unzip starts.

Source code in common/ayon_common/distribution/control.py
473
474
475
476
def set_unzip_started(self):
    """Call just before unzip starts."""

    self._unzip_started = True

DistributionItem

Bases: BaseDistributionItem

Distribution item with sources and target directories.

Distribution item for addons and dependency packages. They have defined unzip directory where the downloaded content is unzipped.

Parameters:

Name Type Description Default
target_dirpath str

Path to directory where zip is downloaded.

required
download_dirpath str

Path to directory where file is unzipped.

required
state UpdateState

Initial state (UpdateState.UPDATED or UpdateState.OUTDATED).

required
file_hash str

Hash of file for validation.

required
factory DownloadFactory

Downloaders factory object.

required
sources List[SourceInfo]

Possible sources to receive the distribution item.

required
downloader_data Dict[str, Any]

More information for downloaders.

required
item_label str

Label used in log outputs (and in UI).

required
progress_dir Optional[str]

Directory where progress is stored for other processes.

required
logger Logger

Logger object.

required
Source code in common/ayon_common/distribution/control.py
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
class DistributionItem(BaseDistributionItem):
    """Distribution item with sources and target directories.

    Distribution item for addons and dependency packages. They have defined
    unzip directory where the downloaded content is unzipped.

    Args:
        target_dirpath (str): Path to directory where zip is downloaded.
        download_dirpath (str): Path to directory where file is unzipped.
        state (UpdateState): Initial state (UpdateState.UPDATED or
            UpdateState.OUTDATED).
        file_hash (str): Hash of file for validation.
        factory (DownloadFactory): Downloaders factory object.
        sources (List[SourceInfo]): Possible sources to receive the
            distribution item.
        downloader_data (Dict[str, Any]): More information for downloaders.
        item_label (str): Label used in log outputs (and in UI).
        progress_dir (Optional[str]): Directory where progress is stored for
            other processes.
        logger (logging.Logger): Logger object.

    """
    def __init__(
        self, target_dirpath: str, unzip_temp_dir: str, *args, **kwargs
    ):
        self.target_dirpath = target_dirpath
        self.unzip_temp_dir = unzip_temp_dir
        super().__init__(*args, **kwargs)

    @property
    def is_missing_permissions(self) -> bool:
        return not _has_write_permissions(self.target_dirpath)

    def _post_source_process(
        self,
        filepath: str,
        source_data: dict[str, Any],
        source_progress: DistributeTransferProgress,
        downloader: SourceDownloader,
    ) -> Generator[Optional[bool], None, None]:
        source_progress.set_unzip_started()
        result = False
        for result in _wait_for_other_process(
            self._progress_dir, self._progress_id, self.log
        ):
            if result is not None:
                break
            yield None

        if result is True:
            self.state = UpdateState.UPDATED
            yield True
            return

        filename = os.path.basename(self.target_dirpath)
        unzip_dirpath = os.path.join(self.unzip_temp_dir, filename)
        # NOTE This is a workaround for dependency packages
        # TODO remove when dependency packages are not stored to directory
        #   ending with .zip
        if filepath == unzip_dirpath:
            filedir = os.path.dirname(filepath)
            ext = os.path.splitext(filepath)[-1]
            new_filepath = os.path.join(filedir, f"{uuid.uuid4().hex}{ext}")
            os.rename(filepath, new_filepath)
            filepath = new_filepath

        # Create directory
        os.makedirs(unzip_dirpath, exist_ok=True)
        try:
            os.chmod(unzip_dirpath, 0o777)
            change_permissions_recursive(unzip_dirpath)
        except PermissionError:
            message = f"Permission denied for {unzip_dirpath}"
            self.log.exception(
                f"{self.item_label}: {message}",
                exc_info=True
            )

        try:
            downloader.unzip(filepath, unzip_dirpath)
        except Exception:
            message = "Couldn't unzip source file"
            source_progress.set_failed(message)
            self.log.warning(
                f"{self.item_label}: {message}",
                exc_info=True
            )
            yield False
            return

        source_progress.set_unzip_finished()

        yield None

        result = False
        for result in _wait_for_other_process(
            self._progress_dir, self._progress_id, self.log
        ):
            if result is not None:
                break
            yield None

        if result is True:
            self.state = UpdateState.UPDATED
            yield True
            return

        failed = False
        renamed_mapping = []

        # Target directory can contain only distribution metadata file
        #   anything else is temporarily moved to different directory
        #   - next to target directory
        # NOTE: We might validate if the content is exactly same?
        tmp_subfolder = os.path.join(
            os.path.dirname(self.target_dirpath), uuid.uuid4().hex
        )
        if not os.path.exists(self.target_dirpath):
            os.makedirs(self.target_dirpath, exist_ok=True)
            try:
                os.chmod(self.target_dirpath, 0o777)
                change_permissions_recursive(self.target_dirpath)
            except PermissionError:
                self.log.exception(
                    f"{self.item_label}: permission denied "
                    f"for {self.target_dirpath}",
                )

        for name in os.listdir(self.target_dirpath):
            if name == DIST_PROGRESS_FILENAME:
                continue
            if not os.path.exists(tmp_subfolder):
                os.makedirs(tmp_subfolder, exist_ok=True)
                try:
                    os.chmod(self.target_dirpath, 0o777)
                    change_permissions_recursive(tmp_subfolder)
                except PermissionError:
                    self.log.exception(
                        f"{self.item_label}: permission denied "
                        f"for {self.target_dirpath}",
                    )

            current_path = os.path.join(self.target_dirpath, name)
            new_path = os.path.join(tmp_subfolder, name)
            try:
                os.rename(current_path, new_path)
            except Exception:
                message = (
                    "Target files already exist and can't be renamed."
                )
                source_progress.set_failed(message)
                self.log.warning(
                    f"{self.item_label}: {message}",
                    exc_info=True
                )
                failed = True
                break
            renamed_mapping.append((current_path, new_path))

        if failed:
            # Rollback renamed files
            for src_path, renamed_path in renamed_mapping:
                os.rename(renamed_path, src_path)
            yield False
            return

        yield None

        # Move unzipped content to target directory
        moved_paths = []
        rename_attemps = 5
        for subname in os.listdir(unzip_dirpath):
            target_path = os.path.join(self.target_dirpath, subname)
            src_path = os.path.join(unzip_dirpath, subname)
            dst_path = os.path.join(self.target_dirpath, subname)
            self.log.debug("Copying %s to %s", src_path, dst_path)
            # Sometimes 'os.rename' crashes because of permissions issue
            #   even though it can be done in a future attempt (probably some
            #   service traversing through files blocking it?)
            for attempt in range(rename_attemps):
                try:
                    os.rename(src_path, dst_path)
                    break
                except Exception:
                    if attempt < (rename_attemps - 1):
                        yield None
                        continue
                    message = (
                        "Failed to move unzipped content to target directory."
                    )
                    source_progress.set_failed(message)
                    self.log.warning(
                        f"{self.item_label}: {message}",
                        exc_info=True
                    )
                    failed = True

            if failed:
                break

            moved_paths.append(target_path)

        # Handle failed movement
        if failed:
            # Remove moved files
            for path in moved_paths:
                if os.path.isfile(path):
                    os.remove(path)
                else:
                    shutil.rmtree(path)

            # Rename renamed files back to original
            for src_path, renamed_path in renamed_mapping:
                os.rename(renamed_path, src_path)

        # Remove temp subfolder used for renaming
        if os.path.exists(tmp_subfolder):
            shutil.rmtree(tmp_subfolder)

        if failed:
            yield False
            return

        yield from super()._post_source_process(
            filepath, source_data, source_progress, downloader
        )

    def _post_distribute(self):
        if (
            self.state != UpdateState.UPDATED
            and self.target_dirpath
            and os.path.isdir(self.target_dirpath)
        ):
            self.log.debug(f"Cleaning {self.target_dirpath}")
            # TODO use '_clean_dist_dir' when backwards compatibility with
            #   previous versions of AYON launchers is not needed.
            # _clean_dist_dir(self.target_dirpath)
            shutil.rmtree(self.target_dirpath)

InstallerDistributionItem

Bases: BaseDistributionItem

Distribution of new version of AYON launcher/Installer.

Source code in common/ayon_common/distribution/control.py
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
class InstallerDistributionItem(BaseDistributionItem):
    """Distribution of new version of AYON launcher/Installer."""

    def __init__(self, cleanup_on_fail: bool, *args, **kwargs):
        super().__init__(*args, **kwargs, change_permissions=False)
        self._cleanup_on_fail = cleanup_on_fail
        self._executable = None
        self._installer_path = None
        self._installer_error = None

    @property
    def executable(self) -> Optional[str]:
        """Path to distributed ayon executable.

        Returns:
            Optional[str]: Path to executable path which was distributed.

        """
        return self._executable

    @property
    def installer_path(self) -> Optional[str]:
        """Path to a distribution package/installer.

        This can be used as reference for user where to find downloaded
            installer on disk and distribute it manually.

        Returns:
            Optional[str]: Path to installer.

        """
        return self._installer_path

    @property
    def installer_error(self) -> Optional[str]:
        """Known installer error that happened during distribution.

        Returns:
            Optional[str]: Message that will be shown to user and logged
                out.

        """
        return self._installer_error

    @property
    def is_missing_permissions(self) -> bool:
        return not _has_write_permissions(
            os.path.dirname(os.path.dirname(sys.executable))
        )

    def _find_windows_executable(self, log_output: str):
        """Find executable path in log output.

        Setup exe should print out log output to a file where are described
        steps that happened during installation.

        Todos:
            Find a better way how to find out where AYON launcher was
                installed.

        Args:
            log_output (str): Output from installer log.

        """
        exe_name = "ayon.exe"
        for line in log_output.splitlines():
            idx = line.find(exe_name)
            if idx < 0:
                continue

            line = line[:idx + len(exe_name)]
            parts = line.split("\\")
            if len(parts) < 2:
                parts = line.replace("/", "\\").split("\\")

            last_part = parts.pop(-1)
            found_valid = False
            final_parts = []
            for part in parts:
                if found_valid:
                    final_parts.append(part)
                    continue
                part = part + "\\"
                while part:
                    if os.path.exists(part):
                        break
                    part = part[1:]

                if part:
                    found_valid = True
                    final_parts.append(part[:-1])
            final_parts.append(last_part)
            executable_path = "\\".join(final_parts)
            if os.path.exists(executable_path):
                return executable_path

    def _install_windows(self, filepath: str):
        """Install windows AYON launcher.

        Args:
            filepath (str): Path to setup.exe file.

        """
        install_root = os.path.dirname(os.path.dirname(sys.executable))

        # A file where installer may store log output
        log_file = create_tmp_file(suffix="ayon_install")
        # A file where installer may store output directory
        install_exe_tmp = create_tmp_file(suffix="ayon_install_dir")
        user_arg = "/CURRENTUSER"
        # Ask for admin permissions if user is not admin and
        if not _has_write_permissions(install_root):
            if HEADLESS_MODE_ENABLED:
                raise InstallerDistributionError((
                    "Installation requires administration permissions, which"
                    " cannot be granted in headless mode."
                ))
            user_arg = "/ALLUSERS"
        args = [
            filepath,
            user_arg,
            "/NOCANCEL",
            f"/LOG={log_file}",
            f"/INSTALLROOT={install_root}"
        ]
        if not HEADLESS_MODE_ENABLED:
            args.append("/SILENT")
        else:
            args.append("/VERYSILENT")

        env = dict(os.environ.items())
        env["AYON_INSTALL_EXE_OUTPUT"] = install_exe_tmp

        code = subprocess.call(args, env=env)
        with open(log_file, "r") as stream:
            log_output = stream.read()
        with open(install_exe_tmp, "r") as stream:
            install_exe_path = stream.read()
        os.remove(log_file)
        os.remove(install_exe_tmp)
        if code != 0:
            self.log.error(log_output)
            raise InstallerDistributionError(
                "Install process failed without known reason."
                " Try to install AYON manually."
            )

        executable = install_exe_path.strip() or None
        if not executable or not os.path.exists(executable):
            executable = self._find_windows_executable(log_output)

        self._executable = executable

    def _install_linux(self, filepath: str):
        """Install linux AYON launcher.

        Linux installations are just an archive file, so we attempt to unzip
            the new installation one level up of the one being run.

        Args:
            filepath (str): Path to a .tar.gz file.

        """
        install_root = os.path.dirname(os.path.dirname(sys.executable))

        self.log.info(
            f"Installing AYON launcher {filepath} into:\n{install_root}"
        )

        if not os.path.exists(install_root):
            os.makedirs(install_root, exist_ok=True)
            try:
                os.chmod(install_root, 0o777)
            except PermissionError:
                self.log.exception(
                    f"{self.item_label}: Permission denied for {install_root}"
                )

        try:
            extract_archive_file(filepath, install_root)
        except Exception as e:
            self.log.error(e)
            raise InstallerDistributionError(
                "Install process failed without known reason."
                " Try to install AYON manually."
            )

        installer_dir = os.path.basename(filepath).replace(".tar.gz", "")
        executable = os.path.join(install_root, installer_dir, "ayon")
        self.log.info(f"Setting executable to {executable}")
        self._executable = executable

    def _install_macos(self, filepath: str):
        """Install macOS AYON launcher.

        Args:
            filepath (str): Path to a .dmg file.

        """
        import plistlib

        # Attach dmg file and read plist output (bytes)
        stdout = subprocess.check_output([
            "hdiutil", "attach", filepath, "-plist", "-nobrowse"
        ])
        mounted_volumes = []
        try:
            # Parse plist output and find mounted volume
            attach_info = plistlib.loads(stdout)
            for entity in attach_info["system-entities"]:
                mounted_volume = entity.get("mount-point")
                if mounted_volume:
                    mounted_volumes.append(mounted_volume)

            # We do expect there is only one .app in .dmg file
            src_path = None
            src_filename = None
            for mounted_volume in mounted_volumes:
                for filename in os.listdir(mounted_volume):
                    if filename.endswith(".app"):
                        src_filename = filename
                        src_path = os.path.join(mounted_volume, src_filename)
                        break

            if src_path is not None:
                # Copy the .app file to /Applications
                dst_dir = "/Applications"
                dst_path = os.path.join(dst_dir, src_filename)
                subprocess.run(["cp", "-rf", src_path, dst_dir])

        finally:
            # Detach mounted volume
            for mounted_volume in mounted_volumes:
                subprocess.run(["hdiutil", "detach", mounted_volume])

        # Find executable inside .app file and return its path
        contents_dir = os.path.join(dst_path, "Contents")
        # Load plist file and check for bundle executable
        plist_filepath = os.path.join(contents_dir, "Info.plist")
        if hasattr(plistlib, "load"):
            with open(plist_filepath, "rb") as stream:
                parsed_plist = plistlib.load(stream)
        else:
            parsed_plist = plistlib.readPlist(plist_filepath)
        executable_filename = parsed_plist.get("CFBundleExecutable")
        self._executable = os.path.join(
            contents_dir, "MacOS", executable_filename
        )

    def _install_file(self, filepath):
        """Trigger installation installer file based on platform."""

        # TODO consider using platform name in target folder
        #  - for windows and linux
        platform_name = platform.system().lower()
        if platform_name == "windows":
            self._install_windows(filepath)
        elif platform_name == "linux":
            self._install_linux(filepath)
        elif platform_name == "darwin":
            self._install_macos(filepath)
        else:
            raise InstallerDistributionError(
                f"Unsupported platform: {platform_name}"
            )

    def _post_source_process(
        self,
        filepath: str,
        source_data: dict[str, Any],
        source_progress: DistributeTransferProgress,
        downloader: SourceDownloader,
    ) -> Generator[Optional[bool], None, None]:
        self._installer_path = filepath
        success = False
        try:
            if filepath:
                self._install_file(filepath)
                success = True
            else:
                message = "File was not downloaded"
                source_progress.set_failed(message)

        except Exception as exc:
            message = "Installation failed"
            source_progress.set_failed(message)
            if isinstance(exc, InstallerDistributionError):
                self._installer_error = str(exc)
            else:
                self.log.warning(
                    f"{self.item_label}: {message}",
                    exc_info=True
                )
                self._installer_error = (
                    "Distribution of AYON launcher"
                    " failed with unexpected reason."
                )

        self.state = (
            UpdateState.UPDATED if success else UpdateState.UPDATE_FAILED
        )

        self._used_source = source_data
        if success or self._cleanup_on_fail:
            downloader.cleanup(
                source_data,
                self.download_dirpath,
                self.downloader_data
            )

        yield True

executable property

Path to distributed ayon executable.

Returns:

Type Description
Optional[str]

Optional[str]: Path to executable path which was distributed.

installer_error property

Known installer error that happened during distribution.

Returns:

Type Description
Optional[str]

Optional[str]: Message that will be shown to user and logged out.

installer_path property

Path to a distribution package/installer.

This can be used as reference for user where to find downloaded installer on disk and distribute it manually.

Returns:

Type Description
Optional[str]

Optional[str]: Path to installer.

change_permissions_recursive(path, mode=511)

Change permission recursively.

This will raise PermissionError if chmod fails.

Parameters:

Name Type Description Default
path str

Path to the directory.

required
mode int

Permission mode.

511
Source code in common/ayon_common/distribution/control.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def change_permissions_recursive(path: str, mode: int = 0o777) -> None:
    """Change permission recursively.

    This will raise PermissionError if chmod fails.

    Args:
        path (str): Path to the directory.
        mode (int): Permission mode.

    """
    if IS_WINDOWS or not os.path.exists(path):
        return

    if os.path.isfile(path):
        # If the path is a file, change its permissions directly
        os.chmod(path, mode)
        return

    # Traverse the directory tree starting from 'path' to top
    for root, dirnames, filenames in os.walk(path, topdown=False):
        # Change the permissions of each directory
        for dirname in dirnames:
            dirpath = os.path.join(root, dirname)
            os.chmod(dirpath, mode)

        for filename in filenames:
            filepath = os.path.join(root, filename)
            os.chmod(filepath, mode)