github.com/bugraaydogar/snapd@v0.0.0-20210315170335-8c70bb858939/sandbox/cgroup/process_test.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_test 21 22 import ( 23 "io/ioutil" 24 "os" 25 "path/filepath" 26 27 . "gopkg.in/check.v1" 28 29 "github.com/snapcore/snapd/sandbox/cgroup" 30 ) 31 32 func (s *cgroupSuite) mockPidCgroup(c *C, text string) int { 33 f := filepath.Join(s.rootDir, "proc/333/cgroup") 34 c.Assert(os.MkdirAll(filepath.Dir(f), 0755), IsNil) 35 c.Assert(ioutil.WriteFile(f, []byte(text), 0755), IsNil) 36 return 333 37 } 38 39 func (s *cgroupSuite) TestV1SnapNameFromPidHappy(c *C) { 40 restore := cgroup.MockVersion(cgroup.V1, nil) 41 defer restore() 42 pid := s.mockPidCgroup(c, string(mockCgroup)) // defined in cgroup_test.go 43 name, err := cgroup.SnapNameFromPid(pid) 44 c.Assert(err, IsNil) 45 c.Check(name, Equals, "hello-world") 46 } 47 48 func (s *cgroupSuite) TestV1SnapNameFromPidUnhappy(c *C) { 49 restore := cgroup.MockVersion(cgroup.V1, nil) 50 defer restore() 51 pid := s.mockPidCgroup(c, "1:freezer:/\n") 52 name, err := cgroup.SnapNameFromPid(pid) 53 c.Assert(err, ErrorMatches, "cannot find a snap for pid .*") 54 c.Check(name, Equals, "") 55 } 56 57 func (s *cgroupSuite) TestV1SnapNameFromPidEmptyName(c *C) { 58 restore := cgroup.MockVersion(cgroup.V1, nil) 59 defer restore() 60 pid := s.mockPidCgroup(c, "1:freezer:/snap./\n") 61 name, err := cgroup.SnapNameFromPid(pid) 62 c.Assert(err, ErrorMatches, "snap name in cgroup path is empty") 63 c.Check(name, Equals, "") 64 } 65 66 func (s *cgroupSuite) TestSnapNameFromPidTracking(c *C) { 67 pid := s.mockPidCgroup(c, "1:name=systemd:/user.slice/user-1000.slice/user@1000.service/apps.slice/snap.foo.bar.00000-1111-3333.service\n") 68 name, err := cgroup.SnapNameFromPid(pid) 69 c.Assert(err, IsNil) 70 c.Check(name, Equals, "foo") 71 } 72 73 func (s *cgroupSuite) TestSnapNameFromPidWithoutSources(c *C) { 74 restore := cgroup.MockVersion(cgroup.V2, nil) 75 defer restore() 76 77 pid := s.mockPidCgroup(c, "") 78 name, err := cgroup.SnapNameFromPid(pid) 79 c.Assert(err, ErrorMatches, "not supported") 80 c.Check(name, Equals, "") 81 }