github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/cmd/container/top_windows.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package container 18 19 import ( 20 "context" 21 "fmt" 22 "io" 23 "os" 24 "strings" 25 "text/tabwriter" 26 "time" 27 28 "github.com/Microsoft/hcsshim/cmd/containerd-shim-runhcs-v1/options" 29 "github.com/containerd/containerd" 30 "github.com/containerd/typeurl/v2" 31 "github.com/docker/go-units" 32 ) 33 34 // containerTop was inspired from https://github.com/moby/moby/blob/master/daemon/top_windows.go 35 // 36 // ContainerTop lists the processes running inside of the given 37 // container. An error is returned if the container 38 // is not found, or is not running. 39 func containerTop(ctx context.Context, stdio io.Writer, client *containerd.Client, id string, psArgs string) error { 40 container, err := client.LoadContainer(ctx, id) 41 if err != nil { 42 return err 43 } 44 45 task, err := container.Task(ctx, nil) 46 if err != nil { 47 return err 48 } 49 processes, err := task.Pids(ctx) 50 if err != nil { 51 return err 52 } 53 procList := &ContainerTopOKBody{} 54 procList.Titles = []string{"Name", "PID", "CPU", "Private Working Set"} 55 56 for _, j := range processes { 57 var info options.ProcessDetails 58 err = typeurl.UnmarshalTo(j.Info, &info) 59 if err != nil { 60 return err 61 } 62 d := time.Duration((info.KernelTime_100Ns + info.UserTime_100Ns) * 100) // Combined time in nanoseconds 63 procList.Processes = append(procList.Processes, []string{ 64 info.ImageName, 65 fmt.Sprint(info.ProcessID), 66 fmt.Sprintf("%02d:%02d:%02d.%03d", int(d.Hours()), int(d.Minutes())%60, int(d.Seconds())%60, int(d.Nanoseconds()/1000000)%1000), 67 units.HumanSize(float64(info.MemoryWorkingSetPrivateBytes))}) 68 69 } 70 71 w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0) 72 fmt.Fprintln(w, strings.Join(procList.Titles, "\t")) 73 74 for _, proc := range procList.Processes { 75 fmt.Fprintln(w, strings.Join(proc, "\t")) 76 } 77 w.Flush() 78 79 return nil 80 }