Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame^] | 1 | /* |
| 2 | Copyright 2014 The Kubernetes Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package admission |
| 18 | |
| 19 | // chainAdmissionHandler is an instance of admission.NamedHandler that performs admission control using |
| 20 | // a chain of admission handlers |
| 21 | type chainAdmissionHandler []Interface |
| 22 | |
| 23 | // NewChainHandler creates a new chain handler from an array of handlers. Used for testing. |
| 24 | func NewChainHandler(handlers ...Interface) chainAdmissionHandler { |
| 25 | return chainAdmissionHandler(handlers) |
| 26 | } |
| 27 | |
| 28 | // Admit performs an admission control check using a chain of handlers, and returns immediately on first error |
| 29 | func (admissionHandler chainAdmissionHandler) Admit(a Attributes) error { |
| 30 | for _, handler := range admissionHandler { |
| 31 | if !handler.Handles(a.GetOperation()) { |
| 32 | continue |
| 33 | } |
| 34 | if mutator, ok := handler.(MutationInterface); ok { |
| 35 | err := mutator.Admit(a) |
| 36 | if err != nil { |
| 37 | return err |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | return nil |
| 42 | } |
| 43 | |
| 44 | // Validate performs an admission control check using a chain of handlers, and returns immediately on first error |
| 45 | func (admissionHandler chainAdmissionHandler) Validate(a Attributes) error { |
| 46 | for _, handler := range admissionHandler { |
| 47 | if !handler.Handles(a.GetOperation()) { |
| 48 | continue |
| 49 | } |
| 50 | if validator, ok := handler.(ValidationInterface); ok { |
| 51 | err := validator.Validate(a) |
| 52 | if err != nil { |
| 53 | return err |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | return nil |
| 58 | } |
| 59 | |
| 60 | // Handles will return true if any of the handlers handles the given operation |
| 61 | func (admissionHandler chainAdmissionHandler) Handles(operation Operation) bool { |
| 62 | for _, handler := range admissionHandler { |
| 63 | if handler.Handles(operation) { |
| 64 | return true |
| 65 | } |
| 66 | } |
| 67 | return false |
| 68 | } |