lib/piservices/initd.py
from StringIO import StringIO
import loader, color
class InitScript:
def __init__(self, service, script_name = None, remote_path=None):
self.service = service
self.remote_path = remote_path
self.script_name = script_name
if not self.script_name:
self.script_name = self.service.name
if not self.remote_path:
self.remote_path = '/etc/init.d'
self.target_init_script = self.remote_path+'/'+self.script_name
def start(self):
self.service.sudo('%s start' % self.target_init_script)
def stop(self):
self.service.sudo('%s stop' % self.target_init_script)
def restart(self):
self.service.sudo('%s restart' % self.target_init_script)
def enable_autostart(self):
self.service.sudo('update-rc.d %s defaults 98 02' % self.script_name)
def disable_autostart(self):
self.service.sudo('update-rc.d -f %s remove' % self.script_name)
def copy(self):
pass
def delete(self):
pass
class InitScriptWithTemplate(InitScript):
def __init__(self, service, local_script_path, script_name = None, remote_path=None, local_path=None):
InitScript.__init__(self, service, script_name, remote_path)
self.local_path = local_path
self.local_script_path = local_script_path
if not self.local_path:
self.local_path = self.service.local_path
if self.local_script_path.startswith('/'):
self.source_init_script = self.local_script_path
else:
self.source_init_script = self.local_path+'/'+self.local_script_path
def copy(self):
self.delete()
with open(self.source_init_script, 'r') as i:
content = self.with_init_script_content_do(i.read())
output = StringIO()
output.write(content)
with color.for_put():
print "\n>> writing init script: "+self.target_init_script+"\n"+('='*30)+"\n"+content+"\n\n"
self.service.put(output, self.target_init_script, use_sudo = True)
output.close()
self.service.sudo('chmod +x %s' % self.target_init_script)
def delete(self):
self.service.sudo('rm -f %s' % self.target_init_script)
def with_init_script_content_do(self, content):
if hasattr(self.service, 'with_init_script_content_do'):
content = self.service.with_init_script_content_do(content)
return content
class AutogeneratedInitScript(InitScriptWithTemplate):
default_init_script_template = loader.services_path+'/setup/src/service.sh.tpl'
def __init__(self, service, remote_path=None, init_script_template=None):
self.init_script_template = init_script_template
if not init_script_template:
self.init_script_template = self.default_init_script_template
InitScriptWithTemplate.__init__(self, service, self.init_script_template, remote_path)
def with_init_script_content_do(self, content):
content = InitScriptWithTemplate.with_init_script_content_do(self, content)
defaults = {
'name' : self.script_name,
'daemon' : '/usr/bin/python',
'command' : 'fab %s:start' % self.service.name,
'path' : self.service.remote_path
}
for key, value in defaults.iteritems():
if '%('+key+')s' in content:
content = content.replace('%('+key+')s', value)
return content