github.com/fafucoder/cilium@v1.6.11/cilium/cmd/policy_import.go (about) 1 // Copyright 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 cmd 16 17 import ( 18 "encoding/json" 19 "fmt" 20 "os" 21 22 "github.com/cilium/cilium/pkg/command" 23 "github.com/cilium/cilium/pkg/logging/logfields" 24 "github.com/spf13/cobra" 25 ) 26 27 var printPolicy bool 28 29 // policyImportCmd represents the policy_import command 30 var policyImportCmd = &cobra.Command{ 31 Use: "import <path>", 32 Short: "Import security policy in JSON format", 33 Example: ` cilium policy import ~/policy.json 34 cilium policy import ./policies/app/`, 35 PreRun: requirePath, 36 Run: func(cmd *cobra.Command, args []string) { 37 path := args[0] 38 if ruleList, err := loadPolicy(path); err != nil { 39 Fatalf("Cannot parse policy %s: %s\n", path, err) 40 } else { 41 log.WithField("rule", logfields.Repr(ruleList)).Debug("Constructed policy object for import") 42 43 // Ignore request if no policies have been found 44 if len(ruleList) == 0 { 45 fmt.Printf("No policy specified") 46 return 47 } 48 49 for _, r := range ruleList { 50 if err := r.Sanitize(); err != nil { 51 Fatalf("%s", err) 52 } 53 } 54 55 jsonPolicy, err := json.MarshalIndent(ruleList, "", " ") 56 if err != nil { 57 Fatalf("Cannot marshal policy: %s\n", err) 58 } 59 if resp, err := client.PolicyPut(string(jsonPolicy)); err != nil { 60 Fatalf("Cannot import policy: %s\n", err) 61 } else if command.OutputJSON() { 62 if err := command.PrintOutput(resp); err != nil { 63 os.Exit(1) 64 } 65 } else if printPolicy { 66 fmt.Printf("%s\nRevision: %d\n", resp.Policy, resp.Revision) 67 } else { 68 fmt.Printf("Revision: %d\n", resp.Revision) 69 } 70 } 71 }, 72 } 73 74 func init() { 75 policyCmd.AddCommand(policyImportCmd) 76 policyImportCmd.Flags().BoolVarP(&printPolicy, "print", "", false, "Print policy after import") 77 command.AddJSONOutput(policyImportCmd) 78 }