Skip to content

recreate generated service cert secret when deleted #12853

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 8, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 61 additions & 2 deletions pkg/service/controller/servingcert/secret_creating_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ type ServiceServingCertController struct {

serviceCache cache.Store
serviceController *cache.Controller
serviceHasSynced informerSynced

secretCache cache.Store
secretController *cache.Controller
secretHasSynced informerSynced

ca *crypto.CA
publicCert string
Expand Down Expand Up @@ -106,6 +111,24 @@ func NewServiceServingCertController(serviceClient kcoreclient.ServicesGetter, s
},
},
)
sc.serviceHasSynced = sc.serviceController.HasSynced

sc.secretCache, sc.secretController = cache.NewInformer(
&cache.ListWatch{
ListFunc: func(options kapi.ListOptions) (runtime.Object, error) {
return sc.secretClient.Secrets(kapi.NamespaceAll).List(options)
},
WatchFunc: func(options kapi.ListOptions) (watch.Interface, error) {
return sc.secretClient.Secrets(kapi.NamespaceAll).Watch(options)
},
},
&kapi.Secret{},
resyncInterval,
cache.ResourceEventHandlerFuncs{
DeleteFunc: sc.deleteSecret,
},
)
sc.secretHasSynced = sc.secretController.HasSynced

sc.syncHandler = sc.syncService

Expand All @@ -116,6 +139,11 @@ func NewServiceServingCertController(serviceClient kcoreclient.ServicesGetter, s
func (sc *ServiceServingCertController) Run(workers int, stopCh <-chan struct{}) {
defer utilruntime.HandleCrash()
go sc.serviceController.Run(stopCh)
go sc.secretController.Run(stopCh)
if !waitForCacheSync(stopCh, sc.serviceHasSynced, sc.secretHasSynced) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@deads2k any reason you did not waited for the caches to sync before?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@deads2k any reason you did not waited for the caches to sync before?

Things would self-settle since the first mutation would fail until the cache updated and the services aren't self referential.

return
}

for i := 0; i < workers; i++ {
go wait.Until(sc.worker, time.Second, stopCh)
}
Expand All @@ -125,7 +153,34 @@ func (sc *ServiceServingCertController) Run(workers int, stopCh <-chan struct{})
sc.queue.ShutDown()
}

// deleteSecret handles the case when the service certificate secret is manually removed.
// In that case the secret will be automatically recreated.
func (sc *ServiceServingCertController) deleteSecret(obj interface{}) {
secret, ok := obj.(*kapi.Secret)
if !ok {
return
}
if _, exists := secret.Annotations[ServiceNameAnnotation]; !exists {
return
}
serviceObj, exists, err := sc.serviceCache.GetByKey(secret.Namespace + "/" + secret.Annotations[ServiceNameAnnotation])
if !exists {
return
}
if err != nil {
return
}
service := serviceObj.(*kapi.Service)
glog.V(4).Infof("Recreating secret for service %q", service.Namespace+"/"+service.Name)

sc.enqueueService(serviceObj)
}

func (sc *ServiceServingCertController) enqueueService(obj interface{}) {
_, ok := obj.(*kapi.Service)
if !ok {
return
}
key, err := controller.KeyFunc(obj)
if err != nil {
glog.Errorf("Couldn't get key for object %+v: %v", obj, err)
Expand Down Expand Up @@ -292,7 +347,8 @@ func getNumFailures(service *kapi.Service) int {
}

func (sc *ServiceServingCertController) requiresCertGeneration(service *kapi.Service) bool {
if secretName := service.Annotations[ServingCertSecretAnnotation]; len(secretName) == 0 {
secretName := service.Annotations[ServingCertSecretAnnotation]
if len(secretName) == 0 {
return false
}
if getNumFailures(service) >= sc.maxRetries {
Expand All @@ -301,6 +357,9 @@ func (sc *ServiceServingCertController) requiresCertGeneration(service *kapi.Ser
if service.Annotations[ServingCertCreatedByAnnotation] == sc.ca.Config.Certs[0].Subject.CommonName {
return false
}

// TODO: use the lister here
if _, exists, _ := sc.secretCache.GetByKey(service.Namespace + "/" + secretName); !exists {
return true
}
return true
}
153 changes: 145 additions & 8 deletions pkg/service/controller/servingcert/secret_creating_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import (
"github.com/openshift/origin/pkg/cmd/server/crypto/extensions"
)

func controllerSetup(startingObjects []runtime.Object, stopChannel chan struct{}, t *testing.T) ( /*caName*/ string, *fake.Clientset, *watch.FakeWatcher, *ServiceServingCertController) {
func controllerSetup(startingObjects []runtime.Object, stopChannel chan struct{}, t *testing.T) ( /*caName*/ string, *fake.Clientset, *watch.FakeWatcher, *watch.FakeWatcher, *ServiceServingCertController) {
certDir, err := ioutil.TempDir("", "serving-cert-unit-")
if err != nil {
t.Fatalf("unexpected error: %v", err)
Expand All @@ -42,17 +42,21 @@ func controllerSetup(startingObjects []runtime.Object, stopChannel chan struct{}

kubeclient := fake.NewSimpleClientset(startingObjects...)
fakeWatch := watch.NewFake()
fakeSecretWatch := watch.NewFake()
kubeclient.PrependReactor("create", "*", func(action core.Action) (handled bool, ret runtime.Object, err error) {
return true, action.(core.CreateAction).GetObject(), nil
})
kubeclient.PrependReactor("update", "*", func(action core.Action) (handled bool, ret runtime.Object, err error) {
return true, action.(core.UpdateAction).GetObject(), nil
})
kubeclient.PrependWatchReactor("*", core.DefaultWatchReactor(fakeWatch, nil))
kubeclient.PrependWatchReactor("services", core.DefaultWatchReactor(fakeWatch, nil))
kubeclient.PrependWatchReactor("secrets", core.DefaultWatchReactor(fakeSecretWatch, nil))

controller := NewServiceServingCertController(kubeclient.Core(), kubeclient.Core(), ca, "cluster.local", 10*time.Minute)
controller.serviceHasSynced = func() bool { return true }
controller.secretHasSynced = func() bool { return true }

return caOptions.Name, kubeclient, fakeWatch, controller
return caOptions.Name, kubeclient, fakeWatch, fakeSecretWatch, controller
}

func checkGeneratedCertificate(t *testing.T, certData []byte, service *kapi.Service) {
Expand Down Expand Up @@ -105,7 +109,7 @@ func TestBasicControllerFlow(t *testing.T) {
defer close(stopChannel)
received := make(chan bool)

caName, kubeclient, fakeWatch, controller := controllerSetup([]runtime.Object{}, stopChannel, t)
caName, kubeclient, fakeWatch, _, controller := controllerSetup([]runtime.Object{}, stopChannel, t)
controller.syncHandler = func(serviceKey string) error {
defer func() { received <- true }()

Expand Down Expand Up @@ -200,7 +204,7 @@ func TestAlreadyExistingSecretControllerFlow(t *testing.T) {
existingSecret.Type = kapi.SecretTypeTLS
existingSecret.Annotations = expectedSecretAnnotations

caName, kubeclient, fakeWatch, controller := controllerSetup([]runtime.Object{existingSecret}, stopChannel, t)
caName, kubeclient, fakeWatch, _, controller := controllerSetup([]runtime.Object{existingSecret}, stopChannel, t)
kubeclient.PrependReactor("create", "secrets", func(action core.Action) (handled bool, ret runtime.Object, err error) {
return true, &kapi.Secret{}, kapierrors.NewAlreadyExists(kapi.Resource("secrets"), "new-secret")
})
Expand Down Expand Up @@ -277,7 +281,7 @@ func TestAlreadyExistingSecretForDifferentUIDControllerFlow(t *testing.T) {
existingSecret.Type = kapi.SecretTypeTLS
existingSecret.Annotations = map[string]string{ServiceUIDAnnotation: "wrong-uid", ServiceNameAnnotation: serviceName}

_, kubeclient, fakeWatch, controller := controllerSetup([]runtime.Object{existingSecret}, stopChannel, t)
_, kubeclient, fakeWatch, _, controller := controllerSetup([]runtime.Object{existingSecret}, stopChannel, t)
kubeclient.PrependReactor("create", "secrets", func(action core.Action) (handled bool, ret runtime.Object, err error) {
return true, &kapi.Secret{}, kapierrors.NewAlreadyExists(kapi.Resource("secrets"), "new-secret")
})
Expand Down Expand Up @@ -347,7 +351,7 @@ func TestSecretCreationErrorControllerFlow(t *testing.T) {
serviceUID := "some-uid"
namespace := "ns"

_, kubeclient, fakeWatch, controller := controllerSetup([]runtime.Object{}, stopChannel, t)
_, kubeclient, fakeWatch, _, controller := controllerSetup([]runtime.Object{}, stopChannel, t)
kubeclient.PrependReactor("create", "secrets", func(action core.Action) (handled bool, ret runtime.Object, err error) {
return true, &kapi.Secret{}, kapierrors.NewForbidden(kapi.Resource("secrets"), "new-secret", fmt.Errorf("any reason"))
})
Expand Down Expand Up @@ -409,7 +413,7 @@ func TestSkipGenerationControllerFlow(t *testing.T) {
serviceUID := "some-uid"
namespace := "ns"

caName, kubeclient, fakeWatch, controller := controllerSetup([]runtime.Object{}, stopChannel, t)
caName, kubeclient, fakeWatch, _, controller := controllerSetup([]runtime.Object{}, stopChannel, t)
kubeclient.PrependReactor("update", "service", func(action core.Action) (handled bool, ret runtime.Object, err error) {
return true, &kapi.Service{}, kapierrors.NewForbidden(kapi.Resource("fdsa"), "new-service", fmt.Errorf("any service reason"))
})
Expand Down Expand Up @@ -470,3 +474,136 @@ func TestSkipGenerationControllerFlow(t *testing.T) {
}
}
}

func TestRecreateSecretControllerFlow(t *testing.T) {
stopChannel := make(chan struct{})
defer close(stopChannel)
received := make(chan bool)

caName, kubeclient, fakeWatch, fakeSecretWatch, controller := controllerSetup([]runtime.Object{}, stopChannel, t)
controller.syncHandler = func(serviceKey string) error {
defer func() { received <- true }()

err := controller.syncService(serviceKey)
if err != nil {
t.Errorf("unexpected error: %v", err)
}

return err
}
go controller.Run(1, stopChannel)

expectedSecretName := "new-secret"
serviceName := "svc-name"
serviceUID := "some-uid"
expectedServiceAnnotations := map[string]string{ServingCertSecretAnnotation: expectedSecretName, ServingCertCreatedByAnnotation: caName}
expectedSecretAnnotations := map[string]string{ServiceUIDAnnotation: serviceUID, ServiceNameAnnotation: serviceName}
namespace := "ns"

serviceToAdd := &kapi.Service{}
serviceToAdd.Name = serviceName
serviceToAdd.Namespace = namespace
serviceToAdd.UID = types.UID(serviceUID)
serviceToAdd.Annotations = map[string]string{ServingCertSecretAnnotation: expectedSecretName}
fakeWatch.Add(serviceToAdd)

secretToDelete := &kapi.Secret{}
secretToDelete.Name = expectedSecretName
secretToDelete.Namespace = namespace
secretToDelete.Annotations = map[string]string{ServiceNameAnnotation: serviceName}

t.Log("waiting to reach syncHandler")
select {
case <-received:
case <-time.After(time.Duration(30 * time.Second)):
t.Fatalf("failed to call into syncService")
}

foundSecret := false
foundServiceUpdate := false
for _, action := range kubeclient.Actions() {
switch {
case action.Matches("create", "secrets"):
createSecret := action.(core.CreateAction)
newSecret := createSecret.GetObject().(*kapi.Secret)
if newSecret.Name != expectedSecretName {
t.Errorf("expected %v, got %v", expectedSecretName, newSecret.Name)
continue
}
if newSecret.Namespace != namespace {
t.Errorf("expected %v, got %v", namespace, newSecret.Namespace)
continue
}
delete(newSecret.Annotations, ServingCertExpiryAnnotation)
if !reflect.DeepEqual(newSecret.Annotations, expectedSecretAnnotations) {
t.Errorf("expected %v, got %v", expectedSecretAnnotations, newSecret.Annotations)
continue
}

checkGeneratedCertificate(t, newSecret.Data["tls.crt"], serviceToAdd)
foundSecret = true

case action.Matches("update", "services"):
updateService := action.(core.UpdateAction)
service := updateService.GetObject().(*kapi.Service)
if !reflect.DeepEqual(service.Annotations, expectedServiceAnnotations) {
t.Errorf("expected %v, got %v", expectedServiceAnnotations, service.Annotations)
continue
}
foundServiceUpdate = true

}
}

if !foundSecret {
t.Errorf("secret wasn't created. Got %v\n", kubeclient.Actions())
}
if !foundServiceUpdate {
t.Errorf("service wasn't updated. Got %v\n", kubeclient.Actions())
}

kubeclient.ClearActions()
fakeSecretWatch.Add(secretToDelete)
fakeSecretWatch.Delete(secretToDelete)

t.Log("waiting to reach syncHandler")
select {
case <-received:
case <-time.After(time.Duration(30 * time.Second)):
t.Fatalf("failed to call into syncService")
}

for _, action := range kubeclient.Actions() {
switch {
case action.Matches("create", "secrets"):
createSecret := action.(core.CreateAction)
newSecret := createSecret.GetObject().(*kapi.Secret)
if newSecret.Name != expectedSecretName {
t.Errorf("expected %v, got %v", expectedSecretName, newSecret.Name)
continue
}
if newSecret.Namespace != namespace {
t.Errorf("expected %v, got %v", namespace, newSecret.Namespace)
continue
}
delete(newSecret.Annotations, ServingCertExpiryAnnotation)
if !reflect.DeepEqual(newSecret.Annotations, expectedSecretAnnotations) {
t.Errorf("expected %v, got %v", expectedSecretAnnotations, newSecret.Annotations)
continue
}

checkGeneratedCertificate(t, newSecret.Data["tls.crt"], serviceToAdd)
foundSecret = true

case action.Matches("update", "services"):
updateService := action.(core.UpdateAction)
service := updateService.GetObject().(*kapi.Service)
if !reflect.DeepEqual(service.Annotations, expectedServiceAnnotations) {
t.Errorf("expected %v, got %v", expectedServiceAnnotations, service.Annotations)
continue
}
foundServiceUpdate = true

}
}
}