├── .ci ├── create-release.py └── requirements.txt ├── .github └── workflows │ ├── binary-build.yml │ ├── ci-test.yml │ └── container-build.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── assets └── apollo-social-card.png ├── build ├── coordinator │ ├── Dockerfile │ └── Dockerfile.dockerignore └── worker │ ├── Dockerfile │ └── Dockerfile.dockerignore ├── cmd ├── coordinator │ └── main.go └── worker │ └── main.go ├── deploy └── coordinator.yaml ├── go.mod ├── go.sum ├── internal ├── coordinator │ ├── artifactmanager.go │ ├── config.go │ ├── jobdmetadatamanager.go │ ├── jobscheduler.go │ └── k8sclient.go ├── db │ ├── artifactrepo.go │ ├── db.go │ ├── jobrepo.go │ └── taskrepo.go ├── handler │ ├── artifactcreator.go │ ├── controller.go │ ├── jobmanager.go │ └── taskcreator.go ├── io │ ├── fsregistrar.go │ ├── localfsregistrar.go │ └── s3registrar.go ├── server │ ├── coordinatorHTTPserver.go │ └── workergRPCserver.go ├── utils │ ├── hash.go │ ├── logger.go │ └── scanner.go └── worker │ ├── map.go │ ├── reduce.go │ └── worker.go ├── proto └── msg.proto └── test ├── coordinator └── artifactmanager_test.go ├── db ├── artifactrepo_test.go ├── db_test.go └── jobrepo_test.go └── utils ├── data ├── crlf_corpus_1.txt ├── crlf_corpus_2.txt ├── lf_corpus_1.txt └── lf_corpus_2.txt └── scanner_test.go /.ci/create-release.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import argparse 3 | import os 4 | import sys 5 | import json 6 | 7 | def main(): 8 | parser = argparse.ArgumentParser() 9 | parser.add_argument("token") 10 | parser.add_argument("tag") 11 | args = parser.parse_args() 12 | 13 | auth_token = args.token 14 | tag = os.path.basename(args.tag) 15 | release_name = f"Apollo v{tag}" 16 | request_headers = { 17 | "Accept": "application/vnd.github+json", 18 | "Authorization": f"Bearer {auth_token}", 19 | "X-GitHub-Api-Version": "2022-11-28" 20 | } 21 | body = { 22 | "tag_name": f"release/{tag}", 23 | "name": release_name, 24 | "draft": True, 25 | "prerelease": False, 26 | "generate_release_notes": False 27 | } 28 | res = requests.post( 29 | url="https://api.github.com/repos/Assifar-Karim/apollo/releases", 30 | headers=request_headers, 31 | data=json.dumps(body) 32 | ) 33 | 34 | if not res.ok: 35 | print(res.text) 36 | sys.exit(1) 37 | json_res = res.json() 38 | release_id = json_res["id"] 39 | binaries = [ 40 | "worker-linux-amd64.tar.gz", 41 | "worker-linux-arm64.tar.gz", 42 | "coordinator-linux-amd64.tar.gz", 43 | "coordinator-linux-arm64.tar.gz" 44 | ] 45 | request_headers["Content-Type"] = "application/octet-stream" 46 | for binary in binaries: 47 | path = os.path.join("bin", binary) 48 | bin_req = requests.post( 49 | url=f"https://uploads.github.com/repos/Assifar-Karim/apollo/releases/{release_id}/assets?name={binary}", 50 | headers=request_headers, 51 | data=open(path, "rb").read() 52 | ) 53 | if not bin_req.ok: 54 | print(f"Could not upload {binary} to release!") 55 | 56 | 57 | if __name__ == "__main__": 58 | main() -------------------------------------------------------------------------------- /.ci/requirements.txt: -------------------------------------------------------------------------------- 1 | certifi==2025.1.31 2 | charset-normalizer==3.4.1 3 | idna==3.10 4 | requests==2.32.3 5 | urllib3==2.3.0 6 | -------------------------------------------------------------------------------- /.github/workflows/binary-build.yml: -------------------------------------------------------------------------------- 1 | name: Build Apollo binaries 2 | on: 3 | push: 4 | tags: 5 | - release/**/** 6 | jobs: 7 | build-binaries: 8 | runs-on: ubuntu-latest 9 | permissions: 10 | contents: write 11 | steps: 12 | - uses: actions/checkout@v4 13 | - name: Set up Go 14 | uses: actions/setup-go@v4 15 | with: 16 | go-version: '1.21' 17 | - name: Set up Python 18 | uses: actions/setup-python@v5 19 | with: 20 | python-version: '3.10' 21 | - name: Install python dependencies 22 | run: pip install -r .ci/requirements.txt 23 | - name: Install go dependencies 24 | run: go mod download 25 | - name: Install protoc 26 | uses: arduino/setup-protoc@v3 27 | with: 28 | version: "27.1" 29 | - name: Install protoc-gen-go 30 | run: | 31 | go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.36.5 32 | go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.5.1 33 | - name: Generate gRPC code 34 | run: make generate_grpc_code 35 | - name: Build worker amd64 binaries 36 | run: make build_worker_amd64 37 | - name: Build worker arm64 binaires 38 | run: make build_worker_arm64 39 | - name: Build coordinator amd64 binaries 40 | run: make build_coordinator_amd64 41 | - name: Build coordinator arm64 binaires 42 | run: make build_coordinator_arm64 43 | - name: Create release draft 44 | run: python3 .ci/create-release.py ${{ secrets.GITHUB_TOKEN }} ${{ github.ref }} -------------------------------------------------------------------------------- /.github/workflows/ci-test.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | push: 4 | branches: [ "main" ] 5 | pull_request: 6 | branches: [ "main" ] 7 | jobs: 8 | test: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | - name: Set up Go 13 | uses: actions/setup-go@v4 14 | with: 15 | go-version: '1.21' 16 | - name: Install dependencies 17 | run: go mod download 18 | - name: Install protoc 19 | uses: arduino/setup-protoc@v3 20 | with: 21 | version: "27.1" 22 | - name: Install protoc-gen-go 23 | run: | 24 | go install google.golang.org/protobuf/cmd/protoc-gen-go@latest 25 | go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest 26 | - name: Generate gRPC code 27 | run: make generate_grpc_code 28 | - name: Run tests 29 | run: go test -v ./test/... 30 | -------------------------------------------------------------------------------- /.github/workflows/container-build.yml: -------------------------------------------------------------------------------- 1 | name: Build Apollo containers 2 | on: 3 | push: 4 | tags: 5 | - release/**/** 6 | env: 7 | REGISTRY: ghcr.io 8 | jobs: 9 | build-coordinator: 10 | runs-on: ubuntu-latest 11 | permissions: 12 | contents: read 13 | packages: write 14 | attestations: write 15 | id-token: write 16 | steps: 17 | - uses: actions/checkout@v4 18 | - name: Log in to GitHub Container Registry 19 | uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1 20 | with: 21 | registry: ${{ env.REGISTRY }} 22 | username: ${{ github.actor }} 23 | password: ${{ secrets.GITHUB_TOKEN }} 24 | - name: Set up QEMU 25 | uses: docker/setup-qemu-action@v3 26 | - name: Set up Docker buildx 27 | uses: docker/setup-buildx-action@v3 28 | - name: Extract image metadata (tags, labels) 29 | id: meta 30 | uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7 31 | with: 32 | images: ${{ env.REGISTRY }}/assifar-karim/apollo-coordinator 33 | - name: Build and push Docker image 34 | id: push 35 | uses: docker/build-push-action@v6 36 | with: 37 | context: . 38 | file: build/coordinator/Dockerfile 39 | platforms: linux/amd64, linux/arm64 40 | push: true 41 | tags: ${{ steps.meta.outputs.tags }} 42 | labels: ${{ steps.meta.outputs.labels }} 43 | - name: Generate artifact provenance attestation 44 | uses: actions/attest-build-provenance@v2 45 | with: 46 | subject-name: ${{ env.REGISTRY }}/assifar-karim/apollo-coordinator 47 | subject-digest: ${{ steps.push.outputs.digest }} 48 | push-to-registry: true 49 | build-worker: 50 | runs-on: ubuntu-latest 51 | permissions: 52 | contents: read 53 | packages: write 54 | attestations: write 55 | id-token: write 56 | steps: 57 | - uses: actions/checkout@v4 58 | - name: Log in to GitHub Container Registry 59 | uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1 60 | with: 61 | registry: ${{ env.REGISTRY }} 62 | username: ${{ github.actor }} 63 | password: ${{ secrets.GITHUB_TOKEN }} 64 | - name: Set up QEMU 65 | uses: docker/setup-qemu-action@v3 66 | - name: Set up Docker buildx 67 | uses: docker/setup-buildx-action@v3 68 | - name: Extract image metadata (tags, labels) 69 | id: meta 70 | uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7 71 | with: 72 | images: ${{ env.REGISTRY }}/assifar-karim/apollo-worker 73 | - name: Build and push Docker image 74 | id: push 75 | uses: docker/build-push-action@v6 76 | with: 77 | context: . 78 | file: build/worker/Dockerfile 79 | platforms: linux/amd64, linux/arm64 80 | push: true 81 | tags: ${{ steps.meta.outputs.tags }} 82 | labels: ${{ steps.meta.outputs.labels }} 83 | - name: Generate artifact provenance attestation 84 | uses: actions/attest-build-provenance@v2 85 | with: 86 | subject-name: ${{ env.REGISTRY }}/assifar-karim/apollo-worker 87 | subject-digest: ${{ steps.push.outputs.digest }} 88 | push-to-registry: true -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | internal/proto/ 2 | .vscode 3 | bin 4 | queries/ 5 | *.db 6 | manifests_temp/ 7 | docs/.docusaurus 8 | docs/build 9 | docs/node_modules 10 | .ci/venv -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | generate_grpc_code: 2 | protoc \ 3 | --go_out=./internal \ 4 | --go_opt=paths=source_relative \ 5 | --go-grpc_out=./internal \ 6 | --go-grpc_opt=paths=source_relative \ 7 | proto/msg.proto 8 | 9 | build_worker:generate_grpc_code 10 | mkdir -p bin 11 | go build -o bin/worker cmd/worker/main.go 12 | build_coordinator:generate_grpc_code 13 | mkdir -p bin 14 | go build -o bin/coordinator cmd/coordinator/main.go 15 | 16 | build_worker_amd64: 17 | mkdir -p bin 18 | GOARCH=amd64 GOOS=linux go build -o bin/worker-linux-amd64 cmd/worker/main.go 19 | tar -czvf bin/worker-linux-amd64.tar.gz bin/worker-linux-amd64 20 | build_worker_arm64: 21 | mkdir -p bin 22 | GOARCH=arm64 GOOS=linux go build -o bin/worker-linux-arm64 cmd/worker/main.go 23 | tar -czvf bin/worker-linux-arm64.tar.gz bin/worker-linux-arm64 24 | 25 | build_coordinator_amd64: 26 | mkdir -p bin 27 | GOARCH=amd64 GOOS=linux go build -o bin/coordinator-linux-amd64 cmd/coordinator/main.go 28 | tar -czvf bin/coordinator-linux-amd64.tar.gz bin/coordinator-linux-amd64 29 | build_coordinator_arm64: 30 | mkdir -p bin 31 | GOARCH=arm64 GOOS=linux go build -o bin/coordinator-linux-arm64 cmd/coordinator/main.go 32 | tar -czvf bin/coordinator-linux-arm64.tar.gz bin/coordinator-linux-arm64 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apollo 2 |

3 | 4 |

5 |
 6 | A lightweight modern map reduce framework brought to k8s
 7 | 
8 | 9 | Apollo is a lightweight modern kubernetes native map reduce framework based on the original [Google MapReduce paper](https://research.google.com/archive/mapreduce-osdi04.pdf).\ 10 | Apollo provides a distributed computation framework grafted on top of the kubernetes orchestrator while requiring minimal configuration and staying lightweight. It mainly relies on S3 based object storages as input sources instead of bulky distributed filesystems such as HDFS or GFS. 11 | 12 | The computation model that Apollo follows is the MapReduce model where a global computation is subdivided into two types of operations which are map operations and reduce operations. These operations are distributed on multiple kubernetes pods that perform their specific operations on the data chunks that are given to them as a responsibility. 13 | In addition to following the MapReduce model, Apollo is kubernetes native which means that it is directly grafted on top of the k8s abstractions without any added configuration or any customization effort. 14 | 15 | For more details on how Apollo works and how to get started with it check our [docs](https://assifar-karim.github.io/apollo). 16 | 17 |
18 | Made with ❤️ by your friendly neighborhood software engineer Karim Assifar
19 | 
20 | 21 | -------------------------------------------------------------------------------- /assets/apollo-social-card.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Assifar-Karim/apollo/255924e2184648818adfbd195f2d56bb0400603e/assets/apollo-social-card.png -------------------------------------------------------------------------------- /build/coordinator/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.21-alpine AS Build 2 | 3 | RUN apk add --no-cache make 4 | 5 | RUN mkdir -p protoc 6 | RUN cd protoc && wget https://github.com/protocolbuffers/protobuf/releases/download/v27.1/protoc-27.1-linux-x86_64.zip 7 | RUN unzip protoc/protoc-27.1-linux-x86_64.zip 8 | ENV PATH="$PATH:/go/protoc/bin" 9 | 10 | RUN go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.36.5 11 | RUN go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.5.1 12 | 13 | 14 | WORKDIR /apollo 15 | COPY go.mod . 16 | COPY go.sum . 17 | 18 | RUN go mod download 19 | RUN go mod verify 20 | 21 | COPY cmd/coordinator cmd/coordinator 22 | COPY proto/msg.proto proto/msg.proto 23 | COPY internal internal 24 | COPY Makefile . 25 | 26 | RUN make build_coordinator 27 | 28 | FROM alpine:3.20 29 | 30 | RUN addgroup --gid 4010 apollo && \ 31 | adduser \ 32 | --disabled-password \ 33 | --gecos "" \ 34 | --home /apollo \ 35 | --no-create-home \ 36 | --ingroup apollo \ 37 | --uid 4010 \ 38 | apollo 39 | 40 | USER apollo:apollo 41 | WORKDIR /apollo 42 | RUN mkdir -p data 43 | COPY --chown=apollo:apollo --from=Build /apollo/bin/coordinator coordinator 44 | EXPOSE 4750 45 | 46 | ENTRYPOINT ./coordinator $COORDINATOR_OPTS -------------------------------------------------------------------------------- /build/coordinator/Dockerfile.dockerignore: -------------------------------------------------------------------------------- 1 | internal/proto/**/* 2 | internal/proto -------------------------------------------------------------------------------- /build/worker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.21-alpine AS Build 2 | 3 | RUN apk add --no-cache make 4 | 5 | RUN mkdir -p protoc 6 | RUN cd protoc && wget https://github.com/protocolbuffers/protobuf/releases/download/v27.1/protoc-27.1-linux-x86_64.zip 7 | RUN unzip protoc/protoc-27.1-linux-x86_64.zip 8 | ENV PATH="$PATH:/go/protoc/bin" 9 | 10 | RUN go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.36.5 11 | RUN go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.5.1 12 | 13 | 14 | WORKDIR /apollo 15 | COPY go.mod . 16 | COPY go.sum . 17 | 18 | RUN go mod download 19 | RUN go mod verify 20 | 21 | COPY cmd/worker cmd/worker 22 | COPY proto/msg.proto proto/msg.proto 23 | COPY internal internal 24 | COPY Makefile . 25 | 26 | RUN make build_worker 27 | 28 | FROM alpine:3.20 29 | 30 | RUN addgroup --gid 4010 apollo && \ 31 | adduser \ 32 | --disabled-password \ 33 | --gecos "" \ 34 | --home /apollo \ 35 | --no-create-home \ 36 | --ingroup apollo \ 37 | --uid 4010 \ 38 | apollo 39 | 40 | USER apollo:apollo 41 | WORKDIR /apollo 42 | COPY --chown=apollo:apollo --from=Build /apollo/bin/worker worker 43 | EXPOSE 8090 44 | 45 | ENTRYPOINT "./worker" -------------------------------------------------------------------------------- /build/worker/Dockerfile.dockerignore: -------------------------------------------------------------------------------- 1 | internal/proto/**/* 2 | internal/proto -------------------------------------------------------------------------------- /cmd/coordinator/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "time" 6 | 7 | "github.com/Assifar-Karim/apollo/internal/coordinator" 8 | "github.com/Assifar-Karim/apollo/internal/db" 9 | "github.com/Assifar-Karim/apollo/internal/handler" 10 | "github.com/Assifar-Karim/apollo/internal/server" 11 | "github.com/Assifar-Karim/apollo/internal/utils" 12 | ) 13 | 14 | var startTime = time.Now() 15 | 16 | func main() { 17 | logger := utils.GetLogger() 18 | logger.PrintBanner() 19 | logger.Info("Startup completed in %v", time.Since(startTime)) 20 | database, err := db.New("sqlite", "coordinator.db", coordinator.GetConfig().IsInDevMode()) 21 | if err != nil { 22 | logger.Error("Can't connect to database: %s", err) 23 | os.Exit(1) 24 | } 25 | k8sClient, err := coordinator.NewK8sClient() 26 | if err != nil { 27 | logger.Error("Can't connect to the k8s cluster %s", err) 28 | os.Exit(1) 29 | } 30 | jobRepository := db.NewSQLiteJobsRepository(database) 31 | taskRepository := db.NewSQLiteTaskRepository(database) 32 | jobMetadataManager := coordinator.NewJobMetadataManager(jobRepository, taskRepository) 33 | artifactRepository := db.NewSQLiteArtifactRepository(database) 34 | artifactManager := coordinator.NewArtifactManager(artifactRepository) 35 | jobScheduler := coordinator.NewJobScheduler(k8sClient, taskRepository) 36 | jobManagerHandler := handler.NewJobManagerHandler(jobMetadataManager, artifactManager, jobScheduler) 37 | artifactHandler := handler.NewArtifactHandler(artifactManager) 38 | httpServer, err := server.NewHttpServer(":4750", jobManagerHandler, artifactHandler) 39 | if err != nil { 40 | logger.Error("Can't create listener: %s", err) 41 | os.Exit(1) 42 | } 43 | err = httpServer.Serve() 44 | if err != nil { 45 | logger.Error("Impossible to serve: %s", err) 46 | os.Exit(1) 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /cmd/worker/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "time" 6 | 7 | "github.com/Assifar-Karim/apollo/internal/handler" 8 | "github.com/Assifar-Karim/apollo/internal/server" 9 | "github.com/Assifar-Karim/apollo/internal/utils" 10 | "github.com/Assifar-Karim/apollo/internal/worker" 11 | ) 12 | 13 | var startTime = time.Now() 14 | 15 | func main() { 16 | logger := utils.GetLogger() 17 | logger.PrintBanner() 18 | logger.Info("Startup completed in %v", time.Since(startTime)) 19 | taskCreatorHandler := handler.NewTaskCreatorHandler(&worker.Worker{}) 20 | gRPCserver, err := server.NewGrpcServer(":8090", *taskCreatorHandler) 21 | if err != nil { 22 | logger.Error("Can't create listener: %s", err) 23 | os.Exit(1) 24 | } 25 | err = gRPCserver.Serve() 26 | if err != nil { 27 | logger.Error("Impossible to serve: %s", err) 28 | os.Exit(1) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /deploy/coordinator.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: Namespace 4 | metadata: 5 | name: apollo-workers 6 | labels: 7 | name: apollo-workers 8 | --- 9 | apiVersion: v1 10 | kind: ServiceAccount 11 | metadata: 12 | name: apollo-coordinator 13 | namespace: apollo-workers 14 | --- 15 | apiVersion: rbac.authorization.k8s.io/v1 16 | kind: Role 17 | metadata: 18 | name: coordinator-role 19 | namespace: apollo-workers 20 | rules: 21 | - apiGroups: 22 | - "" 23 | resources: 24 | - pods 25 | - services 26 | verbs: 27 | - get 28 | - watch 29 | - list 30 | - create 31 | - update 32 | - patch 33 | - delete 34 | - deletecollection 35 | --- 36 | apiVersion: rbac.authorization.k8s.io/v1 37 | kind: RoleBinding 38 | metadata: 39 | name: coordinator-role-binding 40 | namespace: apollo-workers 41 | roleRef: 42 | apiGroup: rbac.authorization.k8s.io 43 | kind: Role 44 | name: coordinator-role 45 | subjects: 46 | - namespace: apollo-workers 47 | kind: ServiceAccount 48 | name: apollo-coordinator 49 | --- 50 | apiVersion: v1 51 | kind: PersistentVolumeClaim 52 | metadata: 53 | name: apollo-intermediate-files-pvc 54 | namespace: apollo-workers 55 | spec: 56 | accessModes: 57 | - ReadWriteOnce 58 | storageClassName: local-path 59 | resources: 60 | requests: 61 | storage: 1Gi 62 | --- 63 | apiVersion: v1 64 | kind: Service 65 | metadata: 66 | name: coordinator 67 | namespace: apollo-workers 68 | spec: 69 | type: NodePort 70 | externalTrafficPolicy: Local 71 | ports: 72 | - port: 4750 73 | selector: 74 | app: coordinator 75 | --- 76 | apiVersion: v1 77 | kind: Service 78 | metadata: 79 | name: workers 80 | namespace: apollo-workers 81 | spec: 82 | selector: 83 | app: worker 84 | clusterIP: None 85 | --- 86 | apiVersion: apps/v1 87 | kind: StatefulSet 88 | metadata: 89 | name: coordinator 90 | namespace: apollo-workers 91 | spec: 92 | selector: 93 | matchLabels: 94 | app: coordinator 95 | serviceName: coordinator 96 | replicas: 1 97 | template: 98 | metadata: 99 | namespace: apollo-workers 100 | labels: 101 | app: coordinator 102 | spec: 103 | serviceAccountName: apollo-coordinator 104 | containers: 105 | - name: coordinator 106 | image: ghcr.io/assifar-karim/apollo-coordinator:release-0.1.1 107 | imagePullPolicy: Always 108 | ports: 109 | - containerPort: 4750 110 | volumeMounts: 111 | - name: data 112 | mountPath: /apollo/data 113 | - name: artifacts 114 | mountPath: /coordinator/artifacts 115 | env: 116 | - name: COORDINATOR_OPTS 117 | value: "--trace" 118 | volumeClaimTemplates: 119 | - metadata: 120 | name: data 121 | namespace: apollo-workers 122 | spec: 123 | accessModes: 124 | - ReadWriteOnce 125 | storageClassName: local-path 126 | resources: 127 | requests: 128 | storage: 1Gi 129 | - metadata: 130 | name: artifacts 131 | namespace: apollo-workers 132 | spec: 133 | accessModes: 134 | - ReadWriteOnce 135 | storageClassName: local-path 136 | resources: 137 | requests: 138 | storage: 1Gi 139 | 140 | 141 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/Assifar-Karim/apollo 2 | 3 | go 1.21 4 | 5 | require ( 6 | github.com/go-chi/chi/v5 v5.1.0 7 | github.com/google/uuid v1.6.0 8 | github.com/minio/minio-go/v7 v7.0.75 9 | golang.org/x/sync v0.8.0 10 | google.golang.org/grpc v1.65.0 11 | google.golang.org/protobuf v1.34.2 12 | k8s.io/api v0.29.10 13 | k8s.io/apimachinery v0.29.10 14 | k8s.io/client-go v0.29.10 15 | modernc.org/sqlite v1.33.1 16 | ) 17 | 18 | require ( 19 | github.com/davecgh/go-spew v1.1.1 // indirect 20 | github.com/dustin/go-humanize v1.0.1 // indirect 21 | github.com/emicklei/go-restful/v3 v3.11.0 // indirect 22 | github.com/go-ini/ini v1.67.0 // indirect 23 | github.com/go-logr/logr v1.3.0 // indirect 24 | github.com/go-openapi/jsonpointer v0.19.6 // indirect 25 | github.com/go-openapi/jsonreference v0.20.2 // indirect 26 | github.com/go-openapi/swag v0.22.3 // indirect 27 | github.com/goccy/go-json v0.10.3 // indirect 28 | github.com/gogo/protobuf v1.3.2 // indirect 29 | github.com/golang/protobuf v1.5.4 // indirect 30 | github.com/google/gnostic-models v0.6.8 // indirect 31 | github.com/google/gofuzz v1.2.0 // indirect 32 | github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect 33 | github.com/imdario/mergo v0.3.6 // indirect 34 | github.com/josharian/intern v1.0.0 // indirect 35 | github.com/json-iterator/go v1.1.12 // indirect 36 | github.com/klauspost/compress v1.17.9 // indirect 37 | github.com/klauspost/cpuid/v2 v2.2.8 // indirect 38 | github.com/mailru/easyjson v0.7.7 // indirect 39 | github.com/mattn/go-isatty v0.0.20 // indirect 40 | github.com/minio/md5-simd v1.1.2 // indirect 41 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 42 | github.com/modern-go/reflect2 v1.0.2 // indirect 43 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect 44 | github.com/ncruces/go-strftime v0.1.9 // indirect 45 | github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect 46 | github.com/rs/xid v1.5.0 // indirect 47 | github.com/spf13/pflag v1.0.5 // indirect 48 | golang.org/x/crypto v0.26.0 // indirect 49 | golang.org/x/net v0.28.0 // indirect 50 | golang.org/x/oauth2 v0.20.0 // indirect 51 | golang.org/x/sys v0.24.0 // indirect 52 | golang.org/x/term v0.23.0 // indirect 53 | golang.org/x/text v0.17.0 // indirect 54 | golang.org/x/time v0.3.0 // indirect 55 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240812133136-8ffd90a71988 // indirect 56 | gopkg.in/inf.v0 v0.9.1 // indirect 57 | gopkg.in/yaml.v2 v2.4.0 // indirect 58 | gopkg.in/yaml.v3 v3.0.1 // indirect 59 | k8s.io/klog/v2 v2.110.1 // indirect 60 | k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00 // indirect 61 | k8s.io/utils v0.0.0-20230726121419-3b25d923346b // indirect 62 | modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect 63 | modernc.org/libc v1.55.3 // indirect 64 | modernc.org/mathutil v1.6.0 // indirect 65 | modernc.org/memory v1.8.0 // indirect 66 | modernc.org/strutil v1.2.0 // indirect 67 | modernc.org/token v1.1.0 // indirect 68 | sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect 69 | sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect 70 | sigs.k8s.io/yaml v1.3.0 // indirect 71 | ) 72 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 4 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 5 | github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= 6 | github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= 7 | github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= 8 | github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= 9 | github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw= 10 | github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= 11 | github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A= 12 | github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= 13 | github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY= 14 | github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= 15 | github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE= 16 | github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= 17 | github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE= 18 | github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= 19 | github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= 20 | github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= 21 | github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= 22 | github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= 23 | github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= 24 | github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= 25 | github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= 26 | github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= 27 | github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= 28 | github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= 29 | github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I= 30 | github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U= 31 | github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 32 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 33 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 34 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 35 | github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= 36 | github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 37 | github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo= 38 | github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= 39 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 40 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 41 | github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= 42 | github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= 43 | github.com/imdario/mergo v0.3.6 h1:xTNEAn+kxVO7dTZGu0CegyqKZmoWFI0rF8UxjlB2d28= 44 | github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= 45 | github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= 46 | github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= 47 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= 48 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 49 | github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= 50 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= 51 | github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= 52 | github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= 53 | github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= 54 | github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM= 55 | github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= 56 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 57 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 58 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 59 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 60 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 61 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 62 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 63 | github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= 64 | github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= 65 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 66 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 67 | github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= 68 | github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= 69 | github.com/minio/minio-go/v7 v7.0.75 h1:0uLrB6u6teY2Jt+cJUVi9cTvDRuBKWSRzSAcznRkwlE= 70 | github.com/minio/minio-go/v7 v7.0.75/go.mod h1:qydcVzV8Hqtj1VtEocfxbmVFa2siu6HGa+LDEPogjD8= 71 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 72 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 73 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 74 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 75 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 76 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= 77 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= 78 | github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= 79 | github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= 80 | github.com/onsi/ginkgo/v2 v2.13.0 h1:0jY9lJquiL8fcf3M4LAXN5aMlS/b2BV86HFFPCPMgE4= 81 | github.com/onsi/ginkgo/v2 v2.13.0/go.mod h1:TE309ZR8s5FsKKpuB1YAQYBzCaAfUgatB/xlT/ETL/o= 82 | github.com/onsi/gomega v1.29.0 h1:KIA/t2t5UBzoirT4H9tsML45GEbo3ouUnBHsCfD2tVg= 83 | github.com/onsi/gomega v1.29.0/go.mod h1:9sxs+SwGrKI0+PWe4Fxa9tFQQBG5xSsSbMXOI8PPpoQ= 84 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 85 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 86 | github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= 87 | github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= 88 | github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= 89 | github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= 90 | github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc= 91 | github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= 92 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 93 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 94 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 95 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 96 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 97 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 98 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 99 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 100 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 101 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 102 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 103 | github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= 104 | github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= 105 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 106 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 107 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 108 | golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw= 109 | golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54= 110 | golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 111 | golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 112 | golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= 113 | golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= 114 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 115 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 116 | golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 117 | golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= 118 | golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE= 119 | golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg= 120 | golang.org/x/oauth2 v0.20.0 h1:4mQdhULixXKP1rwYBW0vAijoXnkTG0BLCDRzfe1idMo= 121 | golang.org/x/oauth2 v0.20.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= 122 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 123 | golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 124 | golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 125 | golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= 126 | golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 127 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 128 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 129 | golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 130 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 131 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 132 | golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= 133 | golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 134 | golang.org/x/term v0.23.0 h1:F6D4vR+EHoL9/sWAWgAR1H2DcHr4PareCbAaCo1RpuU= 135 | golang.org/x/term v0.23.0/go.mod h1:DgV24QBUrK6jhZXl+20l6UWznPlwAHm1Q1mGHtydmSk= 136 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 137 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 138 | golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc= 139 | golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= 140 | golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= 141 | golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 142 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 143 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 144 | golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= 145 | golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= 146 | golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= 147 | golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= 148 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 149 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 150 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 151 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 152 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240812133136-8ffd90a71988 h1:V71AcdLZr2p8dC9dbOIMCpqi4EmRl8wUwnJzXXLmbmc= 153 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240812133136-8ffd90a71988/go.mod h1:Ue6ibwXGpU+dqIcODieyLOcgj7z8+IcskoNIgZxtrFY= 154 | google.golang.org/grpc v1.65.0 h1:bs/cUb4lp1G5iImFFd3u5ixQzweKizoZJAwBNLR42lc= 155 | google.golang.org/grpc v1.65.0/go.mod h1:WgYC2ypjlB0EiQi6wdKixMqukr6lBc0Vo+oOgjrM5ZQ= 156 | google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= 157 | google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= 158 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 159 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 160 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 161 | gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= 162 | gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= 163 | gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 164 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 165 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 166 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 167 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 168 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 169 | k8s.io/api v0.29.10 h1:Fao3HOxccbGRC1HZtXD+Y41xJhP0tEToVo5W7EEUBm0= 170 | k8s.io/api v0.29.10/go.mod h1:rF0sRh64w1hMNAVGh4YYniSxODyHye3GLmymAbWBDvY= 171 | k8s.io/apimachinery v0.29.10 h1:57OLNqOJUgp5KlRRY3JOBFOTTa5Rt/LVkmKiiN2cvaQ= 172 | k8s.io/apimachinery v0.29.10/go.mod h1:i3FJVwhvSp/6n8Fl4K97PJEP8C+MM+aoDq4+ZJBf70Y= 173 | k8s.io/client-go v0.29.10 h1:hPmG1pmKslRhmCIzVd90sA58B0sJwNwduNgXFWsFqhI= 174 | k8s.io/client-go v0.29.10/go.mod h1:gnMCQiRXGL9K0VtlW8gTkhzptGrHm2BJ4qBbujNemc4= 175 | k8s.io/klog/v2 v2.110.1 h1:U/Af64HJf7FcwMcXyKm2RPM22WZzyR7OSpYj5tg3cL0= 176 | k8s.io/klog/v2 v2.110.1/go.mod h1:YGtd1984u+GgbuZ7e08/yBuAfKLSO0+uR1Fhi6ExXjo= 177 | k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00 h1:aVUu9fTY98ivBPKR9Y5w/AuzbMm96cd3YHRTU83I780= 178 | k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00/go.mod h1:AsvuZPBlUDVuCdzJ87iajxtXuR9oktsTctW/R9wwouA= 179 | k8s.io/utils v0.0.0-20230726121419-3b25d923346b h1:sgn3ZU783SCgtaSJjpcVVlRqd6GSnlTLKgpAAttJvpI= 180 | k8s.io/utils v0.0.0-20230726121419-3b25d923346b/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= 181 | modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ= 182 | modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ= 183 | modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y= 184 | modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s= 185 | modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= 186 | modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= 187 | modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw= 188 | modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU= 189 | modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI= 190 | modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4= 191 | modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U= 192 | modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w= 193 | modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= 194 | modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= 195 | modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E= 196 | modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU= 197 | modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= 198 | modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= 199 | modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc= 200 | modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss= 201 | modernc.org/sqlite v1.33.1 h1:trb6Z3YYoeM9eDL1O8do81kP+0ejv+YzgyFo+Gwy0nM= 202 | modernc.org/sqlite v1.33.1/go.mod h1:pXV2xHxhzXZsgT/RtTFAPY6JJDEvOTcTdwADQCCWD4k= 203 | modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= 204 | modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= 205 | modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= 206 | modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= 207 | sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= 208 | sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= 209 | sigs.k8s.io/structured-merge-diff/v4 v4.4.1 h1:150L+0vs/8DA78h1u02ooW1/fFq/Lwr+sGiqlzvrtq4= 210 | sigs.k8s.io/structured-merge-diff/v4 v4.4.1/go.mod h1:N8hJocpFajUSSeSJ9bOZ77VzejKZaXsTtZo4/u7Io08= 211 | sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= 212 | sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= 213 | -------------------------------------------------------------------------------- /internal/coordinator/artifactmanager.go: -------------------------------------------------------------------------------- 1 | package coordinator 2 | 3 | import ( 4 | "bytes" 5 | "crypto/sha256" 6 | "fmt" 7 | "io" 8 | "os" 9 | 10 | "github.com/Assifar-Karim/apollo/internal/db" 11 | "github.com/Assifar-Karim/apollo/internal/utils" 12 | ) 13 | 14 | type ArtifactManager interface { 15 | CreateArtifact(filename, artifactType string, size int64, file io.Reader) (db.Artifact, error) 16 | GetAllArtifactDetails() ([]db.Artifact, error) 17 | GetArtifactDetailsByName(filename string) (*db.Artifact, error) 18 | DeleteArtifact(filename string) (bool, error) 19 | } 20 | 21 | type ArtifactMngmtSvc struct { 22 | artifactRepository db.ArtifactRepository 23 | config *Config 24 | logger *utils.Logger 25 | } 26 | 27 | func getFileContent(file io.Reader) ([]byte, error) { 28 | buffer := bytes.NewBuffer(nil) 29 | if _, err := io.Copy(buffer, file); err != nil { 30 | return nil, err 31 | } 32 | return buffer.Bytes(), nil 33 | } 34 | 35 | func hash(buf []byte) (string, error) { 36 | h := sha256.New() 37 | if _, err := h.Write(buf); err != nil { 38 | return "", nil 39 | } 40 | 41 | return fmt.Sprintf("%x", h.Sum(nil)), nil 42 | } 43 | 44 | func writeFile(path string, fileContent []byte) error { 45 | if err := os.WriteFile(path, fileContent, 0666); err != nil { 46 | return err 47 | } 48 | return nil 49 | } 50 | 51 | func (s ArtifactMngmtSvc) CreateArtifact(filename, artifactType string, size int64, file io.Reader) (db.Artifact, error) { 52 | path := fmt.Sprintf("%s/%s", s.config.GetArtifactsPath(), filename) 53 | fileContent, err := getFileContent(file) 54 | if err != nil { 55 | s.logger.Error(err.Error()) 56 | return db.Artifact{}, err 57 | } 58 | fileHash, err := hash(fileContent) 59 | if err != nil { 60 | s.logger.Error(err.Error()) 61 | return db.Artifact{}, err 62 | } 63 | artifact, err := s.artifactRepository.FetchArficatByName(filename) 64 | if err != nil { 65 | return db.Artifact{}, err 66 | } 67 | if artifact == nil { 68 | if err = writeFile(path, fileContent); err != nil { 69 | s.logger.Error(err.Error()) 70 | return db.Artifact{}, err 71 | } 72 | return s.artifactRepository.CreateArtifact(filename, artifactType, fileHash, size) 73 | } 74 | 75 | if fileHash == artifact.Hash { 76 | return *artifact, nil 77 | } 78 | 79 | if err = writeFile(path, fileContent); err != nil { 80 | s.logger.Error(err.Error()) 81 | return db.Artifact{}, err 82 | } 83 | 84 | return s.artifactRepository.UpdateArtifact(filename, fileHash, size) 85 | } 86 | 87 | func (s ArtifactMngmtSvc) GetAllArtifactDetails() ([]db.Artifact, error) { 88 | return s.artifactRepository.FetchArtifacts() 89 | } 90 | 91 | func (s ArtifactMngmtSvc) GetArtifactDetailsByName(filename string) (*db.Artifact, error) { 92 | return s.artifactRepository.FetchArficatByName(filename) 93 | } 94 | 95 | func (s ArtifactMngmtSvc) DeleteArtifact(filename string) (bool, error) { 96 | path := fmt.Sprintf("%s/%s", s.config.artifactsPath, filename) 97 | if _, err := os.Stat(path); err != nil { 98 | s.logger.Error(err.Error()) 99 | return false, err 100 | } 101 | if err := os.Remove(path); err != nil { 102 | s.logger.Error(err.Error()) 103 | return false, err 104 | } 105 | return s.artifactRepository.DeleteArtifact(filename) 106 | } 107 | 108 | func NewArtifactManager(artifactRepository db.ArtifactRepository) ArtifactManager { 109 | return &ArtifactMngmtSvc{ 110 | artifactRepository: artifactRepository, 111 | config: GetConfig(), 112 | logger: utils.GetLogger(), 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /internal/coordinator/config.go: -------------------------------------------------------------------------------- 1 | package coordinator 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | "slices" 7 | "strconv" 8 | "sync" 9 | 10 | "github.com/Assifar-Karim/apollo/internal/utils" 11 | ) 12 | 13 | var lock = &sync.Mutex{} 14 | 15 | type Config struct { 16 | devMode bool 17 | artifactsPath string 18 | splitSize int64 19 | kubeConfigPath string 20 | workerNS string 21 | workerImg string 22 | intermediateFilesLoc string 23 | } 24 | 25 | var configInstance *Config 26 | 27 | func GetConfig() *Config { 28 | if configInstance == nil { 29 | lock.Lock() 30 | defer lock.Unlock() 31 | args := os.Args[1:] 32 | devMode := false 33 | if slices.Contains(args, "--dev") { 34 | devMode = true 35 | } 36 | artifactsPath, exists := os.LookupEnv("ARTIFACTS_PATH") 37 | if !exists { 38 | artifactsPath = "/coordinator/artifacts" 39 | } 40 | if artifactsPath[len(artifactsPath)-1] == '/' { 41 | artifactsPath = artifactsPath[:len(artifactsPath)-1] 42 | } 43 | splitSizeStr, exists := os.LookupEnv("SPLIT_SIZE") 44 | var splitSize int64 45 | if !exists { 46 | splitSize = 67108864 47 | } else { 48 | conv, err := strconv.Atoi(splitSizeStr) 49 | if err != nil { 50 | splitSize = 67108864 51 | logger := utils.GetLogger() 52 | logger.Warn("can't read split size from SPLIT_SIZE environment variable, size will default to 67108864 bytes") 53 | } else { 54 | splitSize = int64(conv) 55 | } 56 | } 57 | kubeConfigPath, exists := os.LookupEnv("KUBECONFIG_PATH") 58 | if !exists { 59 | home, err := os.UserHomeDir() 60 | if err != nil { 61 | // In case of an error we suppose that the home can be found using ~ 62 | home = "~" 63 | } 64 | kubeConfigPath = filepath.Join(home, ".kube/config") 65 | } 66 | 67 | workerNS, exists := os.LookupEnv("WORKER_NS") 68 | if !exists { 69 | workerNS = "apollo-workers" 70 | } 71 | 72 | workerImg, exists := os.LookupEnv("WORKER_IMG") 73 | if !exists { 74 | workerImg = "ghcr.io/assifar-karim/apollo-worker:release-0.1.1" 75 | } 76 | 77 | intermediateFilesLoc, exists := os.LookupEnv("INT_FILES_LOC") 78 | if !exists { 79 | intermediateFilesLoc = "/apollo/intermediate-files" 80 | } 81 | if intermediateFilesLoc[len(intermediateFilesLoc)-1] == '/' { 82 | intermediateFilesLoc = intermediateFilesLoc[:len(intermediateFilesLoc)-1] 83 | } 84 | configInstance = &Config{ 85 | devMode: devMode, 86 | artifactsPath: artifactsPath, 87 | splitSize: splitSize, 88 | kubeConfigPath: kubeConfigPath, 89 | workerNS: workerNS, 90 | workerImg: workerImg, 91 | intermediateFilesLoc: intermediateFilesLoc, 92 | } 93 | 94 | } 95 | return configInstance 96 | } 97 | 98 | func (c *Config) IsInDevMode() bool { 99 | return c.devMode 100 | } 101 | 102 | func (c *Config) GetArtifactsPath() string { 103 | return c.artifactsPath 104 | } 105 | 106 | func (c *Config) GetSplitSize() int64 { 107 | return c.splitSize 108 | } 109 | 110 | func (c *Config) GetKubeConfigPath() string { 111 | return c.kubeConfigPath 112 | } 113 | 114 | func (c *Config) GetWorkerNS() string { 115 | return c.workerNS 116 | } 117 | 118 | func (c *Config) GetWorkerImg() string { 119 | return c.workerImg 120 | } 121 | 122 | func (c *Config) GetIntermediateFilesLoc() string { 123 | return c.intermediateFilesLoc 124 | } 125 | -------------------------------------------------------------------------------- /internal/coordinator/jobdmetadatamanager.go: -------------------------------------------------------------------------------- 1 | package coordinator 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | 7 | "github.com/Assifar-Karim/apollo/internal/db" 8 | "github.com/Assifar-Karim/apollo/internal/utils" 9 | "github.com/google/uuid" 10 | ) 11 | 12 | type JobMetadataManager interface { 13 | PersistJob(nReducers int, inputPath, inputType, outputPath string, useSSL bool) (db.Job, error) 14 | GetAllJobs() ([]db.Job, error) 15 | GetJobById(id string) (*db.Job, error) 16 | GetTasksByJobID(id string) ([]db.Task, error) 17 | SetJobEndTimestamp(id string) error 18 | SetJobTasksAsStopped(id string) error 19 | } 20 | 21 | type JobMetadataMngmtSvc struct { 22 | jobRepository db.JobRepository 23 | taskRepository db.TaskRepository 24 | logger *utils.Logger 25 | } 26 | 27 | func (s JobMetadataMngmtSvc) PersistJob(nReducers int, inputPath, inputType, outputPath string, useSSL bool) (db.Job, error) { 28 | uuid, err := uuid.NewV7() 29 | if err != nil { 30 | s.logger.Error(err.Error()) 31 | return db.Job{}, err 32 | } 33 | id := fmt.Sprintf("j-%s", uuid.String()) 34 | startTime := time.Now().Unix() 35 | return s.jobRepository.CreateJob(nReducers, startTime, id, inputPath, inputType, outputPath, useSSL) 36 | } 37 | 38 | func (s JobMetadataMngmtSvc) GetAllJobs() ([]db.Job, error) { 39 | return s.jobRepository.FetchJobs() 40 | } 41 | 42 | func (s JobMetadataMngmtSvc) GetJobById(id string) (*db.Job, error) { 43 | return s.jobRepository.FetchJobByID(id) 44 | } 45 | 46 | func (s JobMetadataMngmtSvc) GetTasksByJobID(id string) ([]db.Task, error) { 47 | return s.taskRepository.FetchTasksByJobID(id) 48 | } 49 | 50 | func (s JobMetadataMngmtSvc) SetJobEndTimestamp(id string) error { 51 | return s.jobRepository.UpdateJobEndTimeByID(id, time.Now().Unix()) 52 | } 53 | 54 | func (s JobMetadataMngmtSvc) SetJobTasksAsStopped(id string) error { 55 | return s.taskRepository.UpdateUnfinishedTasksStatusByJobID("stopped", id) 56 | } 57 | 58 | func NewJobMetadataManager(jobRepository db.JobRepository, taskRepository db.TaskRepository) JobMetadataManager { 59 | return &JobMetadataMngmtSvc{ 60 | jobRepository: jobRepository, 61 | taskRepository: taskRepository, 62 | logger: utils.GetLogger(), 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /internal/coordinator/jobscheduler.go: -------------------------------------------------------------------------------- 1 | package coordinator 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "io" 7 | "regexp" 8 | "strings" 9 | "time" 10 | 11 | "github.com/Assifar-Karim/apollo/internal/db" 12 | coreio "github.com/Assifar-Karim/apollo/internal/io" 13 | "github.com/Assifar-Karim/apollo/internal/proto" 14 | "github.com/Assifar-Karim/apollo/internal/utils" 15 | "golang.org/x/sync/errgroup" 16 | "google.golang.org/grpc" 17 | "google.golang.org/grpc/credentials/insecure" 18 | 19 | corev1 "k8s.io/api/core/v1" 20 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 21 | utilrand "k8s.io/apimachinery/pkg/util/rand" 22 | "k8s.io/client-go/kubernetes" 23 | v1 "k8s.io/client-go/kubernetes/typed/core/v1" 24 | ) 25 | 26 | const MaxRetries = 5 27 | 28 | type JobScheduler interface { 29 | ScheduleJob(job db.Job, programArtifacts []db.Artifact, creds []coreio.Credentials, splitSize *int64) ([]db.Task, error) 30 | StopJob(id string) error 31 | } 32 | 33 | type JobSchedulingSvc struct { 34 | config *Config 35 | podClient v1.PodInterface 36 | k8sClient *kubernetes.Clientset 37 | taskRepository db.TaskRepository 38 | logger *utils.Logger 39 | } 40 | 41 | func (s JobSchedulingSvc) ScheduleJob( 42 | job db.Job, 43 | programArtifacts []db.Artifact, 44 | creds []coreio.Credentials, 45 | splitSize *int64) ([]db.Task, error) { 46 | 47 | splits, err := s.generateMapInputSplits( 48 | job.InputData.Path, 49 | job.Id, 50 | job.InputData.Type, 51 | creds[0].Username, 52 | creds[0].Password, 53 | splitSize) 54 | if err != nil { 55 | return nil, err 56 | } 57 | nMapper := len(splits) 58 | 59 | pods, err := s.createWorkerPods(job.Id, "mapper", programArtifacts[0].Name, "/mappers", nMapper) 60 | if err != nil { 61 | s.logger.Error(err.Error()) 62 | return nil, err 63 | } 64 | 65 | mTasks, err := s.taskRepository.CreateTasksBatch(job.Id, "mapper", pods, splits, 66 | programArtifacts[0], time.Now().Unix(), nMapper) 67 | if err != nil { 68 | s.logger.Error(err.Error()) 69 | return nil, err 70 | } 71 | 72 | if err := s.coordinateMapTasks(mTasks, job, creds[0]); err != nil { 73 | s.logger.Error(err.Error()) 74 | return nil, err 75 | } 76 | 77 | pods, err = s.createWorkerPods(job.Id, "reducer", programArtifacts[1].Name, s.config.GetIntermediateFilesLoc(), job.NReducers) 78 | if err != nil { 79 | s.logger.Error(err.Error()) 80 | return nil, err 81 | } 82 | 83 | rTasks, err := s.taskRepository.CreateTasksBatch(job.Id, "reducer", pods, []db.InputData{}, 84 | programArtifacts[1], time.Now().Unix(), job.NReducers) 85 | if err != nil { 86 | s.logger.Error(err.Error()) 87 | return nil, err 88 | } 89 | if err := s.coordinateReduceTasks(rTasks, nMapper, creds[1], job.Id, job.OutputLocation); err != nil { 90 | s.logger.Error(err.Error()) 91 | return nil, err 92 | } 93 | 94 | tasks := append(mTasks, rTasks...) 95 | return tasks, nil 96 | } 97 | 98 | func (s JobSchedulingSvc) StopJob(id string) error { 99 | listOptions := metav1.ListOptions{ 100 | LabelSelector: fmt.Sprintf("job=%s", id), 101 | } 102 | err := s.podClient.DeleteCollection(context.Background(), metav1.DeleteOptions{}, listOptions) 103 | if err != nil { 104 | s.logger.Error("Could not delete job %s pods -> %v", id, err) 105 | } 106 | return err 107 | } 108 | 109 | func (s JobSchedulingSvc) createWorkerPods(jobId, wType, programPath, mountPath string, nSize int) ([]string, error) { 110 | podName := generatePodName("worker-") 111 | podDefinition := &corev1.Pod{ 112 | ObjectMeta: metav1.ObjectMeta{ 113 | Name: podName, 114 | Namespace: s.config.GetWorkerNS(), 115 | Labels: map[string]string{"type": wType, "job": jobId, "app": "worker"}, 116 | }, 117 | Spec: corev1.PodSpec{ 118 | Subdomain: "workers", 119 | Hostname: podName, 120 | Containers: []corev1.Container{ 121 | { 122 | Name: "worker", 123 | Image: s.config.GetWorkerImg(), 124 | Ports: []corev1.ContainerPort{ 125 | { 126 | ContainerPort: 8090, 127 | }, 128 | }, 129 | VolumeMounts: []corev1.VolumeMount{ 130 | { 131 | Name: "data", 132 | MountPath: mountPath, 133 | }, 134 | }, 135 | }, 136 | }, 137 | Volumes: []corev1.Volume{ 138 | { 139 | Name: "data", 140 | VolumeSource: corev1.VolumeSource{ 141 | PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ 142 | ClaimName: "apollo-intermediate-files-pvc", 143 | }, 144 | }, 145 | }, 146 | }, 147 | }, 148 | } 149 | pods := make([]string, nSize) 150 | for i := 0; i < nSize; i++ { 151 | taskId := fmt.Sprintf("%s-%c-%v", jobId, wType[0], i) 152 | if s.config.IsInDevMode() { 153 | // Create a service for external communication with the coordinator on dev mode 154 | servicePort, err := generateDevModeServicePort(taskId) 155 | if err != nil { 156 | return nil, err 157 | } 158 | serviceDefinition := &corev1.Service{ 159 | ObjectMeta: metav1.ObjectMeta{ 160 | Name: fmt.Sprintf("dev-mode-service-%s", taskId), 161 | }, 162 | Spec: corev1.ServiceSpec{ 163 | Ports: []corev1.ServicePort{ 164 | { 165 | Port: 8090, 166 | NodePort: int32(servicePort), 167 | }, 168 | }, 169 | Selector: map[string]string{"id": taskId}, 170 | Type: corev1.ServiceTypeNodePort, 171 | }, 172 | } 173 | _, err = s.k8sClient.CoreV1().Services(s.config.GetWorkerNS()).Create( 174 | context.Background(), 175 | serviceDefinition, 176 | metav1.CreateOptions{}) 177 | if err != nil { 178 | return nil, err 179 | } 180 | 181 | } 182 | podDefinition.ObjectMeta.Labels["id"] = taskId 183 | podDefinition.ObjectMeta.Labels["program"] = programPath 184 | pod, err := s.podClient.Create(context.Background(), podDefinition, metav1.CreateOptions{}) 185 | if err != nil && err.Error() == fmt.Sprintf("namespaces \"%s\" not found", s.config.GetWorkerNS()) { 186 | s.logger.Warn("%s", err) 187 | s.logger.Info("Creating %s namespace", s.config.GetWorkerNS()) 188 | s.k8sClient.CoreV1().Namespaces().Create(context.Background(), &corev1.Namespace{ 189 | ObjectMeta: metav1.ObjectMeta{ 190 | Name: s.config.GetWorkerNS(), 191 | }, 192 | }, metav1.CreateOptions{}) 193 | pod, err = s.podClient.Create(context.Background(), podDefinition, metav1.CreateOptions{}) 194 | } 195 | if err != nil { 196 | s.logger.Error("worker pod %v couldn't be created -> %v", i, err) 197 | return nil, err 198 | } 199 | pods[i] = pod.Name 200 | s.logger.Info("worker pod %s was successfully created for job %s and task %s", pod.Name, jobId, taskId) 201 | } 202 | return pods, nil 203 | } 204 | 205 | func (s JobSchedulingSvc) generateMapInputSplits(path, jobId, wType, username, password string, splitSize *int64) ([]db.InputData, error) { 206 | pathInfo := strings.Split(path, "/") 207 | endpoint := strings.Join(pathInfo[2:len(pathInfo)-2], "/") 208 | 209 | protocol := pathInfo[0] 210 | var useSSL bool 211 | if protocol == "http:" { 212 | useSSL = false 213 | } else if protocol == "https:" { 214 | useSSL = true 215 | } else { 216 | errMsg := "wrong protocol, please make sure the protocol is either HTTP or HTTPS" 217 | s.logger.Error("Wrong input data protocol found for job %s -> %s", jobId, errMsg) 218 | return nil, fmt.Errorf(errMsg) 219 | } 220 | 221 | if s.config.IsInDevMode() { 222 | endpoint = regexp.MustCompile(`(.)*:`).ReplaceAllString(endpoint, "localhost:") 223 | } 224 | s3Registrar, err := coreio.NewS3Registrar(endpoint, username, password, useSSL) 225 | if err != nil { 226 | s.logger.Error(err.Error()) 227 | return nil, err 228 | } 229 | bucket := pathInfo[len(pathInfo)-2] 230 | filename := pathInfo[len(pathInfo)-1] 231 | 232 | filesize, err := s3Registrar.GetFileSize(bucket, filename) 233 | if err != nil { 234 | s.logger.Error(err.Error()) 235 | return nil, err 236 | } 237 | 238 | var concreteSplitSize int64 239 | if splitSize == nil { 240 | concreteSplitSize = s.config.GetSplitSize() 241 | } else { 242 | concreteSplitSize = *splitSize 243 | } 244 | 245 | splits := make([]db.InputData, 0) 246 | var i int64 247 | for i = 0; i < filesize; i += concreteSplitSize { 248 | a := i 249 | var b int64 250 | if i+concreteSplitSize < filesize { 251 | b = i + concreteSplitSize 252 | } else { 253 | b = filesize 254 | } 255 | splits = append(splits, db.InputData{ 256 | Path: path, 257 | Type: wType, 258 | SplitStart: &a, 259 | SplitEnd: &b, 260 | }) 261 | } 262 | s.logger.Info("Input file %s of size %s B generated %v of maximum size %v", path, filesize, len(splits), concreteSplitSize) 263 | return splits, nil 264 | } 265 | 266 | func (s JobSchedulingSvc) coordinateMapTasks(tasks []db.Task, job db.Job, creds coreio.Credentials) error { 267 | var taskGroup errgroup.Group 268 | for i := 0; i < len(tasks); i++ { 269 | taskType, err := tasks[i].GetType() 270 | if err != nil { 271 | s.logger.Error(err.Error()) 272 | return err 273 | } 274 | s.logger.Info("Program name: %s", tasks[i].Program.Name) 275 | programContent, err := tasks[i].GetProgramContent(s.config.GetArtifactsPath()) 276 | if err != nil { 277 | s.logger.Error(err.Error()) 278 | return err 279 | } 280 | 281 | inputData := []*proto.FileData{{ 282 | Path: tasks[i].InputData.Path, 283 | SplitStart: tasks[i].InputData.SplitStart, 284 | SplitEnd: tasks[i].InputData.SplitEnd, 285 | }} 286 | 287 | if i < len(tasks)-1 { 288 | inputData = append( 289 | inputData, 290 | &proto.FileData{ 291 | Path: tasks[i+1].InputData.Path, 292 | SplitStart: tasks[i+1].InputData.SplitStart, 293 | SplitEnd: tasks[i+1].InputData.SplitEnd, 294 | }, 295 | ) 296 | } 297 | nReducers := int64(job.NReducers) 298 | 299 | target := *tasks[i].PodName 300 | payload := &proto.Task{ 301 | Id: tasks[i].Id, 302 | Type: taskType, 303 | NReducers: &nReducers, 304 | Program: &proto.Program{ 305 | Name: fmt.Sprintf("/apollo/%s", tasks[i].Program.Name), 306 | Content: programContent, 307 | }, 308 | InputData: inputData, 309 | ObjectStorageCreds: &proto.Credentials{ 310 | Username: creds.Username, 311 | Password: creds.Password, 312 | }, 313 | } 314 | taskGroup.Go(func() error { 315 | return s.startTask(target, payload) 316 | }) 317 | } 318 | return taskGroup.Wait() 319 | } 320 | 321 | func (s JobSchedulingSvc) coordinateReduceTasks(tasks []db.Task, nMapper int, creds coreio.Credentials, jobId string, outLoc db.OutputLocation) error { 322 | var taskGroup errgroup.Group 323 | for i := 0; i < len(tasks); i++ { 324 | taskType, err := tasks[i].GetType() 325 | if err != nil { 326 | s.logger.Warn(err.Error()) 327 | return err 328 | } 329 | programContent, err := tasks[i].GetProgramContent(s.config.GetArtifactsPath()) 330 | if err != nil { 331 | s.logger.Error(err.Error()) 332 | return err 333 | } 334 | 335 | inputData := []*proto.FileData{} 336 | for j := 0; j < nMapper; j++ { 337 | filename := fmt.Sprintf("%s-m-%v_%v.json", jobId, j, i) 338 | path := fmt.Sprintf("%s/%s", s.config.GetIntermediateFilesLoc(), filename) 339 | inputData = append(inputData, &proto.FileData{ 340 | Path: path, 341 | }) 342 | } 343 | target := *tasks[i].PodName 344 | payload := &proto.Task{ 345 | Id: tasks[i].Id, 346 | Type: taskType, 347 | Program: &proto.Program{ 348 | Name: fmt.Sprintf("/apollo/%s", tasks[i].Program.Name), 349 | Content: programContent, 350 | }, 351 | InputData: inputData, 352 | ObjectStorageCreds: &proto.Credentials{ 353 | Username: creds.Username, 354 | Password: creds.Password, 355 | }, 356 | OutputStorageInfo: &proto.OutputStorageInfo{ 357 | Location: outLoc.Location, 358 | UseSSL: &outLoc.UseSSL, 359 | }, 360 | } 361 | taskGroup.Go(func() error { 362 | return s.startTask(target, payload) 363 | }) 364 | } 365 | 366 | return taskGroup.Wait() 367 | } 368 | 369 | func (s JobSchedulingSvc) startTask(target string, task *proto.Task) error { 370 | target = fmt.Sprintf("%s.workers.%s.svc.cluster.local:8090", target, s.config.GetWorkerNS()) 371 | if s.config.IsInDevMode() { 372 | port, err := generateDevModeServicePort(task.GetId()) 373 | if err != nil { 374 | return err 375 | } 376 | target = fmt.Sprintf("localhost:%v", port) 377 | } 378 | conn, err := grpc.NewClient(target, grpc.WithTransportCredentials(insecure.NewCredentials())) 379 | if err != nil { 380 | return err 381 | } 382 | defer conn.Close() 383 | s.logger.Info("Connected successfuly to %s", target) 384 | client := proto.NewTaskCreatorClient(conn) 385 | stream, err := client.StartTask(context.Background(), task) 386 | retries := MaxRetries 387 | exp := 2 388 | for retries > 0 && err != nil { 389 | s.logger.Warn("Connection attempt %v to %s failed with error %v", MaxRetries-retries+1, target, err) 390 | backoff := time.Duration(exp-1) * time.Second 391 | s.logger.Info("Retrying connection to %s in %v", target, backoff) 392 | time.Sleep(backoff) 393 | retries-- 394 | exp *= 2 395 | stream, err = client.StartTask(context.Background(), task) 396 | } 397 | if err != nil { 398 | return err 399 | } 400 | 401 | s.logger.Info("Starting task %v in %s", task.Id, target) 402 | for { 403 | taskStatusInfo, err := stream.Recv() 404 | if err == io.EOF { 405 | break 406 | } 407 | if err != nil { 408 | return err 409 | } 410 | err = s.taskRepository.UpdateTaskStatusByID(task.Id, taskStatusInfo.TaskStatus) 411 | if err != nil { 412 | return err 413 | } 414 | 415 | if taskStatusInfo.TaskStatus == "failed" { 416 | errMsg := fmt.Sprintf("Task %s has failed", task.Id) 417 | return fmt.Errorf(errMsg) 418 | } 419 | } 420 | s.logger.Info("Task %s has completed its workload", task.Id) 421 | return s.taskRepository.UpdateTaskEndTimeByID(task.Id, time.Now().Unix()) 422 | } 423 | 424 | func generateDevModeServicePort(taskId string) (int, error) { 425 | // NOTE: This function generates an exact node port for a task that should be between 30000 and 32767 426 | taskHash, err := utils.Hash(taskId) 427 | if err != nil { 428 | return 0, err 429 | } 430 | return (taskHash % 2768) + 30000, nil 431 | } 432 | 433 | func generatePodName(base string) string { 434 | // NOTE: This code logic is directly extracted from the k8s api server codebase, for more details check: 435 | // https://github.com/kubernetes/apiserver/blob/master/pkg/storage/names/generate.go 436 | const ( 437 | maxNameLength = 63 438 | randomLength = 5 439 | maxGeneratedNameLength = maxNameLength - randomLength 440 | ) 441 | if len(base) > maxGeneratedNameLength { 442 | base = base[:maxGeneratedNameLength] 443 | } 444 | return fmt.Sprintf("%s%s", base, utilrand.String(randomLength)) 445 | } 446 | 447 | func NewJobScheduler(k8sClient *kubernetes.Clientset, taskRepository db.TaskRepository) JobScheduler { 448 | config := GetConfig() 449 | podClient := k8sClient.CoreV1().Pods(config.GetWorkerNS()) 450 | return &JobSchedulingSvc{ 451 | config: config, 452 | podClient: podClient, 453 | k8sClient: k8sClient, 454 | taskRepository: taskRepository, 455 | logger: utils.GetLogger(), 456 | } 457 | } 458 | -------------------------------------------------------------------------------- /internal/coordinator/k8sclient.go: -------------------------------------------------------------------------------- 1 | package coordinator 2 | 3 | import ( 4 | "k8s.io/client-go/kubernetes" 5 | "k8s.io/client-go/rest" 6 | "k8s.io/client-go/tools/clientcmd" 7 | ) 8 | 9 | func NewK8sClient() (*kubernetes.Clientset, error) { 10 | var config *rest.Config 11 | var err error 12 | appConfig := GetConfig() 13 | if appConfig.IsInDevMode() { 14 | kubeConfigPath := GetConfig().GetKubeConfigPath() 15 | config, err = clientcmd.BuildConfigFromFlags("", kubeConfigPath) 16 | } else { 17 | config, err = rest.InClusterConfig() 18 | } 19 | if err != nil { 20 | return nil, err 21 | } 22 | 23 | return kubernetes.NewForConfig(config) 24 | } 25 | -------------------------------------------------------------------------------- /internal/db/artifactrepo.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "database/sql" 5 | "errors" 6 | 7 | "github.com/Assifar-Karim/apollo/internal/utils" 8 | ) 9 | 10 | type ArtifactRepository interface { 11 | CreateArtifact(name, artifactType, hash string, size int64) (Artifact, error) 12 | FetchArtifacts() ([]Artifact, error) 13 | FetchArficatByName(name string) (*Artifact, error) 14 | DeleteArtifact(name string) (bool, error) 15 | UpdateArtifact(name, hash string, size int64) (Artifact, error) 16 | } 17 | 18 | type SQLiteArtifactRepository struct { 19 | db *sql.DB 20 | logger *utils.Logger 21 | } 22 | 23 | func (r SQLiteArtifactRepository) CreateArtifact(name, artifactType, hash string, size int64) (Artifact, error) { 24 | query := "INSERT INTO artifact VALUES (?, ?, ?, ?);" 25 | r.logger.Trace(query) 26 | _, err := r.db.Exec(query, name, artifactType, size, hash) 27 | if err != nil { 28 | r.logger.Error(err.Error()) 29 | return Artifact{}, err 30 | } 31 | return Artifact{ 32 | Name: name, 33 | Type: artifactType, 34 | Size: size, 35 | Hash: hash, 36 | }, nil 37 | } 38 | 39 | func (r SQLiteArtifactRepository) FetchArtifacts() ([]Artifact, error) { 40 | query := "SELECT name, type, size, hash FROM artifact;" 41 | r.logger.Trace(query) 42 | rows, err := r.db.Query(query) 43 | if err != nil { 44 | r.logger.Error(err.Error()) 45 | return []Artifact{}, err 46 | } 47 | defer rows.Close() 48 | artifacts := []Artifact{} 49 | for rows.Next() { 50 | artifact := Artifact{} 51 | err := rows.Scan(&artifact.Name, &artifact.Type, &artifact.Size, &artifact.Hash) 52 | if err != nil { 53 | r.logger.Error(err.Error()) 54 | return []Artifact{}, err 55 | } 56 | artifacts = append(artifacts, artifact) 57 | } 58 | return artifacts, nil 59 | } 60 | 61 | func (r SQLiteArtifactRepository) FetchArficatByName(name string) (*Artifact, error) { 62 | query := "SELECT name, type, size, hash FROM artifact WHERE name = ?;" 63 | r.logger.Trace(query) 64 | row := r.db.QueryRow(query, name) 65 | artifact := Artifact{} 66 | err := row.Scan(&artifact.Name, &artifact.Type, &artifact.Size, &artifact.Hash) 67 | 68 | if errors.Is(err, sql.ErrNoRows) { 69 | r.logger.Warn("No artifact with name %s was found", name) 70 | return nil, nil 71 | } 72 | if err != nil { 73 | r.logger.Error(err.Error()) 74 | return nil, err 75 | } 76 | 77 | return &artifact, nil 78 | } 79 | 80 | func (r SQLiteArtifactRepository) DeleteArtifact(name string) (bool, error) { 81 | query := "DELETE FROM artifact WHERE name = ?;" 82 | r.logger.Trace(query) 83 | res, err := r.db.Exec(query, name) 84 | if err != nil { 85 | r.logger.Error(err.Error()) 86 | return false, err 87 | } 88 | count, err := res.RowsAffected() 89 | if err != nil { 90 | r.logger.Error(err.Error()) 91 | return false, err 92 | } 93 | return count != 0, nil 94 | } 95 | 96 | func (r SQLiteArtifactRepository) UpdateArtifact(name, hash string, size int64) (Artifact, error) { 97 | query := "UPDATE artifact SET hash = ?, size = ? WHERE name = ?;" 98 | r.logger.Trace(query) 99 | _, err := r.db.Exec(query, hash, size, name) 100 | if err != nil { 101 | return Artifact{}, err 102 | } 103 | artifact, err := r.FetchArficatByName(name) 104 | if err != nil { 105 | r.logger.Error(err.Error()) 106 | return Artifact{}, err 107 | } 108 | if artifact == nil { 109 | return Artifact{}, sql.ErrNoRows 110 | } 111 | return *artifact, nil 112 | } 113 | 114 | func NewSQLiteArtifactRepository(db *sql.DB) ArtifactRepository { 115 | return &SQLiteArtifactRepository{ 116 | db: db, 117 | logger: utils.GetLogger(), 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /internal/db/db.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "database/sql" 5 | "errors" 6 | "fmt" 7 | "os" 8 | "strings" 9 | 10 | "github.com/Assifar-Karim/apollo/internal/utils" 11 | ) 12 | 13 | type Job struct { 14 | Id string `json:"id"` 15 | NReducers int `json:"nReducers"` 16 | OutputLocation OutputLocation `json:"outputLocation"` 17 | InputData InputData `json:"inputData"` 18 | StartTime int64 `json:"startTime"` 19 | EndTime *int64 `json:"endTime,omitempty"` 20 | } 21 | 22 | type Task struct { 23 | Id string `json:"id"` 24 | Job *Job `json:"job,omitempty"` 25 | Type string `json:"type"` 26 | Status string `json:"status"` 27 | Program Artifact `json:"program"` 28 | InputData *InputData `json:"inputData,omitempty"` 29 | PodName *string `json:"podName,omitempty"` 30 | StartTime int64 `json:"startTime"` 31 | EndTime *int64 `json:"endTime,omitempty"` 32 | } 33 | 34 | type InputData struct { 35 | Id int `json:"id"` 36 | Path string `json:"path"` 37 | Type string `json:"type"` 38 | SplitStart *int64 `json:"splitStart,omitempty"` 39 | SplitEnd *int64 `json:"splitEnd,omitempty"` 40 | } 41 | 42 | type OutputLocation struct { 43 | Location string `json:"location"` 44 | UseSSL bool `json:"useSSL"` 45 | } 46 | 47 | type Artifact struct { 48 | Name string `json:"name"` 49 | Type string `json:"type"` 50 | Size int64 `json:"size"` 51 | Hash string `json:"hash"` 52 | } 53 | 54 | func runInTx(db *sql.DB, fn func(tx *sql.Tx) error) error { 55 | tx, err := db.Begin() 56 | if err != nil { 57 | return err 58 | } 59 | err = fn(tx) 60 | if err == nil { 61 | return tx.Commit() 62 | } 63 | rollbackErr := tx.Rollback() 64 | if rollbackErr != nil { 65 | // In case even the rollback fails 66 | return errors.Join(err, rollbackErr) 67 | } 68 | return err 69 | } 70 | 71 | func New(driver, dbName string, devMode bool) (*sql.DB, error) { 72 | logger := utils.GetLogger() 73 | // Open DB connection 74 | if !devMode { 75 | dbName = fmt.Sprintf("/apollo/data/%s", dbName) 76 | } 77 | logger.Info("Connecting to %s:%s database", driver, dbName) 78 | db, err := sql.Open(driver, dbName) 79 | if err != nil { 80 | return nil, err 81 | } 82 | // Setup DB tables 83 | queries := make([]string, 5) 84 | 85 | queries[0] = `CREATE TABLE IF NOT EXISTS output_location ( 86 | location VARCHAR PRIMARY KEY NOT NULL, 87 | use_SSL BOOLEAN NOT NULL);` 88 | 89 | queries[1] = `CREATE TABLE IF NOT EXISTS input_data ( 90 | id INTEGER PRIMARY KEY NOT NULL, 91 | path VARCHAR NOT NULL, 92 | type VARCHAR NOT NULL, 93 | split_start INTEGER, 94 | split_end INTEGER);` 95 | 96 | queries[2] = `CREATE TABLE IF NOT EXISTS job ( 97 | id VARCHAR PRIMARY KEY NOT NULL, 98 | n_reducers INTEGER NOT NULL, 99 | output_path VARCHAR NOT NULL, 100 | input_id INTEGER NOT NULL, 101 | start_time DATETIME NOT NULL, 102 | end_time DATETIME, 103 | FOREIGN KEY(input_id) REFERENCES input_data(id), 104 | FOREIGN KEY(output_path) REFERENCES output_location(location));` 105 | 106 | queries[3] = `CREATE TABLE IF NOT EXISTS artifact ( 107 | name VARCHAR PRIMARY KEY NOT NULL, 108 | type VARCHAR NOT NULL DEFAULT executable, 109 | size INTEGER NOT NULL DEFAULT 0, 110 | hash VARCHAR NOT NULL);` 111 | 112 | queries[4] = `CREATE TABLE IF NOT EXISTS task ( 113 | id VARCHAR PRIMARY KEY NOT NULL, 114 | job_id VARCHAR NOT NULL, 115 | type VARCHAR NOT NULL, 116 | status VARCHAR NOT NULL DEFAULT scheduled, 117 | program_name VARCHAR NOT NULL, 118 | input_data_id INTEGER, 119 | pod_name VARCHAR, 120 | start_time DATETIME NOT NULL, 121 | end_time DATETIME, 122 | FOREIGN KEY(job_id) REFERENCES job(id), 123 | FOREIGN KEY(input_data_id) REFERENCES input_data(id), 124 | FOREIGN KEY(program_name) REFERENCES artifact(name));` 125 | 126 | for _, query := range queries { 127 | logger.Trace(query) 128 | _, err := db.Exec(query) 129 | if err != nil { 130 | return nil, err 131 | } 132 | } 133 | return db, err 134 | } 135 | 136 | func (t Task) GetType() (int64, error) { 137 | taskType := strings.ToLower(t.Type) 138 | if taskType == "mapper" { 139 | return 0, nil 140 | } else if taskType == "reducer" { 141 | return 1, nil 142 | } 143 | return -1, fmt.Errorf("%s isn't supported by apollo", taskType) 144 | } 145 | 146 | func (t Task) GetProgramContent(origin string) ([]byte, error) { 147 | path := fmt.Sprintf("%s/%s", origin, t.Program.Name) 148 | file, err := os.Open(path) 149 | if err != nil { 150 | return nil, err 151 | } 152 | defer file.Close() 153 | fInfo, err := file.Stat() 154 | if err != nil { 155 | return nil, err 156 | } 157 | buffer := make([]byte, fInfo.Size()) 158 | _, err = file.Read(buffer) 159 | if err != nil { 160 | return nil, err 161 | } 162 | return buffer, nil 163 | } 164 | -------------------------------------------------------------------------------- /internal/db/jobrepo.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "database/sql" 5 | "errors" 6 | 7 | "github.com/Assifar-Karim/apollo/internal/utils" 8 | ) 9 | 10 | type JobRepository interface { 11 | CreateJob(nReducers int, startTime int64, id, inputPath, inputType, outputPath string, useSSL bool) (Job, error) 12 | FetchJobs() ([]Job, error) 13 | FetchJobByID(id string) (*Job, error) 14 | UpdateJobEndTimeByID(id string, endTs int64) error 15 | } 16 | 17 | type SQLiteJobRepository struct { 18 | db *sql.DB 19 | logger *utils.Logger 20 | } 21 | 22 | func (r *SQLiteJobRepository) CreateJob( 23 | nReducers int, startTime int64, 24 | id, inputPath, inputType, outputPath string, 25 | useSSL bool) (Job, error) { 26 | inputDataID := 0 27 | transactionLogic := func(tx *sql.Tx) error { 28 | query := "SELECT location FROM output_location WHERE location=?;" 29 | r.logger.Trace(query) 30 | if err := tx.QueryRow(query, outputPath).Scan(); errors.Is(err, sql.ErrNoRows) { 31 | query = "INSERT INTO output_location VALUES (?, ?);" 32 | r.logger.Trace(query) 33 | _, err := tx.Exec(query, outputPath, useSSL) 34 | if err != nil { 35 | return err 36 | } 37 | } 38 | 39 | query = "INSERT INTO input_data VALUES (NULL, ?, ?, NULL, NULL);" 40 | r.logger.Trace(query) 41 | res, err := tx.Exec(query, inputPath, inputType) 42 | if err != nil { 43 | return err 44 | } 45 | 46 | inputId, err := res.LastInsertId() 47 | inputDataID = int(inputId) 48 | if err != nil { 49 | return err 50 | } 51 | query = "INSERT INTO job VALUES (?, ?, ?, ?, ?, NULL);" 52 | r.logger.Trace(query) 53 | _, err = tx.Exec(query, id, nReducers, outputPath, inputId, startTime) 54 | return err 55 | } 56 | 57 | if err := runInTx(r.db, transactionLogic); err != nil { 58 | r.logger.Error(err.Error()) 59 | return Job{}, err 60 | } 61 | 62 | return Job{ 63 | Id: id, 64 | NReducers: nReducers, 65 | OutputLocation: OutputLocation{ 66 | Location: outputPath, 67 | UseSSL: useSSL, 68 | }, 69 | InputData: InputData{ 70 | Id: inputDataID, 71 | Path: inputPath, 72 | Type: inputType, 73 | }, 74 | StartTime: startTime, 75 | }, nil 76 | } 77 | 78 | func (r *SQLiteJobRepository) FetchJobs() ([]Job, error) { 79 | query := `SELECT j.id, j.n_reducers, o.location, o.use_ssl, i.id, 80 | i.path, i.type, i.split_start, i.split_end, j.start_time, j.end_time FROM job j 81 | JOIN input_data i ON i.id = j.input_id 82 | JOIN output_location o ON o.location = j.output_path;` 83 | 84 | r.logger.Trace(query) 85 | rows, err := r.db.Query(query) 86 | if err != nil { 87 | return []Job{}, err 88 | } 89 | defer rows.Close() 90 | jobs := []Job{} 91 | for rows.Next() { 92 | job := Job{} 93 | inputData := InputData{} 94 | outputLocation := OutputLocation{} 95 | 96 | err := rows.Scan( 97 | &job.Id, 98 | &job.NReducers, 99 | &outputLocation.Location, 100 | &outputLocation.UseSSL, 101 | &inputData.Id, 102 | &inputData.Path, 103 | &inputData.Type, 104 | &inputData.SplitStart, 105 | &inputData.SplitEnd, 106 | &job.StartTime, 107 | &job.EndTime) 108 | 109 | if err != nil { 110 | r.logger.Error(err.Error()) 111 | return []Job{}, err 112 | } 113 | 114 | job.InputData = inputData 115 | job.OutputLocation = outputLocation 116 | jobs = append(jobs, job) 117 | } 118 | return jobs, nil 119 | } 120 | 121 | func (r *SQLiteJobRepository) FetchJobByID(id string) (*Job, error) { 122 | query := `SELECT j.id, j.n_reducers, o.location, o.use_ssl, i.id, 123 | i.path, i.type, i.split_start, i.split_end, j.start_time, j.end_time FROM job j 124 | JOIN input_data i ON i.id = j.input_id 125 | JOIN output_location o ON o.location = j.output_path 126 | WHERE j.id = ?;` 127 | 128 | r.logger.Trace(query) 129 | row := r.db.QueryRow(query, id) 130 | 131 | job := Job{} 132 | inputData := InputData{} 133 | outputLocation := OutputLocation{} 134 | err := row.Scan( 135 | &job.Id, 136 | &job.NReducers, 137 | &outputLocation.Location, 138 | &outputLocation.UseSSL, 139 | &inputData.Id, 140 | &inputData.Path, 141 | &inputData.Type, 142 | &inputData.SplitStart, 143 | &inputData.SplitEnd, 144 | &job.StartTime, 145 | &job.EndTime) 146 | 147 | if errors.Is(err, sql.ErrNoRows) { 148 | r.logger.Warn("No job with id %s was found", id) 149 | return nil, nil 150 | } 151 | if err != nil { 152 | r.logger.Error(err.Error()) 153 | return nil, err 154 | } 155 | job.InputData = inputData 156 | job.OutputLocation = outputLocation 157 | return &job, nil 158 | 159 | } 160 | 161 | func (r *SQLiteJobRepository) UpdateJobEndTimeByID(id string, endTs int64) error { 162 | query := "UPDATE job SET end_time = ? WHERE id = ?;" 163 | r.logger.Trace(query) 164 | _, err := r.db.Exec(query, endTs, id) 165 | return err 166 | } 167 | 168 | func NewSQLiteJobsRepository(db *sql.DB) JobRepository { 169 | return &SQLiteJobRepository{ 170 | db: db, 171 | logger: utils.GetLogger(), 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /internal/db/taskrepo.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | 7 | "github.com/Assifar-Karim/apollo/internal/utils" 8 | ) 9 | 10 | type TaskRepository interface { 11 | CreateTasksBatch(jobId, taskType string, pods []string, inputs []InputData, program Artifact, startTime int64, count int) ([]Task, error) 12 | FetchTasksByJobID(jobId string) ([]Task, error) 13 | UpdateTaskStatusByID(id, status string) error 14 | UpdateTaskEndTimeByID(id string, endTs int64) error 15 | UpdateUnfinishedTasksStatusByJobID(status, jobId string) error 16 | } 17 | 18 | type SQLiteTaskRepository struct { 19 | db *sql.DB 20 | logger *utils.Logger 21 | } 22 | 23 | func (r *SQLiteTaskRepository) CreateTasksBatch(jobId, taskType string, 24 | pods []string, inputs []InputData, program Artifact, startTime int64, count int) ([]Task, error) { 25 | 26 | tasks := make([]Task, count) 27 | transactionLogic := func(tx *sql.Tx) error { 28 | if len(inputs) > 0 { 29 | query := `INSERT INTO input_data (id, path, type, split_start, split_end) VALUES ` 30 | queryParams := []any{} 31 | for _, inputData := range inputs { 32 | queryParams = append(queryParams, inputData.Path, inputData.Type, inputData.SplitStart, inputData.SplitEnd) 33 | query += `(NULL, ?, ?, ?, ?),` 34 | } 35 | query = query[:len(query)-1] + ";" 36 | r.logger.Trace(query) 37 | res, err := tx.Exec(query, queryParams...) 38 | if err != nil { 39 | return err 40 | } 41 | lastInputId, err := res.LastInsertId() 42 | if err != nil { 43 | return err 44 | } 45 | offset := int(lastInputId) - len(inputs) + 1 46 | for i := range inputs { 47 | inputs[i].Id = offset + i 48 | } 49 | } 50 | 51 | query := `INSERT INTO task ( 52 | id, job_id, type, program_name, input_data_id, 53 | pod_name, start_time, end_time) VALUES ` 54 | queryParams := []any{} 55 | for i := 0; i < count; i++ { 56 | id := fmt.Sprintf("%s-%c-%v", jobId, taskType[0], i) 57 | task := Task{ 58 | Id: id, 59 | Type: taskType, 60 | Status: "scheduled", 61 | Program: program, 62 | PodName: &pods[i], 63 | StartTime: startTime, 64 | } 65 | if len(inputs) > 0 { 66 | task.InputData = &inputs[i] 67 | queryParams = append(queryParams, 68 | task.Id, 69 | jobId, 70 | task.Type, 71 | program.Name, 72 | task.InputData.Id, 73 | *task.PodName, 74 | task.StartTime) 75 | query += `(?, ?, ?, ?, ?, ?, ?, NULL),` 76 | } else { 77 | queryParams = append(queryParams, 78 | task.Id, 79 | jobId, 80 | task.Type, 81 | program.Name, 82 | *task.PodName, 83 | task.StartTime) 84 | query += `(?, ?, ?, ?, NULL, ?, ?, NULL),` 85 | } 86 | tasks[i] = task 87 | } 88 | query = query[:len(query)-1] + ";" 89 | r.logger.Trace(query) 90 | _, err := tx.Exec(query, queryParams...) 91 | return err 92 | } 93 | if err := runInTx(r.db, transactionLogic); err != nil { 94 | r.logger.Error(err.Error()) 95 | return []Task{}, err 96 | } 97 | return tasks, nil 98 | } 99 | 100 | func (r *SQLiteTaskRepository) FetchTasksByJobID(jobId string) ([]Task, error) { 101 | query := `SELECT t.id, t.type, t.status, t.pod_name, t.start_time, t.end_time, 102 | a.name, a.type, a.size, a.hash, 103 | i.id, i.path, i.type, i.split_start, i.split_end 104 | FROM task t 105 | JOIN artifact a ON a.name = t.program_name 106 | LEFT OUTER JOIN input_data i ON i.id = t.input_data_id 107 | WHERE t.job_id = ?;` 108 | 109 | r.logger.Trace(query) 110 | rows, err := r.db.Query(query, jobId) 111 | if err != nil { 112 | r.logger.Error(err.Error()) 113 | return []Task{}, err 114 | } 115 | defer rows.Close() 116 | tasks := []Task{} 117 | for rows.Next() { 118 | task := Task{} 119 | inputData := InputData{} 120 | artifact := Artifact{} 121 | // input data scan verification vars 122 | var iId sql.NullInt32 123 | var iPath, iType sql.NullString 124 | err := rows.Scan( 125 | &task.Id, 126 | &task.Type, 127 | &task.Status, 128 | &task.PodName, 129 | &task.StartTime, 130 | &task.EndTime, 131 | &artifact.Name, 132 | &artifact.Type, 133 | &artifact.Size, 134 | &artifact.Hash, 135 | &iId, 136 | &iPath, 137 | &iType, 138 | &inputData.SplitStart, 139 | &inputData.SplitEnd) 140 | 141 | if err != nil { 142 | r.logger.Error(err.Error()) 143 | return []Task{}, err 144 | } 145 | 146 | if iId.Valid && iPath.Valid && iType.Valid { 147 | inputData.Id = int(iId.Int32) 148 | inputData.Path = iPath.String 149 | inputData.Type = iType.String 150 | task.InputData = &inputData 151 | } 152 | 153 | task.Program = artifact 154 | tasks = append(tasks, task) 155 | } 156 | return tasks, nil 157 | } 158 | 159 | func (r *SQLiteTaskRepository) UpdateTaskStatusByID(id, status string) error { 160 | query := "UPDATE task SET status = ? WHERE id = ?;" 161 | r.logger.Trace(query) 162 | _, err := r.db.Exec(query, status, id) 163 | return err 164 | } 165 | 166 | func (r *SQLiteTaskRepository) UpdateTaskEndTimeByID(id string, endTs int64) error { 167 | query := "UPDATE task SET end_time = ? WHERE id = ?;" 168 | r.logger.Trace(query) 169 | _, err := r.db.Exec(query, endTs, id) 170 | return err 171 | } 172 | 173 | func (r *SQLiteTaskRepository) UpdateUnfinishedTasksStatusByJobID(status, jobId string) error { 174 | query := "UPDATE task SET status = ? WHERE job_id = ? AND status != completed" 175 | r.logger.Trace(query) 176 | _, err := r.db.Exec(query, status, jobId) 177 | return err 178 | } 179 | 180 | func NewSQLiteTaskRepository(db *sql.DB) TaskRepository { 181 | return &SQLiteTaskRepository{ 182 | db: db, 183 | logger: utils.GetLogger(), 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /internal/handler/artifactcreator.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "net/http" 7 | 8 | "github.com/Assifar-Karim/apollo/internal/coordinator" 9 | "github.com/go-chi/chi/v5" 10 | "github.com/go-chi/chi/v5/middleware" 11 | ) 12 | 13 | type artifactHandler struct { 14 | artifactManager coordinator.ArtifactManager 15 | } 16 | 17 | func (h *artifactHandler) CreateArtifact(w http.ResponseWriter, r *http.Request) { 18 | file, fHandler, err := r.FormFile("program") 19 | if err != nil { 20 | errMsg := fmt.Sprintf("Couldn't get program artifact: %v", err.Error()) 21 | http.Error(w, errMsg, http.StatusBadRequest) 22 | return 23 | } 24 | defer file.Close() 25 | artifact, err := h.artifactManager.CreateArtifact(fHandler.Filename, "executable", fHandler.Size, file) 26 | 27 | if err != nil { 28 | http.Error(w, err.Error(), http.StatusInternalServerError) 29 | return 30 | } 31 | w.Header().Set("Content-Type", "application/json") 32 | w.WriteHeader(http.StatusOK) 33 | err = json.NewEncoder(w).Encode(artifact) 34 | if err != nil { 35 | http.Error(w, err.Error(), http.StatusInternalServerError) 36 | return 37 | } 38 | } 39 | 40 | func (h *artifactHandler) GetArtifacts(w http.ResponseWriter, r *http.Request) { 41 | artifacts, err := h.artifactManager.GetAllArtifactDetails() 42 | if err != nil { 43 | http.Error(w, err.Error(), http.StatusInternalServerError) 44 | return 45 | } 46 | w.Header().Set("Content-Type", "application/json") 47 | w.WriteHeader(http.StatusOK) 48 | err = json.NewEncoder(w).Encode(artifacts) 49 | if err != nil { 50 | http.Error(w, err.Error(), http.StatusInternalServerError) 51 | return 52 | } 53 | } 54 | 55 | func (h *artifactHandler) GetArtifactByName(w http.ResponseWriter, r *http.Request) { 56 | name := chi.URLParam(r, "filename") 57 | artifact, err := h.artifactManager.GetArtifactDetailsByName(name) 58 | if err != nil { 59 | http.Error(w, err.Error(), http.StatusInternalServerError) 60 | return 61 | } 62 | if artifact == nil { 63 | http.Error(w, "", http.StatusNotFound) 64 | return 65 | } 66 | w.Header().Set("Content-Type", "application/json") 67 | w.WriteHeader(http.StatusOK) 68 | err = json.NewEncoder(w).Encode(&artifact) 69 | if err != nil { 70 | http.Error(w, err.Error(), http.StatusInternalServerError) 71 | return 72 | } 73 | } 74 | 75 | func (h *artifactHandler) DeleteArtifact(w http.ResponseWriter, r *http.Request) { 76 | name := chi.URLParam(r, "filename") 77 | _, err := h.artifactManager.DeleteArtifact(name) 78 | if err != nil { 79 | http.Error(w, err.Error(), http.StatusInternalServerError) 80 | return 81 | } 82 | w.Header().Set("Content-Type", "application/json") 83 | w.WriteHeader(http.StatusNoContent) 84 | } 85 | 86 | func NewArtifactHandler(artifactManager coordinator.ArtifactManager) *Controller { 87 | router := chi.NewRouter() 88 | router.Use(middleware.AllowContentType("application/json", "multipart/form-data")) 89 | handler := artifactHandler{ 90 | artifactManager: artifactManager, 91 | } 92 | 93 | // Endpoints definition 94 | router.Put("/", handler.CreateArtifact) 95 | router.Get("/", handler.GetArtifacts) 96 | router.Get("/{filename}", handler.GetArtifactByName) 97 | router.Delete("/{filename}", handler.DeleteArtifact) 98 | 99 | return &Controller{ 100 | Pattern: "/api/v1/artifacts", 101 | Router: router, 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /internal/handler/controller.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import "github.com/go-chi/chi/v5" 4 | 5 | type Controller struct { 6 | Pattern string 7 | Router chi.Router 8 | } 9 | -------------------------------------------------------------------------------- /internal/handler/jobmanager.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "net/http" 7 | "slices" 8 | 9 | "github.com/Assifar-Karim/apollo/internal/coordinator" 10 | "github.com/Assifar-Karim/apollo/internal/db" 11 | "github.com/Assifar-Karim/apollo/internal/io" 12 | "github.com/go-chi/chi/v5" 13 | "github.com/go-chi/chi/v5/middleware" 14 | _ "modernc.org/sqlite" 15 | ) 16 | 17 | type jobManagerHandler struct { 18 | jobMetadataManager coordinator.JobMetadataManager 19 | artifactManager coordinator.ArtifactManager 20 | jobScheduler coordinator.JobScheduler 21 | } 22 | 23 | type jobInfo struct { 24 | NReducers int `json:"nReducers"` 25 | InputPath string `json:"inputPath"` 26 | InputType string `json:"inputType"` 27 | OutputPath string `json:"outputPath"` 28 | UseSSL bool `json:"useSSL"` 29 | MapperName string `json:"mapperName"` 30 | ReducerName string `json:"reducerName"` 31 | InputStorageCredentials io.Credentials `json:"inputStorageCredentials"` 32 | OutputStorageCredentials io.Credentials `json:"outputStorageCredentials"` 33 | SplitSize *int64 `json:"splitSize,omitempty"` 34 | } 35 | 36 | type ScheduleDTO struct { 37 | Job db.Job `json:"job"` 38 | MapProgram db.Artifact `json:"mProgram"` 39 | ReduceProgram db.Artifact `json:"rProgram"` 40 | } 41 | 42 | var allowedInputTypes []string = []string{"file/txt"} 43 | 44 | func (h *jobManagerHandler) getJobs(w http.ResponseWriter, r *http.Request) { 45 | jobs, err := h.jobMetadataManager.GetAllJobs() 46 | if err != nil { 47 | http.Error(w, err.Error(), http.StatusInternalServerError) 48 | return 49 | } 50 | w.Header().Set("Content-Type", "application/json") 51 | w.WriteHeader(http.StatusOK) 52 | err = json.NewEncoder(w).Encode(jobs) 53 | if err != nil { 54 | http.Error(w, err.Error(), http.StatusInternalServerError) 55 | return 56 | } 57 | } 58 | 59 | func (h *jobManagerHandler) getJobById(w http.ResponseWriter, r *http.Request) { 60 | id := chi.URLParam(r, "id") 61 | job, err := h.jobMetadataManager.GetJobById(id) 62 | if err != nil { 63 | http.Error(w, err.Error(), http.StatusInternalServerError) 64 | return 65 | } 66 | if job == nil { 67 | http.Error(w, "", http.StatusNotFound) 68 | return 69 | } 70 | w.Header().Set("Content-Type", "application/json") 71 | w.WriteHeader(http.StatusOK) 72 | err = json.NewEncoder(w).Encode(&job) 73 | if err != nil { 74 | http.Error(w, err.Error(), http.StatusInternalServerError) 75 | return 76 | } 77 | } 78 | 79 | func (h *jobManagerHandler) scheduleJob(w http.ResponseWriter, r *http.Request) { 80 | decoder := json.NewDecoder(r.Body) 81 | decoder.DisallowUnknownFields() 82 | var body jobInfo 83 | err := decoder.Decode(&body) 84 | if err != nil { 85 | http.Error(w, err.Error(), http.StatusBadRequest) 86 | return 87 | } 88 | if !slices.Contains(allowedInputTypes, body.InputType) { 89 | errMsg := fmt.Sprintf("%s isn't in the allowed input types list %v", body.InputType, allowedInputTypes) 90 | http.Error(w, errMsg, http.StatusBadRequest) 91 | return 92 | } 93 | 94 | artifactNames := []string{body.MapperName, body.ReducerName} 95 | artifacts := make([]db.Artifact, 2) 96 | for idx, name := range artifactNames { 97 | artifact, err := h.artifactManager.GetArtifactDetailsByName(name) 98 | if err != nil { 99 | http.Error(w, err.Error(), http.StatusInternalServerError) 100 | return 101 | } 102 | if artifact == nil { 103 | errMsg := fmt.Sprintf("%s artifact metadata can't be found!", name) 104 | http.Error(w, errMsg, http.StatusNotFound) 105 | return 106 | } 107 | artifacts[idx] = *artifact 108 | } 109 | 110 | job, err := h.jobMetadataManager.PersistJob(body.NReducers, body.InputPath, body.InputType, body.OutputPath, body.UseSSL) 111 | if err != nil { 112 | http.Error(w, err.Error(), http.StatusInternalServerError) 113 | return 114 | } 115 | 116 | creds := []io.Credentials{body.InputStorageCredentials, body.OutputStorageCredentials} 117 | go func() { 118 | _, err := h.jobScheduler.ScheduleJob(job, artifacts, creds, body.SplitSize) 119 | if err == nil { 120 | h.jobMetadataManager.SetJobEndTimestamp(job.Id) 121 | } 122 | }() 123 | 124 | // NOTE (KARIM): Add a way to save the credentials in a vault later for restarting jobs in case of failure 125 | response := ScheduleDTO{ 126 | Job: job, 127 | MapProgram: artifacts[0], 128 | ReduceProgram: artifacts[1], 129 | } 130 | w.Header().Set("Content-Type", "application/json") 131 | w.WriteHeader(http.StatusCreated) 132 | err = json.NewEncoder(w).Encode(response) 133 | if err != nil { 134 | http.Error(w, err.Error(), http.StatusInternalServerError) 135 | return 136 | } 137 | 138 | } 139 | 140 | func (h *jobManagerHandler) getTasksByJobId(w http.ResponseWriter, r *http.Request) { 141 | id := chi.URLParam(r, "id") 142 | tasks, err := h.jobMetadataManager.GetTasksByJobID(id) 143 | if err != nil { 144 | http.Error(w, err.Error(), http.StatusInternalServerError) 145 | return 146 | } 147 | w.Header().Set("Content-Type", "application/json") 148 | w.WriteHeader(http.StatusOK) 149 | err = json.NewEncoder(w).Encode(tasks) 150 | if err != nil { 151 | http.Error(w, err.Error(), http.StatusInternalServerError) 152 | return 153 | } 154 | } 155 | 156 | func (h *jobManagerHandler) stopJob(w http.ResponseWriter, r *http.Request) { 157 | id := chi.URLParam(r, "id") 158 | job, err := h.jobMetadataManager.GetJobById(id) 159 | if err != nil { 160 | http.Error(w, err.Error(), http.StatusInternalServerError) 161 | return 162 | } 163 | if job == nil { 164 | http.Error(w, fmt.Sprintf("No job with id %s was found!", id), http.StatusNotFound) 165 | return 166 | } 167 | if job.EndTime != nil { 168 | http.Error(w, fmt.Sprintf("Job %s already finished its workload!", id), http.StatusNotAcceptable) 169 | return 170 | } 171 | if err := h.jobScheduler.StopJob(id); err != nil { 172 | http.Error(w, err.Error(), http.StatusInternalServerError) 173 | return 174 | } 175 | if err := h.jobMetadataManager.SetJobEndTimestamp(id); err != nil { 176 | http.Error(w, err.Error(), http.StatusInternalServerError) 177 | return 178 | } 179 | if err := h.jobMetadataManager.SetJobTasksAsStopped(id); err != nil { 180 | http.Error(w, err.Error(), http.StatusInternalServerError) 181 | return 182 | } 183 | w.Header().Set("Content-Type", "application/json") 184 | w.WriteHeader(http.StatusOK) 185 | w.Write([]byte(fmt.Sprintf("Job %s was successfully stopped", id))) 186 | } 187 | 188 | func NewJobManagerHandler( 189 | jobMetadataManager coordinator.JobMetadataManager, 190 | artifactManager coordinator.ArtifactManager, 191 | jobScheduler coordinator.JobScheduler) *Controller { 192 | router := chi.NewRouter() 193 | router.Use(middleware.AllowContentType("application/json")) 194 | handler := jobManagerHandler{ 195 | jobMetadataManager: jobMetadataManager, 196 | artifactManager: artifactManager, 197 | jobScheduler: jobScheduler, 198 | } 199 | // Endpoints definition 200 | router.Get("/", handler.getJobs) 201 | router.Get("/{id}", handler.getJobById) 202 | router.Get("/{id}/tasks", handler.getTasksByJobId) 203 | router.Post("/", handler.scheduleJob) 204 | router.Delete("/{id}", handler.stopJob) 205 | 206 | return &Controller{ 207 | Pattern: "/api/v1/jobs", 208 | Router: router, 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /internal/handler/taskcreator.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "sync" 5 | 6 | "github.com/Assifar-Karim/apollo/internal/proto" 7 | "github.com/Assifar-Karim/apollo/internal/utils" 8 | "github.com/Assifar-Karim/apollo/internal/worker" 9 | "google.golang.org/grpc/codes" 10 | "google.golang.org/grpc/status" 11 | ) 12 | 13 | type TaskCreatorHandler struct { 14 | proto.UnimplementedTaskCreatorServer 15 | worker *worker.Worker 16 | } 17 | 18 | func (h TaskCreatorHandler) StartTask(task *proto.Task, stream proto.TaskCreator_StartTaskServer) error { 19 | logger := utils.GetLogger() 20 | workerType := task.GetType() 21 | var workerAlgorithm worker.WorkerAlgorithm 22 | var err error = nil 23 | var resultingFiles []*proto.FileData 24 | 25 | if workerType == 0 { 26 | workerAlgorithm = worker.NewMapper() 27 | logger.Info("Map task assigned") 28 | } else if workerType == 1 { 29 | workerAlgorithm = worker.NewReducer() 30 | logger.Info("Reduce task assigned") 31 | } else { 32 | return status.Error(codes.InvalidArgument, "illegal worker type") 33 | } 34 | h.worker.SetWorkerAlgorithm(workerAlgorithm) 35 | 36 | stream.Send(&proto.TaskStatusInfo{ 37 | TaskStatus: "idle", 38 | ResultingFiles: []*proto.FileData{}, 39 | }) 40 | 41 | var wg sync.WaitGroup 42 | wg.Add(1) 43 | 44 | go func() { 45 | defer wg.Done() 46 | resultingFiles, err = h.worker.Compute(task) 47 | logger.Info("Task started") 48 | }() 49 | 50 | stream.Send(&proto.TaskStatusInfo{ 51 | TaskStatus: "in-progress", 52 | ResultingFiles: []*proto.FileData{}, 53 | }) 54 | 55 | wg.Wait() 56 | 57 | if err != nil { 58 | stream.Send(&proto.TaskStatusInfo{ 59 | TaskStatus: "failed", 60 | ResultingFiles: []*proto.FileData{}, 61 | }) 62 | logger.Error("Task failed") 63 | logger.Error(err.Error()) 64 | } else { 65 | stream.Send(&proto.TaskStatusInfo{ 66 | TaskStatus: "completed", 67 | ResultingFiles: resultingFiles, 68 | }) 69 | logger.Info("Task completed succesfully") 70 | } 71 | return err 72 | } 73 | 74 | func NewTaskCreatorHandler(worker *worker.Worker) *TaskCreatorHandler { 75 | return &TaskCreatorHandler{worker: worker} 76 | } 77 | -------------------------------------------------------------------------------- /internal/io/fsregistrar.go: -------------------------------------------------------------------------------- 1 | package io 2 | 3 | import ( 4 | "bufio" 5 | 6 | "github.com/Assifar-Karim/apollo/internal/proto" 7 | ) 8 | 9 | type Closeable interface { 10 | Close() error 11 | } 12 | 13 | type FSRegistrar interface { 14 | GetFile(fileData *proto.FileData) (*bufio.Scanner, Closeable, error) 15 | WriteFile(path string, content []byte) error 16 | } 17 | -------------------------------------------------------------------------------- /internal/io/localfsregistrar.go: -------------------------------------------------------------------------------- 1 | package io 2 | 3 | import ( 4 | "bufio" 5 | "os" 6 | 7 | "github.com/Assifar-Karim/apollo/internal/proto" 8 | "google.golang.org/grpc/codes" 9 | "google.golang.org/grpc/status" 10 | ) 11 | 12 | type LocalFSRegistrar struct { 13 | } 14 | 15 | func (r LocalFSRegistrar) GetFile(fileData *proto.FileData) (*bufio.Scanner, Closeable, error) { 16 | path := fileData.GetPath() 17 | file, err := os.Open(path) 18 | 19 | if err != nil { 20 | return nil, nil, status.Error(codes.NotFound, err.Error()) 21 | } 22 | 23 | scanner := bufio.NewScanner(file) 24 | return scanner, file, err 25 | } 26 | 27 | func (r LocalFSRegistrar) WriteFile(path string, content []byte) error { 28 | err := os.WriteFile(path, content, 0644) 29 | if err != nil { 30 | return status.Error(codes.Internal, err.Error()) 31 | } 32 | return nil 33 | } 34 | -------------------------------------------------------------------------------- /internal/io/s3registrar.go: -------------------------------------------------------------------------------- 1 | package io 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "context" 7 | "fmt" 8 | "strings" 9 | 10 | "github.com/Assifar-Karim/apollo/internal/proto" 11 | "github.com/Assifar-Karim/apollo/internal/utils" 12 | "github.com/minio/minio-go/v7" 13 | "github.com/minio/minio-go/v7/pkg/credentials" 14 | "google.golang.org/grpc/codes" 15 | "google.golang.org/grpc/status" 16 | ) 17 | 18 | type Credentials struct { 19 | Username string `json:"username"` 20 | Password string `json:"password"` 21 | } 22 | 23 | type S3Registrar struct { 24 | minioClient *minio.Client 25 | } 26 | 27 | func (r S3Registrar) GetFile(fileData *proto.FileData) (*bufio.Scanner, Closeable, error) { 28 | splitStart := fileData.GetSplitStart() 29 | splitEnd := fileData.GetSplitEnd() 30 | 31 | if splitStart > splitEnd { 32 | errorMsg := fmt.Sprintf("the split start %v can't be bigger than the split end %v", splitStart, splitEnd) 33 | return nil, nil, status.Error(codes.FailedPrecondition, errorMsg) 34 | } 35 | 36 | if splitStart == splitEnd && splitStart == 0 { 37 | return nil, nil, status.Error(codes.FailedPrecondition, "can't handle empty split") 38 | } 39 | objectOptions := minio.GetObjectOptions{} 40 | objectOptions.SetRange(splitStart, splitEnd) 41 | 42 | pathInfo := strings.Split(fileData.GetPath(), "/") 43 | 44 | // This check is added to verify whether the stored file trully exists in the object storage or not and if the app can access it 45 | _, err := r.minioClient.StatObject(context.Background(), pathInfo[len(pathInfo)-2], pathInfo[len(pathInfo)-1], objectOptions) 46 | if err != nil { 47 | return nil, nil, status.Error(codes.Internal, err.Error()) 48 | } 49 | 50 | object, err := r.minioClient.GetObject(context.Background(), pathInfo[len(pathInfo)-2], pathInfo[len(pathInfo)-1], objectOptions) 51 | if err != nil { 52 | return nil, nil, status.Error(codes.Internal, err.Error()) 53 | } 54 | scanner := utils.NewScanner(object) 55 | return scanner, object, err 56 | } 57 | 58 | func (r S3Registrar) GetFileSize(bucket, filename string) (int64, error) { 59 | stats, err := r.minioClient.StatObject(context.Background(), bucket, filename, minio.GetObjectOptions{}) 60 | if err != nil { 61 | return 0, err 62 | } 63 | return stats.Size, nil 64 | } 65 | 66 | func (r S3Registrar) WriteFile(path string, content []byte) error { 67 | ctx := context.Background() 68 | splittedPath := strings.Split(path, "/")[1:] 69 | topBucket := splittedPath[0] 70 | jobFolder := splittedPath[1] 71 | filename := splittedPath[2] 72 | exists, err := r.minioClient.BucketExists(ctx, topBucket) 73 | if err != nil { 74 | return status.Error(codes.Internal, err.Error()) 75 | } 76 | if !exists { 77 | err = r.minioClient.MakeBucket(ctx, topBucket, minio.MakeBucketOptions{}) 78 | if err != nil { 79 | return status.Error(codes.Internal, err.Error()) 80 | } 81 | } 82 | _, err = r.minioClient.PutObject(ctx, topBucket, fmt.Sprintf("%v/%v", jobFolder, filename), bytes.NewReader(content), -1, minio.PutObjectOptions{}) 83 | if err != nil { 84 | return status.Error(codes.Internal, err.Error()) 85 | } 86 | return nil 87 | } 88 | 89 | func NewS3Registrar(endpoint, accessKeyID, secretAccessKey string, useSSL bool) (*S3Registrar, error) { 90 | client, err := minio.New(endpoint, &minio.Options{ 91 | Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""), 92 | Secure: useSSL, 93 | }) 94 | if err != nil { 95 | err = status.Error(codes.PermissionDenied, fmt.Sprintf("Couldn't connect to %s object storage: %s", endpoint, err)) 96 | } 97 | return &S3Registrar{ 98 | minioClient: client, 99 | }, err 100 | } 101 | -------------------------------------------------------------------------------- /internal/server/coordinatorHTTPserver.go: -------------------------------------------------------------------------------- 1 | package server 2 | 3 | import ( 4 | "net" 5 | "net/http" 6 | "os" 7 | 8 | "github.com/Assifar-Karim/apollo/internal/handler" 9 | "github.com/Assifar-Karim/apollo/internal/utils" 10 | "github.com/go-chi/chi/v5" 11 | "github.com/go-chi/chi/v5/middleware" 12 | ) 13 | 14 | type CoordinatorHTTPSrv struct { 15 | port string 16 | lis net.Listener 17 | router chi.Router 18 | } 19 | 20 | func NewHttpServer(port string, controllers ...*handler.Controller) (*CoordinatorHTTPSrv, error) { 21 | lis, err := net.Listen("tcp", port) 22 | if err != nil { 23 | return nil, err 24 | } 25 | 26 | router := chi.NewRouter() 27 | router.Use(middleware.Logger) 28 | for _, controller := range controllers { 29 | router.Mount(controller.Pattern, controller.Router) 30 | } 31 | return &CoordinatorHTTPSrv{ 32 | port: port, 33 | lis: lis, 34 | router: router, 35 | }, nil 36 | } 37 | 38 | func (c CoordinatorHTTPSrv) Serve() error { 39 | logger := utils.GetLogger() 40 | hostname, err := os.Hostname() 41 | if err != nil { 42 | hostname = "localhost" 43 | } 44 | logger.Info("Coordinator Server Running: %s%s", hostname, c.port) 45 | return http.Serve(c.lis, c.router) 46 | } 47 | -------------------------------------------------------------------------------- /internal/server/workergRPCserver.go: -------------------------------------------------------------------------------- 1 | package server 2 | 3 | import ( 4 | "net" 5 | "os" 6 | 7 | "github.com/Assifar-Karim/apollo/internal/handler" 8 | "github.com/Assifar-Karim/apollo/internal/proto" 9 | "github.com/Assifar-Karim/apollo/internal/utils" 10 | "google.golang.org/grpc" 11 | ) 12 | 13 | type WorkerGrpcSrv struct { 14 | port string 15 | lis net.Listener 16 | concreteSrv *grpc.Server 17 | } 18 | 19 | func NewGrpcServer(port string, taskCreatorHandler handler.TaskCreatorHandler) (*WorkerGrpcSrv, error) { 20 | lis, err := net.Listen("tcp", port) 21 | if err != nil { 22 | return nil, err 23 | } 24 | serverRegistrar := grpc.NewServer() 25 | proto.RegisterTaskCreatorServer(serverRegistrar, taskCreatorHandler) 26 | return &WorkerGrpcSrv{ 27 | port: port, 28 | lis: lis, 29 | concreteSrv: serverRegistrar, 30 | }, nil 31 | } 32 | 33 | func (w WorkerGrpcSrv) Serve() error { 34 | logger := utils.GetLogger() 35 | hostname, err := os.Hostname() 36 | if err != nil { 37 | hostname = "localhost" 38 | } 39 | logger.Info("Worker Server Running: %s%s", hostname, w.port) 40 | return w.concreteSrv.Serve(w.lis) 41 | } 42 | -------------------------------------------------------------------------------- /internal/utils/hash.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bytes" 5 | "encoding/gob" 6 | "hash/fnv" 7 | ) 8 | 9 | func Hash[T any](input T) (int, error) { 10 | buffer := bytes.NewBuffer([]byte{}) 11 | encoder := gob.NewEncoder(buffer) 12 | err := encoder.Encode(input) 13 | if err != nil { 14 | return 0, err 15 | } 16 | hasher := fnv.New32a() 17 | hasher.Write(buffer.Bytes()) 18 | return int(hasher.Sum32()), nil 19 | } 20 | -------------------------------------------------------------------------------- /internal/utils/logger.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "slices" 8 | "sync" 9 | ) 10 | 11 | var lock = &sync.Mutex{} 12 | 13 | type Logger struct { 14 | infoLogger *log.Logger 15 | warnLogger *log.Logger 16 | errorLogger *log.Logger 17 | traceLogger *log.Logger 18 | } 19 | 20 | var loggerInstance *Logger 21 | 22 | func GetLogger() *Logger { 23 | if loggerInstance == nil { 24 | lock.Lock() 25 | defer lock.Unlock() 26 | flags := log.Ldate | log.Ltime | log.Lmsgprefix 27 | 28 | args := os.Args[1:] 29 | var traceLogger *log.Logger = nil 30 | if slices.Contains(args, "--trace") { 31 | traceLogger = log.New(os.Stdout, "\033[32mTRACE: \033[0m", flags) 32 | } 33 | 34 | loggerInstance = &Logger{ 35 | infoLogger: log.New(os.Stdout, "\033[35mINFO: \033[0m", flags), 36 | warnLogger: log.New(os.Stdout, "\033[33mWARN: \033[0m", flags), 37 | errorLogger: log.New(os.Stderr, "\033[31mERROR: \033[0m", flags), 38 | traceLogger: traceLogger, 39 | } 40 | } 41 | return loggerInstance 42 | } 43 | 44 | func (l *Logger) Info(format string, v ...interface{}) { 45 | l.infoLogger.Printf(format+"\n", v...) 46 | } 47 | 48 | func (l *Logger) Warn(format string, v ...interface{}) { 49 | l.warnLogger.Printf(format+"\n", v...) 50 | } 51 | 52 | func (l *Logger) Error(format string, v ...interface{}) { 53 | l.errorLogger.Printf(format, v...) 54 | } 55 | 56 | func (l *Logger) Trace(format string, v ...interface{}) { 57 | if l.traceLogger != nil { 58 | l.traceLogger.Printf(format, v...) 59 | } 60 | } 61 | 62 | func (l *Logger) PrintBanner() { 63 | fmt.Println(" ___ __ __ ") 64 | fmt.Println(" / | ____ ____ / / / / ____ ") 65 | fmt.Println(" / /| | / __ \\ / __ \\ / / / / / __ \\") 66 | fmt.Println(" / ___ | / /_/ // /_/ // /___ / /___/ /_/ /") 67 | fmt.Println("/_/ |_|/ .___/ \\____//_____//_____/\\____/ ") 68 | fmt.Println(" /_/ ") 69 | } 70 | -------------------------------------------------------------------------------- /internal/utils/scanner.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "io" 7 | ) 8 | 9 | func dropCR(data []byte) []byte { 10 | if len(data) > 0 && data[len(data)-1] == '\r' { 11 | return data[0 : len(data)-1] 12 | } 13 | return data 14 | } 15 | 16 | // NOTE : This is a modified split function that keeps the newline character while dropping the CR 17 | func scanLines(data []byte, atEOF bool) (advance int, token []byte, err error) { 18 | if atEOF && len(data) == 0 { 19 | return 0, nil, nil 20 | } 21 | if i := bytes.IndexByte(data, '\n'); i >= 0 { 22 | // We have a full newline-terminated line. 23 | lineData := dropCR(data[0:i]) 24 | return i + 1, append(lineData, '\n'), nil 25 | } 26 | // If we're at EOF, we have a final, non-terminated line. Return it. 27 | if atEOF { 28 | return len(data), dropCR(data), nil 29 | } 30 | // Request more data. 31 | return 0, nil, nil 32 | } 33 | 34 | func NewScanner(r io.Reader) *bufio.Scanner { 35 | scanner := bufio.NewScanner(r) 36 | scanner.Split(scanLines) 37 | return scanner 38 | } 39 | -------------------------------------------------------------------------------- /internal/worker/map.go: -------------------------------------------------------------------------------- 1 | package worker 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "encoding/json" 7 | "fmt" 8 | "net" 9 | "os" 10 | "os/exec" 11 | "strings" 12 | "sync" 13 | 14 | "github.com/Assifar-Karim/apollo/internal/io" 15 | "github.com/Assifar-Karim/apollo/internal/proto" 16 | "github.com/Assifar-Karim/apollo/internal/utils" 17 | "golang.org/x/sync/errgroup" 18 | "google.golang.org/grpc/codes" 19 | "google.golang.org/grpc/status" 20 | ) 21 | 22 | type Mapper struct { 23 | inputFSRegistrar io.FSRegistrar 24 | outputFSRegistrar io.FSRegistrar 25 | output map[int][]KVPair 26 | logger *utils.Logger 27 | } 28 | 29 | type KVPairArray struct { 30 | Pairs []KVPair `json:"pairs"` 31 | } 32 | type KVPair struct { 33 | Key any `json:"key"` 34 | Value any `json:"value"` 35 | } 36 | 37 | type partitionPayload struct { 38 | partitionKey int 39 | pair KVPair 40 | } 41 | 42 | func (m *Mapper) setinputFSRegistrar(fileData *proto.FileData, credentials *proto.Credentials) error { 43 | path := fileData.GetPath() 44 | if path == "" { 45 | return status.Error(codes.InvalidArgument, "empty path") 46 | } 47 | pathInfo := strings.Split(path, "/") 48 | endpoint := strings.Join(pathInfo[2:len(pathInfo)-2], "/") 49 | 50 | protocol := pathInfo[0] 51 | var useSSL bool 52 | if protocol == "http:" { 53 | useSSL = false 54 | } else if protocol == "https:" { 55 | useSSL = true 56 | } else { 57 | return status.Error(codes.InvalidArgument, "wrong protocol, please make sure the protocol is either HTTP or HTTPS") 58 | } 59 | 60 | inputFSRegistrar, err := io.NewS3Registrar(endpoint, credentials.GetUsername(), credentials.GetPassword(), useSSL) 61 | if err == nil { 62 | m.inputFSRegistrar = inputFSRegistrar 63 | } 64 | return err 65 | } 66 | 67 | func (m *Mapper) HandleTask(task *proto.Task, input []*bufio.Scanner) error { 68 | nReducers := task.GetNReducers() 69 | if nReducers == 0 { 70 | return status.Error(codes.InvalidArgument, "reducers can't be set to 0") 71 | } 72 | program := task.GetProgram() 73 | if program == nil { 74 | return status.Error(codes.InvalidArgument, "program field can't be empty") 75 | } 76 | pName := program.GetName() 77 | if pName == "" { 78 | return status.Error(codes.InvalidArgument, "empty program name") 79 | } 80 | pContent := program.GetContent() 81 | if pContent == nil { 82 | return status.Error(codes.InvalidArgument, "empty program content") 83 | } 84 | err := os.WriteFile(pName, pContent, 0744) 85 | if err != nil { 86 | return status.Error(codes.Internal, err.Error()) 87 | } 88 | 89 | socket, err := net.Listen("unix", "/tmp/map.sock") 90 | if err != nil { 91 | return status.Error(codes.Internal, err.Error()) 92 | } 93 | defer socket.Close() 94 | m.logger.Info("listening on \033[33m/tmp/map.sock\033[0m socket") 95 | 96 | output := make(map[int][]KVPair) 97 | endLine := "" 98 | for idx, scanner := range input { 99 | lineNumber := 0 100 | // Skip the first line of every input split that doesn't start at offset 0 101 | if task.InputData[idx].GetSplitStart() != 0 { 102 | scanner.Scan() 103 | } 104 | // Producers 105 | pairsChan := make(chan partitionPayload) 106 | var eg errgroup.Group 107 | for idx == 0 && scanner.Scan() { 108 | line := scanner.Text() 109 | // Check if the line is incomplete unless it's in the final input split 110 | rLine := []rune(line) 111 | if len(input) > 1 && rLine[len(line)-1] != '\n' { 112 | endLine += line 113 | break 114 | } 115 | // Remove the newline character from the line 116 | if rLine[len(line)-1] == '\n' { 117 | line = line[0 : len(line)-1] 118 | } 119 | eg.Go(func() error { 120 | cmd := exec.Command(pName, fmt.Sprintf("%v", lineNumber), line) 121 | if err := cmd.Start(); err != nil { 122 | return err 123 | } 124 | return cmd.Wait() 125 | }) 126 | 127 | lineNumber++ 128 | } 129 | if idx == 1 { 130 | line := endLine + scanner.Text() 131 | // Remove the newline character from the line 132 | line = line[0 : len(line)-1] 133 | eg.Go(func() error { 134 | cmd := exec.Command(pName, fmt.Sprintf("%v", lineNumber), line) 135 | if err := cmd.Start(); err != nil { 136 | return err 137 | } 138 | return cmd.Wait() 139 | }) 140 | lineNumber++ 141 | } 142 | // Consumers 143 | for i := 0; i < lineNumber; i++ { 144 | eg.Go(func() error { 145 | fd, err := socket.Accept() 146 | if err != nil { 147 | return err 148 | } 149 | 150 | buf := make([]byte, 1024) 151 | _, err = fd.Read(buf) 152 | if err != nil { 153 | return err 154 | } 155 | buf = bytes.Trim(buf, "\x00") 156 | var pairsArray KVPairArray 157 | err = json.Unmarshal(buf, &pairsArray) 158 | if err != nil { 159 | return err 160 | } 161 | fd.Close() 162 | 163 | for _, pair := range pairsArray.Pairs { 164 | paritionKey, err := utils.Hash(pair.Key) 165 | if err != nil { 166 | return err 167 | } 168 | paritionKey = paritionKey % int(nReducers) 169 | pairsChan <- partitionPayload{ 170 | partitionKey: paritionKey, 171 | pair: pair, 172 | } 173 | } 174 | return nil 175 | }) 176 | } 177 | var wg sync.WaitGroup 178 | wg.Add(1) 179 | go func() { 180 | for payload := range pairsChan { 181 | partitionkey := payload.partitionKey 182 | pair := payload.pair 183 | output[partitionkey] = append(output[partitionkey], pair) 184 | } 185 | wg.Done() 186 | }() 187 | if err = eg.Wait(); err != nil { 188 | return status.Error(codes.Internal, err.Error()) 189 | } 190 | close(pairsChan) 191 | wg.Wait() 192 | } 193 | m.output = output 194 | return nil 195 | } 196 | 197 | func (m *Mapper) FetchInputData(task *proto.Task) ([]*bufio.Scanner, []io.Closeable, error) { 198 | inputData := task.GetInputData() 199 | if len(inputData) == 0 { 200 | return nil, nil, status.Error(codes.InvalidArgument, "can't find input data to use for task") 201 | } 202 | m.logger.Info("Fetching the following input data: %v", inputData) 203 | creds := task.GetObjectStorageCreds() 204 | if creds == nil { 205 | return nil, nil, status.Error(codes.InvalidArgument, "can't find object storage credential infos") 206 | } 207 | 208 | scanners := make([]*bufio.Scanner, 0) 209 | closeables := make([]io.Closeable, 0) 210 | for _, fileData := range inputData { 211 | err := m.setinputFSRegistrar(fileData, creds) 212 | if err != nil { 213 | return nil, nil, err 214 | } 215 | scanner, closeable, err := m.inputFSRegistrar.GetFile(fileData) 216 | if err != nil { 217 | return nil, nil, err 218 | } 219 | scanners = append(scanners, scanner) 220 | closeables = append(closeables, closeable) 221 | } 222 | return scanners, closeables, nil 223 | } 224 | 225 | func (m *Mapper) PersistOutputData(task *proto.Task) ([]*proto.FileData, error) { 226 | taskId := task.GetId() 227 | if taskId == "" { 228 | return nil, status.Error(codes.InvalidArgument, "task id can't be empty") 229 | } 230 | 231 | var eg errgroup.Group 232 | resultingFiles := make([]*proto.FileData, len(m.output)) 233 | for partitionKey, partition := range m.output { 234 | partitionKey := partitionKey 235 | partition := partition 236 | 237 | eg.Go(func() error { 238 | jsonPartition, err := json.Marshal(&KVPairArray{ 239 | Pairs: partition, 240 | }) 241 | if err != nil { 242 | return status.Error(codes.Internal, err.Error()) 243 | } 244 | path := fmt.Sprintf("/mappers/%v_%v.json", taskId, partitionKey) 245 | m.logger.Info("Persisting partition %v data to %v", partitionKey, path) 246 | resultingFiles[partitionKey] = &proto.FileData{ 247 | Path: path, 248 | } 249 | return m.outputFSRegistrar.WriteFile(path, jsonPartition) 250 | }) 251 | } 252 | return resultingFiles, eg.Wait() 253 | } 254 | 255 | func NewMapper() *Mapper { 256 | return &Mapper{ 257 | outputFSRegistrar: io.LocalFSRegistrar{}, 258 | logger: utils.GetLogger(), 259 | } 260 | } 261 | -------------------------------------------------------------------------------- /internal/worker/reduce.go: -------------------------------------------------------------------------------- 1 | package worker 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "encoding/json" 7 | "fmt" 8 | "net" 9 | "os" 10 | "os/exec" 11 | "regexp" 12 | "sort" 13 | "strings" 14 | "time" 15 | 16 | "github.com/Assifar-Karim/apollo/internal/io" 17 | "github.com/Assifar-Karim/apollo/internal/proto" 18 | "github.com/Assifar-Karim/apollo/internal/utils" 19 | "golang.org/x/sync/errgroup" 20 | "google.golang.org/grpc/codes" 21 | "google.golang.org/grpc/status" 22 | ) 23 | 24 | type Reducer struct { 25 | inputFSRegistrar io.FSRegistrar 26 | outputFSRegistrar io.FSRegistrar 27 | idRegs []*regexp.Regexp 28 | output []KVPair 29 | logger *utils.Logger 30 | } 31 | 32 | type OrderedKVPair struct { 33 | Key KVPair `json:"key"` 34 | Value any `json:"value"` 35 | } 36 | 37 | func (r *Reducer) setOutputFSRegistrar(storageData *proto.OutputStorageInfo, credentials *proto.Credentials) error { 38 | location := storageData.GetLocation() 39 | if location == "" { 40 | return status.Error(codes.InvalidArgument, "empty storage location") 41 | } 42 | locationInfo := strings.Split(location, "/") 43 | protocol := locationInfo[0] 44 | var useSSL bool 45 | if protocol == "http:" { 46 | useSSL = false 47 | location = strings.Join(locationInfo[2:], "/") 48 | } else if protocol == "https:" { 49 | useSSL = true 50 | location = strings.Join(locationInfo[2:], "/") 51 | } else { 52 | useSSL = storageData.GetUseSSL() 53 | } 54 | outputFSRegistrar, err := io.NewS3Registrar(location, credentials.GetUsername(), credentials.GetPassword(), useSSL) 55 | if err == nil { 56 | r.outputFSRegistrar = outputFSRegistrar 57 | } 58 | return err 59 | } 60 | 61 | func fuse(scanners []*bufio.Scanner) ([]KVPair, error) { 62 | pairs := make([]KVPair, 0) 63 | for _, scanner := range scanners { 64 | buf := make([]byte, 0) 65 | for scanner.Scan() { 66 | buf = append(buf, scanner.Bytes()...) 67 | } 68 | var scannerPairsArray KVPairArray 69 | if err := json.Unmarshal(buf, &scannerPairsArray); err != nil { 70 | return nil, err 71 | } 72 | pairs = append(pairs, scannerPairsArray.Pairs...) 73 | } 74 | return pairs, nil 75 | } 76 | func shuffle(pairs []KVPair) []KVPair { 77 | keyMap := map[any][]any{} 78 | for _, pair := range pairs { 79 | _, ok := keyMap[pair.Key] 80 | if !ok { 81 | keyMap[pair.Key] = []any{pair.Value} 82 | } else { 83 | keyMap[pair.Key] = append(keyMap[pair.Key], pair.Value) 84 | } 85 | } 86 | res := make([]KVPair, 0) 87 | for k, v := range keyMap { 88 | res = append(res, KVPair{ 89 | Key: k, 90 | Value: v, 91 | }) 92 | } 93 | sort.SliceStable(res, func(i, j int) bool { 94 | a, _ := utils.Hash(res[i].Key) 95 | b, _ := utils.Hash(res[j].Key) 96 | return a < b 97 | }) 98 | return res 99 | } 100 | 101 | func (r *Reducer) HandleTask(task *proto.Task, input []*bufio.Scanner) error { 102 | program := task.GetProgram() 103 | if program == nil { 104 | return status.Error(codes.InvalidArgument, "program field can't be empty") 105 | } 106 | pName := program.GetName() 107 | if pName == "" { 108 | return status.Error(codes.InvalidArgument, "empty program name") 109 | } 110 | pContent := program.GetContent() 111 | if pContent == nil { 112 | return status.Error(codes.InvalidArgument, "empty program content") 113 | } 114 | err := os.WriteFile(pName, pContent, 0744) 115 | if err != nil { 116 | return status.Error(codes.Internal, err.Error()) 117 | } 118 | 119 | fusedPairs, err := fuse(input) 120 | if err != nil { 121 | return status.Error(codes.Internal, err.Error()) 122 | } 123 | pairs := shuffle(fusedPairs) 124 | 125 | socket, err := net.Listen("unix", "/tmp/reduce.sock") 126 | if err != nil { 127 | return status.Error(codes.Internal, err.Error()) 128 | } 129 | defer socket.Close() 130 | r.logger.Info("listening on \033[33m/tmp/reduce.sock\033[0m socket") 131 | 132 | output := make([]KVPair, len(pairs)) 133 | 134 | var producerGroup errgroup.Group 135 | producerGroup.SetLimit(50) 136 | var consumerGroup errgroup.Group 137 | consumerGroup.SetLimit(50) 138 | for idx, p := range pairs { 139 | order := idx 140 | pair := p 141 | // Producer 142 | producerGroup.Go(func() error { 143 | pair.Key = KVPair{ 144 | Key: pair.Key, 145 | Value: order, // This is used to keep track of the initial sort order 146 | } 147 | buf, err := json.Marshal(pair) 148 | if err != nil { 149 | return err 150 | } 151 | cmd := exec.Command(pName, fmt.Sprintf("%v", order)) 152 | if err = cmd.Start(); err != nil { 153 | return err 154 | } 155 | retry := 0 156 | socketLocation := fmt.Sprintf("/tmp/reduce-input-%v.sock", order) 157 | r.logger.Info("Trying to connect to %s socket", socketLocation) 158 | fd, err := net.Dial("unix", socketLocation) 159 | for err != nil && retry < 3 { 160 | r.logger.Warn("Connection attempt %v to %s failed", retry, socketLocation) 161 | fd, err = net.Dial("unix", socketLocation) 162 | retry++ 163 | time.Sleep(time.Duration(retry*5) * time.Second) 164 | } 165 | if err != nil { 166 | return status.Error(codes.Internal, err.Error()) 167 | } 168 | defer fd.Close() 169 | fd.Write(buf) 170 | return cmd.Wait() 171 | }) 172 | // Consumer 173 | consumerGroup.Go(func() error { 174 | fd, err := socket.Accept() 175 | if err != nil { 176 | return err 177 | } 178 | buf := make([]byte, 1024) 179 | _, err = fd.Read(buf) 180 | if err != nil { 181 | return err 182 | } 183 | buf = bytes.Trim(buf, "\x00") 184 | var pair OrderedKVPair 185 | err = json.Unmarshal(buf, &pair) 186 | if err != nil { 187 | return err 188 | } 189 | fd.Close() 190 | output[int(pair.Key.Value.(float64))] = KVPair{ 191 | Key: pair.Key.Key, 192 | Value: pair.Value, 193 | } 194 | 195 | return nil 196 | }) 197 | } 198 | 199 | if err = producerGroup.Wait(); err != nil { 200 | return status.Error(codes.Internal, err.Error()) 201 | } 202 | if err = consumerGroup.Wait(); err != nil { 203 | return status.Error(codes.Internal, err.Error()) 204 | } 205 | 206 | r.output = output 207 | return nil 208 | } 209 | 210 | func (r *Reducer) FetchInputData(task *proto.Task) ([]*bufio.Scanner, []io.Closeable, error) { 211 | inputData := task.GetInputData() 212 | capacity := len(inputData) 213 | if capacity == 0 { 214 | return nil, nil, status.Error(codes.InvalidArgument, "can't find input data to use for task") 215 | } 216 | r.logger.Info("Fetching the following input data: %v", inputData) 217 | r.inputFSRegistrar = io.LocalFSRegistrar{} 218 | 219 | scanners := []*bufio.Scanner{} 220 | closeables := []io.Closeable{} 221 | for _, fileData := range inputData { 222 | path := fileData.GetPath() 223 | if path == "" { 224 | return nil, nil, status.Error(codes.InvalidArgument, "empty path") 225 | } 226 | scanner, closeable, err := r.inputFSRegistrar.GetFile(fileData) 227 | if err != nil { 228 | return nil, nil, err 229 | } 230 | scanners = append(scanners, scanner) 231 | closeables = append(closeables, closeable) 232 | 233 | } 234 | return scanners, closeables, nil 235 | } 236 | 237 | func (r *Reducer) PersistOutputData(task *proto.Task) ([]*proto.FileData, error) { 238 | taskId := task.GetId() 239 | if taskId == "" { 240 | return nil, status.Error(codes.InvalidArgument, "task id can't be empty") 241 | } 242 | creds := task.GetObjectStorageCreds() 243 | if creds == nil { 244 | return nil, status.Error(codes.InvalidArgument, "can't find object storage credential info") 245 | } 246 | storageData := task.GetOutputStorageInfo() 247 | if storageData == nil { 248 | return nil, status.Error(codes.InvalidArgument, "can't find storage location info") 249 | } 250 | if err := r.setOutputFSRegistrar(storageData, creds); err != nil { 251 | return nil, status.Error(codes.Internal, err.Error()) 252 | } 253 | jobIdLoc := r.idRegs[0].FindStringIndex(taskId) 254 | reducerNumGroups := r.idRegs[1].FindStringSubmatch(taskId) 255 | rNumIdx := r.idRegs[1].SubexpIndex("reducer") 256 | if jobIdLoc == nil || reducerNumGroups == nil || rNumIdx == -1 { 257 | return nil, status.Error(codes.InvalidArgument, "task id format is wrong") 258 | } 259 | jobId := taskId[jobIdLoc[0]:jobIdLoc[1]] 260 | reducerNumber := reducerNumGroups[rNumIdx] 261 | buf, err := json.Marshal(KVPairArray{ 262 | Pairs: r.output, 263 | }) 264 | if err != nil { 265 | return nil, status.Error(codes.Internal, err.Error()) 266 | } 267 | path := fmt.Sprintf("/reducers/%v/%v.json", jobId, reducerNumber) 268 | r.logger.Info("Persisting reducer %v to %v", taskId, path) 269 | return []*proto.FileData{{Path: path}}, r.outputFSRegistrar.WriteFile(path, buf) 270 | } 271 | 272 | func NewReducer() *Reducer { 273 | return &Reducer{ 274 | idRegs: []*regexp.Regexp{ 275 | regexp.MustCompile(`j-\w{8}-\w{4}-\w{4}-\w{4}-\w{12}`), 276 | regexp.MustCompile(`(?:j-\w{8}-\w{4}-\w{4}-\w{4}-\w{12}-r-)(?P\d+)`), 277 | }, 278 | logger: utils.GetLogger(), 279 | } 280 | } 281 | -------------------------------------------------------------------------------- /internal/worker/worker.go: -------------------------------------------------------------------------------- 1 | package worker 2 | 3 | import ( 4 | "bufio" 5 | 6 | "github.com/Assifar-Karim/apollo/internal/io" 7 | "github.com/Assifar-Karim/apollo/internal/proto" 8 | ) 9 | 10 | type WorkerAlgorithm interface { 11 | FetchInputData(task *proto.Task) ([]*bufio.Scanner, []io.Closeable, error) 12 | HandleTask(task *proto.Task, input []*bufio.Scanner) error 13 | PersistOutputData(task *proto.Task) ([]*proto.FileData, error) 14 | } 15 | 16 | type Worker struct { 17 | workerAlgorithm WorkerAlgorithm 18 | } 19 | 20 | func (w *Worker) SetWorkerAlgorithm(algorithm WorkerAlgorithm) { 21 | w.workerAlgorithm = algorithm 22 | } 23 | 24 | func (w Worker) Compute(task *proto.Task) ([]*proto.FileData, error) { 25 | scanners, closeables, err := w.workerAlgorithm.FetchInputData(task) 26 | if err != nil { 27 | return nil, err 28 | } 29 | for _, closeable := range closeables { 30 | defer closeable.Close() 31 | } 32 | 33 | err = w.workerAlgorithm.HandleTask(task, scanners) 34 | if err != nil { 35 | return nil, err 36 | } 37 | resultingFiles, err := w.workerAlgorithm.PersistOutputData(task) 38 | if err != nil { 39 | return nil, err 40 | } 41 | return resultingFiles, nil 42 | } 43 | -------------------------------------------------------------------------------- /proto/msg.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | option go_package = "github.com/Assifar-Karim/apollo/internal/proto"; 3 | 4 | message Task { 5 | string id = 1; 6 | int64 type = 2; // 0: map, 1: reduce 7 | optional int64 nReducers = 3; 8 | Program program = 4; 9 | repeated FileData inputData = 5; 10 | Credentials objectStorageCreds = 6; 11 | optional OutputStorageInfo outputStorageInfo = 7; 12 | } 13 | 14 | message OutputStorageInfo { 15 | string location = 1; 16 | optional bool useSSL = 2; 17 | } 18 | 19 | message Credentials { 20 | string username = 1; 21 | string password = 2; 22 | } 23 | 24 | message FileData { 25 | string path = 1; 26 | optional int64 splitStart = 2; 27 | optional int64 splitEnd = 3; 28 | } 29 | 30 | message Program { 31 | string name = 1; 32 | bytes content = 2; 33 | } 34 | 35 | message TaskStatusInfo { 36 | string taskStatus = 1; // idle, in-progress, completed, failed 37 | repeated FileData resultingFiles = 2; // This field is mainly used for map tasks results 38 | } 39 | 40 | service TaskCreator { 41 | rpc StartTask (Task) returns (stream TaskStatusInfo); 42 | } -------------------------------------------------------------------------------- /test/coordinator/artifactmanager_test.go: -------------------------------------------------------------------------------- 1 | package coordinator 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "os" 7 | "path/filepath" 8 | "strings" 9 | "testing" 10 | 11 | "github.com/Assifar-Karim/apollo/internal/coordinator" 12 | "github.com/Assifar-Karim/apollo/internal/db" 13 | ) 14 | 15 | type artifactRepositoryMock struct { 16 | calls int 17 | } 18 | 19 | func (r *artifactRepositoryMock) CreateArtifact(name, artifactType, hash string, size int64) (db.Artifact, error) { 20 | r.calls += 1 21 | if name == "new-case" { 22 | return db.Artifact{ 23 | Name: name, 24 | Type: artifactType, 25 | Size: size, 26 | Hash: hash, 27 | }, nil 28 | } 29 | return db.Artifact{}, nil 30 | } 31 | 32 | func (r *artifactRepositoryMock) FetchArtifacts() ([]db.Artifact, error) { 33 | // do nothing 34 | return nil, nil 35 | } 36 | 37 | func (r *artifactRepositoryMock) FetchArficatByName(name string) (*db.Artifact, error) { 38 | r.calls += 1 39 | if name == "fail-case" { 40 | return nil, errors.New("custom fetch error") 41 | } 42 | if name == "new-case" { 43 | return nil, nil 44 | } 45 | if name == "exist-case" { 46 | return &db.Artifact{ 47 | Hash: "1c87d5ffba8bd8a4143f34f99beb33dfeb18031a545dc43647f21f4c4b9e99a3", 48 | }, nil 49 | } 50 | 51 | if name == "update-case" { 52 | return &db.Artifact{ 53 | Hash: "old-hash", 54 | }, nil 55 | } 56 | return nil, nil 57 | } 58 | 59 | func (r *artifactRepositoryMock) DeleteArtifact(name string) (bool, error) { 60 | // do nothing 61 | r.calls += 1 62 | return true, nil 63 | } 64 | 65 | func (r *artifactRepositoryMock) UpdateArtifact(name, hash string, size int64) (db.Artifact, error) { 66 | r.calls += 1 67 | return db.Artifact{}, nil 68 | } 69 | 70 | func TestCreateArtifactWhenArtifactDataFetchFails(t *testing.T) { 71 | // Given 72 | filename := "fail-case" 73 | reader := strings.NewReader("dummy artifact data") 74 | t.Setenv("ARTIFACTS_PATH", os.TempDir()) 75 | mockRepository := &artifactRepositoryMock{ 76 | calls: 0, 77 | } 78 | artifactManager := coordinator.NewArtifactManager(mockRepository) 79 | 80 | // When 81 | _, err := artifactManager.CreateArtifact(filename, "type", reader.Size(), reader) 82 | 83 | // Then 84 | if mockRepository.calls != 1 && err == nil { 85 | t.Errorf("CreateArtifact was expected to fail but it didn't!") 86 | } 87 | } 88 | 89 | func TestCreateArtifactWhenArtifactDoesNotExist(t *testing.T) { 90 | // Given 91 | filename := "new-case" 92 | reader := strings.NewReader("dummy artifact data") 93 | t.Setenv("ARTIFACTS_PATH", os.TempDir()) 94 | mockRepository := &artifactRepositoryMock{ 95 | calls: 0, 96 | } 97 | artifactManager := coordinator.NewArtifactManager(mockRepository) 98 | 99 | // When 100 | _, err := artifactManager.CreateArtifact(filename, "type", reader.Size(), reader) 101 | defer os.Remove(fmt.Sprintf("%s/%s", os.TempDir(), filename)) 102 | 103 | // Then 104 | if mockRepository.calls != 2 && err != nil { 105 | t.Errorf("CreateArtifact failed with unexpected error!") 106 | } 107 | } 108 | 109 | func TestCreateArtifactWhenArtifactExistsWithSameHash(t *testing.T) { 110 | // Given 111 | filename := "exist-case" 112 | reader := strings.NewReader("dummy artifact data") 113 | t.Setenv("ARTIFACTS_PATH", os.TempDir()) 114 | mockRepository := &artifactRepositoryMock{ 115 | calls: 0, 116 | } 117 | artifactManager := coordinator.NewArtifactManager(mockRepository) 118 | 119 | // When 120 | artifact, err := artifactManager.CreateArtifact(filename, "type", reader.Size(), reader) 121 | 122 | // Then 123 | if artifact.Hash != "1c87d5ffba8bd8a4143f34f99beb33dfeb18031a545dc43647f21f4c4b9e99a3" && mockRepository.calls != 1 && err != nil { 124 | t.Errorf("Expected existing artifact but method failed!") 125 | } 126 | } 127 | 128 | func TestCreateArtifactWhenArtifactExistsWithDifferentHash(t *testing.T) { 129 | // Given 130 | filename := "update-case" 131 | reader := strings.NewReader("dummy artifact data") 132 | t.Setenv("ARTIFACTS_PATH", os.TempDir()) 133 | mockRepository := &artifactRepositoryMock{ 134 | calls: 0, 135 | } 136 | artifactManager := coordinator.NewArtifactManager(mockRepository) 137 | 138 | // When 139 | _, err := artifactManager.CreateArtifact(filename, "type", reader.Size(), reader) 140 | defer os.Remove(fmt.Sprintf("%s/%s", os.TempDir(), filename)) 141 | 142 | // Then 143 | if err != nil && mockRepository.calls != 2 { 144 | t.Errorf("Expected artifact to be updated but method failed to do!") 145 | } 146 | } 147 | 148 | func TestDeleteArtifactWhenFileDoesNotExist(t *testing.T) { 149 | // Given 150 | filename := "temp_artifact.txt" 151 | file, err := os.CreateTemp("", filename) 152 | if err != nil { 153 | t.Fatalf("Couldn't create temp file %v during test initialization!", filename) 154 | } 155 | if err := os.Remove(file.Name()); err != nil { 156 | t.Fatalf("Couldn't delete randomly created temp for test!") 157 | } 158 | t.Setenv("ARTIFACTS_PATH", os.TempDir()) 159 | mockRepository := &artifactRepositoryMock{ 160 | calls: 0, 161 | } 162 | artifactManager := coordinator.NewArtifactManager(mockRepository) 163 | 164 | // When 165 | _, err = artifactManager.DeleteArtifact(file.Name()) 166 | 167 | // Then 168 | if err == nil && mockRepository.calls != 0 { 169 | t.Errorf("File was deleted even though it wasn't supposed to exist!") 170 | } 171 | } 172 | 173 | func TestDeleteArtifactWhenFileExists(t *testing.T) { 174 | // Given 175 | filename := "temp_artifact.txt" 176 | file, err := os.CreateTemp("", filename) 177 | if err != nil { 178 | t.Fatalf("Couldn't create temp file %v during test initialization!", filename) 179 | } 180 | defer os.Remove(file.Name()) 181 | t.Setenv("ARTIFACTS_PATH", os.TempDir()) 182 | mockRepository := &artifactRepositoryMock{ 183 | calls: 0, 184 | } 185 | artifactManager := coordinator.NewArtifactManager(mockRepository) 186 | 187 | // When 188 | artifactManager.DeleteArtifact(filepath.Base(file.Name())) 189 | 190 | // Then 191 | if _, err := os.Stat(file.Name()); !errors.Is(err, os.ErrNotExist) || mockRepository.calls != 1 { 192 | t.Errorf("File %s wasn't deleted by manager!", file.Name()) 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /test/db/artifactrepo_test.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "database/sql" 5 | "errors" 6 | "fmt" 7 | "os" 8 | "testing" 9 | 10 | "github.com/Assifar-Karim/apollo/internal/db" 11 | ) 12 | 13 | func setupDB() (*sql.DB, string, error) { 14 | currentDir, err := os.Getwd() 15 | if err != nil { 16 | return nil, "", err 17 | } 18 | driver := "sqlite" 19 | dbName := fmt.Sprintf("%s/test.db", currentDir) 20 | database, err := db.New(driver, dbName, true) 21 | return database, dbName, err 22 | } 23 | 24 | func TestCreateArtifact(t *testing.T) { 25 | // Given 26 | name := "name" 27 | artifactType := "artifact-type" 28 | hash := "hash" 29 | size := int64(10) 30 | expectedResult := db.Artifact{ 31 | Name: name, 32 | Type: artifactType, 33 | Size: size, 34 | Hash: hash, 35 | } 36 | database, dbName, err := setupDB() 37 | t.Cleanup(func() { os.Remove(dbName) }) 38 | if err != nil { 39 | t.Fatalf("Can't connect to database: %s", err) 40 | } 41 | artifactRepo := db.NewSQLiteArtifactRepository(database) 42 | 43 | // When 44 | result, err := artifactRepo.CreateArtifact(name, artifactType, hash, size) 45 | if err != nil { 46 | t.Fatalf("Couldn't create artifact %v", err) 47 | } 48 | 49 | // Then 50 | if expectedResult.Name != result.Name || 51 | expectedResult.Type != result.Type || 52 | expectedResult.Size != result.Size || 53 | expectedResult.Hash != result.Hash { 54 | t.Errorf("Expected %v but found %v", expectedResult, result) 55 | } 56 | row := database.QueryRow("SELECT name, type, size, hash FROM artifact WHERE name = name;") 57 | fetchedArtifact := db.Artifact{} 58 | err = row.Scan(&fetchedArtifact.Name, &fetchedArtifact.Type, &fetchedArtifact.Size, &fetchedArtifact.Hash) 59 | if errors.Is(err, sql.ErrNoRows) { 60 | t.Errorf("Expected %v to be saved on db but it wasn't!", expectedResult) 61 | } 62 | if expectedResult.Name != fetchedArtifact.Name || 63 | expectedResult.Type != fetchedArtifact.Type || 64 | expectedResult.Size != fetchedArtifact.Size || 65 | expectedResult.Hash != fetchedArtifact.Hash { 66 | t.Errorf("Expected %v but found %v", expectedResult, fetchedArtifact) 67 | } 68 | } 69 | 70 | func TestFetchArtifactsWhenNoArtifacts(t *testing.T) { 71 | // Given 72 | database, dbName, err := setupDB() 73 | t.Cleanup(func() { os.Remove(dbName) }) 74 | if err != nil { 75 | t.Fatalf("Can't connect to database: %s", err) 76 | } 77 | artifactRepo := db.NewSQLiteArtifactRepository(database) 78 | 79 | // When 80 | artifacts, err := artifactRepo.FetchArtifacts() 81 | if err != nil { 82 | t.Fatalf("Couldn't fetch from the db %v", err) 83 | } 84 | 85 | // Then 86 | if len(artifacts) != 0 { 87 | t.Errorf("Expected to find no artifact but found %v artifacts", len(artifacts)) 88 | } 89 | } 90 | 91 | func TestFetchArtifactsWhenArtifactsExist(t *testing.T) { 92 | database, dbName, err := setupDB() 93 | t.Cleanup(func() { os.Remove(dbName) }) 94 | if err != nil { 95 | t.Fatalf("Can't connect to database: %s", err) 96 | } 97 | artifactRepo := db.NewSQLiteArtifactRepository(database) 98 | artifact, err := artifactRepo.CreateArtifact("name", "artifact-type", "hash", 10) 99 | if err != nil { 100 | t.Fatalf("Couldn't create artifact for logic testing! %v", err) 101 | } 102 | 103 | // When 104 | artifacts, err := artifactRepo.FetchArtifacts() 105 | if err != nil { 106 | t.Fatalf("Couldn't fetch from the db %v", err) 107 | } 108 | 109 | // Then 110 | if len(artifacts) != 1 && (artifact.Name != artifacts[0].Name || 111 | artifact.Type != artifacts[0].Type || 112 | artifact.Hash != artifacts[0].Hash || 113 | artifact.Size != artifacts[0].Size) { 114 | t.Errorf("Expected to find artifact %v but found %v", artifact, artifacts[0]) 115 | } 116 | } 117 | 118 | func TestFetchArtifactByNameWhenArtifactDoesNotExist(t *testing.T) { 119 | // Given 120 | database, dbName, err := setupDB() 121 | t.Cleanup(func() { os.Remove(dbName) }) 122 | if err != nil { 123 | t.Fatalf("Can't connect to database: %s", err) 124 | } 125 | artifactRepo := db.NewSQLiteArtifactRepository(database) 126 | 127 | // When 128 | artifact, err := artifactRepo.FetchArficatByName("name") 129 | 130 | // Then 131 | if artifact != nil && err != nil { 132 | t.Error("Expected to find no artifact by found one!") 133 | } 134 | } 135 | 136 | func TestFetchArtifactByNameWhenArtifactExists(t *testing.T) { 137 | // Given 138 | database, dbName, err := setupDB() 139 | t.Cleanup(func() { os.Remove(dbName) }) 140 | if err != nil { 141 | t.Fatalf("Can't connect to database: %s", err) 142 | } 143 | artifactRepo := db.NewSQLiteArtifactRepository(database) 144 | artifact, err := artifactRepo.CreateArtifact("name", "artifact-type", "hash", 10) 145 | if err != nil { 146 | t.Fatalf("Couldn't create artifact for logic testing! %v", err) 147 | } 148 | 149 | // When 150 | result, err := artifactRepo.FetchArficatByName("name") 151 | if err != nil { 152 | t.Fatalf("Couldn't fetch from the db %v", err) 153 | } 154 | 155 | // Then 156 | if artifact.Name != result.Name || 157 | artifact.Type != result.Type || 158 | artifact.Hash != result.Hash || 159 | artifact.Size != result.Size { 160 | t.Errorf("Expected to find artifact %v but found %v", artifact, result) 161 | } 162 | } 163 | 164 | func TestDeleteArtifactWhenArtifactDoesNotExist(t *testing.T) { 165 | // Given 166 | database, dbName, err := setupDB() 167 | t.Cleanup(func() { os.Remove(dbName) }) 168 | if err != nil { 169 | t.Fatalf("Can't connect to database: %s", err) 170 | } 171 | artifactRepo := db.NewSQLiteArtifactRepository(database) 172 | 173 | // When 174 | isDeleted, err := artifactRepo.DeleteArtifact("name") 175 | if err != nil { 176 | t.Fatalf("The delete operation didn't work %v", err) 177 | } 178 | // Then 179 | if isDeleted { 180 | t.Error("Expected no record to be deleted!") 181 | } 182 | } 183 | 184 | func TestDeleteArtifactWhenArtifactExists(t *testing.T) { 185 | // Given 186 | database, dbName, err := setupDB() 187 | t.Cleanup(func() { os.Remove(dbName) }) 188 | if err != nil { 189 | t.Fatalf("Can't connect to database: %s", err) 190 | } 191 | artifactRepo := db.NewSQLiteArtifactRepository(database) 192 | _, err = artifactRepo.CreateArtifact("name", "artifact-type", "hash", 10) 193 | if err != nil { 194 | t.Fatalf("Couldn't create artifact for logic testing! %v", err) 195 | } 196 | 197 | // When 198 | isDeleted, err := artifactRepo.DeleteArtifact("name") 199 | if err != nil { 200 | t.Fatalf("The delete operation didn't work %v", err) 201 | } 202 | 203 | // Then 204 | if !isDeleted { 205 | t.Error("Expected record to be deleted but no record was deleted!") 206 | } 207 | } 208 | 209 | func TestUpdateArtifactWhenArtifactDoesNotExist(t *testing.T) { 210 | // Given 211 | database, dbName, err := setupDB() 212 | t.Cleanup(func() { os.Remove(dbName) }) 213 | if err != nil { 214 | t.Fatalf("Can't connect to database: %s", err) 215 | } 216 | artifactRepo := db.NewSQLiteArtifactRepository(database) 217 | 218 | // When 219 | artifact, err := artifactRepo.UpdateArtifact("name", "hash", 10) 220 | 221 | // Then 222 | if !errors.Is(err, sql.ErrNoRows) { 223 | t.Errorf("Expected to update no artifact but one was!: %v", artifact) 224 | } 225 | } 226 | 227 | func TestUpdateArtifactWhenArtifactExists(t *testing.T) { 228 | // Given 229 | database, dbName, err := setupDB() 230 | t.Cleanup(func() { os.Remove(dbName) }) 231 | if err != nil { 232 | t.Fatalf("Can't connect to database: %s", err) 233 | } 234 | artifactRepo := db.NewSQLiteArtifactRepository(database) 235 | _, err = artifactRepo.CreateArtifact("name", "artifact-type", "hash", 10) 236 | if err != nil { 237 | t.Fatalf("Couldn't create artifact for logic testing! %v", err) 238 | } 239 | 240 | // When 241 | artifact, err := artifactRepo.UpdateArtifact("name", "new-hash", 15) 242 | if err != nil { 243 | t.Fatalf("The update operation didn't work %v", err) 244 | } 245 | 246 | // Then 247 | if artifact.Hash != "new-hash" || artifact.Size != 15 { 248 | t.Fatalf("Expected artifact data to be updated but it wasn't! %v", artifact) 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /test/db/db_test.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "slices" 7 | "strings" 8 | "testing" 9 | 10 | "github.com/Assifar-Karim/apollo/internal/db" 11 | _ "modernc.org/sqlite" 12 | ) 13 | 14 | func TestSQLiteDBEagerLoad(t *testing.T) { 15 | // Given 16 | currentDir, err := os.Getwd() 17 | if err != nil { 18 | t.Fatal(err) 19 | } 20 | driver := "sqlite" 21 | dbName := fmt.Sprintf("%s/test.db", currentDir) 22 | 23 | queries := make([]string, 5) 24 | 25 | queries[0] = `CREATE TABLE output_location ( 26 | location VARCHAR PRIMARY KEY NOT NULL, 27 | use_SSL BOOLEAN NOT NULL)` 28 | 29 | queries[1] = `CREATE TABLE input_data ( 30 | id INTEGER PRIMARY KEY NOT NULL, 31 | path VARCHAR NOT NULL, 32 | type VARCHAR NOT NULL, 33 | split_start INTEGER, 34 | split_end INTEGER)` 35 | 36 | queries[2] = `CREATE TABLE job ( 37 | id VARCHAR PRIMARY KEY NOT NULL, 38 | n_reducers INTEGER NOT NULL, 39 | output_path VARCHAR NOT NULL, 40 | input_id INTEGER NOT NULL, 41 | start_time DATETIME NOT NULL, 42 | end_time DATETIME, 43 | FOREIGN KEY(input_id) REFERENCES input_data(id), 44 | FOREIGN KEY(output_path) REFERENCES output_location(location))` 45 | 46 | queries[3] = `CREATE TABLE artifact ( 47 | name VARCHAR PRIMARY KEY NOT NULL, 48 | type VARCHAR NOT NULL DEFAULT executable, 49 | size INTEGER NOT NULL DEFAULT 0, 50 | hash VARCHAR NOT NULL)` 51 | 52 | queries[4] = `CREATE TABLE task ( 53 | id VARCHAR PRIMARY KEY NOT NULL, 54 | job_id VARCHAR NOT NULL, 55 | type VARCHAR NOT NULL, 56 | status VARCHAR NOT NULL DEFAULT scheduled, 57 | program_name VARCHAR NOT NULL, 58 | input_data_id INTEGER, 59 | pod_name VARCHAR, 60 | start_time DATETIME NOT NULL, 61 | end_time DATETIME, 62 | FOREIGN KEY(job_id) REFERENCES job(id), 63 | FOREIGN KEY(input_data_id) REFERENCES input_data(id), 64 | FOREIGN KEY(program_name) REFERENCES artifact(name))` 65 | slices.Sort(queries) 66 | 67 | // When 68 | database, err := db.New(driver, dbName, true) 69 | if err != nil { 70 | t.Fatalf("Can't connect to database: %s", err) 71 | } 72 | defer os.Remove(dbName) 73 | 74 | // Then 75 | rows, err := database.Query("SELECT DISTINCT sql FROM SQLITE_MASTER;") 76 | if err != nil { 77 | t.Fatal(err) 78 | } 79 | defer rows.Close() 80 | fetchedQueries := []string{} 81 | for rows.Next() { 82 | fetchedQuery := "" 83 | rows.Scan(&fetchedQuery) 84 | if strings.TrimSpace(fetchedQuery) != "" { 85 | fetchedQueries = append(fetchedQueries, fetchedQuery) 86 | } 87 | } 88 | slices.Sort(fetchedQueries) 89 | for i := 0; i < 4; i++ { 90 | if queries[i] != fetchedQueries[i] { 91 | t.Errorf("Expected %s but found %s", queries[i], fetchedQueries[i]) 92 | } 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /test/db/jobrepo_test.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | "time" 7 | 8 | "github.com/Assifar-Karim/apollo/internal/db" 9 | ) 10 | 11 | func TestCreateJob(t *testing.T) { 12 | // Given 13 | nReducers := 1 14 | startTime := time.Now().UTC().UnixMilli() 15 | id := "id" 16 | inputPath := "input-path" 17 | inputType := "input-type" 18 | outputPath := "output-path" 19 | useSSL := false 20 | 21 | expectedJob := db.Job{ 22 | Id: id, 23 | NReducers: nReducers, 24 | OutputLocation: db.OutputLocation{ 25 | Location: outputPath, 26 | UseSSL: useSSL, 27 | }, 28 | InputData: db.InputData{ 29 | Id: 1, 30 | Path: inputPath, 31 | Type: inputType, 32 | }, 33 | StartTime: startTime, 34 | } 35 | database, dbName, err := setupDB() 36 | t.Cleanup(func() { os.Remove(dbName) }) 37 | if err != nil { 38 | t.Fatalf("Can't connect to database: %s", err) 39 | } 40 | jobRepo := db.NewSQLiteJobsRepository(database) 41 | 42 | // When 43 | job, err := jobRepo.CreateJob(nReducers, startTime, id, inputPath, inputType, outputPath, useSSL) 44 | if err != nil { 45 | t.Fatalf("The job creation operation failed! %v", err) 46 | } 47 | 48 | // Then 49 | if job.Id != expectedJob.Id || 50 | job.NReducers != expectedJob.NReducers || 51 | job.StartTime != expectedJob.StartTime || 52 | job.OutputLocation.Location != expectedJob.OutputLocation.Location || 53 | job.OutputLocation.UseSSL != expectedJob.OutputLocation.UseSSL || 54 | job.InputData.Id != expectedJob.InputData.Id || 55 | job.InputData.Path != expectedJob.InputData.Path || 56 | job.InputData.Type != expectedJob.InputData.Type { 57 | t.Errorf("Expected %v but found %v!", expectedJob, job) 58 | } 59 | } 60 | 61 | func TestFetchJobsWhenNoJobExists(t *testing.T) { 62 | // Given 63 | database, dbName, err := setupDB() 64 | t.Cleanup(func() { os.Remove(dbName) }) 65 | if err != nil { 66 | t.Fatalf("Can't connect to database: %s", err) 67 | } 68 | jobRepo := db.NewSQLiteJobsRepository(database) 69 | 70 | // When 71 | jobs, err := jobRepo.FetchJobs() 72 | if err != nil { 73 | t.Fatalf("The job fetch operation failed! %v", err) 74 | } 75 | 76 | // Then 77 | if len(jobs) != 0 { 78 | t.Errorf("Expected to find no jobs but found %v", jobs) 79 | } 80 | } 81 | 82 | func TestFetchJobsWhenJobsExist(t *testing.T) { 83 | // Given 84 | database, dbName, err := setupDB() 85 | t.Cleanup(func() { os.Remove(dbName) }) 86 | if err != nil { 87 | t.Fatalf("Can't connect to database: %s", err) 88 | } 89 | jobRepo := db.NewSQLiteJobsRepository(database) 90 | job, err := jobRepo.CreateJob(1, time.Now().UnixMilli(), "id", "input-path", "input-type", "output-path", false) 91 | if err != nil { 92 | t.Fatal("Couldn't populate db with job for test logic!") 93 | } 94 | 95 | // When 96 | jobs, err := jobRepo.FetchJobs() 97 | if err != nil { 98 | t.Fatalf("The job fetch operation failed! %v", err) 99 | } 100 | 101 | // Then 102 | if len(jobs) != 1 && (job.Id != jobs[0].Id || 103 | job.NReducers != jobs[0].NReducers || 104 | job.StartTime != jobs[0].StartTime || 105 | job.OutputLocation.Location != jobs[0].OutputLocation.Location || 106 | job.OutputLocation.UseSSL != jobs[0].OutputLocation.UseSSL || 107 | job.InputData.Id != jobs[0].InputData.Id || 108 | job.InputData.Path != jobs[0].InputData.Path || 109 | job.InputData.Type != jobs[0].InputData.Type) { 110 | t.Errorf("Expected to find 1 job but found %v", jobs) 111 | } 112 | } 113 | 114 | func TestFetchJobByIDWhenJobDoesNotExist(t *testing.T) { 115 | // Given 116 | database, dbName, err := setupDB() 117 | t.Cleanup(func() { os.Remove(dbName) }) 118 | if err != nil { 119 | t.Fatalf("Can't connect to database: %s", err) 120 | } 121 | jobRepo := db.NewSQLiteJobsRepository(database) 122 | 123 | // When 124 | job, err := jobRepo.FetchJobByID("id") 125 | 126 | // Then 127 | if job != nil || err != nil { 128 | t.Errorf("Expected to find no job but found %v, %v", job, err) 129 | } 130 | } 131 | 132 | func TestFetchJobByIDWhenJobExists(t *testing.T) { 133 | // Given 134 | database, dbName, err := setupDB() 135 | t.Cleanup(func() { os.Remove(dbName) }) 136 | if err != nil { 137 | t.Fatalf("Can't connect to database: %s", err) 138 | } 139 | jobRepo := db.NewSQLiteJobsRepository(database) 140 | job, err := jobRepo.CreateJob(1, time.Now().UnixMilli(), "id", "input-path", "input-type", "output-path", false) 141 | if err != nil { 142 | t.Fatal("Couldn't populate db with job for test logic!") 143 | } 144 | 145 | // When 146 | fetchedJob, err := jobRepo.FetchJobByID(job.Id) 147 | if err != nil { 148 | t.Fatalf("The job fetch operation failed! %v", err) 149 | } 150 | 151 | // Then 152 | if job.Id != fetchedJob.Id || 153 | job.NReducers != fetchedJob.NReducers || 154 | job.StartTime != fetchedJob.StartTime || 155 | job.OutputLocation.Location != fetchedJob.OutputLocation.Location || 156 | job.OutputLocation.UseSSL != fetchedJob.OutputLocation.UseSSL || 157 | job.InputData.Id != fetchedJob.InputData.Id || 158 | job.InputData.Path != fetchedJob.InputData.Path || 159 | job.InputData.Type != fetchedJob.InputData.Type { 160 | t.Errorf("Expected to find %v but found %v", job, fetchedJob) 161 | } 162 | } 163 | 164 | func TestUpdateJobEndTimeByIDWhenJobExists(t *testing.T) { 165 | // Given 166 | id := "id" 167 | endTs := time.Now().UnixMilli() 168 | 169 | database, dbName, err := setupDB() 170 | t.Cleanup(func() { os.Remove(dbName) }) 171 | if err != nil { 172 | t.Fatalf("Can't connect to database: %s", err) 173 | } 174 | jobRepo := db.NewSQLiteJobsRepository(database) 175 | _, err = jobRepo.CreateJob(1, time.Now().UnixMilli(), id, "input-path", "input-type", "output-path", false) 176 | if err != nil { 177 | t.Fatal("Couldn't populate db with job for test logic!") 178 | } 179 | 180 | // When 181 | if err := jobRepo.UpdateJobEndTimeByID(id, endTs); err != nil { 182 | t.Fatalf("Update operation failed! %v", err) 183 | } 184 | 185 | // Then 186 | fetchedEndTs := int64(0) 187 | row := database.QueryRow("SELECT end_time FROM job WHERE id = id;") 188 | if err := row.Scan(&fetchedEndTs); err != nil { 189 | t.Fatalf("Data fetching operation failed for verification failed! %v", err) 190 | } 191 | if fetchedEndTs != endTs { 192 | t.Errorf("Expected %v but found %v", endTs, fetchedEndTs) 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /test/utils/data/crlf_corpus_1.txt: -------------------------------------------------------------------------------- 1 | Line 1 2 | Line 2 3 | -------------------------------------------------------------------------------- /test/utils/data/crlf_corpus_2.txt: -------------------------------------------------------------------------------- 1 | Line 1 2 | Lin -------------------------------------------------------------------------------- /test/utils/data/lf_corpus_1.txt: -------------------------------------------------------------------------------- 1 | Line 1 2 | Line 2 3 | -------------------------------------------------------------------------------- /test/utils/data/lf_corpus_2.txt: -------------------------------------------------------------------------------- 1 | Line 1 2 | Lin -------------------------------------------------------------------------------- /test/utils/scanner_test.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bufio" 5 | "os" 6 | "testing" 7 | 8 | "github.com/Assifar-Karim/apollo/internal/utils" 9 | ) 10 | 11 | func readFile(path string) (*bufio.Reader, error) { 12 | file, err := os.Open(path) 13 | if err != nil { 14 | return nil, err 15 | } 16 | return bufio.NewReader(file), nil 17 | } 18 | 19 | func TestModifiedScannerWithCRLFCorpusAndFullLines(t *testing.T) { 20 | // Given 21 | path := "data/crlf_corpus_1.txt" 22 | reader, err := readFile(path) 23 | if err != nil { 24 | t.Errorf("Couldn't read file %s -> %v", path, err) 25 | } 26 | scanner := utils.NewScanner(reader) 27 | expectedResult := "Line 1\nLine 2\n" 28 | 29 | // When 30 | res := "" 31 | for scanner.Scan() { 32 | res += scanner.Text() 33 | } 34 | 35 | // Then 36 | if res != expectedResult { 37 | t.Errorf("Expected %s but found %s", expectedResult, res) 38 | } 39 | } 40 | 41 | func TestModifiedScannerWithCRLFCorpusAndIncompleteLines(t *testing.T) { 42 | // Given 43 | path := "data/crlf_corpus_2.txt" 44 | reader, err := readFile(path) 45 | if err != nil { 46 | t.Errorf("Couldn't read file %s -> %v", path, err) 47 | } 48 | scanner := utils.NewScanner(reader) 49 | expectedResult := "Line 1\nLin" 50 | 51 | // When 52 | res := "" 53 | for scanner.Scan() { 54 | res += scanner.Text() 55 | } 56 | 57 | // Then 58 | if res != expectedResult { 59 | t.Errorf("Expected %s but found %s", expectedResult, res) 60 | } 61 | } 62 | 63 | func TestModifiedScannerWithLFCorpusAndFullLines(t *testing.T) { 64 | // Given 65 | path := "data/lf_corpus_1.txt" 66 | reader, err := readFile(path) 67 | if err != nil { 68 | t.Errorf("Couldn't read file %s -> %v", path, err) 69 | } 70 | scanner := utils.NewScanner(reader) 71 | expectedResult := "Line 1\nLine 2\n" 72 | 73 | // When 74 | res := "" 75 | for scanner.Scan() { 76 | res += scanner.Text() 77 | } 78 | 79 | // Then 80 | if res != expectedResult { 81 | t.Errorf("Expected %s but found %s", expectedResult, res) 82 | } 83 | } 84 | 85 | func TestModifiedScannerWithLFCorpusAndIncompleteLines(t *testing.T) { 86 | // Given 87 | path := "data/lf_corpus_2.txt" 88 | reader, err := readFile(path) 89 | if err != nil { 90 | t.Errorf("Couldn't read file %s -> %v", path, err) 91 | } 92 | scanner := utils.NewScanner(reader) 93 | expectedResult := "Line 1\nLin" 94 | 95 | // When 96 | res := "" 97 | for scanner.Scan() { 98 | res += scanner.Text() 99 | } 100 | 101 | // Then 102 | if res != expectedResult { 103 | t.Errorf("Expected %s but found %s", expectedResult, res) 104 | } 105 | } 106 | --------------------------------------------------------------------------------