3 |
4 |
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