Adding TTLs to kubernetes api server

2019-09-11 06:12发布

Following up on Kubernetes Endpoints with TTL:

Is there a plan to add TTLs to Kubernetes API resources in the future?

If I wanted to try to experiment with adding an optional TTL to the API myself, can somebody help me get started by pointing me to the right place in the code or docs where I should start looking to figure out what I need to change?

I'm assuming that the interface to the underlying storage has TTLs and all I need to change is how the API server could be passed a TTL that I would then forward to the storage. Does that sound right?

标签: kubernetes
1条回答
Bombasti
2楼-- · 2019-09-11 06:49

You do not need to modify kubernetes to do this.

Here is how to do it yourself.

  1. add an annotation to each object that you want to have a TTL. The annotation can say when it should expire. You can pick the name and format of this annotation.
  2. update the annotation each time you update the object.
  3. run another process that repeatedly lists all the objects of a given type and deletes ones that need to expire.

Here are specific commands to do this for endpoints.

Add an annotation to an endpoint with expiration time one minute from now:

   #!/bin/bash
   expiretime=$(date -v+60S +%s)
   kubectl annotate endpoints/somename expires-at=$expiretime

Script to list endpoints, and delete those with expires-at after now:

   #!/bin/bash
   while 1
   do 
     for NS in $(kubectl get namespaces -o name | cut -f 2 -d "/")
     do 
         for NAME in $(kubectl --namespace=$NS get endpoints -o name)
         do
             exp=$( kubectl get --namespace $NS $NAME -o jsonpath={.metadata.annotations."expires-at"} 2> /dev/null) && \
             [[ $exp < $(date +%s) ]] && \
             echo "Deleting expired endpoints $NAME in $NS" && \ 
             kubectl delete $NS $NAME
         done
     done
   done

A pod is a great place to run the above script. It will have automatic access to the API and with a replication controller, it will run forever.

查看更多
登录 后发表回答