github.com/zhyoulun/cilium@v1.6.12/pkg/policy/api/decision.go (about)

     1  // Copyright 2016-2017 Authors of Cilium
     2  //
     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  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package api
    16  
    17  import (
    18  	"fmt"
    19  )
    20  
    21  // Decision is a reachability policy decision
    22  type Decision byte
    23  
    24  const (
    25  	// Undecided means that we have not come to a decision yet
    26  	Undecided Decision = iota
    27  	// Allowed means that reachability is allowed
    28  	Allowed
    29  	// Denied means that reachability is denied
    30  	Denied
    31  )
    32  
    33  var (
    34  	decisionToString = map[Decision]string{
    35  		Undecided: "undecided",
    36  		Allowed:   "allowed",
    37  		Denied:    "denied",
    38  	}
    39  	stringToDecision = map[string]Decision{
    40  		"undecided": Undecided,
    41  		"allowed":   Allowed,
    42  		"denied":    Denied,
    43  	}
    44  )
    45  
    46  // String returns the decision in human readable format
    47  func (d Decision) String() string {
    48  	if v, exists := decisionToString[d]; exists {
    49  		return v
    50  	}
    51  	return ""
    52  }
    53  
    54  // UnmarshalJSON parses a JSON formatted buffer and returns a decision
    55  func (d *Decision) UnmarshalJSON(b []byte) error {
    56  	if d == nil {
    57  		d = new(Decision)
    58  	}
    59  	if len(b) <= len(`""`) {
    60  		return fmt.Errorf("invalid decision '%s'", string(b))
    61  	}
    62  	if v, exists := stringToDecision[string(b[1:len(b)-1])]; exists {
    63  		*d = v
    64  		return nil
    65  	}
    66  
    67  	return fmt.Errorf("unknown '%s' decision", string(b))
    68  }
    69  
    70  // MarshalJSON returns the decision as JSON formatted buffer
    71  func (d Decision) MarshalJSON() ([]byte, error) {
    72  	return []byte(fmt.Sprintf(`"%s"`, d)), nil
    73  }