Commit a1d8136e authored by Matthew Slipper's avatar Matthew Slipper

go/stackman: Add stackman operator

Converts Stackman into a Kube operator by adding the following:

- The basic Operator scaffolding. Things like RBAC, the manifests for the Operator itself, etc.
- CRDs for the DTL, Sequencer, Gas Oracle, Clique L1, batch submitter, deployer, and actors.

To see how the CRDs get used, see the nightly env in the stacks repo: https://github.com/ethereum-optimism/stacks/tree/master/nightly

Metadata:

- Fixes ENG-1673
parent a21cec6d
# More info: https://docs.docker.com/engine/reference/builder/#dockerignore-file
# Ignore build and test binaries.
bin/
testbin/
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
bin
testbin/*
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Kubernetes Generated files - skip generated files, except for vendored files
!vendor/**/zz_generated.*
# editor and IDE paraphernalia
.idea
*.swp
*.swo
*~
# Build the manager binary
FROM golang:1.16 as builder
WORKDIR /workspace
# Copy the Go Modules manifests
COPY go.mod go.mod
COPY go.sum go.sum
# cache deps before building and copying source so that we don't need to re-download as much
# and so that source changes don't invalidate our downloaded layer
RUN go mod download
# Copy the go source
COPY main.go main.go
COPY api/ api/
COPY controllers/ controllers/
# Build
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -o manager main.go
# Use distroless as minimal base image to package the manager binary
# Refer to https://github.com/GoogleContainerTools/distroless for more details
FROM gcr.io/distroless/static:nonroot
WORKDIR /
COPY --from=builder /workspace/manager .
USER 65532:65532
ENTRYPOINT ["/manager"]
# VERSION defines the project version for the bundle.
# Update this value when you upgrade the version of your project.
# To re-generate a bundle for another specific version without changing the standard setup, you can:
# - use the VERSION as arg of the bundle target (e.g make bundle VERSION=0.0.2)
# - use environment variables to overwrite this value (e.g export VERSION=0.0.2)
VERSION ?= 0.0.1
# CHANNELS define the bundle channels used in the bundle.
# Add a new line here if you would like to change its default config. (E.g CHANNELS = "candidate,fast,stable")
# To re-generate a bundle for other specific channels without changing the standard setup, you can:
# - use the CHANNELS as arg of the bundle target (e.g make bundle CHANNELS=candidate,fast,stable)
# - use environment variables to overwrite this value (e.g export CHANNELS="candidate,fast,stable")
ifneq ($(origin CHANNELS), undefined)
BUNDLE_CHANNELS := --channels=$(CHANNELS)
endif
# DEFAULT_CHANNEL defines the default channel used in the bundle.
# Add a new line here if you would like to change its default config. (E.g DEFAULT_CHANNEL = "stable")
# To re-generate a bundle for any other default channel without changing the default setup, you can:
# - use the DEFAULT_CHANNEL as arg of the bundle target (e.g make bundle DEFAULT_CHANNEL=stable)
# - use environment variables to overwrite this value (e.g export DEFAULT_CHANNEL="stable")
ifneq ($(origin DEFAULT_CHANNEL), undefined)
BUNDLE_DEFAULT_CHANNEL := --default-channel=$(DEFAULT_CHANNEL)
endif
BUNDLE_METADATA_OPTS ?= $(BUNDLE_CHANNELS) $(BUNDLE_DEFAULT_CHANNEL)
# IMAGE_TAG_BASE defines the docker.io namespace and part of the image name for remote images.
# This variable is used to construct full image tags for bundle and catalog images.
#
# For example, running 'make bundle-build bundle-push catalog-build catalog-push' will build and push both
# optimism-stacks.net/stackman-bundle:$VERSION and optimism-stacks.net/stackman-catalog:$VERSION.
IMAGE_TAG_BASE ?= optimism-stacks.net/stackman
# BUNDLE_IMG defines the image:tag used for the bundle.
# You can use it as an arg. (E.g make bundle-build BUNDLE_IMG=<some-registry>/<project-name-bundle>:<tag>)
BUNDLE_IMG ?= $(IMAGE_TAG_BASE)-bundle:v$(VERSION)
# Image URL to use all building/pushing image targets
IMG ?= ethereumoptimism/stackman-controller:latest
# ENVTEST_K8S_VERSION refers to the version of kubebuilder assets to be downloaded by envtest binary.
ENVTEST_K8S_VERSION = 1.22
# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set)
ifeq (,$(shell go env GOBIN))
GOBIN=$(shell go env GOPATH)/bin
else
GOBIN=$(shell go env GOBIN)
endif
# Setting SHELL to bash allows bash commands to be executed by recipes.
# This is a requirement for 'setup-envtest.sh' in the test target.
# Options are set to exit when a recipe line exits non-zero or a piped command fails.
SHELL = /usr/bin/env bash -o pipefail
.SHELLFLAGS = -ec
all: build
##@ General
# The help target prints out all targets with their descriptions organized
# beneath their categories. The categories are represented by '##@' and the
# target descriptions by '##'. The awk commands is responsible for reading the
# entire set of makefiles included in this invocation, looking for lines of the
# file as xyz: ## something, and then pretty-format the target and help. Then,
# if there's a line with ##@ something, that gets pretty-printed as a category.
# More info on the usage of ANSI control characters for terminal formatting:
# https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters
# More info on the awk command:
# http://linuxcommand.org/lc3_adv_awk.php
help: ## Display this help.
@awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m<target>\033[0m\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST)
##@ Development
manifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and CustomResourceDefinition objects.
$(CONTROLLER_GEN) rbac:roleName=manager-role crd webhook paths="./..." output:crd:artifacts:config=config/crd/bases
generate: controller-gen ## Generate code containing DeepCopy, DeepCopyInto, and DeepCopyObject method implementations.
$(CONTROLLER_GEN) object:headerFile="hack/boilerplate.go.txt" paths="./..."
fmt: ## Run go fmt against code.
go fmt ./...
vet: ## Run go vet against code.
go vet ./...
test: manifests generate fmt vet envtest ## Run tests.
KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) -p path)" go test ./... -coverprofile cover.out
##@ Build
build: generate fmt vet ## Build manager binary.
go build -o bin/manager main.go
run: manifests generate fmt vet ## Run a controller from your host.
go run ./main.go
docker-build: test ## Build docker image with the manager.
docker build -t ${IMG} .
docker-push: ## Push docker image with the manager.
docker push ${IMG}
##@ Deployment
install: manifests kustomize ## Install CRDs into the K8s cluster specified in ~/.kube/config.
$(KUSTOMIZE) build config/crd | kubectl apply -f -
uninstall: manifests kustomize ## Uninstall CRDs from the K8s cluster specified in ~/.kube/config.
$(KUSTOMIZE) build config/crd | kubectl delete -f -
deploy: manifests kustomize ## Deploy controller to the K8s cluster specified in ~/.kube/config.
cd config/manager && $(KUSTOMIZE) edit set image controller=${IMG}
$(KUSTOMIZE) build config/default | kubectl apply -f -
undeploy: ## Undeploy controller from the K8s cluster specified in ~/.kube/config.
$(KUSTOMIZE) build config/default | kubectl delete -f -
CONTROLLER_GEN = $(shell pwd)/bin/controller-gen
controller-gen: ## Download controller-gen locally if necessary.
$(call go-get-tool,$(CONTROLLER_GEN),sigs.k8s.io/controller-tools/cmd/controller-gen@v0.7.0)
KUSTOMIZE = $(shell pwd)/bin/kustomize
kustomize: ## Download kustomize locally if necessary.
$(call go-get-tool,$(KUSTOMIZE),sigs.k8s.io/kustomize/kustomize/v3@v3.8.7)
ENVTEST = $(shell pwd)/bin/setup-envtest
envtest: ## Download envtest-setup locally if necessary.
$(call go-get-tool,$(ENVTEST),sigs.k8s.io/controller-runtime/tools/setup-envtest@latest)
# go-get-tool will 'go get' any package $2 and install it to $1.
PROJECT_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST))))
define go-get-tool
@[ -f $(1) ] || { \
set -e ;\
TMP_DIR=$$(mktemp -d) ;\
cd $$TMP_DIR ;\
go mod init tmp ;\
echo "Downloading $(2)" ;\
GOBIN=$(PROJECT_DIR)/bin go get $(2) ;\
rm -rf $$TMP_DIR ;\
}
endef
.PHONY: bundle
bundle: manifests kustomize ## Generate bundle manifests and metadata, then validate generated files.
operator-sdk generate kustomize manifests -q
cd config/manager && $(KUSTOMIZE) edit set image controller=$(IMG)
$(KUSTOMIZE) build config/manifests | operator-sdk generate bundle -q --overwrite --version $(VERSION) $(BUNDLE_METADATA_OPTS)
operator-sdk bundle validate ./bundle
.PHONY: bundle-build
bundle-build: ## Build the bundle image.
docker build -f bundle.Dockerfile -t $(BUNDLE_IMG) .
.PHONY: bundle-push
bundle-push: ## Push the bundle image.
$(MAKE) docker-push IMG=$(BUNDLE_IMG)
.PHONY: opm
OPM = ./bin/opm
opm: ## Download opm locally if necessary.
ifeq (,$(wildcard $(OPM)))
ifeq (,$(shell which opm 2>/dev/null))
@{ \
set -e ;\
mkdir -p $(dir $(OPM)) ;\
OS=$(shell go env GOOS) && ARCH=$(shell go env GOARCH) && \
curl -sSLo $(OPM) https://github.com/operator-framework/operator-registry/releases/download/v1.15.1/$${OS}-$${ARCH}-opm ;\
chmod +x $(OPM) ;\
}
else
OPM = $(shell which opm)
endif
endif
# A comma-separated list of bundle images (e.g. make catalog-build BUNDLE_IMGS=example.com/operator-bundle:v0.1.0,example.com/operator-bundle:v0.2.0).
# These images MUST exist in a registry and be pull-able.
BUNDLE_IMGS ?= $(BUNDLE_IMG)
# The image tag given to the resulting catalog image (e.g. make catalog-build CATALOG_IMG=example.com/operator-catalog:v0.2.0).
CATALOG_IMG ?= $(IMAGE_TAG_BASE)-catalog:v$(VERSION)
# Set CATALOG_BASE_IMG to an existing catalog image tag to add $BUNDLE_IMGS to that image.
ifneq ($(origin CATALOG_BASE_IMG), undefined)
FROM_INDEX_OPT := --from-index $(CATALOG_BASE_IMG)
endif
# Build a catalog image by adding bundle images to an empty catalog using the operator package manager tool, 'opm'.
# This recipe invokes 'opm' in 'semver' bundle add mode. For more information on add modes, see:
# https://github.com/operator-framework/community-operators/blob/7f1438c/docs/packaging-operator.md#updating-your-existing-operator
.PHONY: catalog-build
catalog-build: opm ## Build a catalog image.
$(OPM) index add --container-tool docker --mode semver --tag $(CATALOG_IMG) --bundles $(BUNDLE_IMGS) $(FROM_INDEX_OPT)
# Push the catalog image.
.PHONY: catalog-push
catalog-push: ## Push a catalog image.
$(MAKE) docker-push IMG=$(CATALOG_IMG)
domain: optimism-stacks.net
layout:
- go.kubebuilder.io/v3
plugins:
manifests.sdk.operatorframework.io/v2: {}
scorecard.sdk.operatorframework.io/v2: {}
projectName: stackman
repo: github.com/ethereum-optimism/optimism/go/stackman
resources:
- api:
crdVersion: v1
namespaced: true
controller: true
domain: optimism-stacks.net
group: stack
kind: CliqueL1
path: github.com/ethereum-optimism/optimism/go/stackman/api/v1
version: v1
- api:
crdVersion: v1
namespaced: true
controller: true
domain: optimism-stacks.net
group: stack
kind: Deployer
path: github.com/ethereum-optimism/optimism/go/stackman/api/v1
version: v1
- api:
crdVersion: v1
namespaced: true
controller: true
domain: optimism-stacks.net
group: stack
kind: DataTransportLayer
path: github.com/ethereum-optimism/optimism/go/stackman/api/v1
version: v1
- api:
crdVersion: v1
namespaced: true
controller: true
domain: optimism-stacks.net
group: stack
kind: Sequencer
path: github.com/ethereum-optimism/optimism/go/stackman/api/v1
version: v1
- api:
crdVersion: v1
namespaced: true
controller: true
domain: optimism-stacks.net
group: stack
kind: BatchSubmitter
path: github.com/ethereum-optimism/optimism/go/stackman/api/v1
version: v1
- api:
crdVersion: v1
namespaced: true
controller: true
domain: optimism-stacks.net
group: stack
kind: GasOracle
path: github.com/ethereum-optimism/optimism/go/stackman/api/v1
version: v1
- api:
crdVersion: v1
namespaced: true
controller: true
domain: optimism-stacks.net
group: stack
kind: Actor
path: github.com/ethereum-optimism/optimism/go/stackman/api/v1
version: v1
version: "3"
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// ActorSpec defines the desired state of Actor
type ActorSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
Image string `json:"image,omitempty"`
L1URL string `json:"l1_url"`
L2URL string `json:"l2_url"`
PrivateKey *Valuer `json:"private_key,omitempty"`
AddressManagerAddress string `json:"address_manager_address"`
TestFilename string `json:"test_filename,omitempty"`
Concurrency int `json:"concurrency,omitempty"`
RunForMS int `json:"run_for_ms,omitempty"`
RunCount int `json:"run_count,omitempty"`
ThinkTimeMS int `json:"think_time_ms,omitempty"`
Env []corev1.EnvVar `json:"env,omitempty"`
}
// ActorStatus defines the observed state of Actor
type ActorStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
}
//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
// Actor is the Schema for the actors API
type Actor struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec ActorSpec `json:"spec,omitempty"`
Status ActorStatus `json:"status,omitempty"`
}
//+kubebuilder:object:root=true
// ActorList contains a list of Actor
type ActorList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Actor `json:"items"`
}
func init() {
SchemeBuilder.Register(&Actor{}, &ActorList{})
}
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// BatchSubmitterSpec defines the desired state of BatchSubmitter
type BatchSubmitterSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
Image string `json:"image,omitempty"`
L1URL string `json:"l1_url,omitempty"`
L1TimeoutSeconds int `json:"l1_timeout_seconds,omitempty"`
L2URL string `json:"l2_url,omitempty"`
L2TimeoutSeconds int `json:"l2_timeout_seconds,omitempty"`
DeployerURL string `json:"deployer_url,omitempty"`
DeployerTimeoutSeconds int `json:"deployer_timeout_seconds,omitempty"`
Env []corev1.EnvVar `json:"env,omitempty"`
}
// BatchSubmitterStatus defines the observed state of BatchSubmitter
type BatchSubmitterStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
}
//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
// BatchSubmitter is the Schema for the batchsubmitters API
type BatchSubmitter struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec BatchSubmitterSpec `json:"spec,omitempty"`
Status BatchSubmitterStatus `json:"status,omitempty"`
}
//+kubebuilder:object:root=true
// BatchSubmitterList contains a list of BatchSubmitter
type BatchSubmitterList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []BatchSubmitter `json:"items"`
}
func init() {
SchemeBuilder.Register(&BatchSubmitter{}, &BatchSubmitterList{})
}
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// CliqueL1Spec defines the desired state of CliqueL1
type CliqueL1Spec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
Image string `json:"image,omitempty"`
GenesisFile *Valuer `json:"genesis_file,omitempty"`
SealerPrivateKey *Valuer `json:"sealer_private_key"`
SealerAddress string `json:"sealer_address,omitempty"`
ChainID int `json:"chain_id,omitempty"`
DataPVC *PVCConfig `json:"data_pvc,omitempty"`
AdditionalArgs []string `json:"additional_args,omitempty"`
}
// CliqueL1Status defines the observed state of CliqueL1
type CliqueL1Status struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
}
//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
// CliqueL1 is the Schema for the cliquel1s API
type CliqueL1 struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec CliqueL1Spec `json:"spec,omitempty"`
Status CliqueL1Status `json:"status,omitempty"`
}
//+kubebuilder:object:root=true
// CliqueL1List contains a list of CliqueL1
type CliqueL1List struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []CliqueL1 `json:"items"`
}
func init() {
SchemeBuilder.Register(&CliqueL1{}, &CliqueL1List{})
}
package v1
import (
"gopkg.in/yaml.v2"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
)
type Valuer struct {
Value string `json:"value,omitempty"`
ValueFrom *corev1.EnvVarSource `json:"value_from,omitempty"`
}
func (v *Valuer) String() string {
out, err := yaml.Marshal(v)
if err != nil {
panic(err)
}
return string(out)
}
func (v *Valuer) EnvVar(name string) corev1.EnvVar {
return corev1.EnvVar{
Name: name,
Value: v.Value,
ValueFrom: v.ValueFrom,
}
}
type PVCConfig struct {
Name string `json:"name"`
Storage *resource.Quantity `json:"storage,omitempty"`
}
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// DataTransportLayerSpec defines the desired state of DataTransportLayer
type DataTransportLayerSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
Image string `json:"image,omitempty"`
L1URL string `json:"l1_url,omitempty"`
L1TimeoutSeconds int `json:"l1_timeout_seconds,omitempty"`
DeployerURL string `json:"deployer_url,omitempty"`
DeployerTimeoutSeconds int `json:"deployer_timeout_seconds,omitempty"`
DataPVC *PVCConfig `json:"data_pvc,omitempty"`
Env []v1.EnvVar `json:"env,omitempty"`
}
// DataTransportLayerStatus defines the observed state of DataTransportLayer
type DataTransportLayerStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
}
//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
// DataTransportLayer is the Schema for the datatransportlayers API
type DataTransportLayer struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec DataTransportLayerSpec `json:"spec,omitempty"`
Status DataTransportLayerStatus `json:"status,omitempty"`
}
//+kubebuilder:object:root=true
// DataTransportLayerList contains a list of DataTransportLayer
type DataTransportLayerList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []DataTransportLayer `json:"items"`
}
func init() {
SchemeBuilder.Register(&DataTransportLayer{}, &DataTransportLayerList{})
}
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// DeployerSpec defines the desired state of Deployer
type DeployerSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
Image string `json:"image,omitempty"`
L1URL string `json:"l1_url,omitempty"`
L1TimeoutSeconds int `json:"l1_timeout_seconds,omitempty"`
Env []corev1.EnvVar `json:"env,omitempty"`
}
// DeployerStatus defines the observed state of Deployer
type DeployerStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
}
//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
// Deployer is the Schema for the deployers API
type Deployer struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec DeployerSpec `json:"spec,omitempty"`
Status DeployerStatus `json:"status,omitempty"`
}
//+kubebuilder:object:root=true
// DeployerList contains a list of Deployer
type DeployerList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Deployer `json:"items"`
}
func init() {
SchemeBuilder.Register(&Deployer{}, &DeployerList{})
}
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// GasOracleSpec defines the desired state of GasOracle
type GasOracleSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
Image string `json:"image,omitempty"`
L1URL string `json:"l1_url,omitempty"`
L1TimeoutSeconds int `json:"l1_timeout_seconds,omitempty"`
L2URL string `json:"l2_url,omitempty"`
L2TimeoutSeconds int `json:"l2_timeout_seconds,omitempty"`
Env []v1.EnvVar `json:"env,omitempty"`
}
// GasOracleStatus defines the observed state of GasOracle
type GasOracleStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
}
//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
// GasOracle is the Schema for the gasoracles API
type GasOracle struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec GasOracleSpec `json:"spec,omitempty"`
Status GasOracleStatus `json:"status,omitempty"`
}
//+kubebuilder:object:root=true
// GasOracleList contains a list of GasOracle
type GasOracleList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []GasOracle `json:"items"`
}
func init() {
SchemeBuilder.Register(&GasOracle{}, &GasOracleList{})
}
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package v1 contains API Schema definitions for the stack v1 API group
//+kubebuilder:object:generate=true
//+groupName=stack.optimism-stacks.net
package v1
import (
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/scheme"
)
var (
// GroupVersion is group version used to register these objects
GroupVersion = schema.GroupVersion{Group: "stack.optimism-stacks.net", Version: "v1"}
// SchemeBuilder is used to add go types to the GroupVersionKind scheme
SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion}
// AddToScheme adds the types in this group-version to the given scheme.
AddToScheme = SchemeBuilder.AddToScheme
)
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// SequencerSpec defines the desired state of Sequencer
type SequencerSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
Image string `json:"image,omitempty"`
L1URL string `json:"l1_url,omitempty"`
L1TimeoutSeconds int `json:"l1_timeout_seconds,omitempty"`
DeployerURL string `json:"deployer_url,omitempty"`
DeployerTimeoutSeconds int `json:"deployer_timeout_seconds,omitempty"`
DTLURL string `json:"dtl_url,omitempty"`
DTLTimeoutSeconds int `json:"dtl_timeout_seconds,omitempty"`
DataPVC *PVCConfig `json:"data_pvc,omitempty"`
Env []corev1.EnvVar `json:"env,omitempty"`
AdditionalArgs []string `json:"additional_args,omitempty"`
}
// SequencerStatus defines the observed state of Sequencer
type SequencerStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
}
//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
// Sequencer is the Schema for the sequencers API
type Sequencer struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec SequencerSpec `json:"spec,omitempty"`
Status SequencerStatus `json:"status,omitempty"`
}
//+kubebuilder:object:root=true
// SequencerList contains a list of Sequencer
type SequencerList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Sequencer `json:"items"`
}
func init() {
SchemeBuilder.Register(&Sequencer{}, &SequencerList{})
}
This diff is collapsed.
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
controller-gen.kubebuilder.io/version: v0.7.0
creationTimestamp: null
name: cliquel1s.stack.optimism-stacks.net
spec:
group: stack.optimism-stacks.net
names:
kind: CliqueL1
listKind: CliqueL1List
plural: cliquel1s
singular: cliquel1
scope: Namespaced
versions:
- name: v1
schema:
openAPIV3Schema:
description: CliqueL1 is the Schema for the cliquel1s API
properties:
apiVersion:
description: 'APIVersion defines the versioned schema of this representation
of an object. Servers should convert recognized schemas to the latest
internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources'
type: string
kind:
description: 'Kind is a string value representing the REST resource this
object represents. Servers may infer this from the endpoint the client
submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
type: string
metadata:
type: object
spec:
description: CliqueL1Spec defines the desired state of CliqueL1
type: object
status:
description: CliqueL1Status defines the observed state of CliqueL1
properties:
pod_names:
items:
type: string
type: array
required:
- pod_names
type: object
type: object
served: true
storage: true
subresources:
status: {}
status:
acceptedNames:
kind: ""
plural: ""
conditions: []
storedVersions: []
# This kustomization.yaml is not intended to be run by itself,
# since it depends on service name and namespace that are out of this kustomize package.
# It should be run by config/default
resources:
- bases/stack.optimism-stacks.net_cliquel1s.yaml
- bases/stack.optimism-stacks.net_deployers.yaml
- bases/stack.optimism-stacks.net_datatransportlayers.yaml
- bases/stack.optimism-stacks.net_sequencers.yaml
- bases/stack.optimism-stacks.net_batchsubmitters.yaml
- bases/stack.optimism-stacks.net_gasoracles.yaml
- bases/stack.optimism-stacks.net_actors.yaml
#+kubebuilder:scaffold:crdkustomizeresource
patchesStrategicMerge:
# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix.
# patches here are for enabling the conversion webhook for each CRD
#- patches/webhook_in_cliquel1s.yaml
#- patches/webhook_in_deployers.yaml
#- patches/webhook_in_datatransportlayers.yaml
#- patches/webhook_in_sequencers.yaml
#- patches/webhook_in_batchsubmitters.yaml
#- patches/webhook_in_gasoracles.yaml
#- patches/webhook_in_actors.yaml
#+kubebuilder:scaffold:crdkustomizewebhookpatch
# [CERTMANAGER] To enable cert-manager, uncomment all the sections with [CERTMANAGER] prefix.
# patches here are for enabling the CA injection for each CRD
#- patches/cainjection_in_cliquel1s.yaml
#- patches/cainjection_in_deployers.yaml
#- patches/cainjection_in_datatransportlayers.yaml
#- patches/cainjection_in_sequencers.yaml
#- patches/cainjection_in_batchsubmitters.yaml
#- patches/cainjection_in_gasoracles.yaml
#- patches/cainjection_in_actors.yaml
#+kubebuilder:scaffold:crdkustomizecainjectionpatch
# the following config is for teaching kustomize how to do kustomization for CRDs.
configurations:
- kustomizeconfig.yaml
# This file is for teaching kustomize how to substitute name and namespace reference in CRD
nameReference:
- kind: Service
version: v1
fieldSpecs:
- kind: CustomResourceDefinition
version: v1
group: apiextensions.k8s.io
path: spec/conversion/webhook/clientConfig/service/name
namespace:
- kind: CustomResourceDefinition
version: v1
group: apiextensions.k8s.io
path: spec/conversion/webhook/clientConfig/service/namespace
create: false
varReference:
- path: metadata/annotations
# The following patch adds a directive for certmanager to inject CA into the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME)
name: actors.stack.optimism-stacks.net
# The following patch adds a directive for certmanager to inject CA into the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME)
name: batchsubmitters.stack.optimism-stacks.net
# The following patch adds a directive for certmanager to inject CA into the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME)
name: cliquel1s.stack.optimism-stacks.net
# The following patch adds a directive for certmanager to inject CA into the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME)
name: datatransportlayers.stack.optimism-stacks.net
# The following patch adds a directive for certmanager to inject CA into the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME)
name: deployers.stack.optimism-stacks.net
# The following patch adds a directive for certmanager to inject CA into the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME)
name: gasoracles.stack.optimism-stacks.net
# The following patch adds a directive for certmanager to inject CA into the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME)
name: sequencers.stack.optimism-stacks.net
# The following patch enables a conversion webhook for the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: actors.stack.optimism-stacks.net
spec:
conversion:
strategy: Webhook
webhook:
clientConfig:
service:
namespace: system
name: webhook-service
path: /convert
conversionReviewVersions:
- v1
# The following patch enables a conversion webhook for the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: batchsubmitters.stack.optimism-stacks.net
spec:
conversion:
strategy: Webhook
webhook:
clientConfig:
service:
namespace: system
name: webhook-service
path: /convert
conversionReviewVersions:
- v1
# The following patch enables a conversion webhook for the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: cliquel1s.stack.optimism-stacks.net
spec:
conversion:
strategy: Webhook
webhook:
clientConfig:
service:
namespace: system
name: webhook-service
path: /convert
conversionReviewVersions:
- v1
# The following patch enables a conversion webhook for the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: datatransportlayers.stack.optimism-stacks.net
spec:
conversion:
strategy: Webhook
webhook:
clientConfig:
service:
namespace: system
name: webhook-service
path: /convert
conversionReviewVersions:
- v1
# The following patch enables a conversion webhook for the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: deployers.stack.optimism-stacks.net
spec:
conversion:
strategy: Webhook
webhook:
clientConfig:
service:
namespace: system
name: webhook-service
path: /convert
conversionReviewVersions:
- v1
# The following patch enables a conversion webhook for the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: gasoracles.stack.optimism-stacks.net
spec:
conversion:
strategy: Webhook
webhook:
clientConfig:
service:
namespace: system
name: webhook-service
path: /convert
conversionReviewVersions:
- v1
# The following patch enables a conversion webhook for the CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: sequencers.stack.optimism-stacks.net
spec:
conversion:
strategy: Webhook
webhook:
clientConfig:
service:
namespace: system
name: webhook-service
path: /convert
conversionReviewVersions:
- v1
# Adds namespace to all resources.
namespace: stackman-system
# Value of this field is prepended to the
# names of all resources, e.g. a deployment named
# "wordpress" becomes "alices-wordpress".
# Note that it should also match with the prefix (text before '-') of the namespace
# field above.
namePrefix: stackman-
# Labels to add to all resources and selectors.
#commonLabels:
# someName: someValue
bases:
- ../crd
- ../rbac
- ../manager
# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in
# crd/kustomization.yaml
#- ../webhook
# [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER'. 'WEBHOOK' components are required.
#- ../certmanager
# [PROMETHEUS] To enable prometheus monitor, uncomment all sections with 'PROMETHEUS'.
- ../prometheus
#patchesStrategicMerge:
# Protect the /metrics endpoint by putting it behind auth.
# If you want your controller-manager to expose the /metrics
# endpoint w/o any authn/z, please comment the following line.
#- manager_auth_proxy_patch.yaml
# Mount the controller config file for loading manager configurations
# through a ComponentConfig type
#- manager_config_patch.yaml
# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in
# crd/kustomization.yaml
#- manager_webhook_patch.yaml
# [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER'.
# Uncomment 'CERTMANAGER' sections in crd/kustomization.yaml to enable the CA injection in the admission webhooks.
# 'CERTMANAGER' needs to be enabled to use ca injection
#- webhookcainjection_patch.yaml
# the following config is for teaching kustomize how to do var substitution
vars:
# [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER' prefix.
#- name: CERTIFICATE_NAMESPACE # namespace of the certificate CR
# objref:
# kind: Certificate
# group: cert-manager.io
# version: v1
# name: serving-cert # this name should match the one in certificate.yaml
# fieldref:
# fieldpath: metadata.namespace
#- name: CERTIFICATE_NAME
# objref:
# kind: Certificate
# group: cert-manager.io
# version: v1
# name: serving-cert # this name should match the one in certificate.yaml
#- name: SERVICE_NAMESPACE # namespace of the service
# objref:
# kind: Service
# version: v1
# name: webhook-service
# fieldref:
# fieldpath: metadata.namespace
#- name: SERVICE_NAME
# objref:
# kind: Service
# version: v1
# name: webhook-service
# This patch inject a sidecar container which is a HTTP proxy for the
# controller manager, it performs RBAC authorization against the Kubernetes API using SubjectAccessReviews.
apiVersion: apps/v1
kind: Deployment
metadata:
name: controller-manager
namespace: system
spec:
template:
spec:
containers:
- name: kube-rbac-proxy
image: gcr.io/kubebuilder/kube-rbac-proxy:v0.8.0
args:
- "--secure-listen-address=0.0.0.0:8443"
- "--upstream=http://127.0.0.1:8080/"
- "--logtostderr=true"
- "--v=10"
ports:
- containerPort: 8443
protocol: TCP
name: https
- name: manager
args:
- "--health-probe-bind-address=:8081"
- "--metrics-bind-address=127.0.0.1:8080"
- "--leader-elect"
apiVersion: apps/v1
kind: Deployment
metadata:
name: controller-manager
namespace: system
spec:
template:
spec:
containers:
- name: manager
args:
- "--config=controller_manager_config.yaml"
volumeMounts:
- name: manager-config
mountPath: /controller_manager_config.yaml
subPath: controller_manager_config.yaml
volumes:
- name: manager-config
configMap:
name: manager-config
apiVersion: controller-runtime.sigs.k8s.io/v1alpha1
kind: ControllerManagerConfig
health:
healthProbeBindAddress: :8081
metrics:
bindAddress: 127.0.0.1:8080
webhook:
port: 9443
leaderElection:
leaderElect: true
resourceName: 8103f40b.optimism-stacks.net
resources:
- manager.yaml
generatorOptions:
disableNameSuffixHash: true
configMapGenerator:
- files:
- controller_manager_config.yaml
name: manager-config
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
images:
- name: controller
newName: controller
newTag: latest
apiVersion: v1
kind: Namespace
metadata:
labels:
control-plane: controller-manager
name: system
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: controller-manager
namespace: system
labels:
control-plane: controller-manager
spec:
selector:
matchLabels:
control-plane: controller-manager
replicas: 1
template:
metadata:
labels:
control-plane: controller-manager
spec:
securityContext:
runAsNonRoot: true
containers:
- command:
- /manager
args:
- --leader-elect
image: controller:latest
name: manager
securityContext:
allowPrivilegeEscalation: false
livenessProbe:
httpGet:
path: /healthz
port: 8081
initialDelaySeconds: 15
periodSeconds: 20
readinessProbe:
httpGet:
path: /readyz
port: 8081
initialDelaySeconds: 5
periodSeconds: 10
resources:
limits:
cpu: 200m
memory: 100Mi
requests:
cpu: 100m
memory: 20Mi
serviceAccountName: controller-manager
terminationGracePeriodSeconds: 10
# These resources constitute the fully configured set of manifests
# used to generate the 'manifests/' directory in a bundle.
resources:
- bases/stackman.clusterserviceversion.yaml
- ../default
- ../samples
- ../scorecard
# [WEBHOOK] To enable webhooks, uncomment all the sections with [WEBHOOK] prefix.
# Do NOT uncomment sections with prefix [CERTMANAGER], as OLM does not support cert-manager.
# These patches remove the unnecessary "cert" volume and its manager container volumeMount.
#patchesJson6902:
#- target:
# group: apps
# version: v1
# kind: Deployment
# name: controller-manager
# namespace: system
# patch: |-
# # Remove the manager container's "cert" volumeMount, since OLM will create and mount a set of certs.
# # Update the indices in this path if adding or removing containers/volumeMounts in the manager's Deployment.
# - op: remove
# path: /spec/template/spec/containers/1/volumeMounts/0
# # Remove the "cert" volume, since OLM will create and mount a set of certs.
# # Update the indices in this path if adding or removing volumes in the manager's Deployment.
# - op: remove
# path: /spec/template/spec/volumes/0
# Prometheus Monitor Service (Metrics)
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
labels:
control-plane: controller-manager
name: controller-manager-metrics-monitor
namespace: system
spec:
endpoints:
- path: /metrics
port: https
scheme: https
bearerTokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token
tlsConfig:
insecureSkipVerify: true
selector:
matchLabels:
control-plane: controller-manager
# permissions for end users to edit actors.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: actor-editor-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- actors
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- actors/status
verbs:
- get
# permissions for end users to view actors.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: actor-viewer-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- actors
verbs:
- get
- list
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- actors/status
verbs:
- get
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: metrics-reader
rules:
- nonResourceURLs:
- "/metrics"
verbs:
- get
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: proxy-role
rules:
- apiGroups:
- authentication.k8s.io
resources:
- tokenreviews
verbs:
- create
- apiGroups:
- authorization.k8s.io
resources:
- subjectaccessreviews
verbs:
- create
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: proxy-rolebinding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: proxy-role
subjects:
- kind: ServiceAccount
name: controller-manager
namespace: system
apiVersion: v1
kind: Service
metadata:
labels:
control-plane: controller-manager
name: controller-manager-metrics-service
namespace: system
spec:
ports:
- name: https
port: 8443
protocol: TCP
targetPort: https
selector:
control-plane: controller-manager
# permissions for end users to edit batchsubmitters.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: batchsubmitter-editor-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- batchsubmitters
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- batchsubmitters/status
verbs:
- get
# permissions for end users to view batchsubmitters.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: batchsubmitter-viewer-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- batchsubmitters
verbs:
- get
- list
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- batchsubmitters/status
verbs:
- get
# permissions for end users to edit cliquel1s.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: cliquel1-editor-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- cliquel1s
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- cliquel1s/status
verbs:
- get
# permissions for end users to view cliquel1s.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: cliquel1-viewer-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- cliquel1s
verbs:
- get
- list
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- cliquel1s/status
verbs:
- get
# permissions for end users to edit datatransportlayers.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: datatransportlayer-editor-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- datatransportlayers
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- datatransportlayers/status
verbs:
- get
# permissions for end users to view datatransportlayers.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: datatransportlayer-viewer-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- datatransportlayers
verbs:
- get
- list
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- datatransportlayers/status
verbs:
- get
# permissions for end users to edit deployers.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: deployer-editor-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- deployers
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- deployers/status
verbs:
- get
# permissions for end users to view deployers.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: deployer-viewer-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- deployers
verbs:
- get
- list
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- deployers/status
verbs:
- get
# permissions for end users to edit gasoracles.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: gasoracle-editor-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- gasoracles
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- gasoracles/status
verbs:
- get
# permissions for end users to view gasoracles.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: gasoracle-viewer-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- gasoracles
verbs:
- get
- list
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- gasoracles/status
verbs:
- get
resources:
# All RBAC will be applied under this service account in
# the deployment namespace. You may comment out this resource
# if your manager will use a service account that exists at
# runtime. Be sure to update RoleBinding and ClusterRoleBinding
# subjects if changing service account names.
- service_account.yaml
- role.yaml
- role_binding.yaml
- leader_election_role.yaml
- leader_election_role_binding.yaml
# Comment the following 4 lines if you want to disable
# the auth proxy (https://github.com/brancz/kube-rbac-proxy)
# which protects your /metrics endpoint.
- auth_proxy_service.yaml
- auth_proxy_role.yaml
- auth_proxy_role_binding.yaml
- auth_proxy_client_clusterrole.yaml
# permissions to do leader election.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: leader-election-role
rules:
- apiGroups:
- ""
resources:
- configmaps
verbs:
- get
- list
- watch
- create
- update
- patch
- delete
- apiGroups:
- coordination.k8s.io
resources:
- leases
verbs:
- get
- list
- watch
- create
- update
- patch
- delete
- apiGroups:
- ""
resources:
- events
verbs:
- create
- patch
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: leader-election-rolebinding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: leader-election-role
subjects:
- kind: ServiceAccount
name: controller-manager
namespace: system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
creationTimestamp: null
name: manager-role
rules:
- apiGroups:
- apps
resources:
- deployments
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- ""
resources:
- configmaps
- pods
- services
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- cliquel1s
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- cliquel1s/finalizers
verbs:
- update
- apiGroups:
- stack.optimism-stacks.net
resources:
- cliquel1s/status
verbs:
- get
- patch
- update
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: manager-rolebinding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: manager-role
subjects:
- kind: ServiceAccount
name: controller-manager
namespace: system
# permissions for end users to edit sequencers.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: sequencer-editor-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- sequencers
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- sequencers/status
verbs:
- get
# permissions for end users to view sequencers.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: sequencer-viewer-role
rules:
- apiGroups:
- stack.optimism-stacks.net
resources:
- sequencers
verbs:
- get
- list
- watch
- apiGroups:
- stack.optimism-stacks.net
resources:
- sequencers/status
verbs:
- get
apiVersion: v1
kind: ServiceAccount
metadata:
name: controller-manager
namespace: system
## Append samples you want in your CSV to this file as resources ##
resources:
- stack_v1_cliquel1.yaml
- stack_v1_deployer.yaml
- stack_v1_datatransportlayer.yaml
- stack_v1_sequencer.yaml
- stack_v1_batchsubmitter.yaml
- stack_v1_gasoracle.yaml
- stack_v1_actor.yaml
#+kubebuilder:scaffold:manifestskustomizesamples
apiVersion: stack.optimism-stacks.net/v1
kind: Actor
metadata:
name: actor-sample
spec:
# Add fields here
apiVersion: stack.optimism-stacks.net/v1
kind: BatchSubmitter
metadata:
name: batchsubmitter-sample
spec:
# Add fields here
apiVersion: stack.optimism-stacks.net/v1
kind: CliqueL1
metadata:
name: cliquel1-sample
spec:
# Add fields here
apiVersion: stack.optimism-stacks.net/v1
kind: DataTransportLayer
metadata:
name: datatransportlayer-sample
spec:
# Add fields here
apiVersion: stack.optimism-stacks.net/v1
kind: Deployer
metadata:
name: deployer-sample
spec:
# Add fields here
apiVersion: stack.optimism-stacks.net/v1
kind: GasOracle
metadata:
name: gasoracle-sample
spec:
# Add fields here
apiVersion: stack.optimism-stacks.net/v1
kind: Sequencer
metadata:
name: sequencer-sample
spec:
# Add fields here
apiVersion: scorecard.operatorframework.io/v1alpha3
kind: Configuration
metadata:
name: config
stages:
- parallel: true
tests: []
resources:
- bases/config.yaml
patchesJson6902:
- path: patches/basic.config.yaml
target:
group: scorecard.operatorframework.io
version: v1alpha3
kind: Configuration
name: config
- path: patches/olm.config.yaml
target:
group: scorecard.operatorframework.io
version: v1alpha3
kind: Configuration
name: config
#+kubebuilder:scaffold:patchesJson6902
- op: add
path: /stages/0/tests/-
value:
entrypoint:
- scorecard-test
- basic-check-spec
image: quay.io/operator-framework/scorecard-test:v1.15.0
labels:
suite: basic
test: basic-check-spec-test
- op: add
path: /stages/0/tests/-
value:
entrypoint:
- scorecard-test
- olm-bundle-validation
image: quay.io/operator-framework/scorecard-test:v1.15.0
labels:
suite: olm
test: olm-bundle-validation-test
- op: add
path: /stages/0/tests/-
value:
entrypoint:
- scorecard-test
- olm-crds-have-validation
image: quay.io/operator-framework/scorecard-test:v1.15.0
labels:
suite: olm
test: olm-crds-have-validation-test
- op: add
path: /stages/0/tests/-
value:
entrypoint:
- scorecard-test
- olm-crds-have-resources
image: quay.io/operator-framework/scorecard-test:v1.15.0
labels:
suite: olm
test: olm-crds-have-resources-test
- op: add
path: /stages/0/tests/-
value:
entrypoint:
- scorecard-test
- olm-spec-descriptors
image: quay.io/operator-framework/scorecard-test:v1.15.0
labels:
suite: olm
test: olm-spec-descriptors-test
- op: add
path: /stages/0/tests/-
value:
entrypoint:
- scorecard-test
- olm-status-descriptors
image: quay.io/operator-framework/scorecard-test:v1.15.0
labels:
suite: olm
test: olm-status-descriptors-test
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"crypto/md5"
"encoding/hex"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"strconv"
"time"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
stackv1 "github.com/ethereum-optimism/optimism/go/stackman/api/v1"
)
// ActorReconciler reconciles a Actor object
type ActorReconciler struct {
client.Client
Scheme *runtime.Scheme
}
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=actors,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=actors/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=actors/finalizers,verbs=update
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the Actor object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile
func (r *ActorReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
lgr := log.FromContext(ctx)
crd := &stackv1.Actor{}
if err := r.Get(ctx, req.NamespacedName, crd); err != nil {
if errors.IsNotFound(err) {
lgr.Info("actor resource not found, ignoring")
return ctrl.Result{}, nil
}
lgr.Error(err, "error getting actor")
return ctrl.Result{}, err
}
deployment := &appsv1.Deployment{}
created, err := GetOrCreateResource(ctx, r, func() client.Object {
return r.deployment(crd)
}, ObjectNamespacedName(crd.ObjectMeta, "actor"), deployment)
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
argsHash := r.argsHash(crd)
if deployment.Labels["args_hash"] != argsHash {
err := r.Update(ctx, r.deployment(crd))
if err != nil {
lgr.Error(err, "error updating actor deployment")
return ctrl.Result{}, err
}
return ctrl.Result{RequeueAfter: 10 * time.Second}, nil
}
created, err = GetOrCreateResource(ctx, r, func() client.Object {
return r.service(crd)
}, ObjectNamespacedName(crd.ObjectMeta, "actor"), &corev1.Service{})
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
return ctrl.Result{}, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *ActorReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&stackv1.Actor{}).
Complete(r)
}
func (r *ActorReconciler) labels(crd *stackv1.Actor) map[string]string {
return map[string]string{
"actor": crd.ObjectMeta.Name,
}
}
func (r *ActorReconciler) argsHash(crd *stackv1.Actor) string {
h := md5.New()
h.Write([]byte(crd.Spec.Image))
h.Write([]byte(crd.Spec.L1URL))
h.Write([]byte(crd.Spec.L2URL))
h.Write([]byte(crd.Spec.PrivateKey.String()))
h.Write([]byte(crd.Spec.AddressManagerAddress))
h.Write([]byte(crd.Spec.TestFilename))
h.Write([]byte(strconv.Itoa(crd.Spec.Concurrency)))
h.Write([]byte(strconv.Itoa(crd.Spec.RunForMS)))
h.Write([]byte(strconv.Itoa(crd.Spec.RunCount)))
h.Write([]byte(strconv.Itoa(crd.Spec.ThinkTimeMS)))
return hex.EncodeToString(h.Sum(nil))
}
func (r *ActorReconciler) deployment(crd *stackv1.Actor) *appsv1.Deployment {
replicas := int32(1)
command := []string{
"yarn",
"test:actor",
"-f",
crd.Spec.TestFilename,
"-c",
strconv.Itoa(crd.Spec.Concurrency),
"--serve",
}
if crd.Spec.RunForMS != 0 {
command = append(command, "-t")
command = append(command, strconv.Itoa(crd.Spec.RunForMS))
} else if crd.Spec.RunCount != 0 {
command = append(command, "-r")
command = append(command, strconv.Itoa(crd.Spec.RunCount))
}
if crd.Spec.ThinkTimeMS != 0 {
command = append(command, "--think-time")
command = append(command, strconv.Itoa(crd.Spec.ThinkTimeMS))
}
env := append([]corev1.EnvVar{
crd.Spec.PrivateKey.EnvVar("PRIVATE_KEY"),
{
Name: "L1_URL",
Value: crd.Spec.L1URL,
},
{
Name: "L2_URL",
Value: crd.Spec.L2URL,
},
{
Name: "IS_LIVE_NETWORK",
Value: "true",
},
{
Name: "ADDRESS_MANAGER",
Value: crd.Spec.AddressManagerAddress,
},
}, crd.Spec.Env...)
deployment := &appsv1.Deployment{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "actor", map[string]string{
"args_hash": r.argsHash(crd),
"actor": crd.ObjectMeta.Name,
}),
Spec: appsv1.DeploymentSpec{
Replicas: &replicas,
Selector: &metav1.LabelSelector{
MatchLabels: r.labels(crd),
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: r.labels(crd),
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyAlways,
Containers: []corev1.Container{
{
Name: "actor",
Image: crd.Spec.Image,
ImagePullPolicy: corev1.PullAlways,
WorkingDir: "/opt/optimism/integration-tests",
Command: command,
Env: env,
Ports: []corev1.ContainerPort{
{
Name: "metrics",
ContainerPort: 8545,
},
},
},
},
},
},
},
}
ctrl.SetControllerReference(crd, deployment, r.Scheme)
return deployment
}
func (r *ActorReconciler) service(crd *stackv1.Actor) *corev1.Service {
service := &corev1.Service{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "actor", r.labels(crd)),
Spec: corev1.ServiceSpec{
Selector: r.labels(crd),
Type: corev1.ServiceTypeClusterIP,
Ports: []corev1.ServicePort{
{
Name: "metrics",
Port: 8545,
},
},
},
}
ctrl.SetControllerReference(crd, service, r.Scheme)
return service
}
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"crypto/md5"
"encoding/hex"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"strconv"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
stackv1 "github.com/ethereum-optimism/optimism/go/stackman/api/v1"
)
// BatchSubmitterReconciler reconciles a BatchSubmitter object
type BatchSubmitterReconciler struct {
client.Client
Scheme *runtime.Scheme
}
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=batchsubmitters,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=batchsubmitters/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=batchsubmitters/finalizers,verbs=update
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the BatchSubmitter object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile
func (r *BatchSubmitterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
lgr := log.FromContext(ctx)
crd := &stackv1.BatchSubmitter{}
if err := r.Get(ctx, req.NamespacedName, crd); err != nil {
if errors.IsNotFound(err) {
lgr.Info("batch submitter resource not found, ignoring")
return ctrl.Result{}, nil
}
lgr.Error(err, "error getting batch submitter")
return ctrl.Result{}, err
}
created, err := GetOrCreateResource(ctx, r, func() client.Object {
return r.entrypointsCfgMap(crd)
}, ObjectNamespacedName(crd.ObjectMeta, "batch-submitter-entrypoints"), &corev1.ConfigMap{})
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
statefulSet := &appsv1.StatefulSet{}
created, err = GetOrCreateResource(ctx, r, func() client.Object {
return r.statefulSet(crd)
}, ObjectNamespacedName(crd.ObjectMeta, "batch-submitter"), statefulSet)
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
argsHash := r.statefulSetArgsHash(crd)
if statefulSet.Labels["args_hash"] != argsHash {
err := r.Update(ctx, r.statefulSet(crd))
if err != nil {
lgr.Error(err, "error updating batch submitter statefulSet")
return ctrl.Result{}, err
}
return ctrl.Result{Requeue: true}, nil
}
created, err = GetOrCreateResource(ctx, r, func() client.Object {
return r.service(crd)
}, ObjectNamespacedName(crd.ObjectMeta, "batch-submitter"), &corev1.Service{})
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
return ctrl.Result{}, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *BatchSubmitterReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&stackv1.BatchSubmitter{}).
Complete(r)
}
func (r *BatchSubmitterReconciler) labels() map[string]string {
return map[string]string{
"app": "batch-submitter",
}
}
func (r *BatchSubmitterReconciler) entrypointsCfgMap(crd *stackv1.BatchSubmitter) *corev1.ConfigMap {
cfgMap := &corev1.ConfigMap{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "batch-submitter-entrypoints", r.labels()),
Data: map[string]string{
"entrypoint.sh": BatchSubmitterEntrypoint,
},
}
ctrl.SetControllerReference(crd, cfgMap, r.Scheme)
return cfgMap
}
func (r *BatchSubmitterReconciler) statefulSetArgsHash(crd *stackv1.BatchSubmitter) string {
h := md5.New()
h.Write([]byte(crd.Spec.Image))
h.Write([]byte(crd.Spec.L1URL))
h.Write([]byte(strconv.Itoa(crd.Spec.L1TimeoutSeconds)))
h.Write([]byte(crd.Spec.L2URL))
h.Write([]byte(strconv.Itoa(crd.Spec.L2TimeoutSeconds)))
h.Write([]byte(crd.Spec.DeployerURL))
h.Write([]byte(strconv.Itoa(crd.Spec.DeployerTimeoutSeconds)))
for _, ev := range crd.Spec.Env {
h.Write([]byte(ev.String()))
}
return hex.EncodeToString(h.Sum(nil))
}
func (r *BatchSubmitterReconciler) statefulSet(crd *stackv1.BatchSubmitter) *appsv1.StatefulSet {
replicas := int32(1)
defaultMode := int32(0o777)
labels := r.labels()
labels["args_hash"] = r.statefulSetArgsHash(crd)
initContainers := []corev1.Container{
{
Name: "wait-for-l1",
Image: "mslipper/wait-for-it:latest",
ImagePullPolicy: corev1.PullAlways,
Args: []string{
Hostify(crd.Spec.L1URL),
"-t",
strconv.Itoa(crd.Spec.L1TimeoutSeconds),
},
},
{
Name: "wait-for-l2",
Image: "mslipper/wait-for-it:latest",
ImagePullPolicy: corev1.PullAlways,
Args: []string{
Hostify(crd.Spec.L2URL),
"-t",
strconv.Itoa(crd.Spec.L2TimeoutSeconds),
},
},
}
baseEnv := []corev1.EnvVar{
{
Name: "L1_NODE_WEB3_URL",
Value: crd.Spec.L1URL,
},
{
Name: "L2_NODE_WEB3_URL",
Value: crd.Spec.L2URL,
},
{
Name: "RUN_METRICS_SERVER",
Value: "true",
},
{
Name: "METRICS_HOSTNAME",
Value: "0.0.0.0",
},
{
Name: "METRICS_PORT",
Value: "9090",
},
}
if crd.Spec.DeployerURL != "" {
initContainers = append(initContainers, corev1.Container{
Name: "wait-for-deployer",
Image: "mslipper/wait-for-it:latest",
ImagePullPolicy: corev1.PullAlways,
Args: []string{
Hostify(crd.Spec.DeployerURL),
"-t",
strconv.Itoa(crd.Spec.DeployerTimeoutSeconds),
},
})
baseEnv = append(baseEnv, []corev1.EnvVar{
{
Name: "ROLLUP_STATE_DUMP_PATH",
Value: "http://deployer:8081/state-dump.latest.json",
},
{
Name: "DEPLOYER_URL",
Value: crd.Spec.DeployerURL,
},
}...)
}
statefulSet := &appsv1.StatefulSet{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "batch-submitter", labels),
Spec: appsv1.StatefulSetSpec{
Replicas: &replicas,
Selector: &v1.LabelSelector{
MatchLabels: map[string]string{
"app": "batch-submitter",
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: v1.ObjectMeta{
Labels: r.labels(),
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyAlways,
InitContainers: initContainers,
Containers: []corev1.Container{
{
Name: "batch-submitter",
Image: crd.Spec.Image,
ImagePullPolicy: corev1.PullAlways,
WorkingDir: "/opt/optimism/packages/batch-submitter",
Command: []string{
"/bin/sh",
"/opt/entrypoints/entrypoint.sh",
"npm",
"run",
"start",
},
Env: append(baseEnv, crd.Spec.Env...),
VolumeMounts: []corev1.VolumeMount{
{
Name: "entrypoints",
MountPath: "/opt/entrypoints",
},
},
Ports: []corev1.ContainerPort{
{
Name: "metrics",
ContainerPort: 9090,
},
},
},
},
Volumes: []corev1.Volume{
{
Name: "entrypoints",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: ObjectName(crd.ObjectMeta, "batch-submitter-entrypoints"),
},
DefaultMode: &defaultMode,
},
},
},
},
},
},
},
}
ctrl.SetControllerReference(crd, statefulSet, r.Scheme)
return statefulSet
}
func (r *BatchSubmitterReconciler) service(crd *stackv1.BatchSubmitter) *corev1.Service {
service := &corev1.Service{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "batch-submitter", r.labels()),
Spec: corev1.ServiceSpec{
Selector: map[string]string{
"app": "batch-submitter",
},
Ports: []corev1.ServicePort{
{
Name: "metrics",
Port: 9090,
},
},
},
}
ctrl.SetControllerReference(crd, service, r.Scheme)
return service
}
const BatchSubmitterEntrypoint = `
#!/bin/sh
if [ -n "$DEPLOYER_URL" ]; then
echo "Loading addresses from $DEPLOYER_URL."
ADDRESSES=$(curl --fail --show-error --silent "$DEPLOYER_URL/addresses.json")
export ADDRESS_MANAGER_ADDRESS=$(echo $ADDRESSES | jq -r ".AddressManager")
fi
exec "$@"
`
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"strconv"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
stackv1 "github.com/ethereum-optimism/optimism/go/stackman/api/v1"
)
// CliqueL1Reconciler reconciles a CliqueL1 object
type CliqueL1Reconciler struct {
client.Client
Scheme *runtime.Scheme
}
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=cliquel1s,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=cliquel1s/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=cliquel1s/finalizers,verbs=update
//+kubebuilder:rbac:groups=apps,resources=deployments;statefulsets,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=core,resources=services;pods;configmaps,verbs=get;list;watch;create;update;patch;delete
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the CliqueL1 object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile
func (r *CliqueL1Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
lgr := log.FromContext(ctx)
crd := &stackv1.CliqueL1{}
if err := r.Get(ctx, req.NamespacedName, crd); err != nil {
if errors.IsNotFound(err) {
lgr.Info("clique resource, not found, ignoring")
return ctrl.Result{}, nil
}
lgr.Error(err, "error getting clique")
return ctrl.Result{}, err
}
created, err := GetOrCreateResource(ctx, r, func() client.Object {
return r.entrypointsCfgMap(crd)
}, ObjectNamespacedName(crd.ObjectMeta, "clique-entrypoints"), &corev1.ConfigMap{})
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
nsName := ObjectNamespacedName(crd.ObjectMeta, "clique")
created, err = GetOrCreateResource(ctx, r, func() client.Object {
return r.statefulSet(crd)
}, nsName, &appsv1.StatefulSet{})
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
created, err = GetOrCreateResource(ctx, r, func() client.Object {
return r.service(crd)
}, nsName, &corev1.Service{})
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
return ctrl.Result{}, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *CliqueL1Reconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&stackv1.CliqueL1{}).
Owns(&corev1.ConfigMap{}).
Owns(&appsv1.Deployment{}).
Owns(&corev1.Service{}).
Complete(r)
}
func (r *CliqueL1Reconciler) entrypointsCfgMap(crd *stackv1.CliqueL1) *corev1.ConfigMap {
cfgMap := &corev1.ConfigMap{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "clique-entrypoints", map[string]string{
"app": "clique",
}),
Data: map[string]string{
"entrypoint.sh": CliqueEntrypoint,
},
}
ctrl.SetControllerReference(crd, cfgMap, r.Scheme)
return cfgMap
}
func (r *CliqueL1Reconciler) statefulSet(crd *stackv1.CliqueL1) *appsv1.StatefulSet {
replicas := int32(1)
labels := map[string]string{
"app": "clique",
}
defaultMode := int32(0o777)
volumes := []corev1.Volume{
{
Name: "entrypoints",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: ObjectName(crd.ObjectMeta, "clique-entrypoints"),
},
DefaultMode: &defaultMode,
},
},
},
}
var volumeClaimTemplates []corev1.PersistentVolumeClaim
dbVolumeName := "db"
if crd.Spec.DataPVC != nil {
storage := resource.MustParse("128Gi")
dbVolumeName = crd.Spec.DataPVC.Name
if crd.Spec.DataPVC.Storage != nil {
storage = *crd.Spec.DataPVC.Storage
}
volumeClaimTemplates = []corev1.PersistentVolumeClaim{
{
ObjectMeta: metav1.ObjectMeta{
Name: crd.Spec.DataPVC.Name,
},
Spec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{
corev1.ReadWriteOnce,
},
Resources: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceStorage: storage,
},
},
},
},
}
} else {
volumes = append(volumes, corev1.Volume{
Name: dbVolumeName,
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
})
}
statefulSet := &appsv1.StatefulSet{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "clique", labels),
Spec: appsv1.StatefulSetSpec{
Replicas: &replicas,
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": "clique",
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: labels,
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyAlways,
Containers: []corev1.Container{
{
Name: "geth",
Image: crd.Spec.Image,
ImagePullPolicy: corev1.PullAlways,
Command: append([]string{
"/bin/sh",
"/opt/entrypoints/entrypoint.sh",
}, crd.Spec.AdditionalArgs...),
Env: []corev1.EnvVar{
crd.Spec.SealerPrivateKey.EnvVar("BLOCK_SIGNER_PRIVATE_KEY"),
crd.Spec.GenesisFile.EnvVar("GENESIS_DATA"),
{
Name: "BLOCK_SIGNER_ADDRESS",
Value: crd.Spec.SealerAddress,
},
{
Name: "CHAIN_ID",
Value: strconv.Itoa(crd.Spec.ChainID),
},
},
VolumeMounts: []corev1.VolumeMount{
{
Name: "entrypoints",
MountPath: "/opt/entrypoints",
},
{
Name: dbVolumeName,
MountPath: "/db",
},
},
Ports: []corev1.ContainerPort{
{
ContainerPort: 8085,
},
{
ContainerPort: 8086,
},
},
},
},
Volumes: volumes,
},
},
VolumeClaimTemplates: volumeClaimTemplates,
},
}
ctrl.SetControllerReference(crd, statefulSet, r.Scheme)
return statefulSet
}
func (r *CliqueL1Reconciler) service(crd *stackv1.CliqueL1) *corev1.Service {
labels := map[string]string{
"app": "clique",
}
service := &corev1.Service{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "clique", labels),
Spec: corev1.ServiceSpec{
Selector: map[string]string{
"app": "clique",
},
Ports: []corev1.ServicePort{
{
Name: "rpc",
Port: 8545,
TargetPort: intstr.FromInt(8545),
},
{
Name: "ws",
Port: 8546,
TargetPort: intstr.FromInt(8546),
},
},
},
}
ctrl.SetControllerReference(crd, service, r.Scheme)
return service
}
const CliqueEntrypoint = `
#!/bin/sh
set -exu
VERBOSITY=${VERBOSITY:-9}
GETH_DATA_DIR=/db
GETH_CHAINDATA_DIR="$GETH_DATA_DIR/geth/chaindata"
GETH_KEYSTORE_DIR="$GETH_DATA_DIR/keystore"
if [ ! -d "$GETH_KEYSTORE_DIR" ]; then
echo "$GETH_KEYSTORE_DIR missing, running account import"
echo -n "pwd" > "$GETH_DATA_DIR"/password
echo -n "$BLOCK_SIGNER_PRIVATE_KEY" | sed 's/0x//' > "$GETH_DATA_DIR"/block-signer-key
geth account import \
--datadir="$GETH_DATA_DIR" \
--password="$GETH_DATA_DIR"/password \
"$GETH_DATA_DIR"/block-signer-key
else
echo "$GETH_KEYSTORE_DIR exists."
fi
if [ ! -d "$GETH_CHAINDATA_DIR" ]; then
echo "$GETH_CHAINDATA_DIR missing, running init"
echo "Creating genesis file."
echo -n "$GENESIS_DATA" > "$GETH_DATA_DIR/genesis.json"
geth --verbosity="$VERBOSITY" init \
--datadir="$GETH_DATA_DIR" \
"$GETH_DATA_DIR/genesis.json"
else
echo "$GETH_CHAINDATA_DIR exists."
fi
geth \
--datadir="$GETH_DATA_DIR" \
--verbosity="$VERBOSITY" \
--http \
--http.corsdomain="*" \
--http.vhosts="*" \
--http.addr=0.0.0.0 \
--http.port=8545 \
--ws.addr=0.0.0.0 \
--ws.port=8546 \
--ws.origins="*" \
--syncmode=full \
--nodiscover \
--maxpeers=1 \
--networkid=$CHAIN_ID \
--unlock=$BLOCK_SIGNER_ADDRESS \
--mine \
--miner.etherbase=$BLOCK_SIGNER_ADDRESS \
--password="$GETH_DATA_DIR"/password \
--allow-insecure-unlock \
"$@"
`
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"crypto/md5"
"encoding/hex"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"strconv"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
stackv1 "github.com/ethereum-optimism/optimism/go/stackman/api/v1"
)
// DataTransportLayerReconciler reconciles a DataTransportLayer object
type DataTransportLayerReconciler struct {
client.Client
Scheme *runtime.Scheme
}
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=datatransportlayers,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=datatransportlayers/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=datatransportlayers/finalizers,verbs=update
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the DataTransportLayer object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile
func (r *DataTransportLayerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
lgr := log.FromContext(ctx)
crd := &stackv1.DataTransportLayer{}
if err := r.Get(ctx, req.NamespacedName, crd); err != nil {
if errors.IsNotFound(err) {
lgr.Info("dtl resource not found, ignoring")
return ctrl.Result{}, nil
}
lgr.Error(err, "error getting dtl")
return ctrl.Result{}, err
}
created, err := GetOrCreateResource(ctx, r, func() client.Object {
return r.entrypointsCfgMap(crd)
}, ObjectNamespacedName(crd.ObjectMeta, "dtl-entrypoints"), &corev1.ConfigMap{})
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
statefulSet := &appsv1.StatefulSet{}
created, err = GetOrCreateResource(ctx, r, func() client.Object {
return r.statefulSet(crd)
}, ObjectNamespacedName(crd.ObjectMeta, "dtl"), statefulSet)
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
argsHash := r.argsHash(crd)
if statefulSet.Labels["args_hash"] != argsHash {
err := r.Update(ctx, r.statefulSet(crd))
if err != nil {
lgr.Error(err, "error updating dtl statefulSet")
return ctrl.Result{}, err
}
return ctrl.Result{Requeue: true}, nil
}
created, err = GetOrCreateResource(ctx, r, func() client.Object {
return r.service(crd)
}, ObjectNamespacedName(crd.ObjectMeta, "dtl"), &corev1.Service{})
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
return ctrl.Result{}, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *DataTransportLayerReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&stackv1.DataTransportLayer{}).
Owns(&corev1.ConfigMap{}).
Owns(&appsv1.Deployment{}).
Owns(&corev1.Service{}).
Complete(r)
}
func (r *DataTransportLayerReconciler) labels() map[string]string {
return map[string]string{
"app": "dtl",
}
}
func (r *DataTransportLayerReconciler) argsHash(crd *stackv1.DataTransportLayer) string {
h := md5.New()
h.Write([]byte(crd.Spec.Image))
h.Write([]byte(crd.Spec.L1URL))
h.Write([]byte(strconv.Itoa(crd.Spec.L1TimeoutSeconds)))
h.Write([]byte(crd.Spec.DeployerURL))
h.Write([]byte(strconv.Itoa(crd.Spec.DeployerTimeoutSeconds)))
if crd.Spec.DataPVC != nil {
h.Write([]byte(crd.Spec.DataPVC.Name))
h.Write([]byte(crd.Spec.DataPVC.Storage.String()))
}
for _, ev := range crd.Spec.Env {
h.Write([]byte(ev.String()))
}
return hex.EncodeToString(h.Sum(nil))
}
func (r *DataTransportLayerReconciler) entrypointsCfgMap(crd *stackv1.DataTransportLayer) *corev1.ConfigMap {
cfgMap := &corev1.ConfigMap{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "dtl-entrypoints", r.labels()),
Data: map[string]string{
"entrypoint.sh": DTLEntrypoint,
},
}
ctrl.SetControllerReference(crd, cfgMap, r.Scheme)
return cfgMap
}
func (r *DataTransportLayerReconciler) statefulSet(crd *stackv1.DataTransportLayer) *appsv1.StatefulSet {
replicas := int32(1)
defaultMode := int32(0o777)
initContainers := []corev1.Container{
{
Name: "wait-for-l1",
Image: "mslipper/wait-for-it:latest",
ImagePullPolicy: corev1.PullAlways,
Args: []string{
Hostify(crd.Spec.L1URL),
"-t",
strconv.Itoa(crd.Spec.L1TimeoutSeconds),
},
},
}
baseEnv := []corev1.EnvVar{
{
Name: "DATA_TRANSPORT_LAYER__L1_RPC_ENDPOINT",
Value: crd.Spec.L1URL,
},
}
if crd.Spec.DeployerURL != "" {
initContainers = append(initContainers, corev1.Container{
Name: "wait-for-deployer",
Image: "mslipper/wait-for-it:latest",
ImagePullPolicy: corev1.PullAlways,
Args: []string{
Hostify(crd.Spec.DeployerURL),
"-t",
strconv.Itoa(crd.Spec.DeployerTimeoutSeconds),
},
})
baseEnv = append(baseEnv, corev1.EnvVar{
Name: "DEPLOYER_URL",
Value: crd.Spec.DeployerURL,
})
}
volumes := []corev1.Volume{
{
Name: "entrypoints",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: ObjectName(crd.ObjectMeta, "dtl-entrypoints"),
},
DefaultMode: &defaultMode,
},
},
},
}
var volumeClaimTemplates []corev1.PersistentVolumeClaim
dbVolumeName := "db"
if crd.Spec.DataPVC != nil {
storage := resource.MustParse("10Gi")
dbVolumeName = crd.Spec.DataPVC.Name
if crd.Spec.DataPVC.Storage != nil {
storage = *crd.Spec.DataPVC.Storage
}
volumeClaimTemplates = []corev1.PersistentVolumeClaim{
{
ObjectMeta: v1.ObjectMeta{
Name: crd.Spec.DataPVC.Name,
},
Spec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{
corev1.ReadWriteOnce,
},
Resources: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceStorage: storage,
},
},
},
},
}
} else {
volumes = append(volumes, corev1.Volume{
Name: dbVolumeName,
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
})
}
statefulSet := &appsv1.StatefulSet{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "dtl", r.labels()),
Spec: appsv1.StatefulSetSpec{
Replicas: &replicas,
Selector: &v1.LabelSelector{
MatchLabels: map[string]string{
"app": "dtl",
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: v1.ObjectMeta{
Labels: r.labels(),
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyAlways,
InitContainers: initContainers,
Containers: []corev1.Container{
{
Name: "dtl",
Image: crd.Spec.Image,
ImagePullPolicy: corev1.PullAlways,
Command: []string{
"/bin/sh",
"/opt/entrypoints/entrypoint.sh",
"node",
"/opt/optimism/packages/data-transport-layer/dist/src/services/run.js",
},
Env: append(baseEnv, crd.Spec.Env...),
VolumeMounts: []corev1.VolumeMount{
{
Name: dbVolumeName,
MountPath: "/db",
},
{
Name: "entrypoints",
MountPath: "/opt/entrypoints",
},
},
Ports: []corev1.ContainerPort{
{
Name: "api",
ContainerPort: 7878,
},
{
Name: "metrics",
ContainerPort: 3000,
},
},
LivenessProbe: &corev1.Probe{
Handler: corev1.Handler{
HTTPGet: &corev1.HTTPGetAction{
Path: "/eth/syncing",
Port: intstr.FromInt(7878),
},
},
},
},
},
Volumes: volumes,
},
},
VolumeClaimTemplates: volumeClaimTemplates,
},
}
ctrl.SetControllerReference(crd, statefulSet, r.Scheme)
return statefulSet
}
func (r *DataTransportLayerReconciler) service(crd *stackv1.DataTransportLayer) *corev1.Service {
service := &corev1.Service{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "dtl", r.labels()),
Spec: corev1.ServiceSpec{
Selector: map[string]string{
"app": "dtl",
},
Ports: []corev1.ServicePort{
{
Port: 3000,
},
{
Port: 7878,
},
},
},
}
ctrl.SetControllerReference(crd, service, r.Scheme)
return service
}
const DTLEntrypoint = `
#!/bin/sh
if [ -n "$DEPLOYER_URL" ]; then
echo "Loading addresses from $DEPLOYER_URL."
ADDRESSES=$(curl --fail --show-error --silent "$DEPLOYER_URL/addresses.json")
export DATA_TRANSPORT_LAYER__ADDRESS_MANAGER=$(echo $ADDRESSES | jq -r ".AddressManager")
fi
exec "$@"
`
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"crypto/md5"
"encoding/hex"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"strconv"
"time"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
stackv1 "github.com/ethereum-optimism/optimism/go/stackman/api/v1"
)
// DeployerReconciler reconciles a Deployer object
type DeployerReconciler struct {
client.Client
Scheme *runtime.Scheme
}
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=deployers,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=deployers/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=deployers/finalizers,verbs=update
//+kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=core,resources=services;pods;configmaps,verbs=get;list;watch;create;update;patch;delete
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the Deployer object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile
func (r *DeployerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
lgr := log.FromContext(ctx)
crd := &stackv1.Deployer{}
if err := r.Get(ctx, req.NamespacedName, crd); err != nil {
if errors.IsNotFound(err) {
lgr.Info("deployer resource not found, ignoring")
return ctrl.Result{}, nil
}
lgr.Error(err, "error getting deployer")
return ctrl.Result{}, err
}
created, err := GetOrCreateResource(ctx, r, func() client.Object {
return r.entrypointsCfgMap(crd)
}, ObjectNamespacedName(crd.ObjectMeta, "entrypoints"), &corev1.ConfigMap{})
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
deployment := &appsv1.Deployment{}
created, err = GetOrCreateResource(ctx, r, func() client.Object {
return r.deployment(crd)
}, ObjectNamespacedName(crd.ObjectMeta, "deployer"), deployment)
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
argsHash := r.deploymentArgsHash(crd)
if deployment.Labels["args_hash"] != argsHash {
err := r.Update(ctx, r.deployment(crd))
if err != nil {
lgr.Error(err, "error updating deployer deployment")
return ctrl.Result{}, err
}
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
created, err = GetOrCreateResource(ctx, r, func() client.Object {
return r.service(crd)
}, ObjectNamespacedName(crd.ObjectMeta, "deployer"), &corev1.Service{})
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
return ctrl.Result{}, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *DeployerReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&stackv1.Deployer{}).
Owns(&corev1.ConfigMap{}).
Owns(&appsv1.Deployment{}).
Owns(&corev1.Service{}).
Complete(r)
}
func (r *DeployerReconciler) labels(crd *stackv1.Deployer) map[string]string {
return map[string]string{
"app": "deployer",
"deployer_crd": crd.Namespace,
}
}
func (r *DeployerReconciler) entrypointsCfgMap(crd *stackv1.Deployer) *corev1.ConfigMap {
cfgMap := &corev1.ConfigMap{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "entrypoints", r.labels(crd)),
Data: map[string]string{
"entrypoint.sh": DeployerEntrypoint,
},
}
ctrl.SetControllerReference(crd, cfgMap, r.Scheme)
return cfgMap
}
func (r *DeployerReconciler) deploymentArgsHash(crd *stackv1.Deployer) string {
h := md5.New()
h.Write([]byte(crd.Spec.Image))
h.Write([]byte(crd.Spec.L1URL))
h.Write([]byte(strconv.Itoa(crd.Spec.L1TimeoutSeconds)))
for _, ev := range crd.Spec.Env {
h.Write([]byte(ev.String()))
}
return hex.EncodeToString(h.Sum(nil))
}
func (r *DeployerReconciler) deployment(crd *stackv1.Deployer) *appsv1.Deployment {
replicas := int32(1)
defaultMode := int32(0o777)
deployment := &appsv1.Deployment{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "deployer", map[string]string{
"app": "deployer",
"deployer_crd": crd.Namespace,
"args_hash": r.deploymentArgsHash(crd),
}),
Spec: appsv1.DeploymentSpec{
Replicas: &replicas,
Selector: &v1.LabelSelector{
MatchLabels: map[string]string{
"app": "deployer",
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: v1.ObjectMeta{
Labels: r.labels(crd),
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyAlways,
InitContainers: []corev1.Container{
{
Name: "wait-for-l1",
Image: "mslipper/wait-for-it:latest",
ImagePullPolicy: corev1.PullAlways,
Args: []string{
Hostify(crd.Spec.L1URL),
"-t",
strconv.Itoa(crd.Spec.L1TimeoutSeconds),
},
},
},
Containers: []corev1.Container{
{
Name: "deployer",
Image: crd.Spec.Image,
ImagePullPolicy: corev1.PullAlways,
Command: []string{
"/bin/bash",
"/opt/entrypoints/entrypoint.sh",
},
Env: append([]corev1.EnvVar{
{
Name: "L1_NODE_WEB3_URL",
Value: crd.Spec.L1URL,
},
{
Name: "NO_COMPILE",
Value: "1",
},
{
Name: "AUTOMATICALLY_TRANSFER_OWNERSHIP",
Value: "true",
},
}, crd.Spec.Env...),
VolumeMounts: []corev1.VolumeMount{
{
Name: "entrypoints",
MountPath: "/opt/entrypoints",
},
},
Ports: []corev1.ContainerPort{
{
ContainerPort: 8081,
},
},
},
},
Volumes: []corev1.Volume{
{
Name: "entrypoints",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: ObjectName(crd.ObjectMeta, "entrypoints"),
},
DefaultMode: &defaultMode,
},
},
},
},
},
},
},
}
ctrl.SetControllerReference(crd, deployment, r.Scheme)
return deployment
}
func (r *DeployerReconciler) service(crd *stackv1.Deployer) *corev1.Service {
service := &corev1.Service{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "deployer", r.labels(crd)),
Spec: corev1.ServiceSpec{
Selector: map[string]string{
"app": "deployer",
},
Ports: []corev1.ServicePort{
{
Name: "web",
Port: 8081,
},
},
},
}
ctrl.SetControllerReference(crd, service, r.Scheme)
return service
}
const DeployerEntrypoint = `
#!/bin/bash
set -e
cd /optimism/packages/contracts
yarn run deploy
function envSet() {
VAR=$1
export $VAR=$(cat ./dist/dumps/addresses.json | jq -r ".$2")
}
# set the address to the proxy gateway if possible
envSet L1_STANDARD_BRIDGE_ADDRESS Proxy__OVM_L1StandardBridge
if [ $L1_STANDARD_BRIDGE_ADDRESS == null ]; then
envSet L1_STANDARD_BRIDGE_ADDRESS L1StandardBridge
fi
envSet L1_CROSS_DOMAIN_MESSENGER_ADDRESS Proxy__OVM_L1CrossDomainMessenger
if [ $L1_CROSS_DOMAIN_MESSENGER_ADDRESS == null ]; then
envSet L1_CROSS_DOMAIN_MESSENGER_ADDRESS L1CrossDomainMessenger
fi
# build the dump file
yarn run build:dump
echo "Starting server."
# service the addresses and dumps
python3 -m http.server \
--bind "0.0.0.0" 8081 \
--directory ./dist/dumps
`
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"crypto/md5"
"encoding/hex"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"strconv"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
stackv1 "github.com/ethereum-optimism/optimism/go/stackman/api/v1"
)
// GasOracleReconciler reconciles a GasOracle object
type GasOracleReconciler struct {
client.Client
Scheme *runtime.Scheme
}
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=gasoracles,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=gasoracles/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=stack.optimism-stacks.net,resources=gasoracles/finalizers,verbs=update
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the GasOracle object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile
func (r *GasOracleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
lgr := log.FromContext(ctx)
crd := &stackv1.GasOracle{}
if err := r.Get(ctx, req.NamespacedName, crd); err != nil {
if errors.IsNotFound(err) {
lgr.Info("gas oracle resource not found, ignoring")
return ctrl.Result{}, nil
}
lgr.Error(err, "error getting gas oracle")
return ctrl.Result{}, err
}
deployment := &appsv1.Deployment{}
created, err := GetOrCreateResource(ctx, r, func() client.Object {
return r.deployment(crd)
}, ObjectNamespacedName(crd.ObjectMeta, "gas-oracle"), deployment)
if err != nil {
return ctrl.Result{}, err
}
if created {
return ctrl.Result{Requeue: true}, nil
}
argsHash := r.deploymentArgsHash(crd)
if deployment.Labels["args_hash"] != argsHash {
err := r.Update(ctx, r.deployment(crd))
if err != nil {
lgr.Error(err, "error updating gas oracle deployment")
return ctrl.Result{}, err
}
return ctrl.Result{Requeue: true}, nil
}
return ctrl.Result{}, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *GasOracleReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&stackv1.GasOracle{}).
Complete(r)
}
func (r *GasOracleReconciler) labels() map[string]string {
return map[string]string{
"app": "gas-oracle",
}
}
func (r *GasOracleReconciler) deploymentArgsHash(crd *stackv1.GasOracle) string {
h := md5.New()
h.Write([]byte(crd.Spec.Image))
h.Write([]byte(crd.Spec.L1URL))
h.Write([]byte(strconv.Itoa(crd.Spec.L1TimeoutSeconds)))
h.Write([]byte(crd.Spec.L2URL))
h.Write([]byte(strconv.Itoa(crd.Spec.L2TimeoutSeconds)))
for _, ev := range crd.Spec.Env {
h.Write([]byte(ev.String()))
}
return hex.EncodeToString(h.Sum(nil))
}
func (r *GasOracleReconciler) deployment(crd *stackv1.GasOracle) *appsv1.Deployment {
replicas := int32(1)
labels := r.labels()
labels["args_hash"] = r.deploymentArgsHash(crd)
baseEnv := []corev1.EnvVar{
{
Name: "GAS_PRICE_ORACLE_ETHEREUM_HTTP_URL",
Value: crd.Spec.L1URL,
},
{
Name: "GAS_PRICE_ORACLE_LAYER_TWO_HTTP_URL",
Value: crd.Spec.L2URL,
},
}
deployment := &appsv1.Deployment{
ObjectMeta: ObjectMeta(crd.ObjectMeta, "gas-oracle", labels),
Spec: appsv1.DeploymentSpec{
Replicas: &replicas,
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": "gas-oracle",
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: r.labels(),
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyAlways,
InitContainers: []corev1.Container{
{
Name: "wait-for-l1",
Image: "mslipper/wait-for-it:latest",
ImagePullPolicy: corev1.PullAlways,
Args: []string{
Hostify(crd.Spec.L1URL),
"-t",
strconv.Itoa(crd.Spec.L1TimeoutSeconds),
},
},
{
Name: "wait-for-l2",
Image: "mslipper/wait-for-it:latest",
ImagePullPolicy: corev1.PullAlways,
Args: []string{
Hostify(crd.Spec.L2URL),
"-t",
strconv.Itoa(crd.Spec.L2TimeoutSeconds),
},
},
},
Containers: []corev1.Container{
{
Name: "gpo",
Image: crd.Spec.Image,
ImagePullPolicy: corev1.PullAlways,
Env: append(baseEnv, crd.Spec.Env...),
},
},
},
},
},
}
ctrl.SetControllerReference(crd, deployment, r.Scheme)
return deployment
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
package controllers
import (
"github.com/stretchr/testify/require"
"testing"
)
func TestHostify(t *testing.T) {
tests := [][2]string{
{
"https://test.infura.io/v1/123456",
"test.infura.io:443",
},
{
"http://test.infura.io/v1/123456",
"test.infura.io:80",
},
{
"test.infura.io/v1/123456",
"test.infura.io:80",
},
{
"test.infura.io",
"test.infura.io:80",
},
{
"http://sequencer:8545",
"sequencer:8545",
},
}
for _, tt := range tests {
t.Run(tt[0], func(t *testing.T) {
require.Equal(t, tt[1], Hostify(tt[0]))
})
}
}
module github.com/ethereum-optimism/optimism/go/stackman
go 1.16
require (
github.com/onsi/ginkgo v1.16.4
github.com/onsi/gomega v1.15.0
github.com/stretchr/testify v1.7.0
gopkg.in/yaml.v2 v2.4.0 // indirect
k8s.io/api v0.22.1
k8s.io/apimachinery v0.22.1
k8s.io/client-go v0.22.1
sigs.k8s.io/controller-runtime v0.10.0
)
This diff is collapsed.
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
\ No newline at end of file
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment