1
0
Fork 0
mirror of https://github.com/vbatts/go-cgroup.git synced 2024-11-23 09:05:39 +00:00

Merge pull request #5 from dongsupark/fix-get-uid-gid

cg: fix a bug in GetUidGid() to call cgroup_get_uid_gid() correctly
This commit is contained in:
Vincent Batts 2017-05-07 09:02:06 -04:00 committed by GitHub
commit 1ab93081d9
2 changed files with 66 additions and 5 deletions

30
cg.go
View file

@ -13,6 +13,7 @@ import "C"
import (
"errors"
"runtime"
"strconv"
"unsafe"
)
@ -212,11 +213,11 @@ func (cg Cgroup) GetUIDGID() (tasksUID UID, tasksGID GID, controlUID UID, contro
cCU C.uid_t
cCG C.gid_t
)
err = _err(C.cgroup_set_uid_gid(cg.g,
cTU,
cTG,
cCU,
cCG))
err = _err(C.cgroup_get_uid_gid(cg.g,
&cTU,
&cTG,
&cCU,
&cCG))
return UID(cTU), GID(cTG), UID(cCU), GID(cCG), err
}
@ -561,3 +562,22 @@ func _err(num C.int) error {
// There's a lot. We'll create them as they come
return errors.New(C.GoString(C.cgroup_strerror(num)))
}
// simple helpers to get UID or GID from a given string
func stringToUID(uidStr string) UID {
intVal, err := strconv.Atoi(uidStr)
if err != nil {
return UID(0)
}
return UID(intVal)
}
func stringToGID(gidStr string) GID {
intVal, err := strconv.Atoi(gidStr)
if err != nil {
return GID(0)
}
return GID(intVal)
}

41
cg_test.go Normal file
View file

@ -0,0 +1,41 @@
package cgroup
import (
"os/user"
"testing"
)
func TestUidGid(t *testing.T) {
Init()
var wantTaskUid, wantCtrlUid UID
var wantTaskGid, wantCtrlGid GID
curUser, err := user.Current()
if err == nil {
wantTaskUid = stringToUID(curUser.Uid)
wantTaskGid = stringToGID(curUser.Gid)
wantCtrlUid = stringToUID(curUser.Uid)
wantCtrlGid = stringToGID(curUser.Gid)
} else {
t.Logf("cannot get the current user. fall back to 0.\n")
wantTaskUid, wantTaskGid, wantCtrlUid, wantCtrlGid = 0, 0, 0, 0
}
cg := NewCgroup("test_cgroup")
if err := cg.SetUIDGID(wantTaskUid, wantTaskGid, wantCtrlUid, wantCtrlGid); err != nil {
t.Fatalf("cannot set cgroup uids/gids: %v\n", err)
}
gotTaskUid, gotTaskGid, gotCtrlUid, gotCtrlGid, err := cg.GetUIDGID()
if err != nil {
t.Fatalf("cannot get cgroup uids/gids: %v\n", err)
}
if wantTaskUid != gotTaskUid || wantTaskGid != gotTaskGid ||
wantCtrlUid != gotCtrlUid || wantCtrlGid != gotCtrlGid {
t.Fatalf("wanted (%d,%d,%d,%d), got (%d,%d,%d,%d)\n",
wantTaskUid, wantTaskGid, wantCtrlUid, wantCtrlGid,
gotTaskUid, gotTaskGid, gotCtrlUid, gotCtrlGid)
}
}