github.com/inspektor-gadget/inspektor-gadget@v0.28.1/pkg/gadgets/top/top.go (about) 1 // Copyright 2022 The Inspektor Gadget authors 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 top 16 17 import ( 18 "fmt" 19 "time" 20 21 "github.com/inspektor-gadget/inspektor-gadget/pkg/columns" 22 columnssort "github.com/inspektor-gadget/inspektor-gadget/pkg/columns/sort" 23 ) 24 25 const ( 26 MaxRowsDefault = 20 27 IntervalDefault = 1 28 29 IntervalParam = "interval" 30 MaxRowsParam = "max_rows" 31 SortByParam = "sort_by" 32 ) 33 34 type Event[T any] struct { 35 Error string `json:"error,omitempty"` 36 Stats []*T `json:"stats,omitempty"` 37 } 38 39 func SortStats[T any](stats []*T, sortBy []string, colMap *columns.ColumnMap[T]) { 40 columnssort.SortEntries(*colMap, stats, sortBy) 41 } 42 43 // ComputeIterations returns the number of iterations to perform to get the 44 // desired timeout. It returns zero if timeout is zero. 45 func ComputeIterations(interval, timeout time.Duration) (int, error) { 46 if timeout <= 0 { 47 return 0, nil 48 } 49 if timeout < interval { 50 return 0, fmt.Errorf("timeout must be greater than interval") 51 } 52 if timeout%interval != 0 { 53 return 0, fmt.Errorf("timeout must be a multiple of interval") 54 } 55 return int(timeout / interval), nil 56 }