• Stars
    star
    443
  • Rank 98,504 (Top 2 %)
  • Language
    Go
  • Created over 5 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⏰kubernetes-cronhpa-controller is a HPA controller that allows to scale your workload based on time schedule.

kubernetes-cronhpa-controller

License Build Status

Overview

kubernetes-cronhpa-controller is a kubernetes cron horizontal pod autoscaler controller using crontab like scheme. You can use CronHorizontalPodAutoscaler with any kind object defined in kubernetes which support scale subresource(such as Deployment and StatefulSet).

Installation

  1. install CRD
# k8s < v1.22
kubectl apply -f config/crds/autoscaling.alibabacloud.com_cronhorizontalpodautoscalers.yaml
# k8s >=v1.22
kubectl apply -f config/crds/autoscaling.alibabacloud.com_cronhorizontalpodautoscalers.v1.22.yaml
  1. install RBAC settings
# create ClusterRole 
kubectl apply -f config/rbac/rbac_role.yaml

# create ClusterRolebinding and ServiceAccount 
kubectl apply -f config/rbac/rbac_role_binding.yaml
  1. deploy kubernetes-cronhpa-controller
kubectl apply -f config/deploy/deploy.yaml
  1. verify installation
kubectl get deploy kubernetes-cronhpa-controller -n kube-system -o wide 

➜  kubernetes-cronhpa-controller git:(master) ✗ kubectl get deploy kubernetes-cronhpa-controller -n kube-system
NAME                            DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
kubernetes-cronhpa-controller   1         1         1            1           49s

Example

Please try out the examples in the examples folder.

  1. Deploy sample workload and cronhpa
kubectl apply -f examples/deployment_cronhpa.yaml 
  1. Check deployment replicas
kubectl get deploy nginx-deployment-basic 

➜  kubernetes-cronhpa-controller git:(master) ✗ kubectl get deploy nginx-deployment-basic
NAME                     DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment-basic   2         2         2            2           9s
  1. Describe cronhpa status
kubectl describe cronhpa cronhpa-sample 

Name:         cronhpa-sample
Namespace:    default
Labels:       controller-tools.k8s.io=1.0
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"autoscaling.alibabacloud.com/v1beta1","kind":"CronHorizontalPodAutoscaler","metadata":{"annotations":{},"labels":{"controll...
API Version:  autoscaling.alibabacloud.com/v1beta1
Kind:         CronHorizontalPodAutoscaler
Metadata:
  Creation Timestamp:  2019-04-14T10:42:38Z
  Generation:          1
  Resource Version:    4017247
  Self Link:           /apis/autoscaling.alibabacloud.com/v1beta1/namespaces/default/cronhorizontalpodautoscalers/cronhpa-sample
  UID:                 05e41c95-5ea2-11e9-8ce6-00163e12e274
Spec:
  Exclude Dates:  <nil>
  Jobs:
    Name:         scale-down
    Run Once:     false
    Schedule:     30 */1 * * * *
    Target Size:  1
    Name:         scale-up
    Run Once:     false
    Schedule:     0 */1 * * * *
    Target Size:  3
  Scale Target Ref:
    API Version:  apps/v1beta2
    Kind:         Deployment
    Name:         nginx-deployment-basic
Status:
  Conditions:
    Job Id:           38e79271-9a42-4131-9acd-1f5bfab38802
    Last Probe Time:  2019-04-14T10:43:02Z
    Message:
    Name:             scale-down
    Run Once:         false
    Schedule:         30 */1 * * * *
    State:            Submitted
    Job Id:           a7db95b6-396a-4753-91d5-23c2e73819ac
    Last Probe Time:  2019-04-14T10:43:02Z
    Message:
    Name:             scale-up
    Run Once:         false
    Schedule:         0 */1 * * * *
    State:            Submitted
  Exclude Dates:      <nil>
  Scale Target Ref:
    API Version:  apps/v1beta2
    Kind:         Deployment
    Name:         nginx-deployment-basic
Events:               <none>

if the State of cronhpa job is Succeed that means the last execution is successful. Submitted means the cronhpa job is submitted to the cron engine but haven't be executed so far. Wait for 30s seconds and check the status.

➜  kubernetes-cronhpa-controller git:(master) kubectl describe cronhpa cronhpa-sample
Name:         cronhpa-sample
Namespace:    default
Labels:       controller-tools.k8s.io=1.0
Annotations:  <none>
API Version:  autoscaling.alibabacloud.com/v1beta1
Kind:         CronHorizontalPodAutoscaler
Metadata:
  Creation Timestamp:  2019-11-01T12:49:57Z
  Generation:          1
  Resource Version:    47812775
  Self Link:           /apis/autoscaling.alibabacloud.com/v1beta1/namespaces/default/cronhorizontalpodautoscalers/cronhpa-sample
  UID:                 1bbbab8a-fca6-11e9-bb47-00163e12ab74
Spec:
  Exclude Dates:  <nil>
  Jobs:
    Name:         scale-down
    Run Once:     false
    Schedule:     30 */1 * * * *
    Target Size:  2
    Name:         scale-up
    Run Once:     false
    Schedule:     0 */1 * * * *
    Target Size:  3
  Scale Target Ref:
    API Version:  apps/v1beta2
    Kind:         Deployment
    Name:         nginx-deployment-basic2
Status:
  Conditions:
    Job Id:           157260b9-489c-4a12-ad5c-f544386f0243
    Last Probe Time:  2019-11-05T03:47:30Z
    Message:          cron hpa job scale-down executed successfully. current replicas:3, desired replicas:2
    Name:             scale-down
    Run Once:         false
    Schedule:         30 */1 * * * *
    State:            Succeed
    Job Id:           5bab7b8c-158a-469c-a68c-a4657486e2a5
    Last Probe Time:  2019-11-05T03:48:00Z
    Message:          cron hpa job scale-up executed successfully. current replicas:2, desired replicas:3
    Name:             scale-up
    Run Once:         false
    Schedule:         0 */1 * * * *
    State:            Succeed
  Exclude Dates:      <nil>
  Scale Target Ref:
    API Version:  apps/v1beta2
    Kind:         Deployment
    Name:         nginx-deployment-basic
Events:
  Type    Reason   Age                     From                            Message
  ----    ------   ----                    ----                            -------
  Normal  Succeed  42m (x5165 over 3d14h)  cron-horizontal-pod-autoscaler  cron hpa job scale-down executed successfully. current replicas:3, desired replicas:1
  Normal  Succeed  30m                     cron-horizontal-pod-autoscaler  cron hpa job scale-up executed successfully. current replicas:1, desired replicas:3
  Normal  Succeed  17m (x13 over 29m)      cron-horizontal-pod-autoscaler  cron hpa job scale-up executed successfully. current replicas:2, desired replicas:3
  Normal  Succeed  4m59s (x26 over 29m)    cron-horizontal-pod-autoscaler  cron hpa job scale-down executed successfully. current replicas:3, desired replicas:2

🍻Cheers! It works.

Implementation Details

The following is an example of a CronHorizontalPodAutoscaler.

apiVersion: autoscaling.alibabacloud.com/v1beta1
kind: CronHorizontalPodAutoscaler
metadata:
  labels:
    controller-tools.k8s.io: "1.0"
  name: cronhpa-sample
  namespace: default 
spec:
   scaleTargetRef:
      apiVersion: apps/v1beta2
      kind: Deployment
      name: nginx-deployment-basic
   jobs:
   - name: "scale-down"
     schedule: "30 */1 * * * *"
     targetSize: 1
   - name: "scale-up"
     schedule: "0 */1 * * * *"
     targetSize: 3

The scaleTargetRef is the field to specify workload to scale. If the workload supports scale subresource(such as Deployment and StatefulSet), CronHorizontalPodAutoscaler should work well. CronHorizontalPodAutoscaler support multi cronhpa job in one spec.

The cronhpa job spec need three fields:

  • name
    name should be unique in one cronhpa spec. You can distinguish different job execution status by job name.

  • schedule
    The scheme of schedule is similar with crontab. kubernetes-cronhpa-controller use an enhanced cron golang lib (go-cron) which support more expressive rules.

    The cron expression format is as described below:

    
      Field name   | Mandatory? | Allowed values  | Allowed special characters
      ----------   | ---------- | --------------  | --------------------------
      Seconds      | Yes        | 0-59            | * / , -
      Minutes      | Yes        | 0-59            | * / , -
      Hours        | Yes        | 0-23            | * / , -
      Day of month | Yes        | 1-31            | * / , - ?
      Month        | Yes        | 1-12 or JAN-DEC | * / , -
      Day of week  | Yes        | 0-6 or SUN-SAT  | * / , - ?    
    

    Asterisk ( * )

    The asterisk indicates that the cron expression will match for all values of the field; e.g., using an asterisk in the 5th field (month) would indicate every month.

    Slash ( / )

    Slashes are used to describe increments of ranges. For example 3-59/15 in the 1st field (minutes) would indicate the 3rd minute of the hour and every 15 minutes thereafter. The form "*/..." is equivalent to the form "first-last/...", that is, an increment over the largest possible range of the field. The form "N/..." is accepted as meaning "N-MAX/...", that is, starting at N, use the increment until the end of that specific range. It does not wrap around.

    Comma ( , )

    Commas are used to separate items of a list. For example, using "MON,WED,FRI" in the 5th field (day of week) would mean Mondays, Wednesdays and Fridays.

    Hyphen ( - )

    Hyphens are used to define ranges. For example, 9-17 would indicate every hour between 9am and 5pm inclusive.

    Question mark ( ? )

    Question mark may be used instead of '*' for leaving either day-of-month or day-of-week blank.

    Predefined schedules

    You may use one of several pre-defined schedules in place of a cron expression.

    Entry Description Equivalent To
    @yearly (or @annually) Run once a year, midnight, Jan. 1st 0 0 1 1 *
    @monthly Run once a month, midnight, first of month 0 0 1 * *
    @weekly Run once a week, midnight between Sat/Sun 0 0 * * 0
    @daily (or @midnight) Run once a day, midnight 0 0 * * *
    @hourly Run once an hour, beginning of hour 0 * * * *
    Intervals
    You may also schedule a job to execute at fixed intervals, starting at the time it's added or cron is run. This is supported by formatting the cron spec like this:

    @every where "duration" is a string accepted by time.ParseDuration (http://golang.org/pkg/time/#ParseDuration).

    For example, "@every 1h30m10s" would indicate a schedule that activates after 1 hour, 30 minutes, 10 seconds, and then every interval after that.

    Note: The interval does not take the job runtime into account. For example, if a job takes 3 minutes to run, and it is scheduled to run every 5 minutes, it will have only 2 minutes of idle time between each run.

    more schedule scheme please check this doc.

    Specific Date (@date)

    You may use the specific date to schedule a job for scaling the workloads. It is useful when you want to do a daily promotion.

    Entry Description Equivalent To
    @date 2020-10-27 21:54:00 Run once when the date reach 0 54 21 27 10 *
  • targetSize
    TargetSize is the size you desired to scale when the scheduled time arrive.

  • runOnce
    if runOnce is true then the job will only run and exit after the first execution.

  • excludeDates
    excludeDates is a dates array. The job will skip the execution when the dates is matched. The minimum unit is day. If you want to skip the date(November 15th), You can specific the excludeDates like below.

      excludeDates:
      - "* * * 15 11 *"
    

Metrics and Monitoring

kubernetes-cronhpa-controller export metrics through prometheus metrics format. Here are core metrics list.

# HELP kube_expired_jobs_in_cron_engine_total Expired jobs in queue of Cron Engine
# TYPE kube_expired_jobs_in_cron_engine_total gauge
kube_expired_jobs_in_cron_engine_total 0

# HELP kube_failed_jobs_in_cron_engine_total Failed jobs in queue of Cron Engine
# TYPE kube_failed_jobs_in_cron_engine_total gauge
kube_failed_jobs_in_cron_engine_total 0

HELP kube_jobs_in_cron_engine_total Jobs in queue of Cron Engine
# TYPE kube_jobs_in_cron_engine_total gauge
kube_jobs_in_cron_engine_total 2

# HELP kube_submitted_jobs_in_cron_engine_total Submitted jobs in queue of Cron Engine
# TYPE kube_submitted_jobs_in_cron_engine_total gauge
kube_submitted_jobs_in_cron_engine_total 0

# HELP kube_successful_jobs_in_cron_engine_total Successful jobs in queue of Cron Engine
# TYPE kube_successful_jobs_in_cron_engine_total gauge
kube_successful_jobs_in_cron_engine_total 2

In most of kubernetes cluster.

kube_jobs_in_cron_engine_total = kube_failed_jobs_in_cron_engine_total + kube_submitted_jobs_in_cron_engine_total + kube_successful_jobs_in_cron_engine_total.

Expired jobs are in unique state when cron engine have exceptions. So kube_failed_jobs_in_cron_engine_total and kube_expired_jobs_in_cron_engine_total are two key metrics to monitor.

Common Question

  • Could kubernetes-cronhpa-controller and HPA work together?
    Yes and no is the answer. kubernetes-cronhpa-controller can work together with hpa. But if the desired replicas is independent. So when the HPA min replicas reached kubernetes-cronhpa-controller will ignore the replicas and scale down and later the HPA controller will scale it up.

Contributing

Please check CONTRIBUTING.md

License

This software is released under the Apache 2.0 license.

More Repositories

1

k8s-for-docker-desktop

为Docker Desktop for Mac/Windows开启Kubernetes和Istio。
PowerShell
4,960
star
2

pouch

An Efficient Enterprise-class Container Engine
Go
4,626
star
3

log-pilot

Collect logs for docker containers
Go
1,429
star
4

gpushare-scheduler-extender

GPU Sharing Scheduler for Kubernetes Cluster
Go
1,403
star
5

kube-eventer

kube-eventer emit kubernetes events to sinks
Go
1,000
star
6

image-syncer

Docker image synchronization tool for Docker Registry V2 based services
Go
874
star
7

DevOps

阿里云容器服务持续交付
779
star
8

derrick

🐳A tool to help you containerize application in seconds
Go
685
star
9

terway

CNI plugin for Alibaba Cloud VPC/ENI
Go
550
star
10

gpushare-device-plugin

GPU Sharing Device Plugin for Kubernetes Cluster
Go
468
star
11

redis-cluster

HA Redis Cluster with Sentinel by Docker Compose
Shell
455
star
12

docker-machine-driver-aliyunecs

Aliyun (Alibaba Cloud) ECS Driver of Docker Machine
Go
203
star
13

serverless-k8s-examples

Examples for Serverless Kubernetes on Alibaba Cloud - https://yq.aliyun.com/articles/591115
Go
158
star
14

ackdistro

Shell
122
star
15

flexvolume

FlexVolume plugin for Alibaba Cloud EBS/NAS/OSS, etc.
Go
109
star
16

jenkins-slaves

jenkins containerized slaves
Shell
107
star
17

alicloud-controller-manager

The official project is moved to https://github.com/kubernetes/cloud-provider-alibaba-cloud
Go
90
star
18

et-operator

Kubernetes Operator for AI and Bigdata Elastic Training
Go
84
star
19

sync-repo

Synchronize images from gcr.io, quay.io and Docker Hub to your Docker registry
Python
82
star
20

velero-plugin

Go
78
star
21

sgx-device-plugin

Kubernetes Device Plugin for Intel SGX
Go
67
star
22

alibaba-cloud-metrics-adapter

Kubernetes Custom Metrics API and External Metrics API for Alibaba Cloud
Go
55
star
23

maven-image

Maven Docker Image with Aliyun Mirror
Dockerfile
47
star
24

kubernetes-issues-solution

Kubernetes related issues solution
Shell
39
star
25

scaler

Java
39
star
26

roadmap

Product roadmap for Alibaba Cloud Container Services including ACK, ACR, ASK - Serverless K8S, ACK@Edge and ASM - Service Mesh
33
star
27

kube2ram

kube2ram provides different Alibaba Cloud RAM roles for pods running on ACK
Go
32
star
28

ack-ram-authenticator

Using Alibaba Cloud credentials to authenticate to a Kubernetes cluster
Go
31
star
29

alicloud-storage-provisioner

Alicloud Storage Provider for Kubernetes
Go
31
star
30

open-service-broker-alibabacloud

The Open Service Broker API implementation for Alibaba Cloud
Go
30
star
31

ack-image-builder

Custom Image Builder for ACK
Shell
28
star
32

ack-kms-plugin

KMS provider plugin for Alibaba Cloud
Go
27
star
33

spring-cloud-k8s-sample

This example demonstrate how to use AliCloud Container Service feature to build a spring-boot application leveraging with Spring Cloud capabilities.
Java
24
star
34

jenkins-demo

Java
23
star
35

spot-instance-advisor

spot-instance-advisor is command line tool to get the cheapest group of spot instanceTypes.
Go
22
star
36

solution-blockchain-demo

This is a repository for source codes of demo application and demo explorer for Blockchain Solution of Alibaba Cloud Container Service
JavaScript
22
star
37

helm-acr

Alibaba Cloud's Helm plugin to push chart package to ChartMuseum.
Go
22
star
38

docker-jenkins

Jenkins Docker Image which can set proper permission for local host volume
Shell
20
star
39

gpu-analyzer

GPU analyzer for Kubernetes GPU clusters
Go
17
star
40

ai-starter

Shell
17
star
41

benchmark-for-spark

benchmark-for-spark
HCL
16
star
42

terway-qos

The QoS project is a cloud-native solution leveraging eBPF technology, designed to efficiently manage and optimize network traffic across diverse hybrid deployment scenarios.
C
15
star
43

ack-secret-manager

ACK Secret Manager allows you to use external secret management systems (*e.g.*, Alibaba Cloud Secrets Manager) to securely add secrets in Kubernetes.
Go
15
star
44

kubeflow-aliyun

Deploy Kubeflow on Alibaba Cloud
14
star
45

monitoring-sample

Shell
13
star
46

cluster-api-provider-alibabacloud

Go
11
star
47

kubernetes-ops-handbook

Common kubernetes problems ops handbook.
10
star
48

hello-servicemesh-grpc

gRPC demo for ServiceMesh
Shell
9
star
49

jenkins-cos

Aliyun-Container-Service-plugin
Java
9
star
50

jenkins-on-serverless

9
star
51

rust-wasm-4-envoy

Shell
8
star
52

kubectl-autoscaler-plugin

7
star
53

ubuntu-image

Official Ubuntu Docker image with Aliyun mirror
7
star
54

centos-image

Official CentOS Docker image with Aliyun mirror
6
star
55

ack-ram-tool

Go
6
star
56

asm-labs

Go
6
star
57

ai-models-on-ack

Examples of deploying AI applications on ACK
Makefile
6
star
58

kubernetes-webhook-injector

Go
6
star
59

ghost-image

Ghost Blog Docker image with Aliyun OSS and MySQL
JavaScript
6
star
60

disk-snapshot

Support Aliyun Disk Snapshot in K8S without CSI Plugin
Go
5
star
61

prometheus-operator-charts

5
star
62

alibabacloud-ack-connector

Go
5
star
63

tsung-image

tsung docker image.
Shell
5
star
64

alpine-image

Official Alpine Docker Image with Aliyun Mirror
Shell
5
star
65

notation-alibabacloud-secret-manager

Go
4
star
66

data-on-ack

Examples of Data & AI/ML on Alibaba Cloud ACK by AI Suite
Go
4
star
67

debian-image

Official Debian Docker image with Aliyun mirror
3
star
68

demo-java

Java
3
star
69

node-resource-manager

3
star
70

nginx-sd-image

Python
2
star
71

demo-logstash

2
star
72

secrets-store-csi-driver-provider-alibaba-cloud

The Alibaba Cloud provider for the Secrets Store CSI Driver allows you to fetch secrets from Alibaba Cloud Secrets Manager and mount them into Kubernetes pods.
Go
2
star
73

python-image

Official Python image with Aliyun mirror of Pypi
Shell
2
star
74

grpc-transcoder

an envoyfiler generator for grpc-transcoder
Go
2
star
75

mpi-operator

Go
1
star
76

ack-tag-tool

Simple tool to tag all Alibaba Cloud resources used in specific ACK K8s cluster.
Python
1
star
77

wordpress-image

Official Wordpress Docker Image with Aliyun OSS plugin
PHP
1
star
78

haproxy-image

Official Haproxy Docker Image with Aliyun Mirror
1
star
79

cloud-environments

Makefile
1
star
80

argo-workflow-examples

Python
1
star
81

infrakit.aliyun

Infrakit plugins for Aliyun (Alibaba Cloud).
Go
1
star
82

node-image

Official NodeJS Docker Image with Taobao NPM mirror
1
star
83

demo-nodejs

JavaScript
1
star
84

gitops-demo

Smarty
1
star
85

ruby-image

Official Ruby Docker image with Ruby China mirror
Shell
1
star
86

jupyter-notebook

Jupyter Notebook Python, Scala, R, Spark, Mesos Stack
1
star
87

alibabacloud-erdma-controller

Go
1
star