1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/python

import getpass
import sys
import os
import getopt
import commands 
import time

__author__ = 	"Anuj Bhatt (anuj.bhatt@gmail.com)"
__date__   = 	"Nov 3 2008"


def printUsage():
	"""Prints usage info for red.py"""
	print """
red: A script that tries to emulate what ReadyBoost does (but not quite).

RUNNING
	#./red [-mrh]
OPTIONS
	m: make cache on attached device
	r: remove cache on attached device
	h: help (This message will be printed again)"""

def doPreprocessing():
	"""Preprocessing to get details from mount and df"""

	#Get the last mounted device name
	cmd_str_mount = "mount | tail -n1"
	ret_str = commands.getoutput(cmd_str_mount)
	temp_str = ret_str.split()
	#Device name is obtained here
	device_name = temp_str[2]


	#Get Avail space on device_name
	cmd_str_df = "df | tail -n1"	
	ret_avail = commands.getoutput(cmd_str_df)
	temp_str = ret_avail.split()
	#Avail space is obtained here
	avail_space = temp_str[3]
	
	return device_name, avail_space
	
def makeCache():
	"""Make cache on the attached device"""
	
	device_name, avail_space = doPreprocessing()
	print "Detected device", device_name, " with available space", avail_space
	option = raw_input("Proceed? (y/n)")

	if option == 'y':
		print "Creating swap space on", device_name
		t = device_name+"/swap"
		avail_space = int(avail_space)
		if avail_space > 1000:
			print "Too much space available, using 1000"
			avail_space = 1000
		avail_space = str(avail_space)
		cmd_str = "dd if=/dev/zero of="+t+" bs=1K count="+avail_space
		ret_val = os.system(cmd_str)
		time.sleep(4) #Give command some time
		ret_val = os.system("mkswap "+t+" "+avail_space)
		time.sleep(4)
		ret_val = os.system("swapon "+t)
		time.sleep(4)
		#print "Done creating cache/swap space ", t
		return t, avail_space, 1
	elif option == 'n':
		print "Not selected. Exiting."
		sys.exit(0)


def removeCache():
	"""Remove cache from attached device(s)"""
	device_name, avail_space = doPreprocessing()
	device_name = device_name+"/swap"
	print "Removing cache/swap space from ", device_name
	ret_val = os.system("swapoff "+device_name)
	time.sleep(4)
	ret_val = os.system("rm "+device_name)
	time.sleep(4)
	print "Done removing "+device_name
		

if __name__ == '__main__':
	if getpass.getuser() != 'root':
		print "Error (red.py): Need to be root to do this."
		sys.exit(0)
	optlist, lst = getopt.getopt(sys.argv[1:], 'mrh')
	for opt in optlist:
		if opt[0] == '-h':
			printUsage()
		if opt[0] == '-m':
			dev_swap_name, avail_space, flag = makeCache()
		if opt[0] == '-r':
			removeCache()