├── .github ├── actions │ ├── matrix_check.yml │ ├── matrix_dependabot.yml │ ├── matrix_reduced_test_1.yml │ ├── matrix_reduced_test_2.yml │ └── matrix_test.yml ├── dependabot.yml └── workflows │ ├── ci_distributed_computing_bench.yml │ ├── ci_http_downloader.yml │ ├── ci_node_activator.yml │ ├── ci_pelemay_backend.yml │ ├── ci_spawn_co_elixir.yml │ ├── cleanup_all_cache.yml │ ├── dependabot_auto_merge.yml │ ├── reusable_ci.yml │ ├── reusable_ci_for_self_hosted_runner_macos.yml │ └── reusable_ci_with_working_directory.yml ├── .gitignore ├── CITATION.cff ├── LICENSE ├── Makefile ├── README.md ├── backends ├── logging_backend │ ├── .formatter.exs │ ├── .gitignore │ ├── LICENSE │ ├── README.md │ ├── lib │ │ └── logging_backend.ex │ ├── mix.exs │ ├── mix.lock │ └── test │ │ ├── logging_backend_test.exs │ │ └── test_helper.exs └── pelemay_backend │ ├── .credo.exs │ ├── .dialyzer_ignore.exs │ ├── .formatter.exs │ ├── .gitignore │ ├── LICENSE │ ├── Makefile │ ├── README.md │ ├── lib │ ├── pelemay_backend.ex │ └── pelemay_backend │ │ ├── application.ex │ │ ├── backend.ex │ │ ├── defn.ex │ │ ├── defn │ │ ├── lock.ex │ │ └── locked_cache.ex │ │ ├── engine.ex │ │ ├── nif.ex │ │ └── parser.ex │ ├── mix.exs │ ├── mix.lock │ ├── nif_src │ ├── libnif.c │ └── opcode.h │ └── test │ ├── pelemay_backend │ ├── backend_test.exs │ └── engine_test.exs │ ├── pelemay_backend_test.exs │ └── test_helper.exs ├── benchmarks └── distributed_computing_bench │ ├── .formatter.exs │ ├── .gitignore │ ├── README.md │ ├── lib │ ├── distributed_computing_bench.ex │ └── distributed_computing_bench │ │ ├── bumblebee_bench.ex │ │ └── bumblebee_bench │ │ └── runner.exs │ ├── mix.exs │ ├── mix.lock │ └── test │ ├── distributed_computing_bench_test.exs │ └── test_helper.exs └── utilities ├── backend_decorator ├── .formatter.exs ├── .gitignore ├── LICENSE ├── README.md ├── lib │ └── backend_decorator.ex ├── mix.exs ├── mix.lock └── test │ ├── backend_decorator_test.exs │ └── test_helper.exs ├── http_downloader ├── .formatter.exs ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── lib │ └── http_downloader.ex ├── mix.exs ├── mix.lock └── test │ ├── http_downloader_test.exs │ └── test_helper.exs ├── node_activator ├── .formatter.exs ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── lib │ ├── node_activator.ex │ └── node_activator │ │ ├── epmd.ex │ │ └── utils.ex ├── mix.exs ├── mix.lock └── test │ ├── node_activator │ ├── epmd_test.exs │ └── utils_test.exs │ ├── node_activator_test.exs │ └── test_helper.exs └── spawn_co_elixir ├── .formatter.exs ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── lib ├── spawn_co_elixir.ex └── spawn_co_elixir │ ├── application.ex │ ├── co_elixir.ex │ ├── co_elixir │ └── worker.ex │ ├── co_elixir_lookup.ex │ ├── co_elixir_worker_spawner.ex │ └── watch_dog_timer.ex ├── mix.exs ├── mix.lock └── test ├── spawn_co_elixir └── co_elixir_lookup_test.exs ├── spawn_co_elixir_test.exs └── test_helper.exs /.github/actions/matrix_check.yml: -------------------------------------------------------------------------------- 1 | include: 2 | - otp-version: "27.2" 3 | elixir-version: "1.18.1" 4 | -------------------------------------------------------------------------------- /.github/actions/matrix_dependabot.yml: -------------------------------------------------------------------------------- 1 | include: 2 | - otp-version: "27.2" 3 | elixir-version: "1.18.1" 4 | working-directory: utilities/node_activator 5 | - otp-version: "27.2" 6 | elixir-version: "1.18.1" 7 | working-directory: utilities/spawn_co_elixir 8 | - otp-version: "27.2" 9 | elixir-version: "1.18.1" 10 | working-directory: utilities/http_downloader 11 | - otp-version: "27.2" 12 | elixir-version: "1.18.1" 13 | working-directory: benchmarks/distributed_computing_bench 14 | - otp-version: "27.2" 15 | elixir-version: "1.18.1" 16 | working-directory: benchmarks/onnx_to_axon_bench 17 | -------------------------------------------------------------------------------- /.github/actions/matrix_reduced_test_1.yml: -------------------------------------------------------------------------------- 1 | include: 2 | - otp-version: "25.3.2.16" 3 | elixir-version: "1.17.3" 4 | - otp-version: "26.2.5.6" 5 | elixir-version: "1.16.3" 6 | - otp-version: "27.2" 7 | elixir-version: "1.16.3" 8 | - otp-version: "26.2.5.6" 9 | elixir-version: "1.18.1" 10 | - otp-version: "27.2" 11 | elixir-version: "1.18.1" 12 | -------------------------------------------------------------------------------- /.github/actions/matrix_reduced_test_2.yml: -------------------------------------------------------------------------------- 1 | include: 2 | - otp-version: "25.3.2.16" 3 | elixir-version: "1.16.3" 4 | - otp-version: "26.2.5.6" 5 | elixir-version: "1.17.3" 6 | - otp-version: "27.2" 7 | elixir-version: "1.17.3" 8 | -------------------------------------------------------------------------------- /.github/actions/matrix_test.yml: -------------------------------------------------------------------------------- 1 | include: 2 | - otp-version: "25.3.2.16" 3 | elixir-version: "1.16.3" 4 | - otp-version: "25.3.2.16" 5 | elixir-version: "1.17.3" 6 | - otp-version: "26.2.5.6" 7 | elixir-version: "1.16.3" 8 | - otp-version: "26.2.5.6" 9 | elixir-version: "1.17.3" 10 | - otp-version: "26.2.5.6" 11 | elixir-version: "1.18.1" 12 | - otp-version: "27.2" 13 | elixir-version: "1.16.3" 14 | - otp-version: "27.2" 15 | elixir-version: "1.17.3" 16 | - otp-version: "27.2" 17 | elixir-version: "1.18.1" 18 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | 8 | - package-ecosystem: "mix" 9 | directory: "/utilities/node_activator" 10 | schedule: 11 | interval: "daily" 12 | 13 | - package-ecosystem: "mix" 14 | directory: "/utilities/spawn_co_elixir" 15 | schedule: 16 | interval: "daily" 17 | 18 | - package-ecosystem: "mix" 19 | directory: "/utilities/http_downloader" 20 | schedule: 21 | interval: "daily" 22 | 23 | - package-ecosystem: "mix" 24 | directory: "/benchmarks/onnx_to_axon_bench" 25 | schedule: 26 | interval: "daily" 27 | 28 | - package-ecosystem: "mix" 29 | directory: "/benchmarks/distributed_computing_bench" 30 | schedule: 31 | interval: "daily" -------------------------------------------------------------------------------- /.github/workflows/ci_distributed_computing_bench.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # CI 5 | 6 | name: Elixir CI (DistributedComputingBench) 7 | 8 | on: 9 | pull_request: 10 | types: [opened, reopened, synchronize] 11 | branches: [ "develop", "check_by_SHR" ] 12 | paths: 13 | - 'benchmarks/distributed_computing_bench/**' 14 | - '!.github/workflows/*' 15 | - '.github/workflows/ci_distributed_computing_bench.yml' 16 | - '.github/workflows/reusable_ci.yml' 17 | - '.github/actions/matrix_check.yml' 18 | - '.github/actions/matrix_test.yml' 19 | - '.github/actions/matrix_reduced_test_1.yml' 20 | - '.github/actions/matrix_reduced_test_2.yml' 21 | - '!**/*.md' 22 | - '!**/LICENSE*' 23 | - '!*.md' 24 | - '!*.cff' 25 | - '!LICENSE*' 26 | - '!publish.exs' 27 | push: 28 | branches: [ "main", "develop", "check_by_SHR" ] 29 | paths: 30 | - 'benchmarks/distributed_computing_bench/**' 31 | - '!.github/workflows/*' 32 | - '.github/workflows/ci_distributed_computing_bench.yml' 33 | - '.github/workflows/reusable_ci.yml' 34 | - '.github/actions/matrix_check.yml' 35 | - '.github/actions/matrix_test.yml' 36 | - '.github/actions/matrix_reduced_test_1.yml' 37 | - '.github/actions/matrix_reduced_test_2.yml' 38 | - '!**/*.md' 39 | - '!**/LICENSE*' 40 | - '!*.md' 41 | - '!*.cff' 42 | - '!LICENSE*' 43 | - '!publish.exs' 44 | 45 | concurrency: 46 | group: ${{ github.workflow }}-${{ github.ref }} 47 | cancel-in-progress: true 48 | 49 | permissions: 50 | contents: read 51 | 52 | jobs: 53 | constants: 54 | name: Constants 55 | if: ${{ github.actor != 'dependabot[bot]' }} 56 | runs-on: ubuntu-22.04 57 | outputs: 58 | matrix-for-check: ${{ steps.set-matrix-for-check.outputs.matrix }} 59 | matrix-test: ${{ steps.set-matrix-test.outputs.matrix }} 60 | matrix-reduced-test-1: ${{ steps.set-matrix-reduced-test-1.outputs.matrix }} 61 | matrix-reduced-test-2: ${{ steps.set-matrix-reduced-test-2.outputs.matrix }} 62 | steps: 63 | - uses: actions/checkout@v4 64 | - id: set-matrix-for-check 65 | run: | 66 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_check.yml| ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 67 | echo "matrix=${json}" >> $GITHUB_OUTPUT 68 | - id: set-matrix-test 69 | run: | 70 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_test.yml | ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 71 | echo "matrix=${json}" >> $GITHUB_OUTPUT 72 | - id: set-matrix-reduced-test-1 73 | run: | 74 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_reduced_test_1.yml | ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 75 | echo "matrix=${json}" >> $GITHUB_OUTPUT 76 | - id: set-matrix-reduced-test-2 77 | run: | 78 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_reduced_test_2.yml | ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 79 | echo "matrix=${json}" >> $GITHUB_OUTPUT 80 | check_distributed_computing_bench: 81 | name: Check DistributedComputingBench 82 | needs: constants 83 | uses: ./.github/workflows/reusable_ci.yml 84 | with: 85 | working-directory: benchmarks/distributed_computing_bench 86 | os: ubuntu-22.04 87 | matrix: ${{ needs.constants.outputs.matrix-for-check }} 88 | perform-check: true 89 | test_ubuntu_22_distributed_computing_bench: 90 | name: Test DistributedComputingBench (Ubuntu 22.04) 91 | needs: [constants, check_distributed_computing_bench] 92 | uses: ./.github/workflows/reusable_ci.yml 93 | with: 94 | working-directory: benchmarks/distributed_computing_bench 95 | os: ubuntu-22.04 96 | matrix: ${{ needs.constants.outputs.matrix-test }} 97 | perform-check: false 98 | test_ubuntu_24_distributed_computing_bench: 99 | name: Test DistributedComputingBench (Ubuntu 24.04) 100 | needs: [constants, check_distributed_computing_bench] 101 | uses: ./.github/workflows/reusable_ci.yml 102 | with: 103 | working-directory: benchmarks/distributed_computing_bench 104 | os: ubuntu-24.04 105 | matrix: ${{ needs.constants.outputs.matrix-test }} 106 | perform-check: false 107 | -------------------------------------------------------------------------------- /.github/workflows/ci_http_downloader.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # CI 5 | 6 | name: Elixir CI (HttpDownloader) 7 | 8 | on: 9 | pull_request: 10 | types: [opened, reopened, synchronize] 11 | branches: [ "develop", "check_by_SHR" ] 12 | paths: 13 | - 'utilities/http_downloader/**' 14 | - '!benchmarks/onnx_to_axon_bench/**' 15 | - '!benchmarks/distributed_computing_bench/**' 16 | - '!.github/workflows/*' 17 | - '.github/workflows/ci_http_downloader.yml' 18 | - '.github/workflows/reusable_ci.yml' 19 | - '.github/actions/matrix_check.yml' 20 | - '.github/actions/matrix_test.yml' 21 | - '!**/*.md' 22 | - '!**/LICENSE*' 23 | - '!*.md' 24 | - '!*.cff' 25 | - '!LICENSE*' 26 | - '!publish.exs' 27 | push: 28 | branches: [ "main", "develop", "check_by_SHR" ] 29 | paths: 30 | - 'utilities/http_downloader/**' 31 | - '!benchmarks/onnx_to_axon_bench/**' 32 | - '!benchmarks/distributed_computing_bench/**' 33 | - '!.github/workflows/*' 34 | - '.github/workflows/ci_http_downloader.yml' 35 | - '.github/workflows/reusable_ci.yml' 36 | - '.github/actions/matrix_check.yml' 37 | - '.github/actions/matrix_test.yml' 38 | - '!**/*.md' 39 | - '!**/LICENSE*' 40 | - '!*.md' 41 | - '!*.cff' 42 | - '!LICENSE*' 43 | - '!publish.exs' 44 | 45 | concurrency: 46 | group: ${{ github.workflow }}-${{ github.ref }} 47 | cancel-in-progress: true 48 | 49 | permissions: 50 | contents: read 51 | 52 | jobs: 53 | constants: 54 | name: Constants 55 | if: ${{ github.actor != 'dependabot[bot]' }} 56 | runs-on: ubuntu-22.04 57 | outputs: 58 | matrix-for-check: ${{ steps.set-matrix-for-check.outputs.matrix }} 59 | matrix-test: ${{ steps.set-matrix-test.outputs.matrix }} 60 | steps: 61 | - uses: actions/checkout@v4 62 | - id: set-matrix-for-check 63 | run: | 64 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_check.yml| ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 65 | echo "matrix=${json}" >> $GITHUB_OUTPUT 66 | - id: set-matrix-test 67 | run: | 68 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_test.yml | ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 69 | echo "matrix=${json}" >> $GITHUB_OUTPUT 70 | check_http_downloader: 71 | name: Check HttpDownloader 72 | needs: constants 73 | uses: ./.github/workflows/reusable_ci.yml 74 | with: 75 | working-directory: utilities/http_downloader 76 | os: ubuntu-22.04 77 | matrix: ${{ needs.constants.outputs.matrix-for-check }} 78 | perform-check: true 79 | test_ubuntu_22_http_downloader: 80 | name: Test HttpDownloader (Ubuntu 22.04) 81 | needs: [constants, check_http_downloader] 82 | uses: ./.github/workflows/reusable_ci.yml 83 | with: 84 | working-directory: utilities/http_downloader 85 | os: ubuntu-22.04 86 | matrix: ${{ needs.constants.outputs.matrix-test }} 87 | perform-check: false 88 | test_ubuntu_24_http_downloader: 89 | name: Test HttpDownloader (Ubuntu 24.04) 90 | needs: [constants, check_http_downloader] 91 | uses: ./.github/workflows/reusable_ci.yml 92 | with: 93 | working-directory: utilities/http_downloader 94 | os: ubuntu-24.04 95 | matrix: ${{ needs.constants.outputs.matrix-test }} 96 | perform-check: false 97 | check_onnx_to_axon_bench: 98 | name: Check OnnxToAxonBench 99 | needs: [constants, check_http_downloader] 100 | uses: ./.github/workflows/reusable_ci.yml 101 | with: 102 | working-directory: benchmarks/onnx_to_axon_bench 103 | os: ubuntu-22.04 104 | matrix: ${{ needs.constants.outputs.matrix-for-check }} 105 | perform-check: true 106 | test_ubuntu_22_onnx_to_axon_bench: 107 | name: Test OnnxToAxonBench (Ubuntu 22.04) 108 | needs: [constants, check_onnx_to_axon_bench] 109 | uses: ./.github/workflows/reusable_ci.yml 110 | with: 111 | working-directory: benchmarks/onnx_to_axon_bench 112 | os: ubuntu-22.04 113 | matrix: ${{ needs.constants.outputs.matrix-test }} 114 | perform-check: false 115 | test_ubuntu_24_onnx_to_axon_bench: 116 | name: Test OnnxToAxonBench (Ubuntu 24.04) 117 | needs: [constants, check_onnx_to_axon_bench] 118 | uses: ./.github/workflows/reusable_ci.yml 119 | with: 120 | working-directory: benchmarks/onnx_to_axon_bench 121 | os: ubuntu-24.04 122 | matrix: ${{ needs.constants.outputs.matrix-test }} 123 | perform-check: false 124 | check_distributed_computing_bench: 125 | name: Check DistributedComputingBench 126 | needs: [constants, check_http_downloader] 127 | uses: ./.github/workflows/reusable_ci.yml 128 | with: 129 | working-directory: benchmarks/distributed_computing_bench 130 | os: ubuntu-22.04 131 | matrix: ${{ needs.constants.outputs.matrix-for-check }} 132 | perform-check: true 133 | test_ubuntu_22_distributed_computing_bench: 134 | name: Test DistributedComputingBench (Ubuntu 22.04) 135 | needs: [constants, check_distributed_computing_bench] 136 | uses: ./.github/workflows/reusable_ci.yml 137 | with: 138 | working-directory: benchmarks/distributed_computing_bench 139 | os: ubuntu-22.04 140 | matrix: ${{ needs.constants.outputs.matrix-test }} 141 | perform-check: false 142 | test_ubuntu_24_distributed_computing_bench: 143 | name: Test DistributedComputingBench (Ubuntu 24.04) 144 | needs: [constants, check_distributed_computing_bench] 145 | uses: ./.github/workflows/reusable_ci.yml 146 | with: 147 | working-directory: benchmarks/distributed_computing_bench 148 | os: ubuntu-24.04 149 | matrix: ${{ needs.constants.outputs.matrix-test }} 150 | perform-check: false 151 | 152 | -------------------------------------------------------------------------------- /.github/workflows/ci_node_activator.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # CI 5 | 6 | name: Elixir CI (NodeActivator) 7 | 8 | on: 9 | pull_request: 10 | types: [opened, reopened, synchronize] 11 | branches: [ "develop", "check_by_SHR" ] 12 | paths: 13 | - 'utilities/node_activator/**' 14 | - '!utilities/spawn_co_elixir/**' 15 | - '!benchmarks/distributed_computing_bench/**' 16 | - '!.github/workflows/*' 17 | - '.github/workflows/ci_node_activator.yml' 18 | - '.github/workflows/reusable_ci.yml' 19 | - '.github/actions/matrix_check.yml' 20 | - '.github/actions/matrix_test.yml' 21 | - '.github/actions/matrix_reduced_test_1.yml' 22 | - '.github/actions/matrix_reduced_test_2.yml' 23 | - '!**/*.md' 24 | - '!**/LICENSE*' 25 | - '!*.md' 26 | - '!*.cff' 27 | - '!LICENSE*' 28 | - '!publish.exs' 29 | push: 30 | branches: [ "main", "develop", "check_by_SHR" ] 31 | paths: 32 | - 'utilities/node_activator/**' 33 | - '!utilities/spawn_co_elixir/**' 34 | - '!benchmarks/distributed_computing_bench/**' 35 | - '!.github/workflows/*' 36 | - '.github/workflows/ci_node_activator.yml' 37 | - '.github/workflows/reusable_ci.yml' 38 | - '.github/actions/matrix_check.yml' 39 | - '.github/actions/matrix_test.yml' 40 | - '.github/actions/matrix_reduced_test_1.yml' 41 | - '.github/actions/matrix_reduced_test_2.yml' 42 | - '!**/*.md' 43 | - '!**/LICENSE*' 44 | - '!*.md' 45 | - '!*.cff' 46 | - '!LICENSE*' 47 | - '!publish.exs' 48 | 49 | concurrency: 50 | group: ${{ github.workflow }}-${{ github.ref }} 51 | cancel-in-progress: true 52 | 53 | permissions: 54 | contents: read 55 | 56 | jobs: 57 | constants: 58 | name: Constants 59 | if: ${{ github.actor != 'dependabot[bot]' }} 60 | runs-on: ubuntu-22.04 61 | outputs: 62 | matrix-for-check: ${{ steps.set-matrix-for-check.outputs.matrix }} 63 | matrix-test: ${{ steps.set-matrix-test.outputs.matrix }} 64 | matrix-reduced-test-1: ${{ steps.set-matrix-reduced-test-1.outputs.matrix }} 65 | matrix-reduced-test-2: ${{ steps.set-matrix-reduced-test-2.outputs.matrix }} 66 | steps: 67 | - uses: actions/checkout@v4 68 | - id: set-matrix-for-check 69 | run: | 70 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_check.yml| ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 71 | echo "matrix=${json}" >> $GITHUB_OUTPUT 72 | - id: set-matrix-test 73 | run: | 74 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_test.yml | ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 75 | echo "matrix=${json}" >> $GITHUB_OUTPUT 76 | - id: set-matrix-reduced-test-1 77 | run: | 78 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_reduced_test_1.yml | ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 79 | echo "matrix=${json}" >> $GITHUB_OUTPUT 80 | - id: set-matrix-reduced-test-2 81 | run: | 82 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_reduced_test_2.yml | ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 83 | echo "matrix=${json}" >> $GITHUB_OUTPUT 84 | check_node_activator: 85 | name: Check NodeActivator 86 | needs: constants 87 | uses: ./.github/workflows/reusable_ci.yml 88 | with: 89 | working-directory: utilities/node_activator 90 | os: ubuntu-22.04 91 | matrix: ${{ needs.constants.outputs.matrix-for-check }} 92 | perform-check: true 93 | test_ubuntu_22_node_activator: 94 | name: Test NodeActivator (Ubuntu 22.04) 95 | needs: [constants, check_node_activator] 96 | uses: ./.github/workflows/reusable_ci.yml 97 | with: 98 | working-directory: utilities/node_activator 99 | os: ubuntu-22.04 100 | matrix: ${{ needs.constants.outputs.matrix-test }} 101 | perform-check: false 102 | test_ubuntu_24_node_activator: 103 | name: Test NodeActivator (Ubuntu 24.04) 104 | needs: [constants, check_node_activator] 105 | uses: ./.github/workflows/reusable_ci.yml 106 | with: 107 | working-directory: utilities/node_activator 108 | os: ubuntu-24.04 109 | matrix: ${{ needs.constants.outputs.matrix-test }} 110 | perform-check: false 111 | test_ubuntu_22_spawn_co_elixir: 112 | name: Test SpawnCoElixir (Ubuntu 22.04) 113 | needs: [constants, test_ubuntu_22_node_activator] 114 | uses: ./.github/workflows/reusable_ci.yml 115 | with: 116 | working-directory: utilities/spawn_co_elixir 117 | os: ubuntu-22.04 118 | matrix: ${{ needs.constants.outputs.matrix-test }} 119 | perform-check: false 120 | test_ubuntu_24_spawn_co_elixir: 121 | name: Test SpawnCoElixir (Ubuntu 24.04) 122 | needs: [constants, test_ubuntu_24_node_activator] 123 | uses: ./.github/workflows/reusable_ci.yml 124 | with: 125 | working-directory: utilities/spawn_co_elixir 126 | os: ubuntu-24.04 127 | matrix: ${{ needs.constants.outputs.matrix-test }} 128 | perform-check: false 129 | test_ubuntu_22_distribued_computing_bench: 130 | name: Test DistributedComputingBench (Ubuntu 22.04) 131 | needs: [constants, test_ubuntu_22_node_activator] 132 | uses: ./.github/workflows/reusable_ci.yml 133 | with: 134 | working-directory: benchmarks/distributed_computing_bench 135 | os: ubuntu-22.04 136 | matrix: ${{ needs.constants.outputs.matrix-test }} 137 | perform-check: false 138 | test_ubuntu_24_distribued_computing_bench: 139 | name: Test DistributedComputingBench (Ubuntu 24.04) 140 | needs: [constants, test_ubuntu_24_node_activator] 141 | uses: ./.github/workflows/reusable_ci.yml 142 | with: 143 | working-directory: benchmarks/distributed_computing_bench 144 | os: ubuntu-24.04 145 | matrix: ${{ needs.constants.outputs.matrix-test }} 146 | perform-check: false 147 | -------------------------------------------------------------------------------- /.github/workflows/ci_pelemay_backend.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # CI 5 | 6 | name: Elixir CI (PelemayBackend) 7 | 8 | on: 9 | pull_request: 10 | types: [opened, reopened, synchronize] 11 | branches: [ "develop", "check_by_SHR" ] 12 | paths: 13 | - "backends/pelemay_backend/**" 14 | - "!benchmarks/onnx_to_axon_bench/**" 15 | - "!benchmarks/distributed_computing_bench/**" 16 | - "!.github/workflows/*" 17 | - ".github/workflows/ci_pelemay_backend.yml" 18 | - ".github/workflows/reusable_ci.yml" 19 | - ".github/actions/matrix_check.yml" 20 | - ".github/actions/matrix_test.yml" 21 | - "!**/*.md" 22 | - "!**/LICENSE*" 23 | - "!*.md" 24 | - "!*.cff" 25 | - "!LICENSE*" 26 | - "!publish.exs" 27 | push: 28 | branches: [ "main", "develop", "check_by_SHR" ] 29 | paths: 30 | - "utilities/http_downloader/**" 31 | - "!benchmarks/onnx_to_axon_bench/**" 32 | - "!benchmarks/distributed_computing_bench/**" 33 | - "!.github/workflows/*" 34 | - ".github/workflows/ci_http_downloader.yml" 35 | - ".github/workflows/reusable_ci.yml" 36 | - ".github/actions/matrix_check.yml" 37 | - ".github/actions/matrix_test.yml" 38 | - "!**/*.md" 39 | - "!**/LICENSE*" 40 | - "!*.md" 41 | - "!*.cff" 42 | - "!LICENSE*" 43 | - "!publish.exs" 44 | 45 | concurrency: 46 | group: ${{ github.workflow }}-${{ github.ref }} 47 | cancel-in-progress: true 48 | 49 | permissions: 50 | contents: read 51 | 52 | jobs: 53 | constants: 54 | name: Constants 55 | if: ${{ github.actor != 'dependabot[bot]' }} 56 | runs-on: ubuntu-22.04 57 | outputs: 58 | matrix-for-check: ${{ steps.set-matrix-for-check.outputs.matrix }} 59 | matrix-test: ${{ steps.set-matrix-test.outputs.matrix }} 60 | steps: 61 | - uses: actions/checkout@v4 62 | - id: set-matrix-for-check 63 | run: | 64 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_check.yml| ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 65 | echo "matrix=${json}" >> $GITHUB_OUTPUT 66 | - id: set-matrix-test 67 | run: | 68 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_test.yml | ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 69 | echo "matrix=${json}" >> $GITHUB_OUTPUT 70 | check_pelemay_backend: 71 | name: Check PelemayBackend 72 | needs: constants 73 | uses: ./.github/workflows/reusable_ci.yml 74 | with: 75 | working-directory: backends/pelemay_backend 76 | os: ubuntu-22.04 77 | matrix: ${{ needs.constants.outputs.matrix-for-check }} 78 | perform-check: true 79 | test_ubuntu_22_pelemay_backend: 80 | name: Test PelemayBackend (Ubuntu 22.04) 81 | needs: [constants, check_pelemay_backend] 82 | uses: ./.github/workflows/reusable_ci.yml 83 | with: 84 | working-directory: backends/pelemay_backend 85 | os: ubuntu-22.04 86 | matrix: ${{ needs.constants.outputs.matrix-test }} 87 | perform-check: false 88 | test_ubuntu_24_pelemay_backend: 89 | name: Test PelemayBackend (Ubuntu 24.04) 90 | needs: [constants, check_pelemay_backend] 91 | uses: ./.github/workflows/reusable_ci.yml 92 | with: 93 | working-directory: backends/pelemay_backend 94 | os: ubuntu-24.04 95 | matrix: ${{ needs.constants.outputs.matrix-test }} 96 | perform-check: false 97 | -------------------------------------------------------------------------------- /.github/workflows/ci_spawn_co_elixir.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # CI 5 | 6 | name: Elixir CI (SpawnCoElixir) 7 | 8 | on: 9 | pull_request: 10 | types: [opened, reopened, synchronize] 11 | branches: [ "develop", "check_by_SHR" ] 12 | paths: 13 | - 'utilities/spawn_co_elixir/**' 14 | - '!benchmarks/distributed_computing_bench/**' 15 | - '!.github/workflows/*' 16 | - '.github/workflows/ci_spawn_co_elixir.yml' 17 | - '.github/workflows/reusable_ci.yml' 18 | - '.github/actions/matrix_check.yml' 19 | - '.github/actions/matrix_test.yml' 20 | - '.github/actions/matrix_reduced_test_1.yml' 21 | - '.github/actions/matrix_reduced_test_2.yml' 22 | - '!**/*.md' 23 | - '!**/LICENSE*' 24 | - '!*.md' 25 | - '!*.cff' 26 | - '!LICENSE*' 27 | - '!publish.exs' 28 | push: 29 | branches: [ "main", "develop", "check_by_SHR" ] 30 | paths: 31 | - 'utilities/spawn_co_elixir/**' 32 | - '!benchmarks/distributed_computing_bench/**' 33 | - '!.github/workflows/*' 34 | - '.github/workflows/ci_spawn_co_elixir.yml' 35 | - '.github/workflows/reusable_ci.yml' 36 | - '.github/actions/matrix_check.yml' 37 | - '.github/actions/matrix_test.yml' 38 | - '.github/actions/matrix_reduced_test_1.yml' 39 | - '.github/actions/matrix_reduced_test_2.yml' 40 | - '!**/*.md' 41 | - '!**/LICENSE*' 42 | - '!*.md' 43 | - '!*.cff' 44 | - '!LICENSE*' 45 | - '!publish.exs' 46 | 47 | concurrency: 48 | group: ${{ github.workflow }}-${{ github.ref }} 49 | cancel-in-progress: true 50 | 51 | permissions: 52 | contents: read 53 | 54 | jobs: 55 | constants: 56 | name: Constants 57 | if: ${{ github.actor != 'dependabot[bot]' }} 58 | runs-on: ubuntu-22.04 59 | outputs: 60 | matrix-for-check: ${{ steps.set-matrix-for-check.outputs.matrix }} 61 | matrix-test: ${{ steps.set-matrix-test.outputs.matrix }} 62 | matrix-reduced-test-1: ${{ steps.set-matrix-reduced-test-1.outputs.matrix }} 63 | matrix-reduced-test-2: ${{ steps.set-matrix-reduced-test-2.outputs.matrix }} 64 | steps: 65 | - uses: actions/checkout@v4 66 | - id: set-matrix-for-check 67 | run: | 68 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_check.yml| ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 69 | echo "matrix=${json}" >> $GITHUB_OUTPUT 70 | - id: set-matrix-test 71 | run: | 72 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_test.yml | ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 73 | echo "matrix=${json}" >> $GITHUB_OUTPUT 74 | - id: set-matrix-reduced-test-1 75 | run: | 76 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_reduced_test_1.yml | ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 77 | echo "matrix=${json}" >> $GITHUB_OUTPUT 78 | - id: set-matrix-reduced-test-2 79 | run: | 80 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_reduced_test_2.yml | ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 81 | echo "matrix=${json}" >> $GITHUB_OUTPUT 82 | check_spawn_co_elixir: 83 | name: Check SpawnCoElixir 84 | needs: constants 85 | uses: ./.github/workflows/reusable_ci.yml 86 | with: 87 | working-directory: utilities/spawn_co_elixir 88 | os: ubuntu-22.04 89 | matrix: ${{ needs.constants.outputs.matrix-for-check }} 90 | perform-check: true 91 | test_ubuntu_22_spawn_co_elixir: 92 | name: Test SpawnCoElixir (Ubuntu 22.04) 93 | needs: [constants, check_spawn_co_elixir] 94 | uses: ./.github/workflows/reusable_ci.yml 95 | with: 96 | working-directory: utilities/spawn_co_elixir 97 | os: ubuntu-22.04 98 | matrix: ${{ needs.constants.outputs.matrix-test }} 99 | perform-check: false 100 | test_ubuntu_24_spawn_co_elixir: 101 | name: Test SpawnCoElixir (Ubuntu 24.04) 102 | needs: [constants, check_spawn_co_elixir] 103 | uses: ./.github/workflows/reusable_ci.yml 104 | with: 105 | working-directory: utilities/spawn_co_elixir 106 | os: ubuntu-24.04 107 | matrix: ${{ needs.constants.outputs.matrix-test }} 108 | perform-check: false 109 | test_ubuntu_22_distribued_computing_bench: 110 | name: Test DistributedComputingBench (Ubuntu 22.04) 111 | needs: [constants, test_ubuntu_22_spawn_co_elixir] 112 | uses: ./.github/workflows/reusable_ci.yml 113 | with: 114 | working-directory: benchmarks/distributed_computing_bench 115 | os: ubuntu-22.04 116 | matrix: ${{ needs.constants.outputs.matrix-test }} 117 | perform-check: false 118 | test_ubuntu_24_distribued_computing_bench: 119 | name: Test DistributedComputingBench (Ubuntu 24.04) 120 | needs: [constants, test_ubuntu_24_spawn_co_elixir] 121 | uses: ./.github/workflows/reusable_ci.yml 122 | with: 123 | working-directory: benchmarks/distributed_computing_bench 124 | os: ubuntu-24.04 125 | matrix: ${{ needs.constants.outputs.matrix-test }} 126 | perform-check: false 127 | -------------------------------------------------------------------------------- /.github/workflows/cleanup_all_cache.yml: -------------------------------------------------------------------------------- 1 | name: cleanup all caches 2 | on: 3 | workflow_dispatch: 4 | 5 | jobs: 6 | cleanup: 7 | runs-on: ubuntu-22.04 8 | steps: 9 | - name: Cleanup 10 | run: | 11 | gh extension install actions/gh-actions-cache 12 | 13 | set +e 14 | echo "Deleting caches..." 15 | gh actions-cache list -R $REPO -L 100 | while IFS=$'\t' read -r cacheKey _ branch _ 16 | do 17 | gh actions-cache delete "$cacheKey" -R $REPO -B "$branch" --confirm 18 | done 19 | echo "Done" 20 | env: 21 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 22 | REPO: ${{ github.repository }} -------------------------------------------------------------------------------- /.github/workflows/dependabot_auto_merge.yml: -------------------------------------------------------------------------------- 1 | name: Dependabot auto merge 2 | on: 3 | pull_request: 4 | paths: 5 | - '**/*' 6 | - '!.github/workflows/*' 7 | - '.github/workflows/dependabot_auto_merge.yml' 8 | - '.github/workflows/reusable_ci_with_working_directory.yml' 9 | - '.github/actions/matrix_dependabot.yml' 10 | - '!**/*.md' 11 | - '!**/LICENSE*' 12 | - '!*.md' 13 | - '!*.cff' 14 | - '!LICENSE*' 15 | - '!publish.exs' 16 | 17 | concurrency: 18 | group: ${{ github.workflow }}-${{ github.ref }} 19 | cancel-in-progress: true 20 | 21 | permissions: 22 | contents: write 23 | pull-requests: write 24 | 25 | jobs: 26 | constants: 27 | name: Constants 28 | runs-on: ubuntu-22.04 29 | if: ${{ github.actor == 'dependabot[bot]' || github.event.action == 'synchronize' && startsWith( github.head_ref, 'dependabot' ) }} 30 | outputs: 31 | matrix-for-dependabot: ${{ steps.set-matrix-for-dependabot.outputs.matrix }} 32 | steps: 33 | - uses: actions/checkout@v4 34 | - id: set-matrix-for-dependabot 35 | run: | 36 | json=$(cat ${{ github.workspace }}/.github/actions/matrix_dependabot.yml| ruby -ryaml -rjson -e 'puts YAML.load(STDIN).to_json') 37 | echo "matrix=${json}" >> $GITHUB_OUTPUT 38 | check_matrix: 39 | name: Check DistributedComputingBench 40 | needs: constants 41 | uses: ./.github/workflows/reusable_ci_with_working_directory.yml 42 | with: 43 | os: ubuntu-22.04 44 | matrix: ${{ needs.constants.outputs.matrix-for-dependabot }} 45 | perform-check: true 46 | test_ubuntu_22_matrix: 47 | name: Test DistributedComputingBench (Ubuntu 22.04) 48 | needs: [constants, check_matrix] 49 | uses: ./.github/workflows/reusable_ci_with_working_directory.yml 50 | with: 51 | os: ubuntu-22.04 52 | matrix: ${{ needs.constants.outputs.matrix-for-dependabot }} 53 | perform-check: false 54 | dependabot: 55 | runs-on: ubuntu-22.04 56 | permissions: write-all 57 | needs: [constants, check_matrix, test_ubuntu_22_matrix] 58 | if: ${{ github.actor == 'dependabot[bot]' || github.event.action == 'synchronize' && startsWith( github.head_ref, 'dependabot' ) }} 59 | steps: 60 | - name: Dependabot metadata 61 | if: ${{ github.actor == 'dependabot[bot]' }} 62 | id: metadata 63 | uses: dependabot/fetch-metadata@v2 64 | with: 65 | github-token: "${{ secrets.GITHUB_TOKEN }}" 66 | - name: Change merge branch for Dependabot PR 67 | run: | 68 | gh pr edit "$PR_URL" --base 'check_by_SHR' 69 | env: 70 | PR_URL: ${{ github.event.pull_request.html_url }} 71 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 72 | - name: Approve and enable auto-merge for Dependabot PRs 73 | if: ${{ ( steps.metadata.outputs.package-ecosystem == 'hex' && steps.metadata.outputs.update-type == 'version-update:semver-patch' ) || steps.metadata.outputs.package-ecosystem == 'github-actions' }} 74 | run: | 75 | gh pr review --approve "$PR_URL" 76 | gh pr edit "$PR_URL" -t "(auto merged) $PR_TITLE" 77 | gh pr merge --auto --merge "$PR_URL" 78 | env: 79 | PR_URL: ${{ github.event.pull_request.html_url }} 80 | PR_TITLE: ${{ github.event.pull_request.title }} 81 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.github/workflows/reusable_ci.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # CI 5 | 6 | name: Reusable Elixir CI 7 | 8 | on: 9 | workflow_call: 10 | inputs: 11 | working-directory: 12 | required: true 13 | type: string 14 | os: 15 | required: true 16 | type: string 17 | matrix: 18 | required: true 19 | type: string 20 | perform-check: 21 | required: true 22 | type: boolean 23 | 24 | env: 25 | XLA_HTTP_HEADERS: "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" 26 | 27 | jobs: 28 | elixir_ci: 29 | 30 | name: On ${{ matrix.elixir-version }}, ${{ matrix.otp-version }} 31 | runs-on: ${{ inputs.os }} 32 | strategy: 33 | matrix: ${{ fromJSON(inputs.matrix) }} 34 | defaults: 35 | run: 36 | working-directory: ${{ inputs.working-directory }} 37 | steps: 38 | - uses: actions/checkout@v4 39 | - uses: kenchan0130/actions-system-info@master 40 | id: system-info 41 | - name: Set up OTP MAJOR and MINOR VERSION 42 | run: | 43 | echo "OTP_MAJOR_VERSION=$(echo ${{ matrix.otp-version }} | sed -e 's/^\([^\.]*\)\.\(.*\)$/\1/')" >> $GITHUB_ENV 44 | echo "OTP_MINOR_VERSION=$(echo ${{ matrix.otp-version }} | sed -e 's/^\([^\.]*\)\.\([^\.]*\).*$/\2/')" >> $GITHUB_ENV 45 | - name: Set versions Elixir and OTP 46 | run: | 47 | echo "erlang ${{ matrix.otp-version }}" >> ${{ github.workspace }}/.tool-versions 48 | echo "elixir ${{ matrix.elixir-version }}-otp-${{ env.OTP_MAJOR_VERSION }}" >> ${{ github.workspace }}/.tool-versions 49 | - name: Set up Elixir 50 | continue-on-error: true 51 | id: set_up_elixir_by_setup-beam 52 | uses: erlef/setup-beam@v1 53 | with: 54 | elixir-version: ${{ matrix.elixir-version }} 55 | otp-version: ${{ matrix.otp-version }} 56 | - name: Install asdf 57 | continue-on-error: true 58 | if: ${{ steps.set_up_elixir_by_setup-beam.outcome == 'failure' }} 59 | id: install_asdf 60 | uses: asdf-vm/actions/setup@v3 61 | - name: Restore .asdf 62 | if: ${{ steps.install_asdf.outcome == 'success' }} 63 | id: asdf-cache 64 | uses: actions/cache@v4 65 | with: 66 | path: | 67 | ~/.asdf/ 68 | key: ${{ runner.os }}-${{ steps.system-info.outputs.release }}-Elixir-${{ matrix.elixir-version }}-OTP-${{ matrix.otp-version }}-asdf-${{ hashFiles('**/.tool-versions') }} 69 | restore-keys: ${{ runner.os }}-${{ steps.system-info.outputs.release }}-Elixir-${{ matrix.elixir-version }}-OTP-${{ matrix.otp-version }}-asdf- 70 | - name: Set up Elixir by asdf (Ubuntu) 71 | id: install_by_asdf 72 | continue-on-error: true 73 | if: ${{ steps.set_up_elixir_by_setup-beam.outcome == 'failure' }} 74 | uses: asdf-vm/actions/install@v3 75 | with: 76 | before_install: | 77 | sudo apt -y install build-essential automake autoconf git squashfs-tools ssh-askpass pkg-config curl libmnl-dev 78 | - name: Recover if fail 79 | if: steps.install_by_asdf.outcome == 'failure' 80 | run: | 81 | echo "erlang ${{ matrix.otp-version }}" > ${{ github.workspace }}/.tool-versions 82 | echo "elixir ${{ matrix.elixir-version }}-otp-$((${{ env.OTP_MAJOR_VERSION }}-1))" > ${{ github.workspace }}/.tool-versions 83 | - name: Set up Elixir by asdf, again (Ubuntu) 84 | if: steps.install_by_asdf.outcome == 'failure' 85 | uses: asdf-vm/actions/install@v3 86 | with: 87 | before_install: | 88 | sudo apt -y install build-essential automake autoconf git squashfs-tools ssh-askpass pkg-config curl libmnl-dev 89 | - name: Restore dependencies cache 90 | uses: actions/cache@v4 91 | id: dependencies-cache 92 | with: 93 | path: ${{ github.workspace }}/${{ inputs.working-directory }}/deps 94 | key: ${{ runner.os }}-${{ steps.system-info.outputs.release }}-Elixir-${{ matrix.elixir-version }}-OTP-${{ matrix.otp-version }}-${{ hashFiles('**/mix.lock') }} 95 | restore-keys: ${{ runner.os }}-${{ steps.system-info.outputs.release }}-Elixir-${{ matrix.elixir-version }}-OTP-${{ matrix.otp-version }}- 96 | - name: Set up hex and rebar 97 | run: | 98 | mix local.hex --force 99 | mix local.rebar --force 100 | - name: Install dependencies 101 | run: mix deps.get 102 | - name: Compile and check warning 103 | if: ${{ inputs.perform-check }} 104 | run: mix compile --warnings-as-errors 105 | - name: Check formatting (Ubuntu, macOS) 106 | if: ${{ inputs.perform-check && !startsWith(runner.os, 'windows') }} 107 | run: mix format --check-formatted 108 | - name: Check by credo (Ubuntu) 109 | if: ${{ inputs.perform-check && startsWith(runner.os, 'linux') }} 110 | run: mix credo 111 | - name: Restore PLT cache 112 | id: plt_cache 113 | uses: actions/cache/restore@v4 114 | with: 115 | key: | 116 | plt-${{ runner.os }}-${{ steps.system-info.outputs.release }}-${{ matrix.otp-version }}-${{ matrix.elixir-version }}-${{ inputs.working-directory }}-${{ hashFiles('**/mix.lock') }} 117 | restore-keys: | 118 | plt-${{ runner.os }}-${{ steps.system-info.outputs.release }}-${{ matrix.otp-version }}-${{ matrix.elixir-version }}-${{ inputs.working-directory }}- 119 | path: | 120 | ${{ github.workspace }}/${{ inputs.working-directory }}/_build/test/dialyxir_erlang-${{ matrix.otp-version }}_elixir-${{ matrix.elixir-version }}_deps-test.plt 121 | - name: Create PLTs 122 | if: steps.plt_cache.outputs.cache-hit != 'true' && ${{ inputs.perform-check && startsWith(runner.os, 'linux') }} 123 | run: mix dialyzer --plt 124 | - name: Save PLT cache 125 | id: plt_cache_save 126 | uses: actions/cache/save@v4 127 | if: steps.plt_cache.outputs.cache-hit != 'true' && ${{ inputs.perform-check && startsWith(runner.os, 'linux') }} 128 | with: 129 | key: | 130 | plt-${{ runner.os }}-${{ steps.system-info.outputs.release }}-${{ matrix.otp-version }}-${{ matrix.elixir-version }}-${{ inputs.working-directory }}-${{ hashFiles('**/mix.lock') }} 131 | path: | 132 | ${{ github.workspace }}/${{ inputs.working-directory }}/_build/test/dialyxir_erlang-${{ matrix.otp-version }}_elixir-${{ matrix.elixir-version }}_deps-test.plt 133 | - name: Check by dialyzer (Ubuntu) 134 | id: dialyzer 135 | if: ${{ inputs.perform-check && startsWith(runner.os, 'linux') }} 136 | continue-on-error: true 137 | run: mix dialyzer --format github 138 | - name: Run tests 139 | if: ${{ !inputs.perform-check }} 140 | run: mix test 141 | -------------------------------------------------------------------------------- /.github/workflows/reusable_ci_for_self_hosted_runner_macos.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # CI 5 | 6 | name: Reusable Elixir CI 7 | 8 | on: 9 | workflow_call: 10 | inputs: 11 | matrix: 12 | required: true 13 | type: string 14 | arch: 15 | required: false 16 | type: string 17 | default: "none" 18 | 19 | env: 20 | XLA_HTTP_HEADERS: "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" 21 | 22 | jobs: 23 | elixir_ci: 24 | 25 | name: On ${{ inputs.arch }}, ${{ matrix.working-directory }}, ${{ matrix.elixir-version }}, ${{ matrix.otp-version }} 26 | runs-on: [self-hosted, macOS] 27 | strategy: 28 | matrix: ${{ fromJSON(inputs.matrix) }} 29 | defaults: 30 | run: 31 | working-directory: ${{ matrix.working-directory }} 32 | steps: 33 | - uses: actions/checkout@v4 34 | - uses: kenchan0130/actions-system-info@master 35 | id: system-info 36 | - name: Set up OTP MAJOR and MINOR VERSION 37 | run: | 38 | echo "OTP_MAJOR_VERSION=$(echo ${{ matrix.otp-version }} | sed -e 's/^\([^\.]*\)\.\(.*\)$/\1/')" >> $GITHUB_ENV 39 | echo "OTP_MINOR_VERSION=$(echo ${{ matrix.otp-version }} | sed -e 's/^\([^\.]*\)\.\([^\.]*\).*$/\2/')" >> $GITHUB_ENV 40 | - name: Set versions Elixir and OTP 41 | run: | 42 | echo "erlang ${{ matrix.otp-version }}" >> ${{ github.workspace }}/.tool-versions 43 | echo "elixir ${{ matrix.elixir-version }}-otp-${{ env.OTP_MAJOR_VERSION }}" >> ${{ github.workspace }}/.tool-versions 44 | - name: Set up Elixir by asdf (macOS) 45 | uses: asdf-vm/actions/install@v3 46 | id: install_by_asdf 47 | continue-on-error: true 48 | with: 49 | before_install: | 50 | brew install wxwidgets openjdk fop openssl@3 51 | export CC="/usr/bin/gcc -I$(brew --prefix unixodbc)/include" 52 | export LDFLAGS="-L$(brew --prefix unixodbc)/lib" 53 | echo 'setup CC and LDFLAGS' 54 | if [ ${{ env.OTP_MAJOR_VERSION }} -eq 25 ]; then 55 | if [ ${{ env.OTP_MINOR_VERSION }} -ge 1 ]; then 56 | export KERL_CONFIGURE_OPTIONS="--with-ssl=$(brew --prefix openssl@3) --with-odbc=$(brew --prefix unixodbc)" 57 | else 58 | export KERL_CONFIGURE_OPTIONS="--with-ssl=$(brew --prefix openssl@1.1) --with-odbc=$(brew --prefix unixodbc)" 59 | fi 60 | elif [ ${{ env.OTP_MAJOR_VERSION }} -ge 26 ]; then 61 | export KERL_CONFIGURE_OPTIONS="--with-ssl=$(brew --prefix openssl@3) --with-odbc=$(brew --prefix unixodbc)" 62 | else 63 | export KERL_CONFIGURE_OPTIONS="--with-ssl=$(brew --prefix openssl@1.1) --with-odbc=$(brew --prefix unixodbc)" 64 | fi 65 | echo "KERL_CONFIGURE_OPTIONS=$KERL_CONFIGURE_OPTIONS" 66 | ulimit -n 65536 67 | - name: Recover if fail 68 | if: steps.install_by_asdf.outcome == 'failure' 69 | run: | 70 | echo "erlang ${{ matrix.otp-version }}" > ${{ github.workspace }}/.tool-versions 71 | echo "elixir ${{ matrix.elixir-version }}-otp-$((${{ env.OTP_MAJOR_VERSION }}-1))" > ${{ github.workspace }}/.tool-versions 72 | - name: Set up Elixir by asdf, again (macOS) 73 | if: steps.install_by_asdf.outcome == 'failure' 74 | uses: asdf-vm/actions/install@v3 75 | with: 76 | before_install: | 77 | brew install wxwidgets openjdk fop openssl@3 78 | export CC="/usr/bin/gcc -I$(brew --prefix unixodbc)/include" 79 | export LDFLAGS="-L$(brew --prefix unixodbc)/lib" 80 | echo 'setup CC and LDFLAGS' 81 | if [ ${{ env.OTP_MAJOR_VERSION }} -eq 25 ]; then 82 | if [ ${{ env.OTP_MINOR_VERSION }} -ge 1 ]; then 83 | export KERL_CONFIGURE_OPTIONS="--with-ssl=$(brew --prefix openssl@3) --with-odbc=$(brew --prefix unixodbc)" 84 | else 85 | export KERL_CONFIGURE_OPTIONS="--with-ssl=$(brew --prefix openssl@1.1) --with-odbc=$(brew --prefix unixodbc)" 86 | fi 87 | elif [ ${{ env.OTP_MAJOR_VERSION }} -ge 26 ]; then 88 | export KERL_CONFIGURE_OPTIONS="--with-ssl=$(brew --prefix openssl@3) --with-odbc=$(brew --prefix unixodbc)" 89 | else 90 | export KERL_CONFIGURE_OPTIONS="--with-ssl=$(brew --prefix openssl@1.1) --with-odbc=$(brew --prefix unixodbc)" 91 | fi 92 | echo "KERL_CONFIGURE_OPTIONS=$KERL_CONFIGURE_OPTIONS" 93 | ulimit -n 65536 94 | - name: Set up hex and rebar (macOS) 95 | run: | 96 | mix local.hex --force 97 | mix local.rebar --force 98 | - name: fix issue of Erlang/OTP 26.2.3 99 | run: | 100 | mix archive.install github hexpm/hex branch latest --force 101 | - name: Install dependencies 102 | run: mix deps.get 103 | - name: Run tests 104 | run: mix test 105 | -------------------------------------------------------------------------------- /.github/workflows/reusable_ci_with_working_directory.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # CI 5 | 6 | name: Reusable Elixir CI 7 | 8 | on: 9 | workflow_call: 10 | inputs: 11 | os: 12 | required: true 13 | type: string 14 | matrix: 15 | required: true 16 | type: string 17 | perform-check: 18 | required: true 19 | type: boolean 20 | 21 | env: 22 | XLA_HTTP_HEADERS: "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" 23 | 24 | jobs: 25 | elixir_ci: 26 | 27 | name: On ${{ matrix.working-directory }}, ${{ matrix.elixir-version }}, ${{ matrix.otp-version }} 28 | runs-on: ${{ inputs.os }} 29 | strategy: 30 | matrix: ${{ fromJSON(inputs.matrix) }} 31 | defaults: 32 | run: 33 | working-directory: ${{ matrix.working-directory }} 34 | steps: 35 | - uses: actions/checkout@v4 36 | - uses: kenchan0130/actions-system-info@master 37 | id: system-info 38 | - name: Set up OTP MAJOR and MINOR VERSION 39 | run: | 40 | echo "OTP_MAJOR_VERSION=$(echo ${{ matrix.otp-version }} | sed -e 's/^\([^\.]*\)\.\(.*\)$/\1/')" >> $GITHUB_ENV 41 | echo "OTP_MINOR_VERSION=$(echo ${{ matrix.otp-version }} | sed -e 's/^\([^\.]*\)\.\([^\.]*\).*$/\2/')" >> $GITHUB_ENV 42 | - name: Set versions Elixir and OTP 43 | run: | 44 | echo "erlang ${{ matrix.otp-version }}" >> ${{ github.workspace }}/.tool-versions 45 | echo "elixir ${{ matrix.elixir-version }}-otp-${{ env.OTP_MAJOR_VERSION }}" >> ${{ github.workspace }}/.tool-versions 46 | - name: Set up Elixir 47 | continue-on-error: true 48 | id: set_up_elixir_by_setup-beam 49 | uses: erlef/setup-beam@v1 50 | with: 51 | elixir-version: ${{ matrix.elixir-version }} 52 | otp-version: ${{ matrix.otp-version }} 53 | - name: Install asdf 54 | continue-on-error: true 55 | if: ${{ steps.set_up_elixir_by_setup-beam.outcome == 'failure' }} 56 | id: install_asdf 57 | uses: asdf-vm/actions/setup@v3 58 | - name: Restore .asdf 59 | if: ${{ steps.install_asdf.outcome == 'success' }} 60 | id: asdf-cache 61 | uses: actions/cache@v4 62 | with: 63 | path: | 64 | ~/.asdf/ 65 | key: ${{ runner.os }}-${{ steps.system-info.outputs.release }}-Elixir-${{ matrix.elixir-version }}-OTP-${{ matrix.otp-version }}-asdf-${{ hashFiles('**/.tool-versions') }} 66 | restore-keys: ${{ runner.os }}-${{ steps.system-info.outputs.release }}-Elixir-${{ matrix.elixir-version }}-OTP-${{ matrix.otp-version }}-asdf- 67 | - name: Set up Elixir by asdf (Ubuntu) 68 | id: install_by_asdf 69 | continue-on-error: true 70 | if: ${{ steps.set_up_elixir_by_setup-beam.outcome == 'failure' }} 71 | uses: asdf-vm/actions/install@v3 72 | with: 73 | before_install: | 74 | sudo apt -y install build-essential automake autoconf git squashfs-tools ssh-askpass pkg-config curl libmnl-dev 75 | - name: Recover if fail 76 | if: steps.install_by_asdf.outcome == 'failure' 77 | run: | 78 | echo "erlang ${{ matrix.otp-version }}" > ${{ github.workspace }}/.tool-versions 79 | echo "elixir ${{ matrix.elixir-version }}-otp-$((${{ env.OTP_MAJOR_VERSION }}-1))" > ${{ github.workspace }}/.tool-versions 80 | - name: Set up Elixir by asdf, again (Ubuntu) 81 | if: steps.install_by_asdf.outcome == 'failure' 82 | uses: asdf-vm/actions/install@v3 83 | with: 84 | before_install: | 85 | sudo apt -y install build-essential automake autoconf git squashfs-tools ssh-askpass pkg-config curl libmnl-dev 86 | - name: Restore dependencies cache 87 | uses: actions/cache@v4 88 | id: dependencies-cache 89 | with: 90 | path: ${{ github.workspace }}/${{ matrix.working-directory }}/deps 91 | key: ${{ runner.os }}-${{ steps.system-info.outputs.release }}-Elixir-${{ matrix.elixir-version }}-OTP-${{ matrix.otp-version }}-${{ hashFiles('**/mix.lock') }} 92 | restore-keys: ${{ runner.os }}-${{ steps.system-info.outputs.release }}-Elixir-${{ matrix.elixir-version }}-OTP-${{ matrix.otp-version }}- 93 | - name: Set up hex and rebar 94 | run: | 95 | mix local.hex --force 96 | mix local.rebar --force 97 | - name: Install dependencies 98 | run: mix deps.get 99 | - name: Compile and check warning 100 | if: ${{ inputs.perform-check }} 101 | run: mix compile --warnings-as-errors 102 | - name: Check formatting (Ubuntu, macOS) 103 | if: ${{ inputs.perform-check && !startsWith(runner.os, 'windows') }} 104 | run: mix format --check-formatted 105 | - name: Check by credo (Ubuntu) 106 | if: ${{ inputs.perform-check && startsWith(runner.os, 'linux') }} 107 | run: mix credo 108 | - name: Restore PLT cache 109 | id: plt_cache 110 | uses: actions/cache/restore@v4 111 | with: 112 | key: | 113 | plt-${{ runner.os }}-${{ steps.system-info.outputs.release }}-${{ matrix.otp-version }}-${{ matrix.elixir-version }}-${{ inputs.working-directory }}-${{ hashFiles('**/mix.lock') }} 114 | restore-keys: | 115 | plt-${{ runner.os }}-${{ steps.system-info.outputs.release }}-${{ matrix.otp-version }}-${{ matrix.elixir-version }}-${{ inputs.working-directory }}- 116 | path: | 117 | ${{ github.workspace }}/${{ inputs.working-directory }}/_build/test/dialyxir_erlang-${{ matrix.otp-version }}_elixir-${{ matrix.elixir-version }}_deps-test.plt 118 | - name: Create PLTs 119 | if: steps.plt_cache.outputs.cache-hit != 'true' && ${{ inputs.perform-check && startsWith(runner.os, 'linux') }} 120 | run: mix dialyzer --plt 121 | - name: Save PLT cache 122 | id: plt_cache_save 123 | uses: actions/cache/save@v4 124 | if: steps.plt_cache.outputs.cache-hit != 'true' && ${{ inputs.perform-check && startsWith(runner.os, 'linux') }} 125 | with: 126 | key: | 127 | plt-${{ runner.os }}-${{ steps.system-info.outputs.release }}-${{ matrix.otp-version }}-${{ matrix.elixir-version }}-${{ inputs.working-directory }}-${{ hashFiles('**/mix.lock') }} 128 | path: | 129 | ${{ github.workspace }}/${{ inputs.working-directory }}/_build/test/dialyxir_erlang-${{ matrix.otp-version }}_elixir-${{ matrix.elixir-version }}_deps-test.plt 130 | - name: Check by dialyzer (Ubuntu) 131 | id: dialyzer 132 | if: ${{ inputs.perform-check && startsWith(runner.os, 'linux') }} 133 | continue-on-error: true 134 | run: mix dialyzer --format github 135 | - name: Run tests 136 | if: ${{ !inputs.perform-check }} 137 | run: mix test 138 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | demo-*.tar 24 | 25 | # Others 26 | .DS_Store 27 | -------------------------------------------------------------------------------- /CITATION.cff: -------------------------------------------------------------------------------- 1 | # This CITATION.cff file was generated with cffinit. 2 | # Visit https://bit.ly/cffinit to generate yours today! 3 | 4 | cff-version: 1.2.0 5 | title: >- 6 | PelemayBackend: A memory-saving, fault-tolerant and 7 | distributed collection of Nx compilers and backends for 8 | embedded systems. 9 | message: Please cite this software using these metadata. 10 | type: software 11 | authors: 12 | - given-names: Susumu 13 | family-names: Yamazaki 14 | email: zacky@kitakyu-u.ac.jp 15 | affiliation: University of Kitakyushu 16 | orcid: 'https://orcid.org/0009-0008-3972-4141' 17 | - given-names: Masatoshi 18 | family-names: Nishiguchi 19 | repository-code: 'https://github.com/zeam-vm/pelemay_backend' 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SUBDIRS := \ 2 | utilities/backend_decorator \ 3 | utilities/node_activator \ 4 | utilities/spawn_co_elixir \ 5 | utilities/http_downloader \ 6 | backends/pelemay_backend \ 7 | backends/logging_backend \ 8 | benchmarks/onnx_to_axon_bench \ 9 | benchmarks/distributed_computing_bench 10 | 11 | all: setup 12 | @for _dir in ${SUBDIRS}; do \ 13 | (cd $${_dir} && mix compile); \ 14 | done 15 | 16 | setup: 17 | @for _dir in ${SUBDIRS}; do \ 18 | (cd $${_dir} && mix deps.get); \ 19 | done 20 | 21 | test: all 22 | @for _dir in ${SUBDIRS}; do \ 23 | (cd $${_dir} && mix test); \ 24 | done 25 | 26 | format: 27 | @for _dir in ${SUBDIRS}; do \ 28 | (cd $${_dir} && mix format); \ 29 | done 30 | 31 | credo: 32 | @for _dir in ${SUBDIRS}; do \ 33 | (cd $${_dir} && mix credo); \ 34 | done 35 | 36 | dialyzer: 37 | @for _dir in ${SUBDIRS}; do \ 38 | (cd $${_dir} && mix dialyzer); \ 39 | done 40 | 41 | update: 42 | @for _dir in ${SUBDIRS}; do \ 43 | (cd $${_dir} && mix deps.update --all); \ 44 | done 45 | 46 | clean: 47 | @for _dir in ${SUBDIRS}; do \ 48 | (cd $${_dir} && echo "Cleaning in $${_dir}" && mix clean); \ 49 | done 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pelemay Backend (Collection) 2 | 3 | 4 | A memory-saving, fault-tolerant and distributed collection of Nx compilers and 5 | backends for embedded systems. 6 | 7 | 8 | This repository currently holds the following projects: 9 | 10 | Backends: 11 | 12 | * [`PelemayBackend`](https://github.com/zeam-vm/pelemay_backend/tree/main/backends/pelemay_backend#readme) (WIP) - A memory-saving, fault-tolerant and distributed collection of Nx compilers and backends for embedded systems. 13 | * [`LoggingBackend`](https://github.com/zeam-vm/pelemay_backend/blob/main/backends/logging_backend#readme) (WIP) - A backend to log the behavior of the specified `based_backend`. 14 | 15 | Utilities: 16 | 17 | * [`BackendDecorator`](https://github.com/zeam-vm/pelemay_backend/blob/main/utilities/backend_decorator#readme) (WIP) - A backend generator to decorate the specified `based_backend` with the functions before and after a set of functions in the backend. The set can be specified with the style of [AspectJ, which is an AOP language](https://en.wikipedia.org/wiki/Aspect-oriented_programming), and with grouping written in [hexdocs of Nx](https://hexdocs.pm/nx/Nx.html), for example, Aggregates, Backend, Conversion, and so on. 18 | * [`NodeActivator`](https://github.com/zeam-vm/pelemay_backend/blob/main/utilities/node_activator#readme) [![Hex.pm](https://img.shields.io/hexpm/v/node_activator.svg?style=flat&color=blue)](https://hex.pm/packages/node_activator) [![Elixir CI (NodeActivator) status](https://github.com/zeam-vm/pelemay_backend/actions/workflows/ci_node_activator.yml/badge.svg)](https://github.com/zeam-vm/pelemay_backend/actions/workflows/ci_node_activator.yml/badge.svg) - A module to activate VM nodes. 19 | * [`SpawnCoElixir`](https://github.com/zeam-vm/pelemay_backend/blob/main/utilities/spawn_co_elixir#readme) [![Hex.pm](https://img.shields.io/hexpm/v/spawn_co_elixir.svg?style=flat&color=blue)](https://hex.pm/packages/spawn_co_elixir) [![Elixir CI (SpawnCoElixir) status](https://github.com/zeam-vm/pelemay_backend/actions/workflows/ci_spawn_co_elixir.yml/badge.svg)](https://github.com/zeam-vm/pelemay_backend/actions/workflows/ci_spawn_co_elixir.yml/badge.svg) - SpawnCoElixir spawns cooperative Elixir nodes that are supervised. 20 | * [`HttpDownloader`](https://github.com/zeam-vm/pelemay_backend/blob/main/utilities/http_downloader#readme) [![Hex.pm](https://img.shields.io/hexpm/v/http_downloader.svg?style=flat&color=blue)](https://hex.pm/packages/http_downloader) [![Elixir CI (HttpDownloader) status](https://github.com/zeam-vm/pelemay_backend/actions/workflows/ci_http_downloader.yml/badge.svg)](https://github.com/zeam-vm/pelemay_backend/actions/workflows/ci_http_downloader.yml/badge.svg) - Downloads remote file with progress bar. 21 | 22 | 23 | Benchmarks: 24 | 25 | * [`DistributedComputingBench`](https://github.com/zeam-vm/pelemay_backend/blob/main/benchmarks/distributed_computing_bench#readme) [![Elixir CI (DistributedComputingBench) status](https://github.com/zeam-vm/pelemay_backend/actions/workflows/ci_distributed_computing_bench.yml/badge.svg)](https://github.com/zeam-vm/pelemay_backend/actions/workflows/ci_distributed_computing_bench.yml/badge.svg) 26 | 27 | Each has their own README, which you can access above to learn more. 28 | 29 | ## Supported Erlang/OTP and Elixir versions: 30 | 31 | Supported Erlang/OTP and Elixir versions: 32 | 33 | * OTP: 25, 26, 27 34 | * Elixir: 1.16, 1.17, 1.18 35 | 36 | ## Supported Platforms 37 | 38 | Tested Platforms by CI: 39 | 40 | * Ubuntu 22.04, 24.04 41 | 42 | Other manually tested platforms: 43 | 44 | * macOS 14 Sonoma (Apple Silicon and x86_64) 45 | * groovEPIC 46 | 47 | Not tested by CI: 48 | 49 | * macOS 13 Ventura and 12 Monterey (Apple Silicon and x86_64) 50 | 51 | Temporally not tested by CI of Nerves: 52 | 53 | * rpi4 54 | * rpi3a, rpi3, rpi2, rpi0, rpi 55 | * bbb 56 | * osd32mp1 57 | * npi_imx6ull 58 | * grisp2 59 | * mangopi_mq_pro 60 | 61 | Temporally unsupportted: 62 | 63 | * Windows 2022 64 | 65 | ## License 66 | 67 | Copyright (c) 2023 University of Kitakyushu 68 | 69 | Licensed under the Apache License, Version 2.0 (the "License"); 70 | you may not use this file except in compliance with the License. 71 | You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) 72 | 73 | Unless required by applicable law or agreed to in writing, software 74 | distributed under the License is distributed on an "AS IS" BASIS, 75 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 76 | See the License for the specific language governing permissions and 77 | limitations under the License. 78 | 79 | ## Acknowledgement 80 | 81 | This work was supported by Asahi Kohsan Group Research Support Program of Kitakyushu Foundation for the Advancement of Industry Science and Technology (FAIS). 82 | -------------------------------------------------------------------------------- /backends/logging_backend/.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /backends/logging_backend/.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | logging_backend-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /backends/logging_backend/README.md: -------------------------------------------------------------------------------- 1 | # LoggingBackend 2 | 3 | 4 | A backend to log the behavior of the specified `based_backend`. 5 | 6 | 7 | ## Installation 8 | 9 | ```elixir 10 | def deps do 11 | [ 12 | {:logging_backend, "~> 0.1.0-dev", github: "zeam-vm/pelemay_backend", sparse: "backends/logging_backend"}, 13 | {:backend_decorator, "~> 0.1.0-dev", github: "zeam-vm/pelemay_backend", sparse: "utilities/backend_decorator", override: true} 14 | ] 15 | end 16 | ``` 17 | 18 | ## License 19 | 20 | Copyright (c) 2023 University of Kitakyushu 21 | 22 | Licensed under the Apache License, Version 2.0 (the "License"); 23 | you may not use this file except in compliance with the License. 24 | You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) 25 | 26 | Unless required by applicable law or agreed to in writing, software 27 | distributed under the License is distributed on an "AS IS" BASIS, 28 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 29 | See the License for the specific language governing permissions and 30 | limitations under the License. 31 | 32 | ## Acknowledgement 33 | 34 | This work was supported by Asahi Kohsan Group Research Support Program of Kitakyushu Foundation for the Advancement of Industry Science and Technology (FAIS). 35 | -------------------------------------------------------------------------------- /backends/logging_backend/lib/logging_backend.ex: -------------------------------------------------------------------------------- 1 | defmodule LoggingBackend do 2 | @moduledoc File.read!("README.md") 3 | |> String.split("") 4 | |> Enum.fetch!(1) 5 | 6 | @doc """ 7 | Hello world. 8 | 9 | ## Examples 10 | 11 | iex> LoggingBackend.hello() 12 | :world 13 | 14 | """ 15 | def hello do 16 | :world 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /backends/logging_backend/mix.exs: -------------------------------------------------------------------------------- 1 | defmodule LoggingBackend.MixProject do 2 | use Mix.Project 3 | 4 | @version "0.1.0-dev" 5 | 6 | def project do 7 | [ 8 | app: :logging_backend, 9 | version: @version, 10 | elixir: "~> 1.14", 11 | start_permanent: Mix.env() == :prod, 12 | deps: deps() 13 | ] 14 | end 15 | 16 | # Run "mix help compile.app" to learn about applications. 17 | def application do 18 | [ 19 | extra_applications: [:logger] 20 | ] 21 | end 22 | 23 | # Run "mix help deps" to learn about dependencies. 24 | defp deps do 25 | [ 26 | {:dialyxir, "~> 1.3", only: [:dev], runtime: false}, 27 | {:credo, "~> 1.7", only: [:dev, :test], runtime: false}, 28 | {:backend_decorator, path: "../../utilities/backend_decorator"} 29 | ] 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /backends/logging_backend/mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, 3 | "complex": {:hex, :complex, "0.5.0", "af2d2331ff6170b61bb738695e481b27a66780e18763e066ee2cd863d0b1dd92", [:mix], [], "hexpm", "2683bd3c184466cfb94fad74cbfddfaa94b860e27ad4ca1bffe3bff169d91ef1"}, 4 | "credo": {:hex, :credo, "1.7.7", "771445037228f763f9b2afd612b6aa2fd8e28432a95dbbc60d8e03ce71ba4446", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "8bc87496c9aaacdc3f90f01b7b0582467b69b4bd2441fe8aae3109d843cc2f2e"}, 5 | "dialyxir": {:hex, :dialyxir, "1.4.3", "edd0124f358f0b9e95bfe53a9fcf806d615d8f838e2202a9f430d59566b6b53b", [:mix], [{:erlex, ">= 0.2.6", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "bf2cfb75cd5c5006bec30141b131663299c661a864ec7fbbc72dfa557487a986"}, 6 | "erlex": {:hex, :erlex, "0.2.6", "c7987d15e899c7a2f34f5420d2a2ea0d659682c06ac607572df55a43753aa12e", [:mix], [], "hexpm", "2ed2e25711feb44d52b17d2780eabf998452f6efda104877a3881c2f8c0c0c75"}, 7 | "file_system": {:hex, :file_system, "1.0.0", "b689cc7dcee665f774de94b5a832e578bd7963c8e637ef940cd44327db7de2cd", [:mix], [], "hexpm", "6752092d66aec5a10e662aefeed8ddb9531d79db0bc145bb8c40325ca1d8536d"}, 8 | "jason": {:hex, :jason, "1.4.1", "af1504e35f629ddcdd6addb3513c3853991f694921b1b9368b0bd32beb9f1b63", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "fbb01ecdfd565b56261302f7e1fcc27c4fb8f32d56eab74db621fc154604a7a1"}, 9 | "nx": {:hex, :nx, "0.5.3", "6ad5534f9b82429dafa12329952708c2fdd6ab01b306e86333fdea72383147ee", [:mix], [{:complex, "~> 0.5", [hex: :complex, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "d1072fc4423809ed09beb729e73c200ce177ddecac425d9eb6fba643669623ec"}, 10 | "telemetry": {:hex, :telemetry, "1.2.1", "68fdfe8d8f05a8428483a97d7aab2f268aaff24b49e0f599faa091f1d4e7f61c", [:rebar3], [], "hexpm", "dad9ce9d8effc621708f99eac538ef1cbe05d6a874dd741de2e689c47feafed5"}, 11 | } 12 | -------------------------------------------------------------------------------- /backends/logging_backend/test/logging_backend_test.exs: -------------------------------------------------------------------------------- 1 | defmodule LoggingBackendTest do 2 | use ExUnit.Case 3 | doctest LoggingBackend 4 | 5 | test "greets the world" do 6 | assert LoggingBackend.hello() == :world 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /backends/logging_backend/test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /backends/pelemay_backend/.credo.exs: -------------------------------------------------------------------------------- 1 | # This file contains the configuration for Credo and you are probably reading 2 | # this after creating it with `mix credo.gen.config`. 3 | # 4 | # If you find anything wrong or unclear in this file, please report an 5 | # issue on GitHub: https://github.com/rrrene/credo/issues 6 | # 7 | %{ 8 | # 9 | # You can have as many configs as you like in the `configs:` field. 10 | configs: [ 11 | %{ 12 | # 13 | # Run any config using `mix credo -C `. If no config name is given 14 | # "default" is used. 15 | # 16 | name: "default", 17 | # 18 | # These are the files included in the analysis: 19 | files: %{ 20 | # 21 | # You can give explicit globs or simply directories. 22 | # In the latter case `**/*.{ex,exs}` will be used. 23 | # 24 | included: [ 25 | "lib/", 26 | "src/", 27 | "test/", 28 | "web/", 29 | "apps/*/lib/", 30 | "apps/*/src/", 31 | "apps/*/test/", 32 | "apps/*/web/" 33 | ], 34 | excluded: [~r"/_build/", ~r"/deps/", ~r"/node_modules/"] 35 | }, 36 | # 37 | # Load and configure plugins here: 38 | # 39 | plugins: [], 40 | # 41 | # If you create your own checks, you must specify the source files for 42 | # them here, so they can be loaded by Credo before running the analysis. 43 | # 44 | requires: [], 45 | # 46 | # If you want to enforce a style guide and need a more traditional linting 47 | # experience, you can change `strict` to `true` below: 48 | # 49 | strict: false, 50 | # 51 | # To modify the timeout for parsing files, change this value: 52 | # 53 | parse_timeout: 5000, 54 | # 55 | # If you want to use uncolored output by default, you can change `color` 56 | # to `false` below: 57 | # 58 | color: true, 59 | # 60 | # You can customize the parameters of any check by adding a second element 61 | # to the tuple. 62 | # 63 | # To disable a check put `false` as second element: 64 | # 65 | # {Credo.Check.Design.DuplicatedCode, false} 66 | # 67 | checks: %{ 68 | enabled: [ 69 | # 70 | ## Consistency Checks 71 | # 72 | {Credo.Check.Consistency.ExceptionNames, []}, 73 | {Credo.Check.Consistency.LineEndings, []}, 74 | {Credo.Check.Consistency.ParameterPatternMatching, []}, 75 | {Credo.Check.Consistency.SpaceAroundOperators, []}, 76 | {Credo.Check.Consistency.SpaceInParentheses, []}, 77 | {Credo.Check.Consistency.TabsOrSpaces, []}, 78 | 79 | # 80 | ## Design Checks 81 | # 82 | # You can customize the priority of any check 83 | # Priority values are: `low, normal, high, higher` 84 | # 85 | {Credo.Check.Design.AliasUsage, 86 | [priority: :low, if_nested_deeper_than: 2, if_called_more_often_than: 0]}, 87 | {Credo.Check.Design.TagFIXME, []}, 88 | # You can also customize the exit_status of each check. 89 | # If you don't want TODO comments to cause `mix credo` to fail, just 90 | # set this value to 0 (zero). 91 | # 92 | {Credo.Check.Design.TagTODO, [exit_status: 2]}, 93 | 94 | # 95 | ## Readability Checks 96 | # 97 | {Credo.Check.Readability.AliasOrder, []}, 98 | {Credo.Check.Readability.FunctionNames, []}, 99 | {Credo.Check.Readability.LargeNumbers, []}, 100 | {Credo.Check.Readability.MaxLineLength, [priority: :low, max_length: 120]}, 101 | {Credo.Check.Readability.ModuleAttributeNames, []}, 102 | {Credo.Check.Readability.ModuleDoc, false}, 103 | {Credo.Check.Readability.ModuleNames, []}, 104 | {Credo.Check.Readability.ParenthesesInCondition, []}, 105 | {Credo.Check.Readability.ParenthesesOnZeroArityDefs, []}, 106 | {Credo.Check.Readability.PipeIntoAnonymousFunctions, []}, 107 | {Credo.Check.Readability.PredicateFunctionNames, []}, 108 | {Credo.Check.Readability.PreferImplicitTry, []}, 109 | {Credo.Check.Readability.RedundantBlankLines, []}, 110 | {Credo.Check.Readability.Semicolons, []}, 111 | {Credo.Check.Readability.SpaceAfterCommas, []}, 112 | {Credo.Check.Readability.StringSigils, []}, 113 | {Credo.Check.Readability.TrailingBlankLine, []}, 114 | {Credo.Check.Readability.TrailingWhiteSpace, []}, 115 | {Credo.Check.Readability.UnnecessaryAliasExpansion, []}, 116 | {Credo.Check.Readability.VariableNames, []}, 117 | {Credo.Check.Readability.WithSingleClause, []}, 118 | 119 | # 120 | ## Refactoring Opportunities 121 | # 122 | {Credo.Check.Refactor.Apply, false}, 123 | {Credo.Check.Refactor.CondStatements, false}, 124 | {Credo.Check.Refactor.CyclomaticComplexity, false}, 125 | {Credo.Check.Refactor.FilterCount, false}, 126 | {Credo.Check.Refactor.FilterFilter, false}, 127 | {Credo.Check.Refactor.FunctionArity, false}, 128 | {Credo.Check.Refactor.LongQuoteBlocks, false}, 129 | {Credo.Check.Refactor.MapJoin, false}, 130 | {Credo.Check.Refactor.MatchInCondition, false}, 131 | {Credo.Check.Refactor.NegatedConditionsInUnless, false}, 132 | {Credo.Check.Refactor.NegatedConditionsWithElse, false}, 133 | {Credo.Check.Refactor.Nesting, [max_nesting: 4]}, 134 | {Credo.Check.Refactor.RedundantWithClauseResult, false}, 135 | {Credo.Check.Refactor.RejectReject, false}, 136 | {Credo.Check.Refactor.UnlessWithElse, false}, 137 | {Credo.Check.Refactor.WithClauses, false}, 138 | 139 | # 140 | ## Warnings 141 | # 142 | {Credo.Check.Warning.ApplicationConfigInModuleAttribute, []}, 143 | {Credo.Check.Warning.BoolOperationOnSameValues, []}, 144 | {Credo.Check.Warning.Dbg, []}, 145 | {Credo.Check.Warning.ExpensiveEmptyEnumCheck, []}, 146 | {Credo.Check.Warning.IExPry, []}, 147 | {Credo.Check.Warning.IoInspect, []}, 148 | {Credo.Check.Warning.MissedMetadataKeyInLoggerConfig, []}, 149 | {Credo.Check.Warning.OperationOnSameValues, []}, 150 | {Credo.Check.Warning.OperationWithConstantResult, []}, 151 | {Credo.Check.Warning.RaiseInsideRescue, []}, 152 | {Credo.Check.Warning.SpecWithStruct, false}, 153 | {Credo.Check.Warning.UnsafeExec, []}, 154 | {Credo.Check.Warning.UnusedEnumOperation, []}, 155 | {Credo.Check.Warning.UnusedFileOperation, []}, 156 | {Credo.Check.Warning.UnusedKeywordOperation, []}, 157 | {Credo.Check.Warning.UnusedListOperation, []}, 158 | {Credo.Check.Warning.UnusedPathOperation, []}, 159 | {Credo.Check.Warning.UnusedRegexOperation, []}, 160 | {Credo.Check.Warning.UnusedStringOperation, []}, 161 | {Credo.Check.Warning.UnusedTupleOperation, []}, 162 | {Credo.Check.Warning.WrongTestFileExtension, []} 163 | ], 164 | disabled: [ 165 | # 166 | # Checks scheduled for next check update (opt-in for now) 167 | {Credo.Check.Refactor.UtcNowTruncate, false}, 168 | 169 | # 170 | # Controversial and experimental checks (opt-in, just move the check to `:enabled` 171 | # and be sure to use `mix credo --strict` to see low priority checks) 172 | # 173 | {Credo.Check.Consistency.MultiAliasImportRequireUse, []}, 174 | {Credo.Check.Consistency.UnusedVariableNames, []}, 175 | {Credo.Check.Design.DuplicatedCode, []}, 176 | {Credo.Check.Design.SkipTestWithoutComment, []}, 177 | {Credo.Check.Readability.AliasAs, []}, 178 | {Credo.Check.Readability.BlockPipe, []}, 179 | {Credo.Check.Readability.ImplTrue, []}, 180 | {Credo.Check.Readability.MultiAlias, []}, 181 | {Credo.Check.Readability.NestedFunctionCalls, []}, 182 | {Credo.Check.Readability.OneArityFunctionInPipe, []}, 183 | {Credo.Check.Readability.OnePipePerLine, []}, 184 | {Credo.Check.Readability.SeparateAliasRequire, []}, 185 | {Credo.Check.Readability.SingleFunctionToBlockPipe, []}, 186 | {Credo.Check.Readability.SinglePipe, []}, 187 | {Credo.Check.Readability.Specs, []}, 188 | {Credo.Check.Readability.StrictModuleLayout, []}, 189 | {Credo.Check.Readability.WithCustomTaggedTuple, []}, 190 | {Credo.Check.Refactor.ABCSize, false}, 191 | {Credo.Check.Refactor.AppendSingleItem, false}, 192 | {Credo.Check.Refactor.DoubleBooleanNegation, false}, 193 | {Credo.Check.Refactor.FilterReject, false}, 194 | {Credo.Check.Refactor.IoPuts, false}, 195 | {Credo.Check.Refactor.MapMap, false}, 196 | {Credo.Check.Refactor.ModuleDependencies, false}, 197 | {Credo.Check.Refactor.NegatedIsNil, false}, 198 | {Credo.Check.Refactor.PassAsyncInTestCases, false}, 199 | {Credo.Check.Refactor.PipeChainStart, false}, 200 | {Credo.Check.Refactor.RejectFilter, false}, 201 | {Credo.Check.Refactor.VariableRebinding, false}, 202 | {Credo.Check.Warning.LazyLogging, []}, 203 | {Credo.Check.Warning.LeakyEnvironment, []}, 204 | {Credo.Check.Warning.MapGetUnsafePass, []}, 205 | {Credo.Check.Warning.MixEnv, []}, 206 | {Credo.Check.Warning.UnsafeToAtom, []} 207 | 208 | # {Credo.Check.Refactor.MapInto, []}, 209 | 210 | # 211 | # Custom checks can be created using `mix credo.gen.check`. 212 | # 213 | ] 214 | } 215 | } 216 | ] 217 | } 218 | -------------------------------------------------------------------------------- /backends/pelemay_backend/.dialyzer_ignore.exs: -------------------------------------------------------------------------------- 1 | [ 2 | {"lib/pelemay_backend.ex", :no_return}, 3 | {"lib/pelemay_backend.ex", :callback_type_mismatch}, 4 | {"lib/pelemay_backend/backend.ex", :callback_type_mismatch}, 5 | {"lib/pelemay_backend/backend.ex", :callback_arg_type_mismatch}, 6 | {"lib/pelemay_backend/defn.ex", :no_return}, 7 | {"lib/pelemay_backend/defn.ex", :call}, 8 | {"lib/pelemay_backend/engine.ex", :pattern_match}, 9 | {"lib/pelemay_backend/parser.ex", :extra_range}, 10 | {"lib/pelemay_backend/defn/locked_cache.ex", :unmatched_return} 11 | ] 12 | -------------------------------------------------------------------------------- /backends/pelemay_backend/.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /backends/pelemay_backend/.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | pelemay_backend-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /backends/pelemay_backend/Makefile: -------------------------------------------------------------------------------- 1 | .phony: all clean 2 | 3 | PRIV = $(MIX_APP_PATH)/priv 4 | BUILD = $(MIX_APP_PATH)/obj 5 | NIF = $(PRIV)/libnif.so 6 | 7 | LDFLAGS = -lpthread 8 | 9 | ifeq ($(CROSSCOMPILE),) 10 | ifeq ($(shell uname -s),Linux) 11 | LDFLAGS += -fPIC -shared 12 | CFLAGS += -fPIC 13 | else # macOS 14 | LDFLAGS += -undefined dynamic_lookup -dynamiclib -Wl,-w 15 | endif 16 | else 17 | LDFLAGS += -fPIC -shared 18 | CFLAGS += -fPIC 19 | endif 20 | 21 | ifeq ($(ERL_EI_INCLUDE_DIR),) 22 | ERLANG_PATH = $(shell elixir --eval ':code.root_dir |> to_string() |> IO.puts') 23 | ifeq ($(ERLANG_PATH),) 24 | $(error Could not find the Elixir installation. Check to see that 'elixir') 25 | endif 26 | ERL_EI_INCLUDE_DIR = $(ERLANG_PATH)/usr/include 27 | ERL_EI_LIBDIR = $(ERLANG_PATH)/usr/lib 28 | endif 29 | 30 | ERL_CFLAGS ?= -I$(ERL_EI_INCLUDE_DIR) 31 | ERL_LDFLAGS ?= -L$(ERL_EI_LIBDIR) 32 | 33 | CFLAGS += $(shell mix openblas_builder.info including_option) 34 | 35 | CFLAGS += -std=c11 -O3 -Wall -Wextra -Wno-unused-function -Wno-unused-parameter -Wno-missing-field-initializers 36 | 37 | NIF_SRC_DIR = nif_src 38 | C_SRC = $(NIF_SRC_DIR)/libnif.c 39 | C_OBJ = $(C_SRC:$(NIF_SRC_DIR)/%.c=$(BUILD)/%.o) 40 | 41 | all: $(PRIV) $(BUILD) $(NIF) 42 | 43 | $(PRIV) $(BUILD): 44 | mkdir -p $@ 45 | 46 | $(BUILD)/%.o: $(NIF_SRC_DIR)/%.c 47 | @echo " CC $(notdir $@)" 48 | $(CC) -c $(ERL_CFLAGS) $(CFLAGS) -o $@ $< 49 | 50 | $(NIF): $(C_OBJ) $(OPENBLAS_OBJ) 51 | @echo " LD $(notdir $@)" 52 | $(CC) -o $@ $^ $(ERL_LDFLAGS) $(LDFLAGS) 53 | 54 | clean: 55 | $(RM) $(NIF) $(C_OBJ) 56 | -------------------------------------------------------------------------------- /backends/pelemay_backend/README.md: -------------------------------------------------------------------------------- 1 | # PelemayBackend 2 | 3 | 4 | A memory-saving, fault-tolerant and distributed collection of Nx compilers and 5 | backends for embedded systems. 6 | 7 | 8 | ## Installation 9 | 10 | TBD 11 | 12 | ## License 13 | 14 | Copyright (c) 2023 University of Kitakyushu 15 | 16 | Licensed under the Apache License, Version 2.0 (the "License"); 17 | you may not use this file except in compliance with the License. 18 | You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | 26 | ## Acknowledgement 27 | 28 | This work was supported by Asahi Kohsan Group Research Support Program of Kitakyushu Foundation for the Advancement of Industry Science and Technology (FAIS). 29 | -------------------------------------------------------------------------------- /backends/pelemay_backend/lib/pelemay_backend.ex: -------------------------------------------------------------------------------- 1 | defmodule PelemayBackend do 2 | @moduledoc ~S""" 3 | An integrated lightweight tensor backend for Nx. 4 | """ 5 | 6 | @behaviour Nx.Defn.Compiler 7 | 8 | @doc """ 9 | A shortcut for `Nx.Defn.jit/2` with the Pelemay backend compiler. 10 | 11 | iex> PelemayBackend.jit(&Nx.add(&1, &1)).(Nx.tensor([1, 2, 3])) 12 | #Nx.Tensor< 13 | s64[3] 14 | [2, 4, 6] 15 | > 16 | 17 | ## Options 18 | 19 | It accepts the same option as `Nx.Defn.jit/2` plus: 20 | 21 | * `:debug` - print compile and debugging information, defaults to `false`. 22 | 23 | * `:cache` - cache the results of compilation, defaults to `true`. 24 | 25 | * `:client` - an atom representing the client to use. The default 26 | client is chosen on this order: `:cuda`, `:rocm`, `:tpu`, and `:host`. 27 | 28 | * `:device_id` - the default device id to run the computation on. 29 | Defaults to the `:default_device_id` on the client 30 | 31 | """ 32 | def jit(function, options \\ []) do 33 | Nx.Defn.jit(function, Keyword.put(options, :compiler, PelemayBackend)) 34 | end 35 | 36 | @doc """ 37 | A shortcut for `Nx.Defn.jit_apply/3` with the Pelemay backend compiler. 38 | 39 | iex> PelemayBackend.jit_apply(&Nx.add(&1, &1), [Nx.tensor([1, 2, 3])]) 40 | #Nx.Tensor< 41 | s64[3] 42 | [2, 4, 6] 43 | > 44 | 45 | See `jit/2` for supported options. 46 | """ 47 | def jit_apply(function, args, options \\ []) do 48 | Nx.Defn.jit_apply(function, args, Keyword.put(options, :compiler, PelemayBackend)) 49 | end 50 | 51 | @doc """ 52 | A shortcut for `Nx.Defn.compile/3` with the Pelemay backend compiler. 53 | 54 | iex> fun = PelemayBackend.compile(&Nx.add(&1, &1), [Nx.template({3}, {:s, 64})]) 55 | iex> fun.(Nx.tensor([1, 2, 3])) 56 | #Nx.Tensor< 57 | s64[3] 58 | [2, 4, 6] 59 | > 60 | 61 | ## Options 62 | 63 | It accepts the same option as `Nx.Defn.compile/3` plus: 64 | 65 | * `:debug` - print compile and debugging information, defaults to `false`. 66 | 67 | * `:cache` - cache the results of compilation, defaults to `true`. 68 | You can set it to false if you plan to compile the function only 69 | once and store the compile contents somewhere. 70 | 71 | * `:client` - an atom representing the client to use. The default 72 | client is chosen on this order: `:cuda`, `:rocm`, `:tpu`, and `:host`. 73 | 74 | * `:device_id` - the default device id to run the computation on. 75 | Defaults to the `:default_device_id` on the client 76 | 77 | """ 78 | def compile(function, args, options \\ []) do 79 | Nx.Defn.compile(function, args, Keyword.put(options, :compiler, PelemayBackend)) 80 | end 81 | 82 | @doc """ 83 | Starts streaming the given anonymous function with just-in-time 84 | compilation. 85 | 86 | At least two arguments are expected: 87 | 88 | 1. The first argument is a tensor template of the data to 89 | be streamed in 90 | 91 | 2. The second argument is a tensor with the stream initial state 92 | 93 | The streaming function must return a two element tuple, the 94 | first element is the data to be sent and the second is the 95 | accumulator. 96 | 97 | For each streamed chunk, you must call `Nx.Stream.send/2` and 98 | `Nx.Stream.recv/1`. You don't need to call `recv` immediately 99 | after `send`, but doing so can be a useful mechanism to provide 100 | backpressure. Once all chunks are sent, you must use `Nx.Stream.done/1` 101 | to receive the accumulated result. Let's see an example: 102 | 103 | defmodule Streamed do 104 | import Nx.Defn 105 | 106 | defn sum(tensor, acc) do 107 | {acc, tensor + acc} 108 | end 109 | end 110 | 111 | Now let's invoke it: 112 | 113 | stream = PelemayBackend.stream(&Streamed.sum/2, [Nx.template({}, {:s, 64}), 0]) 114 | 115 | for i <- 1..5 do 116 | Nx.Stream.send(stream, i) 117 | IO.inspect {:chunk, Nx.Stream.recv(stream)} 118 | end 119 | 120 | IO.inspect {:result, Nx.Stream.done(stream)} 121 | 122 | It will print: 123 | 124 | {:chunk, 0} 125 | {:chunk, 1} 126 | {:chunk, 2} 127 | {:chunk, 3} 128 | {:chunk, 4} 129 | {:result, 5} 130 | 131 | **Note:** While any process can call `Nx.Stream.send/2`, EXLA 132 | expects the process that starts the streaming to be the one 133 | calling `Nx.Stream.recv/1` and `Nx.Stream.done/1`. 134 | 135 | See `jit/2` for supported options. 136 | """ 137 | def stream(function, args, options \\ []) do 138 | Nx.Defn.stream(function, args, Keyword.put(options, :compiler, PelemayBackend)) 139 | end 140 | 141 | @doc """ 142 | Checks if the compilation of function with args is cached. 143 | 144 | Note that hooks are part of the cache, and 145 | therefore they must be included in the options. 146 | 147 | ## Examples 148 | 149 | iex> fun = fn a, b -> Nx.add(a, b) end 150 | iex> left = Nx.tensor(1, type: {:u, 8}) 151 | iex> right = Nx.tensor([1, 2, 3], type: {:u, 16}) 152 | iex> PelemayBackend.jit(fun).(left, right) 153 | iex> PelemayBackend.cached?(fun, [left, right]) 154 | true 155 | iex> PelemayBackend.cached?(fun, [left, Nx.tensor([1, 2, 3, 4], type: {:u, 16})]) 156 | false 157 | 158 | Compiled functions are also cached, unless cache is set to false: 159 | 160 | iex> fun = fn a, b -> Nx.subtract(a, b) end 161 | iex> left = Nx.tensor(1, type: {:u, 8}) 162 | iex> right = Nx.tensor([1, 2, 3], type: {:u, 16}) 163 | iex> PelemayBackend.compile(fun, [left, right], cache: false) 164 | iex> PelemayBackend.cached?(fun, [left, right]) 165 | false 166 | iex> PelemayBackend.compile(fun, [left, right]) 167 | iex> PelemayBackend.cached?(fun, [left, right]) 168 | true 169 | 170 | """ 171 | def cached?(function, args, options \\ []) do 172 | function |> jit([{PelemayBackend, cached_check()} | options]) |> apply(args) 173 | catch 174 | {:cached?, bool} -> bool 175 | end 176 | 177 | @doc """ 178 | Checks if the JIT compilation of stream with 179 | args is cached. 180 | 181 | Note that hooks are part of the cache, and 182 | therefore they must be included in the options. 183 | 184 | ## Examples 185 | 186 | iex> left = Nx.tensor(1, type: {:u, 8}) 187 | iex> right = Nx.tensor([1, 2, 3], type: {:u, 16}) 188 | iex> fun = fn x, acc -> {acc, Nx.add(x, acc)} end 189 | iex> stream = PelemayBackend.stream(fun, [left, right]) 190 | iex> Nx.Stream.done(stream) 191 | iex> PelemayBackend.stream_cached?(fun, [left, right]) 192 | true 193 | iex> PelemayBackend.stream_cached?(fun, [left, Nx.tensor([1, 2, 3, 4], type: {:u, 16})]) 194 | false 195 | """ 196 | def stream_cached?(function, args, options \\ []) do 197 | stream(function, args, [{PelemayBackend, cached_check()} | options]) 198 | catch 199 | {:cached?, bool} -> bool 200 | end 201 | 202 | defp cached_check do 203 | expr_cache_fun = fn key, _callback -> 204 | if res = PelemayBackend.Defn.LockedCache.get(key) do 205 | {nil, res} 206 | else 207 | throw({:cached?, false}) 208 | end 209 | end 210 | 211 | comp_cache_fun = fn key, _callback -> 212 | throw({:cached?, PelemayBackend.Defn.LockedCache.get(key) != nil}) 213 | end 214 | 215 | {expr_cache_fun, comp_cache_fun} 216 | end 217 | 218 | @impl true 219 | defdelegate __compile__(key, vars, fun, opts), to: PelemayBackend.Defn 220 | 221 | @impl true 222 | defdelegate __jit__(key, vars, fun, args, opts), to: PelemayBackend.Defn 223 | 224 | @impl true 225 | defdelegate __stream__(key, input, acc, vars, fun, args, opts), to: PelemayBackend.Defn 226 | end 227 | -------------------------------------------------------------------------------- /backends/pelemay_backend/lib/pelemay_backend/application.ex: -------------------------------------------------------------------------------- 1 | defmodule PelemayBackend.Application do 2 | # See https://hexdocs.pm/elixir/Application.html 3 | # for more information on OTP Applications 4 | @moduledoc false 5 | 6 | use Application 7 | 8 | @impl true 9 | def start(_type, _args) do 10 | children = [ 11 | # Starts a worker by calling: PelemayBackend.Worker.start_link(arg) 12 | # {PelemayBackend.Worker, arg} 13 | PelemayBackend.Defn.Lock, 14 | PelemayBackend.Defn.LockedCache 15 | ] 16 | 17 | # See https://hexdocs.pm/elixir/Supervisor.html 18 | # for other strategies and supported options 19 | opts = [strategy: :one_for_one, name: PelemayBackend.Supervisor] 20 | Supervisor.start_link(children, opts) 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /backends/pelemay_backend/lib/pelemay_backend/defn.ex: -------------------------------------------------------------------------------- 1 | defmodule PelemayBackend.Defn do 2 | @moduledoc false 3 | 4 | require Logger 5 | 6 | @doc false 7 | def __stream__(_key, _input, _acc, _vars, _fun, [_args], _options) do 8 | end 9 | 10 | @doc false 11 | def __jit__(key, vars, fun, args_list, options) do 12 | __compile__(key, vars, fun, options).(args_list) 13 | end 14 | 15 | @doc false 16 | def __compile__(_key, _vars, _fun, options) do 17 | # Logger.debug( 18 | # "__compile__(key: #{inspect(key)}, vars: #{inspect(vars)}, fun: #{inspect(fun)}, options: #{inspect(options)})" 19 | # ) 20 | 21 | # Logger.debug("fun #{inspect(fun)}(#{inspect(vars)}): #{inspect(fun.(vars))}") 22 | 23 | {_run_options, _compile_options} = Keyword.pop(options, :run_options, []) 24 | 25 | code = 26 | """ 27 | aloadt 0 28 | copy 29 | is_scalar 30 | skip {10, {:if, true}} 31 | aloadt 1 32 | is_scalar 33 | skip {4, {:if, true}} 34 | sende 'multiply with two vectors is not supported.' 35 | pop2 36 | pop2 37 | return 38 | scal 1 39 | sendt 40 | return 41 | aloadt 1 42 | copy 43 | swap 44 | scal 1 45 | sendt 46 | """ 47 | |> PelemayBackend.Engine.assemble() 48 | 49 | fn [args] -> 50 | args = 51 | Enum.map(args, fn a -> 52 | cond do 53 | is_struct(a, Nx.Tensor) -> 54 | { 55 | Nx.size(a), 56 | Nx.shape(a), 57 | Nx.type(a), 58 | Nx.to_binary(a) 59 | } 60 | 61 | true -> 62 | a 63 | end 64 | end) 65 | 66 | try do 67 | case PelemayBackend.Engine.execute(code, args, self()) do 68 | :ok -> :ok 69 | {:error, reason} -> raise RuntimeError, message: List.to_string(reason) 70 | end 71 | rescue 72 | e in ErlangError -> 73 | Logger.error(Exception.format(:error, e, __STACKTRACE__)) 74 | reraise e, __STACKTRACE__ 75 | end 76 | 77 | receive do 78 | {:result, binary, shape, type} -> 79 | Nx.from_binary(binary, type) 80 | |> Nx.reshape(shape) 81 | |> then(&[&1]) 82 | 83 | {:error, reason} -> 84 | raise RuntimeError, message: List.to_string(reason) 85 | after 86 | 5000 -> 87 | raise RuntimeError, message: "timeout" 88 | end 89 | end 90 | end 91 | end 92 | -------------------------------------------------------------------------------- /backends/pelemay_backend/lib/pelemay_backend/defn/lock.ex: -------------------------------------------------------------------------------- 1 | defmodule PelemayBackend.Defn.Lock do 2 | @moduledoc false 3 | 4 | use GenServer 5 | require Logger 6 | 7 | @name __MODULE__ 8 | @timeout :infinity 9 | 10 | @doc """ 11 | Locks the given `key`. 12 | 13 | It will wait until the key becomes available. 14 | """ 15 | def lock(key) do 16 | GenServer.call(@name, {:lock, key}, @timeout) 17 | end 18 | 19 | @doc """ 20 | Transfers the lock to a new process. 21 | """ 22 | def transfer(ref, prepare, pid) 23 | when is_reference(ref) and is_function(prepare, 0) and is_pid(pid) do 24 | GenServer.call(@name, {:transfer, ref, prepare, pid}, @timeout) 25 | end 26 | 27 | @doc """ 28 | Registers what happens when the current lock is unlocked. 29 | 30 | The `prepare` is executed and then the new `to_unlock` is registered. 31 | """ 32 | def on_unlock(ref, prepare, to_unlock) 33 | when is_reference(ref) and 34 | is_function(prepare, 0) and is_function(to_unlock, 0) do 35 | GenServer.call(@name, {:on_unlock, ref, prepare, to_unlock}, @timeout) 36 | end 37 | 38 | @doc """ 39 | Unlocks the given `ref`. 40 | 41 | It will execute the registered `to_unlock` callback, if any. 42 | """ 43 | def unlock(ref) when is_reference(ref) do 44 | GenServer.call(@name, {:unlock, ref}, @timeout) 45 | end 46 | 47 | ## Callbacks 48 | 49 | @doc false 50 | def start_link(_opts) do 51 | GenServer.start_link(__MODULE__, :ok, name: @name) 52 | end 53 | 54 | @impl true 55 | def init(:ok) do 56 | Process.flag(:trap_exit, true) 57 | {:ok, {%{}, %{}}} 58 | end 59 | 60 | @impl true 61 | def handle_call({:lock, key}, from, {refs, devices}) do 62 | {refs, devices} = 63 | get_and_update_in(devices[key], fn device -> 64 | device 65 | |> enqueue(from) 66 | |> dequeue_if_possible(key, refs) 67 | end) 68 | 69 | {:noreply, {refs, devices}} 70 | end 71 | 72 | def handle_call({:unlock, ref}, _from, {refs, devices}) do 73 | _ = Process.demonitor(ref, [:flush]) 74 | {:reply, :ok, unlock(ref, refs, devices)} 75 | end 76 | 77 | def handle_call({:transfer, ref, prepare, pid}, _from, {refs, devices}) do 78 | {key, refs} = Map.pop!(refs, ref) 79 | _ = Process.demonitor(ref, [:flush]) 80 | _ = prepare.() 81 | ref = Process.monitor(pid) 82 | {:reply, ref, {Map.put(refs, ref, key), devices}} 83 | end 84 | 85 | def handle_call({:on_unlock, ref, prepare, to_unlock}, _from, {refs, devices}) do 86 | key = Map.fetch!(refs, ref) 87 | _ = prepare.() 88 | devices = update_in(devices[key], fn {_to_unlock, queue} -> {to_unlock, queue} end) 89 | {:reply, ref, {refs, devices}} 90 | end 91 | 92 | @impl true 93 | def handle_info({:DOWN, ref, _, _, _}, {refs, devices}) do 94 | {:noreply, unlock(ref, refs, devices)} 95 | end 96 | 97 | defp enqueue(nil, entry), do: enqueue({:unlocked, :queue.new()}, entry) 98 | defp enqueue({state, queue}, entry), do: {state, :queue.in(entry, queue)} 99 | 100 | defp unlock(ref, refs, devices) do 101 | case Map.pop(refs, ref, nil) do 102 | {nil, refs} -> 103 | {refs, devices} 104 | 105 | {key, refs} -> 106 | get_and_update_in(devices[key], fn {to_unlock, queue} -> 107 | case run_to_unlock(key, to_unlock) do 108 | {:transfer, new} -> 109 | ref = Process.monitor(new) 110 | {Map.put(refs, ref, key), {fn -> :unlock end, queue}} 111 | 112 | :unlock -> 113 | dequeue_if_possible({:unlocked, queue}, key, refs) 114 | end 115 | end) 116 | end 117 | end 118 | 119 | defp run_to_unlock(key, to_unlock) do 120 | to_unlock.() 121 | rescue 122 | exception -> 123 | Logger.error( 124 | "Unlocking #{inspect(key)} with #{inspect(to_unlock)} failed. " <> 125 | Exception.format(:error, exception, __STACKTRACE__) 126 | ) 127 | 128 | :unlock 129 | end 130 | 131 | defp dequeue_if_possible({:unlocked, queue}, key, refs) do 132 | case :queue.out(queue) do 133 | {{:value, {pid, _} = from}, queue} -> 134 | ref = Process.monitor(pid) 135 | GenServer.reply(from, ref) 136 | {Map.put(refs, ref, key), {fn -> :unlock end, queue}} 137 | 138 | {:empty, queue} -> 139 | {refs, {:unlocked, queue}} 140 | end 141 | end 142 | 143 | defp dequeue_if_possible({to_unlock, queue}, _key, refs) do 144 | {refs, {to_unlock, queue}} 145 | end 146 | end 147 | -------------------------------------------------------------------------------- /backends/pelemay_backend/lib/pelemay_backend/defn/locked_cache.ex: -------------------------------------------------------------------------------- 1 | defmodule PelemayBackend.Defn.LockedCache do 2 | @moduledoc false 3 | 4 | # PelemayBackend has many expensive singleton resources such as 5 | # the executable that we want to compute just once. 6 | # This module provides a cache functionality so that 7 | # those are done only once, even if concurrently. 8 | # 9 | # Since those resources can be created dynamically, 10 | # multiple times, they are stored in ETS instead of 11 | # persistent term. 12 | use GenServer 13 | 14 | @name __MODULE__ 15 | @timeout :infinity 16 | 17 | @doc """ 18 | Reads the cache key. 19 | """ 20 | def get(key) do 21 | soft_read(key) 22 | end 23 | 24 | @doc """ 25 | Reads cache key or executes the given function if not 26 | cached yet. 27 | """ 28 | def run(key, fun) do 29 | try do 30 | {nil, hard_read(key)} 31 | catch 32 | :error, :badarg -> 33 | case GenServer.call(@name, {:lock, key}, @timeout) do 34 | {:uncached, ref} -> 35 | try do 36 | fun.() 37 | catch 38 | kind, reason -> 39 | GenServer.cast(@name, {:uncached, ref}) 40 | :erlang.raise(kind, reason, __STACKTRACE__) 41 | else 42 | {return, result} -> 43 | write(key, result) 44 | GenServer.cast(@name, {:cached, ref}) 45 | {return, result} 46 | end 47 | 48 | :cached -> 49 | {nil, hard_read(key)} 50 | end 51 | end 52 | end 53 | 54 | defp init(), do: :ets.new(@name, [:public, :set, :named_table, read_concurrency: true]) 55 | defp write(key, value), do: :ets.insert(@name, {key, value}) 56 | defp hard_read(key), do: :ets.lookup_element(@name, key, 2) 57 | 58 | defp soft_read(key) do 59 | try do 60 | :ets.lookup_element(@name, key, 2) 61 | catch 62 | :error, :badarg -> nil 63 | end 64 | end 65 | 66 | ## Callbacks 67 | 68 | @doc false 69 | def start_link(_opts) do 70 | GenServer.start_link(__MODULE__, :ok, name: @name) 71 | end 72 | 73 | @impl true 74 | def init(:ok) do 75 | init() 76 | {:ok, %{keys: %{}, ref_to_key: %{}}} 77 | end 78 | 79 | @impl true 80 | def handle_call({:lock, key}, from, state) do 81 | case state.keys do 82 | %{^key => {ref, waiting}} -> 83 | {:noreply, put_in(state.keys[key], {ref, [from | waiting]})} 84 | 85 | %{} -> 86 | {:noreply, lock(key, from, [], state)} 87 | end 88 | end 89 | 90 | @impl true 91 | def handle_cast({:cached, ref}, state) do 92 | Process.demonitor(ref, [:flush]) 93 | {key, state} = pop_in(state.ref_to_key[ref]) 94 | {{^ref, waiting}, state} = pop_in(state.keys[key]) 95 | for from <- waiting, do: GenServer.reply(from, :cached) 96 | {:noreply, state} 97 | end 98 | 99 | @impl true 100 | def handle_cast({:uncached, ref}, state) do 101 | Process.demonitor(ref, [:flush]) 102 | {:noreply, unlock(ref, state)} 103 | end 104 | 105 | @impl true 106 | def handle_info({:DOWN, ref, _, _, _}, state) do 107 | {:noreply, unlock(ref, state)} 108 | end 109 | 110 | defp lock(key, {pid, _} = from, waiting, state) do 111 | ref = Process.monitor(pid) 112 | state = put_in(state.keys[key], {ref, waiting}) 113 | state = put_in(state.ref_to_key[ref], key) 114 | GenServer.reply(from, {:uncached, ref}) 115 | state 116 | end 117 | 118 | defp unlock(ref, state) do 119 | {key, state} = pop_in(state.ref_to_key[ref]) 120 | {{^ref, waiting}, state} = pop_in(state.keys[key]) 121 | 122 | case waiting do 123 | [] -> state 124 | [from | waiting] -> lock(key, from, waiting, state) 125 | end 126 | end 127 | end 128 | -------------------------------------------------------------------------------- /backends/pelemay_backend/lib/pelemay_backend/engine.ex: -------------------------------------------------------------------------------- 1 | defmodule PelemayBackend.Engine do 2 | @moduledoc """ 3 | Document for `PelemayBackend.Engine`. 4 | """ 5 | import Bitwise 6 | require Logger 7 | 8 | @opcode_macro "PELEMAY_ENGINE_OPCODE_H" 9 | @opcode_header "nif_src/opcode.h" 10 | 11 | @type opcode :: non_neg_integer() 12 | @type operand :: any() 13 | 14 | @doc """ 15 | Gets key of opcode. 16 | """ 17 | def key_opcode() do 18 | [ 19 | :instruction, 20 | :reserved 21 | ] 22 | end 23 | 24 | @doc """ 25 | Gets map instruction to code. 26 | """ 27 | def instruction_code() do 28 | %{ 29 | scal: 0x0000, 30 | sscal: 0x0001, 31 | copy: 0x0002, 32 | dot: 0x0003, 33 | axpy: 0x0004, 34 | gemv: 0x1000, 35 | gemm: 0x2000, 36 | aloadt: 0x8000, 37 | sendt: 0x8001, 38 | return: 0x8002, 39 | skip: 0x8003, 40 | is_scalar: 0x8004, 41 | dup: 0x8005, 42 | pop: 0x8006, 43 | pop2: 0x8007, 44 | swap: 0x8008, 45 | sende: 0x8009 46 | } 47 | end 48 | 49 | @doc """ 50 | Gets opcode from keyword. 51 | """ 52 | def opcode(keyword) do 53 | instruction = Keyword.get(keyword, :instruction, 0) 54 | reserved = Keyword.get(keyword, :reserved, 0) 55 | 56 | <> = << 57 | reserved::48, 58 | instruction::16 59 | >> 60 | 61 | opcode 62 | end 63 | 64 | @doc """ 65 | Gets the mask of opcode. 66 | """ 67 | def mask(key) do 68 | opcode(Keyword.put([], key, 0xFFFFFFFFFFFFFFFF)) 69 | end 70 | 71 | @doc """ 72 | Gets the mask hex string of opcode. 73 | """ 74 | def hex_mask(key) do 75 | mask(key) 76 | |> Integer.to_string(16) 77 | |> then(&Kernel.<>("0x", &1)) 78 | end 79 | 80 | @doc """ 81 | Gets the shift value of opcode. 82 | """ 83 | def shift(key) do 84 | shift_s(mask(key), 0) 85 | end 86 | 87 | defp shift_s(0, s), do: s 88 | 89 | defp shift_s(mask, s) do 90 | case band(mask, 1) do 91 | 1 -> s 92 | 0 -> shift_s(mask >>> 1, s + 1) 93 | end 94 | end 95 | 96 | @doc """ 97 | Gets the name of the macro of the mask or shift from key. 98 | """ 99 | def name_macro(key, :mask) do 100 | name_macro_s(key, "MASK") 101 | end 102 | 103 | def name_macro(key, :shift) do 104 | name_macro_s(key, "SHIFT") 105 | end 106 | 107 | def name_macro(key, :inst) do 108 | name_macro_s(key, "INST") 109 | end 110 | 111 | defp name_macro_s(key, prefix) do 112 | key 113 | |> Atom.to_string() 114 | |> String.upcase() 115 | |> then(&Enum.join([prefix, &1], "_")) 116 | end 117 | 118 | @doc """ 119 | Gets c code of the masks and the shifts. 120 | """ 121 | def c_code_masks_shifts() do 122 | key_opcode() 123 | |> Enum.map(fn key -> 124 | """ 125 | #define #{name_macro(key, :mask)} #{hex_mask(key)} 126 | #define #{name_macro(key, :shift)} #{shift(key)} 127 | """ 128 | end) 129 | |> Enum.join("\n") 130 | end 131 | 132 | @doc """ 133 | Gets c code of `enum instruction`. 134 | """ 135 | def c_enum_instruction() do 136 | instruction_code() 137 | |> Enum.sort(fn {_, c1}, {_, c2} -> c1 < c2 end) 138 | |> Enum.map(fn {inst, code} -> 139 | " #{name_macro(inst, :inst)} = 0x#{Integer.to_string(code, 16)}," 140 | end) 141 | |> Enum.join("\n") 142 | |> then( 143 | &""" 144 | enum instruction { 145 | #{&1} 146 | }; 147 | """ 148 | ) 149 | end 150 | 151 | @doc false 152 | def c_code(:mask), do: c_code_masks_shifts() 153 | def c_code(:inst), do: c_enum_instruction() 154 | 155 | @doc """ 156 | Gets c header code. 157 | """ 158 | def c_header_code(macro) do 159 | """ 160 | #ifndef #{macro} 161 | #define #{macro} 162 | 163 | #{c_code(:mask)} 164 | 165 | #{c_code(:inst)} 166 | 167 | enum stack_type { 168 | type_undefined, 169 | type_tensor, 170 | type_scalar, 171 | type_error, 172 | type_bool, 173 | }; 174 | 175 | enum type_binary { 176 | tb_s = 0, 177 | tb_u = 1, 178 | tb_f = 2, 179 | tb_bf = 3, 180 | tb_c = 6, 181 | }; 182 | 183 | enum bit_type_binary { 184 | btb_8 = 0, 185 | btb_16 = 1, 186 | btb_32 = 2, 187 | btb_64 = 3, 188 | btb_c16 = 0, 189 | btb_c32 = 1, 190 | btb_c64 = 2, 191 | btb_c128 = 3, 192 | }; 193 | #endif // #{macro} 194 | """ 195 | end 196 | 197 | @spec put_c_header( 198 | binary 199 | | maybe_improper_list( 200 | binary | maybe_improper_list(any, binary | []) | char, 201 | binary | [] 202 | ), 203 | any 204 | ) :: :ok 205 | @doc """ 206 | Puts c header code. 207 | """ 208 | def put_c_header(file \\ @opcode_header, macro \\ @opcode_macro) do 209 | File.write!(file, c_header_code(macro)) 210 | end 211 | 212 | @doc """ 213 | Executes code for the engine. 214 | 215 | The code should be a list of tuples of an opcode and an operand. 216 | """ 217 | @spec execute(list({opcode(), operand()}), list(), pid()) :: :ok | {:error, String.t()} 218 | def execute(code, args, pid) do 219 | PelemayBackend.NIF.execute_engine(code, args, pid) 220 | end 221 | 222 | @doc """ 223 | Gets Regex of instructions. 224 | """ 225 | def regex_inst() do 226 | instruction_code() 227 | |> Map.keys() 228 | |> Enum.map(&Atom.to_string/1) 229 | |> Enum.map(&"(^ *(?<#{&1}>#{&1}.*)$)") 230 | |> Enum.join("|") 231 | |> Regex.compile!() 232 | end 233 | 234 | @doc """ 235 | Assemble code into 236 | """ 237 | @spec assemble(String.t()) :: list({opcode(), operand()}) 238 | def assemble(code) do 239 | r = regex_inst() 240 | 241 | String.split(code, "\n") 242 | |> Stream.reject(&(&1 == "")) 243 | |> Stream.map(&Regex.named_captures(r, &1)) 244 | |> Stream.reject(&is_nil/1) 245 | |> Stream.map(&Map.reject(&1, fn {_k, v} -> v == "" end)) 246 | |> Enum.reduce([], fn map, acc -> 247 | inst = Map.keys(map) |> hd() 248 | 249 | args = 250 | Map.get(map, inst, "") 251 | |> String.replace_prefix(inst, "") 252 | |> PelemayBackend.Parser.parse_constant() 253 | |> case do 254 | {:ok, value, _, _, _, _} -> value 255 | {:error, _, _, _, _, _} -> [:error] 256 | end 257 | |> evaluate() 258 | 259 | inst = String.to_atom(inst) 260 | acc ++ [{inst, args}] 261 | end) 262 | |> Stream.map(fn {inst, args} -> 263 | encode(inst, args) 264 | end) 265 | |> Enum.to_list() 266 | end 267 | 268 | defp evaluate([]), do: [] 269 | 270 | defp evaluate([:error]), do: [] 271 | 272 | defp evaluate(integer: [value]), do: value 273 | 274 | defp evaluate(string: [value]), do: String.to_charlist(value) 275 | 276 | defp evaluate(atom: [value]), do: String.to_atom(value) 277 | 278 | defp evaluate(tuple: list), do: list |> Enum.map(&evaluate([&1])) |> List.to_tuple() 279 | 280 | defp encode(:scal, args) do 281 | # Logger.debug("scal #{inspect(args)}") 282 | 283 | code = { 284 | Map.get(instruction_code(), :scal), 285 | args 286 | } 287 | 288 | # Logger.debug("generated code of scal: #{inspect(code)}") 289 | 290 | code 291 | end 292 | 293 | defp encode(:sscal, _args) do 294 | # Logger.debug("sscal") 295 | end 296 | 297 | defp encode(:copy, args) do 298 | # Logger.debug("copy") 299 | 300 | code = { 301 | Map.get(instruction_code(), :copy), 302 | args 303 | } 304 | 305 | # Logger.debug("generated code of copy: #{inspect(code)}") 306 | 307 | code 308 | end 309 | 310 | defp encode(:dot, _args) do 311 | # Logger.debug("dot") 312 | end 313 | 314 | defp encode(:axpy, _args) do 315 | # Logger.debug("axpy") 316 | end 317 | 318 | defp encode(:gemv, _args) do 319 | # Logger.debug("gemv") 320 | end 321 | 322 | defp encode(:gemm, _args) do 323 | # Logger.debug("gemm") 324 | end 325 | 326 | defp encode(:sendt, _args) do 327 | code = { 328 | Map.get(instruction_code(), :sendt), 329 | nil 330 | } 331 | 332 | code 333 | end 334 | 335 | defp encode(:sende, args) do 336 | code = { 337 | Map.get(instruction_code(), :sende), 338 | args 339 | } 340 | 341 | code 342 | end 343 | 344 | defp encode(:return, _args) do 345 | code = { 346 | Map.get(instruction_code(), :return), 347 | nil 348 | } 349 | 350 | code 351 | end 352 | 353 | defp encode(:skip, args) do 354 | code = { 355 | Map.get(instruction_code(), :skip), 356 | args 357 | } 358 | 359 | code 360 | end 361 | 362 | defp encode(:is_scalar, _args) do 363 | code = { 364 | Map.get(instruction_code(), :is_scalar), 365 | nil 366 | } 367 | 368 | code 369 | end 370 | 371 | defp encode(:dup, _args) do 372 | code = { 373 | Map.get(instruction_code(), :dup), 374 | nil 375 | } 376 | 377 | code 378 | end 379 | 380 | defp encode(:pop, _args) do 381 | code = { 382 | Map.get(instruction_code(), :pop), 383 | nil 384 | } 385 | 386 | code 387 | end 388 | 389 | defp encode(:pop2, _args) do 390 | code = { 391 | Map.get(instruction_code(), :pop2), 392 | nil 393 | } 394 | 395 | code 396 | end 397 | 398 | defp encode(:swap, _args) do 399 | code = { 400 | Map.get(instruction_code(), :swap), 401 | nil 402 | } 403 | 404 | code 405 | end 406 | 407 | defp encode(:aloadt, args) do 408 | code = { 409 | Map.get(instruction_code(), :aloadt), 410 | args 411 | } 412 | 413 | code 414 | end 415 | end 416 | -------------------------------------------------------------------------------- /backends/pelemay_backend/lib/pelemay_backend/nif.ex: -------------------------------------------------------------------------------- 1 | defmodule PelemayBackend.NIF do 2 | @moduledoc """ 3 | Documentation for `PelemayBackend.NIF`. 4 | """ 5 | require Logger 6 | 7 | @on_load :load_nif 8 | 9 | @doc false 10 | def load_nif do 11 | nif_file = ~c'#{Application.app_dir(:pelemay_backend, "priv/libnif")}' 12 | 13 | case :erlang.load_nif(nif_file, 0) do 14 | :ok -> :ok 15 | {:error, {:reload, _}} -> :ok 16 | {:error, reason} -> Logger.error("Failed to load NIF: #{inspect(reason)}") 17 | end 18 | end 19 | 20 | def execute_engine(_code, _args, _pid), do: :erlang.nif_error(:not_loaded) 21 | end 22 | -------------------------------------------------------------------------------- /backends/pelemay_backend/lib/pelemay_backend/parser.ex: -------------------------------------------------------------------------------- 1 | defmodule PelemayBackend.Parser do 2 | import NimbleParsec 3 | 4 | defparsec(:parse_integer, ignore(repeat(string(" "))) |> integer(min: 1) |> tag(:integer)) 5 | 6 | defparsec( 7 | :parse_atom, 8 | ignore(repeat(string(" "))) 9 | |> ignore(string(":")) 10 | |> ascii_string([?a..?z], min: 1) 11 | |> tag(:atom) 12 | ) 13 | 14 | defparsec( 15 | :parse_bool, 16 | ignore(repeat(string(" "))) |> choice([string("true"), string("false")]) |> tag(:atom) 17 | ) 18 | 19 | defparsec( 20 | :parse_string, 21 | ignore(repeat(string(" "))) 22 | |> ignore(string("'")) 23 | |> utf8_string([not: ?\'], min: 0) 24 | |> ignore(string("'")) 25 | |> tag(:string) 26 | ) 27 | 28 | defcombinator( 29 | :args, 30 | ignore(repeat(string(" "))) 31 | |> parsec(:parse_constant) 32 | |> repeat( 33 | ignore(repeat(string(" "))) 34 | |> ignore(string(",")) 35 | |> ignore(repeat(string(" "))) 36 | |> concat(parsec(:parse_constant)) 37 | ) 38 | ) 39 | 40 | defparsec( 41 | :parse_tuple, 42 | ignore(repeat(string(" "))) 43 | |> ignore(string("{")) 44 | |> parsec(:args) 45 | |> ignore(string("}")) 46 | |> tag(:tuple) 47 | ) 48 | 49 | defparsec( 50 | :parse_constant, 51 | choice([ 52 | parsec(:parse_integer), 53 | parsec(:parse_atom), 54 | parsec(:parse_bool), 55 | parsec(:parse_tuple), 56 | parsec(:parse_string), 57 | empty() 58 | ]) 59 | |> ignore(repeat(string(" "))) 60 | ) 61 | end 62 | -------------------------------------------------------------------------------- /backends/pelemay_backend/mix.exs: -------------------------------------------------------------------------------- 1 | # if :erlang.system_info(:otp_release) < ~c"24" do 2 | # Mix.raise("Nx requires Erlang/OTP 24+") 3 | # end 4 | 5 | defmodule PelemayBackend.MixProject do 6 | use Mix.Project 7 | 8 | @version "0.1.0-dev" 9 | 10 | def project do 11 | [ 12 | app: :pelemay_backend, 13 | version: @version, 14 | elixir: "~> 1.14", 15 | start_permanent: Mix.env() == :prod, 16 | deps: deps(), 17 | compilers: [:pelemay_backend, :elixir_make] ++ Mix.compilers(), 18 | aliases: [ 19 | "compile.pelemay_backend": &compile/1 20 | ], 21 | dialyzer: [ 22 | plt_add_apps: [:mix], 23 | flags: [ 24 | :unmatched_returns, 25 | :error_handling, 26 | :underspecs, 27 | :no_contracts, 28 | :unknown 29 | ], 30 | ignore_warnings: ".dialyzer_ignore.exs" 31 | ] 32 | ] 33 | end 34 | 35 | # Run "mix help compile.app" to learn about applications. 36 | def application do 37 | [ 38 | extra_applications: [:logger], 39 | mod: {PelemayBackend.Application, []} 40 | ] 41 | end 42 | 43 | # Run "mix help deps" to learn about dependencies. 44 | defp deps do 45 | [ 46 | {:nx, "== 0.3.0"}, 47 | {:ex_doc, "~> 0.29.4", only: :dev, runtime: false}, 48 | {:openblas_builder, "~> 0.1.0-dev", github: "zeam-vm/openblas_builder", branch: "main"}, 49 | {:elixir_make, "~> 0.7.6", runtime: false}, 50 | {:nimble_parsec, "~> 1.4.0"}, 51 | {:dialyxir, "~> 1.3", only: [:dev], runtime: false}, 52 | {:credo, "~> 1.7", only: [:dev, :test], runtime: false} 53 | ] 54 | end 55 | 56 | defp compile(_) do 57 | OpenBLASBuilder.extract_archive!() 58 | 59 | OpenBLASBuilder.compile_matched!([ 60 | {"interface", "cblas_sscal"}, 61 | {"interface", "sscal"}, 62 | {"interface", "cblas_scopy"}, 63 | {"interface", "scopy"}, 64 | {"interface", "cblas_dscal"}, 65 | {"interface", "dscal"}, 66 | {"interface", "cblas_dcopy"}, 67 | {"interface", "dcopy"}, 68 | {"driver/others", "memory"}, 69 | {"driver/others", "blas_l1_thread"}, 70 | {"driver/others", "blas_server"}, 71 | {"driver/others", "parameter"}, 72 | {"driver/others", "openblas_env"}, 73 | {"driver/others", "openblas_error_handle"}, 74 | {"driver/others", "divtable"} 75 | ]) 76 | |> Map.values() 77 | |> Enum.join(" ") 78 | |> then(&System.put_env("OPENBLAS_OBJ", &1)) 79 | 80 | {:ok, []} 81 | end 82 | end 83 | -------------------------------------------------------------------------------- /backends/pelemay_backend/mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, 3 | "complex": {:hex, :complex, "0.4.3", "84db4aad241099a8785446ac6eacf498bf3a60634a0e45c7745d875714ddbf98", [:mix], [], "hexpm", "2ceda96ebddcc22697974f1a2666d4cc5dfdd34f8cd8c4f9dced037bcb41eeb5"}, 4 | "credo": {:hex, :credo, "1.7.7", "771445037228f763f9b2afd612b6aa2fd8e28432a95dbbc60d8e03ce71ba4446", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "8bc87496c9aaacdc3f90f01b7b0582467b69b4bd2441fe8aae3109d843cc2f2e"}, 5 | "dialyxir": {:hex, :dialyxir, "1.4.5", "ca1571ac18e0f88d4ab245f0b60fa31ff1b12cbae2b11bd25d207f865e8ae78a", [:mix], [{:erlex, ">= 0.2.7", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "b0fb08bb8107c750db5c0b324fa2df5ceaa0f9307690ee3c1f6ba5b9eb5d35c3"}, 6 | "earmark_parser": {:hex, :earmark_parser, "1.4.41", "ab34711c9dc6212dda44fcd20ecb87ac3f3fce6f0ca2f28d4a00e4154f8cd599", [:mix], [], "hexpm", "a81a04c7e34b6617c2792e291b5a2e57ab316365c2644ddc553bb9ed863ebefa"}, 7 | "elixir_make": {:hex, :elixir_make, "0.7.6", "67716309dc5d43e16b5abbd00c01b8df6a0c2ab54a8f595468035a50189f9169", [:mix], [{:castore, "~> 0.1 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}], "hexpm", "5a0569756b0f7873a77687800c164cca6dfc03a09418e6fcf853d78991f49940"}, 8 | "erlex": {:hex, :erlex, "0.2.7", "810e8725f96ab74d17aac676e748627a07bc87eb950d2b83acd29dc047a30595", [:mix], [], "hexpm", "3ed95f79d1a844c3f6bf0cea61e0d5612a42ce56da9c03f01df538685365efb0"}, 9 | "ex_doc": {:hex, :ex_doc, "0.29.4", "6257ecbb20c7396b1fe5accd55b7b0d23f44b6aa18017b415cb4c2b91d997729", [:mix], [{:earmark_parser, "~> 1.4.31", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1", [hex: :makeup_erlang, repo: "hexpm", optional: false]}], "hexpm", "2c6699a737ae46cb61e4ed012af931b57b699643b24dabe2400a8168414bc4f5"}, 10 | "file_system": {:hex, :file_system, "1.0.0", "b689cc7dcee665f774de94b5a832e578bd7963c8e637ef940cd44327db7de2cd", [:mix], [], "hexpm", "6752092d66aec5a10e662aefeed8ddb9531d79db0bc145bb8c40325ca1d8536d"}, 11 | "flow": {:hex, :flow, "1.2.4", "1dd58918287eb286656008777cb32714b5123d3855956f29aa141ebae456922d", [:mix], [{:gen_stage, "~> 1.0", [hex: :gen_stage, repo: "hexpm", optional: false]}], "hexpm", "874adde96368e71870f3510b91e35bc31652291858c86c0e75359cbdd35eb211"}, 12 | "gen_stage": {:hex, :gen_stage, "1.2.1", "19d8b5e9a5996d813b8245338a28246307fd8b9c99d1237de199d21efc4c76a1", [:mix], [], "hexpm", "83e8be657fa05b992ffa6ac1e3af6d57aa50aace8f691fcf696ff02f8335b001"}, 13 | "jason": {:hex, :jason, "1.4.1", "af1504e35f629ddcdd6addb3513c3853991f694921b1b9368b0bd32beb9f1b63", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "fbb01ecdfd565b56261302f7e1fcc27c4fb8f32d56eab74db621fc154604a7a1"}, 14 | "makeup": {:hex, :makeup, "1.2.1", "e90ac1c65589ef354378def3ba19d401e739ee7ee06fb47f94c687016e3713d1", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "d36484867b0bae0fea568d10131197a4c2e47056a6fbe84922bf6ba71c8d17ce"}, 15 | "makeup_elixir": {:hex, :makeup_elixir, "0.16.2", "627e84b8e8bf22e60a2579dad15067c755531fea049ae26ef1020cad58fe9578", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "41193978704763f6bbe6cc2758b84909e62984c7752b3784bd3c218bb341706b"}, 16 | "makeup_erlang": {:hex, :makeup_erlang, "0.1.5", "e0ff5a7c708dda34311f7522a8758e23bfcd7d8d8068dc312b5eb41c6fd76eba", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "94d2e986428585a21516d7d7149781480013c56e30c6a233534bedf38867a59a"}, 17 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"}, 18 | "nx": {:hex, :nx, "0.3.0", "12448769619ed1442e22bd198faf4629ae3d0ee3ed565e42be49829cc42bf35f", [:mix], [{:complex, "~> 0.4.2", [hex: :complex, repo: "hexpm", optional: false]}], "hexpm", "d08d8962f4379ade54281aad84c45cb7eb0118b406fc836f07b94acc40df5859"}, 19 | "openblas_builder": {:git, "https://github.com/zeam-vm/openblas_builder.git", "4067b5ab72d752d75126e7605fdb081aad43632b", [branch: "main"]}, 20 | "telemetry": {:hex, :telemetry, "1.3.0", "fedebbae410d715cf8e7062c96a1ef32ec22e764197f70cda73d82778d61e7a2", [:rebar3], [], "hexpm", "7015fc8919dbe63764f4b4b87a95b7c0996bd539e0d499be6ec9d7f3875b79e6"}, 21 | } 22 | -------------------------------------------------------------------------------- /backends/pelemay_backend/nif_src/opcode.h: -------------------------------------------------------------------------------- 1 | #ifndef PELEMAY_ENGINE_OPCODE_H 2 | #define PELEMAY_ENGINE_OPCODE_H 3 | 4 | #define MASK_INSTRUCTION 0xFFFF 5 | #define SHIFT_INSTRUCTION 0 6 | 7 | #define MASK_RESERVED 0xFFFFFFFFFFFF0000 8 | #define SHIFT_RESERVED 16 9 | 10 | 11 | enum instruction { 12 | INST_SCAL = 0x0, 13 | INST_SSCAL = 0x1, 14 | INST_COPY = 0x2, 15 | INST_DOT = 0x3, 16 | INST_AXPY = 0x4, 17 | INST_GEMV = 0x1000, 18 | INST_GEMM = 0x2000, 19 | INST_ALOADT = 0x8000, 20 | INST_SENDT = 0x8001, 21 | INST_RETURN = 0x8002, 22 | INST_SKIP = 0x8003, 23 | INST_IS_SCALAR = 0x8004, 24 | INST_DUP = 0x8005, 25 | INST_POP = 0x8006, 26 | INST_POP2 = 0x8007, 27 | INST_SWAP = 0x8008, 28 | INST_SENDE = 0x8009, 29 | }; 30 | 31 | 32 | enum stack_type { 33 | type_undefined, 34 | type_tensor, 35 | type_scalar, 36 | type_error, 37 | type_bool, 38 | }; 39 | 40 | enum type_binary { 41 | tb_s = 0, 42 | tb_u = 1, 43 | tb_f = 2, 44 | tb_bf = 3, 45 | tb_c = 6, 46 | }; 47 | 48 | enum bit_type_binary { 49 | btb_8 = 0, 50 | btb_16 = 1, 51 | btb_32 = 2, 52 | btb_64 = 3, 53 | btb_c16 = 0, 54 | btb_c32 = 1, 55 | btb_c64 = 2, 56 | btb_c128 = 3, 57 | }; 58 | #endif // PELEMAY_ENGINE_OPCODE_H 59 | -------------------------------------------------------------------------------- /backends/pelemay_backend/test/pelemay_backend/backend_test.exs: -------------------------------------------------------------------------------- 1 | defmodule PelemayBackend.BackendTest do 2 | use ExUnit.Case 3 | doctest PelemayBackend.Backend 4 | 5 | setup do 6 | Nx.default_backend(PelemayBackend.Backend) 7 | :ok 8 | end 9 | 10 | test "multiply scalar and vector" do 11 | assert Nx.multiply(2.0, Nx.tensor([1.0, 2.0], type: {:f, 32})) == 12 | Nx.tensor([2.0, 4.0], type: {:f, 32}) 13 | 14 | assert Nx.multiply(Nx.tensor([1.0, 2.0], type: {:f, 32}), 2.0) == 15 | Nx.tensor([2.0, 4.0], type: {:f, 32}) 16 | 17 | assert Nx.multiply(4.0, Nx.tensor([3.0, 4.0, 5.0], type: {:f, 32})) == 18 | Nx.tensor([12.0, 16.0, 20.0], type: {:f, 32}) 19 | 20 | assert Nx.multiply(2.0, Nx.tensor([1.0, 2.0], type: {:f, 64})) == 21 | Nx.tensor([2.0, 4.0], type: {:f, 64}) 22 | 23 | assert Nx.multiply(4.0, Nx.tensor([3.0, 4.0, 5.0], type: {:f, 64})) == 24 | Nx.tensor([12.0, 16.0, 20.0], type: {:f, 64}) 25 | 26 | assert_raise RuntimeError, fn -> 27 | Nx.multiply(Nx.tensor([1.0, 2.0]), Nx.tensor([2.0, 4.0])) 28 | end 29 | end 30 | 31 | @precision_error_doctests [ 32 | expm1: 1, 33 | erfc: 1, 34 | erf: 1, 35 | cosh: 1, 36 | tanh: 1, 37 | asin: 1, 38 | asinh: 1, 39 | atanh: 1, 40 | ceil: 1, 41 | sigmoid: 1, 42 | fft: 2, 43 | ifft: 2 44 | ] 45 | 46 | @temporarily_broken_doctests [ 47 | # XLA currently doesn't support complex conversion 48 | as_type: 2 49 | ] 50 | 51 | @inherently_unsupported_doctests [ 52 | # XLA requires signed and unsigned tensors to be at least of size 32 53 | random_uniform: 4 54 | ] 55 | 56 | @unrelated_doctests [ 57 | default_backend: 1 58 | ] 59 | 60 | @untest_doctests [ 61 | # is_tensor: 1, 62 | # all: 2, 63 | all_close: 3, 64 | # any: 2, 65 | # argmax: 2, 66 | # argmin: 2, 67 | # mean: 2, 68 | # product: 2, 69 | # reduce: 4, 70 | # reduce_max: 2, 71 | # reduce_min: 2, 72 | # standard_deviation: 2, 73 | # sum: 2, 74 | # variance: 2, 75 | # backend_copy: 2, 76 | # backend_deallocate: 1, 77 | # backend_transfar: 2, 78 | # default_backend: 1, 79 | # global_default_backend: 1, 80 | # deserialize: 2, 81 | # from_numpy: 2, 82 | # from_numpy_archive: 2, 83 | # serialize: 2, 84 | # to_batched: 3, 85 | # to_backed_list: 3, 86 | # to_binary: 2, 87 | # to_flat_list: 2, 88 | # to_heatmap: 2, 89 | # to_number: 2, 90 | # to_template: 1, 91 | # to_tensor: 1, 92 | # eye: 2, 93 | # from_binary: 3, 94 | # iota: 2, 95 | # make_diagonal: 2, 96 | # put_diagonal: 3, 97 | # random_normal: 2, 98 | # random_normal: 4, 99 | # random_uniform: 2, 100 | # random_uniform: 4, 101 | # shuflle: 2, 102 | # sigil_M: 2, 103 | # sigil_V: 2, 104 | # take_diagonal: 2, 105 | # template: 3, 106 | # tensor: 2, 107 | cumulative_max: 2, 108 | cumulative_min: 2, 109 | cumulative_product: 2, 110 | cumulative_sum: 2, 111 | # abs: 1, 112 | # acos: 1, 113 | # acosh: 1, 114 | # add: 2, 115 | # asin: 1, 116 | # asinh: 1, 117 | # atan2: 2, 118 | # atan: 1, 119 | # atanh: 1, 120 | # bitwise_and: 2, 121 | # bitwise_not: 1, 122 | # bitwise_or: 2, 123 | # bitwise_xor: 2, 124 | # cbrt: 1, 125 | # ceil: 1, 126 | # clip: 3, 127 | complex: 2, 128 | # conjugate: 1, 129 | # cos: 1, 130 | # cosh: 1, 131 | # count_leading_zeros: 1, 132 | # divide: 2, 133 | # equal: 2, 134 | # erf: 1, 135 | # erf_inv: 1, 136 | # erlc: 1, 137 | # exp: 1, 138 | # expm1: 1, 139 | # floor: 1, 140 | # greater: 2, 141 | # greater_equal: 2, 142 | # imag: 1, 143 | # is_infinity: 1, 144 | # is_nan: 1, 145 | # left_shift: 2, 146 | # less: 2, 147 | # less_equal: 2, 148 | # log1p: 1, 149 | # log: 1, 150 | # logical_and: 2, 151 | logical_not: 1, 152 | # logical_or: 2, 153 | # logical_xor: 2, 154 | map: 3, 155 | # max: 2, 156 | # min: 2, 157 | multiply: 2, 158 | # negate: 1, 159 | # not_equal: 2, 160 | phase: 1, 161 | # population_count: 1, 162 | # power: 2, 163 | # quotient: 2, 164 | # real: 1, 165 | # remainder: 2, 166 | # right_shift: 2, 167 | # round: 1, 168 | # rsqrt: 1, 169 | # select: 3, 170 | # sigmoid: 1, 171 | # sign: 1, 172 | # sin: 1, 173 | # sinh: 1, 174 | # sqrt: 1, 175 | # subtract: 2, 176 | # tan: 1, 177 | # tanh: 1, 178 | # gather: 2, 179 | # indexed_add: 3, 180 | # indexed_put: 3, 181 | put_slice: 3, 182 | slice: 4, 183 | # slice_along_axis: 4, 184 | # take: 3, 185 | # take_along_axis: 3, 186 | # argsort: 2, 187 | concatenate: 2, 188 | # conv: 3, 189 | dot: 2, 190 | # dot: 4, 191 | # dot: 6, 192 | # fft: 2, 193 | # ifft: 2, 194 | # outer: 2, 195 | # reverse: 2, 196 | # sort: 2, 197 | # stack: 2, 198 | # axes: 1, 199 | # axis_index: 2, 200 | # axis_size: 2, 201 | # broadcast: 3, 202 | # byte_size: 1, 203 | # compatible?: 2, 204 | # flatten: 1, 205 | # names: 1, 206 | # new_axis: 3, 207 | # pad: 3, 208 | # rank: 1, 209 | # reshape: 3, 210 | # shape: 1, 211 | # size: 1, 212 | # squeeze: 2, 213 | # tile: 2, 214 | # transpose: 2, 215 | # as_type: 2, 216 | # bitcast: 2, 217 | # type: 1, 218 | # window_max: 3, 219 | # window_mean: 3, 220 | # window_min: 3, 221 | # window_product: 3, 222 | # window_reduce: 5, 223 | window_scatter_max: 5, 224 | window_scatter_min: 5 225 | # window_sum: 3 226 | ] 227 | 228 | doctest Nx, 229 | except: 230 | [:moduledoc] ++ 231 | @precision_error_doctests ++ 232 | @temporarily_broken_doctests ++ 233 | @inherently_unsupported_doctests ++ 234 | @unrelated_doctests ++ 235 | @untest_doctests 236 | end 237 | -------------------------------------------------------------------------------- /backends/pelemay_backend/test/pelemay_backend/engine_test.exs: -------------------------------------------------------------------------------- 1 | defmodule PelemayBackend.EngineTest do 2 | use ExUnit.Case 3 | doctest PelemayBackend.Engine 4 | end 5 | -------------------------------------------------------------------------------- /backends/pelemay_backend/test/pelemay_backend_test.exs: -------------------------------------------------------------------------------- 1 | defmodule PelemayBackendTest do 2 | use ExUnit.Case 3 | 4 | doctest PelemayBackend, 5 | except: [stream_cached?: 3, cached?: 3, jit: 2, jit_apply: 3, compile: 3] 6 | 7 | test "multiply scalar and vector(1000)" do 8 | input = Nx.iota({1000}, type: {:f, 32}) 9 | fun = &Nx.multiply(&1, &2) 10 | result = fun.(2.0, input) 11 | assert result == PelemayBackend.jit_apply(fun, [2.0, input]) 12 | assert result == PelemayBackend.jit_apply(fun, [input, 2.0]) 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /backends/pelemay_backend/test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /benchmarks/distributed_computing_bench/.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /benchmarks/distributed_computing_bench/.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | distributed_computing_bench-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /benchmarks/distributed_computing_bench/README.md: -------------------------------------------------------------------------------- 1 | # DistributedComputingBench 2 | 3 | **TODO: Add description** 4 | 5 | ## Installation 6 | 7 | If [available in Hex](https://hex.pm/docs/publish), the package can be installed 8 | by adding `distributed_computing_bench` to your list of dependencies in `mix.exs`: 9 | 10 | ```elixir 11 | def deps do 12 | [ 13 | {:distributed_computing_bench, "~> 0.1.0"} 14 | ] 15 | end 16 | ``` 17 | 18 | Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc) 19 | and published on [HexDocs](https://hexdocs.pm). Once published, the docs can 20 | be found at . 21 | 22 | -------------------------------------------------------------------------------- /benchmarks/distributed_computing_bench/lib/distributed_computing_bench.ex: -------------------------------------------------------------------------------- 1 | defmodule DistributedComputingBench do 2 | @moduledoc """ 3 | Documentation for `DistributedComputingBench`. 4 | """ 5 | end 6 | -------------------------------------------------------------------------------- /benchmarks/distributed_computing_bench/lib/distributed_computing_bench/bumblebee_bench.ex: -------------------------------------------------------------------------------- 1 | defmodule DistributedComputingBench.BumblebeeBench do 2 | @moduledoc """ 3 | Documentation for `DistributedComputingBench.BumblebeeBench`. 4 | """ 5 | 6 | require Logger 7 | 8 | def run() do 9 | System.cmd( 10 | "mix", 11 | [ 12 | "run", 13 | "-r", 14 | "lib/distributed_computing_bench/bumblebee_bench/runner.exs", 15 | "-e", 16 | "DistributedComputingBench.BumblebeeBench.Runner.run" 17 | ], 18 | env: [ 19 | {"MIX_ENV", "bumblebee_bench"} 20 | ] 21 | ) 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /benchmarks/distributed_computing_bench/lib/distributed_computing_bench/bumblebee_bench/runner.exs: -------------------------------------------------------------------------------- 1 | defmodule DistributedComputingBench.BumblebeeBench.Runner do 2 | @moduledoc false 3 | 4 | def run() do 5 | Nx.default_backend(EXLA.Backend) 6 | 7 | {:ok, model_info} = Bumblebee.load_model({:hf, "google/vit-base-patch16-224"}) 8 | {:ok, featurizer} = Bumblebee.load_featurizer({:hf, "google/vit-base-patch16-224"}) 9 | 10 | serving = 11 | Bumblebee.Vision.image_classification(model_info, featurizer, 12 | compile: [batch_size: 1], 13 | defn_options: [compiler: EXLA], 14 | top_k: 1 15 | ) 16 | 17 | Nx.Serving.start_link(name: ViT, serving: serving) 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /benchmarks/distributed_computing_bench/mix.exs: -------------------------------------------------------------------------------- 1 | defmodule DistributedComputingBench.MixProject do 2 | use Mix.Project 3 | 4 | @version "0.1.0" 5 | 6 | def project do 7 | [ 8 | app: :distributed_computing_bench, 9 | version: @version, 10 | elixir: "~> 1.14", 11 | start_permanent: Mix.env() == :prod, 12 | deps: deps(), 13 | preferred_cli_env: %{ 14 | bumblebee_bench: :bumblebee_bench, 15 | credo: :test, 16 | dialyzer: :test, 17 | docs: :docs, 18 | "hex.publish": :docs, 19 | "hex.build": :docs 20 | } 21 | ] 22 | end 23 | 24 | # Run "mix help compile.app" to learn about applications. 25 | def application do 26 | case Mix.env() do 27 | :bumblebee_bench -> 28 | [ 29 | extra_applications: [:logger, :exla] 30 | ] 31 | 32 | :test -> 33 | [ 34 | extra_applications: [:logger, :exla] 35 | ] 36 | 37 | _ -> 38 | [ 39 | extra_applications: [:logger] 40 | ] 41 | end 42 | end 43 | 44 | # Run "mix help deps" to learn about dependencies. 45 | defp deps do 46 | [ 47 | {:dialyxir, "~> 1.3", only: :test, runtime: false}, 48 | {:credo, "~> 1.7", only: :test, runtime: false}, 49 | {:ex_doc, "~> 0.29", only: :docs, runtime: false}, 50 | {:http_downloader, "~> 0.1"}, 51 | {:spawn_co_elixir, "~> 0.3"}, 52 | {:nx, "~> 0.5"}, 53 | {:bumblebee, "~> 0.4.2", only: [:bumblebee_bench, :test]}, 54 | {:exla, "~> 0.5", only: [:bumblebee_bench, :test]}, 55 | {:benchee, "~> 1.1"} 56 | ] 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /benchmarks/distributed_computing_bench/test/distributed_computing_bench_test.exs: -------------------------------------------------------------------------------- 1 | defmodule DistributedComputingBenchTest do 2 | use ExUnit.Case 3 | doctest DistributedComputingBench 4 | end 5 | -------------------------------------------------------------------------------- /benchmarks/distributed_computing_bench/test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /utilities/backend_decorator/.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /utilities/backend_decorator/.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | backend_decorator-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /utilities/backend_decorator/README.md: -------------------------------------------------------------------------------- 1 | # BackendDecorator 2 | 3 | 4 | A backend generator to decorate the specified `based_backend` with the functions before and after a set of functions in the backend. The set can be specified with the style of [AspectJ, which is an AOP language](https://en.wikipedia.org/wiki/Aspect-oriented_programming), and with grouping written in [hexdocs of Nx](https://hexdocs.pm/nx/Nx.html), for example, Aggregates, Backend, Conversion, and so on. 5 | 6 | 7 | ## Installation 8 | 9 | ```elixir 10 | def deps do 11 | [ 12 | {:backend_decorator, "~> 0.1.0-dev", github: "zeam-vm/pelemay_backend", sparse: "utilities/backend_decorator"} 13 | ] 14 | end 15 | ``` 16 | 17 | ## License 18 | 19 | Copyright (c) 2023 University of Kitakyushu 20 | 21 | Licensed under the Apache License, Version 2.0 (the "License"); 22 | you may not use this file except in compliance with the License. 23 | You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) 24 | 25 | Unless required by applicable law or agreed to in writing, software 26 | distributed under the License is distributed on an "AS IS" BASIS, 27 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 28 | See the License for the specific language governing permissions and 29 | limitations under the License. 30 | 31 | ## Acknowledgement 32 | 33 | This work was supported by Asahi Kohsan Group Research Support Program of Kitakyushu Foundation for the Advancement of Industry Science and Technology (FAIS). 34 | -------------------------------------------------------------------------------- /utilities/backend_decorator/lib/backend_decorator.ex: -------------------------------------------------------------------------------- 1 | defmodule BackendDecorator do 2 | @moduledoc File.read!("README.md") 3 | |> String.split("") 4 | |> Enum.fetch!(1) 5 | end 6 | -------------------------------------------------------------------------------- /utilities/backend_decorator/mix.exs: -------------------------------------------------------------------------------- 1 | defmodule BackendDecorator.MixProject do 2 | use Mix.Project 3 | 4 | @nx_version "0.5.3" 5 | @version "0.1.0-dev" 6 | 7 | def project do 8 | [ 9 | app: :backend_decorator, 10 | version: @version, 11 | elixir: "~> 1.14", 12 | start_permanent: Mix.env() == :prod, 13 | deps: deps() 14 | ] 15 | end 16 | 17 | # Run "mix help compile.app" to learn about applications. 18 | def application do 19 | [ 20 | extra_applications: [:logger] 21 | ] 22 | end 23 | 24 | # Run "mix help deps" to learn about dependencies. 25 | defp deps do 26 | [ 27 | {:dialyxir, "~> 1.3", only: [:dev], runtime: false}, 28 | {:credo, "~> 1.7", only: [:dev, :test], runtime: false}, 29 | {:nx, "~> #{@nx_version}"} 30 | ] 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /utilities/backend_decorator/mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, 3 | "complex": {:hex, :complex, "0.5.0", "af2d2331ff6170b61bb738695e481b27a66780e18763e066ee2cd863d0b1dd92", [:mix], [], "hexpm", "2683bd3c184466cfb94fad74cbfddfaa94b860e27ad4ca1bffe3bff169d91ef1"}, 4 | "credo": {:hex, :credo, "1.7.7", "771445037228f763f9b2afd612b6aa2fd8e28432a95dbbc60d8e03ce71ba4446", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "8bc87496c9aaacdc3f90f01b7b0582467b69b4bd2441fe8aae3109d843cc2f2e"}, 5 | "dialyxir": {:hex, :dialyxir, "1.4.3", "edd0124f358f0b9e95bfe53a9fcf806d615d8f838e2202a9f430d59566b6b53b", [:mix], [{:erlex, ">= 0.2.6", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "bf2cfb75cd5c5006bec30141b131663299c661a864ec7fbbc72dfa557487a986"}, 6 | "erlex": {:hex, :erlex, "0.2.6", "c7987d15e899c7a2f34f5420d2a2ea0d659682c06ac607572df55a43753aa12e", [:mix], [], "hexpm", "2ed2e25711feb44d52b17d2780eabf998452f6efda104877a3881c2f8c0c0c75"}, 7 | "file_system": {:hex, :file_system, "1.0.0", "b689cc7dcee665f774de94b5a832e578bd7963c8e637ef940cd44327db7de2cd", [:mix], [], "hexpm", "6752092d66aec5a10e662aefeed8ddb9531d79db0bc145bb8c40325ca1d8536d"}, 8 | "jason": {:hex, :jason, "1.4.1", "af1504e35f629ddcdd6addb3513c3853991f694921b1b9368b0bd32beb9f1b63", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "fbb01ecdfd565b56261302f7e1fcc27c4fb8f32d56eab74db621fc154604a7a1"}, 9 | "nx": {:hex, :nx, "0.5.3", "6ad5534f9b82429dafa12329952708c2fdd6ab01b306e86333fdea72383147ee", [:mix], [{:complex, "~> 0.5", [hex: :complex, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "d1072fc4423809ed09beb729e73c200ce177ddecac425d9eb6fba643669623ec"}, 10 | "telemetry": {:hex, :telemetry, "1.2.1", "68fdfe8d8f05a8428483a97d7aab2f268aaff24b49e0f599faa091f1d4e7f61c", [:rebar3], [], "hexpm", "dad9ce9d8effc621708f99eac538ef1cbe05d6a874dd741de2e689c47feafed5"}, 11 | } 12 | -------------------------------------------------------------------------------- /utilities/backend_decorator/test/backend_decorator_test.exs: -------------------------------------------------------------------------------- 1 | defmodule BackendDecoratorTest do 2 | use ExUnit.Case 3 | doctest BackendDecorator 4 | end 5 | -------------------------------------------------------------------------------- /utilities/backend_decorator/test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /utilities/http_downloader/.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /utilities/http_downloader/.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | http_downloader-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /utilities/http_downloader/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog for 0.3.0 2 | 3 | ## 1. Enhancements 4 | 5 | * Update Req to 0.4.1 6 | 7 | ## 2. Bug fixes 8 | 9 | ## 3. Soft deprecations (no warnings emitted) 10 | 11 | ## 4. Hard deprecations 12 | -------------------------------------------------------------------------------- /utilities/http_downloader/README.md: -------------------------------------------------------------------------------- 1 | # HttpDownloader 2 | 3 | 4 | Downloads remote file with progress bar. 5 | 6 | 7 | ## Installation 8 | 9 | Just add `http_downloader` to your list of dependencies in `mix.exs`: 10 | 11 | ```elixir 12 | def deps do 13 | [ 14 | {:http_downloader, "~> 0.1.0"} 15 | ] 16 | end 17 | ``` 18 | 19 | In notebooks and scripts, use the following `Mix.install/2` call: 20 | 21 | ```elixir 22 | Mix.install( 23 | [ 24 | {:http_downloader, "~> 0.1.0"} 25 | ] 26 | ) 27 | ``` 28 | 29 | ## Usage 30 | 31 | ```elixir 32 | {:ok, data} = HttpDownloader.download!("http://speedtest.ftp.otenet.gr/files/test100k.db") 33 | ``` 34 | 35 | ## License 36 | 37 | Copyright (c) 2023 University of Kitakyushu 38 | 39 | Licensed under the Apache License, Version 2.0 (the "License"); 40 | you may not use this file except in compliance with the License. 41 | You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) 42 | 43 | Unless required by applicable law or agreed to in writing, software 44 | distributed under the License is distributed on an "AS IS" BASIS, 45 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 46 | See the License for the specific language governing permissions and 47 | limitations under the License. 48 | 49 | ## Acknowledgement 50 | 51 | This work was supported by Asahi Kohsan Group Research Support Program of 52 | Kitakyushu Foundation for the Advancement of Industry Science and Technology 53 | (FAIS). 54 | -------------------------------------------------------------------------------- /utilities/http_downloader/lib/http_downloader.ex: -------------------------------------------------------------------------------- 1 | defmodule HttpDownloader do 2 | @moduledoc File.read!("README.md") 3 | |> String.split("") 4 | |> Enum.fetch!(1) 5 | 6 | require Logger 7 | 8 | @type url :: URI.t() | String.t() 9 | 10 | @doc """ 11 | Downloads a remote file with progress bar. 12 | 13 | Currently built on top of the req package. 14 | For a list of available options, See https://hexdocs.pm/req/Req.html#new/1. 15 | """ 16 | @spec download(url(), keyword()) :: {:ok, binary()} | {:error, any()} 17 | def download(source_url, req_options \\ []) do 18 | case Req.get(source_url, [finch_request: &finch_request/4] ++ req_options) do 19 | {:ok, response} when response.status == 200 -> {:ok, response.body} 20 | {:ok, response} -> {:error, response.body} 21 | {:error, reason} -> {:error, reason} 22 | end 23 | end 24 | 25 | @doc """ 26 | Downloads a remote file with progress bar. 27 | 28 | Currently built on top of the req package. 29 | For a list of available options, See https://hexdocs.pm/req/Req.html#new/1. 30 | """ 31 | @spec download!(url(), keyword()) :: binary() 32 | def download!(source_url, req_options \\ []) do 33 | case Req.get!(source_url, [finch_request: &finch_request/4] ++ req_options) do 34 | response when response.status == 200 -> response.body 35 | response -> raise(response.body) 36 | end 37 | end 38 | 39 | @doc """ 40 | Returns the last component of the path. 41 | """ 42 | @spec basename_from_uri(url() | struct()) :: String.t() 43 | def basename_from_uri(url) when is_binary(url) do 44 | Path.basename(url) 45 | end 46 | 47 | def basename_from_uri(url) when is_map_key(url, :path) do 48 | URI.parse(url) |> Map.get(:path) |> Path.basename() 49 | end 50 | 51 | @doc """ 52 | Downloads multiple remote files with progress bar and save them to provided 53 | destination. 54 | """ 55 | @spec download_files([url()], String.t()) :: [String.t()] 56 | def download_files(files, dst_path) do 57 | Enum.map(files, fn url -> 58 | basename = basename_from_uri(url) 59 | 60 | dst_path = Path.join(dst_path, basename) 61 | 62 | dst_path 63 | |> File.exists?() 64 | |> case do 65 | true -> 66 | Logger.info("File #{basename} has already been downloaded.") 67 | 68 | false -> 69 | Logger.info("File #{basename} will be downloaded...") 70 | download!(url, output: dst_path, max_redirects: 5, redirect_log_level: false) 71 | end 72 | end) 73 | end 74 | 75 | defp finch_request(req_request, finch_request, finch_name, finch_options) do 76 | acc = Req.Response.new() 77 | 78 | case Finch.stream(finch_request, finch_name, acc, &handle_message/2, finch_options) do 79 | {:ok, response} -> {req_request, response} 80 | {:error, reason} -> {req_request, reason} 81 | end 82 | end 83 | 84 | defp handle_message({:status, status}, response), do: %{response | status: status} 85 | 86 | defp handle_message({:headers, headers}, response) do 87 | {_, total_size} = 88 | Enum.find(headers, fn 89 | {"content-length", v} -> String.to_integer(v) 90 | {_, _} -> nil 91 | end) 92 | 93 | response 94 | |> Map.put(:headers, headers) 95 | |> Map.put(:private, %{total_size: String.to_integer(total_size), downloaded_size: 0}) 96 | end 97 | 98 | defp handle_message({:data, data}, response) do 99 | total_size = response.private.total_size 100 | 101 | if total_size > 0 do 102 | handle_message_data(data, response) 103 | else 104 | response 105 | end 106 | end 107 | 108 | defp handle_message_data(data, response) do 109 | new_downloaded_size = response.private.downloaded_size + byte_size(data) 110 | ProgressBar.render(new_downloaded_size, response.private.total_size, suffix: :bytes) 111 | 112 | response 113 | |> Map.update!(:body, &(&1 <> data)) 114 | |> Map.update!(:private, &%{&1 | downloaded_size: new_downloaded_size}) 115 | end 116 | end 117 | -------------------------------------------------------------------------------- /utilities/http_downloader/mix.exs: -------------------------------------------------------------------------------- 1 | defmodule HttpDownloader.MixProject do 2 | use Mix.Project 3 | 4 | @version "0.3.0" 5 | @source_url "https://github.com/zeam-vm/pelemay_backend" 6 | 7 | def project do 8 | [ 9 | app: :http_downloader, 10 | version: @version, 11 | elixir: "~> 1.14", 12 | start_permanent: Mix.env() == :prod, 13 | deps: deps(), 14 | docs: docs(), 15 | preferred_cli_env: %{ 16 | credo: :test, 17 | dialyzer: :test, 18 | docs: :docs, 19 | "hex.publish": :docs, 20 | "hex.build": :docs 21 | }, 22 | name: "HttpDownloader", 23 | description: "Downloads remote file with progress bar.", 24 | package: package() 25 | ] 26 | end 27 | 28 | # Run "mix help compile.app" to learn about applications. 29 | def application do 30 | [ 31 | extra_applications: [:logger] 32 | ] 33 | end 34 | 35 | # Run "mix help deps" to learn about dependencies. 36 | defp deps do 37 | [ 38 | {:dialyxir, "~> 1.3", only: :test, runtime: false}, 39 | {:credo, "~> 1.7", only: :test, runtime: false}, 40 | {:ex_doc, "~> 0.29", only: :docs, runtime: false}, 41 | {:req, "~> 0.4"}, 42 | {:progress_bar, "~> 3.0"} 43 | ] 44 | end 45 | 46 | defp docs do 47 | [ 48 | main: "HttpDownloader", 49 | source_url_pattern: 50 | "#{@source_url}/blob/v#{@version}/utilities/http_downloaderr/%{path}#L%{line}", 51 | extras: [ 52 | "README.md", 53 | "CHANGELOG.md" 54 | ] 55 | ] 56 | end 57 | 58 | defp package do 59 | [ 60 | maintainers: ["Susumu Yamazaki", "Masatoshi Nishiguchi"], 61 | licenses: ["Apache-2.0"], 62 | links: %{"GitHub" => @source_url} 63 | ] 64 | end 65 | end 66 | -------------------------------------------------------------------------------- /utilities/http_downloader/mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, 3 | "castore": {:hex, :castore, "1.0.8", "dedcf20ea746694647f883590b82d9e96014057aff1d44d03ec90f36a5c0dc6e", [:mix], [], "hexpm", "0b2b66d2ee742cb1d9cb8c8be3b43c3a70ee8651f37b75a8b982e036752983f1"}, 4 | "credo": {:hex, :credo, "1.7.11", "d3e805f7ddf6c9c854fd36f089649d7cf6ba74c42bc3795d587814e3c9847102", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "56826b4306843253a66e47ae45e98e7d284ee1f95d53d1612bb483f88a8cf219"}, 5 | "decimal": {:hex, :decimal, "2.3.0", "3ad6255aa77b4a3c4f818171b12d237500e63525c2fd056699967a3e7ea20f62", [:mix], [], "hexpm", "a4d66355cb29cb47c3cf30e71329e58361cfcb37c34235ef3bf1d7bf3773aeac"}, 6 | "dialyxir": {:hex, :dialyxir, "1.4.5", "ca1571ac18e0f88d4ab245f0b60fa31ff1b12cbae2b11bd25d207f865e8ae78a", [:mix], [{:erlex, ">= 0.2.7", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "b0fb08bb8107c750db5c0b324fa2df5ceaa0f9307690ee3c1f6ba5b9eb5d35c3"}, 7 | "earmark_parser": {:hex, :earmark_parser, "1.4.42", "f23d856f41919f17cd06a493923a722d87a2d684f143a1e663c04a2b93100682", [:mix], [], "hexpm", "6915b6ca369b5f7346636a2f41c6a6d78b5af419d61a611079189233358b8b8b"}, 8 | "erlex": {:hex, :erlex, "0.2.7", "810e8725f96ab74d17aac676e748627a07bc87eb950d2b83acd29dc047a30595", [:mix], [], "hexpm", "3ed95f79d1a844c3f6bf0cea61e0d5612a42ce56da9c03f01df538685365efb0"}, 9 | "ex_doc": {:hex, :ex_doc, "0.36.1", "4197d034f93e0b89ec79fac56e226107824adcce8d2dd0a26f5ed3a95efc36b1", [:mix], [{:earmark_parser, "~> 1.4.42", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "d7d26a7cf965dacadcd48f9fa7b5953d7d0cfa3b44fa7a65514427da44eafd89"}, 10 | "file_system": {:hex, :file_system, "1.0.1", "79e8ceaddb0416f8b8cd02a0127bdbababe7bf4a23d2a395b983c1f8b3f73edd", [:mix], [], "hexpm", "4414d1f38863ddf9120720cd976fce5bdde8e91d8283353f0e31850fa89feb9e"}, 11 | "finch": {:hex, :finch, "0.19.0", "c644641491ea854fc5c1bbaef36bfc764e3f08e7185e1f084e35e0672241b76d", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.6.2 or ~> 1.7", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "fc5324ce209125d1e2fa0fcd2634601c52a787aff1cd33ee833664a5af4ea2b6"}, 12 | "hpax": {:hex, :hpax, "1.0.1", "c857057f89e8bd71d97d9042e009df2a42705d6d690d54eca84c8b29af0787b0", [:mix], [], "hexpm", "4e2d5a4f76ae1e3048f35ae7adb1641c36265510a2d4638157fbcb53dda38445"}, 13 | "jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"}, 14 | "makeup": {:hex, :makeup, "1.2.1", "e90ac1c65589ef354378def3ba19d401e739ee7ee06fb47f94c687016e3713d1", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "d36484867b0bae0fea568d10131197a4c2e47056a6fbe84922bf6ba71c8d17ce"}, 15 | "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"}, 16 | "makeup_erlang": {:hex, :makeup_erlang, "1.0.1", "c7f58c120b2b5aa5fd80d540a89fdf866ed42f1f3994e4fe189abebeab610839", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "8a89a1eeccc2d798d6ea15496a6e4870b75e014d1af514b1b71fa33134f57814"}, 17 | "mime": {:hex, :mime, "2.0.6", "8f18486773d9b15f95f4f4f1e39b710045fa1de891fada4516559967276e4dc2", [:mix], [], "hexpm", "c9945363a6b26d747389aac3643f8e0e09d30499a138ad64fe8fd1d13d9b153e"}, 18 | "mint": {:hex, :mint, "1.6.2", "af6d97a4051eee4f05b5500671d47c3a67dac7386045d87a904126fd4bbcea2e", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 0.1.1 or ~> 0.2.0 or ~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "5ee441dffc1892f1ae59127f74afe8fd82fda6587794278d924e4d90ea3d63f9"}, 19 | "nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"}, 20 | "nimble_ownership": {:hex, :nimble_ownership, "0.3.1", "99d5244672fafdfac89bfad3d3ab8f0d367603ce1dc4855f86a1c75008bce56f", [:mix], [], "hexpm", "4bf510adedff0449a1d6e200e43e57a814794c8b5b6439071274d248d272a549"}, 21 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"}, 22 | "nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"}, 23 | "progress_bar": {:hex, :progress_bar, "3.0.0", "f54ff038c2ac540cfbb4c2bfe97c75e7116ead044f3c2b10c9f212452194b5cd", [:mix], [{:decimal, "~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}], "hexpm", "6981c2b25ab24aecc91a2dc46623658e1399c21a2ae24db986b90d678530f2b7"}, 24 | "req": {:hex, :req, "0.5.8", "50d8d65279d6e343a5e46980ac2a70e97136182950833a1968b371e753f6a662", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:ezstd, "~> 1.0", [hex: :ezstd, repo: "hexpm", optional: true]}, {:finch, "~> 0.17", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "d7fc5898a566477e174f26887821a3c5082b243885520ee4b45555f5d53f40ef"}, 25 | "telemetry": {:hex, :telemetry, "1.3.0", "fedebbae410d715cf8e7062c96a1ef32ec22e764197f70cda73d82778d61e7a2", [:rebar3], [], "hexpm", "7015fc8919dbe63764f4b4b87a95b7c0996bd539e0d499be6ec9d7f3875b79e6"}, 26 | } 27 | -------------------------------------------------------------------------------- /utilities/http_downloader/test/http_downloader_test.exs: -------------------------------------------------------------------------------- 1 | defmodule HttpDownloaderTest do 2 | use ExUnit.Case 3 | doctest HttpDownloader 4 | 5 | setup do 6 | url = "http://example.com" 7 | ok_mock = fn request -> {request, Req.Response.new(status: 200, body: "😊")} end 8 | bad_mock = fn request -> {request, Req.Response.new(status: 400, body: "😡")} end 9 | 10 | %{url: url, mock: %{ok: ok_mock, bad: bad_mock}} 11 | end 12 | 13 | describe "download/2" do 14 | test "returns ok tuple when successful", %{url: url, mock: mock} do 15 | assert {:ok, "😊"} = HttpDownloader.download(url, adapter: mock.ok) 16 | end 17 | 18 | test "returns error tuple with bad request", %{url: url, mock: mock} do 19 | assert {:error, "😡"} = HttpDownloader.download(url, adapter: mock.bad) 20 | end 21 | end 22 | 23 | describe "download!/2" do 24 | test "returns data when successful", %{url: url, mock: mock} do 25 | assert "😊" = HttpDownloader.download!(url, adapter: mock.ok) 26 | end 27 | 28 | test "raises with bad request", %{url: url, mock: mock} do 29 | assert_raise RuntimeError, "😡", fn -> 30 | HttpDownloader.download!(url, adapter: mock.bad) 31 | end 32 | end 33 | end 34 | 35 | describe "basename_from_uri/1" do 36 | test "returns basename when string url is provided" do 37 | assert "3.dat" = HttpDownloader.basename_from_uri("http://example.com/1/2/3.dat") 38 | end 39 | 40 | test "returns basename when struct url is provided" do 41 | uri = URI.new!("http://example.com/1/2/3.dat") 42 | assert "3.dat" = HttpDownloader.basename_from_uri(uri) 43 | end 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /utilities/http_downloader/test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /utilities/node_activator/.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /utilities/node_activator/.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | node_activator-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /utilities/node_activator/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog for 0.2.0 2 | 3 | ## 1. Enhancements 4 | 5 | * Add `NodeActivator.epmd_running?/0` 6 | 7 | ## 2. Bug fixes 8 | 9 | * Rename one of test code. 10 | * Fix the issue of fully-qualified hostname on Linux. It requires to use IP address instead of hostname. 11 | 12 | ## 3. Soft deprecations (no warnings emitted) 13 | 14 | ## 4. Hard deprecations 15 | 16 | * Deprecate supporting Windows, temporally. To recover it, need to fix the issue that Node does not respond on Windows (related to #187). 17 | 18 | -------------------------------------------------------------------------------- /utilities/node_activator/README.md: -------------------------------------------------------------------------------- 1 | # NodeActivator 2 | 3 | 4 | A module to activate VM nodes. 5 | 6 | 7 | ## Installation 8 | 9 | In order to use `NodeActivator`, you will need Elixir installed. Then create an Elixir project via the `mix` build tool. For example, if your project is `my_app`, you may run the following command. 10 | 11 | ```sh 12 | $ mix new my_app 13 | ``` 14 | 15 | Then you can add `NodeActivator` to the list of dependencies in your `mix.exs`: 16 | 17 | ```elixir 18 | def deps do 19 | [ 20 | {:node_activator, "~> 0.1"} 21 | ] 22 | end 23 | ``` 24 | 25 | If you are using Livebook or IEx, you can instead run: 26 | 27 | ```elixir 28 | Mix.install([ 29 | {:node_activator, "~> 0.1"} 30 | ]) 31 | ``` 32 | 33 | ## License 34 | 35 | Copyright (c) 2023 University of Kitakyushu 36 | 37 | Licensed under the Apache License, Version 2.0 (the "License"); 38 | you may not use this file except in compliance with the License. 39 | You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) 40 | 41 | Unless required by applicable law or agreed to in writing, software 42 | distributed under the License is distributed on an "AS IS" BASIS, 43 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 44 | See the License for the specific language governing permissions and 45 | limitations under the License. 46 | 47 | ## Acknowledgement 48 | 49 | This work was supported by Asahi Kohsan Group Research Support Program of Kitakyushu Foundation for the Advancement of Industry Science and Technology (FAIS). 50 | 51 | -------------------------------------------------------------------------------- /utilities/node_activator/lib/node_activator.ex: -------------------------------------------------------------------------------- 1 | defmodule NodeActivator do 2 | @moduledoc File.read!("README.md") 3 | |> String.split("") 4 | |> Enum.fetch!(1) 5 | 6 | require Logger 7 | alias NodeActivator.Epmd 8 | alias NodeActivator.Utils 9 | 10 | @doc """ 11 | Turns a non-distributed node into a distributed node after ensuring 12 | that the `epmd` operation system process is running. Returns the name of the 13 | started distributed node. The node name will be generated by appending 14 | a random string to the provided `node_name_prefix` string. 15 | 16 | This function does nothing when the distribution has already 17 | been started. 18 | 19 | For more info, see `Node`. 20 | 21 | ## Examples 22 | 23 | {:ok, node_name} = NodeActivator.run("foo") 24 | 25 | """ 26 | @spec run(binary()) :: {:ok, node()} | {:error, any()} 27 | def run(node_name_prefix) do 28 | if Node.alive?() do 29 | {:ok, Node.self()} 30 | else 31 | start_distributed_node(node_name_prefix) 32 | end 33 | end 34 | 35 | @doc """ 36 | Checks if the `epmd` process is running. 37 | """ 38 | @spec epmd_running?() :: boolean() 39 | defdelegate epmd_running?(), to: Epmd 40 | 41 | defp start_distributed_node(node_name_prefix) do 42 | Epmd.launch_epmd() 43 | 44 | name = Utils.generate_node_name(node_name_prefix) 45 | Logger.info("starting node #{name}") 46 | 47 | case Node.start(name) do 48 | {:ok, _node} -> 49 | Logger.info("Node #{name} has been launched.") 50 | {:ok, Node.self()} 51 | 52 | {:error, error} -> 53 | Logger.error("Node #{name} cannot be launched.") 54 | {:error, error} 55 | end 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /utilities/node_activator/lib/node_activator/epmd.ex: -------------------------------------------------------------------------------- 1 | defmodule NodeActivator.Epmd do 2 | @moduledoc false 3 | 4 | require Logger 5 | 6 | @epmd_port 4369 7 | 8 | @doc """ 9 | Launch the the `epmd` process. 10 | """ 11 | @spec launch_epmd() :: :ok 12 | def launch_epmd() do 13 | options = 14 | case :os.type() do 15 | {:unix, _} -> [port: @epmd_port] 16 | {:win32, _} -> [port: @epmd_port] 17 | end 18 | 19 | epmd_cmd = System.find_executable("epmd") 20 | epmd_options = epmd_options_to_list(options) 21 | 22 | if is_nil(epmd_cmd) do 23 | Logger.error("Fail to find epmd.") 24 | raise RuntimeError, "Fail to find epmd." 25 | end 26 | 27 | unless epmd_running?() do 28 | spawn_link(fn -> do_launch_epmd(epmd_cmd, epmd_options) end) 29 | end 30 | 31 | Logger.info("wait launching epmd...") 32 | wait_launching_epmd(5) 33 | Logger.info("done.") 34 | :ok 35 | end 36 | 37 | # Checks if the `epmd` process is running. 38 | @spec epmd_running?() :: boolean() 39 | def epmd_running?() do 40 | case :gen_tcp.connect(~c'localhost', @epmd_port, [:binary, active: false], 1000) do 41 | {:ok, socket} -> 42 | Logger.info("Port epmd is active.") 43 | :gen_tcp.close(socket) 44 | true 45 | 46 | {:error, reason} -> 47 | Logger.warning("Fail to connect due to #{inspect(reason)}.") 48 | false 49 | end 50 | end 51 | 52 | defp do_launch_epmd(epmd_cmd, epmd_options) do 53 | {result, exit_code} = System.cmd(epmd_cmd, epmd_options, parallelism: true) 54 | 55 | options_and_result = "#{Enum.join(epmd_options, " ")}: #{result}" 56 | 57 | if exit_code == 0 do 58 | Logger.info("epmd " <> options_and_result) 59 | else 60 | Logger.error("epmd " <> options_and_result <> ": error_code: #{exit_code}") 61 | raise RuntimeError, "Fail to launch epmd " <> options_and_result 62 | end 63 | end 64 | 65 | # Waits at most x seconds for the epmd process to be ready. Raises on timeout. 66 | defp wait_launching_epmd(0), do: raise(RuntimeError, "Fail to launch epmd.") 67 | 68 | defp wait_launching_epmd(count) do 69 | unless epmd_running?() do 70 | Process.sleep(1000) 71 | wait_launching_epmd(count - 1) 72 | end 73 | 74 | :ok 75 | end 76 | 77 | # Converts a keyword list to a list of strings for used of `System.cmd/3`. 78 | @spec epmd_options_to_list(keyword) :: [binary()] 79 | defp epmd_options_to_list(options) do 80 | Enum.map(options, fn 81 | {:adress, list} when is_binary(list) -> ["-address", list] 82 | {:port, no} when is_integer(no) -> ["-port", "#{no}"] 83 | {:debug, true} -> ["-debug"] 84 | {:debug, false} -> [] 85 | {:daemon, true} -> ["-daemon"] 86 | {:daemon, false} -> [] 87 | {:relaxed_command_check, true} -> ["-relaxed_command"] 88 | {:relaxed_command_check, false} -> [] 89 | {:packet_timeout, seconds} when is_integer(seconds) -> ["-packet_timeout", "#{seconds}"] 90 | {:delay_accept, seconds} when is_integer(seconds) -> ["-delay_accept", "#{seconds}"] 91 | {:delay_write, seconds} when is_integer(seconds) -> ["-delay_write", "#{seconds}"] 92 | {:kill, true} -> ["-kill"] 93 | {:kill, false} -> [] 94 | {:names, true} -> ["-names"] 95 | {:names, false} -> [] 96 | {:stop, name} when is_binary(name) -> ["-stop", name] 97 | end) 98 | |> List.flatten() 99 | end 100 | end 101 | -------------------------------------------------------------------------------- /utilities/node_activator/lib/node_activator/utils.ex: -------------------------------------------------------------------------------- 1 | defmodule NodeActivator.Utils do 2 | @moduledoc false 3 | 4 | require Logger 5 | 6 | @spec generate_node_name(binary()) :: atom() 7 | def generate_node_name(prefix) do 8 | prefix = Regex.replace(~r/\s/, prefix, "-") 9 | random_string = :crypto.strong_rand_bytes(5) |> Base.encode32(case: :lower) 10 | 11 | :"#{prefix}_#{random_string}@#{get_hostname()}" 12 | end 13 | 14 | @spec get_hostname() :: binary() 15 | def get_hostname() do 16 | Logger.debug("os.type: #{inspect(:os.type())}") 17 | 18 | hostname_cmd = System.find_executable("hostname") 19 | 20 | if is_nil(hostname_cmd) do 21 | raise RuntimeError, "Fail to find the \"hostname\" command." 22 | end 23 | 24 | {result, exit_code} = 25 | case :os.type() do 26 | {:unix, :darwin} -> System.cmd(hostname_cmd, ["-f"]) 27 | {:unix, _} -> System.cmd(hostname_cmd, ["-i"]) 28 | {:win32, _} -> System.cmd(hostname_cmd, []) 29 | end 30 | 31 | if exit_code > 0 do 32 | raise RuntimeError, "Fail to execute the \"hostname\" command." 33 | end 34 | 35 | hostname = 36 | result 37 | |> String.trim() 38 | 39 | Logger.debug("short hostname: #{hostname}") 40 | 41 | hostname = 42 | hostname 43 | |> to_fully_qualified_hostname(:os.type()) 44 | |> expand_ipv6() 45 | 46 | Logger.debug("fully qualified hostname: #{hostname}") 47 | hostname 48 | end 49 | 50 | defp to_fully_qualified_hostname(hostname, {:unix, _}), do: hostname 51 | 52 | defp to_fully_qualified_hostname(hostname, {:win32, _}) do 53 | ping_cmd = System.find_executable("ping") 54 | 55 | if is_nil(ping_cmd) do 56 | raise RuntimeError, "Fail to find the \"ping\" command." 57 | end 58 | 59 | {result, exit_code} = System.cmd(ping_cmd, ["/a", "/n", "1", hostname]) 60 | 61 | if exit_code > 0 do 62 | raise RuntimeError, "Fail to execute the \"ping\" command." 63 | end 64 | 65 | result 66 | |> String.trim() 67 | |> String.split("\n") 68 | |> Enum.at(1) 69 | |> then(&Regex.named_captures(~r/Reply from (?[0-9a-f:.]+)/, &1)) 70 | |> Map.get("ip") 71 | end 72 | 73 | defp expand_ipv6(hostname) do 74 | cond do 75 | Regex.match?(~r/^([0-9a-f]{1,4}:){7}[0-9a-f]{1,4}$/, hostname) -> 76 | hostname 77 | |> String.split(":") 78 | |> Enum.map(&"000#{&1}") 79 | |> Enum.map_join(":", &String.slice(&1, -4..-1)) 80 | 81 | Regex.match?(~r/^([0-9a-f]{1,4}[:]{1,2})+[0-9a-f]{1,4}$/, hostname) -> 82 | hostname 83 | |> String.split("::") 84 | |> Enum.map(&String.split(&1, ":")) 85 | |> Enum.map(&{&1, Enum.count(&1)}) 86 | |> Enum.unzip() 87 | |> then(fn {l, n} -> 88 | [ 89 | Enum.at(l, 0), 90 | 1..(8 - Enum.sum(n)) 91 | |> Enum.map(fn _ -> "0" end), 92 | Enum.at(l, 1) 93 | ] 94 | end) 95 | |> List.flatten() 96 | |> Enum.join(":") 97 | |> expand_ipv6() 98 | 99 | true -> 100 | hostname 101 | end 102 | end 103 | end 104 | -------------------------------------------------------------------------------- /utilities/node_activator/mix.exs: -------------------------------------------------------------------------------- 1 | defmodule NodeActivator.MixProject do 2 | use Mix.Project 3 | 4 | @version "0.2.0" 5 | @source_url "https://github.com/zeam-vm/pelemay_backend" 6 | 7 | def project do 8 | [ 9 | app: :node_activator, 10 | version: @version, 11 | elixir: "~> 1.14", 12 | deps: deps(), 13 | docs: docs(), 14 | name: "NodeActivator", 15 | description: "A module to activate VM nodes", 16 | package: package(), 17 | preferred_cli_env: %{ 18 | credo: :test, 19 | dialyzer: :test, 20 | docs: :docs, 21 | "hex.publish": :docs, 22 | "hex.build": :docs 23 | } 24 | ] 25 | end 26 | 27 | # Run "mix help compile.app" to learn about applications. 28 | def application do 29 | [ 30 | extra_applications: [:logger, :crypto] 31 | ] 32 | end 33 | 34 | # Run "mix help deps" to learn about dependencies. 35 | defp deps do 36 | [ 37 | {:dialyxir, "~> 1.3", only: :test, runtime: false}, 38 | {:credo, "~> 1.7", only: :test, runtime: false}, 39 | {:ex_doc, "~> 0.29", only: :docs, runtime: false} 40 | ] 41 | end 42 | 43 | defp package do 44 | [ 45 | maintainers: ["Susumu Yamazaki", "Masatoshi Nishiguchi"], 46 | licenses: ["Apache-2.0"], 47 | links: %{"GitHub" => @source_url} 48 | ] 49 | end 50 | 51 | defp docs do 52 | [ 53 | main: "NodeActivator", 54 | source_url_pattern: 55 | "#{@source_url}/blob/v#{@version}/utilities/node_activator/%{path}#L%{line}", 56 | extras: [ 57 | "README.md", 58 | "CHANGELOG.md" 59 | ] 60 | ] 61 | end 62 | end 63 | -------------------------------------------------------------------------------- /utilities/node_activator/mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, 3 | "credo": {:hex, :credo, "1.7.11", "d3e805f7ddf6c9c854fd36f089649d7cf6ba74c42bc3795d587814e3c9847102", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "56826b4306843253a66e47ae45e98e7d284ee1f95d53d1612bb483f88a8cf219"}, 4 | "dialyxir": {:hex, :dialyxir, "1.4.5", "ca1571ac18e0f88d4ab245f0b60fa31ff1b12cbae2b11bd25d207f865e8ae78a", [:mix], [{:erlex, ">= 0.2.7", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "b0fb08bb8107c750db5c0b324fa2df5ceaa0f9307690ee3c1f6ba5b9eb5d35c3"}, 5 | "earmark_parser": {:hex, :earmark_parser, "1.4.42", "f23d856f41919f17cd06a493923a722d87a2d684f143a1e663c04a2b93100682", [:mix], [], "hexpm", "6915b6ca369b5f7346636a2f41c6a6d78b5af419d61a611079189233358b8b8b"}, 6 | "erlex": {:hex, :erlex, "0.2.7", "810e8725f96ab74d17aac676e748627a07bc87eb950d2b83acd29dc047a30595", [:mix], [], "hexpm", "3ed95f79d1a844c3f6bf0cea61e0d5612a42ce56da9c03f01df538685365efb0"}, 7 | "ex_doc": {:hex, :ex_doc, "0.36.1", "4197d034f93e0b89ec79fac56e226107824adcce8d2dd0a26f5ed3a95efc36b1", [:mix], [{:earmark_parser, "~> 1.4.42", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "d7d26a7cf965dacadcd48f9fa7b5953d7d0cfa3b44fa7a65514427da44eafd89"}, 8 | "file_system": {:hex, :file_system, "1.0.1", "79e8ceaddb0416f8b8cd02a0127bdbababe7bf4a23d2a395b983c1f8b3f73edd", [:mix], [], "hexpm", "4414d1f38863ddf9120720cd976fce5bdde8e91d8283353f0e31850fa89feb9e"}, 9 | "jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"}, 10 | "makeup": {:hex, :makeup, "1.2.1", "e90ac1c65589ef354378def3ba19d401e739ee7ee06fb47f94c687016e3713d1", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "d36484867b0bae0fea568d10131197a4c2e47056a6fbe84922bf6ba71c8d17ce"}, 11 | "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"}, 12 | "makeup_erlang": {:hex, :makeup_erlang, "1.0.1", "c7f58c120b2b5aa5fd80d540a89fdf866ed42f1f3994e4fe189abebeab610839", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "8a89a1eeccc2d798d6ea15496a6e4870b75e014d1af514b1b71fa33134f57814"}, 13 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"}, 14 | } 15 | -------------------------------------------------------------------------------- /utilities/node_activator/test/node_activator/epmd_test.exs: -------------------------------------------------------------------------------- 1 | defmodule NodeActivatorTest.EpmdTest do 2 | use ExUnit.Case 3 | doctest NodeActivator.Epmd 4 | alias NodeActivator.Epmd 5 | 6 | describe "launch_epmd" do 7 | test "does not raise error" do 8 | assert :ok = Epmd.launch_epmd() 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /utilities/node_activator/test/node_activator/utils_test.exs: -------------------------------------------------------------------------------- 1 | defmodule NodeActivator.UtilsTest do 2 | use ExUnit.Case 3 | doctest NodeActivator.Utils 4 | alias NodeActivator.Utils 5 | 6 | describe "generate_node_name" do 7 | test "generates unique atom" do 8 | node_name1 = Utils.generate_node_name("test prefix") 9 | node_name2 = Utils.generate_node_name("test prefix") 10 | 11 | assert is_atom(node_name1) 12 | refute node_name1 == node_name2 13 | end 14 | 15 | test "starts with provided prefix" do 16 | node_name = Utils.generate_node_name("test prefix") 17 | 18 | assert node_name |> Atom.to_string() |> String.starts_with?("test-prefix_") 19 | end 20 | 21 | test "ends with hostname" do 22 | node_name = Utils.generate_node_name("test prefix") 23 | hostname = Utils.get_hostname() 24 | 25 | assert node_name |> Atom.to_string() |> String.ends_with?(hostname) 26 | end 27 | end 28 | 29 | describe "get_hostname" do 30 | test "returns non-blank string" do 31 | hostname = Utils.get_hostname() 32 | 33 | assert is_binary(hostname) 34 | assert String.length(String.trim(hostname)) > 0 35 | end 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /utilities/node_activator/test/node_activator_test.exs: -------------------------------------------------------------------------------- 1 | defmodule NodeActivatorTest do 2 | use ExUnit.Case 3 | doctest NodeActivator 4 | 5 | alias NodeActivator.Epmd 6 | 7 | setup do 8 | Node.stop() 9 | on_exit(fn -> Node.stop() end) 10 | end 11 | 12 | describe "run" do 13 | test "starts node with correct name" do 14 | refute Node.alive?() 15 | 16 | {:ok, node_name} = NodeActivator.run("test prefix") 17 | 18 | assert Node.alive?() 19 | assert Node.self() == node_name 20 | assert "test-prefix" <> <<_::binary>> = to_string(node_name) 21 | end 22 | 23 | test "is idempotent" do 24 | {:ok, node_name1} = NodeActivator.run("test prefix") 25 | {:ok, node_name2} = NodeActivator.run("test prefix") 26 | 27 | assert node_name1 == node_name2 28 | end 29 | end 30 | 31 | describe "launch_epmd" do 32 | test "does not raise error" do 33 | assert :ok = Epmd.launch_epmd() 34 | end 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /utilities/node_activator/test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | spawn_co_elixir-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog for 0.3.0 2 | 3 | ## 1. Enhancements 4 | 5 | ## 2. Bug fixes 6 | 7 | * Fix the issue on concurrency. 8 | 9 | ## 3. Soft deprecations (no warnings emitted) 10 | 11 | ## 4. Hard deprecations 12 | 13 | * Deprecate supporting Windows, temporally. To recover it, need to fix the issue that Node does not respond on Windows (related to #187). 14 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/README.md: -------------------------------------------------------------------------------- 1 | # SpawnCoElixir 2 | 3 | 4 | SpawnCoElixir spawns cooperative Elixir nodes that are supervised. 5 | 6 | 7 | ## Installation 8 | 9 | Just add `spawn_co_elixir` to your list of dependencies in `mix.exs`: 10 | 11 | ```elixir 12 | def deps do 13 | [ 14 | {:spawn_co_elixir, "~> 0.1.0"} 15 | ] 16 | end 17 | ``` 18 | 19 | Documentation can be found at . 20 | 21 | ## Procedure when publishing 22 | 23 | 1. Publish NodeActivator before publishing SpawnCoElixir; 24 | 2. Modify `deps` in `mix.exs` to use `node_activator` of the latest hex package instead of relative path; 25 | 3. Publish SpawnCoElixir; 26 | 4. Modify `deps` in `run` in `lib/spawn_co_elixir/co_elixir_worker_spawner.ex` to use `spawn_co_elixir` of the latest hex package instead of relative path; 27 | 5. Republish SpawnCoElixir. 28 | 29 | ## License 30 | 31 | Copyright (c) 2023 University of Kitakyushu 32 | 33 | Licensed under the Apache License, Version 2.0 (the "License"); 34 | you may not use this file except in compliance with the License. 35 | You may obtain a copy of the License at 36 | [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) 37 | 38 | Unless required by applicable law or agreed to in writing, software 39 | distributed under the License is distributed on an "AS IS" BASIS, 40 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 41 | See the License for the specific language governing permissions and 42 | limitations under the License. 43 | 44 | ## Acknowledgement 45 | 46 | This work was supported by Asahi Kohsan Group Research Support Program of 47 | Kitakyushu Foundation for the Advancement of Industry Science and Technology 48 | (FAIS). 49 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/lib/spawn_co_elixir.ex: -------------------------------------------------------------------------------- 1 | defmodule SpawnCoElixir do 2 | @moduledoc File.read!("README.md") 3 | |> String.split("") 4 | |> Enum.fetch!(1) 5 | 6 | @typedoc """ 7 | The CoElixir server option 8 | 9 | * `:code` - Elixir code to be run by `CoElixir.Worker` 10 | * `:deps` - dependencies for `CoElixir.Worker` 11 | * `:host_name` - the node name prefix for host 12 | * `:co_elixir_name` - the node name prefix for `CoElixir` 13 | """ 14 | @type co_elixir_option :: 15 | {:code, binary} 16 | | {:deps, [atom | tuple]} 17 | | {:host_name, binary} 18 | | {:co_elixir_name, binary} 19 | 20 | @doc """ 21 | Starts a supervised CoElixir worker. 22 | """ 23 | @spec run([co_elixir_option]) :: DynamicSupervisor.on_start_child() 24 | def run(options \\ []) do 25 | co_elixir_options = [ 26 | code: options[:code] || "", 27 | deps: options[:deps] || [], 28 | host_name: options[:host_name] || "host", 29 | co_elixir_name: options[:co_elixir_name] || "co_elixir" 30 | ] 31 | 32 | DynamicSupervisor.start_child( 33 | SpawnCoElixir.DynamicSupervisor, 34 | {SpawnCoElixir.CoElixir, co_elixir_options} 35 | ) 36 | end 37 | 38 | @doc """ 39 | Stops a CoElixir worker by node name. 40 | """ 41 | @spec stop(node) :: :ok 42 | defdelegate stop(worker_node), to: SpawnCoElixir.CoElixir 43 | 44 | @doc """ 45 | Lists all running CoElixir worker nodes. 46 | """ 47 | @spec workers :: [node] 48 | defdelegate workers, to: SpawnCoElixir.CoElixirLookup, as: :list_worker_nodes 49 | end 50 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/lib/spawn_co_elixir/application.ex: -------------------------------------------------------------------------------- 1 | defmodule SpawnCoElixir.Application do 2 | # See https://hexdocs.pm/elixir/Application.html 3 | # for more information on OTP Applications 4 | @moduledoc false 5 | 6 | use Application 7 | 8 | alias SpawnCoElixir.CoElixirLookup 9 | 10 | @impl true 11 | def start(_type, _args) do 12 | CoElixirLookup.create_table() 13 | 14 | children = [ 15 | # Starts a worker by calling: SpawnCoElixir.Worker.start_link(arg) 16 | # {SpawnCoElixir.Worker, arg} 17 | {DynamicSupervisor, strategy: :one_for_one, name: SpawnCoElixir.DynamicSupervisor} 18 | ] 19 | 20 | # See https://hexdocs.pm/elixir/Supervisor.html 21 | # for other strategies and supported options 22 | opts = [strategy: :one_for_one, name: SpawnCoElixir.Supervisor] 23 | Supervisor.start_link(children, opts) 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/lib/spawn_co_elixir/co_elixir.ex: -------------------------------------------------------------------------------- 1 | defmodule SpawnCoElixir.CoElixir do 2 | @moduledoc false 3 | 4 | use GenServer 5 | require Logger 6 | alias SpawnCoElixir.CoElixirLookup 7 | alias SpawnCoElixir.CoElixirWorkerSpawner 8 | 9 | ## Client API 10 | 11 | @spec start_link([SpawnCoElixir.co_elixir_option()]) :: GenServer.on_start() 12 | def start_link(options \\ []) do 13 | server_options = [ 14 | co_elixir_name: Keyword.fetch!(options, :co_elixir_name), 15 | code: Keyword.fetch!(options, :code), 16 | deps: Keyword.fetch!(options, :deps), 17 | host_name: Keyword.fetch!(options, :host_name) 18 | ] 19 | 20 | NodeActivator.run(server_options[:host_name]) 21 | GenServer.start_link(__MODULE__, server_options) 22 | end 23 | 24 | @spec stop(node) :: :ok | {:error, any} 25 | def stop(worker_node) do 26 | case CoElixirLookup.get_worker_pid(worker_node) do 27 | nil -> 28 | Logger.warning("Not found worker_node #{worker_node}.") 29 | {:error, :not_found} 30 | 31 | pid when is_pid(pid) -> 32 | Logger.info("Found worker_node {#{worker_node}, #{inspect(pid)}}") 33 | GenServer.call(pid, :exit_co_elixir) 34 | end 35 | end 36 | 37 | ## GenServer callbacks 38 | 39 | @impl true 40 | def init(options \\ []) do 41 | a_process = %{options: options, running: false, worker_node: nil} 42 | 43 | {:ok, a_process, {:continue, :spawn_co_elixir}} 44 | end 45 | 46 | @impl true 47 | def handle_continue(:spawn_co_elixir, a_process) do 48 | node_name_prefix = Keyword.fetch!(a_process.options, :co_elixir_name) 49 | worker_node = NodeActivator.Utils.generate_node_name(node_name_prefix) 50 | this_pid = self() 51 | this_node = Node.self() 52 | 53 | if a_process.running do 54 | {:noreply, a_process} 55 | else 56 | Logger.info("spawning #{inspect(worker_node)}") 57 | do_spawn_co_elixir(this_pid, this_node, worker_node, a_process.options) 58 | 59 | {:noreply, %{a_process | running: true}} 60 | end 61 | end 62 | 63 | defp do_spawn_co_elixir(this_pid, this_node, worker_node, options) do 64 | spawn_link(fn -> 65 | :ok = GenServer.call(this_pid, {:register_worker_node, worker_node}) 66 | 67 | case CoElixirWorkerSpawner.run(this_node, worker_node, options) do 68 | :ok -> 69 | Logger.info("spawned #{inspect(worker_node)}") 70 | 71 | {:error, exit_code} -> 72 | Logger.info("could not spawn #{inspect(worker_node)}: exit code #{exit_code}") 73 | :ok = GenServer.call(this_pid, :reboot_co_elixir) 74 | 75 | :error -> 76 | Logger.info("could not spawn #{inspect(worker_node)}: without exit code") 77 | :ok = GenServer.call(this_pid, :reboot_co_elixir) 78 | end 79 | end) 80 | end 81 | 82 | @impl true 83 | def handle_call({:register_worker_node, worker_node}, {_pid_from, _}, a_process) do 84 | Logger.info("registering #{inspect(worker_node)}") 85 | :ok = CoElixirLookup.put_entry(worker_node, self()) 86 | 87 | {:reply, :ok, %{a_process | worker_node: worker_node}} 88 | end 89 | 90 | @impl true 91 | def handle_call({:deregister_worker_node, worker_node}, {_pid_from, _}, a_process) do 92 | Logger.info("deregistering #{inspect(worker_node)}") 93 | :ok = CoElixirLookup.delete_entry(worker_node) 94 | 95 | {:reply, :ok, %{a_process | worker_node: nil}} 96 | end 97 | 98 | @impl true 99 | def handle_call(:exit_co_elixir, {_pid_from, _}, a_process) do 100 | Logger.info("exiting #{inspect(a_process.worker_node)}") 101 | :ok = do_exit_co_elixir(a_process.worker_node) 102 | 103 | {:reply, :ok, %{a_process | running: false, worker_node: nil}} 104 | end 105 | 106 | @impl true 107 | def handle_call(:reboot_co_elixir, {_pid_from, _}, a_process) do 108 | Logger.info("rebooting #{inspect(a_process.worker_node)}") 109 | :ok = do_exit_co_elixir(a_process.worker_node) 110 | 111 | {:noreply, %{a_process | running: false, worker_node: nil}, {:continue, :spawn_co_elixir}} 112 | end 113 | 114 | defp do_exit_co_elixir(worker_node) do 115 | if worker_node do 116 | _pid = Node.spawn(worker_node, System, :halt, []) 117 | :ok = CoElixirLookup.delete_entry(worker_node) 118 | end 119 | 120 | :ok 121 | end 122 | end 123 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/lib/spawn_co_elixir/co_elixir/worker.ex: -------------------------------------------------------------------------------- 1 | defmodule SpawnCoElixir.CoElixir.Worker do 2 | @moduledoc false 3 | @waiting_msec 20 4 | @counter_waiting 100 5 | 6 | require Logger 7 | 8 | def run(node_from) do 9 | Stream.unfold({false, @counter_waiting}, fn 10 | {_, 0} -> nil 11 | {true, _} -> nil 12 | {:ignored, count} -> next_count(count, node_from) 13 | {false, count} -> next_count(count, node_from) 14 | end) 15 | |> Enum.reduce(false, fn 16 | {true, _}, _ -> true 17 | {false, _}, acc -> acc 18 | end) 19 | |> case do 20 | true -> find(node_from) 21 | false -> raise RuntimeError, "could not connect to #{node_from}" 22 | end 23 | end 24 | 25 | defp next_count(count, node_from) do 26 | Process.sleep(@waiting_msec) 27 | n = Node.connect(node_from) 28 | Logger.debug("NodeActivator.epmd_running?: #{NodeActivator.epmd_running?()}") 29 | Logger.debug("Node.connect(#{inspect(node_from)}): #{inspect(n)}") 30 | 31 | { 32 | {n, count - 1}, 33 | {n, count - 1} 34 | } 35 | end 36 | 37 | defp find(node_from) do 38 | Logger.debug("CoElixir #{Node.self()} and host #{node_from} are connected.") 39 | 40 | receive do 41 | :end -> :ok 42 | end 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/lib/spawn_co_elixir/co_elixir_lookup.ex: -------------------------------------------------------------------------------- 1 | defmodule SpawnCoElixir.CoElixirLookup do 2 | @moduledoc false 3 | 4 | @table_name :spawn_co_elixir_co_elixir_lookup 5 | 6 | ## table operations 7 | 8 | @spec create_table() :: :ok 9 | def create_table() do 10 | _ref = :ets.new(@table_name, [:set, :public, :named_table]) 11 | :ok 12 | rescue 13 | _ -> {:error, {:already_exists, @table_name}} 14 | end 15 | 16 | @spec delete_table() :: :ok 17 | def delete_table() do 18 | if table_exist?(), do: :ets.delete(@table_name) 19 | :ok 20 | end 21 | 22 | @spec table_exist?() :: boolean() 23 | def table_exist?() do 24 | :ets.whereis(@table_name) != :undefined 25 | end 26 | 27 | ## read operations 28 | 29 | @spec list_worker_nodes() :: [node] 30 | def list_worker_nodes() do 31 | :ets.select(@table_name, [{{:"$1", :"$2"}, [], [:"$1"]}]) 32 | end 33 | 34 | @spec get_worker_pid(node) :: pid | nil 35 | def get_worker_pid(worker_node) when is_atom(worker_node) do 36 | case :ets.lookup(@table_name, worker_node) do 37 | [] -> nil 38 | [{^worker_node, pid}] -> pid 39 | end 40 | end 41 | 42 | ## write operations 43 | 44 | @spec put_entry(node, pid) :: :ok 45 | def put_entry(worker_node, pid) when is_atom(worker_node) and is_pid(pid) do 46 | true = :ets.insert(@table_name, {worker_node, pid}) 47 | :ok 48 | end 49 | 50 | @spec delete_entry(node) :: :ok 51 | def delete_entry(worker_node) when is_atom(worker_node) do 52 | true = :ets.delete(@table_name, worker_node) 53 | :ok 54 | end 55 | 56 | @spec delete_all() :: :ok 57 | def delete_all() do 58 | true = :ets.delete_all_objects(@table_name) 59 | :ok 60 | end 61 | end 62 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/lib/spawn_co_elixir/co_elixir_worker_spawner.ex: -------------------------------------------------------------------------------- 1 | defmodule SpawnCoElixir.CoElixirWorkerSpawner do 2 | @moduledoc false 3 | require Logger 4 | 5 | @waiting_msec 20 6 | @counter_waiting 100 7 | 8 | @spec run(node, node, keyword) :: :ok | :error | {:error, non_neg_integer} 9 | def run(node_from, worker_node, options) do 10 | code = Keyword.fetch!(options, :code) 11 | deps = Keyword.fetch!(options, :deps) ++ [{:spawn_co_elixir, "~> 0.3"}] 12 | 13 | name_or_sname = 14 | if "#{worker_node}" =~ "." do 15 | "--name" 16 | else 17 | "--sname" 18 | end 19 | 20 | pid = self() 21 | 22 | spawn(fn -> 23 | {_, exit_status} = 24 | spawn_elixir(name_or_sname, worker_node, deps, code, node_from) 25 | 26 | send(pid, exit_status) 27 | end) 28 | 29 | Stream.unfold({false, @counter_waiting}, fn 30 | {_, 0} -> nil 31 | {true, _} -> nil 32 | {:ignored, count} -> next_count(count, worker_node) 33 | {false, count} -> next_count(count, worker_node) 34 | end) 35 | |> Enum.reduce(false, fn 36 | {true, _}, _ -> true 37 | {false, _}, acc -> acc 38 | end) 39 | |> epilogue(worker_node) 40 | end 41 | 42 | defp next_count(count, worker_node) do 43 | Process.sleep(@waiting_msec) 44 | n = Node.connect(worker_node) 45 | 46 | { 47 | {n, count - 1}, 48 | {n, count - 1} 49 | } 50 | end 51 | 52 | defp spawn_elixir(name_or_sname, worker_node, deps, code, node_from) do 53 | System.cmd( 54 | "elixir", 55 | [ 56 | name_or_sname, 57 | Atom.to_string(worker_node), 58 | "-e", 59 | integrated_code(deps, code, node_from) 60 | ], 61 | into: IO.stream() 62 | ) 63 | end 64 | 65 | defp integrated_code(deps, code, node_from) do 66 | "Mix.install(#{deps_listing(deps)}); " 67 | |> Kernel.<>( 68 | case code do 69 | "" -> "" 70 | code -> "#{code}; " 71 | end 72 | ) 73 | |> Kernel.<>( 74 | "#{atom_listing(node_from)} |> List.to_atom() |> SpawnCoElixir.CoElixir.Worker.run()" 75 | ) 76 | end 77 | 78 | defp deps_listing(list) when is_list(list) do 79 | list 80 | |> Enum.map_join(", ", &deps_listing(&1)) 81 | |> then(&"[#{&1}]") 82 | end 83 | 84 | defp deps_listing({a, b}) do 85 | "{#{deps_listing(a)}, #{deps_listing(b)}}" 86 | end 87 | 88 | defp deps_listing(atom) when is_atom(atom) do 89 | r = "#{inspect(atom)}" 90 | 91 | if Regex.match?(~r/\"/, r) do 92 | "#{atom_listing(atom)} |> List.to_atom()" 93 | else 94 | r 95 | end 96 | end 97 | 98 | defp deps_listing(str) when is_binary(str) do 99 | "#{string_listing(str)} |> List.to_string()" 100 | end 101 | 102 | defp string_listing(str) do 103 | str 104 | |> String.to_charlist() 105 | |> Enum.join(", ") 106 | |> then(&"[#{&1}]") 107 | end 108 | 109 | defp atom_listing(atom) do 110 | atom 111 | |> Atom.to_charlist() 112 | |> Enum.join(", ") 113 | |> then(&"[#{&1}]") 114 | end 115 | 116 | defp epilogue(true, worker_node) do 117 | Logger.info("Node #{worker_node} is connected.") 118 | :ok 119 | end 120 | 121 | defp epilogue(false, worker_node) do 122 | Logger.debug("NodeActivator.epmd_running?: #{NodeActivator.epmd_running?()}") 123 | 124 | receive do 125 | exit_status -> 126 | Logger.error("exit_status of #{worker_node} is #{inspect(exit_status)}") 127 | {:error, exit_status} 128 | after 129 | 1000 -> 130 | Logger.error("Timeout to receive exit_status from #{worker_node}") 131 | :error 132 | end 133 | end 134 | end 135 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/lib/spawn_co_elixir/watch_dog_timer.ex: -------------------------------------------------------------------------------- 1 | defmodule SpawnCoElixir.WatchDogTimer do 2 | @moduledoc false 3 | use GenServer 4 | 5 | @waiting_msec 10 6 | @table :spawn_co_elixir_watch_dog_timer 7 | @key :watch_dog_timer 8 | 9 | @impl true 10 | def init(state) do 11 | :ets.new(@table, [:set, :protected, :named_table]) 12 | {:ok, state, {:continue, :clock}} 13 | end 14 | 15 | @impl true 16 | def handle_continue(:clock, state) do 17 | spawn_link(fn -> coroutine() end) 18 | {:noreply, state} 19 | end 20 | 21 | defp coroutine() do 22 | Node.list() 23 | |> Enum.each(fn node -> 24 | Node.spawn(node, fn -> 25 | :ets.insert(@table, {@key, true}) 26 | end) 27 | end) 28 | 29 | Process.sleep(@waiting_msec) 30 | GenServer.cast(SpawnCoElixir.Test.WatchDogTimer, :next_clock) 31 | end 32 | 33 | @impl true 34 | def handle_cast(:next_clock, state) do 35 | {:noreply, state, {:continue, :clock}} 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/mix.exs: -------------------------------------------------------------------------------- 1 | defmodule SpawnCoElixir.MixProject do 2 | use Mix.Project 3 | 4 | @version "0.3.0" 5 | @source_url "https://github.com/zeam-vm/pelemay_backend" 6 | 7 | def project do 8 | [ 9 | app: :spawn_co_elixir, 10 | version: @version, 11 | elixir: "~> 1.14", 12 | start_permanent: Mix.env() == :prod, 13 | deps: deps(), 14 | docs: docs(), 15 | name: "SpawnCoElixir", 16 | description: "SpawnCoElixir spawns cooperative Elixir nodes that are supervised.", 17 | package: package(), 18 | preferred_cli_env: %{ 19 | credo: :test, 20 | dialyzer: :test, 21 | docs: :docs, 22 | "hex.publish": :docs, 23 | "hex.build": :docs 24 | } 25 | ] 26 | end 27 | 28 | # Run "mix help compile.app" to learn about applications. 29 | def application do 30 | [ 31 | extra_applications: [:logger], 32 | mod: {SpawnCoElixir.Application, []} 33 | ] 34 | end 35 | 36 | # Run "mix help deps" to learn about dependencies. 37 | defp deps do 38 | [ 39 | {:dialyxir, "~> 1.3", only: :test, runtime: false}, 40 | {:credo, "~> 1.7", only: :test, runtime: false}, 41 | {:ex_doc, "~> 0.29", only: :docs, runtime: false}, 42 | {:node_activator, "~> 0.2"} 43 | ] 44 | end 45 | 46 | defp package do 47 | [ 48 | maintainers: ["Susumu Yamazaki", "Masatoshi Nishiguchi"], 49 | licenses: ["Apache-2.0"], 50 | links: %{"GitHub" => @source_url} 51 | ] 52 | end 53 | 54 | defp docs do 55 | [ 56 | main: "SpawnCoElixir", 57 | source_url_pattern: 58 | "#{@source_url}/blob/v#{@version}/utilities/spawn_co_elixir/%{path}#L%{line}", 59 | extras: [ 60 | "README.md", 61 | "CHANGELOG.md" 62 | ] 63 | ] 64 | end 65 | end 66 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, 3 | "credo": {:hex, :credo, "1.7.11", "d3e805f7ddf6c9c854fd36f089649d7cf6ba74c42bc3795d587814e3c9847102", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "56826b4306843253a66e47ae45e98e7d284ee1f95d53d1612bb483f88a8cf219"}, 4 | "dialyxir": {:hex, :dialyxir, "1.4.5", "ca1571ac18e0f88d4ab245f0b60fa31ff1b12cbae2b11bd25d207f865e8ae78a", [:mix], [{:erlex, ">= 0.2.7", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "b0fb08bb8107c750db5c0b324fa2df5ceaa0f9307690ee3c1f6ba5b9eb5d35c3"}, 5 | "earmark_parser": {:hex, :earmark_parser, "1.4.42", "f23d856f41919f17cd06a493923a722d87a2d684f143a1e663c04a2b93100682", [:mix], [], "hexpm", "6915b6ca369b5f7346636a2f41c6a6d78b5af419d61a611079189233358b8b8b"}, 6 | "erlex": {:hex, :erlex, "0.2.7", "810e8725f96ab74d17aac676e748627a07bc87eb950d2b83acd29dc047a30595", [:mix], [], "hexpm", "3ed95f79d1a844c3f6bf0cea61e0d5612a42ce56da9c03f01df538685365efb0"}, 7 | "ex_doc": {:hex, :ex_doc, "0.36.1", "4197d034f93e0b89ec79fac56e226107824adcce8d2dd0a26f5ed3a95efc36b1", [:mix], [{:earmark_parser, "~> 1.4.42", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "d7d26a7cf965dacadcd48f9fa7b5953d7d0cfa3b44fa7a65514427da44eafd89"}, 8 | "file_system": {:hex, :file_system, "1.0.1", "79e8ceaddb0416f8b8cd02a0127bdbababe7bf4a23d2a395b983c1f8b3f73edd", [:mix], [], "hexpm", "4414d1f38863ddf9120720cd976fce5bdde8e91d8283353f0e31850fa89feb9e"}, 9 | "jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"}, 10 | "makeup": {:hex, :makeup, "1.2.1", "e90ac1c65589ef354378def3ba19d401e739ee7ee06fb47f94c687016e3713d1", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "d36484867b0bae0fea568d10131197a4c2e47056a6fbe84922bf6ba71c8d17ce"}, 11 | "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"}, 12 | "makeup_erlang": {:hex, :makeup_erlang, "1.0.1", "c7f58c120b2b5aa5fd80d540a89fdf866ed42f1f3994e4fe189abebeab610839", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "8a89a1eeccc2d798d6ea15496a6e4870b75e014d1af514b1b71fa33134f57814"}, 13 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"}, 14 | "node_activator": {:hex, :node_activator, "0.2.0", "b9ea947229d0c38a4562c7ef3408279dd9d438c29eed2b3d5c31bf261141b6d2", [:mix], [], "hexpm", "24c977a2838a265bb2f26003c8445e30a01bf96ab448ab4d1be21886654cd1aa"}, 15 | } 16 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/test/spawn_co_elixir/co_elixir_lookup_test.exs: -------------------------------------------------------------------------------- 1 | defmodule SpawnCoElixir.CoElixirLookupTest do 2 | use ExUnit.Case 3 | doctest SpawnCoElixir.CoElixirLookup 4 | alias SpawnCoElixir.CoElixirLookup 5 | 6 | test "table is already started by application" do 7 | assert CoElixirLookup.table_exist?() 8 | 9 | assert {:error, {:already_exists, :spawn_co_elixir_co_elixir_lookup}} = 10 | CoElixirLookup.create_table() 11 | end 12 | 13 | test "basic read write operations" do 14 | assert CoElixirLookup.list_worker_nodes() == [] 15 | 16 | foo_pid = make_pid() 17 | :ok = CoElixirLookup.put_entry(:foo_node, foo_pid) 18 | assert CoElixirLookup.list_worker_nodes() == [:foo_node] 19 | 20 | bar_pid = make_pid() 21 | :ok = CoElixirLookup.put_entry(:bar_node, bar_pid) 22 | assert CoElixirLookup.list_worker_nodes() == [:foo_node, :bar_node] 23 | 24 | assert CoElixirLookup.get_worker_pid(:foo_node) == foo_pid 25 | assert CoElixirLookup.get_worker_pid(:bar_node) == bar_pid 26 | 27 | :ok = CoElixirLookup.delete_entry(:foo_node) 28 | assert CoElixirLookup.list_worker_nodes() == [:bar_node] 29 | 30 | :ok = CoElixirLookup.delete_all() 31 | assert CoElixirLookup.list_worker_nodes() == [] 32 | end 33 | 34 | # makes a fake worker pid 35 | defp make_pid do 36 | {:ok, pid} = Task.start_link(fn -> :ok end) 37 | pid 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/test/spawn_co_elixir_test.exs: -------------------------------------------------------------------------------- 1 | defmodule SpawnCoElixirTest do 2 | use ExUnit.Case 3 | doctest SpawnCoElixir 4 | require Logger 5 | 6 | @waiting_msec 20 7 | @counter_waiting 100 8 | @table :spawn_co_elixir_watch_dog_timer 9 | @key :watch_dog_timer 10 | 11 | setup do 12 | Node.stop() 13 | :ets.new(@table, [:set, :protected, :named_table]) 14 | 15 | on_exit(fn -> 16 | Node.stop() 17 | end) 18 | end 19 | 20 | test "launch and exit co_elixir" do 21 | refute Node.alive?() 22 | assert Enum.empty?(SpawnCoElixir.workers()) 23 | assert Supervisor.count_children(SpawnCoElixir.DynamicSupervisor).workers == 0 24 | 25 | # run 26 | result = 27 | SpawnCoElixir.run(code: "GenServer.start_link(SpawnCoElixir.WatchDogTimer, [])") 28 | 29 | assert {:ok, pid} = result 30 | assert is_pid(pid) 31 | assert Node.alive?() 32 | 33 | # wait until the node is registered 34 | :ets.insert(@table, {@key, false}) 35 | 36 | r = 37 | Stream.unfold({false, @counter_waiting}, fn 38 | {true, _} -> nil 39 | {_, 0} -> nil 40 | {false, count} -> assert_worker_nodes_working(count) 41 | end) 42 | |> Enum.reduce(false, fn {r, _}, acc -> r or acc end) 43 | 44 | assert r 45 | 46 | worker_nodes = SpawnCoElixir.workers() 47 | Logger.debug("worker_nodes = #{inspect(worker_nodes)}") 48 | 49 | # verify supervision 50 | assert [{:undefined, _pid, :worker, [SpawnCoElixir.CoElixir]}] = 51 | Supervisor.which_children(SpawnCoElixir.DynamicSupervisor) 52 | 53 | # exit 54 | 55 | Logger.debug("Exit all nodes #{inspect(worker_nodes)}") 56 | 57 | r = 58 | worker_nodes 59 | |> Enum.map(fn worker_node -> 60 | case SpawnCoElixir.stop(worker_node) do 61 | :ok -> 62 | true 63 | 64 | r -> 65 | Logger.error("SpawnCoElixir.stop(#{inspect(worker_node)}) return #{inspect(r)}") 66 | false 67 | end 68 | end) 69 | |> Enum.reduce(true, fn x, acc -> x and acc end) 70 | 71 | assert r 72 | 73 | :ets.insert(@table, {@key, false}) 74 | 75 | r = 76 | Stream.unfold({false, @counter_waiting}, fn 77 | {true, _} -> nil 78 | {_, 0} -> nil 79 | {false, count} -> wait_worker_nodes(count) 80 | end) 81 | |> Enum.reduce(false, fn {r, _}, acc -> r or acc end) 82 | 83 | refute r 84 | 85 | r = 86 | worker_nodes 87 | |> Enum.map(fn worker_node -> 88 | case Node.ping(worker_node) do 89 | :pang -> 90 | true 91 | 92 | p -> 93 | Logger.error("Node.ping(#{worker_node}) returns #{p}") 94 | false 95 | end 96 | end) 97 | |> Enum.reduce(true, fn x, acc -> x and acc end) 98 | 99 | assert r 100 | 101 | assert Enum.empty?(SpawnCoElixir.workers()) 102 | 103 | r = 104 | worker_nodes 105 | |> Enum.map(fn worker_node -> 106 | case SpawnCoElixir.stop(worker_node) do 107 | {:error, :not_found} -> 108 | true 109 | 110 | r -> 111 | Logger.error("SpawnCoElixir.stop(#{worker_node}) return #{inspect(r)}") 112 | false 113 | end 114 | end) 115 | |> Enum.reduce(true, fn x, acc -> x and acc end) 116 | 117 | assert r 118 | end 119 | 120 | defp assert_worker_nodes_working(count) do 121 | Process.sleep(@waiting_msec) 122 | 123 | case SpawnCoElixir.workers() do 124 | [] -> 125 | Logger.debug("Workers are []") 126 | {{false, count - 1}, {false, count - 1}} 127 | 128 | worker_nodes -> 129 | worker_nodes 130 | |> Enum.map(&Node.ping(&1)) 131 | |> Enum.reduce(false, fn 132 | :pong, _ -> true 133 | _, acc -> acc 134 | end) 135 | |> case do 136 | false -> 137 | Logger.debug("All workers #{inspect(worker_nodes)} are not responded.") 138 | {{false, count - 1}, {false, count - 1}} 139 | 140 | true -> 141 | Logger.debug("A worker in #{inspect(worker_nodes)} is responded") 142 | {{true, 0}, {true, 0}} 143 | end 144 | end 145 | end 146 | 147 | defp wait_worker_nodes(count) do 148 | Process.sleep(@waiting_msec) 149 | 150 | case SpawnCoElixir.workers() do 151 | [] -> {{false, count - 1}, {false, count - 1}} 152 | _ -> lookup_watch_dog_timer(count) 153 | end 154 | end 155 | 156 | defp lookup_watch_dog_timer(count) do 157 | :ets.lookup(@table, @key) 158 | |> lookup_watch_dog_timer_s(count) 159 | end 160 | 161 | defp lookup_watch_dog_timer_s(nil, _) do 162 | Logger.error("ETS table #{@key} not found") 163 | nil 164 | end 165 | 166 | defp lookup_watch_dog_timer_s([], _) do 167 | Logger.error("ETS table #{@key} does not contain any term") 168 | nil 169 | end 170 | 171 | defp lookup_watch_dog_timer_s([{@key, result}], count) do 172 | Logger.debug("#{@key} is #{result}") 173 | {{result, count - 1}, {result, count - 1}} 174 | end 175 | end 176 | -------------------------------------------------------------------------------- /utilities/spawn_co_elixir/test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | --------------------------------------------------------------------------------