Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 39551
1
#!/usr/bin/python
2
###############################################################################
3
#
4
# CoCalc: Collaborative Calculation in the Cloud
5
#
6
# Copyright (C) 2016, Sagemath Inc.
7
#
8
# This program is free software: you can redistribute it and/or modify
9
# it under the terms of the GNU General Public License as published by
10
# the Free Software Foundation, either version 3 of the License, or
11
# (at your option) any later version.
12
#
13
# This program is distributed in the hope that it will be useful,
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
# GNU General Public License for more details.
17
#
18
# You should have received a copy of the GNU General Public License
19
# along with this program. If not, see <http://www.gnu.org/licenses/>.
20
#
21
###############################################################################
22
23
24
25
import os, sys
26
from subprocess import Popen, PIPE
27
28
progname, username, memory_G, cpu_shares, cfs_quota = sys.argv
29
30
if not os.path.exists('/sys/fs/cgroup/memory'):
31
raise RuntimeError("cgroups not supported")
32
33
def cmd(s, ignore_errors=False):
34
print s
35
out = Popen(s, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
36
x = out.stdout.read() + out.stderr.read()
37
e = out.wait() # this must be *after* the out.stdout.read(), etc. above or will hang when output large!
38
if e:
39
if ignore_errors:
40
return (x + "ERROR").strip()
41
else:
42
raise RuntimeError(x)
43
return x.strip()
44
45
cmd("cgcreate -g memory,cpu:%s"%username)
46
open("/sys/fs/cgroup/memory/%s/memory.limit_in_bytes"%username,'w').write("%sG"%memory_G)
47
open("/sys/fs/cgroup/cpu/%s/cpu.shares"%username,'w').write(cpu_shares)
48
open("/sys/fs/cgroup/cpu/%s/cpu.cfs_quota_us"%username,'w').write(cfs_quota)
49
50
z = "\n%s cpu,memory %s\n"%(username, username)
51
cur = open("/etc/cgrules.conf").read()
52
53
if z not in cur:
54
open("/etc/cgrules.conf",'a').write(z)
55
cmd('service cgred restart')
56
57
try:
58
pids = cmd("ps -o pid -u %s"%username, ignore_errors=False).split()[1:]
59
except RuntimeError:
60
# ps returns an error code if there are NO processes at all (a common condition).
61
pids = []
62
if pids:
63
cmd("cgclassify %s"%(' '.join(pids)), ignore_errors=True)
64
# ignore cgclassify errors, since processes come and go, etc.
65
66
67
68