61 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			61 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package main
 | |
| 
 | |
| import (
 | |
| 	"fmt"
 | |
| 	"io"
 | |
| 	"log"
 | |
| 	"os"
 | |
| )
 | |
| 
 | |
| type NetworkPolicyGenerrator struct {
 | |
| 	config          *Config
 | |
| 	policyTemplates *PolicyTemplates
 | |
| }
 | |
| 
 | |
| func (g NetworkPolicyGenerrator) GenerateNamespace(writer io.Writer, namespace *Namespace) error {
 | |
| 	fmt.Fprintf(os.Stderr, "Namespace %s\n", namespace.Name)
 | |
| 
 | |
| 	templates := g.policyTemplates.NamespaceTemplates("netpol", namespace.Capabilities)
 | |
| 	log.Printf("Got %d templates", len(templates))
 | |
| 
 | |
| 	for _, template := range templates {
 | |
| 		err := template.Execute(writer, &namespace)
 | |
| 		if err != nil {
 | |
| 			return fmt.Errorf("Error using template %s: %w", template.Name(), err)
 | |
| 		}
 | |
| 	}
 | |
| 	return nil
 | |
| }
 | |
| 
 | |
| func (g NetworkPolicyGenerrator) GenerateCommunicationRule(
 | |
| 	writer io.Writer,
 | |
| 	app *Application,
 | |
| 	ingress *Ingress,
 | |
| 	egress *Egress) error {
 | |
| 
 | |
| 	if len(ingress.Applications)+
 | |
| 		len(ingress.Networks)+
 | |
| 		len(egress.Applications)+
 | |
| 		len(egress.Networks) > 0 {
 | |
| 		// non-trivial regular network policy
 | |
| 
 | |
| 		tmpl := g.policyTemplates.ApplicationTemplate("netpol")
 | |
| 		log.Printf("Found template %v for pod %s", tmpl, app.Name)
 | |
| 		if tmpl != nil {
 | |
| 
 | |
| 			err := tmpl.Execute(writer, map[string]any{
 | |
| 				"app":     app,
 | |
| 				"ingress": ingress,
 | |
| 				"egress":  egress,
 | |
| 				"labels": map[string]string{
 | |
| 					"policy-generator": "1",
 | |
| 				},
 | |
| 			})
 | |
| 			if err != nil {
 | |
| 				return err
 | |
| 			}
 | |
| 		}
 | |
| 	}
 | |
| 	return nil
 | |
| }
 |