2020-01-28 15:03:23 +09:00
/ *
Copyright 2020 The actions - runner - controller authors .
Licensed under the Apache License , Version 2.0 ( the "License" ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
http : //www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an "AS IS" BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
* /
package controllers
import (
"context"
2022-06-28 01:12:40 -04:00
"errors"
2020-01-28 21:58:01 +09:00
"fmt"
2022-06-28 01:12:40 -04:00
"strconv"
2021-04-06 03:10:10 +02:00
"strings"
"time"
2021-06-22 17:55:06 +09:00
"github.com/actions-runner-controller/actions-runner-controller/hash"
2021-12-17 09:06:55 +09:00
"github.com/go-logr/logr"
2020-01-28 15:03:23 +09:00
2021-02-09 10:17:52 +09:00
kerrors "k8s.io/apimachinery/pkg/api/errors"
2020-01-28 15:03:23 +09:00
"k8s.io/apimachinery/pkg/runtime"
2020-02-03 18:40:59 +09:00
"k8s.io/client-go/tools/record"
2020-01-28 15:03:23 +09:00
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
2021-12-11 21:22:55 -08:00
"sigs.k8s.io/controller-runtime/pkg/reconcile"
2020-01-28 15:03:23 +09:00
2020-01-28 21:58:01 +09:00
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2021-06-22 17:55:06 +09:00
"github.com/actions-runner-controller/actions-runner-controller/api/v1alpha1"
"github.com/actions-runner-controller/actions-runner-controller/github"
2020-01-28 21:58:01 +09:00
)
const (
2020-02-01 00:06:30 +09:00
containerName = "runner"
2020-02-03 21:35:01 +09:00
finalizerName = "runner.actions.summerwind.dev"
2020-12-08 17:56:06 +09:00
LabelKeyPodTemplateHash = "pod-template-hash"
2021-02-09 10:17:52 +09:00
retryDelayOnGitHubAPIRateLimitError = 30 * time . Second
feat: Support for scaling from/to zero (#465)
This is an attempt to support scaling from/to zero.
The basic idea is that we create a one-off "registration-only" runner pod on RunnerReplicaSet being scaled to zero, so that there is one "offline" runner, which enables GitHub Actions to queue jobs instead of discarding those.
GitHub Actions seems to immediately throw away the new job when there are no runners at all. Generally, having runners of any status, `busy`, `idle`, or `offline` would prevent GitHub actions from failing jobs. But retaining `busy` or `idle` runners means that we need to keep runner pods running, which conflicts with our desired to scale to/from zero, hence we retain `offline` runners.
In this change, I enhanced the runnerreplicaset controller to create a registration-only runner on very beginning of its reconciliation logic, only when a runnerreplicaset is scaled to zero. The runner controller creates the registration-only runner pod, waits for it to become "offline", and then removes the runner pod. The runner on GitHub stays `offline`, until the runner resource on K8s is deleted. As we remove the registration-only runner pod as soon as it registers, this doesn't block cluster-autoscaler.
Related to #447
2021-05-02 16:11:36 +09:00
2022-05-11 19:42:55 +09:00
EnvVarOrg = "RUNNER_ORG"
EnvVarRepo = "RUNNER_REPO"
EnvVarEnterprise = "RUNNER_ENTERPRISE"
EnvVarEphemeral = "RUNNER_EPHEMERAL"
EnvVarTrue = "true"
2020-01-28 15:03:23 +09:00
)
// RunnerReconciler reconciles a Runner object
type RunnerReconciler struct {
client . Client
2021-03-19 16:14:15 +09:00
Log logr . Logger
Recorder record . EventRecorder
Scheme * runtime . Scheme
GitHubClient * github . Client
RunnerImage string
2021-12-14 16:29:31 -08:00
RunnerImagePullSecrets [ ] string
2021-03-19 16:14:15 +09:00
DockerImage string
2021-07-14 22:20:08 +01:00
DockerRegistryMirror string
2021-03-19 16:14:15 +09:00
Name string
RegistrationRecheckInterval time . Duration
RegistrationRecheckJitter time . Duration
2022-02-20 07:45:49 +00:00
UnregistrationRetryDelay time . Duration
2020-01-28 15:03:23 +09:00
}
// +kubebuilder:rbac:groups=actions.summerwind.dev,resources=runners,verbs=get;list;watch;create;update;patch;delete
2020-10-06 09:23:03 +09:00
// +kubebuilder:rbac:groups=actions.summerwind.dev,resources=runners/finalizers,verbs=get;list;watch;create;update;patch;delete
2020-01-28 15:03:23 +09:00
// +kubebuilder:rbac:groups=actions.summerwind.dev,resources=runners/status,verbs=get;update;patch
2020-02-02 19:49:10 +09:00
// +kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch;create;update;patch;delete
2022-06-28 01:12:40 -04:00
// +kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;watch;delete
2020-10-06 09:23:03 +09:00
// +kubebuilder:rbac:groups=core,resources=pods/finalizers,verbs=get;list;watch;create;update;patch;delete
2020-03-27 23:25:37 +09:00
// +kubebuilder:rbac:groups=core,resources=events,verbs=create;patch
2020-01-28 15:03:23 +09:00
2021-06-22 17:10:09 +09:00
func ( r * RunnerReconciler ) Reconcile ( ctx context . Context , req ctrl . Request ) ( ctrl . Result , error ) {
2020-01-28 21:58:01 +09:00
log := r . Log . WithValues ( "runner" , req . NamespacedName )
var runner v1alpha1 . Runner
if err := r . Get ( ctx , req . NamespacedName , & runner ) ; err != nil {
return ctrl . Result { } , client . IgnoreNotFound ( err )
}
2020-02-03 21:35:01 +09:00
if runner . ObjectMeta . DeletionTimestamp . IsZero ( ) {
2021-06-24 20:39:37 +09:00
finalizers , added := addFinalizer ( runner . ObjectMeta . Finalizers , finalizerName )
2020-02-03 21:35:01 +09:00
if added {
newRunner := runner . DeepCopy ( )
newRunner . ObjectMeta . Finalizers = finalizers
if err := r . Update ( ctx , newRunner ) ; err != nil {
log . Error ( err , "Failed to update runner" )
return ctrl . Result { } , err
}
return ctrl . Result { } , nil
}
} else {
2022-03-22 14:44:50 -07:00
// Request to remove a runner. DeletionTimestamp was set in the runner - we need to unregister runner
2022-03-02 16:01:34 -08:00
var pod corev1 . Pod
if err := r . Get ( ctx , req . NamespacedName , & pod ) ; err != nil {
if ! kerrors . IsNotFound ( err ) {
2022-03-02 16:51:30 -08:00
log . Info ( fmt . Sprintf ( "Retrying soon as we failed to get runner pod: %v" , err ) )
2022-03-02 16:01:34 -08:00
return ctrl . Result { Requeue : true } , nil
2022-02-19 16:12:39 +00:00
}
2022-03-22 14:44:50 -07:00
// Pod was not found
return r . processRunnerDeletion ( runner , ctx , log , nil )
2022-02-19 16:12:39 +00:00
}
2022-06-28 01:12:40 -04:00
2022-03-02 16:01:34 -08:00
return r . processRunnerDeletion ( runner , ctx , log , & pod )
2020-02-03 21:35:01 +09:00
}
2020-01-29 23:12:07 +09:00
var pod corev1 . Pod
if err := r . Get ( ctx , req . NamespacedName , & pod ) ; err != nil {
2021-02-09 10:17:52 +09:00
if ! kerrors . IsNotFound ( err ) {
2021-12-11 21:22:55 -08:00
// An error ocurred
2020-01-29 23:12:07 +09:00
return ctrl . Result { } , err
2020-01-28 21:58:01 +09:00
}
2021-12-11 21:22:55 -08:00
return r . processRunnerCreation ( ctx , runner , log )
}
2020-01-28 21:58:01 +09:00
2022-03-05 12:13:22 +00:00
phase := string ( pod . Status . Phase )
if phase == "" {
phase = "Created"
2021-12-11 21:22:55 -08:00
}
2021-02-09 10:17:52 +09:00
2022-04-03 11:12:44 +09:00
ready := runnerPodReady ( & pod )
if runner . Status . Phase != phase || runner . Status . Ready != ready {
2022-03-05 12:13:22 +00:00
if pod . Status . Phase == corev1 . PodRunning {
// Seeing this message, you can expect the runner to become `Running` soon.
log . V ( 1 ) . Info (
"Runner appears to have been registered and running." ,
"podCreationTimestamp" , pod . CreationTimestamp ,
)
2021-12-11 21:22:55 -08:00
}
2021-03-16 10:52:30 +09:00
2022-03-05 12:13:22 +00:00
updated := runner . DeepCopy ( )
updated . Status . Phase = phase
2022-04-03 11:12:44 +09:00
updated . Status . Ready = ready
2022-03-05 12:13:22 +00:00
updated . Status . Reason = pod . Status . Reason
updated . Status . Message = pod . Status . Message
2021-12-11 21:22:55 -08:00
2022-03-05 12:13:22 +00:00
if err := r . Status ( ) . Patch ( ctx , updated , client . MergeFrom ( & runner ) ) ; err != nil {
log . Error ( err , "Failed to update runner status for Phase/Reason/Message" )
return ctrl . Result { } , err
2021-12-11 21:22:55 -08:00
}
}
return ctrl . Result { } , nil
}
2022-04-03 11:12:44 +09:00
func runnerPodReady ( pod * corev1 . Pod ) bool {
for _ , c := range pod . Status . Conditions {
if c . Type != corev1 . PodReady {
continue
}
return c . Status == corev1 . ConditionTrue
}
return false
}
2022-02-27 11:55:06 +00:00
func runnerContainerExitCode ( pod * corev1 . Pod ) * int32 {
for _ , status := range pod . Status . ContainerStatuses {
if status . Name != containerName {
continue
}
if status . State . Terminated != nil {
return & status . State . Terminated . ExitCode
}
}
return nil
}
2022-02-19 16:12:39 +00:00
func runnerPodOrContainerIsStopped ( pod * corev1 . Pod ) bool {
// If pod has ended up succeeded we need to restart it
// Happens e.g. when dind is in runner and run completes
2022-04-08 10:17:33 +09:00
stopped := pod . Status . Phase == corev1 . PodSucceeded || pod . Status . Phase == corev1 . PodFailed
2021-12-11 21:22:55 -08:00
2022-02-19 16:12:39 +00:00
if ! stopped {
if pod . Status . Phase == corev1 . PodRunning {
for _ , status := range pod . Status . ContainerStatuses {
if status . Name != containerName {
continue
2021-03-16 10:52:30 +09:00
}
2021-12-11 21:22:55 -08:00
2022-04-08 10:17:33 +09:00
if status . State . Terminated != nil {
2022-02-19 16:12:39 +00:00
stopped = true
}
2021-03-16 10:52:30 +09:00
}
2022-02-19 16:12:39 +00:00
}
}
2021-03-16 10:52:30 +09:00
2022-02-19 16:12:39 +00:00
return stopped
}
2022-05-12 17:34:27 +09:00
func ephemeralRunnerContainerStatus ( pod * corev1 . Pod ) * corev1 . ContainerStatus {
if getRunnerEnv ( pod , "RUNNER_EPHEMERAL" ) != "true" {
return nil
}
for _ , status := range pod . Status . ContainerStatuses {
if status . Name != containerName {
continue
}
status := status
return & status
}
return nil
}
2022-02-19 16:12:39 +00:00
func ( r * RunnerReconciler ) processRunnerDeletion ( runner v1alpha1 . Runner , ctx context . Context , log logr . Logger , pod * corev1 . Pod ) ( reconcile . Result , error ) {
finalizers , removed := removeFinalizer ( runner . ObjectMeta . Finalizers , finalizerName )
if removed {
2021-12-11 21:22:55 -08:00
newRunner := runner . DeepCopy ( )
newRunner . ObjectMeta . Finalizers = finalizers
if err := r . Patch ( ctx , newRunner , client . MergeFrom ( & runner ) ) ; err != nil {
2022-03-13 12:11:11 +00:00
log . Error ( err , "Unable to remove finalizer" )
2020-01-28 21:58:01 +09:00
return ctrl . Result { } , err
}
2020-01-29 23:12:07 +09:00
2022-03-13 12:11:11 +00:00
log . Info ( "Removed finalizer" )
2021-12-11 21:22:55 -08:00
}
return ctrl . Result { } , nil
}
func ( r * RunnerReconciler ) processRunnerCreation ( ctx context . Context , runner v1alpha1 . Runner , log logr . Logger ) ( reconcile . Result , error ) {
if updated , err := r . updateRegistrationToken ( ctx , runner ) ; err != nil {
2022-03-13 07:22:04 +00:00
return ctrl . Result { RequeueAfter : RetryDelayOnCreateRegistrationError } , nil
2021-12-11 21:22:55 -08:00
} else if updated {
return ctrl . Result { Requeue : true } , nil
}
newPod , err := r . newPod ( runner )
if err != nil {
log . Error ( err , "Could not create pod" )
return ctrl . Result { } , err
}
if err := r . Create ( ctx , & newPod ) ; err != nil {
if kerrors . IsAlreadyExists ( err ) {
// Gracefully handle pod-already-exists errors due to informer cache delay.
// Without this we got a few errors like the below on new runner pod:
// 2021-03-16T00:23:10.116Z ERROR controller-runtime.controller Reconciler error {"controller": "runner-controller", "request": "default/example-runnerdeploy-b2g2g-j4mcp", "error": "pods \"example-runnerdeploy-b2g2g-j4mcp\" already exists"}
log . Info (
"Failed to create pod due to AlreadyExists error. Probably this pod has been already created in previous reconcilation but is still not in the informer cache. Will retry on pod created. If it doesn't repeat, there's no problem" ,
)
return ctrl . Result { } , nil
}
log . Error ( err , "Failed to create pod resource" )
return ctrl . Result { } , err
2020-01-28 21:58:01 +09:00
}
2020-01-28 15:03:23 +09:00
2021-12-11 21:22:55 -08:00
r . Recorder . Event ( & runner , corev1 . EventTypeNormal , "PodCreated" , fmt . Sprintf ( "Created pod '%s'" , newPod . Name ) )
log . Info ( "Created runner pod" , "repository" , runner . Spec . Repository )
2022-03-05 12:13:22 +00:00
2020-01-28 15:03:23 +09:00
return ctrl . Result { } , nil
}
2020-11-11 09:38:05 +09:00
func ( r * RunnerReconciler ) updateRegistrationToken ( ctx context . Context , runner v1alpha1 . Runner ) ( bool , error ) {
if runner . IsRegisterable ( ) {
return false , nil
}
log := r . Log . WithValues ( "runner" , runner . Name )
2021-02-05 02:31:06 +02:00
rt , err := r . GitHubClient . GetRegistrationToken ( ctx , runner . Spec . Enterprise , runner . Spec . Organization , runner . Spec . Repository , runner . Name )
2020-11-11 09:38:05 +09:00
if err != nil {
2022-03-13 07:22:04 +00:00
// An error can be a permanent, permission issue like the below:
// POST https://api.github.com/enterprises/YOUR_ENTERPRISE/actions/runners/registration-token: 403 Resource not accessible by integration []
// In such case retrying in seconds might not make much sense.
2020-11-11 09:38:05 +09:00
r . Recorder . Event ( & runner , corev1 . EventTypeWarning , "FailedUpdateRegistrationToken" , "Updating registration token failed" )
log . Error ( err , "Failed to get new registration token" )
return false , err
}
updated := runner . DeepCopy ( )
updated . Status . Registration = v1alpha1 . RunnerStatusRegistration {
Organization : runner . Spec . Organization ,
Repository : runner . Spec . Repository ,
Labels : runner . Spec . Labels ,
Token : rt . GetToken ( ) ,
ExpiresAt : metav1 . NewTime ( rt . GetExpiresAt ( ) . Time ) ,
}
2021-03-18 10:31:17 +09:00
if err := r . Status ( ) . Patch ( ctx , updated , client . MergeFrom ( & runner ) ) ; err != nil {
2021-03-18 10:26:21 +09:00
log . Error ( err , "Failed to update runner status for Registration" )
2020-11-11 09:38:05 +09:00
return false , err
}
r . Recorder . Event ( & runner , corev1 . EventTypeNormal , "RegistrationTokenUpdated" , "Successfully update registration token" )
log . Info ( "Updated registration token" , "repository" , runner . Spec . Repository )
return true , nil
}
func ( r * RunnerReconciler ) newPod ( runner v1alpha1 . Runner ) ( corev1 . Pod , error ) {
2021-06-22 17:10:09 +09:00
var template corev1 . Pod
labels := map [ string ] string { }
for k , v := range runner . ObjectMeta . Labels {
labels [ k ] = v
}
// This implies that...
//
// (1) We recreate the runner pod whenever the runner has changes in:
// - metadata.labels (excluding "runner-template-hash" added by the parent RunnerReplicaSet
// - metadata.annotations
// - metadata.spec (including image, env, organization, repository, group, and so on)
// - GithubBaseURL setting of the controller (can be configured via GITHUB_ENTERPRISE_URL)
//
// (2) We don't recreate the runner pod when there are changes in:
// - runner.status.registration.token
// - This token expires and changes hourly, but you don't need to recreate the pod due to that.
// It's the opposite.
// An unexpired token is required only when the runner agent is registering itself on launch.
//
// In other words, the registered runner doesn't get invalidated on registration token expiration.
// A registered runner's session and the a registration token seem to have two different and independent
// lifecycles.
//
2021-06-22 17:55:06 +09:00
// See https://github.com/actions-runner-controller/actions-runner-controller/issues/143 for more context.
2021-06-22 17:10:09 +09:00
labels [ LabelKeyPodTemplateHash ] = hash . FNVHashStringObjects (
filterLabels ( runner . ObjectMeta . Labels , LabelKeyRunnerTemplateHash ) ,
runner . ObjectMeta . Annotations ,
runner . Spec ,
r . GitHubClient . GithubBaseURL ,
2022-02-19 21:18:00 +09:00
// Token change should trigger replacement.
// We need to include this explicitly here because
// runner.Spec does not contain the possibly updated token stored in the
// runner status yet.
runner . Status . Registration . Token ,
2021-06-22 17:10:09 +09:00
)
objectMeta := metav1 . ObjectMeta {
Name : runner . ObjectMeta . Name ,
Namespace : runner . ObjectMeta . Namespace ,
Labels : labels ,
Annotations : runner . ObjectMeta . Annotations ,
}
template . ObjectMeta = objectMeta
if len ( runner . Spec . Containers ) == 0 {
template . Spec . Containers = append ( template . Spec . Containers , corev1 . Container {
2022-05-12 17:25:51 +09:00
Name : "runner" ,
2021-06-22 17:10:09 +09:00
} )
2021-07-13 18:14:15 +09:00
2021-09-24 01:18:20 +01:00
if ( runner . Spec . DockerEnabled == nil || * runner . Spec . DockerEnabled ) && ( runner . Spec . DockerdWithinRunnerContainer == nil || ! * runner . Spec . DockerdWithinRunnerContainer ) {
2021-07-13 18:14:15 +09:00
template . Spec . Containers = append ( template . Spec . Containers , corev1 . Container {
2022-05-12 17:25:51 +09:00
Name : "docker" ,
2021-07-13 18:14:15 +09:00
} )
}
2021-06-22 17:10:09 +09:00
} else {
template . Spec . Containers = runner . Spec . Containers
}
2022-05-12 17:25:51 +09:00
for i , c := range template . Spec . Containers {
switch c . Name {
case "runner" :
if c . ImagePullPolicy == "" {
template . Spec . Containers [ i ] . ImagePullPolicy = runner . Spec . ImagePullPolicy
}
if len ( c . EnvFrom ) == 0 {
template . Spec . Containers [ i ] . EnvFrom = runner . Spec . EnvFrom
}
if len ( c . Env ) == 0 {
template . Spec . Containers [ i ] . Env = runner . Spec . Env
}
if len ( c . Resources . Requests ) == 0 {
template . Spec . Containers [ i ] . Resources . Requests = runner . Spec . Resources . Requests
}
if len ( c . Resources . Limits ) == 0 {
template . Spec . Containers [ i ] . Resources . Limits = runner . Spec . Resources . Limits
}
case "docker" :
if len ( c . VolumeMounts ) == 0 {
template . Spec . Containers [ i ] . VolumeMounts = runner . Spec . DockerVolumeMounts
}
if len ( c . Resources . Limits ) == 0 {
template . Spec . Containers [ i ] . Resources . Limits = runner . Spec . DockerdContainerResources . Limits
}
if len ( c . Resources . Requests ) == 0 {
template . Spec . Containers [ i ] . Resources . Requests = runner . Spec . DockerdContainerResources . Requests
}
if len ( c . Env ) == 0 {
template . Spec . Containers [ i ] . Env = runner . Spec . DockerEnv
}
}
}
2021-06-22 17:10:09 +09:00
template . Spec . SecurityContext = runner . Spec . SecurityContext
2021-06-22 04:27:26 -04:00
template . Spec . EnableServiceLinks = runner . Spec . EnableServiceLinks
2021-06-22 17:10:09 +09:00
2022-06-28 01:12:40 -04:00
if runner . Spec . ContainerMode == "kubernetes" {
workDir := runner . Spec . WorkDir
if workDir == "" {
workDir = "/runner/_work"
}
if err := applyWorkVolumeClaimTemplateToPod ( & template , runner . Spec . WorkVolumeClaimTemplate , workDir ) ; err != nil {
return corev1 . Pod { } , err
}
}
pod , err := newRunnerPodWithContainerMode ( runner . Spec . ContainerMode , runner . Name , template , runner . Spec . RunnerConfig , r . RunnerImage , r . RunnerImagePullSecrets , r . DockerImage , r . DockerRegistryMirror , r . GitHubClient . GithubBaseURL )
2021-06-22 17:10:09 +09:00
if err != nil {
return pod , err
}
// Customize the pod spec according to the runner spec
runnerSpec := runner . Spec
if len ( runnerSpec . VolumeMounts ) != 0 {
2022-01-07 02:01:40 +01:00
// if operater provides a work volume mount, use that
isPresent , _ := workVolumeMountPresent ( runnerSpec . VolumeMounts )
if isPresent {
2022-06-28 01:12:40 -04:00
if runnerSpec . ContainerMode == "kubernetes" {
return pod , errors . New ( "volume mount \"work\" should be specified by workVolumeClaimTemplate in container mode kubernetes" )
}
2022-01-07 02:01:40 +01:00
// remove work volume since it will be provided from runnerSpec.Volumes
// if we don't remove it here we would get a duplicate key error, i.e. two volumes named work
_ , index := workVolumeMountPresent ( pod . Spec . Containers [ 0 ] . VolumeMounts )
pod . Spec . Containers [ 0 ] . VolumeMounts = append ( pod . Spec . Containers [ 0 ] . VolumeMounts [ : index ] , pod . Spec . Containers [ 0 ] . VolumeMounts [ index + 1 : ] ... )
}
2021-06-22 17:10:09 +09:00
pod . Spec . Containers [ 0 ] . VolumeMounts = append ( pod . Spec . Containers [ 0 ] . VolumeMounts , runnerSpec . VolumeMounts ... )
}
if len ( runnerSpec . Volumes ) != 0 {
2022-01-07 02:01:40 +01:00
// if operator provides a work volume. use that
isPresent , _ := workVolumePresent ( runnerSpec . Volumes )
if isPresent {
2022-06-28 01:12:40 -04:00
if runnerSpec . ContainerMode == "kubernetes" {
return pod , errors . New ( "volume \"work\" should be specified by workVolumeClaimTemplate in container mode kubernetes" )
}
2022-01-07 02:01:40 +01:00
_ , index := workVolumePresent ( pod . Spec . Volumes )
// remove work volume since it will be provided from runnerSpec.Volumes
// if we don't remove it here we would get a duplicate key error, i.e. two volumes named work
pod . Spec . Volumes = append ( pod . Spec . Volumes [ : index ] , pod . Spec . Volumes [ index + 1 : ] ... )
}
2021-06-22 17:10:09 +09:00
pod . Spec . Volumes = append ( pod . Spec . Volumes , runnerSpec . Volumes ... )
}
2022-06-28 01:12:40 -04:00
2021-06-22 17:10:09 +09:00
if len ( runnerSpec . InitContainers ) != 0 {
pod . Spec . InitContainers = append ( pod . Spec . InitContainers , runnerSpec . InitContainers ... )
}
if runnerSpec . NodeSelector != nil {
pod . Spec . NodeSelector = runnerSpec . NodeSelector
}
if runnerSpec . ServiceAccountName != "" {
pod . Spec . ServiceAccountName = runnerSpec . ServiceAccountName
}
if runnerSpec . AutomountServiceAccountToken != nil {
pod . Spec . AutomountServiceAccountToken = runnerSpec . AutomountServiceAccountToken
}
if len ( runnerSpec . SidecarContainers ) != 0 {
pod . Spec . Containers = append ( pod . Spec . Containers , runnerSpec . SidecarContainers ... )
}
if len ( runnerSpec . ImagePullSecrets ) != 0 {
pod . Spec . ImagePullSecrets = runnerSpec . ImagePullSecrets
}
if runnerSpec . Affinity != nil {
pod . Spec . Affinity = runnerSpec . Affinity
}
if len ( runnerSpec . Tolerations ) != 0 {
pod . Spec . Tolerations = runnerSpec . Tolerations
}
2022-06-28 00:45:19 +01:00
if runnerSpec . PriorityClassName != "" {
pod . Spec . PriorityClassName = runnerSpec . PriorityClassName
}
2021-10-18 06:49:44 +10:00
if len ( runnerSpec . TopologySpreadConstraints ) != 0 {
pod . Spec . TopologySpreadConstraints = runnerSpec . TopologySpreadConstraints
}
2021-06-22 17:10:09 +09:00
if len ( runnerSpec . EphemeralContainers ) != 0 {
pod . Spec . EphemeralContainers = runnerSpec . EphemeralContainers
}
if runnerSpec . TerminationGracePeriodSeconds != nil {
pod . Spec . TerminationGracePeriodSeconds = runnerSpec . TerminationGracePeriodSeconds
}
if len ( runnerSpec . HostAliases ) != 0 {
pod . Spec . HostAliases = runnerSpec . HostAliases
}
2022-04-19 21:55:20 -04:00
if runnerSpec . DnsConfig != nil {
pod . Spec . DNSConfig = runnerSpec . DnsConfig
}
2021-06-22 17:10:09 +09:00
if runnerSpec . RuntimeClassName != nil {
pod . Spec . RuntimeClassName = runnerSpec . RuntimeClassName
}
pod . ObjectMeta . Name = runner . ObjectMeta . Name
// Inject the registration token and the runner name
updated := mutatePod ( & pod , runner . Status . Registration . Token )
if err := ctrl . SetControllerReference ( & runner , updated , r . Scheme ) ; err != nil {
return pod , err
}
return * updated , nil
}
func mutatePod ( pod * corev1 . Pod , token string ) * corev1 . Pod {
updated := pod . DeepCopy ( )
2022-03-12 13:49:42 +00:00
if getRunnerEnv ( pod , EnvVarRunnerName ) == "" {
setRunnerEnv ( updated , EnvVarRunnerName , pod . ObjectMeta . Name )
}
if getRunnerEnv ( pod , EnvVarRunnerToken ) == "" {
setRunnerEnv ( updated , EnvVarRunnerToken , token )
2021-06-22 17:10:09 +09:00
}
return updated
}
2022-06-28 01:12:40 -04:00
func runnerHookEnvs ( pod * corev1 . Pod ) ( [ ] corev1 . EnvVar , error ) {
isRequireSameNode , err := isRequireSameNode ( pod )
if err != nil {
return nil , err
}
return [ ] corev1 . EnvVar {
{
Name : "ACTIONS_RUNNER_CONTAINER_HOOKS" ,
Value : defaultRunnerHookPath ,
} ,
{
Name : "ACTIONS_RUNNER_REQUIRE_JOB_CONTAINER" ,
Value : "true" ,
} ,
{
Name : "ACTIONS_RUNNER_POD_NAME" ,
ValueFrom : & corev1 . EnvVarSource {
FieldRef : & corev1 . ObjectFieldSelector {
FieldPath : "metadata.name" ,
} ,
} ,
} ,
{
Name : "ACTIONS_RUNNER_JOB_NAMESPACE" ,
ValueFrom : & corev1 . EnvVarSource {
FieldRef : & corev1 . ObjectFieldSelector {
FieldPath : "metadata.namespace" ,
} ,
} ,
} ,
corev1 . EnvVar {
Name : "ACTIONS_RUNNER_REQUIRE_SAME_NODE" ,
Value : strconv . FormatBool ( isRequireSameNode ) ,
} ,
} , nil
}
func newRunnerPodWithContainerMode ( containerMode string , runnerName string , template corev1 . Pod , runnerSpec v1alpha1 . RunnerConfig , defaultRunnerImage string , defaultRunnerImagePullSecrets [ ] string , defaultDockerImage , defaultDockerRegistryMirror string , githubBaseURL string ) ( corev1 . Pod , error ) {
2020-01-30 23:52:40 +09:00
var (
2021-06-03 16:59:11 -07:00
privileged bool = true
2021-06-22 17:10:09 +09:00
dockerdInRunner bool = runnerSpec . DockerdWithinRunnerContainer != nil && * runnerSpec . DockerdWithinRunnerContainer
dockerEnabled bool = runnerSpec . DockerEnabled == nil || * runnerSpec . DockerEnabled
ephemeral bool = runnerSpec . Ephemeral == nil || * runnerSpec . Ephemeral
2021-06-03 16:59:11 -07:00
dockerdInRunnerPrivileged bool = dockerdInRunner
2020-01-30 23:52:40 +09:00
)
2022-06-28 01:12:40 -04:00
if containerMode == "kubernetes" {
dockerdInRunner = false
dockerEnabled = false
dockerdInRunnerPrivileged = false
}
2022-03-05 12:13:22 +00:00
template = * template . DeepCopy ( )
// This label selector is used by default when rd.Spec.Selector is empty.
template . ObjectMeta . Labels = CloneAndAddLabel ( template . ObjectMeta . Labels , LabelKeyRunnerSetName , runnerName )
template . ObjectMeta . Labels = CloneAndAddLabel ( template . ObjectMeta . Labels , LabelKeyPodMutation , LabelValuePodMutation )
2021-06-22 17:10:09 +09:00
workDir := runnerSpec . WorkDir
2020-11-25 00:55:26 +01:00
if workDir == "" {
workDir = "/runner/_work"
}
2021-07-14 22:20:08 +01:00
var dockerRegistryMirror string
if runnerSpec . DockerRegistryMirror == nil {
dockerRegistryMirror = defaultDockerRegistryMirror
} else {
dockerRegistryMirror = * runnerSpec . DockerRegistryMirror
}
2021-12-29 01:23:35 +00:00
// Be aware some of the environment variables are used
// in the runner entrypoint script
2020-02-06 22:09:07 +09:00
env := [ ] corev1 . EnvVar {
2020-04-23 16:36:40 +02:00
{
2021-06-24 20:39:37 +09:00
Name : EnvVarOrg ,
2021-06-22 17:10:09 +09:00
Value : runnerSpec . Organization ,
2020-04-23 16:36:40 +02:00
} ,
2020-02-06 22:09:07 +09:00
{
2021-06-24 20:39:37 +09:00
Name : EnvVarRepo ,
2021-06-22 17:10:09 +09:00
Value : runnerSpec . Repository ,
2020-02-06 22:09:07 +09:00
} ,
2021-02-05 02:31:06 +02:00
{
2021-06-24 20:39:37 +09:00
Name : EnvVarEnterprise ,
2021-06-22 17:10:09 +09:00
Value : runnerSpec . Enterprise ,
2021-02-05 02:31:06 +02:00
} ,
2020-04-24 11:29:52 +02:00
{
Name : "RUNNER_LABELS" ,
2021-06-22 17:10:09 +09:00
Value : strings . Join ( runnerSpec . Labels , "," ) ,
2020-04-24 11:29:52 +02:00
} ,
2020-11-10 08:15:54 +00:00
{
Name : "RUNNER_GROUP" ,
2021-06-22 17:10:09 +09:00
Value : runnerSpec . Group ,
2020-02-06 22:09:07 +09:00
} ,
2021-12-29 01:23:35 +00:00
{
Name : "DOCKER_ENABLED" ,
Value : fmt . Sprintf ( "%v" , dockerEnabled || dockerdInRunner ) ,
} ,
2020-10-20 02:48:28 +03:00
{
Name : "DOCKERD_IN_RUNNER" ,
Value : fmt . Sprintf ( "%v" , dockerdInRunner ) ,
} ,
2020-10-28 15:15:53 +02:00
{
Name : "GITHUB_URL" ,
2021-06-22 17:10:09 +09:00
Value : githubBaseURL ,
2020-10-28 15:15:53 +02:00
} ,
2020-11-25 00:55:26 +01:00
{
Name : "RUNNER_WORKDIR" ,
Value : workDir ,
} ,
2021-05-02 15:34:14 +05:30
{
2022-03-11 19:03:17 +09:00
Name : EnvVarEphemeral ,
2021-05-02 15:34:14 +05:30
Value : fmt . Sprintf ( "%v" , ephemeral ) ,
} ,
2020-02-06 22:09:07 +09:00
}
2021-06-03 16:59:11 -07:00
var seLinuxOptions * corev1 . SELinuxOptions
2021-06-22 17:10:09 +09:00
if template . Spec . SecurityContext != nil {
seLinuxOptions = template . Spec . SecurityContext . SELinuxOptions
2021-06-03 16:59:11 -07:00
if seLinuxOptions != nil {
privileged = false
dockerdInRunnerPrivileged = false
}
}
2021-06-22 17:10:09 +09:00
var runnerContainerIndex , dockerdContainerIndex int
var runnerContainer , dockerdContainer * corev1 . Container
for i := range template . Spec . Containers {
c := template . Spec . Containers [ i ]
if c . Name == containerName {
runnerContainerIndex = i
runnerContainer = & c
} else if c . Name == "docker" {
dockerdContainerIndex = i
dockerdContainer = & c
}
}
2022-06-28 01:12:40 -04:00
if containerMode == "kubernetes" {
if dockerdContainer != nil {
template . Spec . Containers = append ( template . Spec . Containers [ : dockerdContainerIndex ] , template . Spec . Containers [ dockerdContainerIndex + 1 : ] ... )
}
if runnerContainerIndex < runnerContainerIndex {
runnerContainerIndex --
}
dockerdContainer = nil
dockerdContainerIndex = - 1
}
2021-06-22 17:10:09 +09:00
if runnerContainer == nil {
runnerContainerIndex = - 1
runnerContainer = & corev1 . Container {
Name : containerName ,
SecurityContext : & corev1 . SecurityContext {
// Runner need to run privileged if it contains DinD
Privileged : & dockerdInRunnerPrivileged ,
2020-10-20 02:48:28 +03:00
} ,
2021-06-22 17:10:09 +09:00
}
}
if dockerdContainer == nil {
dockerdContainerIndex = - 1
dockerdContainer = & corev1 . Container {
Name : "docker" ,
}
}
2021-09-10 09:41:46 +01:00
if runnerSpec . Image != "" {
runnerContainer . Image = runnerSpec . Image
}
if runnerContainer . Image == "" {
runnerContainer . Image = defaultRunnerImage
}
2021-06-22 17:10:09 +09:00
if runnerContainer . ImagePullPolicy == "" {
runnerContainer . ImagePullPolicy = corev1 . PullAlways
}
runnerContainer . Env = append ( runnerContainer . Env , env ... )
2022-06-28 01:12:40 -04:00
if containerMode == "kubernetes" {
hookEnvs , err := runnerHookEnvs ( & template )
if err != nil {
return corev1 . Pod { } , err
}
runnerContainer . Env = append ( runnerContainer . Env , hookEnvs ... )
}
2021-06-22 17:10:09 +09:00
if runnerContainer . SecurityContext == nil {
runnerContainer . SecurityContext = & corev1 . SecurityContext { }
2020-10-20 02:48:28 +03:00
}
2022-05-12 17:25:51 +09:00
if runnerContainer . SecurityContext . Privileged == nil {
// Runner need to run privileged if it contains DinD
runnerContainer . SecurityContext . Privileged = & dockerdInRunnerPrivileged
}
2021-06-22 17:10:09 +09:00
pod := template . DeepCopy ( )
2020-10-20 02:48:28 +03:00
2022-05-14 17:07:17 +09:00
forceRunnerPodRestartPolicyNever ( pod )
2021-06-22 17:10:09 +09:00
if mtu := runnerSpec . DockerMTU ; mtu != nil && dockerdInRunner {
runnerContainer . Env = append ( runnerContainer . Env , [ ] corev1 . EnvVar {
2021-03-11 18:44:49 -05:00
{
Name : "MTU" ,
2021-06-22 17:10:09 +09:00
Value : fmt . Sprintf ( "%d" , * runnerSpec . DockerMTU ) ,
2021-03-11 18:44:49 -05:00
} ,
} ... )
}
2021-12-14 16:29:31 -08:00
if len ( pod . Spec . ImagePullSecrets ) == 0 && len ( defaultRunnerImagePullSecrets ) > 0 {
// runner spec didn't provide custom values and default image pull secrets are provided
for _ , imagePullSecret := range defaultRunnerImagePullSecrets {
pod . Spec . ImagePullSecrets = append ( pod . Spec . ImagePullSecrets , corev1 . LocalObjectReference {
Name : imagePullSecret ,
} )
}
}
2021-07-14 22:20:08 +01:00
if dockerRegistryMirror != "" && dockerdInRunner {
2021-06-22 17:10:09 +09:00
runnerContainer . Env = append ( runnerContainer . Env , [ ] corev1 . EnvVar {
2021-04-25 08:04:01 +03:00
{
Name : "DOCKER_REGISTRY_MIRROR" ,
2021-07-14 22:20:08 +01:00
Value : dockerRegistryMirror ,
2021-04-25 08:04:01 +03:00
} ,
} ... )
}
2021-03-25 10:23:36 +09:00
//
// /runner must be generated on runtime from /runnertmp embedded in the container image.
//
// When you're NOT using dindWithinRunner=true,
// it must also be shared with the dind container as it seems like required to run docker steps.
//
2021-07-15 00:29:58 +03:00
// Setting VolumeSizeLimit to zero will disable /runner emptydir mount
//
// VolumeStorageMedium defines ways that storage can be allocated to a volume: "", "Memory", "HugePages", "HugePages-<size>"
//
2021-01-24 10:58:35 +09:00
2021-03-25 10:23:36 +09:00
runnerVolumeName := "runner"
runnerVolumeMountPath := "/runner"
2021-04-18 06:56:59 +02:00
runnerVolumeEmptyDir := & corev1 . EmptyDirVolumeSource { }
2021-07-15 00:29:58 +03:00
if runnerSpec . VolumeStorageMedium != nil {
runnerVolumeEmptyDir . Medium = corev1 . StorageMedium ( * runnerSpec . VolumeStorageMedium )
}
2021-06-22 17:10:09 +09:00
if runnerSpec . VolumeSizeLimit != nil {
runnerVolumeEmptyDir . SizeLimit = runnerSpec . VolumeSizeLimit
2021-04-18 06:56:59 +02:00
}
2021-03-25 10:23:36 +09:00
2021-07-15 00:29:58 +03:00
if runnerSpec . VolumeSizeLimit == nil || ! runnerSpec . VolumeSizeLimit . IsZero ( ) {
pod . Spec . Volumes = append ( pod . Spec . Volumes ,
corev1 . Volume {
Name : runnerVolumeName ,
VolumeSource : corev1 . VolumeSource {
EmptyDir : runnerVolumeEmptyDir ,
} ,
2020-01-30 23:52:40 +09:00
} ,
2021-07-15 00:29:58 +03:00
)
2021-03-25 10:23:36 +09:00
2021-07-15 00:29:58 +03:00
runnerContainer . VolumeMounts = append ( runnerContainer . VolumeMounts ,
corev1 . VolumeMount {
Name : runnerVolumeName ,
MountPath : runnerVolumeMountPath ,
} ,
)
}
2021-03-25 10:23:36 +09:00
if ! dockerdInRunner && dockerEnabled {
2021-07-15 00:29:58 +03:00
if runnerSpec . VolumeSizeLimit != nil && runnerSpec . VolumeSizeLimit . IsZero ( ) {
return * pod , fmt . Errorf (
"%s volume can't be disabled because it is required to share the working directory between the runner and the dockerd containers" ,
runnerVolumeName ,
)
}
2022-05-22 10:25:50 +09:00
if ok , _ := workVolumePresent ( pod . Spec . Volumes ) ; ! ok {
pod . Spec . Volumes = append ( pod . Spec . Volumes ,
corev1 . Volume {
Name : "work" ,
VolumeSource : corev1 . VolumeSource {
EmptyDir : & corev1 . EmptyDirVolumeSource { } ,
} ,
2020-11-25 01:53:47 +02:00
} ,
2022-05-22 10:25:50 +09:00
)
}
pod . Spec . Volumes = append ( pod . Spec . Volumes ,
2021-03-25 10:23:36 +09:00
corev1 . Volume {
2020-11-30 08:57:33 +09:00
Name : "certs-client" ,
VolumeSource : corev1 . VolumeSource {
EmptyDir : & corev1 . EmptyDirVolumeSource { } ,
} ,
} ,
2021-03-25 10:23:36 +09:00
)
2022-01-07 02:01:40 +01:00
2022-05-22 10:25:50 +09:00
if ok , _ := workVolumeMountPresent ( runnerContainer . VolumeMounts ) ; ! ok {
runnerContainer . VolumeMounts = append ( runnerContainer . VolumeMounts ,
corev1 . VolumeMount {
Name : "work" ,
MountPath : workDir ,
} ,
)
}
2021-06-22 17:10:09 +09:00
runnerContainer . VolumeMounts = append ( runnerContainer . VolumeMounts ,
2021-03-25 10:23:36 +09:00
corev1 . VolumeMount {
2020-11-30 08:57:33 +09:00
Name : "certs-client" ,
MountPath : "/certs/client" ,
ReadOnly : true ,
} ,
2021-03-25 10:23:36 +09:00
)
2022-01-07 02:01:40 +01:00
2021-06-22 17:10:09 +09:00
runnerContainer . Env = append ( runnerContainer . Env , [ ] corev1 . EnvVar {
2020-11-30 08:57:33 +09:00
{
Name : "DOCKER_HOST" ,
Value : "tcp://localhost:2376" ,
} ,
{
Name : "DOCKER_TLS_VERIFY" ,
Value : "1" ,
} ,
{
Name : "DOCKER_CERT_PATH" ,
Value : "/certs/client" ,
} ,
} ... )
2021-04-06 03:10:10 +02:00
// Determine the volume mounts assigned to the docker sidecar. In case extra mounts are included in the RunnerSpec, append them to the standard
2021-06-22 17:55:06 +09:00
// set of mounts. See https://github.com/actions-runner-controller/actions-runner-controller/issues/435 for context.
2021-04-06 03:10:10 +02:00
dockerVolumeMounts := [ ] corev1 . VolumeMount {
{
Name : runnerVolumeName ,
MountPath : runnerVolumeMountPath ,
} ,
{
Name : "certs-client" ,
MountPath : "/certs/client" ,
} ,
}
2021-06-22 17:10:09 +09:00
2022-01-07 02:01:40 +01:00
mountPresent , _ := workVolumeMountPresent ( dockerdContainer . VolumeMounts )
if ! mountPresent {
dockerVolumeMounts = append ( dockerVolumeMounts , corev1 . VolumeMount {
Name : "work" ,
MountPath : workDir ,
} )
}
2021-06-22 17:10:09 +09:00
if dockerdContainer . Image == "" {
dockerdContainer . Image = defaultDockerImage
2021-04-06 03:10:10 +02:00
}
2021-06-22 17:10:09 +09:00
dockerdContainer . Env = append ( dockerdContainer . Env , corev1 . EnvVar {
Name : "DOCKER_TLS_CERTDIR" ,
Value : "/certs" ,
} )
if dockerdContainer . SecurityContext == nil {
dockerdContainer . SecurityContext = & corev1 . SecurityContext {
2021-06-03 16:59:11 -07:00
Privileged : & privileged ,
SELinuxOptions : seLinuxOptions ,
2021-06-22 17:10:09 +09:00
}
}
dockerdContainer . VolumeMounts = append ( dockerdContainer . VolumeMounts , dockerVolumeMounts ... )
2020-10-20 02:48:28 +03:00
2021-06-22 17:10:09 +09:00
if mtu := runnerSpec . DockerMTU ; mtu != nil {
dockerdContainer . Env = append ( dockerdContainer . Env , [ ] corev1 . EnvVar {
2021-03-31 09:29:21 +09:00
// See https://docs.docker.com/engine/security/rootless/
2021-03-11 18:44:49 -05:00
{
Name : "DOCKERD_ROOTLESS_ROOTLESSKIT_MTU" ,
2021-06-22 17:10:09 +09:00
Value : fmt . Sprintf ( "%d" , * runnerSpec . DockerMTU ) ,
2021-03-11 18:44:49 -05:00
} ,
} ... )
2021-03-31 09:29:21 +09:00
2021-06-22 17:10:09 +09:00
dockerdContainer . Args = append ( dockerdContainer . Args ,
2021-03-31 09:29:21 +09:00
"--mtu" ,
2021-06-22 17:10:09 +09:00
fmt . Sprintf ( "%d" , * runnerSpec . DockerMTU ) ,
2021-03-31 09:29:21 +09:00
)
2021-03-11 18:44:49 -05:00
}
2021-07-14 22:20:08 +01:00
if dockerRegistryMirror != "" {
2021-06-22 17:10:09 +09:00
dockerdContainer . Args = append ( dockerdContainer . Args ,
2021-07-14 22:20:08 +01:00
fmt . Sprintf ( "--registry-mirror=%s" , dockerRegistryMirror ) ,
2021-04-25 08:04:01 +03:00
)
}
2020-01-28 21:58:01 +09:00
}
2020-01-29 23:12:07 +09:00
2021-06-22 17:10:09 +09:00
if runnerContainerIndex == - 1 {
pod . Spec . Containers = append ( [ ] corev1 . Container { * runnerContainer } , pod . Spec . Containers ... )
2020-03-20 15:50:50 +02:00
2021-06-22 17:10:09 +09:00
if dockerdContainerIndex != - 1 {
dockerdContainerIndex ++
}
} else {
pod . Spec . Containers [ runnerContainerIndex ] = * runnerContainer
2021-06-03 18:56:43 -05:00
}
2021-06-22 17:10:09 +09:00
if ! dockerdInRunner && dockerEnabled {
if dockerdContainerIndex == - 1 {
pod . Spec . Containers = append ( pod . Spec . Containers , * dockerdContainer )
} else {
pod . Spec . Containers [ dockerdContainerIndex ] = * dockerdContainer
}
2020-01-29 23:12:07 +09:00
}
2021-06-22 17:10:09 +09:00
return * pod , nil
2020-01-28 21:58:01 +09:00
}
2022-06-28 01:12:40 -04:00
func newRunnerPod ( runnerName string , template corev1 . Pod , runnerSpec v1alpha1 . RunnerConfig , defaultRunnerImage string , defaultRunnerImagePullSecrets [ ] string , defaultDockerImage , defaultDockerRegistryMirror string , githubBaseURL string ) ( corev1 . Pod , error ) {
return newRunnerPodWithContainerMode ( "" , runnerName , template , runnerSpec , defaultRunnerImage , defaultRunnerImagePullSecrets , defaultDockerImage , defaultDockerRegistryMirror , githubBaseURL )
}
2020-01-28 15:03:23 +09:00
func ( r * RunnerReconciler ) SetupWithManager ( mgr ctrl . Manager ) error {
2021-02-16 18:51:33 +09:00
name := "runner-controller"
2021-03-19 16:14:15 +09:00
if r . Name != "" {
name = r . Name
}
r . Recorder = mgr . GetEventRecorderFor ( name )
2021-02-16 18:51:33 +09:00
2020-01-28 15:03:23 +09:00
return ctrl . NewControllerManagedBy ( mgr ) .
2020-01-28 21:58:01 +09:00
For ( & v1alpha1 . Runner { } ) .
2020-01-29 23:12:07 +09:00
Owns ( & corev1 . Pod { } ) .
2021-02-16 18:51:33 +09:00
Named ( name ) .
2020-01-28 15:03:23 +09:00
Complete ( r )
}
2020-02-03 21:35:01 +09:00
2021-06-24 20:39:37 +09:00
func addFinalizer ( finalizers [ ] string , finalizerName string ) ( [ ] string , bool ) {
2020-02-03 21:35:01 +09:00
exists := false
for _ , name := range finalizers {
if name == finalizerName {
exists = true
}
}
if exists {
return finalizers , false
}
return append ( finalizers , finalizerName ) , true
}
2021-06-24 20:39:37 +09:00
func removeFinalizer ( finalizers [ ] string , finalizerName string ) ( [ ] string , bool ) {
2020-02-03 21:35:01 +09:00
removed := false
result := [ ] string { }
for _ , name := range finalizers {
if name == finalizerName {
removed = true
continue
}
result = append ( result , name )
}
return result , removed
}
2022-01-07 02:01:40 +01:00
func workVolumePresent ( items [ ] corev1 . Volume ) ( bool , int ) {
for index , item := range items {
if item . Name == "work" {
return true , index
}
}
return false , 0
}
func workVolumeMountPresent ( items [ ] corev1 . VolumeMount ) ( bool , int ) {
for index , item := range items {
if item . Name == "work" {
return true , index
}
}
return false , 0
}
2022-06-28 01:12:40 -04:00
func applyWorkVolumeClaimTemplateToPod ( pod * corev1 . Pod , workVolumeClaimTemplate * v1alpha1 . WorkVolumeClaimTemplate , workDir string ) error {
if workVolumeClaimTemplate == nil {
return errors . New ( "work volume claim template must be specified in container mode kubernetes" )
}
for i := range pod . Spec . Volumes {
if pod . Spec . Volumes [ i ] . Name == "work" {
return fmt . Errorf ( "Work volume should not be specified in container mode kubernetes. workVolumeClaimTemplate field should be used instead." )
}
}
pod . Spec . Volumes = append ( pod . Spec . Volumes , workVolumeClaimTemplate . V1Volume ( ) )
var runnerContainer * corev1 . Container
for i := range pod . Spec . Containers {
if pod . Spec . Containers [ i ] . Name == "runner" {
runnerContainer = & pod . Spec . Containers [ i ]
break
}
}
if runnerContainer == nil {
return fmt . Errorf ( "runner container is not present when applying work volume claim template" )
}
if isPresent , _ := workVolumeMountPresent ( runnerContainer . VolumeMounts ) ; isPresent {
return fmt . Errorf ( "volume mount \"work\" should not be present on the runner container in container mode kubernetes" )
}
runnerContainer . VolumeMounts = append ( runnerContainer . VolumeMounts , workVolumeClaimTemplate . V1VolumeMount ( workDir ) )
return nil
}
// isRequireSameNode specifies for the runner in kubernetes mode wether it should
// schedule jobs to the same node where the runner is
//
// This function should only be called in containerMode: kubernetes
func isRequireSameNode ( pod * corev1 . Pod ) ( bool , error ) {
isPresent , index := workVolumePresent ( pod . Spec . Volumes )
if ! isPresent {
return true , errors . New ( "internal error: work volume mount must exist in containerMode: kubernetes" )
}
if pod . Spec . Volumes [ index ] . Ephemeral == nil || pod . Spec . Volumes [ index ] . Ephemeral . VolumeClaimTemplate == nil {
return true , errors . New ( "containerMode: kubernetes should have pod.Spec.Volumes[].Ephemeral.VolumeClaimTemplate set" )
}
for _ , accessMode := range pod . Spec . Volumes [ index ] . Ephemeral . VolumeClaimTemplate . Spec . AccessModes {
switch accessMode {
case corev1 . ReadWriteOnce :
return true , nil
case corev1 . ReadWriteMany :
default :
return true , errors . New ( "actions-runner-controller supports ReadWriteOnce and ReadWriteMany modes only" )
}
}
return false , nil
}
func overwriteRunnerEnv ( runner * v1alpha1 . Runner , key string , value string ) {
for i := range runner . Spec . Env {
if runner . Spec . Env [ i ] . Name == key {
runner . Spec . Env [ i ] . Value = value
return
}
}
runner . Spec . Env = append ( runner . Spec . Env , corev1 . EnvVar { Name : key , Value : value } )
}