├── .dockerignore ├── .github ├── CODEOWNERS ├── dependabot.yml ├── mergify.yml ├── settings.yml └── workflows │ ├── ci.yaml │ └── release.yaml ├── .gitignore ├── .golangci.yml ├── ARCHITECTURE.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── Makefile ├── PROJECT ├── README.md ├── REALEASE.md ├── api └── v1alpha1 │ ├── action.go │ ├── groupversion_info.go │ ├── job.go │ ├── machine.go │ ├── provider_opts.go │ ├── task.go │ └── zz_generated.deepcopy.go ├── config ├── crd │ ├── bases │ │ ├── bmc.tinkerbell.org_jobs.yaml │ │ ├── bmc.tinkerbell.org_machines.yaml │ │ └── bmc.tinkerbell.org_tasks.yaml │ ├── kustomization.yaml │ ├── kustomizeconfig.yaml │ └── patches │ │ ├── cainjection_in_jobs.yaml │ │ ├── cainjection_in_machines.yaml │ │ ├── cainjection_in_tasks.yaml │ │ ├── webhook_in_jobs.yaml │ │ ├── webhook_in_machines.yaml │ │ └── webhook_in_tasks.yaml ├── default │ ├── kustomization.yaml │ └── manager_config_patch.yaml ├── manager │ ├── controller_manager_config.yaml │ ├── kustomization.yaml │ └── manager.yaml ├── prometheus │ ├── kustomization.yaml │ └── monitor.yaml ├── rbac │ ├── job_editor_role.yaml │ ├── job_viewer_role.yaml │ ├── kustomization.yaml │ ├── leader_election_role.yaml │ ├── leader_election_role_binding.yaml │ ├── machine_editor_role.yaml │ ├── machine_viewer_role.yaml │ ├── role.yaml │ ├── role_binding.yaml │ ├── secrets_viewer_role.yaml │ ├── secrets_viewer_role_binding.yaml │ ├── service_account.yaml │ ├── task_editor_role.yaml │ └── task_viewer_role.yaml └── samples │ ├── auth-secret.yaml │ ├── hmac-secret1.yaml │ ├── hmac-secret2.yaml │ ├── job_v1alpha1.yaml │ ├── machine_v1alpha1.yaml │ ├── machine_with_opts_v1alpha1.yaml │ └── task_v1alpha1.yaml ├── contrib └── tag-release.sh ├── controller ├── client.go ├── helpers_test.go ├── job.go ├── job_test.go ├── kube.go ├── machine.go ├── machine_test.go ├── task.go └── task_test.go ├── docs ├── README.md └── puml │ ├── architecture.png │ └── architecture.puml ├── go.mod ├── go.sum ├── hack └── boilerplate.go.txt ├── lint.mk ├── main.go └── tools.go /.dockerignore: -------------------------------------------------------------------------------- 1 | # More info: https://docs.docker.com/engine/reference/builder/#dockerignore-file 2 | # Ignore build and test binaries. 3 | bin/ 4 | testbin/ 5 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | /.github/settings.yml @chrisdoherty4 @jacobweinstock 2 | /.github/CODEOWNERS @chrisdoherty4 @jacobweinstock 3 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | day: "monday" 8 | time: "04:39" 9 | timezone: "America/New_York" 10 | reviewers: 11 | - chrisdoherty4 12 | - jacobweinstock 13 | open-pull-requests-limit: 10 14 | 15 | - package-ecosystem: "gomod" 16 | directory: "/" 17 | schedule: 18 | interval: "weekly" 19 | day: "friday" 20 | time: "03:52" 21 | timezone: "America/New_York" 22 | reviewers: 23 | - chrisdoherty4 24 | - jacobweinstock 25 | open-pull-requests-limit: 10 26 | 27 | - package-ecosystem: "docker" 28 | directory: "/" 29 | schedule: 30 | interval: "weekly" 31 | day: "monday" 32 | time: "04:22" 33 | timezone: "America/New_York" 34 | reviewers: 35 | - chrisdoherty4 36 | - jacobweinstock 37 | open-pull-requests-limit: 10 38 | -------------------------------------------------------------------------------- /.github/mergify.yml: -------------------------------------------------------------------------------- 1 | queue_rules: 2 | - name: default 3 | queue_conditions: 4 | - base=main 5 | - "#approved-reviews-by>=1" 6 | - "#changes-requested-reviews-by=0" 7 | - "#review-requested=0" 8 | - check-success=DCO 9 | - check-success=verify 10 | - check-success=test 11 | - check-success=build 12 | - label!=do-not-merge 13 | - label=ready-to-merge 14 | merge_conditions: 15 | # Conditions to get out of the queue (= merged) 16 | - check-success=DCO 17 | - check-success=build 18 | merge_method: merge 19 | commit_message_template: | 20 | {{ title }} (#{{ number }}) 21 | 22 | pull_request_rules: 23 | - name: refactored queue action rule 24 | conditions: [] 25 | actions: 26 | queue: 27 | -------------------------------------------------------------------------------- /.github/settings.yml: -------------------------------------------------------------------------------- 1 | # Collaborators: give specific users access to this repository. 2 | # See https://docs.github.com/en/rest/reference/repos#add-a-repository-collaborator for available options 3 | collaborators: 4 | # Maintainers, should also be added to the .github/CODEOWNERS file as owners of this settings.yml file. 5 | - username: chrisdoherty4 6 | permission: maintain 7 | - username: jacobweinstock 8 | permission: maintain 9 | # Approvers 10 | # Reviewers 11 | 12 | # Note: `permission` is only valid on organization-owned repositories. 13 | # The permission to grant the collaborator. Can be one of: 14 | # * `pull` - can pull, but not push to or administer this repository. 15 | # * `push` - can pull and push, but not administer this repository. 16 | # * `admin` - can pull, push and administer this repository. 17 | # * `maintain` - Recommended for project managers who need to manage the repository without access to sensitive or destructive actions. 18 | # * `triage` - Recommended for contributors who need to proactively manage issues and pull requests without write access. 19 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: For each commit and PR 2 | on: 3 | push: 4 | branches: 5 | - "*" 6 | tags-ignore: 7 | - "v*" 8 | pull_request: 9 | 10 | env: 11 | CGO_ENABLED: 0 12 | GO_VERSION: '1.21' 13 | 14 | jobs: 15 | verify: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Checkout code 19 | uses: actions/checkout@v4 20 | 21 | - name: Install Go 22 | uses: actions/setup-go@v5 23 | with: 24 | go-version: "${{ env.GO_VERSION }}" 25 | 26 | - name: make vet 27 | run: make vet 28 | 29 | - name: lint 30 | run: make lint 31 | 32 | test: 33 | runs-on: ubuntu-latest 34 | steps: 35 | - name: Checkout code 36 | uses: actions/checkout@v4 37 | 38 | - name: Install Go 39 | uses: actions/setup-go@v5 40 | with: 41 | go-version: "${{ env.GO_VERSION }}" 42 | 43 | - name: Unit test 44 | run: make test 45 | 46 | - name: Upload codecov 47 | uses: codecov/codecov-action@v5 48 | env: 49 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 50 | 51 | build: 52 | runs-on: ubuntu-latest 53 | needs: 54 | - verify 55 | - test 56 | steps: 57 | - name: Checkout code 58 | uses: actions/checkout@v4 59 | 60 | - name: Set up Docker Buildx 61 | uses: docker/setup-buildx-action@v3 62 | 63 | - name: Login to quay.io 64 | uses: docker/login-action@v3 65 | if: ${{ startsWith(github.ref, 'refs/heads/main') || startsWith(github.ref, 'refs/heads/v') }} 66 | with: 67 | registry: quay.io 68 | username: ${{ secrets.QUAY_USERNAME }} 69 | password: ${{ secrets.QUAY_PASSWORD }} 70 | 71 | - name: Docker build meta 72 | id: image-meta 73 | uses: docker/metadata-action@v5 74 | with: 75 | images: quay.io/tinkerbell/rufio 76 | tags: | 77 | type=raw,value=latest,enable={{is_default_branch}} 78 | type=ref,event=branch,enable=${{ !startsWith(github.ref, 'refs/heads/main') }} 79 | type=sha 80 | 81 | - name: Docker build quay.io/tinkerbell/rufio 82 | uses: docker/build-push-action@v6 83 | with: 84 | context: ./ 85 | file: ./Dockerfile 86 | cache-from: type=registry,ref=quay.io/tinkerbell/rufio:latest 87 | tags: ${{ steps.image-meta.outputs.tags }} 88 | platforms: linux/amd64,linux/arm64 89 | push: ${{ startsWith(github.ref, 'refs/heads/main') || startsWith(github.ref, 'refs/heads/v') }} 90 | -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | tags: 4 | - "v*" 5 | name: Create release 6 | env: 7 | REGISTRY: quay.io 8 | IMAGE_NAME: ${{ github.repository }} 9 | jobs: 10 | release: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout code 14 | uses: actions/checkout@v4 15 | 16 | - name: Login to quay.io 17 | uses: docker/login-action@v3 18 | with: 19 | registry: quay.io 20 | username: ${{ secrets.QUAY_USERNAME }} 21 | password: ${{ secrets.QUAY_PASSWORD }} 22 | 23 | # This action generates the source image name and should coincide with the build 24 | # from the ci.yaml workflow. 25 | - name: Generate source image 26 | id: src 27 | uses: docker/metadata-action@v5 28 | with: 29 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 30 | flavor: latest=false 31 | tags: | 32 | type=sha 33 | 34 | - name: Generate docker tags 35 | id: meta 36 | uses: docker/metadata-action@v5 37 | with: 38 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 39 | flavor: latest=false 40 | tags: | 41 | type=semver,pattern=v{{version}} 42 | type=semver,pattern=v{{major}}.{{minor}} 43 | type=semver,pattern=v{{major}} 44 | 45 | - name: Tag and push image 46 | uses: akhilerm/tag-push-action@v2.2.0 47 | with: 48 | src: ${{ steps.src.outputs.tags }} 49 | dst: | 50 | ${{ steps.meta.outputs.tags }} 51 | 52 | - name: Generate release notes 53 | run: | 54 | release_notes=$(gh api repos/{owner}/{repo}/releases/generate-notes -F tag_name=${{ github.ref }} --jq .body) 55 | echo 'RELEASE_NOTES<> $GITHUB_ENV 56 | echo "${release_notes}" >> $GITHUB_ENV 57 | echo 'EOF' >> $GITHUB_ENV 58 | env: 59 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 60 | OWNER: ${{ github.repository_owner }} 61 | REPO: ${{ github.event.repository.name }} 62 | 63 | - name: Create release 64 | id: create_release 65 | uses: actions/create-release@v1 66 | env: 67 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 68 | with: 69 | tag_name: ${{ github.ref }} 70 | release_name: ${{ github.ref }} 71 | body: ${{ env.RELEASE_NOTES }} 72 | draft: false 73 | prerelease: true 74 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | doc/ 3 | .idea 4 | .vscode 5 | coverage.txt 6 | cover.out 7 | 8 | # Terraform 9 | .terraform 10 | terraform.tfstate 11 | terraform.tfstate.backup 12 | 13 | # Vagrant 14 | **/.vagrant 15 | envrc 16 | .env 17 | deploy/state 18 | out/ 19 | 20 | .*.swp 21 | hack/tools 22 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | run: 2 | # The default runtime timeout is 1m, which doesn't work well on Github Actions. 3 | timeout: 4m 4 | 5 | # NOTE: This file is populated by the lint-install tool. Local adjustments may be overwritten. 6 | linters-settings: 7 | cyclop: 8 | # NOTE: This is a very high transitional threshold 9 | max-complexity: 37 10 | package-average: 34.0 11 | skip-tests: true 12 | 13 | gocognit: 14 | # NOTE: This is a very high transitional threshold 15 | min-complexity: 98 16 | 17 | dupl: 18 | threshold: 200 19 | 20 | goconst: 21 | min-len: 4 22 | min-occurrences: 5 23 | ignore-tests: true 24 | 25 | gosec: 26 | excludes: 27 | - G107 # Potential HTTP request made with variable url 28 | - G204 # Subprocess launched with function call as argument or cmd arguments 29 | - G404 # Use of weak random number generator (math/rand instead of crypto/rand 30 | 31 | errorlint: 32 | # these are still common in Go: for instance, exit errors. 33 | asserts: false 34 | 35 | exhaustive: 36 | default-signifies-exhaustive: true 37 | 38 | nestif: 39 | min-complexity: 8 40 | 41 | nolintlint: 42 | require-explanation: true 43 | allow-unused: false 44 | require-specific: true 45 | 46 | revive: 47 | ignore-generated-header: true 48 | severity: warning 49 | rules: 50 | - name: atomic 51 | - name: blank-imports 52 | - name: bool-literal-in-expr 53 | - name: confusing-naming 54 | - name: constant-logical-expr 55 | - name: context-as-argument 56 | - name: context-keys-type 57 | - name: deep-exit 58 | - name: defer 59 | - name: range-val-in-closure 60 | - name: range-val-address 61 | - name: dot-imports 62 | - name: error-naming 63 | - name: error-return 64 | - name: error-strings 65 | - name: errorf 66 | - name: exported 67 | - name: identical-branches 68 | - name: if-return 69 | - name: import-shadowing 70 | - name: increment-decrement 71 | - name: indent-error-flow 72 | - name: indent-error-flow 73 | - name: package-comments 74 | - name: range 75 | - name: receiver-naming 76 | - name: redefines-builtin-id 77 | - name: superfluous-else 78 | - name: struct-tag 79 | - name: time-naming 80 | - name: unexported-naming 81 | - name: unexported-return 82 | - name: unnecessary-stmt 83 | - name: unreachable-code 84 | - name: unused-parameter 85 | - name: var-declaration 86 | - name: var-naming 87 | - name: unconditional-recursion 88 | - name: waitgroup-by-value 89 | 90 | staticcheck: 91 | go: "1.20" 92 | 93 | unused: 94 | go: "1.20" 95 | 96 | output: 97 | sort-results: true 98 | 99 | linters: 100 | disable-all: true 101 | enable: 102 | - asciicheck 103 | - bodyclose 104 | - cyclop 105 | - dogsled 106 | - dupl 107 | - durationcheck 108 | - errcheck 109 | - errname 110 | - errorlint 111 | - exhaustive 112 | - exportloopref 113 | - forcetypeassert 114 | - gocognit 115 | - goconst 116 | - gocritic 117 | - godot 118 | - gofmt 119 | - gofumpt 120 | - gosec 121 | - goheader 122 | - goimports 123 | - goprintffuncname 124 | - gosimple 125 | - govet 126 | - importas 127 | - ineffassign 128 | - makezero 129 | - misspell 130 | - nakedret 131 | - nestif 132 | - nilerr 133 | - noctx 134 | - nolintlint 135 | - predeclared 136 | # disabling for the initial iteration of the linting tool 137 | # - promlinter 138 | - revive 139 | - rowserrcheck 140 | - sqlclosecheck 141 | - staticcheck 142 | - stylecheck 143 | - thelper 144 | - tparallel 145 | - typecheck 146 | - unconvert 147 | - unparam 148 | - unused 149 | - wastedassign 150 | - whitespace 151 | 152 | # Disabled linters, due to being misaligned with Go practices 153 | # - exhaustivestruct 154 | # - gochecknoglobals 155 | # - gochecknoinits 156 | # - goconst 157 | # - godox 158 | # - goerr113 159 | # - gomnd 160 | # - lll 161 | # - nlreturn 162 | # - testpackage 163 | # - wsl 164 | # Disabled linters, due to not being relevant to our code base: 165 | # - maligned 166 | # - prealloc "For most programs usage of prealloc will be a premature optimization." 167 | # Disabled linters due to bad error messages or bugs 168 | # - tagliatelle 169 | 170 | issues: 171 | # Excluding configuration per-path, per-linter, per-text and per-source 172 | exclude-rules: 173 | - path: _test\.go 174 | linters: 175 | - dupl 176 | - errcheck 177 | - forcetypeassert 178 | - gocyclo 179 | - gosec 180 | - noctx 181 | 182 | - path: .*cmd.* 183 | linters: 184 | - noctx 185 | 186 | - path: main\.go 187 | linters: 188 | - noctx 189 | 190 | - path: .*cmd.* 191 | text: "deep-exit" 192 | 193 | - path: main\.go 194 | text: "deep-exit" 195 | 196 | # This check is of questionable value 197 | - linters: 198 | - tparallel 199 | text: "call t.Parallel on the top level as well as its subtests" 200 | 201 | # Don't hide lint issues just because there are many of them 202 | max-same-issues: 0 203 | max-issues-per-linter: 0 -------------------------------------------------------------------------------- /ARCHITECTURE.md: -------------------------------------------------------------------------------- 1 | # Rufio Architecture 2 | 3 | ![Architecutre](/docs/puml/architecture.png) -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | Refer to our [Code of Conduct](https://github.com/tinkerbell/.github/blob/main/CODE_OF_CONDUCT.md) 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributor Guide 2 | 3 | Welcome to Rufio! We are really excited to have you. 4 | Please use the following guide on your contributing journey. 5 | Thanks for contributing! 6 | 7 | ## Table of Contents 8 | 9 | - [Context](#Context) 10 | - [Prerequisites](#Prerequisites) 11 | - [DCO Sign Off](#DCO-Sign-Off) 12 | - [Code of Conduct](#Code-of-Conduct) 13 | - [Setting up your development environment](#Setting-up-your-development-environment) 14 | - [Pull Requests](#Pull-Requests) 15 | - [Branching strategy](#Branching-strategy) 16 | - [Quality](#Quality) 17 | - [CI](#CI) 18 | - [Code coverage](#Code-coverage) 19 | - [Pre PR Checklist](#Pre-PR-Checklist) 20 | 21 | --- 22 | 23 | ## Context 24 | 25 | 26 | Rufio is a Kubernetes controller for managing baseboard management state and actions.It is part of the [Tinkerbell stack](https://tinkerbell.org) and provides the glue for machine provisioning by enabling machine restarts and setting next boot devices. 27 | 28 | ## Prerequisites 29 | 30 | ### DCO Sign Off 31 | 32 | Please read and understand the DCO found [here](docs/DCO.md). 33 | 34 | ### Code of Conduct 35 | 36 | Please read and understand the code of conduct found [here](https://github.com/tinkerbell/rufio/blob/main/CODE_OF_CONDUCT.md). 37 | 38 | ### Setting up your development environment 39 | 40 | 1. Install Go 41 | 42 | Rufio requires [Go 1.17](https://golang.org/dl/) or later. 43 | 44 | 1. Install Docker 45 | 46 | Rufio uses Docker for protocol buffer code generation, container image builds and for the Ruby client example. 47 | Most versions of Docker will work. 48 | 49 | > The items below are nice to haves, but not hard requirements for development 50 | 51 | 1. Install golangci-lint 52 | 53 | [golangci-lint](https://golangci-lint.run/usage/install/) is used in CI for lint checking and should be run locally before creating a PR. 54 | 55 | ## Pull Requests 56 | 57 | ### Branching strategy 58 | 59 | Rufio uses a fork and pull request model. 60 | See this [doc](https://guides.github.com/activities/forking/) for more details. 61 | 62 | ### Quality 63 | 64 | #### CI 65 | 66 | Rufio uses GitHub Actions for CI. 67 | The workflow is found in [.github/workflows/ci.yaml](.github/workflows/ci.yaml). 68 | It is run for each commit and PR. 69 | The container image building only happens once a PR is merged into the main line. 70 | 71 | #### Code coverage 72 | 73 | Rufio does run code coverage with each PR. 74 | Coverage thresholds are not currently enforced. 75 | It is always nice and very welcomed to add tests and keep or increase the code coverage percentage. 76 | 77 | ### Pre PR Checklist 78 | 79 | This checklist is a helper to make sure there's no gotchas that come up when you submit a PR. 80 | 81 | - [ ] You've reviewed the [code of conduct](#Code-of-Conduct) 82 | - [ ] All commits are DCO signed off 83 | - [ ] Code is [formatted and linted](#Linting) 84 | - [ ] Code [builds](#Building) successfully 85 | - [ ] All tests are [passing](#Unit-testing) 86 | - [ ] Code coverage [percentage](#Code-coverage). (main line is the base with which to compare) 87 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Build the manager binary 2 | FROM --platform=$BUILDPLATFORM golang:1.23 AS builder 3 | 4 | WORKDIR /workspace 5 | 6 | # Copy the Go Modules manifests 7 | COPY go.mod go.mod 8 | COPY go.sum go.sum 9 | # cache deps before building and copying source so that we don't need to re-download as much 10 | # and so that source changes don't invalidate our downloaded layer 11 | RUN go mod download 12 | 13 | # Copy the go source 14 | COPY ./ ./ 15 | 16 | # Define args for the target platform so we can identify the binary in the Docker context. 17 | # These args are populated by Docker. The values should match Go's GOOS and GOARCH values for 18 | # the respective os/platform. 19 | ARG TARGETARCH 20 | ARG TARGETOS 21 | 22 | # Build 23 | RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build -a -o manager main.go 24 | 25 | FROM alpine:3.21 26 | 27 | # Install ipmitool required by the third party BMC lib. 28 | RUN apk add --upgrade ipmitool=1.8.19-r1 29 | 30 | COPY --from=builder /workspace/manager . 31 | 32 | USER 65532:65532 33 | ENTRYPOINT ["/manager"] 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022 The Tinkerbell Authors. All rights reserved. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | # Image URL to use all building/pushing image targets 3 | IMG ?= quay.io/tinkerbell/rufio:latest 4 | # ENVTEST_K8S_VERSION refers to the version of kubebuilder assets to be downloaded by envtest binary. 5 | ENVTEST_K8S_VERSION = 1.31.0 6 | 7 | # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) 8 | ifeq (,$(shell go env GOBIN)) 9 | GOBIN=$(shell go env GOPATH)/bin 10 | else 11 | GOBIN=$(shell go env GOBIN) 12 | endif 13 | 14 | # Setting SHELL to bash allows bash commands to be executed by recipes. 15 | # This is a requirement for 'setup-envtest.sh' in the test target. 16 | # Options are set to exit when a recipe line exits non-zero or a piped command fails. 17 | SHELL = /usr/bin/env bash -o pipefail 18 | .SHELLFLAGS = -ec 19 | 20 | ##@ General 21 | 22 | # The help target prints out all targets with their descriptions organized 23 | # beneath their categories. The categories are represented by '##@' and the 24 | # target descriptions by '##'. The awk commands is responsible for reading the 25 | # entire set of makefiles included in this invocation, looking for lines of the 26 | # file as xyz: ## something, and then pretty-format the target and help. Then, 27 | # if there's a line with ##@ something, that gets pretty-printed as a category. 28 | # More info on the usage of ANSI control characters for terminal formatting: 29 | # https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters 30 | # More info on the awk command: 31 | # http://linuxcommand.org/lc3_adv_awk.php 32 | 33 | .PHONY: help 34 | help: ## Display this help. 35 | @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\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) 36 | 37 | include lint.mk 38 | 39 | .PHONY: all 40 | all: build 41 | 42 | ##@ Development 43 | 44 | .PHONY: manifests 45 | manifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and CustomResourceDefinition objects. 46 | $(CONTROLLER_GEN) rbac:roleName=manager-role crd webhook paths="./..." output:crd:artifacts:config=config/crd/bases 47 | 48 | .PHONY: generate 49 | generate: controller-gen ## Generate code containing DeepCopy, DeepCopyInto, and DeepCopyObject method implementations. 50 | $(CONTROLLER_GEN) object:headerFile="hack/boilerplate.go.txt" paths="./..." 51 | 52 | .PHONY: fmt 53 | fmt: goimports ## Run go fmt against code. 54 | go fmt ./... 55 | $(GOIMPORTS) -w . 56 | 57 | .PHONY: vet 58 | vet: ## Run go vet against code. 59 | go vet ./... 60 | 61 | .PHONY: test 62 | test: manifests generate ## Run unit tests. 63 | go test -v ./... -coverprofile cover.out 64 | 65 | .PHONY: cover 66 | cover: test ## Run unit tests with coverage report 67 | go tool cover -func=cover.out 68 | 69 | .PHONY: integration-test 70 | integration-test: manifests generate fmt vet envtest ## Run integration tests. 71 | KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) -p path)" go test ./... -coverprofile cover.out -tags=integration 72 | 73 | ##@ Build 74 | 75 | .PHONY: build 76 | build: generate fmt vet ## Build manager binary. 77 | go build -o bin/manager main.go 78 | 79 | .PHONY: run 80 | run: manifests generate fmt vet ## Run a controller from your host. 81 | go run ./main.go 82 | 83 | .PHONY: docker-build 84 | docker-build: ## Build docker image with the manager. 85 | docker build -t ${IMG} . 86 | 87 | .PHONY: docker-push 88 | docker-push: ## Push docker image with the manager. 89 | docker push ${IMG} 90 | 91 | ##@ Deployment 92 | 93 | ifndef ignore-not-found 94 | ignore-not-found = false 95 | endif 96 | 97 | .PHONY: install 98 | install: manifests kustomize ## Install CRDs into the K8s cluster specified in ~/.kube/config. 99 | $(KUSTOMIZE) build config/crd | kubectl apply -f - 100 | 101 | .PHONY: uninstall 102 | 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. 103 | $(KUSTOMIZE) build config/crd | kubectl delete --ignore-not-found=$(ignore-not-found) -f - 104 | 105 | .PHONY: deploy 106 | deploy: manifests kustomize ## Deploy controller to the K8s cluster specified in ~/.kube/config. 107 | cd config/manager && $(KUSTOMIZE) edit set image controller=${IMG} 108 | $(KUSTOMIZE) build config/default | kubectl apply -f - 109 | 110 | .PHONY: undeploy 111 | 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. 112 | $(KUSTOMIZE) build config/default | kubectl delete --ignore-not-found=$(ignore-not-found) -f - 113 | 114 | CONTROLLER_GEN = $(shell pwd)/bin/controller-gen 115 | .PHONY: controller-gen 116 | controller-gen: ## Download controller-gen locally if necessary. 117 | $(call go-get-tool,$(CONTROLLER_GEN),sigs.k8s.io/controller-tools/cmd/controller-gen@v0.16.4) 118 | 119 | KUSTOMIZE = $(shell pwd)/bin/kustomize 120 | .PHONY: kustomize 121 | kustomize: ## Download kustomize locally if necessary. 122 | $(call go-get-tool,$(KUSTOMIZE),sigs.k8s.io/kustomize/kustomize/v5@v5.4.2) 123 | 124 | ENVTEST = $(shell pwd)/bin/setup-envtest 125 | .PHONY: envtest 126 | envtest: ## Download envtest-setup locally if necessary. 127 | $(call go-get-tool,$(ENVTEST),sigs.k8s.io/controller-runtime/tools/setup-envtest@latest) 128 | 129 | GOIMPORTS = $(shell pwd)/bin/goimports 130 | .PHONY: goimports 131 | goimports: ## Download goimports locally if necessary. 132 | $(call go-get-tool,$(GOIMPORTS),golang.org/x/tools/cmd/goimports@latest) 133 | 134 | ##@ Release 135 | 136 | RELEASE_TAG := $(shell git describe --abbrev=0 2>/dev/null) 137 | RELEASE_DIR ?= out/release 138 | 139 | $(RELEASE_DIR): 140 | mkdir -p $(RELEASE_DIR)/ 141 | 142 | .PHONY: release-manifests 143 | release-manifests: manifests kustomize $(RELEASE_DIR) ## Builds the manifests to publish with a release 144 | $(KUSTOMIZE) build config/default > $(RELEASE_DIR)/manifest.yaml 145 | 146 | ##@ Cleanup 147 | 148 | .PHONY: clean 149 | clean: clean-bin clean-release ## Remove all generated files 150 | 151 | .PHONY: clean-bin 152 | clean-bin: ## Remove all generated binaries 153 | rm -rf bin 154 | 155 | .PHONY: clean-release 156 | clean-release: ## Remove the release folder 157 | rm -rf $(RELEASE_DIR) 158 | 159 | # go-get-tool will 'go get' any package $2 and install it to $1. 160 | PROJECT_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST)))) 161 | define go-get-tool 162 | @[ -f $(1) ] || { \ 163 | set -e ;\ 164 | TMP_DIR=$$(mktemp -d) ;\ 165 | cd $$TMP_DIR ;\ 166 | go mod init tmp ;\ 167 | echo "Downloading $(2)" ;\ 168 | GOBIN=$(PROJECT_DIR)/bin go install $(2) ;\ 169 | rm -rf $$TMP_DIR ;\ 170 | } 171 | endef 172 | 173 | ##@ Docs 174 | 175 | puml: ## Generate PlantUML diagrams. 176 | @for pml in $$(find . -name '*.puml'); do \ 177 | echo "Generating $$(basename $$pml)" ; \ 178 | filename=$$(basename $$pml .puml) ; \ 179 | plantuml -tpng $$pml ; \ 180 | done 181 | -------------------------------------------------------------------------------- /PROJECT: -------------------------------------------------------------------------------- 1 | domain: tinkerbell.org 2 | layout: 3 | - go.kubebuilder.io/v3 4 | projectName: rufio 5 | repo: github.com/tinkerbell/rufio 6 | resources: 7 | - api: 8 | crdVersion: v1 9 | namespaced: true 10 | controller: true 11 | domain: tinkerbell.org 12 | group: bmc 13 | kind: Machine 14 | path: github.com/tinkerbell/rufio/api/v1alpha1 15 | version: v1alpha1 16 | - api: 17 | crdVersion: v1 18 | namespaced: true 19 | controller: true 20 | domain: tinkerbell.org 21 | group: bmc 22 | kind: Job 23 | path: github.com/tinkerbell/rufio/api/v1alpha1 24 | version: v1alpha1 25 | - api: 26 | crdVersion: v1 27 | namespaced: true 28 | controller: true 29 | domain: tinkerbell.org 30 | group: bmc 31 | kind: Task 32 | path: github.com/tinkerbell/rufio/api/v1alpha1 33 | version: v1alpha1 34 | version: "3" 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > [!IMPORTANT] 2 | > The Rufio repo has been deprecated. All functionality has been moved to https://github.com/tinkerbell/tinkerbell. 3 | > For more details, see the roadmap issue [#41](https://github.com/tinkerbell/roadmap/issues/41). 4 | > This repository is scheduled for archive by the end of 2025. 5 | 6 | # Rufio 7 | 8 | ![For each commit and PR](https://github.com/tinkerbell/rufio/workflows/For%20each%20commit%20and%20PR/badge.svg) 9 | [![codecov](https://codecov.io/gh/tinkerbell/rufio/branch/main/graph/badge.svg)](https://codecov.io/gh/tinkerbell/rufio) 10 | 11 | ## Description 12 | 13 | **R**ufio 14 | **U**ses 15 | **F**ancy 16 | **I**PMI 17 | **O**perations 18 | 19 | Rufio is a Kubernetes controller for managing baseboard management controllers in a Tinkerbell context. 20 | 21 | ### Goals 22 | 23 | * Provide baseboard management controller operations necessary for bare metal provisioning. 24 | * Provide insight into baseboard management information that is useful in bare metal provisioning contexts. 25 | * Integrate seamlessly with the Kubernetes capable components of Tinkerbell. 26 | 27 | ### Non-goals 28 | 29 | * Providing non-provisioning related baseboard management controller capabilities. 30 | 31 | ## Contributing 32 | 33 | See the contributors guide [here](CONTRIBUTING.md). 34 | 35 | ## Website 36 | 37 | For complete documentation, please visit the Tinkerbell project hosted at [tinkerbell.org](https://tinkerbell.org). 38 | -------------------------------------------------------------------------------- /REALEASE.md: -------------------------------------------------------------------------------- 1 | # Releasing 2 | 3 | ## Process 4 | 5 | For version v0.x.y: 6 | 7 | 1. Create the annotated tag 8 | > NOTE: To use your GPG signature when pushing the tag, use `SIGN_TAG=1 ./contrib/tag-release.sh v0.x.y` instead) 9 | - `./contrib/tag-release.sh v0.x.y` 10 | 1. Push the tag to the GitHub repository. This will automatically trigger a [Github Action](https://github.com/tinkerbell/hegel/actions) to create a release. 11 | > NOTE: `origin` should be the name of the remote pointing to `github.com/tinkerbell/hegel` 12 | - `git push origin v0.x.y` 13 | 1. Review the release on GitHub. 14 | 15 | ### Permissions 16 | 17 | Releasing requires a particular set of permissions. 18 | 19 | - Tag push access to the GitHub repository 20 | -------------------------------------------------------------------------------- /api/v1alpha1/action.go: -------------------------------------------------------------------------------- 1 | package v1alpha1 2 | 3 | // PowerAction represents the power control operation on the baseboard management. 4 | type PowerAction string 5 | 6 | const ( 7 | PowerOn PowerAction = "on" 8 | PowerHardOff PowerAction = "off" 9 | PowerSoftOff PowerAction = "soft" 10 | PowerCycle PowerAction = "cycle" 11 | PowerReset PowerAction = "reset" 12 | PowerStatus PowerAction = "status" 13 | ) 14 | 15 | // Pointer provides an easy way to retrieve the power action as a pointer for use in job 16 | // tasks. 17 | func (p PowerAction) Ptr() *PowerAction { 18 | return &p 19 | } 20 | 21 | // BootDevice represents boot device of the Machine. 22 | type BootDevice string 23 | 24 | const ( 25 | PXE BootDevice = "pxe" 26 | Disk BootDevice = "disk" 27 | BIOS BootDevice = "bios" 28 | CDROM BootDevice = "cdrom" 29 | Safe BootDevice = "safe" 30 | ) 31 | 32 | // OnTimeBootDeviceAction represents a baseboard management one time set boot device operation. 33 | type OneTimeBootDeviceAction struct { 34 | // Devices represents the boot devices, in order for setting one time boot. 35 | // Currently only the first device in the slice is used to set one time boot. 36 | Devices []BootDevice `json:"device"` 37 | 38 | // EFIBoot instructs the machine to use EFI boot. 39 | EFIBoot bool `json:"efiBoot,omitempty"` 40 | } 41 | 42 | type VirtualMediaKind string 43 | 44 | const ( 45 | // VirtualMediaCD represents a virtual CD-ROM. 46 | VirtualMediaCD VirtualMediaKind = "CD" 47 | ) 48 | 49 | // VirtualMediaAction represents a virtual media action. 50 | type VirtualMediaAction struct { 51 | // mediaURL represents the URL of the image to be inserted into the virtual media, or empty to 52 | // eject media. 53 | MediaURL string `json:"mediaURL,omitempty"` 54 | 55 | Kind VirtualMediaKind `json:"kind"` 56 | } 57 | -------------------------------------------------------------------------------- /api/v1alpha1/groupversion_info.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Tinkerbell. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | // Package v1alpha1 contains API Schema definitions for the bmc v1alpha1 API group 18 | // +kubebuilder:object:generate=true 19 | // +groupName=bmc.tinkerbell.org 20 | package v1alpha1 21 | 22 | import ( 23 | "k8s.io/apimachinery/pkg/runtime/schema" 24 | "sigs.k8s.io/controller-runtime/pkg/scheme" 25 | ) 26 | 27 | var ( 28 | // GroupVersion is group version used to register these objects. 29 | GroupVersion = schema.GroupVersion{Group: "bmc.tinkerbell.org", Version: "v1alpha1"} 30 | 31 | // SchemeBuilder is used to add go types to the GroupVersionKind scheme. 32 | SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} 33 | 34 | // AddToScheme adds the types in this group-version to the given scheme. 35 | AddToScheme = SchemeBuilder.AddToScheme 36 | ) 37 | -------------------------------------------------------------------------------- /api/v1alpha1/job.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Tinkerbell. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package v1alpha1 18 | 19 | import ( 20 | "fmt" 21 | 22 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 23 | ) 24 | 25 | // JobConditionType represents the condition of the BMC Job. 26 | type JobConditionType string 27 | 28 | const ( 29 | // JobCompleted represents successful completion of the BMC Job tasks. 30 | JobCompleted JobConditionType = "Completed" 31 | // JobFailed represents failure in BMC job execution. 32 | JobFailed JobConditionType = "Failed" 33 | // JobRunning represents a currently executing BMC job. 34 | JobRunning JobConditionType = "Running" 35 | ) 36 | 37 | // MachineRef is used to reference a Machine object. 38 | type MachineRef struct { 39 | // Name of the Machine. 40 | Name string `json:"name"` 41 | 42 | // Namespace the Machine resides in. 43 | Namespace string `json:"namespace"` 44 | } 45 | 46 | // JobSpec defines the desired state of Job. 47 | type JobSpec struct { 48 | // MachineRef represents the Machine resource to execute the job. 49 | // All the tasks in the job are executed for the same Machine. 50 | MachineRef MachineRef `json:"machineRef"` 51 | 52 | // Tasks represents a list of baseboard management actions to be executed. 53 | // The tasks are executed sequentially. Controller waits for one task to complete before executing the next. 54 | // If a single task fails, job execution stops and sets condition Failed. 55 | // Condition Completed is set only if all the tasks were successful. 56 | // +kubebuilder:validation:MinItems=1 57 | // +kubebuilder:validation:UniqueItems=false 58 | Tasks []Action `json:"tasks"` 59 | } 60 | 61 | // JobStatus defines the observed state of Job. 62 | type JobStatus struct { 63 | // Conditions represents the latest available observations of an object's current state. 64 | // +optional 65 | Conditions []JobCondition `json:"conditions,omitempty"` 66 | 67 | // StartTime represents time when the Job controller started processing a job. 68 | // +optional 69 | StartTime *metav1.Time `json:"startTime,omitempty"` 70 | 71 | // CompletionTime represents time when the job was completed. 72 | // The completion time is only set when the job finishes successfully. 73 | // +optional 74 | CompletionTime *metav1.Time `json:"completionTime,omitempty"` 75 | } 76 | 77 | type JobCondition struct { 78 | // Type of the Job condition. 79 | Type JobConditionType `json:"type"` 80 | 81 | // Status is the status of the Job condition. 82 | // Can be True or False. 83 | Status ConditionStatus `json:"status"` 84 | 85 | // Message represents human readable message indicating details about last transition. 86 | // +optional 87 | Message string `json:"message,omitempty"` 88 | } 89 | 90 | // +kubebuilder:object:generate=false 91 | type JobSetConditionOption func(*JobCondition) 92 | 93 | // SetCondition applies the cType condition to bmj. If the condition already exists, 94 | // it is updated. 95 | func (j *Job) SetCondition(cType JobConditionType, status ConditionStatus, opts ...JobSetConditionOption) { 96 | var condition *JobCondition 97 | 98 | // Check if there's an existing condition. 99 | for i, c := range j.Status.Conditions { 100 | if c.Type == cType { 101 | condition = &j.Status.Conditions[i] 102 | break 103 | } 104 | } 105 | 106 | // We didn't find an existing condition so create a new one and append it. 107 | if condition == nil { 108 | j.Status.Conditions = append(j.Status.Conditions, JobCondition{ 109 | Type: cType, 110 | }) 111 | condition = &j.Status.Conditions[len(j.Status.Conditions)-1] 112 | } 113 | 114 | condition.Status = status 115 | for _, opt := range opts { 116 | opt(condition) 117 | } 118 | } 119 | 120 | // WithJobConditionMessage sets message m to the JobCondition. 121 | func WithJobConditionMessage(m string) JobSetConditionOption { 122 | return func(c *JobCondition) { 123 | c.Message = m 124 | } 125 | } 126 | 127 | // HasCondition checks if the cType condition is present with status cStatus on a bmj. 128 | func (j *Job) HasCondition(cType JobConditionType, cStatus ConditionStatus) bool { 129 | for _, c := range j.Status.Conditions { 130 | if c.Type == cType { 131 | return c.Status == cStatus 132 | } 133 | } 134 | 135 | return false 136 | } 137 | 138 | // FormatTaskName returns a Task name based on Job name. 139 | func FormatTaskName(job Job, n int) string { 140 | return fmt.Sprintf("%s-task-%d", job.Name, n) 141 | } 142 | 143 | //+kubebuilder:object:root=true 144 | //+kubebuilder:subresource:status 145 | //+kubebuilder:resource:path=jobs,scope=Namespaced,categories=tinkerbell,singular=job,shortName=j 146 | 147 | // Job is the Schema for the bmcjobs API. 148 | type Job struct { 149 | metav1.TypeMeta `json:""` 150 | metav1.ObjectMeta `json:"metadata,omitempty"` 151 | 152 | Spec JobSpec `json:"spec,omitempty"` 153 | Status JobStatus `json:"status,omitempty"` 154 | } 155 | 156 | //+kubebuilder:object:root=true 157 | 158 | // JobList contains a list of Job. 159 | type JobList struct { 160 | metav1.TypeMeta `json:""` 161 | metav1.ListMeta `json:"metadata,omitempty"` 162 | Items []Job `json:"items"` 163 | } 164 | 165 | func init() { 166 | SchemeBuilder.Register(&Job{}, &JobList{}) 167 | } 168 | -------------------------------------------------------------------------------- /api/v1alpha1/machine.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Tinkerbell. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package v1alpha1 18 | 19 | import ( 20 | corev1 "k8s.io/api/core/v1" 21 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 22 | ) 23 | 24 | // PowerState represents power state of a Machine. 25 | type PowerState string 26 | 27 | const ( 28 | On PowerState = "on" 29 | Off PowerState = "off" 30 | Unknown PowerState = "unknown" 31 | ) 32 | 33 | // MachineConditionType represents the condition of the Machine. 34 | type MachineConditionType string 35 | 36 | const ( 37 | // Contactable defines that a connection can be made to the Machine. 38 | Contactable MachineConditionType = "Contactable" 39 | ) 40 | 41 | // ConditionStatus represents the status of a Condition. 42 | type ConditionStatus string 43 | 44 | const ( 45 | ConditionTrue ConditionStatus = "True" 46 | ConditionFalse ConditionStatus = "False" 47 | ) 48 | 49 | // MachineSpec defines desired machine state. 50 | type MachineSpec struct { 51 | // Connection contains connection data for a Baseboard Management Controller. 52 | Connection Connection `json:"connection"` 53 | } 54 | 55 | // ProviderName is the bmclib specific provider name. Names are case insensitive. 56 | // +kubebuilder:validation:Pattern=(?i)^(ipmitool|asrockrack|gofish|IntelAMT|dell|supermicro|openbmc)$ 57 | type ProviderName string 58 | 59 | func (p ProviderName) String() string { 60 | return string(p) 61 | } 62 | 63 | // ProviderOptions hold provider specific configurable options. 64 | type ProviderOptions struct { 65 | // PreferredOrder allows customizing the order that BMC providers are called. 66 | // Providers added to this list will be moved to the front of the default order. 67 | // Provider names are case insensitive. 68 | // The default order is: ipmitool, asrockrack, gofish, intelamt, dell, supermicro, openbmc. 69 | // +optional 70 | PreferredOrder []ProviderName `json:"preferredOrder,omitempty"` 71 | // IntelAMT contains the options to customize the IntelAMT provider. 72 | // +optional 73 | IntelAMT *IntelAMTOptions `json:"intelAMT,omitempty"` 74 | 75 | // IPMITOOL contains the options to customize the Ipmitool provider. 76 | // +optional 77 | IPMITOOL *IPMITOOLOptions `json:"ipmitool,omitempty"` 78 | 79 | // Redfish contains the options to customize the Redfish provider. 80 | // +optional 81 | Redfish *RedfishOptions `json:"redfish,omitempty"` 82 | 83 | // RPC contains the options to customize the RPC provider. 84 | // +optional 85 | RPC *RPCOptions `json:"rpc,omitempty"` 86 | } 87 | 88 | // Connection contains connection data for a Baseboard Management Controller. 89 | type Connection struct { 90 | // Host is the host IP address or hostname of the Machine. 91 | // +kubebuilder:validation:MinLength=1 92 | Host string `json:"host"` 93 | 94 | // Port is the port number for connecting with the Machine. 95 | // +kubebuilder:default:=623 96 | // +optional 97 | Port int `json:"port"` 98 | 99 | // AuthSecretRef is the SecretReference that contains authentication information of the Machine. 100 | // The Secret must contain username and password keys. This is optional as it is not required when using 101 | // the RPC provider. 102 | // +optional 103 | AuthSecretRef corev1.SecretReference `json:"authSecretRef"` 104 | 105 | // InsecureTLS specifies trusted TLS connections. 106 | InsecureTLS bool `json:"insecureTLS"` 107 | 108 | // ProviderOptions contains provider specific options. 109 | // +optional 110 | ProviderOptions *ProviderOptions `json:"providerOptions,omitempty"` 111 | } 112 | 113 | // MachineStatus defines the observed state of Machine. 114 | type MachineStatus struct { 115 | // Power is the current power state of the Machine. 116 | // +kubebuilder:validation:Enum=on;off;unknown 117 | // +optional 118 | Power PowerState `json:"powerState,omitempty"` 119 | 120 | // Conditions represents the latest available observations of an object's current state. 121 | // +optional 122 | Conditions []MachineCondition `json:"conditions,omitempty"` 123 | } 124 | 125 | // MachineCondition defines an observed condition of a Machine. 126 | type MachineCondition struct { 127 | // Type of the Machine condition. 128 | Type MachineConditionType `json:"type"` 129 | 130 | // Status of the condition. 131 | Status ConditionStatus `json:"status"` 132 | 133 | // LastUpdateTime of the condition. 134 | LastUpdateTime metav1.Time `json:"lastUpdateTime,omitempty"` 135 | 136 | // Message is a human readable message indicating with details of the last transition. 137 | // +optional 138 | Message string `json:"message,omitempty"` 139 | } 140 | 141 | // +kubebuilder:object:generate=false 142 | type MachineSetConditionOption func(*MachineCondition) 143 | 144 | // SetCondition applies the cType condition to bm. If the condition already exists, 145 | // it is updated. 146 | func (bm *Machine) SetCondition(cType MachineConditionType, status ConditionStatus, opts ...MachineSetConditionOption) { 147 | var condition *MachineCondition 148 | 149 | // Check if there's an existing condition. 150 | for i, c := range bm.Status.Conditions { 151 | if c.Type == cType { 152 | condition = &bm.Status.Conditions[i] 153 | break 154 | } 155 | } 156 | 157 | // We didn't find an existing condition so create a new one and append it. 158 | if condition == nil { 159 | bm.Status.Conditions = append(bm.Status.Conditions, MachineCondition{ 160 | Type: cType, 161 | }) 162 | condition = &bm.Status.Conditions[len(bm.Status.Conditions)-1] 163 | } 164 | 165 | if condition.Status != status { 166 | condition.Status = status 167 | condition.LastUpdateTime = metav1.Now() 168 | } 169 | 170 | for _, opt := range opts { 171 | opt(condition) 172 | } 173 | } 174 | 175 | // WithMachineConditionMessage sets message m to the MachineCondition. 176 | func WithMachineConditionMessage(m string) MachineSetConditionOption { 177 | return func(c *MachineCondition) { 178 | c.Message = m 179 | } 180 | } 181 | 182 | //+kubebuilder:object:root=true 183 | //+kubebuilder:subresource:status 184 | //+kubebuilder:resource:path=machines,scope=Namespaced,categories=tinkerbell,singular=machine 185 | // +kubebuilder:metadata:labels=clusterctl.cluster.x-k8s.io= 186 | // +kubebuilder:metadata:labels=clusterctl.cluster.x-k8s.io/move= 187 | 188 | // Machine is the Schema for the machines API. 189 | type Machine struct { 190 | metav1.TypeMeta `json:""` 191 | metav1.ObjectMeta `json:"metadata,omitempty"` 192 | 193 | Spec MachineSpec `json:"spec,omitempty"` 194 | Status MachineStatus `json:"status,omitempty"` 195 | } 196 | 197 | //+kubebuilder:object:root=true 198 | 199 | // MachineList contains a list of Machines. 200 | type MachineList struct { 201 | metav1.TypeMeta `json:""` 202 | metav1.ListMeta `json:"metadata,omitempty"` 203 | Items []Machine `json:"items"` 204 | } 205 | 206 | func init() { 207 | SchemeBuilder.Register(&Machine{}, &MachineList{}) 208 | } 209 | -------------------------------------------------------------------------------- /api/v1alpha1/provider_opts.go: -------------------------------------------------------------------------------- 1 | package v1alpha1 2 | 3 | import ( 4 | "net/http" 5 | 6 | corev1 "k8s.io/api/core/v1" 7 | ) 8 | 9 | // RedfishOptions contains the redfish provider specific options. 10 | type RedfishOptions struct { 11 | // Port that redfish will use for calls. 12 | // +optional 13 | Port int `json:"port,omitempty"` 14 | // UseBasicAuth for redfish calls. The default is false which means token based auth is used. 15 | // +optional 16 | UseBasicAuth bool `json:"useBasicAuth,omitempty"` 17 | // SystemName is the name of the system to use for redfish calls. 18 | // With redfish implementations that manage multiple systems via a single endpoint, this allows for specifying the system to manage. 19 | // +optional 20 | SystemName string `json:"systemName,omitempty"` 21 | } 22 | 23 | // IPMITOOLOptions contains the ipmitool provider specific options. 24 | type IPMITOOLOptions struct { 25 | // Port that ipmitool will use for calls. 26 | // +optional 27 | Port int `json:"port,omitempty"` 28 | // CipherSuite that ipmitool will use for calls. 29 | // +optional 30 | CipherSuite string `json:"cipherSuite,omitempty"` 31 | } 32 | 33 | // IntelAMTOptions contains the intelAMT provider specific options. 34 | type IntelAMTOptions struct { 35 | // Port that intelAMT will use for calls. 36 | // +optional 37 | Port int `json:"port,omitempty"` 38 | 39 | // HostScheme determines whether to use http or https for intelAMT calls. 40 | // +optional 41 | // +kubebuilder:validation:Enum=http;https 42 | // +kubebuilder:default:=http 43 | HostScheme string `json:"hostScheme,omitempty"` 44 | } 45 | 46 | // HMACAlgorithm is a type for HMAC algorithms. 47 | type HMACAlgorithm string 48 | 49 | // HMACSecrets holds per Algorithm slice secrets. 50 | // These secrets will be used to create HMAC signatures. 51 | type HMACSecrets map[HMACAlgorithm][]corev1.SecretReference 52 | 53 | // RPCOptions defines the configurable options to use when sending rpc notifications. 54 | type RPCOptions struct { 55 | // ConsumerURL is the URL where an rpc consumer/listener is running 56 | // and to which we will send and receive all notifications. 57 | ConsumerURL string `json:"consumerURL"` 58 | // LogNotificationsDisabled determines whether responses from rpc consumer/listeners will be logged or not. 59 | // +optional 60 | LogNotificationsDisabled bool `json:"logNotificationsDisabled,omitempty"` 61 | // Request is the options used to create the rpc HTTP request. 62 | // +optional 63 | Request *RequestOpts `json:"request,omitempty"` 64 | // Signature is the options used for adding an HMAC signature to an HTTP request. 65 | // +optional 66 | Signature *SignatureOpts `json:"signature,omitempty"` 67 | // HMAC is the options used to create a HMAC signature. 68 | // +optional 69 | HMAC *HMACOpts `json:"hmac,omitempty"` 70 | // Experimental options. 71 | // +optional 72 | Experimental *ExperimentalOpts `json:"experimental,omitempty"` 73 | } 74 | 75 | // RequestOpts are the options used when creating an HTTP request. 76 | type RequestOpts struct { 77 | // HTTPContentType is the content type to use for the rpc request notification. 78 | // +optional 79 | HTTPContentType string `json:"httpContentType,omitempty"` 80 | // HTTPMethod is the HTTP method to use for the rpc request notification. 81 | // +optional 82 | HTTPMethod string `json:"httpMethod,omitempty"` 83 | // StaticHeaders are predefined headers that will be added to every request. 84 | // +optional 85 | StaticHeaders http.Header `json:"staticHeaders,omitempty"` 86 | // TimestampFormat is the time format for the timestamp header. 87 | // +optional 88 | TimestampFormat string `json:"timestampFormat,omitempty"` 89 | // TimestampHeader is the header name that should contain the timestamp. Example: X-BMCLIB-Timestamp 90 | // +optional 91 | TimestampHeader string `json:"timestampHeader,omitempty"` 92 | } 93 | 94 | // SignatureOpts are the options used for adding an HMAC signature to an HTTP request. 95 | type SignatureOpts struct { 96 | // HeaderName is the header name that should contain the signature(s). Example: X-BMCLIB-Signature 97 | // +optional 98 | HeaderName string `json:"headerName,omitempty"` 99 | // AppendAlgoToHeaderDisabled decides whether to append the algorithm to the signature header or not. 100 | // Example: X-BMCLIB-Signature becomes X-BMCLIB-Signature-256 101 | // When set to true, a header will be added for each algorithm. Example: X-BMCLIB-Signature-256 and X-BMCLIB-Signature-512 102 | // +optional 103 | AppendAlgoToHeaderDisabled bool `json:"appendAlgoToHeaderDisabled,omitempty"` 104 | // IncludedPayloadHeaders are headers whose values will be included in the signature payload. Example: X-BMCLIB-My-Custom-Header 105 | // All headers will be deduplicated. 106 | // +optional 107 | IncludedPayloadHeaders []string `json:"includedPayloadHeaders,omitempty"` 108 | } 109 | 110 | // HMACOpts are the options used to create an HMAC signature. 111 | type HMACOpts struct { 112 | // PrefixSigDisabled determines whether the algorithm will be prefixed to the signature. Example: sha256=abc123 113 | // +optional 114 | PrefixSigDisabled bool `json:"prefixSigDisabled,omitempty"` 115 | // Secrets are a map of algorithms to secrets used for signing. 116 | // +optional 117 | Secrets HMACSecrets `json:"secrets,omitempty"` 118 | } 119 | 120 | // ExperimentalOpts are options we're still learning about and should be used carefully. 121 | type ExperimentalOpts struct { 122 | // CustomRequestPayload must be in json. 123 | // +optional 124 | CustomRequestPayload string `json:"customRequestPayload,omitempty"` 125 | // DotPath is the path to the json object where the bmclib RequestPayload{} struct will be embedded. For example: object.data.body 126 | // +optional 127 | DotPath string `json:"dotPath,omitempty"` 128 | } 129 | -------------------------------------------------------------------------------- /api/v1alpha1/task.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Tinkerbell. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package v1alpha1 18 | 19 | import ( 20 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 21 | ) 22 | 23 | // TaskConditionType represents the condition type on for Tasks. 24 | type TaskConditionType string 25 | 26 | const ( 27 | // TaskCompleted represents successful completion of the Task. 28 | TaskCompleted TaskConditionType = "Completed" 29 | // TaskFailed represents failure in Task execution. 30 | TaskFailed TaskConditionType = "Failed" 31 | ) 32 | 33 | // TaskSpec defines the desired state of Task. 34 | type TaskSpec struct { 35 | // Task defines the specific action to be performed. 36 | Task Action `json:"task"` 37 | 38 | // Connection represents the Machine connectivity information. 39 | Connection Connection `json:"connection,omitempty"` 40 | } 41 | 42 | // Action represents the action to be performed. 43 | // A single task can only perform one type of action. 44 | // For example either PowerAction or OneTimeBootDeviceAction. 45 | // +kubebuilder:validation:MaxProperties:=1 46 | type Action struct { 47 | // PowerAction represents a baseboard management power operation. 48 | // +kubebuilder:validation:Enum=on;off;soft;status;cycle;reset 49 | PowerAction *PowerAction `json:"powerAction,omitempty"` 50 | 51 | // OneTimeBootDeviceAction represents a baseboard management one time set boot device operation. 52 | OneTimeBootDeviceAction *OneTimeBootDeviceAction `json:"oneTimeBootDeviceAction,omitempty"` 53 | 54 | // VirtualMediaAction represents a baseboard management virtual media insert/eject. 55 | VirtualMediaAction *VirtualMediaAction `json:"virtualMediaAction,omitempty"` 56 | } 57 | 58 | // TaskStatus defines the observed state of Task. 59 | type TaskStatus struct { 60 | // Conditions represents the latest available observations of an object's current state. 61 | // +optional 62 | Conditions []TaskCondition `json:"conditions,omitempty"` 63 | 64 | // StartTime represents time when the Task started processing. 65 | // +optional 66 | StartTime *metav1.Time `json:"startTime,omitempty"` 67 | 68 | // CompletionTime represents time when the task was completed. 69 | // The completion time is only set when the task finishes successfully. 70 | // +optional 71 | CompletionTime *metav1.Time `json:"completionTime,omitempty"` 72 | } 73 | 74 | type TaskCondition struct { 75 | // Type of the Task condition. 76 | Type TaskConditionType `json:"type"` 77 | 78 | // Status is the status of the Task condition. 79 | // Can be True or False. 80 | Status ConditionStatus `json:"status"` 81 | 82 | // Message represents human readable message indicating details about last transition. 83 | // +optional 84 | Message string `json:"message,omitempty"` 85 | } 86 | 87 | // +kubebuilder:object:generate=false 88 | type TaskSetConditionOption func(*TaskCondition) 89 | 90 | // SetCondition applies the cType condition to bmt. If the condition already exists, 91 | // it is updated. 92 | func (t *Task) SetCondition(cType TaskConditionType, status ConditionStatus, opts ...TaskSetConditionOption) { 93 | var condition *TaskCondition 94 | 95 | // Check if there's an existing condition. 96 | for i, c := range t.Status.Conditions { 97 | if c.Type == cType { 98 | condition = &t.Status.Conditions[i] 99 | break 100 | } 101 | } 102 | 103 | // We didn't find an existing condition so create a new one and append it. 104 | if condition == nil { 105 | t.Status.Conditions = append(t.Status.Conditions, TaskCondition{ 106 | Type: cType, 107 | }) 108 | condition = &t.Status.Conditions[len(t.Status.Conditions)-1] 109 | } 110 | 111 | condition.Status = status 112 | for _, opt := range opts { 113 | opt(condition) 114 | } 115 | } 116 | 117 | // WithTaskConditionMessage sets message m to the TaskCondition. 118 | func WithTaskConditionMessage(m string) TaskSetConditionOption { 119 | return func(c *TaskCondition) { 120 | c.Message = m 121 | } 122 | } 123 | 124 | // HasCondition checks if the cType condition is present with status cStatus on a bmt. 125 | func (t *Task) HasCondition(cType TaskConditionType, cStatus ConditionStatus) bool { 126 | for _, c := range t.Status.Conditions { 127 | if c.Type == cType { 128 | return c.Status == cStatus 129 | } 130 | } 131 | 132 | return false 133 | } 134 | 135 | //+kubebuilder:object:root=true 136 | //+kubebuilder:subresource:status 137 | //+kubebuilder:resource:path=tasks,scope=Namespaced,categories=tinkerbell,singular=task,shortName=t 138 | 139 | // Task is the Schema for the Task API. 140 | type Task struct { 141 | metav1.TypeMeta `json:""` 142 | metav1.ObjectMeta `json:"metadata,omitempty"` 143 | 144 | Spec TaskSpec `json:"spec,omitempty"` 145 | Status TaskStatus `json:"status,omitempty"` 146 | } 147 | 148 | //+kubebuilder:object:root=true 149 | 150 | // TaskList contains a list of Task. 151 | type TaskList struct { 152 | metav1.TypeMeta `json:""` 153 | metav1.ListMeta `json:"metadata,omitempty"` 154 | Items []Task `json:"items"` 155 | } 156 | 157 | func init() { 158 | SchemeBuilder.Register(&Task{}, &TaskList{}) 159 | } 160 | -------------------------------------------------------------------------------- /config/crd/bases/bmc.tinkerbell.org_jobs.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: apiextensions.k8s.io/v1 3 | kind: CustomResourceDefinition 4 | metadata: 5 | annotations: 6 | controller-gen.kubebuilder.io/version: v0.16.4 7 | name: jobs.bmc.tinkerbell.org 8 | spec: 9 | group: bmc.tinkerbell.org 10 | names: 11 | categories: 12 | - tinkerbell 13 | kind: Job 14 | listKind: JobList 15 | plural: jobs 16 | shortNames: 17 | - j 18 | singular: job 19 | scope: Namespaced 20 | versions: 21 | - name: v1alpha1 22 | schema: 23 | openAPIV3Schema: 24 | description: Job is the Schema for the bmcjobs API. 25 | properties: 26 | apiVersion: 27 | description: |- 28 | APIVersion defines the versioned schema of this representation of an object. 29 | Servers should convert recognized schemas to the latest internal value, and 30 | may reject unrecognized values. 31 | More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources 32 | type: string 33 | kind: 34 | description: |- 35 | Kind is a string value representing the REST resource this object represents. 36 | Servers may infer this from the endpoint the client submits requests to. 37 | Cannot be updated. 38 | In CamelCase. 39 | More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds 40 | type: string 41 | metadata: 42 | type: object 43 | spec: 44 | description: JobSpec defines the desired state of Job. 45 | properties: 46 | machineRef: 47 | description: |- 48 | MachineRef represents the Machine resource to execute the job. 49 | All the tasks in the job are executed for the same Machine. 50 | properties: 51 | name: 52 | description: Name of the Machine. 53 | type: string 54 | namespace: 55 | description: Namespace the Machine resides in. 56 | type: string 57 | required: 58 | - name 59 | - namespace 60 | type: object 61 | tasks: 62 | description: |- 63 | Tasks represents a list of baseboard management actions to be executed. 64 | The tasks are executed sequentially. Controller waits for one task to complete before executing the next. 65 | If a single task fails, job execution stops and sets condition Failed. 66 | Condition Completed is set only if all the tasks were successful. 67 | items: 68 | description: |- 69 | Action represents the action to be performed. 70 | A single task can only perform one type of action. 71 | For example either PowerAction or OneTimeBootDeviceAction. 72 | maxProperties: 1 73 | properties: 74 | oneTimeBootDeviceAction: 75 | description: OneTimeBootDeviceAction represents a baseboard 76 | management one time set boot device operation. 77 | properties: 78 | device: 79 | description: |- 80 | Devices represents the boot devices, in order for setting one time boot. 81 | Currently only the first device in the slice is used to set one time boot. 82 | items: 83 | description: BootDevice represents boot device of the 84 | Machine. 85 | type: string 86 | type: array 87 | efiBoot: 88 | description: EFIBoot instructs the machine to use EFI boot. 89 | type: boolean 90 | required: 91 | - device 92 | type: object 93 | powerAction: 94 | description: PowerAction represents a baseboard management power 95 | operation. 96 | enum: 97 | - "on" 98 | - "off" 99 | - soft 100 | - status 101 | - cycle 102 | - reset 103 | type: string 104 | virtualMediaAction: 105 | description: VirtualMediaAction represents a baseboard management 106 | virtual media insert/eject. 107 | properties: 108 | kind: 109 | type: string 110 | mediaURL: 111 | description: |- 112 | mediaURL represents the URL of the image to be inserted into the virtual media, or empty to 113 | eject media. 114 | type: string 115 | required: 116 | - kind 117 | type: object 118 | type: object 119 | minItems: 1 120 | type: array 121 | required: 122 | - machineRef 123 | - tasks 124 | type: object 125 | status: 126 | description: JobStatus defines the observed state of Job. 127 | properties: 128 | completionTime: 129 | description: |- 130 | CompletionTime represents time when the job was completed. 131 | The completion time is only set when the job finishes successfully. 132 | format: date-time 133 | type: string 134 | conditions: 135 | description: Conditions represents the latest available observations 136 | of an object's current state. 137 | items: 138 | properties: 139 | message: 140 | description: Message represents human readable message indicating 141 | details about last transition. 142 | type: string 143 | status: 144 | description: |- 145 | Status is the status of the Job condition. 146 | Can be True or False. 147 | type: string 148 | type: 149 | description: Type of the Job condition. 150 | type: string 151 | required: 152 | - status 153 | - type 154 | type: object 155 | type: array 156 | startTime: 157 | description: StartTime represents time when the Job controller started 158 | processing a job. 159 | format: date-time 160 | type: string 161 | type: object 162 | type: object 163 | served: true 164 | storage: true 165 | subresources: 166 | status: {} 167 | -------------------------------------------------------------------------------- /config/crd/bases/bmc.tinkerbell.org_machines.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: apiextensions.k8s.io/v1 3 | kind: CustomResourceDefinition 4 | metadata: 5 | annotations: 6 | controller-gen.kubebuilder.io/version: v0.16.4 7 | labels: 8 | clusterctl.cluster.x-k8s.io: "" 9 | clusterctl.cluster.x-k8s.io/move: "" 10 | name: machines.bmc.tinkerbell.org 11 | spec: 12 | group: bmc.tinkerbell.org 13 | names: 14 | categories: 15 | - tinkerbell 16 | kind: Machine 17 | listKind: MachineList 18 | plural: machines 19 | singular: machine 20 | scope: Namespaced 21 | versions: 22 | - name: v1alpha1 23 | schema: 24 | openAPIV3Schema: 25 | description: Machine is the Schema for the machines API. 26 | properties: 27 | apiVersion: 28 | description: |- 29 | APIVersion defines the versioned schema of this representation of an object. 30 | Servers should convert recognized schemas to the latest internal value, and 31 | may reject unrecognized values. 32 | More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources 33 | type: string 34 | kind: 35 | description: |- 36 | Kind is a string value representing the REST resource this object represents. 37 | Servers may infer this from the endpoint the client submits requests to. 38 | Cannot be updated. 39 | In CamelCase. 40 | More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds 41 | type: string 42 | metadata: 43 | type: object 44 | spec: 45 | description: MachineSpec defines desired machine state. 46 | properties: 47 | connection: 48 | description: Connection contains connection data for a Baseboard Management 49 | Controller. 50 | properties: 51 | authSecretRef: 52 | description: |- 53 | AuthSecretRef is the SecretReference that contains authentication information of the Machine. 54 | The Secret must contain username and password keys. This is optional as it is not required when using 55 | the RPC provider. 56 | properties: 57 | name: 58 | description: name is unique within a namespace to reference 59 | a secret resource. 60 | type: string 61 | namespace: 62 | description: namespace defines the space within which the 63 | secret name must be unique. 64 | type: string 65 | type: object 66 | x-kubernetes-map-type: atomic 67 | host: 68 | description: Host is the host IP address or hostname of the Machine. 69 | minLength: 1 70 | type: string 71 | insecureTLS: 72 | description: InsecureTLS specifies trusted TLS connections. 73 | type: boolean 74 | port: 75 | default: 623 76 | description: Port is the port number for connecting with the Machine. 77 | type: integer 78 | providerOptions: 79 | description: ProviderOptions contains provider specific options. 80 | properties: 81 | intelAMT: 82 | description: IntelAMT contains the options to customize the 83 | IntelAMT provider. 84 | properties: 85 | hostScheme: 86 | default: http 87 | description: HostScheme determines whether to use http 88 | or https for intelAMT calls. 89 | enum: 90 | - http 91 | - https 92 | type: string 93 | port: 94 | description: Port that intelAMT will use for calls. 95 | type: integer 96 | type: object 97 | ipmitool: 98 | description: IPMITOOL contains the options to customize the 99 | Ipmitool provider. 100 | properties: 101 | cipherSuite: 102 | description: CipherSuite that ipmitool will use for calls. 103 | type: string 104 | port: 105 | description: Port that ipmitool will use for calls. 106 | type: integer 107 | type: object 108 | preferredOrder: 109 | description: |- 110 | PreferredOrder allows customizing the order that BMC providers are called. 111 | Providers added to this list will be moved to the front of the default order. 112 | Provider names are case insensitive. 113 | The default order is: ipmitool, asrockrack, gofish, intelamt, dell, supermicro, openbmc. 114 | items: 115 | description: ProviderName is the bmclib specific provider 116 | name. Names are case insensitive. 117 | pattern: (?i)^(ipmitool|asrockrack|gofish|IntelAMT|dell|supermicro|openbmc)$ 118 | type: string 119 | type: array 120 | redfish: 121 | description: Redfish contains the options to customize the 122 | Redfish provider. 123 | properties: 124 | port: 125 | description: Port that redfish will use for calls. 126 | type: integer 127 | systemName: 128 | description: |- 129 | SystemName is the name of the system to use for redfish calls. 130 | With redfish implementations that manage multiple systems via a single endpoint, this allows for specifying the system to manage. 131 | type: string 132 | useBasicAuth: 133 | description: UseBasicAuth for redfish calls. The default 134 | is false which means token based auth is used. 135 | type: boolean 136 | type: object 137 | rpc: 138 | description: RPC contains the options to customize the RPC 139 | provider. 140 | properties: 141 | consumerURL: 142 | description: |- 143 | ConsumerURL is the URL where an rpc consumer/listener is running 144 | and to which we will send and receive all notifications. 145 | type: string 146 | experimental: 147 | description: Experimental options. 148 | properties: 149 | customRequestPayload: 150 | description: CustomRequestPayload must be in json. 151 | type: string 152 | dotPath: 153 | description: 'DotPath is the path to the json object 154 | where the bmclib RequestPayload{} struct will be 155 | embedded. For example: object.data.body' 156 | type: string 157 | type: object 158 | hmac: 159 | description: HMAC is the options used to create a HMAC 160 | signature. 161 | properties: 162 | prefixSigDisabled: 163 | description: 'PrefixSigDisabled determines whether 164 | the algorithm will be prefixed to the signature. 165 | Example: sha256=abc123' 166 | type: boolean 167 | secrets: 168 | additionalProperties: 169 | items: 170 | description: |- 171 | SecretReference represents a Secret Reference. It has enough information to retrieve secret 172 | in any namespace 173 | properties: 174 | name: 175 | description: name is unique within a namespace 176 | to reference a secret resource. 177 | type: string 178 | namespace: 179 | description: namespace defines the space within 180 | which the secret name must be unique. 181 | type: string 182 | type: object 183 | x-kubernetes-map-type: atomic 184 | type: array 185 | description: Secrets are a map of algorithms to secrets 186 | used for signing. 187 | type: object 188 | type: object 189 | logNotificationsDisabled: 190 | description: LogNotificationsDisabled determines whether 191 | responses from rpc consumer/listeners will be logged 192 | or not. 193 | type: boolean 194 | request: 195 | description: Request is the options used to create the 196 | rpc HTTP request. 197 | properties: 198 | httpContentType: 199 | description: HTTPContentType is the content type to 200 | use for the rpc request notification. 201 | type: string 202 | httpMethod: 203 | description: HTTPMethod is the HTTP method to use 204 | for the rpc request notification. 205 | type: string 206 | staticHeaders: 207 | additionalProperties: 208 | items: 209 | type: string 210 | type: array 211 | description: StaticHeaders are predefined headers 212 | that will be added to every request. 213 | type: object 214 | timestampFormat: 215 | description: TimestampFormat is the time format for 216 | the timestamp header. 217 | type: string 218 | timestampHeader: 219 | description: 'TimestampHeader is the header name that 220 | should contain the timestamp. Example: X-BMCLIB-Timestamp' 221 | type: string 222 | type: object 223 | signature: 224 | description: Signature is the options used for adding 225 | an HMAC signature to an HTTP request. 226 | properties: 227 | appendAlgoToHeaderDisabled: 228 | description: |- 229 | AppendAlgoToHeaderDisabled decides whether to append the algorithm to the signature header or not. 230 | Example: X-BMCLIB-Signature becomes X-BMCLIB-Signature-256 231 | When set to true, a header will be added for each algorithm. Example: X-BMCLIB-Signature-256 and X-BMCLIB-Signature-512 232 | type: boolean 233 | headerName: 234 | description: 'HeaderName is the header name that should 235 | contain the signature(s). Example: X-BMCLIB-Signature' 236 | type: string 237 | includedPayloadHeaders: 238 | description: |- 239 | IncludedPayloadHeaders are headers whose values will be included in the signature payload. Example: X-BMCLIB-My-Custom-Header 240 | All headers will be deduplicated. 241 | items: 242 | type: string 243 | type: array 244 | type: object 245 | required: 246 | - consumerURL 247 | type: object 248 | type: object 249 | required: 250 | - host 251 | - insecureTLS 252 | type: object 253 | required: 254 | - connection 255 | type: object 256 | status: 257 | description: MachineStatus defines the observed state of Machine. 258 | properties: 259 | conditions: 260 | description: Conditions represents the latest available observations 261 | of an object's current state. 262 | items: 263 | description: MachineCondition defines an observed condition of a 264 | Machine. 265 | properties: 266 | lastUpdateTime: 267 | description: LastUpdateTime of the condition. 268 | format: date-time 269 | type: string 270 | message: 271 | description: Message is a human readable message indicating 272 | with details of the last transition. 273 | type: string 274 | status: 275 | description: Status of the condition. 276 | type: string 277 | type: 278 | description: Type of the Machine condition. 279 | type: string 280 | required: 281 | - status 282 | - type 283 | type: object 284 | type: array 285 | powerState: 286 | description: Power is the current power state of the Machine. 287 | enum: 288 | - "on" 289 | - "off" 290 | - unknown 291 | type: string 292 | type: object 293 | type: object 294 | served: true 295 | storage: true 296 | subresources: 297 | status: {} 298 | -------------------------------------------------------------------------------- /config/crd/bases/bmc.tinkerbell.org_tasks.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: apiextensions.k8s.io/v1 3 | kind: CustomResourceDefinition 4 | metadata: 5 | annotations: 6 | controller-gen.kubebuilder.io/version: v0.16.4 7 | name: tasks.bmc.tinkerbell.org 8 | spec: 9 | group: bmc.tinkerbell.org 10 | names: 11 | categories: 12 | - tinkerbell 13 | kind: Task 14 | listKind: TaskList 15 | plural: tasks 16 | shortNames: 17 | - t 18 | singular: task 19 | scope: Namespaced 20 | versions: 21 | - name: v1alpha1 22 | schema: 23 | openAPIV3Schema: 24 | description: Task is the Schema for the Task API. 25 | properties: 26 | apiVersion: 27 | description: |- 28 | APIVersion defines the versioned schema of this representation of an object. 29 | Servers should convert recognized schemas to the latest internal value, and 30 | may reject unrecognized values. 31 | More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources 32 | type: string 33 | kind: 34 | description: |- 35 | Kind is a string value representing the REST resource this object represents. 36 | Servers may infer this from the endpoint the client submits requests to. 37 | Cannot be updated. 38 | In CamelCase. 39 | More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds 40 | type: string 41 | metadata: 42 | type: object 43 | spec: 44 | description: TaskSpec defines the desired state of Task. 45 | properties: 46 | connection: 47 | description: Connection represents the Machine connectivity information. 48 | properties: 49 | authSecretRef: 50 | description: |- 51 | AuthSecretRef is the SecretReference that contains authentication information of the Machine. 52 | The Secret must contain username and password keys. This is optional as it is not required when using 53 | the RPC provider. 54 | properties: 55 | name: 56 | description: name is unique within a namespace to reference 57 | a secret resource. 58 | type: string 59 | namespace: 60 | description: namespace defines the space within which the 61 | secret name must be unique. 62 | type: string 63 | type: object 64 | x-kubernetes-map-type: atomic 65 | host: 66 | description: Host is the host IP address or hostname of the Machine. 67 | minLength: 1 68 | type: string 69 | insecureTLS: 70 | description: InsecureTLS specifies trusted TLS connections. 71 | type: boolean 72 | port: 73 | default: 623 74 | description: Port is the port number for connecting with the Machine. 75 | type: integer 76 | providerOptions: 77 | description: ProviderOptions contains provider specific options. 78 | properties: 79 | intelAMT: 80 | description: IntelAMT contains the options to customize the 81 | IntelAMT provider. 82 | properties: 83 | hostScheme: 84 | default: http 85 | description: HostScheme determines whether to use http 86 | or https for intelAMT calls. 87 | enum: 88 | - http 89 | - https 90 | type: string 91 | port: 92 | description: Port that intelAMT will use for calls. 93 | type: integer 94 | type: object 95 | ipmitool: 96 | description: IPMITOOL contains the options to customize the 97 | Ipmitool provider. 98 | properties: 99 | cipherSuite: 100 | description: CipherSuite that ipmitool will use for calls. 101 | type: string 102 | port: 103 | description: Port that ipmitool will use for calls. 104 | type: integer 105 | type: object 106 | preferredOrder: 107 | description: |- 108 | PreferredOrder allows customizing the order that BMC providers are called. 109 | Providers added to this list will be moved to the front of the default order. 110 | Provider names are case insensitive. 111 | The default order is: ipmitool, asrockrack, gofish, intelamt, dell, supermicro, openbmc. 112 | items: 113 | description: ProviderName is the bmclib specific provider 114 | name. Names are case insensitive. 115 | pattern: (?i)^(ipmitool|asrockrack|gofish|IntelAMT|dell|supermicro|openbmc)$ 116 | type: string 117 | type: array 118 | redfish: 119 | description: Redfish contains the options to customize the 120 | Redfish provider. 121 | properties: 122 | port: 123 | description: Port that redfish will use for calls. 124 | type: integer 125 | systemName: 126 | description: |- 127 | SystemName is the name of the system to use for redfish calls. 128 | With redfish implementations that manage multiple systems via a single endpoint, this allows for specifying the system to manage. 129 | type: string 130 | useBasicAuth: 131 | description: UseBasicAuth for redfish calls. The default 132 | is false which means token based auth is used. 133 | type: boolean 134 | type: object 135 | rpc: 136 | description: RPC contains the options to customize the RPC 137 | provider. 138 | properties: 139 | consumerURL: 140 | description: |- 141 | ConsumerURL is the URL where an rpc consumer/listener is running 142 | and to which we will send and receive all notifications. 143 | type: string 144 | experimental: 145 | description: Experimental options. 146 | properties: 147 | customRequestPayload: 148 | description: CustomRequestPayload must be in json. 149 | type: string 150 | dotPath: 151 | description: 'DotPath is the path to the json object 152 | where the bmclib RequestPayload{} struct will be 153 | embedded. For example: object.data.body' 154 | type: string 155 | type: object 156 | hmac: 157 | description: HMAC is the options used to create a HMAC 158 | signature. 159 | properties: 160 | prefixSigDisabled: 161 | description: 'PrefixSigDisabled determines whether 162 | the algorithm will be prefixed to the signature. 163 | Example: sha256=abc123' 164 | type: boolean 165 | secrets: 166 | additionalProperties: 167 | items: 168 | description: |- 169 | SecretReference represents a Secret Reference. It has enough information to retrieve secret 170 | in any namespace 171 | properties: 172 | name: 173 | description: name is unique within a namespace 174 | to reference a secret resource. 175 | type: string 176 | namespace: 177 | description: namespace defines the space within 178 | which the secret name must be unique. 179 | type: string 180 | type: object 181 | x-kubernetes-map-type: atomic 182 | type: array 183 | description: Secrets are a map of algorithms to secrets 184 | used for signing. 185 | type: object 186 | type: object 187 | logNotificationsDisabled: 188 | description: LogNotificationsDisabled determines whether 189 | responses from rpc consumer/listeners will be logged 190 | or not. 191 | type: boolean 192 | request: 193 | description: Request is the options used to create the 194 | rpc HTTP request. 195 | properties: 196 | httpContentType: 197 | description: HTTPContentType is the content type to 198 | use for the rpc request notification. 199 | type: string 200 | httpMethod: 201 | description: HTTPMethod is the HTTP method to use 202 | for the rpc request notification. 203 | type: string 204 | staticHeaders: 205 | additionalProperties: 206 | items: 207 | type: string 208 | type: array 209 | description: StaticHeaders are predefined headers 210 | that will be added to every request. 211 | type: object 212 | timestampFormat: 213 | description: TimestampFormat is the time format for 214 | the timestamp header. 215 | type: string 216 | timestampHeader: 217 | description: 'TimestampHeader is the header name that 218 | should contain the timestamp. Example: X-BMCLIB-Timestamp' 219 | type: string 220 | type: object 221 | signature: 222 | description: Signature is the options used for adding 223 | an HMAC signature to an HTTP request. 224 | properties: 225 | appendAlgoToHeaderDisabled: 226 | description: |- 227 | AppendAlgoToHeaderDisabled decides whether to append the algorithm to the signature header or not. 228 | Example: X-BMCLIB-Signature becomes X-BMCLIB-Signature-256 229 | When set to true, a header will be added for each algorithm. Example: X-BMCLIB-Signature-256 and X-BMCLIB-Signature-512 230 | type: boolean 231 | headerName: 232 | description: 'HeaderName is the header name that should 233 | contain the signature(s). Example: X-BMCLIB-Signature' 234 | type: string 235 | includedPayloadHeaders: 236 | description: |- 237 | IncludedPayloadHeaders are headers whose values will be included in the signature payload. Example: X-BMCLIB-My-Custom-Header 238 | All headers will be deduplicated. 239 | items: 240 | type: string 241 | type: array 242 | type: object 243 | required: 244 | - consumerURL 245 | type: object 246 | type: object 247 | required: 248 | - host 249 | - insecureTLS 250 | type: object 251 | task: 252 | description: Task defines the specific action to be performed. 253 | maxProperties: 1 254 | properties: 255 | oneTimeBootDeviceAction: 256 | description: OneTimeBootDeviceAction represents a baseboard management 257 | one time set boot device operation. 258 | properties: 259 | device: 260 | description: |- 261 | Devices represents the boot devices, in order for setting one time boot. 262 | Currently only the first device in the slice is used to set one time boot. 263 | items: 264 | description: BootDevice represents boot device of the Machine. 265 | type: string 266 | type: array 267 | efiBoot: 268 | description: EFIBoot instructs the machine to use EFI boot. 269 | type: boolean 270 | required: 271 | - device 272 | type: object 273 | powerAction: 274 | description: PowerAction represents a baseboard management power 275 | operation. 276 | enum: 277 | - "on" 278 | - "off" 279 | - soft 280 | - status 281 | - cycle 282 | - reset 283 | type: string 284 | virtualMediaAction: 285 | description: VirtualMediaAction represents a baseboard management 286 | virtual media insert/eject. 287 | properties: 288 | kind: 289 | type: string 290 | mediaURL: 291 | description: |- 292 | mediaURL represents the URL of the image to be inserted into the virtual media, or empty to 293 | eject media. 294 | type: string 295 | required: 296 | - kind 297 | type: object 298 | type: object 299 | required: 300 | - task 301 | type: object 302 | status: 303 | description: TaskStatus defines the observed state of Task. 304 | properties: 305 | completionTime: 306 | description: |- 307 | CompletionTime represents time when the task was completed. 308 | The completion time is only set when the task finishes successfully. 309 | format: date-time 310 | type: string 311 | conditions: 312 | description: Conditions represents the latest available observations 313 | of an object's current state. 314 | items: 315 | properties: 316 | message: 317 | description: Message represents human readable message indicating 318 | details about last transition. 319 | type: string 320 | status: 321 | description: |- 322 | Status is the status of the Task condition. 323 | Can be True or False. 324 | type: string 325 | type: 326 | description: Type of the Task condition. 327 | type: string 328 | required: 329 | - status 330 | - type 331 | type: object 332 | type: array 333 | startTime: 334 | description: StartTime represents time when the Task started processing. 335 | format: date-time 336 | type: string 337 | type: object 338 | type: object 339 | served: true 340 | storage: true 341 | subresources: 342 | status: {} 343 | -------------------------------------------------------------------------------- /config/crd/kustomization.yaml: -------------------------------------------------------------------------------- 1 | # This kustomization.yaml is not intended to be run by itself, 2 | # since it depends on service name and namespace that are out of this kustomize package. 3 | # It should be run by config/default 4 | resources: 5 | - bases/bmc.tinkerbell.org_machines.yaml 6 | - bases/bmc.tinkerbell.org_jobs.yaml 7 | - bases/bmc.tinkerbell.org_tasks.yaml 8 | #+kubebuilder:scaffold:crdkustomizeresource 9 | 10 | patchesStrategicMerge: 11 | # [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix. 12 | # patches here are for enabling the conversion webhook for each CRD 13 | #- patches/webhook_in_machines.yaml 14 | #- patches/webhook_in_jobs.yaml 15 | #- patches/webhook_in_tasks.yaml 16 | #+kubebuilder:scaffold:crdkustomizewebhookpatch 17 | 18 | # [CERTMANAGER] To enable cert-manager, uncomment all the sections with [CERTMANAGER] prefix. 19 | # patches here are for enabling the CA injection for each CRD 20 | #- patches/cainjection_in_machines.yaml 21 | #- patches/cainjection_in_jobs.yaml 22 | #- patches/cainjection_in_tasks.yaml 23 | #+kubebuilder:scaffold:crdkustomizecainjectionpatch 24 | 25 | # the following config is for teaching kustomize how to do kustomization for CRDs. 26 | configurations: 27 | - kustomizeconfig.yaml 28 | -------------------------------------------------------------------------------- /config/crd/kustomizeconfig.yaml: -------------------------------------------------------------------------------- 1 | # This file is for teaching kustomize how to substitute name and namespace reference in CRD 2 | nameReference: 3 | - kind: Service 4 | version: v1 5 | fieldSpecs: 6 | - kind: CustomResourceDefinition 7 | version: v1 8 | group: apiextensions.k8s.io 9 | path: spec/conversion/webhook/clientConfig/service/name 10 | 11 | namespace: 12 | - kind: CustomResourceDefinition 13 | version: v1 14 | group: apiextensions.k8s.io 15 | path: spec/conversion/webhook/clientConfig/service/namespace 16 | create: false 17 | 18 | varReference: 19 | - path: metadata/annotations 20 | -------------------------------------------------------------------------------- /config/crd/patches/cainjection_in_jobs.yaml: -------------------------------------------------------------------------------- 1 | # The following patch adds a directive for certmanager to inject CA into the CRD 2 | apiVersion: apiextensions.k8s.io/v1 3 | kind: CustomResourceDefinition 4 | metadata: 5 | annotations: 6 | cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME) 7 | name: jobs.bmc.tinkerbell.org 8 | -------------------------------------------------------------------------------- /config/crd/patches/cainjection_in_machines.yaml: -------------------------------------------------------------------------------- 1 | # The following patch adds a directive for certmanager to inject CA into the CRD 2 | apiVersion: apiextensions.k8s.io/v1 3 | kind: CustomResourceDefinition 4 | metadata: 5 | annotations: 6 | cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME) 7 | name: machines.bmc.tinkerbell.org 8 | -------------------------------------------------------------------------------- /config/crd/patches/cainjection_in_tasks.yaml: -------------------------------------------------------------------------------- 1 | # The following patch adds a directive for certmanager to inject CA into the CRD 2 | apiVersion: apiextensions.k8s.io/v1 3 | kind: CustomResourceDefinition 4 | metadata: 5 | annotations: 6 | cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME) 7 | name: tasks.bmc.tinkerbell.org 8 | -------------------------------------------------------------------------------- /config/crd/patches/webhook_in_jobs.yaml: -------------------------------------------------------------------------------- 1 | # The following patch enables a conversion webhook for the CRD 2 | apiVersion: apiextensions.k8s.io/v1 3 | kind: CustomResourceDefinition 4 | metadata: 5 | name: jobs.bmc.tinkerbell.org 6 | spec: 7 | conversion: 8 | strategy: Webhook 9 | webhook: 10 | clientConfig: 11 | service: 12 | namespace: system 13 | name: webhook-service 14 | path: /convert 15 | conversionReviewVersions: 16 | - v1 17 | -------------------------------------------------------------------------------- /config/crd/patches/webhook_in_machines.yaml: -------------------------------------------------------------------------------- 1 | # The following patch enables a conversion webhook for the CRD 2 | apiVersion: apiextensions.k8s.io/v1 3 | kind: CustomResourceDefinition 4 | metadata: 5 | name: machines.bmc.tinkerbell.org 6 | spec: 7 | conversion: 8 | strategy: Webhook 9 | webhook: 10 | clientConfig: 11 | service: 12 | namespace: system 13 | name: webhook-service 14 | path: /convert 15 | conversionReviewVersions: 16 | - v1 17 | -------------------------------------------------------------------------------- /config/crd/patches/webhook_in_tasks.yaml: -------------------------------------------------------------------------------- 1 | # The following patch enables a conversion webhook for the CRD 2 | apiVersion: apiextensions.k8s.io/v1 3 | kind: CustomResourceDefinition 4 | metadata: 5 | name: tasks.bmc.tinkerbell.org 6 | spec: 7 | conversion: 8 | strategy: Webhook 9 | webhook: 10 | clientConfig: 11 | service: 12 | namespace: system 13 | name: webhook-service 14 | path: /convert 15 | conversionReviewVersions: 16 | - v1 17 | -------------------------------------------------------------------------------- /config/default/kustomization.yaml: -------------------------------------------------------------------------------- 1 | # Adds namespace to all resources. 2 | namespace: rufio-system 3 | 4 | # Value of this field is prepended to the 5 | # names of all resources, e.g. a deployment named 6 | # "wordpress" becomes "alices-wordpress". 7 | # Note that it should also match with the prefix (text before '-') of the namespace 8 | # field above. 9 | namePrefix: rufio- 10 | 11 | # Labels to add to all resources and selectors. 12 | #commonLabels: 13 | # someName: someValue 14 | 15 | # [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in 16 | # crd/kustomization.yaml 17 | #- ../webhook 18 | # [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER'. 'WEBHOOK' components are required. 19 | #- ../certmanager 20 | # [PROMETHEUS] To enable prometheus monitor, uncomment all sections with 'PROMETHEUS'. 21 | #- ../prometheus 22 | 23 | # Protect the /metrics endpoint by putting it behind auth. 24 | # If you want your controller-manager to expose the /metrics 25 | # endpoint w/o any authn/z, please comment the following line. 26 | 27 | # Mount the controller config file for loading manager configurations 28 | # through a ComponentConfig type 29 | #- manager_config_patch.yaml 30 | 31 | # [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in 32 | # crd/kustomization.yaml 33 | #- manager_webhook_patch.yaml 34 | 35 | # [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER'. 36 | # Uncomment 'CERTMANAGER' sections in crd/kustomization.yaml to enable the CA injection in the admission webhooks. 37 | # 'CERTMANAGER' needs to be enabled to use ca injection 38 | #- webhookcainjection_patch.yaml 39 | 40 | # the following config is for teaching kustomize how to do var substitution 41 | apiVersion: kustomize.config.k8s.io/v1beta1 42 | kind: Kustomization 43 | resources: 44 | - ../crd 45 | - ../rbac 46 | - ../manager 47 | -------------------------------------------------------------------------------- /config/default/manager_config_patch.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: controller-manager 5 | namespace: system 6 | spec: 7 | template: 8 | spec: 9 | containers: 10 | - name: manager 11 | args: 12 | - "--config=controller_manager_config.yaml" 13 | volumeMounts: 14 | - name: manager-config 15 | mountPath: /controller_manager_config.yaml 16 | subPath: controller_manager_config.yaml 17 | volumes: 18 | - name: manager-config 19 | configMap: 20 | name: manager-config 21 | -------------------------------------------------------------------------------- /config/manager/controller_manager_config.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: controller-runtime.sigs.k8s.io/v1alpha1 2 | kind: ControllerManagerConfig 3 | health: 4 | healthProbeBindAddress: :8081 5 | metrics: 6 | bindAddress: 127.0.0.1:8080 7 | webhook: 8 | port: 9443 9 | leaderElection: 10 | leaderElect: true 11 | resourceName: e74dec1a.tinkerbell.org 12 | -------------------------------------------------------------------------------- /config/manager/kustomization.yaml: -------------------------------------------------------------------------------- 1 | resources: 2 | - manager.yaml 3 | 4 | generatorOptions: 5 | disableNameSuffixHash: true 6 | 7 | configMapGenerator: 8 | - files: 9 | - controller_manager_config.yaml 10 | name: manager-config 11 | apiVersion: kustomize.config.k8s.io/v1beta1 12 | kind: Kustomization 13 | images: 14 | - name: controller 15 | newName: quay.io/tinkerbell/rufio 16 | newTag: latest 17 | -------------------------------------------------------------------------------- /config/manager/manager.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | labels: 5 | control-plane: controller-manager 6 | name: system 7 | --- 8 | apiVersion: apps/v1 9 | kind: Deployment 10 | metadata: 11 | name: controller-manager 12 | namespace: system 13 | labels: 14 | control-plane: controller-manager 15 | spec: 16 | selector: 17 | matchLabels: 18 | control-plane: controller-manager 19 | replicas: 1 20 | template: 21 | metadata: 22 | annotations: 23 | kubectl.kubernetes.io/default-container: manager 24 | labels: 25 | control-plane: controller-manager 26 | spec: 27 | securityContext: 28 | runAsNonRoot: true 29 | containers: 30 | - command: 31 | - /manager 32 | args: 33 | - --leader-elect 34 | image: controller:latest 35 | name: manager 36 | securityContext: 37 | allowPrivilegeEscalation: false 38 | livenessProbe: 39 | httpGet: 40 | path: /healthz 41 | port: 8081 42 | initialDelaySeconds: 15 43 | periodSeconds: 20 44 | readinessProbe: 45 | httpGet: 46 | path: /readyz 47 | port: 8081 48 | initialDelaySeconds: 5 49 | periodSeconds: 10 50 | # TODO(user): Configure the resources accordingly based on the project requirements. 51 | # More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ 52 | resources: 53 | limits: 54 | cpu: 500m 55 | memory: 128Mi 56 | requests: 57 | cpu: 10m 58 | memory: 64Mi 59 | serviceAccountName: controller-manager 60 | terminationGracePeriodSeconds: 10 61 | -------------------------------------------------------------------------------- /config/prometheus/kustomization.yaml: -------------------------------------------------------------------------------- 1 | resources: 2 | - monitor.yaml 3 | -------------------------------------------------------------------------------- /config/prometheus/monitor.yaml: -------------------------------------------------------------------------------- 1 | 2 | # Prometheus Monitor Service (Metrics) 3 | apiVersion: monitoring.coreos.com/v1 4 | kind: ServiceMonitor 5 | metadata: 6 | labels: 7 | control-plane: controller-manager 8 | name: controller-manager-metrics-monitor 9 | namespace: system 10 | spec: 11 | endpoints: 12 | - path: /metrics 13 | port: https 14 | scheme: https 15 | bearerTokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token 16 | tlsConfig: 17 | insecureSkipVerify: true 18 | selector: 19 | matchLabels: 20 | control-plane: controller-manager 21 | -------------------------------------------------------------------------------- /config/rbac/job_editor_role.yaml: -------------------------------------------------------------------------------- 1 | # permissions for end users to edit jobs. 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: ClusterRole 4 | metadata: 5 | name: job-editor-role 6 | rules: 7 | - apiGroups: 8 | - bmc.tinkerbell.org 9 | resources: 10 | - jobs 11 | verbs: 12 | - create 13 | - delete 14 | - get 15 | - list 16 | - patch 17 | - update 18 | - watch 19 | - apiGroups: 20 | - bmc.tinkerbell.org 21 | resources: 22 | - jobs/status 23 | verbs: 24 | - get 25 | -------------------------------------------------------------------------------- /config/rbac/job_viewer_role.yaml: -------------------------------------------------------------------------------- 1 | # permissions for end users to view jobs. 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: ClusterRole 4 | metadata: 5 | name: job-viewer-role 6 | rules: 7 | - apiGroups: 8 | - bmc.tinkerbell.org 9 | resources: 10 | - jobs 11 | verbs: 12 | - get 13 | - list 14 | - watch 15 | - apiGroups: 16 | - bmc.tinkerbell.org 17 | resources: 18 | - jobs/status 19 | verbs: 20 | - get 21 | -------------------------------------------------------------------------------- /config/rbac/kustomization.yaml: -------------------------------------------------------------------------------- 1 | resources: 2 | # All RBAC will be applied under this service account in 3 | # the deployment namespace. You may comment out this resource 4 | # if your manager will use a service account that exists at 5 | # runtime. Be sure to update RoleBinding and ClusterRoleBinding 6 | # subjects if changing service account names. 7 | - service_account.yaml 8 | - role.yaml 9 | - role_binding.yaml 10 | - leader_election_role.yaml 11 | - leader_election_role_binding.yaml 12 | # Comment the following 4 lines if you want to disable 13 | # the auth proxy (https://github.com/brancz/kube-rbac-proxy) 14 | # which protects your /metrics endpoint. 15 | # - auth_proxy_service.yaml 16 | # - auth_proxy_role.yaml 17 | # - auth_proxy_role_binding.yaml 18 | # - auth_proxy_client_clusterrole.yaml 19 | -------------------------------------------------------------------------------- /config/rbac/leader_election_role.yaml: -------------------------------------------------------------------------------- 1 | # permissions to do leader election. 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: Role 4 | metadata: 5 | name: leader-election-role 6 | rules: 7 | - apiGroups: 8 | - "" 9 | resources: 10 | - configmaps 11 | verbs: 12 | - get 13 | - list 14 | - watch 15 | - create 16 | - update 17 | - patch 18 | - delete 19 | - apiGroups: 20 | - coordination.k8s.io 21 | resources: 22 | - leases 23 | verbs: 24 | - get 25 | - list 26 | - watch 27 | - create 28 | - update 29 | - patch 30 | - delete 31 | - apiGroups: 32 | - "" 33 | resources: 34 | - events 35 | verbs: 36 | - create 37 | - patch 38 | -------------------------------------------------------------------------------- /config/rbac/leader_election_role_binding.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: rbac.authorization.k8s.io/v1 2 | kind: RoleBinding 3 | metadata: 4 | name: leader-election-rolebinding 5 | roleRef: 6 | apiGroup: rbac.authorization.k8s.io 7 | kind: Role 8 | name: leader-election-role 9 | subjects: 10 | - kind: ServiceAccount 11 | name: controller-manager 12 | namespace: system 13 | -------------------------------------------------------------------------------- /config/rbac/machine_editor_role.yaml: -------------------------------------------------------------------------------- 1 | # permissions for end users to edit machines. 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: ClusterRole 4 | metadata: 5 | name: machine-editor-role 6 | rules: 7 | - apiGroups: 8 | - bmc.tinkerbell.org 9 | resources: 10 | - machines 11 | verbs: 12 | - create 13 | - delete 14 | - get 15 | - list 16 | - patch 17 | - update 18 | - watch 19 | - apiGroups: 20 | - bmc.tinkerbell.org 21 | resources: 22 | - machines/status 23 | verbs: 24 | - get 25 | -------------------------------------------------------------------------------- /config/rbac/machine_viewer_role.yaml: -------------------------------------------------------------------------------- 1 | # permissions for end users to view machines. 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: ClusterRole 4 | metadata: 5 | name: machine-viewer-role 6 | rules: 7 | - apiGroups: 8 | - bmc.tinkerbell.org 9 | resources: 10 | - machines 11 | verbs: 12 | - get 13 | - list 14 | - watch 15 | - apiGroups: 16 | - bmc.tinkerbell.org 17 | resources: 18 | - machines/status 19 | verbs: 20 | - get 21 | -------------------------------------------------------------------------------- /config/rbac/role.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: ClusterRole 4 | metadata: 5 | name: manager-role 6 | rules: 7 | - apiGroups: 8 | - "" 9 | resources: 10 | - secrets 11 | verbs: 12 | - get 13 | - list 14 | - watch 15 | - apiGroups: 16 | - bmc.tinkerbell.org 17 | resources: 18 | - jobs 19 | - machines 20 | - tasks 21 | verbs: 22 | - create 23 | - delete 24 | - get 25 | - list 26 | - patch 27 | - update 28 | - watch 29 | - apiGroups: 30 | - bmc.tinkerbell.org 31 | resources: 32 | - jobs/finalizers 33 | - machines/finalizers 34 | - tasks/finalizers 35 | verbs: 36 | - update 37 | - apiGroups: 38 | - bmc.tinkerbell.org 39 | resources: 40 | - jobs/status 41 | - machines/status 42 | - tasks/status 43 | verbs: 44 | - get 45 | - patch 46 | - update 47 | -------------------------------------------------------------------------------- /config/rbac/role_binding.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: rbac.authorization.k8s.io/v1 2 | kind: ClusterRoleBinding 3 | metadata: 4 | name: manager-rolebinding 5 | roleRef: 6 | apiGroup: rbac.authorization.k8s.io 7 | kind: ClusterRole 8 | name: manager-role 9 | subjects: 10 | - kind: ServiceAccount 11 | name: controller-manager 12 | namespace: system 13 | -------------------------------------------------------------------------------- /config/rbac/secrets_viewer_role.yaml: -------------------------------------------------------------------------------- 1 | # permissions to do view Secrets. 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: Role 4 | metadata: 5 | name: secrets-viewer-role 6 | rules: 7 | - apiGroups: 8 | - "" 9 | resources: 10 | - secrets 11 | verbs: 12 | - get 13 | - list 14 | - watch -------------------------------------------------------------------------------- /config/rbac/secrets_viewer_role_binding.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: rbac.authorization.k8s.io/v1 2 | kind: RoleBinding 3 | metadata: 4 | name: secrets-viewer-rolebinding 5 | roleRef: 6 | apiGroup: rbac.authorization.k8s.io 7 | kind: Role 8 | name: secrets-viewer-role 9 | subjects: 10 | - kind: ServiceAccount 11 | name: controller-manager 12 | namespace: system 13 | -------------------------------------------------------------------------------- /config/rbac/service_account.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: controller-manager 5 | namespace: system 6 | -------------------------------------------------------------------------------- /config/rbac/task_editor_role.yaml: -------------------------------------------------------------------------------- 1 | # permissions for end users to edit tasks. 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: ClusterRole 4 | metadata: 5 | name: task-editor-role 6 | rules: 7 | - apiGroups: 8 | - bmc.tinkerbell.org 9 | resources: 10 | - tasks 11 | verbs: 12 | - create 13 | - delete 14 | - get 15 | - list 16 | - patch 17 | - update 18 | - watch 19 | - apiGroups: 20 | - bmc.tinkerbell.org 21 | resources: 22 | - tasks/status 23 | verbs: 24 | - get 25 | -------------------------------------------------------------------------------- /config/rbac/task_viewer_role.yaml: -------------------------------------------------------------------------------- 1 | # permissions for end users to view tasks. 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: ClusterRole 4 | metadata: 5 | name: task-viewer-role 6 | rules: 7 | - apiGroups: 8 | - bmc.tinkerbell.org 9 | resources: 10 | - tasks 11 | verbs: 12 | - get 13 | - list 14 | - watch 15 | - apiGroups: 16 | - bmc.tinkerbell.org 17 | resources: 18 | - tasks/status 19 | verbs: 20 | - get 21 | -------------------------------------------------------------------------------- /config/samples/auth-secret.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Secret 3 | metadata: 4 | name: sample-machine-auth 5 | type: Opaque 6 | data: # admin/t0p-Secret; echo -n 'admin' | base64; echo -n 't0p-Secret' | base64 7 | username: YWRtaW4= 8 | password: dDBwLVNlY3JldA== 9 | -------------------------------------------------------------------------------- /config/samples/hmac-secret1.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Secret 3 | metadata: 4 | name: secret1 5 | type: Opaque 6 | data: # echo -n 'superSecret1' | base64; 7 | secret: c3VwZXJTZWNyZXQx 8 | -------------------------------------------------------------------------------- /config/samples/hmac-secret2.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Secret 3 | metadata: 4 | name: secret2 5 | type: Opaque 6 | data: # echo -n 'superSecret2' | base64; 7 | secret: c3VwZXJTZWNyZXQy 8 | -------------------------------------------------------------------------------- /config/samples/job_v1alpha1.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: bmc.tinkerbell.org/v1alpha1 2 | kind: Job 3 | metadata: 4 | name: job-sample 5 | spec: 6 | machineRef: 7 | name: machine-sample 8 | namespace: rufio-system 9 | tasks: 10 | - powerAction: "off" 11 | - oneTimeBootDeviceAction: 12 | device: 13 | - "pxe" 14 | efiBoot: false 15 | - powerAction: "on" 16 | -------------------------------------------------------------------------------- /config/samples/machine_v1alpha1.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: bmc.tinkerbell.org/v1alpha1 2 | kind: Machine 3 | metadata: 4 | name: machine-sample 5 | spec: 6 | connection: 7 | host: 127.0.0.1 8 | authSecretRef: 9 | name: sample-machine-auth 10 | namespace: rufio-system 11 | insecureTLS: true 12 | -------------------------------------------------------------------------------- /config/samples/machine_with_opts_v1alpha1.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: bmc.tinkerbell.org/v1alpha1 2 | kind: Machine 3 | metadata: 4 | name: machine-sample-with-opts 5 | spec: 6 | connection: 7 | host: 127.0.0.1 8 | insecureTLS: true 9 | providerOptions: 10 | rpc: 11 | consumerURL: "https://example.com/rpc" 12 | hmac: 13 | secrets: 14 | sha256: 15 | - name: secret1 16 | namespace: default 17 | - name: secret2 18 | namespace: default 19 | sha512: 20 | - name: secret1 21 | namespace: default 22 | - name: secret2 23 | namespace: default 24 | -------------------------------------------------------------------------------- /config/samples/task_v1alpha1.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: bmc.tinkerbell.org/v1alpha1 2 | kind: Task 3 | metadata: 4 | name: task-sample 5 | spec: 6 | connection: 7 | host: 127.0.0.1 8 | authSecretRef: 9 | name: sample-machine-auth 10 | namespace: rufio-system 11 | insecureTLS: true 12 | task: 13 | powerAction: "off" 14 | -------------------------------------------------------------------------------- /contrib/tag-release.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -o errexit -o nounset -o pipefail 4 | 5 | if [ -z "${1-}" ]; then 6 | echo "Must specify new tag" 7 | exit 1 8 | fi 9 | 10 | new_tag=${1-} 11 | [[ $new_tag =~ ^v[0-9]*\.[0-9]*\.[0-9]*$ ]] || ( 12 | echo "Tag must be in the form of vX.Y.Z" 13 | exit 1 14 | ) 15 | 16 | if [[ $(git symbolic-ref HEAD) != refs/heads/main ]] && [[ -z ${ALLOW_NON_MAIN:-} ]]; then 17 | echo "Must be on main branch" >&2 18 | exit 1 19 | fi 20 | if [[ $(git describe --dirty) != $(git describe) ]]; then 21 | echo "Repo must be in a clean state" >&2 22 | exit 1 23 | fi 24 | 25 | git fetch --all 26 | 27 | last_tag=$(git describe --abbrev=0) 28 | last_tag_commit=$(git rev-list -n1 "$last_tag") 29 | last_specific_tag=$(git tag --contains="$last_tag_commit" | grep -E "^v[0-9]*\.[0-9]*\.[0-9]*$" | tail -n 1) 30 | last_specific_tag_commit=$(git rev-list -n1 "$last_specific_tag") 31 | if [[ $last_specific_tag_commit == $(git rev-list -n1 HEAD) ]]; then 32 | echo "No commits since last tag" >&2 33 | exit 1 34 | fi 35 | 36 | if [[ -n ${SIGN_TAG-} ]]; then 37 | git tag -s -m "${new_tag}" "${new_tag}" &>/dev/null && echo "created signed tag ${new_tag}" >&2 && exit 38 | else 39 | git tag -a -m "${new_tag}" "${new_tag}" &>/dev/null && echo "created annotated tag ${new_tag}" >&2 && exit 40 | fi 41 | -------------------------------------------------------------------------------- /controller/client.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "strconv" 7 | "time" 8 | 9 | "dario.cat/mergo" 10 | bmclib "github.com/bmc-toolbox/bmclib/v2" 11 | "github.com/bmc-toolbox/bmclib/v2/providers/rpc" 12 | "github.com/ccoveille/go-safecast" 13 | "github.com/go-logr/logr" 14 | "github.com/tinkerbell/rufio/api/v1alpha1" 15 | ) 16 | 17 | // ClientFunc defines a func that returns a bmclib.Client. 18 | type ClientFunc func(ctx context.Context, log logr.Logger, hostIP, username, password string, opts *BMCOptions) (*bmclib.Client, error) 19 | 20 | // NewClientFunc returns a new BMCClientFactoryFunc. The timeout parameter determines the 21 | // maximum time to probe for compatible interfaces. 22 | func NewClientFunc(timeout time.Duration) ClientFunc { 23 | // Initializes a bmclib client based on input host and credentials 24 | // Establishes a connection with the bmc with client.Open 25 | // Returns a bmclib.Client. 26 | return func(ctx context.Context, log logr.Logger, hostIP, username, password string, opts *BMCOptions) (*bmclib.Client, error) { 27 | var o []bmclib.Option 28 | if opts != nil { 29 | o = append(o, opts.Translate(hostIP)...) 30 | } 31 | log = log.WithValues("host", hostIP, "username", username) 32 | o = append(o, bmclib.WithLogger(log)) 33 | client := bmclib.NewClient(hostIP, username, password, o...) 34 | 35 | ctx, cancel := context.WithTimeout(ctx, timeout) 36 | defer cancel() 37 | 38 | if opts != nil && opts.ProviderOptions != nil && len(opts.PreferredOrder) > 0 { 39 | client.Registry.Drivers = client.Registry.PreferDriver(toStringSlice(opts.PreferredOrder)...) 40 | } 41 | if err := client.Open(ctx); err != nil { 42 | md := client.GetMetadata() 43 | log.Info("Failed to open connection to BMC", "error", err, "providersAttempted", md.ProvidersAttempted, "successfulProvider", md.SuccessfulOpenConns) 44 | 45 | return nil, fmt.Errorf("failed to open connection to BMC: %w", err) 46 | } 47 | md := client.GetMetadata() 48 | log.Info("Connected to BMC", "providersAttempted", md.ProvidersAttempted, "successfulProvider", md.SuccessfulOpenConns) 49 | 50 | return client, nil 51 | } 52 | } 53 | 54 | type BMCOptions struct { 55 | *v1alpha1.ProviderOptions 56 | rpcSecrets map[rpc.Algorithm][]string 57 | } 58 | 59 | func (b BMCOptions) Translate(host string) []bmclib.Option { 60 | o := []bmclib.Option{} 61 | 62 | if b.ProviderOptions == nil { 63 | return o 64 | } 65 | 66 | // redfish options 67 | if b.Redfish != nil { 68 | if b.Redfish.Port != 0 { 69 | o = append(o, bmclib.WithRedfishPort(strconv.Itoa(b.Redfish.Port))) 70 | } 71 | if b.Redfish.UseBasicAuth { 72 | o = append(o, bmclib.WithRedfishUseBasicAuth(true)) 73 | } 74 | if b.Redfish.SystemName != "" { 75 | o = append(o, bmclib.WithRedfishSystemName(b.Redfish.SystemName)) 76 | } 77 | } 78 | 79 | // ipmitool options 80 | if b.IPMITOOL != nil { 81 | if b.IPMITOOL.Port != 0 { 82 | o = append(o, bmclib.WithIpmitoolPort(strconv.Itoa(b.IPMITOOL.Port))) 83 | } 84 | if b.IPMITOOL.CipherSuite != "" { 85 | o = append(o, bmclib.WithIpmitoolCipherSuite(b.IPMITOOL.CipherSuite)) 86 | } 87 | } 88 | 89 | // intelAmt options 90 | if b.IntelAMT != nil { 91 | // must not be negative, must not be greater than the uint32 max value 92 | p, err := safecast.ToUint32(b.IntelAMT.Port) 93 | if err != nil { 94 | p = 16992 95 | } 96 | amtPort := bmclib.WithIntelAMTPort(p) 97 | amtScheme := bmclib.WithIntelAMTHostScheme(b.IntelAMT.HostScheme) 98 | o = append(o, amtPort, amtScheme) 99 | } 100 | 101 | // rpc options 102 | if b.RPC != nil { 103 | op := b.translateRPC(host) 104 | o = append(o, bmclib.WithRPCOpt(op)) 105 | } 106 | 107 | return o 108 | } 109 | 110 | func (b BMCOptions) translateRPC(host string) rpc.Provider { 111 | s := map[rpc.Algorithm][]string{} 112 | if b.rpcSecrets != nil { 113 | s = b.rpcSecrets 114 | } 115 | 116 | defaults := rpc.Provider{ 117 | Opts: rpc.Opts{ 118 | Request: rpc.RequestOpts{ 119 | TimestampHeader: "X-Rufio-Timestamp", 120 | }, 121 | Signature: rpc.SignatureOpts{ 122 | HeaderName: "X-Rufio-Signature", 123 | IncludedPayloadHeaders: []string{"X-Rufio-Timestamp"}, 124 | }, 125 | }, 126 | } 127 | o := rpc.Provider{ 128 | ConsumerURL: b.RPC.ConsumerURL, 129 | Host: host, 130 | Opts: toRPCOpts(b.RPC), 131 | } 132 | if len(s) > 0 { 133 | o.Opts.HMAC.Secrets = s 134 | } 135 | 136 | _ = mergo.Merge(&o, &defaults, mergo.WithOverride, mergo.WithTransformers(&rpc.Provider{})) 137 | 138 | return o 139 | } 140 | 141 | func toRPCOpts(r *v1alpha1.RPCOptions) rpc.Opts { 142 | opt := rpc.Opts{} 143 | 144 | if r == nil { 145 | return opt 146 | } 147 | opt.Request = toRequestOpts(r.Request) 148 | opt.Signature = toSignatureOpts(r.Signature) 149 | opt.HMAC = toHMACOpts(r.HMAC) 150 | opt.Experimental = toExperimentalOpts(r.Experimental) 151 | 152 | return opt 153 | } 154 | 155 | func toRequestOpts(r *v1alpha1.RequestOpts) rpc.RequestOpts { 156 | opt := rpc.RequestOpts{} 157 | if r == nil { 158 | return opt 159 | } 160 | if r.HTTPContentType != "" { 161 | opt.HTTPContentType = r.HTTPContentType 162 | } 163 | if r.HTTPMethod != "" { 164 | opt.HTTPMethod = r.HTTPMethod 165 | } 166 | if len(r.StaticHeaders) > 0 { 167 | opt.StaticHeaders = r.StaticHeaders 168 | } 169 | if r.TimestampFormat != "" { 170 | opt.TimestampFormat = r.TimestampFormat 171 | } 172 | if r.TimestampHeader != "" { 173 | opt.TimestampHeader = r.TimestampHeader 174 | } 175 | 176 | return opt 177 | } 178 | 179 | func toSignatureOpts(s *v1alpha1.SignatureOpts) rpc.SignatureOpts { 180 | opt := rpc.SignatureOpts{} 181 | 182 | if s == nil { 183 | return opt 184 | } 185 | if s.HeaderName != "" { 186 | opt.HeaderName = s.HeaderName 187 | } 188 | if s.AppendAlgoToHeaderDisabled { 189 | opt.AppendAlgoToHeaderDisabled = s.AppendAlgoToHeaderDisabled 190 | } 191 | if len(s.IncludedPayloadHeaders) > 0 { 192 | opt.IncludedPayloadHeaders = s.IncludedPayloadHeaders 193 | } 194 | 195 | return opt 196 | } 197 | 198 | func toHMACOpts(h *v1alpha1.HMACOpts) rpc.HMACOpts { 199 | opt := rpc.HMACOpts{} 200 | 201 | if h == nil { 202 | return opt 203 | } 204 | if h.PrefixSigDisabled { 205 | opt.PrefixSigDisabled = h.PrefixSigDisabled 206 | } 207 | 208 | return opt 209 | } 210 | 211 | func toExperimentalOpts(e *v1alpha1.ExperimentalOpts) rpc.Experimental { 212 | opt := rpc.Experimental{} 213 | 214 | if e == nil { 215 | return opt 216 | } 217 | if e.CustomRequestPayload != "" { 218 | opt.CustomRequestPayload = []byte(e.CustomRequestPayload) 219 | } 220 | if e.DotPath != "" { 221 | opt.DotPath = e.DotPath 222 | } 223 | 224 | return opt 225 | } 226 | 227 | // convert a slice of ProviderName to a slice of string. 228 | func toStringSlice(p []v1alpha1.ProviderName) []string { 229 | var s []string 230 | for _, v := range p { 231 | s = append(s, v.String()) 232 | } 233 | return s 234 | } 235 | -------------------------------------------------------------------------------- /controller/helpers_test.go: -------------------------------------------------------------------------------- 1 | package controller_test 2 | 3 | import ( 4 | "context" 5 | 6 | bmclib "github.com/bmc-toolbox/bmclib/v2" 7 | "github.com/bmc-toolbox/bmclib/v2/providers" 8 | "github.com/go-logr/logr" 9 | "github.com/jacobweinstock/registrar" 10 | "github.com/tinkerbell/rufio/api/v1alpha1" 11 | "github.com/tinkerbell/rufio/controller" 12 | corev1 "k8s.io/api/core/v1" 13 | "k8s.io/apimachinery/pkg/runtime" 14 | "sigs.k8s.io/controller-runtime/pkg/client/fake" 15 | ) 16 | 17 | // This source file is currently a bucket of stuff. If it grows too big, consider breaking it 18 | // into more granular helper sources. 19 | 20 | // newClientBuilder creates a fake kube client builder loaded with Rufio's and Kubernetes' 21 | // corev1 schemes. 22 | func newClientBuilder() *fake.ClientBuilder { 23 | scheme := runtime.NewScheme() 24 | if err := v1alpha1.AddToScheme(scheme); err != nil { 25 | panic(err) 26 | } 27 | if err := corev1.AddToScheme(scheme); err != nil { 28 | panic(err) 29 | } 30 | 31 | return fake.NewClientBuilder(). 32 | WithScheme(scheme) 33 | } 34 | 35 | type testProvider struct { 36 | PName string 37 | Proto string 38 | Powerstate string 39 | PowerSetOK bool 40 | BootdeviceOK bool 41 | VirtualMediaOK bool 42 | ErrOpen error 43 | ErrClose error 44 | ErrPowerStateGet error 45 | ErrPowerStateSet error 46 | ErrBootDeviceSet error 47 | ErrVirtualMediaInsert error 48 | } 49 | 50 | func (t *testProvider) Name() string { 51 | if t.PName != "" { 52 | return t.PName 53 | } 54 | return "tester" 55 | } 56 | 57 | func (t *testProvider) Protocol() string { 58 | if t.Proto != "" { 59 | return t.Proto 60 | } 61 | return "gofish" 62 | } 63 | 64 | func (t *testProvider) Features() registrar.Features { 65 | return registrar.Features{ 66 | providers.FeaturePowerState, 67 | providers.FeaturePowerSet, 68 | providers.FeatureBootDeviceSet, 69 | providers.FeatureVirtualMedia, 70 | } 71 | } 72 | 73 | func (t *testProvider) Open(_ context.Context) error { 74 | return t.ErrOpen 75 | } 76 | 77 | func (t *testProvider) Close(_ context.Context) error { 78 | return t.ErrClose 79 | } 80 | 81 | func (t *testProvider) PowerStateGet(_ context.Context) (string, error) { 82 | return t.Powerstate, t.ErrPowerStateGet 83 | } 84 | 85 | func (t *testProvider) PowerSet(_ context.Context, _ string) (ok bool, err error) { 86 | return t.PowerSetOK, t.ErrPowerStateSet 87 | } 88 | 89 | func (t *testProvider) BootDeviceSet(_ context.Context, _ string, _, _ bool) (ok bool, err error) { 90 | return t.BootdeviceOK, t.ErrBootDeviceSet 91 | } 92 | 93 | func (t *testProvider) SetVirtualMedia(_ context.Context, _ string, _ string) (ok bool, err error) { 94 | return t.VirtualMediaOK, t.ErrVirtualMediaInsert 95 | } 96 | 97 | // newMockBMCClientFactoryFunc returns a new BMCClientFactoryFunc. 98 | func newTestClient(provider *testProvider) controller.ClientFunc { 99 | return func(ctx context.Context, log logr.Logger, hostIP, username, password string, opts *controller.BMCOptions) (*bmclib.Client, error) { 100 | o := opts.Translate(hostIP) 101 | reg := registrar.NewRegistry(registrar.WithLogger(log)) 102 | reg.Register(provider.Name(), provider.Protocol(), provider.Features(), nil, provider) 103 | o = append(o, bmclib.WithLogger(log), bmclib.WithRegistry(reg)) 104 | cl := bmclib.NewClient(hostIP, username, password, o...) 105 | return cl, cl.Open(ctx) 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /controller/job.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Tinkerbell. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package controller 18 | 19 | import ( 20 | "context" 21 | "fmt" 22 | 23 | apierrors "k8s.io/apimachinery/pkg/api/errors" 24 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 25 | "k8s.io/apimachinery/pkg/types" 26 | utilerrors "k8s.io/apimachinery/pkg/util/errors" 27 | ctrl "sigs.k8s.io/controller-runtime" 28 | "sigs.k8s.io/controller-runtime/pkg/client" 29 | ctrlcontroller "sigs.k8s.io/controller-runtime/pkg/controller" 30 | "sigs.k8s.io/controller-runtime/pkg/handler" 31 | 32 | "github.com/tinkerbell/rufio/api/v1alpha1" 33 | ) 34 | 35 | // Index key for Job Owner Name. 36 | const jobOwnerKey = ".metadata.controller" 37 | 38 | // JobReconciler reconciles a Job object. 39 | type JobReconciler struct { 40 | client client.Client 41 | } 42 | 43 | // NewJobReconciler returns a new JobReconciler. 44 | func NewJobReconciler(c client.Client) *JobReconciler { 45 | return &JobReconciler{ 46 | client: c, 47 | } 48 | } 49 | 50 | //+kubebuilder:rbac:groups=bmc.tinkerbell.org,resources=jobs,verbs=get;list;watch;create;update;patch;delete 51 | //+kubebuilder:rbac:groups=bmc.tinkerbell.org,resources=jobs/status,verbs=get;update;patch 52 | //+kubebuilder:rbac:groups=bmc.tinkerbell.org,resources=jobs/finalizers,verbs=update 53 | 54 | // Reconcile runs a Job. 55 | // Creates the individual Tasks on the cluster. 56 | // Watches for Task and creates next Job Task based on conditions. 57 | func (r *JobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { 58 | logger := ctrl.LoggerFrom(ctx).WithName("controllers/Job").WithValues("job", req.NamespacedName) 59 | logger.Info("Reconciling Job") 60 | 61 | // Fetch the job object 62 | job := &v1alpha1.Job{} 63 | err := r.client.Get(ctx, req.NamespacedName, job) 64 | if err != nil { 65 | if apierrors.IsNotFound(err) { 66 | return ctrl.Result{}, nil 67 | } 68 | 69 | logger.Error(err, "Failed to get Job") 70 | return ctrl.Result{}, err 71 | } 72 | 73 | // Deletion is a noop. 74 | if !job.DeletionTimestamp.IsZero() { 75 | return ctrl.Result{}, nil 76 | } 77 | 78 | // Job is Completed or Failed is noop. 79 | if job.HasCondition(v1alpha1.JobCompleted, v1alpha1.ConditionTrue) || 80 | job.HasCondition(v1alpha1.JobFailed, v1alpha1.ConditionTrue) { 81 | return ctrl.Result{}, nil 82 | } 83 | 84 | // Create a patch from the initial Job object 85 | // Patch is used to update Status after reconciliation 86 | jobPatch := client.MergeFrom(job.DeepCopy()) 87 | 88 | return r.doReconcile(ctx, job, jobPatch) 89 | } 90 | 91 | func (r *JobReconciler) doReconcile(ctx context.Context, job *v1alpha1.Job, jobPatch client.Patch) (ctrl.Result, error) { 92 | // Check if Job is not currently Running 93 | // Initialize the StartTime for the Job 94 | // Set the Job to Running condition True 95 | if !job.HasCondition(v1alpha1.JobRunning, v1alpha1.ConditionTrue) { 96 | now := metav1.Now() 97 | job.Status.StartTime = &now 98 | job.SetCondition(v1alpha1.JobRunning, v1alpha1.ConditionTrue) 99 | } 100 | 101 | // Get Machine object for the Job 102 | // Requeue if error 103 | machine := &v1alpha1.Machine{} 104 | err := r.getMachine(ctx, job.Spec.MachineRef, machine) 105 | if err != nil { 106 | return ctrl.Result{}, fmt.Errorf("get Job %s/%s MachineRef: %w", job.Namespace, job.Name, err) 107 | } 108 | 109 | // List all Task owned by Job 110 | tasks := &v1alpha1.TaskList{} 111 | err = r.client.List(ctx, tasks, client.MatchingFields{jobOwnerKey: job.Name}, client.InNamespace(job.Namespace)) 112 | if err != nil { 113 | return ctrl.Result{}, fmt.Errorf("failed to list owned Tasks for Job %s/%s: %w", job.Namespace, job.Name, err) 114 | } 115 | 116 | completedTasksCount := 0 117 | // Iterate Task Items. 118 | // Count the number of completed tasks. 119 | // Set the Job condition Failed True if Task has failed. 120 | // If the Task has neither Completed or Failed is noop. 121 | for _, task := range tasks.Items { 122 | if task.HasCondition(v1alpha1.TaskCompleted, v1alpha1.ConditionTrue) { 123 | completedTasksCount++ 124 | continue 125 | } 126 | 127 | if task.HasCondition(v1alpha1.TaskFailed, v1alpha1.ConditionTrue) { 128 | err := fmt.Errorf("task %s/%s failed", task.Namespace, task.Name) 129 | job.SetCondition(v1alpha1.JobFailed, v1alpha1.ConditionTrue, v1alpha1.WithJobConditionMessage(err.Error())) 130 | patchErr := r.patchStatus(ctx, job, jobPatch) 131 | if patchErr != nil { 132 | return ctrl.Result{}, utilerrors.NewAggregate([]error{patchErr, err}) 133 | } 134 | 135 | return ctrl.Result{}, err 136 | } 137 | 138 | return ctrl.Result{}, nil 139 | } 140 | 141 | // Check if all Job tasks have Completed 142 | // Set the Task CompletionTime 143 | // Set Task Condition Completed True 144 | if completedTasksCount == len(job.Spec.Tasks) { 145 | job.SetCondition(v1alpha1.JobCompleted, v1alpha1.ConditionTrue) 146 | now := metav1.Now() 147 | job.Status.CompletionTime = &now 148 | err = r.patchStatus(ctx, job, jobPatch) 149 | return ctrl.Result{}, err 150 | } 151 | 152 | // Create the first Task for the Job 153 | if err := r.createTaskWithOwner(ctx, *job, completedTasksCount, machine.Spec.Connection); err != nil { 154 | // Set the Job condition Failed True 155 | job.SetCondition(v1alpha1.JobFailed, v1alpha1.ConditionTrue, v1alpha1.WithJobConditionMessage(err.Error())) 156 | patchErr := r.patchStatus(ctx, job, jobPatch) 157 | if patchErr != nil { 158 | return ctrl.Result{}, utilerrors.NewAggregate([]error{patchErr, err}) 159 | } 160 | 161 | return ctrl.Result{}, err 162 | } 163 | 164 | // Patch the status at the end of reconcile loop 165 | err = r.patchStatus(ctx, job, jobPatch) 166 | return ctrl.Result{}, err 167 | } 168 | 169 | // getMachine Gets the Machine from MachineRef. 170 | func (r *JobReconciler) getMachine(ctx context.Context, reference v1alpha1.MachineRef, machine *v1alpha1.Machine) error { 171 | key := types.NamespacedName{Namespace: reference.Namespace, Name: reference.Name} 172 | err := r.client.Get(ctx, key, machine) 173 | if err != nil { 174 | if apierrors.IsNotFound(err) { 175 | return fmt.Errorf("machine %s not found: %w", key, err) 176 | } 177 | return fmt.Errorf("failed to get Machine %s: %w", key, err) 178 | } 179 | 180 | return nil 181 | } 182 | 183 | // createTaskWithOwner creates a Task object with an OwnerReference set to the Job. 184 | func (r *JobReconciler) createTaskWithOwner(ctx context.Context, job v1alpha1.Job, taskIndex int, conn v1alpha1.Connection) error { 185 | isController := true 186 | task := &v1alpha1.Task{ 187 | ObjectMeta: metav1.ObjectMeta{ 188 | Name: v1alpha1.FormatTaskName(job, taskIndex), 189 | Namespace: job.Namespace, 190 | OwnerReferences: []metav1.OwnerReference{ 191 | { 192 | APIVersion: job.APIVersion, 193 | Kind: job.Kind, 194 | Name: job.Name, 195 | UID: job.ObjectMeta.UID, 196 | Controller: &isController, 197 | }, 198 | }, 199 | }, 200 | Spec: v1alpha1.TaskSpec{ 201 | Task: job.Spec.Tasks[taskIndex], 202 | Connection: conn, 203 | }, 204 | } 205 | 206 | err := r.client.Create(ctx, task) 207 | if err != nil { 208 | return fmt.Errorf("failed to create Task %s/%s: %w", task.Namespace, task.Name, err) 209 | } 210 | 211 | return nil 212 | } 213 | 214 | // patchStatus patches the specified patch on the Job. 215 | func (r *JobReconciler) patchStatus(ctx context.Context, job *v1alpha1.Job, patch client.Patch) error { 216 | err := r.client.Status().Patch(ctx, job, patch) 217 | if err != nil { 218 | return fmt.Errorf("failed to patch Job %s/%s status: %w", job.Namespace, job.Name, err) 219 | } 220 | 221 | return nil 222 | } 223 | 224 | // SetupWithManager sets up the controller with the Manager. 225 | func (r *JobReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager, opts ctrlcontroller.Options) error { 226 | if err := mgr.GetFieldIndexer().IndexField( 227 | ctx, 228 | &v1alpha1.Task{}, 229 | jobOwnerKey, 230 | TaskOwnerIndexFunc, 231 | ); err != nil { 232 | return err 233 | } 234 | 235 | return ctrl.NewControllerManagedBy(mgr). 236 | For(&v1alpha1.Job{}). 237 | WithOptions(opts). 238 | Watches( 239 | &v1alpha1.Task{}, 240 | handler.EnqueueRequestForOwner( 241 | mgr.GetScheme(), 242 | mgr.GetRESTMapper(), 243 | &v1alpha1.Job{}, 244 | handler.OnlyControllerOwner(), 245 | ), 246 | ). 247 | Complete(r) 248 | } 249 | 250 | // TaskOwnerIndexFunc is Indexer func which returns the owner name for obj. 251 | func TaskOwnerIndexFunc(obj client.Object) []string { 252 | task, ok := obj.(*v1alpha1.Task) 253 | if !ok { 254 | return nil 255 | } 256 | 257 | owner := metav1.GetControllerOf(task) 258 | if owner == nil { 259 | return nil 260 | } 261 | 262 | // Check if owner is Job 263 | if owner.Kind != "Job" || owner.APIVersion != v1alpha1.GroupVersion.String() { 264 | return nil 265 | } 266 | 267 | return []string{owner.Name} 268 | } 269 | -------------------------------------------------------------------------------- /controller/job_test.go: -------------------------------------------------------------------------------- 1 | package controller_test 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | 7 | "github.com/google/go-cmp/cmp" 8 | "github.com/tinkerbell/rufio/api/v1alpha1" 9 | "github.com/tinkerbell/rufio/controller" 10 | corev1 "k8s.io/api/core/v1" 11 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 12 | "k8s.io/apimachinery/pkg/types" 13 | "sigs.k8s.io/controller-runtime/pkg/reconcile" 14 | ) 15 | 16 | func TestJobReconcile(t *testing.T) { 17 | tests := map[string]struct { 18 | machine *v1alpha1.Machine 19 | secret *corev1.Secret 20 | job *v1alpha1.Job 21 | shouldErr bool 22 | testAll bool 23 | }{ 24 | "success taskless job": { 25 | machine: createMachine(), 26 | secret: createSecret(), 27 | job: createJob("test", createMachine()), 28 | }, 29 | "failure unknown machine": { 30 | machine: &v1alpha1.Machine{}, 31 | secret: createSecret(), 32 | job: createJob("test", createMachine()), shouldErr: true, 33 | }, 34 | "success power on job": { 35 | machine: createMachine(), 36 | secret: createSecret(), 37 | job: createJob("test", createMachine(), getAction("PowerOn")), 38 | testAll: true, 39 | }, 40 | } 41 | 42 | for name, tt := range tests { 43 | t.Run(name, func(t *testing.T) { 44 | clnt := newClientBuilder(). 45 | WithObjects(tt.job, tt.machine, tt.secret). 46 | WithStatusSubresource(tt.job, tt.machine). 47 | WithIndex(&v1alpha1.Task{}, ".metadata.controller", controller.TaskOwnerIndexFunc). 48 | Build() 49 | 50 | reconciler := controller.NewJobReconciler(clnt) 51 | 52 | request := reconcile.Request{ 53 | NamespacedName: types.NamespacedName{ 54 | Namespace: tt.job.Namespace, 55 | Name: tt.job.Name, 56 | }, 57 | } 58 | 59 | _, err := reconciler.Reconcile(context.Background(), request) 60 | if !tt.shouldErr && err != nil { 61 | t.Fatalf("expected no error, got %v", err) 62 | } 63 | if tt.shouldErr && err == nil { 64 | t.Fatal("expected error, got nil") 65 | } 66 | if tt.shouldErr || !tt.testAll { 67 | return 68 | } 69 | var retrieved1 v1alpha1.Job 70 | if err = clnt.Get(context.Background(), request.NamespacedName, &retrieved1); err != nil { 71 | t.Fatalf("expected no error, got %v", err) 72 | } 73 | // TODO: g.Expect(retrieved1.Status.StartTime.Unix()).To(gomega.BeNumerically("~", time.Now().Unix(), 10)) 74 | if !retrieved1.Status.CompletionTime.IsZero() { 75 | t.Fatalf("expected CompletionTime to be zero, got %v", retrieved1.Status.CompletionTime) 76 | } 77 | if len(retrieved1.Status.Conditions) != 1 { 78 | t.Fatalf("expected 1 condition, got %v", len(retrieved1.Status.Conditions)) 79 | } 80 | if retrieved1.Status.Conditions[0].Type != v1alpha1.JobRunning { 81 | t.Fatalf("expected condition type %v, got %v", v1alpha1.JobRunning, retrieved1.Status.Conditions[0].Type) 82 | } 83 | if retrieved1.Status.Conditions[0].Status != v1alpha1.ConditionTrue { 84 | t.Fatalf("expected condition status %v, got %v", v1alpha1.ConditionTrue, retrieved1.Status.Conditions[0].Status) 85 | } 86 | 87 | var task v1alpha1.Task 88 | taskKey := types.NamespacedName{ 89 | Namespace: tt.job.Namespace, 90 | Name: v1alpha1.FormatTaskName(*tt.job, 0), 91 | } 92 | if err = clnt.Get(context.Background(), taskKey, &task); err != nil { 93 | t.Fatalf("expected no error, got %v", err) 94 | } 95 | if diff := cmp.Diff(task.Spec.Task, tt.job.Spec.Tasks[0]); diff != "" { 96 | t.Fatalf("expected task %v, got %v", tt.job.Spec.Tasks[0], task.Spec.Task) 97 | } 98 | if len(task.OwnerReferences) != 1 { 99 | t.Fatalf("expected 1 owner reference, got %v", len(task.OwnerReferences)) 100 | } 101 | if task.OwnerReferences[0].Name != tt.job.Name { 102 | t.Fatalf("expected owner reference name %v, got %v", tt.job.Name, task.OwnerReferences[0].Name) 103 | } 104 | if task.OwnerReferences[0].Kind != "Job" { 105 | t.Fatalf("expected OwnerReferences[0].Kind = 'Job', got '%v'", task.OwnerReferences[0].Kind) 106 | } 107 | 108 | // Ensure re-reconciling a job does nothing given the task is still outstanding. 109 | result, err := reconciler.Reconcile(context.Background(), request) 110 | if err != nil { 111 | t.Fatalf("expected no error, got %v", err) 112 | } 113 | if diff := cmp.Diff(result, reconcile.Result{}); diff != "" { 114 | t.Fatal(diff) 115 | } 116 | 117 | var retrieved2 v1alpha1.Job 118 | if err = clnt.Get(context.Background(), request.NamespacedName, &retrieved2); err != nil { 119 | t.Fatalf("expected no error, got %v", err) 120 | } 121 | if diff := cmp.Diff(retrieved1, retrieved2); diff != "" { 122 | t.Fatal(diff) 123 | } 124 | }) 125 | } 126 | } 127 | 128 | func createJob(name string, machine *v1alpha1.Machine, t ...v1alpha1.Action) *v1alpha1.Job { 129 | tasks := []v1alpha1.Action{} 130 | if len(t) > 0 { 131 | tasks = t 132 | } 133 | return &v1alpha1.Job{ 134 | TypeMeta: metav1.TypeMeta{ 135 | APIVersion: v1alpha1.GroupVersion.String(), 136 | Kind: "Job", 137 | }, 138 | ObjectMeta: metav1.ObjectMeta{ 139 | Namespace: "default", 140 | Name: name, 141 | }, 142 | Spec: v1alpha1.JobSpec{ 143 | MachineRef: v1alpha1.MachineRef{Name: machine.Name, Namespace: machine.Namespace}, 144 | Tasks: tasks, 145 | }, 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /controller/kube.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "strings" 7 | 8 | "github.com/tinkerbell/rufio/api/v1alpha1" 9 | v1 "k8s.io/api/core/v1" 10 | apierrors "k8s.io/apimachinery/pkg/api/errors" 11 | "k8s.io/apimachinery/pkg/types" 12 | "sigs.k8s.io/controller-runtime/pkg/client" 13 | ) 14 | 15 | // resolveAuthSecretRef Gets the Secret from the SecretReference. 16 | // Returns the username and password encoded in the Secret. 17 | func resolveAuthSecretRef(ctx context.Context, c client.Client, secretRef v1.SecretReference) (string, string, error) { 18 | secret := &v1.Secret{} 19 | key := types.NamespacedName{Namespace: secretRef.Namespace, Name: secretRef.Name} 20 | 21 | if err := c.Get(ctx, key, secret); err != nil { 22 | if apierrors.IsNotFound(err) { 23 | return "", "", fmt.Errorf("secret %s not found: %w", key, err) 24 | } 25 | 26 | return "", "", fmt.Errorf("failed to retrieve secret %s : %w", secretRef, err) 27 | } 28 | 29 | username, ok := secret.Data["username"] 30 | if !ok { 31 | return "", "", fmt.Errorf("'username' required in Machine secret") 32 | } 33 | 34 | password, ok := secret.Data["password"] 35 | if !ok { 36 | return "", "", fmt.Errorf("'password' required in Machine secret") 37 | } 38 | 39 | return string(username), string(password), nil 40 | } 41 | 42 | // toPowerState takes a raw BMC power state response and converts it to a v1alpha1.PowerState. 43 | func toPowerState(state string) v1alpha1.PowerState { 44 | // Normalize the response string for comparison. 45 | state = strings.ToLower(state) 46 | 47 | switch { 48 | case strings.Contains(state, "on"): 49 | return v1alpha1.On 50 | case strings.Contains(state, "off"): 51 | return v1alpha1.Off 52 | default: 53 | return v1alpha1.Unknown 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /controller/machine.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Tinkerbell. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package controller 18 | 19 | import ( 20 | "context" 21 | "fmt" 22 | "time" 23 | 24 | bmclib "github.com/bmc-toolbox/bmclib/v2" 25 | "github.com/bmc-toolbox/bmclib/v2/providers/rpc" 26 | "github.com/go-logr/logr" 27 | corev1 "k8s.io/api/core/v1" 28 | apierrors "k8s.io/apimachinery/pkg/api/errors" 29 | "k8s.io/apimachinery/pkg/types" 30 | utilerrors "k8s.io/apimachinery/pkg/util/errors" 31 | "k8s.io/client-go/tools/record" 32 | ctrlcontroller "sigs.k8s.io/controller-runtime/pkg/controller" 33 | 34 | ctrl "sigs.k8s.io/controller-runtime" 35 | "sigs.k8s.io/controller-runtime/pkg/client" 36 | 37 | "github.com/tinkerbell/rufio/api/v1alpha1" 38 | ) 39 | 40 | // MachineReconciler reconciles a Machine object. 41 | type MachineReconciler struct { 42 | client client.Client 43 | recorder record.EventRecorder 44 | bmcClient ClientFunc 45 | } 46 | 47 | const ( 48 | // machineRequeueInterval is the interval at which the machine's power state is reconciled. 49 | // This should only be used when the power state was successfully retrieved. 50 | machineRequeueInterval = 3 * time.Minute 51 | ) 52 | 53 | // NewMachineReconciler returns a new MachineReconciler. 54 | func NewMachineReconciler(c client.Client, recorder record.EventRecorder, bmcClientFactory ClientFunc) *MachineReconciler { 55 | return &MachineReconciler{ 56 | client: c, 57 | recorder: recorder, 58 | bmcClient: bmcClientFactory, 59 | } 60 | } 61 | 62 | //+kubebuilder:rbac:groups=bmc.tinkerbell.org,resources=machines,verbs=get;list;watch;create;update;patch;delete 63 | //+kubebuilder:rbac:groups=bmc.tinkerbell.org,resources=machines/status,verbs=get;update;patch 64 | //+kubebuilder:rbac:groups=bmc.tinkerbell.org,resources=machines/finalizers,verbs=update 65 | //+kubebuilder:rbac:groups="",resources=secrets;,verbs=get;list;watch 66 | 67 | // Reconcile reports on the state of a Machine. It does not change the state of the Machine in any way. 68 | // Updates the Power status and conditions accordingly. 69 | func (r *MachineReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { 70 | logger := ctrl.LoggerFrom(ctx).WithName("controllers/Machine") 71 | logger.Info("reconciling machine") 72 | 73 | // Fetch the Machine object 74 | machine := &v1alpha1.Machine{} 75 | if err := r.client.Get(ctx, req.NamespacedName, machine); err != nil { 76 | if apierrors.IsNotFound(err) { 77 | return ctrl.Result{}, nil 78 | } 79 | 80 | logger.Error(err, "failed to get Machine from KubeAPI") 81 | return ctrl.Result{}, err 82 | } 83 | 84 | // Deletion is a noop. 85 | if !machine.DeletionTimestamp.IsZero() { 86 | return ctrl.Result{}, nil 87 | } 88 | 89 | // Create a patch from the initial Machine object 90 | // Patch is used to update Status after reconciliation 91 | machinePatch := client.MergeFrom(machine.DeepCopy()) 92 | 93 | return r.doReconcile(ctx, machine, machinePatch, logger) 94 | } 95 | 96 | func (r *MachineReconciler) doReconcile(ctx context.Context, bm *v1alpha1.Machine, bmPatch client.Patch, logger logr.Logger) (ctrl.Result, error) { 97 | var username, password string 98 | opts := &BMCOptions{ 99 | ProviderOptions: bm.Spec.Connection.ProviderOptions, 100 | } 101 | if bm.Spec.Connection.ProviderOptions != nil && bm.Spec.Connection.ProviderOptions.RPC != nil { 102 | opts.ProviderOptions = bm.Spec.Connection.ProviderOptions 103 | if bm.Spec.Connection.ProviderOptions.RPC.HMAC != nil && len(bm.Spec.Connection.ProviderOptions.RPC.HMAC.Secrets) > 0 { 104 | se, err := retrieveHMACSecrets(ctx, r.client, bm.Spec.Connection.ProviderOptions.RPC.HMAC.Secrets) 105 | if err != nil { 106 | return ctrl.Result{}, fmt.Errorf("unable to get hmac secrets: %w", err) 107 | } 108 | opts.rpcSecrets = se 109 | } 110 | } else { 111 | // Fetching username, password from SecretReference 112 | // Requeue if error fetching secret 113 | var err error 114 | username, password, err = resolveAuthSecretRef(ctx, r.client, bm.Spec.Connection.AuthSecretRef) 115 | if err != nil { 116 | return ctrl.Result{}, fmt.Errorf("resolving Machine %s/%s SecretReference: %w", bm.Namespace, bm.Name, err) 117 | } 118 | } 119 | 120 | // Initializing BMC Client and Open the connection. 121 | bmcClient, err := r.bmcClient(ctx, logger, bm.Spec.Connection.Host, username, password, opts) 122 | if err != nil { 123 | logger.Error(err, "BMC connection failed", "host", bm.Spec.Connection.Host) 124 | bm.SetCondition(v1alpha1.Contactable, v1alpha1.ConditionFalse, v1alpha1.WithMachineConditionMessage(err.Error())) 125 | bm.Status.Power = v1alpha1.Unknown 126 | if patchErr := r.patchStatus(ctx, bm, bmPatch); patchErr != nil { 127 | return ctrl.Result{}, utilerrors.NewAggregate([]error{patchErr, err}) 128 | } 129 | 130 | // requeue as bmc connections can be transient. 131 | return ctrl.Result{RequeueAfter: machineRequeueInterval}, nil 132 | } 133 | 134 | // Close BMC connection after reconciliation 135 | defer func() { 136 | if err := bmcClient.Close(ctx); err != nil { 137 | md := bmcClient.GetMetadata() 138 | logger.Error(err, "BMC close connection failed", "host", bm.Spec.Connection.Host, "providersAttempted", md.ProvidersAttempted) 139 | 140 | return 141 | } 142 | md := bmcClient.GetMetadata() 143 | logger.Info("BMC connection closed", "host", bm.Spec.Connection.Host, "successfulCloseConns", md.SuccessfulCloseConns, "providersAttempted", md.ProvidersAttempted, "successfulProvider", md.SuccessfulProvider) 144 | }() 145 | 146 | contactable := v1alpha1.ConditionTrue 147 | conditionMsg := v1alpha1.WithMachineConditionMessage("") 148 | multiErr := []error{} 149 | pErr := r.updatePowerState(ctx, bm, bmcClient) 150 | if pErr != nil { 151 | logger.Error(pErr, "failed to get Machine power state", "host", bm.Spec.Connection.Host) 152 | contactable = v1alpha1.ConditionFalse 153 | conditionMsg = v1alpha1.WithMachineConditionMessage(pErr.Error()) 154 | multiErr = append(multiErr, pErr) 155 | } 156 | 157 | // Set condition. 158 | bm.SetCondition(v1alpha1.Contactable, contactable, conditionMsg) 159 | 160 | // Patch the status after each reconciliation 161 | if err := r.patchStatus(ctx, bm, bmPatch); err != nil { 162 | multiErr = append(multiErr, err) 163 | return ctrl.Result{}, utilerrors.NewAggregate(multiErr) 164 | } 165 | 166 | return ctrl.Result{RequeueAfter: machineRequeueInterval}, nil 167 | } 168 | 169 | // updatePowerState gets the current power state of the machine. 170 | func (r *MachineReconciler) updatePowerState(ctx context.Context, bm *v1alpha1.Machine, bmcClient *bmclib.Client) error { 171 | rawState, err := bmcClient.GetPowerState(ctx) 172 | if err != nil { 173 | bm.Status.Power = v1alpha1.Unknown 174 | r.recorder.Eventf(bm, corev1.EventTypeWarning, "GetPowerStateFailed", "get power state: %v", err) 175 | return fmt.Errorf("get power state: %w", err) 176 | } 177 | 178 | bm.Status.Power = toPowerState(rawState) 179 | 180 | return nil 181 | } 182 | 183 | // patchStatus patches the specifies patch on the Machine. 184 | func (r *MachineReconciler) patchStatus(ctx context.Context, bm *v1alpha1.Machine, patch client.Patch) error { 185 | if err := r.client.Status().Patch(ctx, bm, patch); err != nil { 186 | return fmt.Errorf("failed to patch Machine %s/%s status: %w", bm.Namespace, bm.Name, err) 187 | } 188 | 189 | return nil 190 | } 191 | 192 | func retrieveHMACSecrets(ctx context.Context, c client.Client, hmacSecrets v1alpha1.HMACSecrets) (rpc.Secrets, error) { 193 | sec := rpc.Secrets{} 194 | for k, v := range hmacSecrets { 195 | for _, s := range v { 196 | secret := &corev1.Secret{} 197 | key := types.NamespacedName{Namespace: s.Namespace, Name: s.Name} 198 | 199 | if err := c.Get(ctx, key, secret); err != nil { 200 | if apierrors.IsNotFound(err) { 201 | return nil, fmt.Errorf("secret %s not found: %w", key, err) 202 | } 203 | 204 | return nil, fmt.Errorf("failed to retrieve secret %s : %w", s, err) 205 | } 206 | 207 | sec[rpc.Algorithm(k)] = append(sec[rpc.Algorithm(k)], string(secret.Data["secret"])) 208 | } 209 | } 210 | 211 | return sec, nil 212 | } 213 | 214 | // SetupWithManager sets up the controller with the Manager. 215 | func (r *MachineReconciler) SetupWithManager(mgr ctrl.Manager, opts ctrlcontroller.Options) error { 216 | return ctrl.NewControllerManagedBy(mgr). 217 | For(&v1alpha1.Machine{}). 218 | WithOptions(opts). 219 | Complete(r) 220 | } 221 | -------------------------------------------------------------------------------- /controller/machine_test.go: -------------------------------------------------------------------------------- 1 | package controller_test 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "testing" 7 | 8 | corev1 "k8s.io/api/core/v1" 9 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 10 | "k8s.io/apimachinery/pkg/types" 11 | "k8s.io/client-go/tools/record" 12 | "sigs.k8s.io/controller-runtime/pkg/reconcile" 13 | 14 | "github.com/tinkerbell/rufio/api/v1alpha1" 15 | "github.com/tinkerbell/rufio/controller" 16 | ) 17 | 18 | func TestMachineReconcile(t *testing.T) { 19 | tests := map[string]struct { 20 | provider *testProvider 21 | shouldErr bool 22 | secret *corev1.Secret 23 | machine *v1alpha1.Machine 24 | }{ 25 | "success power on": { 26 | provider: &testProvider{Powerstate: "on"}, 27 | secret: createSecret(), 28 | }, 29 | 30 | "success power off": { 31 | provider: &testProvider{Powerstate: "off"}, 32 | secret: createSecret(), 33 | }, 34 | 35 | "success power on with RPC provider": { 36 | provider: &testProvider{Powerstate: "on", Proto: "rpc"}, 37 | secret: createHMACSecret(), 38 | machine: createMachineWithRPC(createHMACSecret()), 39 | }, 40 | 41 | "success power on with RPC provider w/o secrets": { 42 | provider: &testProvider{Powerstate: "on", Proto: "rpc"}, 43 | secret: createSecret(), 44 | machine: createMachineWithRPC(nil), 45 | }, 46 | 47 | "fail to find secret with RPC provider": { 48 | provider: &testProvider{Powerstate: "on", Proto: "rpc"}, 49 | secret: createHMACSecret(), 50 | shouldErr: true, 51 | machine: createMachineWithRPC(&corev1.Secret{ 52 | ObjectMeta: metav1.ObjectMeta{ 53 | Namespace: "test-namespace", 54 | Name: "test-bm-auths", 55 | }, 56 | Data: map[string][]byte{ 57 | "secret": []byte("test"), 58 | }, 59 | }), 60 | }, 61 | 62 | "fail on open": { 63 | provider: &testProvider{ErrOpen: errors.New("failed to open connection")}, 64 | secret: createSecret(), 65 | }, 66 | 67 | "fail on power get": { 68 | provider: &testProvider{ErrPowerStateGet: errors.New("failed to set power state")}, 69 | secret: createSecret(), 70 | }, 71 | 72 | "fail bad power state": { 73 | provider: &testProvider{Powerstate: "bad"}, 74 | secret: createSecret(), 75 | }, 76 | 77 | "fail on close": { 78 | provider: &testProvider{ErrClose: errors.New("failed to close connection")}, 79 | secret: createSecret(), 80 | }, 81 | 82 | "fail secret not found": { 83 | provider: &testProvider{Powerstate: "on"}, 84 | shouldErr: true, 85 | secret: &corev1.Secret{}, 86 | }, 87 | 88 | "fail secret username not found": { 89 | provider: &testProvider{Powerstate: "on"}, 90 | shouldErr: true, 91 | secret: &corev1.Secret{ 92 | ObjectMeta: metav1.ObjectMeta{ 93 | Namespace: "test-namespace", 94 | Name: "test-bm-auth", 95 | }, 96 | Data: map[string][]byte{ 97 | "password": []byte("test"), 98 | }, 99 | }, 100 | }, 101 | 102 | "fail secret password not found": { 103 | provider: &testProvider{Powerstate: "on"}, 104 | shouldErr: true, 105 | secret: &corev1.Secret{ 106 | ObjectMeta: metav1.ObjectMeta{ 107 | Namespace: "test-namespace", 108 | Name: "test-bm-auth", 109 | }, 110 | Data: map[string][]byte{ 111 | "username": []byte("test"), 112 | }, 113 | }, 114 | }, 115 | } 116 | 117 | for name, tt := range tests { 118 | t.Run(name, func(t *testing.T) { 119 | var bm *v1alpha1.Machine 120 | if tt.machine != nil { 121 | bm = tt.machine 122 | } else { 123 | bm = createMachine() 124 | } 125 | 126 | client := newClientBuilder(). 127 | WithObjects(bm, tt.secret). 128 | WithStatusSubresource(bm). 129 | Build() 130 | 131 | fakeRecorder := record.NewFakeRecorder(2) 132 | 133 | reconciler := controller.NewMachineReconciler( 134 | client, 135 | fakeRecorder, 136 | newTestClient(tt.provider), 137 | ) 138 | 139 | req := reconcile.Request{ 140 | NamespacedName: types.NamespacedName{ 141 | Namespace: "test-namespace", 142 | Name: "test-bm", 143 | }, 144 | } 145 | 146 | _, err := reconciler.Reconcile(context.Background(), req) 147 | if !tt.shouldErr && err != nil { 148 | t.Fatalf("expected no error, got %v", err) 149 | } 150 | if tt.shouldErr && err == nil { 151 | t.Fatal("expected error, got nil") 152 | } 153 | }) 154 | } 155 | } 156 | 157 | func createMachineWithRPC(secret *corev1.Secret) *v1alpha1.Machine { 158 | machine := &v1alpha1.Machine{ 159 | ObjectMeta: metav1.ObjectMeta{ 160 | Name: "test-bm", 161 | Namespace: "test-namespace", 162 | }, 163 | Spec: v1alpha1.MachineSpec{ 164 | Connection: v1alpha1.Connection{ 165 | Host: "127.1.1.1", 166 | InsecureTLS: false, 167 | ProviderOptions: &v1alpha1.ProviderOptions{ 168 | RPC: &v1alpha1.RPCOptions{ 169 | ConsumerURL: "http://127.0.0.1:7777", 170 | }, 171 | }, 172 | }, 173 | }, 174 | } 175 | 176 | if secret != nil { 177 | machine.Spec.Connection.ProviderOptions.RPC.HMAC = &v1alpha1.HMACOpts{ 178 | Secrets: v1alpha1.HMACSecrets{ 179 | "sha256": []corev1.SecretReference{ 180 | { 181 | Name: secret.Name, 182 | Namespace: secret.Namespace, 183 | }, 184 | }, 185 | }, 186 | } 187 | } 188 | 189 | return machine 190 | } 191 | 192 | func createMachine() *v1alpha1.Machine { 193 | return &v1alpha1.Machine{ 194 | ObjectMeta: metav1.ObjectMeta{ 195 | Name: "test-bm", 196 | Namespace: "test-namespace", 197 | }, 198 | Spec: v1alpha1.MachineSpec{ 199 | Connection: v1alpha1.Connection{ 200 | Host: "0.0.0.0", 201 | Port: 623, 202 | AuthSecretRef: corev1.SecretReference{ 203 | Name: "test-bm-auth", 204 | Namespace: "test-namespace", 205 | }, 206 | InsecureTLS: false, 207 | ProviderOptions: &v1alpha1.ProviderOptions{ 208 | Redfish: &v1alpha1.RedfishOptions{ 209 | Port: 443, 210 | }, 211 | }, 212 | }, 213 | }, 214 | } 215 | } 216 | 217 | func createSecret() *corev1.Secret { 218 | return &corev1.Secret{ 219 | ObjectMeta: metav1.ObjectMeta{ 220 | Namespace: "test-namespace", 221 | Name: "test-bm-auth", 222 | }, 223 | Data: map[string][]byte{ 224 | "username": []byte("test"), 225 | "password": []byte("test"), 226 | }, 227 | } 228 | } 229 | 230 | func createHMACSecret() *corev1.Secret { 231 | return &corev1.Secret{ 232 | ObjectMeta: metav1.ObjectMeta{ 233 | Namespace: "test-namespace", 234 | Name: "test-bm-hmac", 235 | }, 236 | Data: map[string][]byte{ 237 | "secret": []byte("superSecret1"), 238 | }, 239 | } 240 | } 241 | -------------------------------------------------------------------------------- /controller/task.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Tinkerbell. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package controller 15 | 16 | import ( 17 | "context" 18 | "fmt" 19 | "time" 20 | 21 | bmclib "github.com/bmc-toolbox/bmclib/v2" 22 | "github.com/go-logr/logr" 23 | apierrors "k8s.io/apimachinery/pkg/api/errors" 24 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 25 | utilerrors "k8s.io/apimachinery/pkg/util/errors" 26 | ctrl "sigs.k8s.io/controller-runtime" 27 | "sigs.k8s.io/controller-runtime/pkg/client" 28 | ctrlcontroller "sigs.k8s.io/controller-runtime/pkg/controller" 29 | 30 | "github.com/tinkerbell/rufio/api/v1alpha1" 31 | ) 32 | 33 | const powerActionRequeueAfter = 3 * time.Second 34 | 35 | // TaskReconciler reconciles a Task object. 36 | type TaskReconciler struct { 37 | client client.Client 38 | bmcClientFactory ClientFunc 39 | } 40 | 41 | // NewTaskReconciler returns a new TaskReconciler. 42 | func NewTaskReconciler(c client.Client, bmcClientFactory ClientFunc) *TaskReconciler { 43 | return &TaskReconciler{ 44 | client: c, 45 | bmcClientFactory: bmcClientFactory, 46 | } 47 | } 48 | 49 | //+kubebuilder:rbac:groups=bmc.tinkerbell.org,resources=tasks,verbs=get;list;watch;create;update;patch;delete 50 | //+kubebuilder:rbac:groups=bmc.tinkerbell.org,resources=tasks/status,verbs=get;update;patch 51 | //+kubebuilder:rbac:groups=bmc.tinkerbell.org,resources=tasks/finalizers,verbs=update 52 | 53 | // Reconcile runs a Task. 54 | // Establishes a connection to the BMC. 55 | // Runs the specified action in the Task. 56 | func (r *TaskReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { 57 | logger := ctrl.LoggerFrom(ctx).WithName("controllers/Task").WithValues("task", req.NamespacedName) 58 | logger.Info("Reconciling Task") 59 | 60 | // Fetch the Task object 61 | task := &v1alpha1.Task{} 62 | if err := r.client.Get(ctx, req.NamespacedName, task); err != nil { 63 | if apierrors.IsNotFound(err) { 64 | return ctrl.Result{}, nil 65 | } 66 | 67 | logger.Error(err, "Failed to get Task") 68 | return ctrl.Result{}, err 69 | } 70 | 71 | // Deletion is a noop. 72 | if !task.DeletionTimestamp.IsZero() { 73 | return ctrl.Result{}, nil 74 | } 75 | 76 | // Task is Completed or Failed is noop. 77 | if task.HasCondition(v1alpha1.TaskFailed, v1alpha1.ConditionTrue) || 78 | task.HasCondition(v1alpha1.TaskCompleted, v1alpha1.ConditionTrue) { 79 | return ctrl.Result{}, nil 80 | } 81 | 82 | // Create a patch from the initial Task object 83 | // Patch is used to update Status after reconciliation 84 | taskPatch := client.MergeFrom(task.DeepCopy()) 85 | logger = logger.WithValues("action", task.Spec.Task, "host", task.Spec.Connection.Host) 86 | 87 | return r.doReconcile(ctx, task, taskPatch, logger) 88 | } 89 | 90 | func (r *TaskReconciler) doReconcile(ctx context.Context, task *v1alpha1.Task, taskPatch client.Patch, logger logr.Logger) (ctrl.Result, error) { 91 | var username, password string 92 | opts := &BMCOptions{ 93 | ProviderOptions: task.Spec.Connection.ProviderOptions, 94 | } 95 | if task.Spec.Connection.ProviderOptions != nil && task.Spec.Connection.ProviderOptions.RPC != nil { 96 | opts.ProviderOptions = task.Spec.Connection.ProviderOptions 97 | if task.Spec.Connection.ProviderOptions.RPC.HMAC != nil && len(task.Spec.Connection.ProviderOptions.RPC.HMAC.Secrets) > 0 { 98 | se, err := retrieveHMACSecrets(ctx, r.client, task.Spec.Connection.ProviderOptions.RPC.HMAC.Secrets) 99 | if err != nil { 100 | return ctrl.Result{}, fmt.Errorf("unable to get hmac secrets: %w", err) 101 | } 102 | opts.rpcSecrets = se 103 | } 104 | } else { 105 | // Fetching username, password from SecretReference in Connection. 106 | // Requeue if error fetching secret 107 | var err error 108 | username, password, err = resolveAuthSecretRef(ctx, r.client, task.Spec.Connection.AuthSecretRef) 109 | if err != nil { 110 | return ctrl.Result{}, fmt.Errorf("resolving connection secret for task %s/%s: %w", task.Namespace, task.Name, err) 111 | } 112 | } 113 | 114 | // Initializing BMC Client 115 | bmcClient, err := r.bmcClientFactory(ctx, logger, task.Spec.Connection.Host, username, password, opts) 116 | if err != nil { 117 | logger.Error(err, "BMC connection failed", "host", task.Spec.Connection.Host) 118 | task.SetCondition(v1alpha1.TaskFailed, v1alpha1.ConditionTrue, v1alpha1.WithTaskConditionMessage(fmt.Sprintf("Failed to connect to BMC: %v", err))) 119 | patchErr := r.patchStatus(ctx, task, taskPatch) 120 | if patchErr != nil { 121 | return ctrl.Result{}, utilerrors.NewAggregate([]error{patchErr, err}) 122 | } 123 | 124 | return ctrl.Result{}, err 125 | } 126 | defer func() { 127 | // Close BMC connection after reconciliation 128 | if err := bmcClient.Close(ctx); err != nil { 129 | md := bmcClient.GetMetadata() 130 | logger.Error(err, "BMC close connection failed", "providersAttempted", md.ProvidersAttempted) 131 | 132 | return 133 | } 134 | md := bmcClient.GetMetadata() 135 | logger.Info("BMC connection closed", "successfulCloseConns", md.SuccessfulCloseConns, "providersAttempted", md.ProvidersAttempted, "successfulProvider", md.SuccessfulProvider) 136 | }() 137 | 138 | // Task has StartTime, we check the status. 139 | // Requeue if actions did not complete. 140 | if !task.Status.StartTime.IsZero() { 141 | jobRunningTime := time.Since(task.Status.StartTime.Time) 142 | // TODO(pokearu): add timeout for tasks on API spec 143 | if jobRunningTime >= 10*time.Minute { 144 | timeOutErr := fmt.Errorf("bmc task timeout: %d", jobRunningTime) 145 | // Set Task Condition Failed True 146 | task.SetCondition(v1alpha1.TaskFailed, v1alpha1.ConditionTrue, v1alpha1.WithTaskConditionMessage(timeOutErr.Error())) 147 | patchErr := r.patchStatus(ctx, task, taskPatch) 148 | if patchErr != nil { 149 | return ctrl.Result{}, utilerrors.NewAggregate([]error{patchErr, timeOutErr}) 150 | } 151 | 152 | return ctrl.Result{}, timeOutErr 153 | } 154 | 155 | result, err := r.checkTaskStatus(ctx, logger, task.Spec.Task, bmcClient) 156 | if err != nil { 157 | return result, fmt.Errorf("bmc task status check: %w", err) 158 | } 159 | 160 | if !result.IsZero() { 161 | return result, nil 162 | } 163 | 164 | // Set the Task CompletionTime 165 | now := metav1.Now() 166 | task.Status.CompletionTime = &now 167 | // Set Task Condition Completed True 168 | task.SetCondition(v1alpha1.TaskCompleted, v1alpha1.ConditionTrue) 169 | if err := r.patchStatus(ctx, task, taskPatch); err != nil { 170 | return result, err 171 | } 172 | 173 | return result, nil 174 | } 175 | 176 | logger.Info("new task run") 177 | 178 | // Set the Task StartTime 179 | now := metav1.Now() 180 | task.Status.StartTime = &now 181 | // run the specified Task in Task 182 | if err := r.runTask(ctx, logger, task.Spec.Task, bmcClient); err != nil { 183 | md := bmcClient.GetMetadata() 184 | logger.Info("failed to perform action", "providersAttempted", md.ProvidersAttempted, "action", task.Spec.Task) 185 | // Set Task Condition Failed True 186 | task.SetCondition(v1alpha1.TaskFailed, v1alpha1.ConditionTrue, v1alpha1.WithTaskConditionMessage(err.Error())) 187 | patchErr := r.patchStatus(ctx, task, taskPatch) 188 | if patchErr != nil { 189 | return ctrl.Result{}, utilerrors.NewAggregate([]error{patchErr, err}) 190 | } 191 | 192 | return ctrl.Result{}, err 193 | } 194 | 195 | if err := r.patchStatus(ctx, task, taskPatch); err != nil { 196 | return ctrl.Result{}, err 197 | } 198 | 199 | return ctrl.Result{}, nil 200 | } 201 | 202 | // runTask executes the defined Task in a Task. 203 | func (r *TaskReconciler) runTask(ctx context.Context, logger logr.Logger, task v1alpha1.Action, bmcClient *bmclib.Client) error { 204 | if task.PowerAction != nil { 205 | ok, err := bmcClient.SetPowerState(ctx, string(*task.PowerAction)) 206 | if err != nil { 207 | return fmt.Errorf("failed to perform PowerAction: %w", err) 208 | } 209 | md := bmcClient.GetMetadata() 210 | logger.Info("power state set successfully", "providersAttempted", md.ProvidersAttempted, "successfulProvider", md.SuccessfulProvider, "ok", ok) 211 | } 212 | 213 | if task.OneTimeBootDeviceAction != nil { 214 | // OneTimeBootDeviceAction currently sets the first boot device from Devices. 215 | // setPersistent is false. 216 | ok, err := bmcClient.SetBootDevice(ctx, string(task.OneTimeBootDeviceAction.Devices[0]), false, task.OneTimeBootDeviceAction.EFIBoot) 217 | if err != nil { 218 | return fmt.Errorf("failed to perform OneTimeBootDeviceAction: %w", err) 219 | } 220 | md := bmcClient.GetMetadata() 221 | logger.Info("one time boot device set successfully", "providersAttempted", md.ProvidersAttempted, "successfulProvider", md.SuccessfulProvider, "ok", ok) 222 | } 223 | 224 | if task.VirtualMediaAction != nil { 225 | ok, err := bmcClient.SetVirtualMedia(ctx, string(task.VirtualMediaAction.Kind), task.VirtualMediaAction.MediaURL) 226 | if err != nil { 227 | return fmt.Errorf("failed to perform SetVirtualMedia: %w", err) 228 | } 229 | md := bmcClient.GetMetadata() 230 | logger.Info("virtual media set successfully", "providersAttempted", md.ProvidersAttempted, "successfulProvider", md.SuccessfulProvider, "ok", ok) 231 | } 232 | 233 | return nil 234 | } 235 | 236 | // checkTaskStatus checks if Task action completed. 237 | // This is currently limited only to a few PowerAction types. 238 | func (r *TaskReconciler) checkTaskStatus(ctx context.Context, log logr.Logger, task v1alpha1.Action, bmcClient *bmclib.Client) (ctrl.Result, error) { 239 | // TODO(pokearu): Extend to all actions. 240 | if task.PowerAction != nil { 241 | rawState, err := bmcClient.GetPowerState(ctx) 242 | if err != nil { 243 | return ctrl.Result{}, fmt.Errorf("failed to get power state: %w", err) 244 | } 245 | log = log.WithValues("currentPowerState", rawState) 246 | log.Info("power state check") 247 | 248 | state := toPowerState(rawState) 249 | 250 | switch *task.PowerAction { //nolint:exhaustive // we only support a few power actions right now. 251 | case v1alpha1.PowerOn: 252 | if state != v1alpha1.On { 253 | log.Info("requeuing task", "requeueAfter", powerActionRequeueAfter) 254 | return ctrl.Result{RequeueAfter: powerActionRequeueAfter}, nil 255 | } 256 | case v1alpha1.PowerHardOff, v1alpha1.PowerSoftOff: 257 | if v1alpha1.Off != state { 258 | return ctrl.Result{RequeueAfter: powerActionRequeueAfter}, nil 259 | } 260 | } 261 | } 262 | 263 | // Other Task action types do not support checking status. So noop. 264 | return ctrl.Result{}, nil 265 | } 266 | 267 | // patchStatus patches the specified patch on the Task. 268 | func (r *TaskReconciler) patchStatus(ctx context.Context, task *v1alpha1.Task, patch client.Patch) error { 269 | err := r.client.Status().Patch(ctx, task, patch) 270 | if err != nil { 271 | return fmt.Errorf("failed to patch Task %s/%s status: %w", task.Namespace, task.Name, err) 272 | } 273 | 274 | return nil 275 | } 276 | 277 | // SetupWithManager sets up the controller with the Manager. 278 | func (r *TaskReconciler) SetupWithManager(mgr ctrl.Manager, opts ctrlcontroller.Options) error { 279 | return ctrl.NewControllerManagedBy(mgr). 280 | For(&v1alpha1.Task{}). 281 | WithOptions(opts). 282 | Complete(r) 283 | } 284 | -------------------------------------------------------------------------------- /controller/task_test.go: -------------------------------------------------------------------------------- 1 | package controller_test 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "testing" 7 | "time" 8 | 9 | "github.com/google/go-cmp/cmp" 10 | "github.com/tinkerbell/rufio/api/v1alpha1" 11 | "github.com/tinkerbell/rufio/controller" 12 | corev1 "k8s.io/api/core/v1" 13 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 14 | "k8s.io/apimachinery/pkg/types" 15 | ctrl "sigs.k8s.io/controller-runtime" 16 | "sigs.k8s.io/controller-runtime/pkg/reconcile" 17 | ) 18 | 19 | func getAction(s string) v1alpha1.Action { 20 | switch s { 21 | case "PowerOn": 22 | return v1alpha1.Action{PowerAction: v1alpha1.PowerOn.Ptr()} 23 | case "HardOff": 24 | return v1alpha1.Action{PowerAction: v1alpha1.PowerHardOff.Ptr()} 25 | case "SoftOff": 26 | return v1alpha1.Action{PowerAction: v1alpha1.PowerSoftOff.Ptr()} 27 | case "BootPXE": 28 | return v1alpha1.Action{OneTimeBootDeviceAction: &v1alpha1.OneTimeBootDeviceAction{Devices: []v1alpha1.BootDevice{v1alpha1.PXE}}} 29 | case "VirtualMedia": 30 | return v1alpha1.Action{VirtualMediaAction: &v1alpha1.VirtualMediaAction{MediaURL: "http://example.com/image.iso", Kind: v1alpha1.VirtualMediaCD}} 31 | default: 32 | return v1alpha1.Action{} 33 | } 34 | } 35 | 36 | func TestTaskReconcile(t *testing.T) { 37 | tests := map[string]struct { 38 | taskName string 39 | action v1alpha1.Action 40 | provider *testProvider 41 | secret *corev1.Secret 42 | task *v1alpha1.Task 43 | shouldErr bool 44 | timeoutErr bool 45 | }{ 46 | "success power on": { 47 | taskName: "PowerOn", 48 | action: getAction("PowerOn"), 49 | provider: &testProvider{Powerstate: "on", PowerSetOK: true}, 50 | }, 51 | 52 | "success hard off": { 53 | taskName: "HardOff", 54 | action: getAction("HardOff"), 55 | provider: &testProvider{Powerstate: "off", PowerSetOK: true}, 56 | }, 57 | 58 | "success soft off": { 59 | taskName: "SoftOff", 60 | action: getAction("SoftOff"), 61 | provider: &testProvider{Powerstate: "off", PowerSetOK: true}, 62 | }, 63 | 64 | "success boot pxe": { 65 | taskName: "BootPXE", 66 | action: getAction("BootPXE"), 67 | provider: &testProvider{BootdeviceOK: true}, 68 | }, 69 | 70 | "success virtual media": { 71 | taskName: "VirtualMedia", 72 | action: getAction("VirtualMedia"), 73 | provider: &testProvider{VirtualMediaOK: true}, 74 | }, 75 | 76 | "success power on with rpc provider": { 77 | taskName: "PowerOn", 78 | action: getAction("PowerOn"), 79 | provider: &testProvider{Powerstate: "on", PowerSetOK: true, Proto: "rpc"}, 80 | secret: createHMACSecret(), 81 | task: createTaskWithRPC("PowerOn", getAction("PowerOn"), createHMACSecret()), 82 | }, 83 | 84 | "success power on with RPC provider w/o secrets": { 85 | taskName: "PowerOn", 86 | action: getAction("PowerOn"), 87 | provider: &testProvider{Powerstate: "on", PowerSetOK: true, Proto: "rpc"}, 88 | }, 89 | 90 | "failure on bmc open": { 91 | taskName: "PowerOn", action: getAction("PowerOn"), 92 | provider: &testProvider{ErrOpen: errors.New("failed to open")}, 93 | shouldErr: true, 94 | }, 95 | 96 | "failure on bmc power on": { 97 | taskName: "PowerOn", 98 | action: getAction("PowerOn"), 99 | provider: &testProvider{ErrPowerStateSet: errors.New("failed to set power state")}, 100 | shouldErr: true, 101 | }, 102 | 103 | "failure on set boot device": { 104 | taskName: "BootPXE", 105 | action: getAction("BootPXE"), 106 | provider: &testProvider{ErrBootDeviceSet: errors.New("failed to set boot device")}, 107 | shouldErr: true, 108 | }, 109 | 110 | "failure on virtual media": { 111 | taskName: "VirtualMedia", 112 | action: getAction("VirtualMedia"), 113 | provider: &testProvider{ErrVirtualMediaInsert: errors.New("failed to set virtual media")}, 114 | shouldErr: true, 115 | }, 116 | 117 | "failure timeout": { 118 | taskName: "PowerOn", 119 | action: getAction("PowerOn"), 120 | provider: &testProvider{Powerstate: "off", PowerSetOK: true}, 121 | timeoutErr: true, 122 | }, 123 | 124 | "fail to find secret": { 125 | taskName: "PowerOn", 126 | action: getAction("PowerOn"), 127 | provider: &testProvider{Powerstate: "off", PowerSetOK: true}, 128 | secret: &corev1.Secret{}, 129 | task: createTask("PowerOn", getAction("PowerOn"), &corev1.Secret{}), 130 | shouldErr: true, 131 | }, 132 | } 133 | 134 | for name, tt := range tests { 135 | t.Run(name, func(t *testing.T) { 136 | var secret *corev1.Secret 137 | if tt.secret != nil { 138 | secret = tt.secret 139 | } else { 140 | secret = createSecret() 141 | } 142 | var task *v1alpha1.Task 143 | if tt.task != nil { 144 | task = tt.task 145 | } else { 146 | task = createTask(tt.taskName, tt.action, secret) 147 | } 148 | 149 | cluster := newClientBuilder(). 150 | WithObjects(task, secret). 151 | WithStatusSubresource(task). 152 | Build() 153 | 154 | reconciler := controller.NewTaskReconciler(cluster, newTestClient(tt.provider)) 155 | request := reconcile.Request{ 156 | NamespacedName: types.NamespacedName{ 157 | Namespace: task.Namespace, 158 | Name: task.Name, 159 | }, 160 | } 161 | 162 | result, err := reconciler.Reconcile(context.Background(), request) 163 | if !tt.shouldErr && err != nil { 164 | t.Fatalf("expected nil err, got: %v", err) 165 | } 166 | if tt.shouldErr && err == nil { 167 | t.Fatalf("expected err, got: %v", err) 168 | } 169 | if tt.shouldErr { 170 | return 171 | } 172 | if diff := cmp.Diff(result, ctrl.Result{}); diff != "" { 173 | t.Fatalf("expected no diff, got: %v", diff) 174 | } 175 | 176 | var retrieved v1alpha1.Task 177 | if err = cluster.Get(context.Background(), request.NamespacedName, &retrieved); err != nil { 178 | t.Fatalf("expected nil err, got: %v", err) 179 | } 180 | // TODO: g.Expect(retrieved.Status.StartTime.Unix()).To(gomega.BeNumerically("~", time.Now().Unix(), 2)) 181 | if !retrieved.Status.CompletionTime.IsZero() { 182 | t.Fatalf("expected completion time to be zero, got: %v", retrieved.Status.CompletionTime) 183 | } 184 | if len(retrieved.Status.Conditions) != 0 { 185 | t.Fatalf("expected no conditions, got: %v", retrieved.Status.Conditions) 186 | } 187 | 188 | // Timeout check 189 | if tt.timeoutErr { 190 | expired := metav1.NewTime(retrieved.Status.StartTime.Add(-time.Hour)) 191 | retrieved.Status.StartTime = &expired 192 | if err = cluster.Status().Update(context.Background(), &retrieved); err != nil { 193 | t.Fatalf("expected nil err, got: %v", err) 194 | } 195 | 196 | result, err = reconciler.Reconcile(context.Background(), request) 197 | if err == nil { 198 | t.Fatalf("expected err, got: %v", err) 199 | } 200 | if diff := cmp.Diff(result, ctrl.Result{}); diff != "" { 201 | t.Fatalf("expected no diff, got: %v", diff) 202 | } 203 | return 204 | } 205 | 206 | // Ensure re-reconciling a task does sends it into a success state. 207 | result, err = reconciler.Reconcile(context.Background(), request) 208 | if err != nil { 209 | t.Fatalf("expected nil err, got: %v", err) 210 | } 211 | if diff := cmp.Diff(result, reconcile.Result{}); diff != "" { 212 | t.Fatalf("expected no diff, got: %v", diff) 213 | } 214 | 215 | err = cluster.Get(context.Background(), request.NamespacedName, &retrieved) 216 | if err != nil { 217 | t.Fatalf("expected nil err, got: %v", err) 218 | } 219 | // TODO: g.Expect(retrieved.Status.CompletionTime.Unix()).To(gomega.BeNumerically("~", time.Now().Unix(), 2)) 220 | if len(retrieved.Status.Conditions) != 1 { 221 | t.Fatalf("expected 1 condition, got: %v", retrieved.Status.Conditions) 222 | } 223 | if retrieved.Status.Conditions[0].Type != v1alpha1.TaskCompleted { 224 | t.Fatalf("expected condition type to be %s, got: %s", v1alpha1.TaskCompleted, retrieved.Status.Conditions[0].Type) 225 | } 226 | if retrieved.Status.Conditions[0].Status != v1alpha1.ConditionTrue { 227 | t.Fatalf("expected condition status to be %s, got: %s", v1alpha1.ConditionTrue, retrieved.Status.Conditions[0].Status) 228 | } 229 | 230 | var retrieved2 v1alpha1.Task 231 | err = cluster.Get(context.Background(), request.NamespacedName, &retrieved2) 232 | if err != nil { 233 | t.Fatalf("expected nil err, got: %v", err) 234 | } 235 | if diff := cmp.Diff(retrieved2, retrieved); diff != "" { 236 | t.Fatalf("expected no diff, got: %v", diff) 237 | } 238 | }) 239 | } 240 | } 241 | 242 | func createTask(name string, action v1alpha1.Action, secret *corev1.Secret) *v1alpha1.Task { 243 | return &v1alpha1.Task{ 244 | ObjectMeta: metav1.ObjectMeta{ 245 | Name: name, 246 | Namespace: "default", 247 | }, 248 | Spec: v1alpha1.TaskSpec{ 249 | Task: action, 250 | Connection: v1alpha1.Connection{ 251 | Host: "host", 252 | Port: 22, 253 | AuthSecretRef: corev1.SecretReference{ 254 | Name: secret.Name, 255 | Namespace: secret.Namespace, 256 | }, 257 | ProviderOptions: &v1alpha1.ProviderOptions{ 258 | Redfish: &v1alpha1.RedfishOptions{ 259 | Port: 443, 260 | }, 261 | }, 262 | }, 263 | }, 264 | } 265 | } 266 | 267 | func createTaskWithRPC(name string, action v1alpha1.Action, secret *corev1.Secret) *v1alpha1.Task { 268 | machine := &v1alpha1.Task{ 269 | ObjectMeta: metav1.ObjectMeta{ 270 | Name: name, 271 | Namespace: "default", 272 | }, 273 | Spec: v1alpha1.TaskSpec{ 274 | Task: action, 275 | Connection: v1alpha1.Connection{ 276 | Host: "host", 277 | Port: 22, 278 | ProviderOptions: &v1alpha1.ProviderOptions{ 279 | RPC: &v1alpha1.RPCOptions{ 280 | ConsumerURL: "http://127.0.0.1:7777", 281 | }, 282 | }, 283 | }, 284 | }, 285 | } 286 | 287 | if secret != nil { 288 | machine.Spec.Connection.AuthSecretRef = corev1.SecretReference{ 289 | Name: secret.Name, 290 | Namespace: secret.Namespace, 291 | } 292 | 293 | machine.Spec.Connection.ProviderOptions.RPC.HMAC = &v1alpha1.HMACOpts{ 294 | Secrets: v1alpha1.HMACSecrets{ 295 | "sha256": []corev1.SecretReference{ 296 | { 297 | Name: secret.Name, 298 | Namespace: secret.Namespace, 299 | }, 300 | }, 301 | }, 302 | } 303 | } 304 | 305 | return machine 306 | } 307 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # Rufio 2 | 3 | ## Who is Rufio? 4 | 5 | Besides being the leader of the Lost Boys after Peter Pan left Neverland, Rufio is a kubernetes controller for managing baseboard management controllers (BMC) in a Tinkerbell context. Rufio can also execute jobs to perform a set of one-off management actions to bring a machine (physical hardware) to a desired state. 6 | 7 | ## Architecture 8 | 9 | ![architecture](puml/architecture.png) 10 | Rufio controller consists of three main API types, [Machine](https://github.com/tinkerbell/rufio/blob/main/api/v1alpha1/machine.go), [Job](https://github.com/tinkerbell/rufio/blob/main/api/v1alpha1/job.go) and [Task](https://github.com/tinkerbell/rufio/blob/main/api/v1alpha1/task.go). An operator or an automated client like [CAPT](https://github.com/tinkerbell/cluster-api-provider-tinkerbell) can interact with Rufio using these APIs to manage the state of their physical machines. 11 | 12 | ### Machine API 13 | 14 | The Machine type contains the information required for communicating with the BMC of the physical hardware. 15 | 16 | ```yaml 17 | apiVersion: bmc.tinkerbell.org/v1alpha1 18 | kind: Machine 19 | metadata: 20 | name: machine-sample 21 | spec: 22 | connection: 23 | host: 0.0.0.0 24 | port: 623 25 | authSecretRef: 26 | name: bm-auth 27 | namespace: sample 28 | insecureTLS: false 29 | ``` 30 | 31 | The `connection` object contains the required fields for establising a BMC connection. Fields `host`, `port` represent the BMC IP for the physical machine and `insecureTLS` instructs weather to use insecure TLS connectivity for performing BMC API calls. Field `authSecretRef` is a `SecretReference` which points to a kubernetes secret that contains the username/password for authenticating BMC API calls. 32 | 33 | ### Machine controller 34 | 35 | When a Machine object is created on the cluster, the machine controller is responsible for updating the current state of the physical machine. It performs API calls to the BMC of the physical machine and updates the `status` of the Machine object. 36 | 37 | ### Job API 38 | 39 | The Job type is used to define a set of one-off operations/actions to be performed on a physical machine. These actions are performed utilizing BMC API calls. 40 | 41 | ```yaml 42 | apiVersion: bmc.tinkerbell.org/v1alpha1 43 | kind: Job 44 | metadata: 45 | name: job-sample 46 | spec: 47 | machineRef: 48 | name: machine-sample 49 | namespace: sample 50 | tasks: 51 | - powerAction: "off" 52 | - oneTimeBootDeviceAction: 53 | device: 54 | - "pxe" 55 | efiBoot: false 56 | - powerAction: "on" 57 | ``` 58 | 59 | The `machineRef` points to the Machine object on the cluster, for which the job is executed. The `tasks` list is a set of ordered actions to be performed on the machine. 60 | > Note: A single task can only perform one type of action. For example either PowerAction or OneTimeBootDeviceAction. 61 | 62 | ### Job Controller 63 | 64 | The job controller watches for Job objects on the cluster. Once a new job object is created, it immediately sets the job condition to `Running` and creates a `Task` object on the cluster for the first item in the tasks list. 65 | 66 | The job controller also watches for changes in `Task` objects which have an ownerRef pointing to a Job. Once a Task object status is updated, the job controller checks the conditions on the Task and either marks the Job as Completed/Failed or proceeds to create the next Task object. 67 | 68 | ### Task API 69 | 70 | The task type represents a single one-off action performed against a BMC of a physical machine. 71 | 72 | ```yaml 73 | apiVersion: bmc.tinkerbell.org/v1alpha1 74 | kind: Task 75 | metadata: 76 | name: task-sample 77 | spec: 78 | connection: 79 | host: 0.0.0.0 80 | port: 623 81 | authSecretRef: 82 | name: bm-auth 83 | namespace: sample 84 | insecureTLS: false 85 | task: 86 | powerAction: "on" 87 | ``` 88 | 89 | ### Task controller 90 | 91 | The Task controller watches for Task objects on the cluster. When a new Task is created, the controller executes the corresponding action. Once the action is completed, the controller reconciles to check for the state of the physical machine. This ensures the action was completed successdully and marks the `status` as `Completed/Failed` accordingly. 92 | 93 | ## Getting Started 94 | 95 | For running Rufio, we require a k8s cluster that has access to the BMC network of the physical machines. 96 | 97 | For the purpose of this tutorial, lets create a [kind](https://kind.sigs.k8s.io/) cluster. 98 | 99 | ```bash 100 | kind create cluster 101 | ``` 102 | 103 | Once the cluster is created, we can run the make target to generate a manifest to apply the CRDs and controller deployment. 104 | 105 | ```bash 106 | make release-manifests 107 | ``` 108 | 109 | The manifest gets generated under `./out/release/manifest.yaml`, we can then apply the manifest to the cluster. 110 | 111 | ```bash 112 | kubectl apply -f ./out/release/manifest.yaml 113 | ``` 114 | 115 | We can now see the Rufio controller pod running on the cluster under the `rufio-system` namespace. 116 | 117 | ```bash 118 | kubectl get po -n rufio-system 119 | 120 | NAME READY STATUS RESTARTS AGE 121 | rufio-controller-manager-6c96d86cf5-kbvdj 1/1 Running 0 5s 122 | ``` 123 | 124 | We can now interact with Rufio using its API. Before creating a Mahine object, we need to create a k8s Secret that contains the BMC user credentials for the physical machine. An example Secret, 125 | 126 | ```yaml 127 | apiVersion: v1 128 | kind: Secret 129 | metadata: 130 | name: bm-auth 131 | namespace: sample 132 | data: 133 | username: cm9vdA== 134 | password: cm9vdA== 135 | type: kubernetes.io/basic-auth 136 | ``` 137 | 138 | Now we can modify the sample [yaml](https://github.com/tinkerbell/rufio/blob/main/config/samples/bmc_v1alpha1_machine.yaml) with the relavent connetion values and create a Machine object. 139 | 140 | ```bash 141 | kubectl apply -f ./config/samples/bmc_v1alpha1_machine.yaml 142 | ``` 143 | 144 | We can obsesrve the status of the Machine object gets updated with current state of the physical machine. 145 | 146 | ```bash 147 | kubectl get machines -o=jsonpath='{.items[0].status}' 148 | ``` 149 | 150 | ```json 151 | { 152 | "conditions": [ 153 | { 154 | "lastUpdateTime": "2022-08-31T20:01:35Z", 155 | "status": "True", 156 | "type": "Contactable" 157 | } 158 | ], 159 | "powerState": "on" 160 | } 161 | ``` 162 | 163 | Finally, we can create a Job with a few actions, 164 | 165 | ```bash 166 | kubectl apply -f ./config/samples/bmc_v1alpha1_job.yaml 167 | 168 | kubectl get jobs.bmc.tinkerbell.org 169 | 170 | NAMESPACE NAME AGE 171 | default job-sample 5s 172 | ``` 173 | 174 | We can also observe that that Task objects were created for each individual task listed on the Job. 175 | 176 | ```bash 177 | kubectl get tasks.bmc.tinkerbell.org -A 178 | 179 | NAMESPACE NAME AGE 180 | default job-sample-task-0 8s 181 | default job-sample-task-1 5s 182 | default job-sample-task-2 3s 183 | ``` 184 | 185 | ### Provider Options 186 | 187 | Options per provider can be defined in the `spec.connection.providerOptions` field of a `Machine` or `Task` object. 188 | 189 | > Note: when the `rpc` provider options are specified: 190 | 1. the `authSecretRef` is not required, otherwise it is required. 191 | 2. under the hood, no other providers will be tried/used. 192 | 193 | `Machine` CR example: 194 | 195 | > Note: The provider options below are not comprehensive. See the [spec](../api/v1alpha1/) for all available options. 196 | 197 | ```yaml 198 | apiVersion: bmc.tinkerbell.org/v1alpha1 199 | kind: Machine 200 | metadata: 201 | name: machine-sample-with-opts 202 | spec: 203 | connection: 204 | host: 127.0.0.1 205 | insecureTLS: true 206 | authSecretRef: 207 | name: sample-machine-auth 208 | namespace: rufio-system 209 | providerOptions: 210 | redfish: 211 | port: 443 212 | ipmitool: 213 | cipherSuite: 3 214 | port: 623 215 | intelAMT: 216 | port: 16992 217 | rpc: 218 | consumerURL: "https://example.com/rpc" 219 | hmac: 220 | secrets: 221 | sha256: 222 | - name: secret1 223 | namespace: default 224 | - name: secret2 225 | namespace: default 226 | sha512: 227 | - name: secret1 228 | namespace: default 229 | - name: secret2 230 | namespace: default 231 | ``` 232 | 233 | `Task` CR example with all providers defined in the options section: 234 | 235 | ```yaml 236 | apiVersion: bmc.tinkerbell.org/v1alpha1 237 | kind: Task 238 | metadata: 239 | name: task-sample 240 | spec: 241 | connection: 242 | host: 127.0.0.1 243 | insecureTLS: true 244 | authSecretRef: 245 | name: sample-machine-auth 246 | namespace: rufio-system 247 | providerOptions: 248 | redfish: 249 | port: 443 250 | ipmitool: 251 | cipherSuite: 3 252 | port: 623 253 | intelAMT: 254 | port: 16992 255 | rpc: 256 | consumerURL: "https://example.com/rpc" 257 | hmac: 258 | secrets: 259 | sha256: 260 | - name: secret1 261 | namespace: default 262 | - name: secret2 263 | namespace: default 264 | sha512: 265 | - name: secret1 266 | namespace: default 267 | - name: secret2 268 | namespace: default 269 | task: 270 | powerAction: "off" 271 | ``` 272 | 273 | ### Secrets 274 | 275 | There are two options for secrets. 276 | 277 | Option 1: A standard username/password. This is defined in a secret with `data.username` and `data.password`. 278 | 279 | ```yaml 280 | apiVersion: v1 281 | kind: Secret 282 | metadata: 283 | name: sample-machine-auth 284 | type: Opaque 285 | data: # admin/t0p-Secret; echo -n 'admin' | base64; echo -n 't0p-Secret' | base64 286 | username: YWRtaW4= 287 | password: dDBwLVNlY3JldA== 288 | ``` 289 | 290 | Option 2: When using the RPC provider, define a secret with `data.secret`. 291 | 292 | ```yaml 293 | apiVersion: v1 294 | kind: Secret 295 | metadata: 296 | name: secret1 297 | type: Opaque 298 | data: # echo -n 'superSecret1' | base64; 299 | secret: c3VwZXJTZWNyZXQx 300 | ``` 301 | -------------------------------------------------------------------------------- /docs/puml/architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkerbell/rufio/126069b950a57d571df90dfec7cd98e6d64692be/docs/puml/architecture.png -------------------------------------------------------------------------------- /docs/puml/architecture.puml: -------------------------------------------------------------------------------- 1 | @startuml architecture 2 | 3 | !define SPRITES_URL https://raw.githubusercontent.com/plantuml-stdlib/gilbarbara-plantuml-sprites/v1.0/sprites 4 | !define C4PUML_URL https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master 5 | 6 | !include C4PUML_URL/C4_Context.puml 7 | !include C4PUML_URL/C4_Container.puml 8 | !include SPRITES_URL/kubernetes.puml 9 | 10 | ' Tags (must be defined before use) 11 | AddRelTag(provides, $lineStyle=DottedLine()) 12 | 13 | ' System entities 14 | System_Boundary(rufio, "Rufio") { 15 | Container(job_controller, "Job Controller", "Go, K8s Controller", \ 16 | "Watches for Jobs and creates sequenced Tasks from Jobs") 17 | Container(task_controller, "Task Controller", "Go, K8s Controller", \ 18 | "Executes Tasks on the target Machine") 19 | Container(machine_controller, "Machine Controller", "Go, K8s Controller", \ 20 | "Monitors physical machine state and updates Machine resources to reflect state") 21 | } 22 | 23 | ' External entities 24 | Person_Ext(operator, "Operator") 25 | System_Ext(auto_client, "Automated Client") 26 | System_Ext(kubernetes, "Kubernetes Cluster", $sprite="kubernetes") 27 | System_Boundary(physical_machine, "Physical Machine") { 28 | Container_Ext( bmc, "Baseboard Management Controller", "IPMI, Redfish", \ 29 | "A management controller for the physical machine") 30 | } 31 | 32 | ' Relationships 33 | Rel_U(job_controller, kubernetes, "Watch for Jobs") 34 | Rel_U(task_controller, kubernetes, "Watch for Tasks") 35 | Rel(task_controller, bmc, "Executes tasks and ensure completion") 36 | Rel(machine_controller, bmc, "Monitor physical machine state") 37 | Rel_U(machine_controller, kubernetes, "Update Machine resource status") 38 | Rel_R(job_controller, task_controller, "Creates Tasks via Kube API", "", $tags="provides") 39 | Rel_L(auto_client, kubernetes, "Submits Rufio Jobs and retrieves state") 40 | Rel_R(operator, kubernetes, "Submits Rufio Jobs and retrieves state") 41 | 42 | @enduml -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/tinkerbell/rufio 2 | 3 | go 1.22.0 4 | 5 | toolchain go1.22.2 6 | 7 | require ( 8 | dario.cat/mergo v1.0.1 9 | github.com/bmc-toolbox/bmclib/v2 v2.3.5-0.20251010091507-63cb571e5597 10 | github.com/ccoveille/go-safecast v1.5.0 11 | github.com/go-logr/logr v1.4.2 12 | github.com/go-logr/zerologr v1.2.3 13 | github.com/google/go-cmp v0.6.0 14 | github.com/jacobweinstock/registrar v0.4.7 15 | github.com/peterbourgon/ff/v3 v3.4.0 16 | github.com/rs/zerolog v1.33.0 17 | golang.org/x/tools v0.29.0 18 | k8s.io/api v0.31.3 19 | k8s.io/apimachinery v0.31.3 20 | k8s.io/client-go v0.31.3 21 | sigs.k8s.io/controller-runtime v0.19.4 22 | ) 23 | 24 | require ( 25 | github.com/Jeffail/gabs/v2 v2.7.0 // indirect 26 | github.com/VictorLowther/simplexml v0.0.0-20180716164440-0bff93621230 // indirect 27 | github.com/VictorLowther/soap v0.0.0-20150314151524-8e36fca84b22 // indirect 28 | github.com/beorn7/perks v1.0.1 // indirect 29 | github.com/bmc-toolbox/common v0.0.0-20250112191656-b6de52e8303d // indirect 30 | github.com/cespare/xxhash/v2 v2.3.0 // indirect 31 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect 32 | github.com/emicklei/go-restful/v3 v3.11.0 // indirect 33 | github.com/evanphx/json-patch v5.6.0+incompatible // indirect 34 | github.com/evanphx/json-patch/v5 v5.9.0 // indirect 35 | github.com/fsnotify/fsnotify v1.7.0 // indirect 36 | github.com/fxamacker/cbor/v2 v2.7.0 // indirect 37 | github.com/ghodss/yaml v1.0.0 // indirect 38 | github.com/go-openapi/jsonpointer v0.19.6 // indirect 39 | github.com/go-openapi/jsonreference v0.20.2 // indirect 40 | github.com/go-openapi/swag v0.22.4 // indirect 41 | github.com/gogo/protobuf v1.3.2 // indirect 42 | github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect 43 | github.com/golang/protobuf v1.5.4 // indirect 44 | github.com/google/gnostic-models v0.6.8 // indirect 45 | github.com/google/gofuzz v1.2.0 // indirect 46 | github.com/google/uuid v1.6.0 // indirect 47 | github.com/hashicorp/errwrap v1.1.0 // indirect 48 | github.com/hashicorp/go-multierror v1.1.1 // indirect 49 | github.com/imdario/mergo v0.3.12 // indirect 50 | github.com/jacobweinstock/iamt v0.0.0-20230502042727-d7cdbe67d9ef // indirect 51 | github.com/josharian/intern v1.0.0 // indirect 52 | github.com/json-iterator/go v1.1.12 // indirect 53 | github.com/mailru/easyjson v0.7.7 // indirect 54 | github.com/mattn/go-colorable v0.1.13 // indirect 55 | github.com/mattn/go-isatty v0.0.20 // indirect 56 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 57 | github.com/modern-go/reflect2 v1.0.2 // indirect 58 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect 59 | github.com/pkg/errors v0.9.1 // indirect 60 | github.com/prometheus/client_golang v1.19.1 // indirect 61 | github.com/prometheus/client_model v0.6.1 // indirect 62 | github.com/prometheus/common v0.55.0 // indirect 63 | github.com/prometheus/procfs v0.15.1 // indirect 64 | github.com/satori/go.uuid v1.2.0 // indirect 65 | github.com/spf13/pflag v1.0.5 // indirect 66 | github.com/stmcginnis/gofish v0.20.0 // indirect 67 | github.com/x448/float16 v0.8.4 // indirect 68 | go.opentelemetry.io/otel v1.29.0 // indirect 69 | go.opentelemetry.io/otel/trace v1.29.0 // indirect 70 | golang.org/x/exp v0.0.0-20240409090435-93d18d7e34b8 // indirect 71 | golang.org/x/mod v0.22.0 // indirect 72 | golang.org/x/net v0.34.0 // indirect 73 | golang.org/x/oauth2 v0.21.0 // indirect 74 | golang.org/x/sync v0.10.0 // indirect 75 | golang.org/x/sys v0.29.0 // indirect 76 | golang.org/x/term v0.28.0 // indirect 77 | golang.org/x/text v0.21.0 // indirect 78 | golang.org/x/time v0.3.0 // indirect 79 | gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect 80 | google.golang.org/protobuf v1.34.2 // indirect 81 | gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect 82 | gopkg.in/inf.v0 v0.9.1 // indirect 83 | gopkg.in/yaml.v2 v2.4.0 // indirect 84 | gopkg.in/yaml.v3 v3.0.1 // indirect 85 | k8s.io/apiextensions-apiserver v0.31.0 // indirect 86 | k8s.io/klog/v2 v2.130.1 // indirect 87 | k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 // indirect 88 | k8s.io/utils v0.0.0-20240711033017-18e509b52bc8 // indirect 89 | sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect 90 | sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect 91 | sigs.k8s.io/yaml v1.4.0 // indirect 92 | ) 93 | -------------------------------------------------------------------------------- /hack/boilerplate.go.txt: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Tinkerbell. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ -------------------------------------------------------------------------------- /lint.mk: -------------------------------------------------------------------------------- 1 | # BEGIN: lint-install tinkerbell/rufio 2 | # http://github.com/tinkerbell/lint-install 3 | 4 | .PHONY: lint 5 | lint: _lint 6 | 7 | LINT_ARCH := $(shell uname -m) 8 | LINT_OS := $(shell uname) 9 | LINT_OS_LOWER := $(shell echo $(LINT_OS) | tr '[:upper:]' '[:lower:]') 10 | LINT_ROOT := $(shell dirname $(realpath $(firstword $(MAKEFILE_LIST)))) 11 | 12 | # shellcheck and hadolint lack arm64 native binaries: rely on x86-64 emulation 13 | ifeq ($(LINT_OS),Darwin) 14 | ifeq ($(LINT_ARCH),arm64) 15 | LINT_ARCH=x86_64 16 | endif 17 | endif 18 | 19 | LINTERS := 20 | FIXERS := 21 | 22 | GOLANGCI_LINT_CONFIG := $(LINT_ROOT)/.golangci.yml 23 | GOLANGCI_LINT_VERSION ?= v1.61.0 24 | GOLANGCI_LINT_BIN := out/linters/golangci-lint-$(GOLANGCI_LINT_VERSION)-$(LINT_ARCH) 25 | $(GOLANGCI_LINT_BIN): 26 | mkdir -p out/linters 27 | rm -rf out/linters/golangci-lint-* 28 | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b out/linters $(GOLANGCI_LINT_VERSION) 29 | mv out/linters/golangci-lint $@ 30 | 31 | LINTERS += golangci-lint-lint 32 | golangci-lint-lint: $(GOLANGCI_LINT_BIN) 33 | "$(GOLANGCI_LINT_BIN)" run -c "$(GOLANGCI_LINT_CONFIG)" 34 | 35 | FIXERS += golangci-lint-fix 36 | golangci-lint-fix: $(GOLANGCI_LINT_BIN) 37 | find . -name go.mod -execdir "$(GOLANGCI_LINT_BIN)" run -c "$(GOLANGCI_LINT_CONFIG)" --fix \; 38 | 39 | .PHONY: _lint $(LINTERS) 40 | _lint: $(LINTERS) 41 | 42 | .PHONY: fix $(FIXERS) 43 | fix: $(FIXERS) 44 | 45 | # END: lint-install tinkerbell/rufio -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 Tinkerbell. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "context" 21 | "flag" 22 | "os" 23 | "time" 24 | 25 | // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) 26 | // to ensure that exec-entrypoint and run can make use of them. 27 | _ "k8s.io/client-go/plugin/pkg/client/auth" 28 | "k8s.io/client-go/tools/clientcmd" 29 | clientcmdapi "k8s.io/client-go/tools/clientcmd/api" 30 | 31 | "github.com/go-logr/logr" 32 | "github.com/go-logr/zerologr" 33 | "github.com/peterbourgon/ff/v3" 34 | "github.com/peterbourgon/ff/v3/ffcli" 35 | "github.com/rs/zerolog" 36 | "github.com/tinkerbell/rufio/api/v1alpha1" 37 | "github.com/tinkerbell/rufio/controller" 38 | "k8s.io/apimachinery/pkg/runtime" 39 | utilruntime "k8s.io/apimachinery/pkg/util/runtime" 40 | clientgoscheme "k8s.io/client-go/kubernetes/scheme" 41 | ctrl "sigs.k8s.io/controller-runtime" 42 | "sigs.k8s.io/controller-runtime/pkg/cache" 43 | ctrlcontroller "sigs.k8s.io/controller-runtime/pkg/controller" 44 | "sigs.k8s.io/controller-runtime/pkg/healthz" 45 | metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" 46 | //+kubebuilder:scaffold:imports 47 | ) 48 | 49 | const ( 50 | appName = "rufio" 51 | ) 52 | 53 | var ( 54 | scheme = runtime.NewScheme() 55 | setupLog = ctrl.Log.WithName("setup") 56 | ) 57 | 58 | func init() { 59 | utilruntime.Must(clientgoscheme.AddToScheme(scheme)) 60 | 61 | utilruntime.Must(v1alpha1.AddToScheme(scheme)) 62 | //+kubebuilder:scaffold:scheme 63 | } 64 | 65 | // defaultLogger is a zerolog logr implementation. 66 | func defaultLogger(level string) logr.Logger { 67 | zl := zerolog.New(os.Stdout) 68 | zl = zl.With().Caller().Timestamp().Logger() 69 | var l zerolog.Level 70 | switch level { 71 | case "debug": 72 | l = zerolog.TraceLevel 73 | default: 74 | l = zerolog.InfoLevel 75 | } 76 | zl = zl.Level(l) 77 | 78 | return zerologr.New(&zl) 79 | } 80 | 81 | func main() { 82 | var metricsAddr string 83 | var enableLeaderElection bool 84 | var probeAddr string 85 | var kubeAPIServer string 86 | var kubeconfig string 87 | var kubeNamespace string 88 | var bmcConnectTimeout time.Duration 89 | var maxConcurrentReconciles int 90 | fs := flag.NewFlagSet(appName, flag.ExitOnError) 91 | fs.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.") 92 | fs.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") 93 | fs.BoolVar(&enableLeaderElection, "leader-elect", false, 94 | "Enable leader election for controller manager. "+ 95 | "Enabling this will ensure there is only one active controller manager.") 96 | fs.StringVar(&kubeAPIServer, "kubernetes", "", "The Kubernetes API URL, used for in-cluster client construction.") 97 | fs.StringVar(&kubeconfig, "kubeconfig", "", "Absolute path to the kubeconfig file.") 98 | fs.StringVar(&kubeNamespace, "kube-namespace", "", "Namespace that the controller watches to reconcile objects.") 99 | fs.DurationVar(&bmcConnectTimeout, "bmc-connect-timeout", 60*time.Second, "Timeout for establishing a connection to BMCs.") 100 | fs.IntVar(&maxConcurrentReconciles, "max-concurrent-reconciles", 1, "Maximum number of concurrent reconciles per controller.") 101 | cli := &ffcli.Command{ 102 | Name: appName, 103 | FlagSet: fs, 104 | Options: []ff.Option{ff.WithEnvVarPrefix(appName)}, 105 | } 106 | 107 | _ = cli.Parse(os.Args[1:]) 108 | 109 | ctrl.SetLogger(defaultLogger("debug")) 110 | 111 | ccfg := newClientConfig(kubeAPIServer, kubeconfig) 112 | 113 | cfg, err := ccfg.ClientConfig() 114 | if err != nil { 115 | setupLog.Error(err, "unable to get client config") 116 | os.Exit(1) 117 | } 118 | 119 | setupLog.Info("Watching objects in namespace for reconciliation", "namespace", kubeNamespace) 120 | 121 | opts := ctrl.Options{ 122 | Scheme: scheme, 123 | Metrics: metricsserver.Options{ 124 | BindAddress: metricsAddr, 125 | }, 126 | HealthProbeBindAddress: probeAddr, 127 | LeaderElection: enableLeaderElection, 128 | LeaderElectionID: "e74dec1a.tinkerbell.org", 129 | } 130 | // If a namespace is specified, only watch that namespace. Otherwise, watch all namespaces. 131 | if kubeNamespace != "" { 132 | opts.Cache = cache.Options{ 133 | DefaultNamespaces: map[string]cache.Config{kubeNamespace: {}}, 134 | } 135 | } 136 | 137 | mgr, err := ctrl.NewManager(cfg, opts) 138 | if err != nil { 139 | setupLog.Error(err, "unable to start manager") 140 | os.Exit(1) 141 | } 142 | 143 | // Setup the context that's going to be used in controllers and for the manager. 144 | ctx := ctrl.SetupSignalHandler() 145 | 146 | bmcClientFactory := controller.NewClientFunc(bmcConnectTimeout) 147 | 148 | // Setup controller reconcilers 149 | setupReconcilers(ctx, mgr, bmcClientFactory, maxConcurrentReconciles) 150 | 151 | //+kubebuilder:scaffold:builder 152 | 153 | err = mgr.AddHealthzCheck("healthz", healthz.Ping) 154 | if err != nil { 155 | setupLog.Error(err, "unable to set up health check") 156 | os.Exit(1) 157 | } 158 | 159 | err = mgr.AddReadyzCheck("readyz", healthz.Ping) 160 | if err != nil { 161 | setupLog.Error(err, "unable to set up ready check") 162 | os.Exit(1) 163 | } 164 | 165 | setupLog.Info("starting manager") 166 | err = mgr.Start(ctx) 167 | if err != nil { 168 | setupLog.Error(err, "problem running manager") 169 | os.Exit(1) 170 | } 171 | } 172 | 173 | func newClientConfig(kubeAPIServer, kubeconfig string) clientcmd.ClientConfig { 174 | return clientcmd.NewNonInteractiveDeferredLoadingClientConfig( 175 | &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}, 176 | &clientcmd.ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: kubeAPIServer}}) 177 | } 178 | 179 | // setupReconcilers initializes the controllers with the Manager. 180 | func setupReconcilers(ctx context.Context, mgr ctrl.Manager, bmcClientFactory controller.ClientFunc, maxConcurrentReconciles int) { 181 | err := (controller.NewMachineReconciler( 182 | mgr.GetClient(), 183 | mgr.GetEventRecorderFor("machine-controller"), 184 | bmcClientFactory, 185 | )).SetupWithManager(mgr, ctrlcontroller.Options{MaxConcurrentReconciles: maxConcurrentReconciles}) 186 | if err != nil { 187 | setupLog.Error(err, "unable to create controller", "controller", "Machine") 188 | os.Exit(1) 189 | } 190 | 191 | err = (controller.NewJobReconciler( 192 | mgr.GetClient(), 193 | )).SetupWithManager(ctx, mgr, ctrlcontroller.Options{MaxConcurrentReconciles: maxConcurrentReconciles}) 194 | if err != nil { 195 | setupLog.Error(err, "unable to create controller", "controller", "Job") 196 | os.Exit(1) 197 | } 198 | 199 | err = (controller.NewTaskReconciler( 200 | mgr.GetClient(), 201 | bmcClientFactory, 202 | )).SetupWithManager(mgr, ctrlcontroller.Options{MaxConcurrentReconciles: maxConcurrentReconciles}) 203 | if err != nil { 204 | setupLog.Error(err, "unable to create controller", "controller", "Task") 205 | os.Exit(1) 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /tools.go: -------------------------------------------------------------------------------- 1 | //go:build tools 2 | // +build tools 3 | 4 | package tools 5 | 6 | import ( 7 | _ "golang.org/x/tools/cmd/goimports" 8 | ) 9 | --------------------------------------------------------------------------------