github.com/ethanhsieh/snapd@v0.0.0-20210615102523-3db9b8e4edc5/sandbox/cgroup/process.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2020 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 package cgroup 21 22 import ( 23 "fmt" 24 "path/filepath" 25 "strings" 26 ) 27 28 func snapNameFromPidUsingTrackingCgroup(pid int) (string, error) { 29 // Maybe we have application tracking and can use it? 30 path, err := ProcessPathInTrackingCgroup(pid) 31 if err != nil { 32 return "", err 33 } 34 if parsedTag := securityTagFromCgroupPath(path); parsedTag != nil { 35 return parsedTag.InstanceName(), nil 36 } 37 return "", fmt.Errorf("cannot find snap security tag") 38 } 39 40 func snapNameFromPidUsingFreezerCgroup(pid int) (string, error) { 41 // This logic only makes sense with cgroup v1. 42 if IsUnified() { 43 return "", fmt.Errorf("not supported") 44 } 45 46 // Find the path in the freezer cgroup. 47 group, err := ProcGroup(pid, MatchV1Controller("freezer")) 48 if err != nil { 49 return "", fmt.Errorf("cannot determine cgroup path of pid %v: %v", pid, err) 50 } 51 if !strings.HasPrefix(group, "/snap.") { 52 return "", fmt.Errorf("cannot find a snap for pid %v", pid) 53 } 54 55 // Extract the snap name form the path. 56 snapName := strings.SplitN(filepath.Base(group), ".", 2)[1] 57 if snapName == "" { 58 return "", fmt.Errorf("snap name in cgroup path is empty") 59 } 60 return snapName, nil 61 } 62 63 func SnapNameFromPid(pid int) (string, error) { 64 if snapName, err := snapNameFromPidUsingTrackingCgroup(pid); err == nil { 65 return snapName, nil 66 } 67 return snapNameFromPidUsingFreezerCgroup(pid) 68 }