|
| 1 | +/* |
| 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 | + |
| 16 | +package kubectl |
| 17 | + |
| 18 | +import ( |
| 19 | + "bytes" |
| 20 | + "fmt" |
| 21 | + "os" |
| 22 | + "sort" |
| 23 | + "strings" |
| 24 | + "time" |
| 25 | + |
| 26 | + "github.com/liggitt/tabwriter" |
| 27 | + "github.com/spf13/cobra" |
| 28 | + v1 "k8s.io/api/core/v1" |
| 29 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 30 | + "k8s.io/apimachinery/pkg/runtime" |
| 31 | + "k8s.io/apimachinery/pkg/runtime/schema" |
| 32 | + "k8s.io/apimachinery/pkg/util/duration" |
| 33 | + "k8s.io/cli-runtime/pkg/printers" |
| 34 | + k8sprinters "k8s.io/kubernetes/pkg/printers" |
| 35 | + api "sigs.k8s.io/hierarchical-namespaces/api/v1alpha2" |
| 36 | +) |
| 37 | + |
| 38 | +const ( |
| 39 | + tabwriterMinWidth = 6 |
| 40 | + tabwriterWidth = 4 |
| 41 | + tabwriterPadding = 3 |
| 42 | + tabwriterPadChar = ' ' |
| 43 | + tabwriterFlags = tabwriter.RememberWidths |
| 44 | +) |
| 45 | + |
| 46 | +var namespace string |
| 47 | + |
| 48 | +// Define HierarchicalResourceQuota Table Column |
| 49 | +var hierarchicalResourceQuotaColumnDefinitions = []metav1.TableColumnDefinition{ |
| 50 | + {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, |
| 51 | + {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, |
| 52 | + {Name: "Request", Type: "string", Description: "Request represents a minimum amount of cpu/memory that a container may consume."}, |
| 53 | + {Name: "Limit", Type: "string", Description: "Limits control the maximum amount of cpu/memory that a container may use independent of contention on the node."}, |
| 54 | +} |
| 55 | + |
| 56 | +var hrqCmd = &cobra.Command{ |
| 57 | + Use: "hrq [NAME]", |
| 58 | + Short: "Display one or more HierarchicalResourceQuota", |
| 59 | + Run: Run, |
| 60 | +} |
| 61 | + |
| 62 | +func Run(cmd *cobra.Command, args []string) { |
| 63 | + flags := cmd.Flags() |
| 64 | + table := &metav1.Table{ColumnDefinitions: hierarchicalResourceQuotaColumnDefinitions} |
| 65 | + |
| 66 | + option := k8sprinters.GenerateOptions{ |
| 67 | + NoHeaders: true, |
| 68 | + Wide: true, |
| 69 | + } |
| 70 | + |
| 71 | + showLabels := flags.Changed("show-labels") |
| 72 | + |
| 73 | + allResourcesNamespaced := !flags.Changed("all-namespaces") |
| 74 | + if !allResourcesNamespaced { |
| 75 | + namespace = "" |
| 76 | + } |
| 77 | + |
| 78 | + // Get HierarchicalResourceQuotaList from the specified namespace |
| 79 | + hrqList := client.getHRQ(args, namespace) |
| 80 | + |
| 81 | + if len(hrqList.Items) < 1 { |
| 82 | + if allResourcesNamespaced { |
| 83 | + fmt.Printf("No resources found in %s namespace.\n", namespace) |
| 84 | + os.Exit(1) |
| 85 | + } else { |
| 86 | + fmt.Println("No resources found") |
| 87 | + os.Exit(1) |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + // Create []metav1.TableRow from HierarchicalResourceQuotaList |
| 92 | + tableRaws, err := printHierarchicalResourceQuotaList(hrqList, option) |
| 93 | + if err != nil { |
| 94 | + fmt.Printf("Error reading hierarchicalresourcequotas: %s\n", err) |
| 95 | + } |
| 96 | + table.Rows = tableRaws |
| 97 | + |
| 98 | + // Create writer |
| 99 | + w := tabwriter.NewWriter(os.Stdout, tabwriterMinWidth, tabwriterWidth, tabwriterPadding, tabwriterPadChar, tabwriterFlags) |
| 100 | + |
| 101 | + // Create TablePrinter |
| 102 | + p := printers.NewTablePrinter(printers.PrintOptions{ |
| 103 | + NoHeaders: false, |
| 104 | + WithNamespace: !allResourcesNamespaced, |
| 105 | + WithKind: true, |
| 106 | + Wide: true, |
| 107 | + ShowLabels: showLabels, |
| 108 | + Kind: schema.GroupKind{}, |
| 109 | + ColumnLabels: nil, |
| 110 | + SortBy: "", |
| 111 | + AllowMissingKeys: false, |
| 112 | + }) |
| 113 | + |
| 114 | + p.PrintObj(table, w) |
| 115 | + |
| 116 | + w.Flush() |
| 117 | +} |
| 118 | + |
| 119 | +func printHierarchicalResourceQuota(hierarchicalResourceQuota *api.HierarchicalResourceQuota, options k8sprinters.GenerateOptions) ([]metav1.TableRow, error) { |
| 120 | + row := metav1.TableRow{ |
| 121 | + Object: runtime.RawExtension{Object: hierarchicalResourceQuota}, |
| 122 | + } |
| 123 | + |
| 124 | + resources := make([]v1.ResourceName, 0, len(hierarchicalResourceQuota.Status.Hard)) |
| 125 | + for resource := range hierarchicalResourceQuota.Status.Hard { |
| 126 | + resources = append(resources, resource) |
| 127 | + } |
| 128 | + sort.Sort(SortableResourceNames(resources)) |
| 129 | + |
| 130 | + requestColumn := bytes.NewBuffer([]byte{}) |
| 131 | + limitColumn := bytes.NewBuffer([]byte{}) |
| 132 | + for i := range resources { |
| 133 | + w := requestColumn |
| 134 | + resource := resources[i] |
| 135 | + usedQuantity := hierarchicalResourceQuota.Status.Used[resource] |
| 136 | + hardQuantity := hierarchicalResourceQuota.Status.Hard[resource] |
| 137 | + |
| 138 | + // use limitColumn writer if a resource name prefixed with "limits" is found |
| 139 | + if pieces := strings.Split(resource.String(), "."); len(pieces) > 1 && pieces[0] == "limits" { |
| 140 | + w = limitColumn |
| 141 | + } |
| 142 | + |
| 143 | + fmt.Fprintf(w, "%s: %s/%s, ", resource, usedQuantity.String(), hardQuantity.String()) |
| 144 | + } |
| 145 | + |
| 146 | + age := translateTimestampSince(hierarchicalResourceQuota.CreationTimestamp) |
| 147 | + row.Cells = append(row.Cells, hierarchicalResourceQuota.Name, age, strings.TrimSuffix(requestColumn.String(), ", "), strings.TrimSuffix(limitColumn.String(), ", ")) |
| 148 | + return []metav1.TableRow{row}, nil |
| 149 | +} |
| 150 | + |
| 151 | +func printHierarchicalResourceQuotaList(list *api.HierarchicalResourceQuotaList, options k8sprinters.GenerateOptions) ([]metav1.TableRow, error) { |
| 152 | + rows := make([]metav1.TableRow, 0, len(list.Items)) |
| 153 | + for i := range list.Items { |
| 154 | + r, err := printHierarchicalResourceQuota(&list.Items[i], options) |
| 155 | + if err != nil { |
| 156 | + return nil, err |
| 157 | + } |
| 158 | + rows = append(rows, r...) |
| 159 | + } |
| 160 | + return rows, nil |
| 161 | +} |
| 162 | + |
| 163 | +// translateTimestampSince returns the elapsed time since timestamp in |
| 164 | +// human-readable approximation. |
| 165 | +func translateTimestampSince(timestamp metav1.Time) string { |
| 166 | + if timestamp.IsZero() { |
| 167 | + return "<unknown>" |
| 168 | + } |
| 169 | + |
| 170 | + return duration.HumanDuration(time.Since(timestamp.Time)) |
| 171 | +} |
| 172 | + |
| 173 | +// SortableResourceNames - An array of sortable resource names |
| 174 | +type SortableResourceNames []v1.ResourceName |
| 175 | + |
| 176 | +func (list SortableResourceNames) Len() int { |
| 177 | + return len(list) |
| 178 | +} |
| 179 | + |
| 180 | +func (list SortableResourceNames) Swap(i, j int) { |
| 181 | + list[i], list[j] = list[j], list[i] |
| 182 | +} |
| 183 | + |
| 184 | +func (list SortableResourceNames) Less(i, j int) bool { |
| 185 | + return list[i] < list[j] |
| 186 | +} |
| 187 | + |
| 188 | +func newHrqCmd() *cobra.Command { |
| 189 | + hrqCmd.Flags().StringVarP(&namespace, "namespace", "n", v1.NamespaceDefault, "If present, the namespace scope for this CLI request") |
| 190 | + |
| 191 | + hrqCmd.Flags().BoolP("all-namespaces", "A", false, "Displays all HierarchicalResourceQuota on the cluster") |
| 192 | + hrqCmd.Flags().BoolP("show-labels", "", false, "Displays Labels of HierarchicalResourceQuota") |
| 193 | + return hrqCmd |
| 194 | +} |
0 commit comments