serviceaccounts_controller.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  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. package serviceaccount
  14. import (
  15. "fmt"
  16. "time"
  17. "github.com/golang/glog"
  18. "k8s.io/kubernetes/pkg/api"
  19. apierrs "k8s.io/kubernetes/pkg/api/errors"
  20. "k8s.io/kubernetes/pkg/api/meta"
  21. "k8s.io/kubernetes/pkg/client/cache"
  22. clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
  23. "k8s.io/kubernetes/pkg/controller/framework"
  24. "k8s.io/kubernetes/pkg/fields"
  25. "k8s.io/kubernetes/pkg/runtime"
  26. "k8s.io/kubernetes/pkg/util/metrics"
  27. "k8s.io/kubernetes/pkg/watch"
  28. )
  29. // nameIndexFunc is an index function that indexes based on an object's name
  30. func nameIndexFunc(obj interface{}) ([]string, error) {
  31. meta, err := meta.Accessor(obj)
  32. if err != nil {
  33. return []string{""}, fmt.Errorf("object has no meta: %v", err)
  34. }
  35. return []string{meta.GetName()}, nil
  36. }
  37. // ServiceAccountsControllerOptions contains options for running a ServiceAccountsController
  38. type ServiceAccountsControllerOptions struct {
  39. // ServiceAccounts is the list of service accounts to ensure exist in every namespace
  40. ServiceAccounts []api.ServiceAccount
  41. // ServiceAccountResync is the interval between full resyncs of ServiceAccounts.
  42. // If non-zero, all service accounts will be re-listed this often.
  43. // Otherwise, re-list will be delayed as long as possible (until the watch is closed or times out).
  44. ServiceAccountResync time.Duration
  45. // NamespaceResync is the interval between full resyncs of Namespaces.
  46. // If non-zero, all namespaces will be re-listed this often.
  47. // Otherwise, re-list will be delayed as long as possible (until the watch is closed or times out).
  48. NamespaceResync time.Duration
  49. }
  50. func DefaultServiceAccountsControllerOptions() ServiceAccountsControllerOptions {
  51. return ServiceAccountsControllerOptions{
  52. ServiceAccounts: []api.ServiceAccount{
  53. {ObjectMeta: api.ObjectMeta{Name: "default"}},
  54. },
  55. }
  56. }
  57. // NewServiceAccountsController returns a new *ServiceAccountsController.
  58. func NewServiceAccountsController(cl clientset.Interface, options ServiceAccountsControllerOptions) *ServiceAccountsController {
  59. e := &ServiceAccountsController{
  60. client: cl,
  61. serviceAccountsToEnsure: options.ServiceAccounts,
  62. }
  63. if cl != nil && cl.Core().GetRESTClient().GetRateLimiter() != nil {
  64. metrics.RegisterMetricAndTrackRateLimiterUsage("serviceaccount_controller", cl.Core().GetRESTClient().GetRateLimiter())
  65. }
  66. accountSelector := fields.Everything()
  67. if len(options.ServiceAccounts) == 1 {
  68. // If we're maintaining a single account, we can scope the accounts we watch to just that name
  69. accountSelector = fields.SelectorFromSet(map[string]string{api.ObjectNameField: options.ServiceAccounts[0].Name})
  70. }
  71. e.serviceAccounts, e.serviceAccountController = framework.NewIndexerInformer(
  72. &cache.ListWatch{
  73. ListFunc: func(options api.ListOptions) (runtime.Object, error) {
  74. options.FieldSelector = accountSelector
  75. return e.client.Core().ServiceAccounts(api.NamespaceAll).List(options)
  76. },
  77. WatchFunc: func(options api.ListOptions) (watch.Interface, error) {
  78. options.FieldSelector = accountSelector
  79. return e.client.Core().ServiceAccounts(api.NamespaceAll).Watch(options)
  80. },
  81. },
  82. &api.ServiceAccount{},
  83. options.ServiceAccountResync,
  84. framework.ResourceEventHandlerFuncs{
  85. DeleteFunc: e.serviceAccountDeleted,
  86. },
  87. cache.Indexers{"namespace": cache.MetaNamespaceIndexFunc},
  88. )
  89. e.namespaces, e.namespaceController = framework.NewIndexerInformer(
  90. &cache.ListWatch{
  91. ListFunc: func(options api.ListOptions) (runtime.Object, error) {
  92. return e.client.Core().Namespaces().List(options)
  93. },
  94. WatchFunc: func(options api.ListOptions) (watch.Interface, error) {
  95. return e.client.Core().Namespaces().Watch(options)
  96. },
  97. },
  98. &api.Namespace{},
  99. options.NamespaceResync,
  100. framework.ResourceEventHandlerFuncs{
  101. AddFunc: e.namespaceAdded,
  102. UpdateFunc: e.namespaceUpdated,
  103. },
  104. cache.Indexers{"name": nameIndexFunc},
  105. )
  106. return e
  107. }
  108. // ServiceAccountsController manages ServiceAccount objects inside Namespaces
  109. type ServiceAccountsController struct {
  110. stopChan chan struct{}
  111. client clientset.Interface
  112. serviceAccountsToEnsure []api.ServiceAccount
  113. serviceAccounts cache.Indexer
  114. namespaces cache.Indexer
  115. // Since we join two objects, we'll watch both of them with controllers.
  116. serviceAccountController *framework.Controller
  117. namespaceController *framework.Controller
  118. }
  119. // Runs controller loops and returns immediately
  120. func (e *ServiceAccountsController) Run() {
  121. if e.stopChan == nil {
  122. e.stopChan = make(chan struct{})
  123. go e.serviceAccountController.Run(e.stopChan)
  124. go e.namespaceController.Run(e.stopChan)
  125. }
  126. }
  127. // Stop gracefully shuts down this controller
  128. func (e *ServiceAccountsController) Stop() {
  129. if e.stopChan != nil {
  130. close(e.stopChan)
  131. e.stopChan = nil
  132. }
  133. }
  134. // serviceAccountDeleted reacts to a ServiceAccount deletion by recreating a default ServiceAccount in the namespace if needed
  135. func (e *ServiceAccountsController) serviceAccountDeleted(obj interface{}) {
  136. serviceAccount, ok := obj.(*api.ServiceAccount)
  137. if !ok {
  138. // Unknown type. If we missed a ServiceAccount deletion, the
  139. // corresponding secrets will be cleaned up during the Secret re-list
  140. return
  141. }
  142. // If the deleted service account is one we're maintaining, recreate it
  143. for _, sa := range e.serviceAccountsToEnsure {
  144. if sa.Name == serviceAccount.Name {
  145. e.createServiceAccountIfNeeded(sa, serviceAccount.Namespace)
  146. }
  147. }
  148. }
  149. // namespaceAdded reacts to a Namespace creation by creating a default ServiceAccount object
  150. func (e *ServiceAccountsController) namespaceAdded(obj interface{}) {
  151. namespace := obj.(*api.Namespace)
  152. for _, sa := range e.serviceAccountsToEnsure {
  153. e.createServiceAccountIfNeeded(sa, namespace.Name)
  154. }
  155. }
  156. // namespaceUpdated reacts to a Namespace update (or re-list) by creating a default ServiceAccount in the namespace if needed
  157. func (e *ServiceAccountsController) namespaceUpdated(oldObj interface{}, newObj interface{}) {
  158. newNamespace := newObj.(*api.Namespace)
  159. for _, sa := range e.serviceAccountsToEnsure {
  160. e.createServiceAccountIfNeeded(sa, newNamespace.Name)
  161. }
  162. }
  163. // createServiceAccountIfNeeded creates a ServiceAccount with the given name in the given namespace if:
  164. // * the named ServiceAccount does not already exist
  165. // * the specified namespace exists
  166. // * the specified namespace is in the ACTIVE phase
  167. func (e *ServiceAccountsController) createServiceAccountIfNeeded(sa api.ServiceAccount, namespace string) {
  168. existingServiceAccount, err := e.getServiceAccount(sa.Name, namespace)
  169. if err != nil {
  170. glog.Error(err)
  171. return
  172. }
  173. if existingServiceAccount != nil {
  174. // If service account already exists, it doesn't need to be created
  175. return
  176. }
  177. namespaceObj, err := e.getNamespace(namespace)
  178. if err != nil {
  179. glog.Error(err)
  180. return
  181. }
  182. if namespaceObj == nil {
  183. // If namespace does not exist, no service account is needed
  184. return
  185. }
  186. if namespaceObj.Status.Phase != api.NamespaceActive {
  187. // If namespace is not active, we shouldn't try to create anything
  188. return
  189. }
  190. e.createServiceAccount(sa, namespace)
  191. }
  192. // createDefaultServiceAccount creates a default ServiceAccount in the specified namespace
  193. func (e *ServiceAccountsController) createServiceAccount(sa api.ServiceAccount, namespace string) {
  194. sa.Namespace = namespace
  195. if _, err := e.client.Core().ServiceAccounts(namespace).Create(&sa); err != nil && !apierrs.IsAlreadyExists(err) {
  196. glog.Error(err)
  197. }
  198. }
  199. // getServiceAccount returns the ServiceAccount with the given name for the given namespace
  200. func (e *ServiceAccountsController) getServiceAccount(name, namespace string) (*api.ServiceAccount, error) {
  201. key := &api.ServiceAccount{ObjectMeta: api.ObjectMeta{Namespace: namespace}}
  202. accounts, err := e.serviceAccounts.Index("namespace", key)
  203. if err != nil {
  204. return nil, err
  205. }
  206. for _, obj := range accounts {
  207. serviceAccount := obj.(*api.ServiceAccount)
  208. if name == serviceAccount.Name {
  209. return serviceAccount, nil
  210. }
  211. }
  212. return nil, nil
  213. }
  214. // getNamespace returns the Namespace with the given name
  215. func (e *ServiceAccountsController) getNamespace(name string) (*api.Namespace, error) {
  216. key := &api.Namespace{ObjectMeta: api.ObjectMeta{Name: name}}
  217. namespaces, err := e.namespaces.Index("name", key)
  218. if err != nil {
  219. return nil, err
  220. }
  221. if len(namespaces) == 0 {
  222. return nil, nil
  223. }
  224. if len(namespaces) == 1 {
  225. return namespaces[0].(*api.Namespace), nil
  226. }
  227. return nil, fmt.Errorf("%d namespaces with the name %s indexed", len(namespaces), name)
  228. }