Skip to content

Instantly share code, notes, and snippets.

@tamalsaha
Last active January 18, 2022 06:58
Show Gist options
  • Save tamalsaha/6215f161788d0293c066d1afd88eb0d4 to your computer and use it in GitHub Desktop.
Save tamalsaha/6215f161788d0293c066d1afd88eb0d4 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
// "time"
// "github.com/nats-io/nats.go"
// "github.com/tamalsaha/nats-hop-demo/shared"
// "github.com/tamalsaha/nats-hop-demo/transport"
core "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
// "k8s.io/klog/v2"
"k8s.io/klog/v2/klogr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
)
func NewClient() (client.Client, error) {
scheme := runtime.NewScheme()
_ = clientgoscheme.AddToScheme(scheme)
crdinstall.Install(scheme)
ctrl.SetLogger(klogr.New())
cfg := ctrl.GetConfigOrDie()
cfg.QPS = 100
cfg.Burst = 100
mapper, err := apiutil.NewDynamicRESTMapper(cfg)
if err != nil {
return nil, err
}
return client.New(cfg, client.Options{
Scheme: scheme,
Mapper: mapper,
//Opts: client.WarningHandlerOptions{
// SuppressWarnings: false,
// AllowDuplicateLogs: false,
//},
})
}
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
func main() {
if err := run(); err != nil {
panic(err)
}
}
func run() error {
_ = clientgoscheme.AddToScheme(scheme)
// nc, err := nats.Connect(shared.NATS_URL)
// if err != nil {
// klog.Fatalln(err)
// }
// defer nc.Close()
ctrl.SetLogger(klogr.New())
cfg := ctrl.GetConfigOrDie()
// tr, err := cfg.TransportConfig()
// if err != nil {
// panic(err)
// }
// cfg.Transport, err = transport.New(tr, nc, "k8s", 10000*time.Second)
// if err != nil {
// panic(err)
// }
mapper, err := apiutil.NewDynamicRESTMapper(cfg)
if err != nil {
return err
}
c, err := client.New(cfg, client.Options{
Scheme: scheme,
Mapper: mapper,
Opts: client.WarningHandlerOptions{
SuppressWarnings: false,
AllowDuplicateLogs: false,
},
})
if err != nil {
return err
}
var nodes core.NodeList
err = c.List(context.TODO(), &nodes)
if err != nil {
panic(err)
}
for _, n := range nodes.Items {
fmt.Println(n.Name)
}
return nil
}
# Image URL to use all building/pushing image targets
IMG ?= 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
.PHONY: all
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
.PHONY: help
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
.PHONY: manifests
manifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and CustomResourceDefinition objects.
$(CONTROLLER_GEN) rbac:roleName=manager-role crd:allowDangerousTypes=true webhook paths="./..." output:crd:artifacts:config=config/crd/bases
.PHONY: generate
generate: controller-gen ## Generate code containing DeepCopy, DeepCopyInto, and DeepCopyObject method implementations.
$(CONTROLLER_GEN) object:headerFile="hack/boilerplate.go.txt" paths="./..."
.PHONY: fmt
fmt: ## Run go fmt against code.
go fmt ./...
.PHONY: vet
vet: ## Run go vet against code.
go vet ./...
.PHONY: test
test: manifests generate fmt vet envtest ## Run tests.
KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) -p path)" go test ./... -coverprofile cover.out
##@ Build
.PHONY: build
build: generate fmt vet ## Build manager binary.
go build -o bin/manager main.go
.PHONY: run
run: manifests generate fmt vet ## Run a controller from your host.
go run ./main.go
.PHONY: docker-build
docker-build: test ## Build docker image with the manager.
docker build -t ${IMG} .
.PHONY: docker-push
docker-push: ## Push docker image with the manager.
docker push ${IMG}
##@ Deployment
ifndef ignore-not-found
ignore-not-found = false
endif
.PHONY: install
install: manifests kustomize ## Install CRDs into the K8s cluster specified in ~/.kube/config.
$(KUSTOMIZE) build config/crd | kubectl apply -f -
.PHONY: uninstall
uninstall: manifests kustomize ## Uninstall CRDs from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion.
$(KUSTOMIZE) build config/crd | kubectl delete --ignore-not-found=$(ignore-not-found) -f -
.PHONY: deploy
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 -
.PHONY: undeploy
undeploy: ## Undeploy controller from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion.
$(KUSTOMIZE) build config/default | kubectl delete --ignore-not-found=$(ignore-not-found) -f -
CONTROLLER_GEN = $(shell pwd)/bin/controller-gen
.PHONY: controller-gen
controller-gen: ## Download controller-gen locally if necessary.
$(call go-forked-tool,$(CONTROLLER_GEN),https://github.com/kmodules/controller-tools,v0.7.0-ac)
KUSTOMIZE = $(shell pwd)/bin/kustomize
.PHONY: kustomize
kustomize: ## Download kustomize locally if necessary.
$(call go-get-tool,$(KUSTOMIZE),sigs.k8s.io/kustomize/kustomize/[email protected])
ENVTEST = $(shell pwd)/bin/setup-envtest
.PHONY: 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
define go-forked-tool
@[ -f $(1) ] || { \
set -e ;\
TMP_DIR=$$(mktemp -d) ;\
cd $$TMP_DIR ;\
echo "Cloning $(2)" ;\
git clone $(2); \
cd $$(ls -b1); \
git checkout $(3); \
GOBIN=$(PROJECT_DIR)/bin go install ./... ;\
rm -rf $$TMP_DIR ;\
}
endef
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment