catalog/INDEX010064400000000000003000000015121132355652200131220ustar00rootsys00000000000000distribution layout_version 1.0 data_model_revision 2.40 uuid 59bacec8-00eb-11df-a40a-001b787c239a mod_time 1263459666 create_time 1263459666 category tag system_management path_max 255 name_max 100 media sequence_number 1 product tag opensvc data_model_revision 2.40 instance_id 1 control_directory opensvc revision 100114.0939 title "opensvc" description "tools to drive OpenSVC services" mod_time 1263459666 create_time 1263459666 architecture HP-UX_10.20_700/800 machine_type * os_name HP-UX os_release * category_tag system_management directory / all_filesets commands is_locatable false copyright "Opensvc SARL" number 1.0 fileset tag commands data_model_revision 2.40 instance_id 1 control_directory commands size 281690 revision 1.0 title "Commands (management utilities)" mod_time 1263459666 create_time 1263459666 state available catalog/dfiles/INDEX010064400000000000003000000003401132355652200143660ustar00rootsys00000000000000distribution layout_version 1.0 data_model_revision 2.40 uuid 59bacec8-00eb-11df-a40a-001b787c239a mod_time 1263459666 create_time 1263459666 category tag system_management path_max 255 name_max 100 media sequence_number 1 catalog/dfiles/INFO010064400000000000003000000002121132355652200142500ustar00rootsys00000000000000control_file path INDEX size 224 mode 0444 mtime 1263459666 tag INDEX control_file path INFO size 198 mode 0444 mtime 1263459666 tag INFO catalog/opensvc/pfiles/INDEX010044400000000000003000000006271132355652200160650ustar00rootsys00000000000000product tag opensvc data_model_revision 2.40 instance_id 1 control_directory opensvc revision 100114.0939 title "opensvc" description "tools to drive OpenSVC services" mod_time 1263459666 create_time 1263459666 architecture HP-UX_10.20_700/800 machine_type * os_name HP-UX os_release * category_tag system_management directory / all_filesets commands is_locatable false copyright "Opensvc SARL" number 1.0 catalog/opensvc/pfiles/INFO010044400000000000003000000002121132355652200157370ustar00rootsys00000000000000control_file path INDEX size 407 mode 0444 mtime 1263459666 tag INDEX control_file path INFO size 198 mode 0444 mtime 1263459666 tag INFO catalog/opensvc/commands/INDEX010044400000000000003000000003231132355652200163750ustar00rootsys00000000000000fileset tag commands data_model_revision 2.40 instance_id 1 control_directory commands size 281690 revision 1.0 title "Commands (management utilities)" mod_time 1263459666 create_time 1263459666 state available catalog/opensvc/commands/INFO010044400000000000003000000302231132355652200162630ustar00rootsys00000000000000control_file path INDEX size 211 mode 0444 mtime 1263459666 tag INDEX control_file path INFO size 12493 mode 0444 mtime 1263459666 tag INFO control_file path postinstall size 5276 cksum 387062635 mode 0544 mtime 1263307862 tag postinstall file path /service type s size 17 mode 0755 uid 0 gid 0 owner root group root mtime 1263283036 link_source usr/local/opensvc file path /usr/local/opensvc/bin type d mode 0755 uid 0 gid 0 owner root group root file path /usr/local/opensvc/bin/alldownservices type s size 6 mode 0777 uid 0 gid 0 owner root group root mtime 1263459666 link_source svcmgr file path /usr/local/opensvc/bin/allprimaryservices type s size 6 mode 0777 uid 0 gid 0 owner root group root mtime 1263459666 link_source svcmgr file path /usr/local/opensvc/bin/allservices type s size 6 mode 0777 uid 0 gid 0 owner root group root mtime 1263459666 link_source svcmgr file path /usr/local/opensvc/bin/allupservices type s size 6 mode 0777 uid 0 gid 0 owner root group root mtime 1263459666 link_source svcmgr file path /usr/local/opensvc/bin/cron type d mode 0755 uid 0 gid 0 owner root group root file path /usr/local/opensvc/bin/cron/opensvc.daily type f size 5054 cksum 801976024 mode 0755 uid 0 gid 0 owner root group root mtime 1262877987 file path /usr/local/opensvc/bin/freezer type f size 1356 cksum 2571278973 mode 0755 uid 0 gid 0 owner root group root mtime 1262696723 file path /usr/local/opensvc/bin/opensvc.init.debian type f size 479 cksum 4293862185 mode 0755 uid 0 gid 0 owner root group root mtime 1262696723 file path /usr/local/opensvc/bin/opensvc.init.hpux type f size 686 cksum 1125838432 mode 0755 uid 0 gid 0 owner root group root mtime 1262796824 file path /usr/local/opensvc/bin/opensvc.init.redhat type f size 494 cksum 1341265086 mode 0755 uid 0 gid 0 owner root group root mtime 1262696723 file path /usr/local/opensvc/bin/postinstall type f size 5276 cksum 387062635 mode 0755 uid 0 gid 0 owner root group root mtime 1263307862 file path /usr/local/opensvc/bin/rcService type f size 1170 cksum 3096677711 mode 0755 uid 0 gid 0 owner root group root mtime 1262877987 file path /usr/local/opensvc/bin/svcfreeze type f size 1356 cksum 2571278973 mode 0755 uid 0 gid 0 owner root group root mtime 1262696723 file path /usr/local/opensvc/bin/svcfrozen type f size 1356 cksum 2571278973 mode 0755 uid 0 gid 0 owner root group root mtime 1262696723 file path /usr/local/opensvc/bin/svcmgr type f size 3384 cksum 610744344 mode 0755 uid 0 gid 0 owner root group root mtime 1262877987 file path /usr/local/opensvc/bin/svcmon type f size 3621 cksum 547019151 mode 0755 uid 0 gid 0 owner root group root mtime 1263458243 file path /usr/local/opensvc/bin/svcthaw type f size 1356 cksum 2571278973 mode 0755 uid 0 gid 0 owner root group root mtime 1262696723 file path /usr/local/opensvc/etc type d mode 0755 uid 0 gid 0 owner root group root file path /usr/local/opensvc/lib type d mode 0755 uid 0 gid 0 owner root group root file path /usr/local/opensvc/lib/freezer.py type f size 1780 cksum 2874905098 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/hostidHP-UX.py type f size 1203 cksum 2005687952 mode 0644 uid 0 gid 0 owner root group root mtime 1263377372 file path /usr/local/opensvc/lib/hostidLinux.py type f size 888 cksum 3030136168 mode 0644 uid 0 gid 0 owner root group root mtime 1263373384 file path /usr/local/opensvc/lib/hostidSunOS.py type f size 888 cksum 3030136168 mode 0644 uid 0 gid 0 owner root group root mtime 1263373386 file path /usr/local/opensvc/lib/lock.py type f size 1373 cksum 2086267765 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/loopSunOS.py type f size 1369 cksum 1753998603 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/lxc.py type f size 4292 cksum 4085623781 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/node.py type f size 2849 cksum 4027553960 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcAddService.py type f size 911 cksum 675864475 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcDiskInfoHP-UX.py type f size 2090 cksum 1631503765 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcDiskInfoLinux.py type f size 2533 cksum 3185469613 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcDiskInfoSunOS.py type f size 1062 cksum 1932564862 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcExceptions.py type f size 2376 cksum 835784503 mode 0644 uid 0 gid 0 owner root group root mtime 1263307862 file path /usr/local/opensvc/lib/rcGlobalEnv.py type f size 4109 cksum 2588931037 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcIfconfig.py type f size 5653 cksum 408206328 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcIfconfigHP-UX.py type f size 2854 cksum 3254693045 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcIfconfigLinux.py type f size 2726 cksum 2961858524 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcIfconfigLinuxlxc.py type f size 1106 cksum 556208950 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcIfconfigSunOS.py type f size 2324 cksum 2724389700 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcLogger.py type f size 1629 cksum 3536090519 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcMounts.py type f size 1938 cksum 3513484438 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcMountsHP-UX.py type f size 2220 cksum 3757210279 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcMountsLinux.py type f size 2271 cksum 3034587613 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcMountsSunOS.py type f size 1892 cksum 442840942 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcNode.py type f size 2086 cksum 237323880 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcOptParser.py type f size 3720 cksum 1304781393 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcStatus.py type f size 3043 cksum 3056146340 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/rcUtilities.py type f size 3169 cksum 418800661 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/resApp.py type f size 2616 cksum 2360883663 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/resDg.py type f size 3066 cksum 3151247316 mode 0644 uid 0 gid 0 owner root group root mtime 1263307862 file path /usr/local/opensvc/lib/resIp.py type f size 5495 cksum 2351273327 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/resIpHP-UX.py type f size 1568 cksum 1383763410 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/resIpLinux.py type f size 1580 cksum 2662347645 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/resIpLinuxLxc.py type f size 2027 cksum 365569638 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/resIpSunOS.py type f size 1627 cksum 4153137718 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/resLoop.py type f size 1552 cksum 2401641678 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/resLoopLinux.py type f size 2403 cksum 531216554 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/resMount.py type f size 2406 cksum 515996708 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/resMountHP-UX.py type f size 3486 cksum 322274318 mode 0644 uid 0 gid 0 owner root group root mtime 1263294006 file path /usr/local/opensvc/lib/resMountLinux.py type f size 3443 cksum 2794667473 mode 0644 uid 0 gid 0 owner root group root mtime 1263294007 file path /usr/local/opensvc/lib/resMountSunOS.py type f size 3206 cksum 553993981 mode 0644 uid 0 gid 0 owner root group root mtime 1263294007 file path /usr/local/opensvc/lib/resRsync.py type f size 9117 cksum 1359727842 mode 0644 uid 0 gid 0 owner root group root mtime 1263294007 file path /usr/local/opensvc/lib/resVgHP-UX.py type f size 5431 cksum 141248170 mode 0644 uid 0 gid 0 owner root group root mtime 1263294007 file path /usr/local/opensvc/lib/resVgHP-VM.py type f size 2103 cksum 1936825810 mode 0644 uid 0 gid 0 owner root group root mtime 1263454276 file path /usr/local/opensvc/lib/resVgLinux.py type f size 4660 cksum 2758167618 mode 0644 uid 0 gid 0 owner root group root mtime 1263294007 file path /usr/local/opensvc/lib/resZfs.py type f size 4873 cksum 199094662 mode 0644 uid 0 gid 0 owner root group root mtime 1263294007 file path /usr/local/opensvc/lib/resources.py type f size 6523 cksum 483361336 mode 0644 uid 0 gid 0 owner root group root mtime 1263294007 file path /usr/local/opensvc/lib/scsiReserv.py type f size 5473 cksum 2079395097 mode 0644 uid 0 gid 0 owner root group root mtime 1263373702 file path /usr/local/opensvc/lib/scsiReservHP-UX.py type f size 5365 cksum 2168130079 mode 0644 uid 0 gid 0 owner root group root mtime 1263394582 file path /usr/local/opensvc/lib/scsiReservLinux.py type f size 4636 cksum 2067245317 mode 0644 uid 0 gid 0 owner root group root mtime 1263312613 file path /usr/local/opensvc/lib/scsiReservSunOS.py type s size 18 mode 0777 uid 0 gid 0 owner root group root mtime 1263459666 link_source scsiReservLinux.py file path /usr/local/opensvc/lib/snapLvmLinux.py type f size 5476 cksum 1612800734 mode 0644 uid 0 gid 0 owner root group root mtime 1263294007 file path /usr/local/opensvc/lib/snapVxfsHP-UX.py type f size 5730 cksum 436910129 mode 0644 uid 0 gid 0 owner root group root mtime 1263294007 file path /usr/local/opensvc/lib/svc.py type f size 8203 cksum 3485463478 mode 0644 uid 0 gid 0 owner root group root mtime 1263294007 file path /usr/local/opensvc/lib/svcBuilder.py type f size 17550 cksum 207656938 mode 0644 uid 0 gid 0 owner root group root mtime 1263401239 file path /usr/local/opensvc/lib/svcHosted.py type f size 4463 cksum 1454976027 mode 0644 uid 0 gid 0 owner root group root mtime 1263294007 file path /usr/local/opensvc/lib/svcLxc.py type f size 3778 cksum 2632345058 mode 0644 uid 0 gid 0 owner root group root mtime 1263294007 file path /usr/local/opensvc/lib/svcZone.py type f size 3408 cksum 3886109119 mode 0644 uid 0 gid 0 owner root group root mtime 1263294007 file path /usr/local/opensvc/lib/xmlrpcClient.py type f size 5356 cksum 891156032 mode 0644 uid 0 gid 0 owner root group root mtime 1263457741 file path /usr/local/opensvc/log type d mode 0755 uid 0 gid 0 owner root group root file path /usr/local/opensvc/tmp type d mode 0755 uid 0 gid 0 owner root group root file path /usr/local/opensvc/usr type d mode 0755 uid 0 gid 0 owner root group root file path /usr/local/opensvc/usr/share type d mode 0755 uid 0 gid 0 owner root group root file path /usr/local/opensvc/usr/share/AUTHORS type f size 48 cksum 2477284957 mode 0644 uid 0 gid 0 owner root group root mtime 1262696723 file path /usr/local/opensvc/usr/share/BANNER type f size 822 cksum 2410265059 mode 0644 uid 0 gid 0 owner root group root mtime 1262696723 file path /usr/local/opensvc/usr/share/COPYING type f size 26436 cksum 3680632528 mode 0644 uid 0 gid 0 owner root group root mtime 1262696723 file path /usr/local/opensvc/usr/share/doc type d mode 0755 uid 0 gid 0 owner root group root file path /usr/local/opensvc/usr/share/doc/template.env type f size 9783 cksum 2914232941 mode 0644 uid 0 gid 0 owner root group root mtime 1263135642 file path /usr/local/opensvc/var type d mode 0755 uid 0 gid 0 owner root group root catalog/opensvc/commands/postinstall010054400017500001750000000122341132310612600164620ustar0000000000000000#!/usr/bin/env python2.6 import os import shutil from subprocess import * def install_cron(): """install opensvc cron jobs """ ce = [{ 'sched': "0,10,20,30,40,50 * * * *", 'user': "", 'cmd': "[ -x /usr/local/opensvc/bin/svcmon ] && /usr/local/opensvc/bin/svcmon --updatedb >/dev/null 2>&1" },{ 'sched': "0 4 * * *", 'user': "", 'cmd': "[ -x /usr/local/opensvc/bin/cron/opensvc.daily ] && /usr/local/opensvc/bin/cron/opensvc.daily >/dev/null 2>&1" }] purge = [] root_crontab = False """ order of preference """ root_crontab_locs = [ '/etc/cron.d/opensvc', '/var/spool/cron/crontabs/root', '/var/spool/cron/root', ] for loc in root_crontab_locs: if os.path.exists(os.path.dirname(loc)): if not root_crontab: root_crontab = loc if root_crontab == '/etc/cron.d/opensvc': ce[0]['user'] = "root" ce[1]['user'] = "root" elif os.path.exists(loc): purge.append(loc) if not root_crontab: print "no root crontab found in usual locations %s"%str(root_crontab_locs) return False cron_entry_1 = ' '.join([ce[0]['sched'], ce[0]['user'], ce[0]['cmd']]) cron_entry_2 = ' '.join([ce[1]['sched'], ce[1]['user'], ce[1]['cmd']]) new = False if os.path.exists(root_crontab): with open(root_crontab, 'r') as f: svcmon_present = False dailycron_present = False new = f.readlines() for line in new: if 'opensvc.daily' in line: dailycron_present = True if 'svcmon --updatedb' in line: svcmon_present = True if not svcmon_present: new.append(cron_entry_1+'\n') if not dailycron_present: new.append(cron_entry_2+'\n') else: new = [] new.append(cron_entry_1+'\n') new.append(cron_entry_2+'\n') if not new: print "problem preparing the new crontab" return False with open(root_crontab, 'w') as f: f.write(''.join(new)) """ Activate changes (actually only needed on HP-UX) """ cmd = ['crontab', root_crontab] process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() for loc in purge: with open(loc, 'r') as f: new = [ line for line in f.readlines() if not 'opensvc.daily' in line and not 'svcmon --updatedb' in line ] with open(loc, 'w') as f: f.write(''.join(new)) """ Clean up old standard file locations """ for f in ['/etc/cron.daily/opensvc', '/etc/cron.daily/opensvc.daily']: if os.path.exists(f): os.unlink(f) def activate_redhat(): cmd = ['chkconfig', '--add', 'opensvc'] process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() if process.returncode > 0: print buff[1] return False return True def activate_debian(): cmd = ['update-rc.d', '-f', 'opensvc', 'remove'] process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() if process.returncode > 0: print buff[1] return False cmd = ['update-rc.d', 'opensvc', 'defaults'] process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() if process.returncode > 0: print buff[1] return False return True def activate_hpux(): rc = "/sbin/init.d/opensvc" links = ["/sbin/rc1.d/K010opensvc", "/sbin/rc2.d/S990opensvc"] for l in links: if not os.path.islink(l): if os.path.exists(l): os.unlink(l) os.symlink(rc, l) with open("/etc/rc.config.d/opensvc", "w") as f: f.write("RUN_OPENSVC=1\n") f.close() return True def install_rc(): """install startup script """ sysname, nodename, x, x, machine = os.uname() if os.path.exists('/etc/debian_version'): rc = '/etc/init.d/opensvc' src = '/usr/local/opensvc/bin/opensvc.init.debian' activate = activate_debian elif os.path.exists('/etc/redhat-release'): rc = '/etc/init.d/opensvc' src = '/usr/local/opensvc/bin/opensvc.init.redhat' activate = activate_redhat elif sysname == "HP-UX": rc = '/sbin/init.d/opensvc' src = '/usr/local/opensvc/bin/opensvc.init.hpux' activate = activate_hpux else: print "could not select an init script: unsupported operating system" return False if os.path.islink(rc): os.unlink(rc) shutil.copyfile(src, rc) os.chmod(rc, 0755) activate() def gen_keys(): home = os.environ['HOME'] priv = os.path.join(home, ".ssh", "id_dsa") pub = os.path.join(home, ".ssh", "id_dsa.pub") if os.path.exists(pub) or os.path.exists(priv): return cmd = ['ssh-keygen', '-t', 'dsa', '-b', '1024', '-P', '', '-f', priv] process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() install_cron() install_rc() gen_keys() opensvc/commands/usr/local/opensvc/bin/004075500000000000000000000000003777777777700205405ustar00rootroot00000000000000opensvc/commands/usr/local/opensvc/bin/cron/004075500000000000000000000000003777777777700215015ustar00rootroot00000000000000opensvc/commands/usr/local/opensvc/bin/cron/opensvc.daily010075500000000000000000000116761132137644300241470ustar00rootroot00000000000000#!/usr/bin/env python2.6 # # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import sys import os import xmlrpclib import uuid """ When installed in /etc/cron.daily/ this must be a symlink to the file in the opensvc distrib, wherever installed, so that we can compute relative paths to locate libs """ pathsvc = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..')) pathlib = os.path.join(pathsvc, 'lib') sys.path.append(pathlib) hostid = str(uuid.getnode()) sysname, x, x, x, x = os.uname() import svcBuilder from rcGlobalEnv import rcEnv from rcUtilities import call, which di = __import__('rcDiskInfo'+sysname) disks = di.diskInfo() proxy = xmlrpclib.ServerProxy(rcEnv.dbopensvc, allow_none=True) disklist_cache = {} def disk_dg(dev, svc): for rset in svc.get_res_sets("disk.vg"): for vg in rset.resources: if not vg.name in disklist_cache: disklist_cache[vg.name] = vg.disklist() if dev in disklist_cache[vg.name]: return vg.name return """ Purge current service configurations from database for this host """ try: proxy.delete_services(hostid) except: pass for svc in svcBuilder.build_services(): """ Load service configuration in database """ try: proxy.delete_syncs(svc.svcname) for rset in svc.get_res_sets("rsync"): for r in rset.resources: if r.internal: continue if 'nodes' in r.target: nodes = ' '.join(r.target['nodes']) else: nodes = '' if 'drpnodes' in r.target: drpnodes = ' '.join(r.target['drpnodes']) else: drpnodes = '' if len(nodes) == 0 and len(drpnodes) == 0: continue proxy.register_sync( ['sync_svcname', 'sync_src', 'sync_dst', 'sync_dstfs', 'sync_exclude', 'sync_snap', 'sync_prdtarget', 'sync_drptarget', 'sync_bwlimit'], [repr(svc.svcname), repr(' '.join(r.src)), repr(r.dst), repr(str(r.dstfs)), repr(str(' '.join(r.exclude))), repr(str(r.snap)), repr(nodes), repr(drpnodes), repr(str(r.bwlimit))] ) except: pass try: for d in svc.disklist(): proxy.register_disk( ['disk_id', 'disk_svcname', 'disk_size', 'disk_vendor', 'disk_model', 'disk_dg', 'disk_nodename'], [repr(disks.disk_id(d)), repr(svc.svcname), repr(disks.disk_size(d)), repr(disks.disk_vendor(d)), repr(disks.disk_model(d)), repr(str(disk_dg(d, svc))), repr(rcEnv.nodename)] ) except: #raise pass try: proxy.update_service( ['svc_hostid', 'svc_name', 'svc_type', 'svc_nodes', 'svc_drpnode', 'svc_drpnodes', 'svc_comment', 'svc_drptype', 'svc_autostart', 'svc_app', 'svc_containertype', 'svc_drnoaction'], [repr(hostid), repr(svc.svcname), repr(svc.svctype), repr(' '.join(svc.nodes)), repr(svc.drpnode), repr(' '.join(svc.drpnodes)), repr(svc.comment), repr(svc.drp_type), repr(svc.autostart_node), repr(svc.app), repr(svc.svcmode), repr(svc.drnoaction)] ) except: pass try: svc.action('diskupdate') except: pass try: svc.action('syncnodes') except: pass try: svc.action('syncdrp') except: pass opensvc/commands/usr/local/opensvc/bin/freezer010075500000000000000000000025141132063442300220530ustar00rootroot00000000000000#!/usr/bin/python # # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import sys import os # # add project lib to path # sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) from freezer import Freezer from rcUtilities import check_privs check_privs() if len(sys.argv) == 1: f = Freezer() elif len(sys.argv) == 2: f = Freezer(sys.argv[1]) else: print __file__ + " [service]" sys.exit(1) cmd = os.path.basename(__file__) if cmd == 'svcfreeze': sys.exit(f.freeze()) elif cmd == 'svcthaw': sys.exit(f.thaw()) elif cmd == 'svcfrozen': sys.exit(int(f.frozen())) opensvc/commands/usr/local/opensvc/bin/opensvc.init.debian010075500000000000000000000007371132063442300242560ustar00rootroot00000000000000#!/bin/sh -e ### BEGIN INIT INFO # Provides: opensvc # Required-Start: $networking # Required-Stop: # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: OpenSVC services startup script ### END INIT INFO osvc_path=/usr/local/opensvc/bin allupservices=${osvc_path}/allupservices allprimaryservices=${osvc_path}/allprimaryservices case $1 in start) ${allprimaryservices} start ;; stop) ${allupservices} stop ;; esac opensvc/commands/usr/local/opensvc/bin/opensvc.init.hpux010075500000000000000000000012561132114003000240000ustar00rootroot00000000000000#!/bin/sh PATH=/sbin:/usr/sbin:/bin:/usr/bin export PATH if [ -r /etc/rc.config.d/opensvc ] ; then . /etc/rc.config.d/opensvc fi osvc_path=/usr/local/opensvc/bin allupservices=${osvc_path}/allupservices allprimaryservices=${osvc_path}/allprimaryservices case $1 in start_msg) if [ "$RUN_OPENSVC" -ne 0 ] ; then echo "Starting opensvc services" fi ;; start) if [ "$RUN_OPENSVC" -ne 0 ] ; then echo "Starting opensvc services" fi ${allprimaryservices} start ;; stop_msg) if [ "$RUN_OPENSVC" -ne 0 ] ; then echo "Shutting down opensvc services" fi ;; stop) if [ "$RUN_OPENSVC" -ne 0 ] ; then echo "Starting opensvc services" fi ${allupservices} stop ;; esac opensvc/commands/usr/local/opensvc/bin/opensvc.init.redhat010075500000000000000000000007561132063442300243040ustar00rootroot00000000000000#!/bin/bash # # /etc/rc.d/init.d/opensvc # # Starts the services driven by OpenSVC # # chkconfig: 345 99 01 # description: Starts the services driven by OpenSVC whose # autostart node is this node. # processname: # Source function library. . /etc/init.d/functions osvc_path=/usr/local/opensvc/bin allupservices=${osvc_path}/allupservices allprimaryservices=${osvc_path}/allprimaryservices case $1 in start) ${allprimaryservices} start ;; stop) ${allupservices} stop ;; esac opensvc/commands/usr/local/opensvc/bin/postinstall010075500000000000000000000122341132310612600227620ustar00rootroot00000000000000#!/usr/bin/env python2.6 import os import shutil from subprocess import * def install_cron(): """install opensvc cron jobs """ ce = [{ 'sched': "0,10,20,30,40,50 * * * *", 'user': "", 'cmd': "[ -x /usr/local/opensvc/bin/svcmon ] && /usr/local/opensvc/bin/svcmon --updatedb >/dev/null 2>&1" },{ 'sched': "0 4 * * *", 'user': "", 'cmd': "[ -x /usr/local/opensvc/bin/cron/opensvc.daily ] && /usr/local/opensvc/bin/cron/opensvc.daily >/dev/null 2>&1" }] purge = [] root_crontab = False """ order of preference """ root_crontab_locs = [ '/etc/cron.d/opensvc', '/var/spool/cron/crontabs/root', '/var/spool/cron/root', ] for loc in root_crontab_locs: if os.path.exists(os.path.dirname(loc)): if not root_crontab: root_crontab = loc if root_crontab == '/etc/cron.d/opensvc': ce[0]['user'] = "root" ce[1]['user'] = "root" elif os.path.exists(loc): purge.append(loc) if not root_crontab: print "no root crontab found in usual locations %s"%str(root_crontab_locs) return False cron_entry_1 = ' '.join([ce[0]['sched'], ce[0]['user'], ce[0]['cmd']]) cron_entry_2 = ' '.join([ce[1]['sched'], ce[1]['user'], ce[1]['cmd']]) new = False if os.path.exists(root_crontab): with open(root_crontab, 'r') as f: svcmon_present = False dailycron_present = False new = f.readlines() for line in new: if 'opensvc.daily' in line: dailycron_present = True if 'svcmon --updatedb' in line: svcmon_present = True if not svcmon_present: new.append(cron_entry_1+'\n') if not dailycron_present: new.append(cron_entry_2+'\n') else: new = [] new.append(cron_entry_1+'\n') new.append(cron_entry_2+'\n') if not new: print "problem preparing the new crontab" return False with open(root_crontab, 'w') as f: f.write(''.join(new)) """ Activate changes (actually only needed on HP-UX) """ cmd = ['crontab', root_crontab] process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() for loc in purge: with open(loc, 'r') as f: new = [ line for line in f.readlines() if not 'opensvc.daily' in line and not 'svcmon --updatedb' in line ] with open(loc, 'w') as f: f.write(''.join(new)) """ Clean up old standard file locations """ for f in ['/etc/cron.daily/opensvc', '/etc/cron.daily/opensvc.daily']: if os.path.exists(f): os.unlink(f) def activate_redhat(): cmd = ['chkconfig', '--add', 'opensvc'] process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() if process.returncode > 0: print buff[1] return False return True def activate_debian(): cmd = ['update-rc.d', '-f', 'opensvc', 'remove'] process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() if process.returncode > 0: print buff[1] return False cmd = ['update-rc.d', 'opensvc', 'defaults'] process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() if process.returncode > 0: print buff[1] return False return True def activate_hpux(): rc = "/sbin/init.d/opensvc" links = ["/sbin/rc1.d/K010opensvc", "/sbin/rc2.d/S990opensvc"] for l in links: if not os.path.islink(l): if os.path.exists(l): os.unlink(l) os.symlink(rc, l) with open("/etc/rc.config.d/opensvc", "w") as f: f.write("RUN_OPENSVC=1\n") f.close() return True def install_rc(): """install startup script """ sysname, nodename, x, x, machine = os.uname() if os.path.exists('/etc/debian_version'): rc = '/etc/init.d/opensvc' src = '/usr/local/opensvc/bin/opensvc.init.debian' activate = activate_debian elif os.path.exists('/etc/redhat-release'): rc = '/etc/init.d/opensvc' src = '/usr/local/opensvc/bin/opensvc.init.redhat' activate = activate_redhat elif sysname == "HP-UX": rc = '/sbin/init.d/opensvc' src = '/usr/local/opensvc/bin/opensvc.init.hpux' activate = activate_hpux else: print "could not select an init script: unsupported operating system" return False if os.path.islink(rc): os.unlink(rc) shutil.copyfile(src, rc) os.chmod(rc, 0755) activate() def gen_keys(): home = os.environ['HOME'] priv = os.path.join(home, ".ssh", "id_dsa") pub = os.path.join(home, ".ssh", "id_dsa.pub") if os.path.exists(pub) or os.path.exists(priv): return cmd = ['ssh-keygen', '-t', 'dsa', '-b', '1024', '-P', '', '-f', priv] process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() install_cron() install_rc() gen_keys() opensvc/commands/usr/local/opensvc/bin/rcService010075500000000000000000000022221132137644300223400ustar00rootroot00000000000000#!/usr/bin/env python2.6 # # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import sys import os # # add project lib to path # sys.path.append(os.path.join(os.path.dirname(__file__), '..' , 'lib')) import svcBuilder import rcOptParser svc = svcBuilder.build(os.path.basename(__file__)) if svc is None: sys.exit(1) parser = rcOptParser.svcOptionParser(svc) sys.exit(svc.action(parser.action)) opensvc/commands/usr/local/opensvc/bin/svcfreeze010075500000000000000000000025141132063442300224050ustar00rootroot00000000000000#!/usr/bin/python # # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import sys import os # # add project lib to path # sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) from freezer import Freezer from rcUtilities import check_privs check_privs() if len(sys.argv) == 1: f = Freezer() elif len(sys.argv) == 2: f = Freezer(sys.argv[1]) else: print __file__ + " [service]" sys.exit(1) cmd = os.path.basename(__file__) if cmd == 'svcfreeze': sys.exit(f.freeze()) elif cmd == 'svcthaw': sys.exit(f.thaw()) elif cmd == 'svcfrozen': sys.exit(int(f.frozen())) opensvc/commands/usr/local/opensvc/bin/svcfrozen010075500000000000000000000025141132063442300224300ustar00rootroot00000000000000#!/usr/bin/python # # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import sys import os # # add project lib to path # sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) from freezer import Freezer from rcUtilities import check_privs check_privs() if len(sys.argv) == 1: f = Freezer() elif len(sys.argv) == 2: f = Freezer(sys.argv[1]) else: print __file__ + " [service]" sys.exit(1) cmd = os.path.basename(__file__) if cmd == 'svcfreeze': sys.exit(f.freeze()) elif cmd == 'svcthaw': sys.exit(f.thaw()) elif cmd == 'svcfrozen': sys.exit(int(f.frozen())) opensvc/commands/usr/local/opensvc/bin/svcmgr010075500000000000000000000064701132137644300217250ustar00rootroot00000000000000#!/usr/bin/env python2.6 # # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import sys import os import optparse # # add project lib to path # pathsvc = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) pathetc = os.path.join(pathsvc, 'etc') rcService = os.path.join(pathsvc, 'bin', 'rcService') sys.path.append(os.path.join(pathsvc, 'lib')) import svcBuilder import rcStatus import rcOptParser from rcUtilities import banner from rcGlobalEnv import * svcs = [] __ver = rcEnv.prog + " version " + str(rcEnv.ver) __usage = "%prog [options] command\n\n" + rcOptParser.format_desc() parser = optparse.OptionParser(version=__ver, usage=__usage) parser.add_option("--debug", default="False", action="store_true", dest="debug", help="debug mode") cmd = os.path.basename(__file__) if cmd == 'allservices': svcs = svcBuilder.build_services() elif cmd == 'allupservices': svcs = svcBuilder.build_services(status=rcStatus.UP) svcs += svcBuilder.build_services(status=rcStatus.WARN) elif cmd == 'alldownservices': svcs = svcBuilder.build_services(status=rcStatus.DOWN) elif cmd == 'allprimaryservices': svcs = svcBuilder.build_services(onlyprimary=True) elif cmd == 'svcmgr': parser.add_option("--service", default=None, action="store", dest="parm_svcs", help="comma-separated list of service to operate on") parser.add_option("--status", default=None, action="store", dest="parm_status", help="operate only on service in the specified status (up/down/warn)") parser.add_option("--onlyprimary", default=None, action="store_true", dest="parm_primary", help="operate only on service flagged for autostart on this node") parm_primary = False parm_status = None (options, args) = parser.parse_args() if hasattr(options, "parm_svcs") and options.parm_svcs is not None: svcnames = options.parm_svcs.split(',') else: svcnames = [] if hasattr(options, "parm_status") and options.parm_status is not None: status = rcStatus.status_value(options.parm_status) else: status = None if hasattr(options, "parm_primary") and options.parm_primary is not None: onlyprimary = options.parm_primary else: onlyprimary = False svcs = svcBuilder.build_services(svcnames=svcnames, status=status, onlyprimary=onlyprimary) if len(args) > 1: parser.error("More than one action") if len(args) is 0: parser.error("Missing action") action = args[0] if not action in rcOptParser.action_desc.keys(): parser.error("unsupported action") for s in svcs: print banner(s.svcname) s.action(action) opensvc/commands/usr/local/opensvc/bin/svcmon010075500000000000000000000070451132355370300217260ustar00rootroot00000000000000#!/usr/bin/env python2.6 # # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import sys import os import optparse import string try: import curses curses.setupterm() columns = curses.tigetnum('cols') except: columns = 80 # # add project lib to path # pathsvc = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) pathetc = os.path.join(pathsvc, 'etc') sys.path.append(os.path.join(pathsvc, 'lib')) import svcBuilder import xmlrpcClient from rcUtilities import * from rcGlobalEnv import rcEnv def svcmon_verbose(svcs): for svc in svcs: print banner(svc.svcname) svc.print_status() def svcname_max_len(svcs): _len = 0 for svc in svcs: if _len < len(svc.svcname): _len = len(svc.svcname) return _len def svcmon_normal(svcs, upddb=False): if columns < 80: fmt = '%-12s %-8s %-9s %-9s %-9s %-9s %-9s %-9s\n' else: fmt = '%-' + str(svcname_max_len(svcs)) + 's %-8s %-9s %-9s %-9s %-9s %-9s %-9s\n' out = fmt % ("service", "service", "container", "container", "ip ", "disk ", "fs ", "overall") out += fmt % ("name ", "type ", "type ", "status ", "status", "status", "status", "status ") out += fmt % ("-------", "-------", "---------", "---------", "------", "------", "------", "-------") for svc in svcs: status = svc.group_status() out += fmt % ( svc.svcname, svc.svctype, svc.svcmode, status["container"], status["ip"], status["disk"], status["fs"], status["overall"]) if upddb: xmlrpcClient.svcmon_update(svc, status) print out svcs = [] __ver = rcEnv.prog + " version " + str(rcEnv.ver) __usage = "%prog [options]\n\nDisplay services status" parser = optparse.OptionParser(version=__ver, usage=__usage) parser.add_option("--service", default=None, action="store", dest="parm_svcs", help="comma-separated list of service to display status of") parser.add_option("--updatedb", default=None, action="store_true", dest="parm_upddb", help="update resource status in central database") parser.add_option("--verbose", default=None, action="store_true", dest="parm_verbose", help="display per-resource status for each selected service") (options, args) = parser.parse_args() if hasattr(options, "parm_upddb") and options.parm_upddb is not None: upddb = True else: upddb = False if hasattr(options, "parm_svcs") and options.parm_svcs is not None: svcs = svcBuilder.build_services(svcnames=options.parm_svcs.split(',')) else: svcs = svcBuilder.build_services() if hasattr(options, "parm_verbose") and options.parm_verbose is not None: svcmon_verbose(svcs) else: svcmon_normal(svcs, upddb) opensvc/commands/usr/local/opensvc/bin/svcthaw010075500000000000000000000025141132063442300220700ustar00rootroot00000000000000#!/usr/bin/python # # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import sys import os # # add project lib to path # sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) from freezer import Freezer from rcUtilities import check_privs check_privs() if len(sys.argv) == 1: f = Freezer() elif len(sys.argv) == 2: f = Freezer(sys.argv[1]) else: print __file__ + " [service]" sys.exit(1) cmd = os.path.basename(__file__) if cmd == 'svcfreeze': sys.exit(f.freeze()) elif cmd == 'svcthaw': sys.exit(f.thaw()) elif cmd == 'svcfrozen': sys.exit(int(f.frozen())) opensvc/commands/usr/local/opensvc/etc/004075500000000000000000000000003777777777700205435ustar00rootroot00000000000000opensvc/commands/usr/local/opensvc/lib/004075500000000000000000000000003777777777700205365ustar00rootroot00000000000000opensvc/commands/usr/local/opensvc/lib/freezer.py010064400000000000000000000033641132305306600225020ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import os import glob def dummy(): return class Freezer: flag_dir = os.path.join(os.path.dirname(__file__), '..', 'var') base_flag = os.path.join(flag_dir, 'FROZEN') flag = base_flag def frozen(self): if os.path.exists(self.flag) or os.path.exists(self.base_flag): return True return False def freeze(self): open(self.flag, 'w').close() def thaw(self): if self.flag != self.base_flag and os.path.exists(self.flag): os.unlink(self.flag) return for name in glob.glob(self.flag_dir + '/FROZEN*'): os.unlink(name) def __init__(self, name=''): if len(name) == 0: pass elif not os.path.exists(os.path.join(os.path.dirname(__file__), '..', 'etc', name)): self.freeze = dummy self.thaw = dummy self.frozen = dummy else: self.flag = self.flag + "." + name opensvc/commands/usr/local/opensvc/lib/hostidHP-UX.py010064400000000000000000000022631132331573400231140ustar00rootroot00000000000000# # Copyright (c) 2010 Christophe Varoqui ' # Copyright (c) 2010 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # from rcUtilities import which from subprocess import * def hostid(): if which('getconf') is None: return '1' cmd = ['getconf', 'MACHINE_SERIAL'] p = Popen(cmd, stderr=None, stdout=PIPE, close_fds=True) buff = p.communicate() sn = buff[0].split()[0] if p.returncode != 0: return '1' return str(hex(abs(sn.__hash__()))).replace('0x', '') opensvc/commands/usr/local/opensvc/lib/hostidLinux.py010064400000000000000000000015701132330611000233360ustar00rootroot00000000000000# # Copyright (c) 2010 Christophe Varoqui ' # Copyright (c) 2010 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # from uuid import getnode def hostid(): return str(getnode()) opensvc/commands/usr/local/opensvc/lib/hostidSunOS.py010064400000000000000000000015701132330611200232500ustar00rootroot00000000000000# # Copyright (c) 2010 Christophe Varoqui ' # Copyright (c) 2010 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # from uuid import getnode def hostid(): return str(getnode()) opensvc/commands/usr/local/opensvc/lib/lock.py010064400000000000000000000025351132305306600217670ustar00rootroot00000000000000import fcntl import os import rcExceptions as ex from rcGlobalEnv import rcEnv def svclock(svc): lock = os.path.join(rcEnv.pathlock, svc.svcname) pid = 0 if not os.path.exists(rcEnv.pathlock): os.makedirs(rcEnv.pathlock) else: try: with open(lock, 'r') as fd: pid = int(fd.read()) fd.close() except: pass try: svc.lockfd = os.open(lock, os.O_RDWR|os.O_SYNC|os.O_CREAT|os.O_TRUNC, 0644) except: svc.log.error("can not create lock file %s"%lock) raise try: """ test if we already own the lock """ if pid == os.getpid(): return """ FD_CLOEXEC makes sure the lock is the held by processes we fork from this process """ fcntl.flock(svc.lockfd, fcntl.LOCK_EX|fcntl.LOCK_NB) flags = fcntl.fcntl(svc.lockfd, fcntl.F_GETFD) flags |= fcntl.FD_CLOEXEC """ acquire lock """ fcntl.fcntl(svc.lockfd, fcntl.F_SETFD, flags) """ drop our pid in the lockfile """ os.write(svc.lockfd, str(os.getpid())) os.fsync(svc.lockfd) except IOError: svc.log.error("another action is currently running (pid=%s)"%pid) raise ex.excError except: raise def svcunlock(svc): os.close(svc.lockfd) opensvc/commands/usr/local/opensvc/lib/loopSunOS.py010064400000000000000000000025311132305306600227340ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import os import logging import resources from rcGlobalEnv import * import rcStatus class Loop(resources.Resource): def is_up(self): """Returns True if the volume group is present and activated """ return True def start(self): pass def stop(self): pass def status(self, verbose=False): if self.is_up(): return rcStatus.UP else: return rcStatus.DOWN def __init__(self, file): self.file = file resources.Resource.__init__(self) opensvc/commands/usr/local/opensvc/lib/lxc.py010064400000000000000000000103041132305306600216160ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import os from datetime import datetime from subprocess import * import rcLogger import rcStatus import resources as Res def lxc(self, action): outf = '/var/tmp/svc_'+self.name+'_lxc_'+action+'.log' if action == 'start': cmd = ['lxc-start', '-d', '-n', self.name, '-o', outf] elif action == 'stop': cmd = ['lxc-stop', '-n', self.name, '-o', outf] else: self.log.error("unsupported lxc action: %s" % action) return 1 t = datetime.now() (ret, out) = self.vcall(cmd) len = datetime.now() - t self.log.info('%s done in %s - ret %i - logs in %s' % (action, len, ret, outf)) return ret def lxc_rootfs_path(self): return os.path.realpath(os.path.join(self.pathlxc, self.name, 'rootfs','rootfs')) def lxc_is_created(self): cmd = [ 'lxc-info', '-n', self.name ] (ret, out) = self.call(cmd) return ret def lxc_wait_for_startup(self): for t in range(self.startup_timeout): if self.is_up(): return 0 log.error("timeout out waiting for %s startup", self.name) return 1 def lxc_wait_for_shutdown(self): for t in range(self.startup_timeout): if not self.is_up(): return 0 log.error("timeout out waiting for %s shutdown", self.name) return 1 def lxc_exec(self, cmd): pass class Lxc(Res.Resource): """ container status transition diagram : --------- | STOPPED |<--------------- --------- | | | start | | | V | ---------- | | STARTING |--error- | ---------- | | | | | V V | --------- ---------- | | RUNNING | | ABORTING | | --------- ---------- | | | | no process | | | | | V | | ---------- | | | STOPPING |<------- | ---------- | | | --------------------- """ pathlxc = os.path.join('usr', 'local', 'var', 'lib', 'lxc') shutdown_timeout = 60 startup_timeout = 60 def start(self): if self.is_up(): self.log.info("lxc container %s already started" % self.name) return 0 lxc(self, 'start') return lxc_wait_for_startup(self) def stop(self): if not self.is_up(): self.log.info("lxc container %s already stopped" % self.name) return 0 lxc(self, 'stop') return lxc_wait_for_shutdown(self) def is_up(self): self.log.debug("call: lxc-ps --name %s | grep %s" % (self.name, self.name)) p1 = Popen(['lxc-ps', '--name', self.name], stdout=PIPE) p2 = Popen(["grep", self.name], stdin=p1.stdout, stdout=PIPE) p2.communicate()[0] if p2.returncode == 0: return True return False def status(self): if self.is_up(): return rcStatus.UP else: return rcStatus.DOWN def __init__(self, svcname, optional=False, disabled=False): Res.Resource.__init__(self, "container.lxc", optional, disabled) self.name = svcname self.id = "lxc" def __str__(self): return "%s name=%s" % (Res.Resource.__str__(self), self.name) opensvc/commands/usr/local/opensvc/lib/node.py010064400000000000000000000054411132305306600217630ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. from svc import Svc from freezer import Freezer import rcStatus import os pathetc = os.path.join(pathsvc, 'etc') def is_service(f): if os.path.realpath(f) != os.path.realpath(rcService): return False if not os.path.exists(f + '.env'): return False return True class Node(Svc, Freezer): """Defines a cluster node. It contain list of Svc. """ def __init__(self): self.svcs = [] Svc.__init__(self, None, None, optional, disabled) Freezer.__init__(self, '') # # add services # for name in os.listdir(pathetc): if is_service(os.path.join(pathetc, name)): s = svcBuilder.build(name) if s is None : continue self += s # # lookup drp_nodes # drp_nodes = [] for s in self.svcs: if s.drpnode not in drp_nodes: drp_nodes.append(s.drpnode) # # add node file synchronization resources to drp # for drp_node in drp_nodes: for src, dst, excl in rcEnv.drp_syncs: dst = drp_node+":"+rcEnv.drp_dir+"/"+dst self += Rsync(src.join(' '), dst, excl.join(' ')) def __iadd__(self, s): if not isinstance(s, Svc): pass self.svcs.append(s) return self def syncnodes(self): for s in self.svcs: s.syncnodes() def syncdrp(self): Svc.syncdrp(self) for s in self.svcs: s.syncnodes() def get_svcs_on(self, status): return [ s for s in self.svcs if s.status == status ] def allupservice(self): return get_svcs_on(rcStatus.UP) def alldownservice(self): return get_svcs_on(rcStatus.UP) def allservices: return self.svcs if __name__ == "__main__" : for n in (Node,) : help(n) opensvc/commands/usr/local/opensvc/lib/rcAddService.py010064400000000000000000000016171132305306600233750ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import logging def addservice(): log = logging.getLogger('CREATE') log.info('enter') opensvc/commands/usr/local/opensvc/lib/rcDiskInfoHP-UX.py010064400000000000000000000040521132305306600236500ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # from rcUtilities import call, which class diskInfo(object): def __init__(self): self.h = {} cmd = ["scsimgr", "-p", "get_attr", "all_lun", "-a", "wwid", "-a", "device_file", "-a", "vid", "-a", "pid", "-a", "capacity"] (ret, out) = call(cmd) for e in out.split('\n'): if len(e) == 0: continue (wwid, dev, vid, pid, size) = e.split(':') dev = self.devkey(dev) wwid = wwid.replace('0x', '') if len(size) != 0: size = int(size)/2097152 vid = vid.strip('" ') pid = pid.strip('" ') self.h[dev] = dict(wwid=wwid, vid=vid, pid=pid, size=size) def devkey(self, dev): dev = dev.replace("/dev/rdisk/", "") dev = dev.replace("/dev/disk/", "") dev = dev.replace("/dev/dsk/", "") return dev def disk_id(self, dev): dev = self.devkey(dev) return self.h[dev]['wwid'] def disk_vendor(self, dev): dev = self.devkey(dev) return self.h[dev]['vid'] def disk_model(self, dev): dev = self.devkey(dev) return self.h[dev]['pid'] def disk_size(self, dev): dev = self.devkey(dev) return self.h[dev]['size'] opensvc/commands/usr/local/opensvc/lib/rcDiskInfoLinux.py010064400000000000000000000047451132305306600241170ustar00rootroot00000000000000#!/usr/bin/python2.6 # # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import sys import os from rcUtilities import call, which class diskInfo(object): disk_ids = {} def __init__(self): pass def disk_id(self, dev): if dev in disk_ids: return self.disk_ids[dev] if which('scsi_id'): scsi_id = 'scsi_id' elif which('/lib/udev/scsi_id'): scsi_id = '/lib/udev/scsi_id' else: return cmd = [scsi_id, '-g', '-u', '-d', dev] (ret, out) = call(cmd) if ret == 0: id = out.split('\n')[0][1:] self.disk_ids[dev] = id return id sdev = dev.replace("/dev/", "/block/") cmd = [scsi_id, '-g', '-u', '-s', sdev] (ret, out) = call(cmd) if ret == 0: id = out.split('\n')[0][1:] self.disk_ids[dev] = id return id return def disk_vendor(self, dev): s = '' path = dev.replace('/dev/', '/sys/block/')+'/device/vendor' if not os.path.exists(path): return with open(path, 'r') as f: s = f.read() f.close() return s def disk_model(self, dev): s = '' path = dev.replace('/dev/', '/sys/block/')+'/device/model' if not os.path.exists(path): return with open(path, 'r') as f: s = f.read() f.close() return s def disk_size(self, dev): size = 0 path = dev.replace('/dev/', '/sys/block/')+'/size' if not os.path.exists(path): return with open(path, 'r') as f: size = f.read() f.close() return int(size)/2097152 opensvc/commands/usr/local/opensvc/lib/rcDiskInfoSunOS.py010064400000000000000000000020461132305306600240170ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # class diskInfo(object): def __init__(self): pass def disk_id(self, dev): pass def disk_vendor(self, dev): pass def disk_model(self, dev): pass def disk_size(self, dev): pass opensvc/commands/usr/local/opensvc/lib/rcExceptions.py010064400000000000000000000045101132310612600234740ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. class excError(Exception): """ Failed action """ class excUndefined(Exception): """ Mandatory Undefined action exception """ def __init__(self,action=None,className=None,func=None): self.action=action self.className=className self.func=func def __str__(self): return "Undefined mandatory Action %s for className %s in function %s" % \ (self.action,self.className,self.func) class syncNoNodesToSync(Exception): """ No nodes to sync => abort stacked syncs resource actions """ class syncNoFilesToSync(Exception): """ No files to sync => move on to the next stacked syncs resource actions """ class syncConfigSyntaxError(Exception): """ Bogus configuration syntax => abort all """ class syncNotSnapable(Exception): """ A dir/file specified as source of a sync with snap is not included in a snapable resource mount => abort all """ class syncSnapExists(Exception): """ The snapshot already exists """ class syncSnapCreateError(Exception): """ Error in snapshot creation => clean up """ class syncSnapMountError(Exception): """ Error mounting fs => clean up """ class excAbortAction(Exception): """ Abort multi-resource action """ class excInitError(Exception): """ Resource initialisation error """ class excScsiPrNotsupported(Exception): """ Scsi persistent reservation is not supported """ opensvc/commands/usr/local/opensvc/lib/rcGlobalEnv.py010064400000000000000000000100151132305306600232250ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # class rcEnv: """Class to store globals """ prog = "opensvc" ver = "20090924-1" """program used to execute remote command on other nodes or virtual hosts """ rsh = "/usr/bin/ssh -o StrictHostKeyChecking=no -o ForwardX11=no -o PasswordAuthentication=no -o ConnectTimeout=10" rcp = "/usr/bin/scp -o StrictHostKeyChecking=no -o ForwardX11=no -o PasswordAuthentication=no -o ConnectTimeout=10" """Database sink for node and service configurations and status collection. """ dbopensvc = "http://dbopensvc:80/init/default/call/xmlrpc" """EZ-HA defines. EZ-HA does heartbeat, stonith, automatic service failover ez_last_chance == True: check_up_script_gen.sh will try a ping + RSH other node before stonith ez_startapp_bg == True: startapp in background if EZ-HA take-over is succesful """ ez_path = "/usr/local/cluster" ez_path_services = ez_path + "/conf/services" ez_last_chance = True ez_startapp_bg = True """Directory on DRP node where to store the PRD nodes files necessary for takeover. """ drp_path = "/usr/local/opensvc/var/cache/" drp_sync_excludes = [ '--exclude="/spice"', '--exclude="/dbadm"', '--exclude="*.dmp"', '--exclude="*.dbf"', '--exclude="*.rdo"', '--exclude="*.log"', '--exclude="*.Z"', '--exclude="*.gz"', '--exclude="*.tgz"', '--exclude="*.tar"', '--exclude="*.tmp"', '--exclude="/oracle/ficimp"', '--exclude="/oracle/tmp"', '--exclude="/oracle/LOG/*"', '--exclude="/oracle/product/*/network/log/listener*.log"', ] drp_sync_etc_solaris = [ "/etc/inet", "/etc/inetd.conf", "/etc/defaultdomain", "/etc/lp", "/etc/printers.conf", "/etc/system", "/etc/auto_master", "/etc/auto_home", "/etc/hosts.equiv", "/etc/pam.conf", "/etc/cron.d", ] drp_sync_etc_linux = [ # linux "/etc/xinetd.d", "/etc/xinetd.conf", "/etc/sysconfig", "/etc/cups", "/etc/auto.master", "/etc/auto.misc", "/etc/listener.ora", "/etc/oratab", "/etc/sqlnet.ora", "/etc/tnsnames.ora", "/etc/yp.conf", "/etc/pam.d", "/etc/cron.allow", "/etc/cron.deny", ] drp_sync_etc_common = [ # common "/etc/shadow", "/etc/passwd", "/etc/group", "/etc/syslog.conf", "/etc/services", "/etc/hosts", "/etc/nsswitch.conf", "/etc/sudoers", "/etc/project", "/etc/user_attr", "/etc/ssh", "/etc/centrifydc", "/etc/krb5*", "/etc/sudoers", ] drp_sync_misc = [ "/var/centrifydc", "/var/opt/oracle", "/var/spool/cron", "/var/spool/cron/crontabs", "/var/yp/binding", "/usr/local/oraenv", "/usr/local/coraenv", "/usr/local/dbhome", "/usr/local/etc/sudoers", ] drp_sync_files = [ [drp_sync_etc_solaris + drp_sync_etc_linux + drp_sync_etc_common + drp_sync_misc, []], [["/home/oracle", "/home/sybase", "/opt/oracle", "/opt/sybase"], drp_sync_excludes], ] opensvc/commands/usr/local/opensvc/lib/rcIfconfig.py010064400000000000000000000130251132305306600231040ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # from subprocess import * import logging from rcGlobalEnv import * class interface: def show(self): log = logging.getLogger('INIT') log.debug('ifconfig:') log.debug(self.name + ' link_encap = ' + self.link_encap) log.debug(self.name + ' scope = ' + self.scope) log.debug(self.name + ' bcast = ' + self.bcast) log.debug(self.name + ' mask = ' + self.mask) log.debug(self.name + ' mtu = ' + self.mtu) log.debug(self.name + ' ipaddr = ' + self.ipaddr) log.debug(self.name + ' ip6addr = ' + self.ip6addr) log.debug(self.name + ' hwaddr = ' + self.hwaddr) log.debug(self.name + ' flag_up = ' + str(self.flag_up)) log.debug(self.name + ' flag_broadcast = ' + str(self.flag_broadcast)) log.debug(self.name + ' flag_running = ' + str(self.flag_running)) log.debug(self.name + ' flag_multicast = ' + str(self.flag_multicast)) log.debug(self.name + ' flag_loopback = ' + str(self.flag_loopback)) def __init__(self, name): self.name = name # defaults self.link_encap = '' self.scope = '' self.bcast = '' self.mask = '' self.mtu = '' self.ipaddr = '' self.ip6addr = '' self.hwaddr = '' self.flag_up = False self.flag_broadcast = False self.flag_running = False self.flag_multicast = False self.flag_loopback = False class ifconfig(object): intf = [] def add_interface(self, name): i = interface(name) self.intf.append(i) def interface(self, name): for i in self.intf: if i.name == name: return i return None def has_interface(self, name): for i in self.intf: if i.name == name: return 1 return 0 def has_param(self, param, value): for i in self.intf: if getattr(i, param) == value: return i return None def __init__(self): out = Popen(['ifconfig', '-a'], stdout=PIPE).communicate()[0] prev = '' prevprev = '' for w in out.split(): if w == 'Link': i = interface(prev) self.intf.append(i) # defaults i.link_encap = '' i.scope = '' i.bcast = '' i.mask = '' i.mtu = '' i.ipaddr = '' i.ip6addr = '' i.hwaddr = '' i.flag_up = False i.flag_broadcast = False i.flag_running = False i.flag_multicast = False i.flag_loopback = False elif 'encap:' in w: (null, i.link_encap) = w.split(':') elif 'Scope:' in w: (null, i.scope) = w.split(':') elif 'Bcast:' in w: (null, i.bcast) = w.split(':') elif 'Mask:' in w: (null, i.mask) = w.split(':') elif 'MTU:' in w: (null, i.mtu) = w.split(':') if 'inet' == prev and 'addr:' in w: (null, i.ipaddr) = w.split(':') if 'inet6' == prevprev and 'addr:' == prev: i.ip6addr = w if 'HWaddr' == prev: i.hwaddr = w if 'UP' == w: i.flag_up = True if 'BROADCAST' == w: i.flag_broadcast = True if 'RUNNING' == w: i.flag_running = True if 'MULTICAST' == w: i.flag_multicast = True if 'LOOPBACK' == w: i.flag_loopback = True prevprev = prev prev = w def next_stacked_dev(self,dev): """Return the first available interfaceX:Y on interfaceX """ i = 1 while True: stacked_dev = dev+':'+str(i) if not self.has_interface(stacked_dev): return stacked_dev i = i + 1 def get_stacked_dev(self, dev, addr, log): """Upon start, a new interfaceX:Y will have to be assigned. Upon stop, the currently assigned interfaceX:Y will have to be found for ifconfig down """ stacked_intf = self.has_param("ipaddr", addr) if stacked_intf is not None: if dev not in stacked_intf.name: log.error("%s is plumbed but not on %s" % (addr, dev)) return stacked_dev = stacked_intf.name log.debug("found matching stacked device %s" % stacked_dev) else: stacked_dev = self.next_stacked_dev(dev) log.debug("allocate new stacked device %s" % stacked_dev) return stacked_dev opensvc/commands/usr/local/opensvc/lib/rcIfconfigHP-UX.py010064400000000000000000000054461132305306600236760ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # from subprocess import * import rcIfconfig class ifconfig(rcIfconfig.ifconfig): def parse(self, out): if len(out) == 0: return intf = out.split()[0] if intf[len(intf)-1] == ':': intf = intf[0:len(intf)-1] i = rcIfconfig.interface(intf) self.intf.append(i) # defaults i.link_encap = '' i.scope = '' i.bcast = '' i.mask = '' i.mtu = '' i.ipaddr = '' i.ip6addr = '' i.hwaddr = '' i.flag_up = False i.flag_broadcast = False i.flag_running = False i.flag_multicast = False i.flag_loopback = False prev = '' for w in out.split(): if 'broadcast' in prev: i.bcast = w elif 'netmask' in prev: i.mask = "%d.%d.%d.%d"%( int(w[0:2], 16), int(w[2:4], 16), int(w[4:6], 16), int(w[6:8], 16) ) elif 'inet' in prev: i.ipaddr = w elif 'inet6' in prev: i.ip6addr = w if 'UP' in w: i.flag_up = True if 'BROADCAST' in w: i.flag_broadcast = True if 'RUNNING' in w: i.flag_running = True if 'MULTICAST' in w: i.flag_multicast = True if 'LOOPBACK' in w: i.flag_loopback = True prev = w def __init__(self): intf_list = Popen(['netstat', '-win'], stdout=PIPE).communicate()[0] for line in intf_list.split('\n'): if len(line) == 0: continue intf = line.split()[0] if intf[len(intf)-1] == ':': intf = intf[0:len(intf)-1] out = Popen(['ifconfig', intf], stdout=PIPE, stderr=PIPE).communicate() if "no such interface" in out[1]: continue self.parse(out[0]) opensvc/commands/usr/local/opensvc/lib/rcIfconfigLinux.py010064400000000000000000000052461132305306600241320ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # from subprocess import * import rcIfconfig class ifconfig(rcIfconfig.ifconfig): def parse(self, out): prev = '' prevprev = '' for w in out.split(): if w == 'Link': i = rcIfconfig.interface(prev) self.intf.append(i) # defaults i.link_encap = '' i.scope = '' i.bcast = '' i.mask = '' i.mtu = '' i.ipaddr = '' i.ip6addr = '' i.hwaddr = '' i.flag_up = False i.flag_broadcast = False i.flag_running = False i.flag_multicast = False i.flag_loopback = False elif 'encap:' in w: (null, i.link_encap) = w.split(':') elif 'Scope:' in w: (null, i.scope) = w.split(':') elif 'Bcast:' in w: (null, i.bcast) = w.split(':') elif 'Mask:' in w: (null, i.mask) = w.split(':') elif 'MTU:' in w: (null, i.mtu) = w.split(':') if 'inet' == prev and 'addr:' in w: (null, i.ipaddr) = w.split(':') if 'inet6' == prevprev and 'addr:' == prev: i.ip6addr = w if 'HWaddr' == prev: i.hwaddr = w if 'UP' == w: i.flag_up = True if 'BROADCAST' == w: i.flag_broadcast = True if 'RUNNING' == w: i.flag_running = True if 'MULTICAST' == w: i.flag_multicast = True if 'LOOPBACK' == w: i.flag_loopback = True prevprev = prev prev = w def __init__(self): out = Popen(['ifconfig', '-a'], stdout=PIPE).communicate()[0] self.parse(out) opensvc/commands/usr/local/opensvc/lib/rcIfconfigLinuxlxc.py010064400000000000000000000021221132305306600246270ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # from subprocess import * import rcIfconfigLinux from rcGlobalEnv import rcEnv class ifconfig(rcIfconfigLinux.ifconfig): def __init__(self, hostname): out = Popen(rcEnv.rsh.split(' ') + [hostname, 'ifconfig', '-a'], stdout=PIPE).communicate()[0] self.parse(out) opensvc/commands/usr/local/opensvc/lib/rcIfconfigSunOS.py010064400000000000000000000044241132305306600240370ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # from subprocess import * import rcIfconfig class ifconfig(rcIfconfig.ifconfig): def __init__(self): out=Popen(['ifconfig','-a'],stdin=None, stdout=PIPE,stderr=PIPE,close_fds=True).communicate()[0] for l in out.split("\n"): if l == '' : break if l[0]!='\t' : (ifname,ifstatus)=l.split(': ') i=rcIfconfig.interface(ifname) self.intf.append(i) # defaults i.link_encap = '' i.scope = '' i.bcast = '' i.mask = '' i.mtu = '' i.ipaddr = '' i.ip6addr = '' i.hwaddr = '' i.flag_up = False i.flag_broadcast = False i.flag_running = False i.flag_multicast = False i.flag_ipv4 = False i.flag_ipv6 = False i.flag_loopback = False if 'UP' in ifstatus : i.flag_up = True elif 'BROADCAST' in ifstatus : i.flag_broadcast = True elif 'RUNNING' in ifstatus : i.flag_running = True elif 'MULTICAST' in ifstatus : i.flag_multicast = True elif 'IPv4' in ifstatus : i.flag_ipv4 = True elif 'IPv6' in ifstatus : i.flag_ipv6 = True else: n=0 w=l.split() while n < len(w) : [p,v]=w[n:n+2] if p == 'inet' : i.ipaddr=v elif p == 'inet6' : i.ip6addr=v elif p == 'netmask' : i.mask=v elif p == 'broadcast' : i.bcast=v n+=2 if __name__ == "__main__": for c in (ifconfig,) : help(c) opensvc/commands/usr/local/opensvc/lib/rcLogger.py010064400000000000000000000031351132305306600226000ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import logging import logging.handlers from rcGlobalEnv import * class Logger(logging.Logger): def __init__(self, name): logging.Logger.__init__(self, name) """Common log formatter """ formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") """Common logfile with rotation """ filehandler = logging.handlers.RotatingFileHandler(rcEnv.logfile, maxBytes=5000, backupCount=5) filehandler.setFormatter(formatter) self.addHandler(filehandler) """Stdout logger """ streamhandler = logging.StreamHandler() streamhandler.setFormatter(formatter) self.addHandler(streamhandler) try: self.setLevel(rcEnv.loglevel) except: pass opensvc/commands/usr/local/opensvc/lib/rcMounts.py010064400000000000000000000036221132305306600226470ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # class Mount: def __init__(self, dev, mnt, type, mnt_opt): self.dev = dev self.mnt = mnt self.type = type self.mnt_opt = mnt_opt def __str__(self): return "Mount: dev[%s] mnt[%s] type[%s] options[%s]" % \ (self.dev,self.mnt,self.type,self.mnt_opt) class Mounts: mounts = [] def __init__(self): """ OS dependent """ pass def match_mount(self): """ OS dependent """ pass def mount(self, dev, mnt): for i in self.mounts: if self.match_mount(i, dev, mnt): return i return None def has_mount(self, dev, mnt): for i in self.mounts: if self.match_mount(i, dev, mnt): return True return False def has_param(self, param, value): for i in self.mounts: if getattr(i, param) == value: return i return None def __str__(self): output="%s" % (self.__class__.__name__) for m in self.mounts: output+="\n %s" % m.__str__() return output opensvc/commands/usr/local/opensvc/lib/rcMountsHP-UX.py010064400000000000000000000042541132305306600234330ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import rcMounts from rcUtilities import * from subprocess import Popen def get_src_dir_dev(dev): """Given a directory path, return its hosting device """ process = Popen(['df', '-l', dev], stdout=PIPE, stderr=STDOUT, close_fds=True) buff = process.communicate() out = buff[0] i = out.index('/') return out[i:].split()[0] class Mounts(rcMounts.Mounts): def match_mount(self, i, dev, mnt): """Given a line of 'mount' output, returns True if (dev, mnt) matches this line. Returns False otherwize. Also care about weirdos like loops and binds, ... """ if os.path.isdir(dev): is_bind = True src_dir_dev = get_src_dir_dev(dev) else: is_bind = False if i.mnt != mnt: return False if i.dev == dev: return True if is_bind and i.dev == src_dir_dev: return True return False def __init__(self): (ret, out) = call(['mount', '-v']) for l in out.split('\n'): if len(l.split()) != 12: return dev, null, mnt, null, type, mnt_opt, null, null, null, null, null, null = l.split() m = rcMounts.Mount(dev, mnt, type, mnt_opt.strip('()')) self.mounts.append(m) if __name__ == "__main__" : help(Mounts) for m in Mounts(): print m opensvc/commands/usr/local/opensvc/lib/rcMountsLinux.py010064400000000000000000000043371132305306600236730ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import rcMounts import resLoopLinux as Res from rcUtilities import * from subprocess import Popen def get_src_dir_dev(dev): """Given a directory path, return its hosting device """ process = Popen(['df', '-l', dev], stdout=PIPE, stderr=STDOUT, close_fds=True) buff = process.communicate() out = buff[0] i = out.index('/') return out[i:].split()[0] class Mounts(rcMounts.Mounts): def match_mount(self, i, dev, mnt): """Given a line of 'mount' output, returns True if (dev, mnt) matches this line. Returns False otherwize. Also care about weirdos like loops and binds, ... """ if os.path.isdir(dev): is_bind = True src_dir_dev = get_src_dir_dev(dev) else: is_bind = False if i.mnt != mnt: return False if i.dev == dev: return True if i.dev == Res.file_to_loop(dev): return True if is_bind and i.dev == src_dir_dev: return True return False def __init__(self): (ret, out) = call(['mount']) for l in out.split('\n'): if len(l.split()) != 6: return dev, null, mnt, null, type, mnt_opt = l.split() m = rcMounts.Mount(dev, mnt, type, mnt_opt.strip('()')) self.mounts.append(m) if __name__ == "__main__" : help(Mounts) for m in Mounts(): print m opensvc/commands/usr/local/opensvc/lib/rcMountsSunOS.py010064400000000000000000000035441132305306600236020ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import rcMounts from rcUtilities import * class Mounts(rcMounts.Mounts): def match_mount(self, i, dev, mnt): """Given a line of 'mount' output, returns True if (dev, mnt) matches this line. Returns False otherwize. Also care about weirdos like loops and binds, ... """ if i.mnt != mnt: return False if i.dev == dev: return True return False def __init__(self): (ret, out) = call(['mount','-p']) for line in out.split('\n'): words=line.split() if len(words) < 6 : continue elif words[1]+words[4] != '--' : # ignore mount line with space in mountpoint or dev continue elif len(words) == 6 : words.append('-') dev, null, mnt, type, null, null, mnt_opt = words m = rcMounts.Mount(dev, mnt, type, mnt_opt.strip('()')) self.mounts.append(m) if __name__ == "__main__" : help(Mounts) M=Mounts() print M opensvc/commands/usr/local/opensvc/lib/rcNode.py010064400000000000000000000040461132305306600222500ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import os import sys import re from rcGlobalEnv import * import logging def node_cap_ez_ha(): if not os.path.exists(rcEnv.ez_path): return False if not os.path.exists(rcEnv.ez_path_services): return False return True def node_cap_lxc(): if not os.path.exists("/proc/1/cgroup"): return False with open("/proc/1/cgroup") as f: for line in f: if not re.search("devices",line): return False if not re.search("memory",line): return False if not re.search("cpuset",line): return False if not re.search("ns",line): return False return True def node_get_hostmode(d): __f = d + "/host_mode" if os.path.exists(__f): with open(__f) as f: for line in f: w = line.split()[0] if w == 'DEV' or w == 'PRD': return w print "Set DEV or PRD in " + __f sys.exit(1) def discover_node(): """Fill rcEnv class with information from node discovery """ global log log = logging.getLogger('INIT') rcEnv.host_mode = node_get_hostmode(rcEnv.pathvar) log.debug('host mode = ' + rcEnv.host_mode) # # node capabilities # rcEnv.capabilities = [] if node_cap_lxc(): rcEnv.capabilities.append("lxc") if node_cap_ez_ha(): rcEnv.capabilities.append("ez_ha") log.debug('capabilities = ' + str(rcEnv.capabilities)) opensvc/commands/usr/local/opensvc/lib/rcOptParser.py010064400000000000000000000072101132305306600232760ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import optparse from rcGlobalEnv import * action_desc = { 'start': 'start a service, chaining startip-diskstart-startapp', 'startip': 'configure service ip addresses', 'mount': 'prepare devices, logical volumes, mount service filesystems, bootstrap containers', 'startapp': 'execute service application startup script', 'stop': 'stop a service, chaining stopapp-diskstop-stopip', 'stopip': 'unconfigure service ip addresses', 'umount': 'shutdown container, umount service filesystems, deactivate logical volumes', 'stopapp': 'execute service application stop script', 'syncnodes': 'send to peer nodes the service config files and additional files described in the config file', 'syncdrp': 'send to drp nodes the service config files and additional files described in the config file', 'configure': 'configure a service container, using configuration file information', 'create': 'create a new service configuration file', 'startlxc': 'start a LinuX Container', 'stoplxc': 'stop a LinuX Container', 'status': 'display service resource status', 'freeze': 'set up a flag to block actions on this service', 'thaw': 'remove the flag to unblock actions on this service', 'frozen': 'report on the current blocking of actions on this service', 'startloop': 'attach loop resources of this service', 'stoploop': 'detach loop resources of this service', 'startvg': 'activate/import volume group resources of this service', 'stopvg': 'deactivate/deport volume group resources of this service', 'diskstart': 'combo action, chaining startvg-mount', 'diskstop': 'combo action, chaining umount-stopvg', 'diskupdate': 'update var files associated to disks', 'scsireserv': 'reserve scsi disks held by this service', 'scsirelease': 'release scsi disks held by this service', 'scsicheckreserv': 'report status of reservations on scsi disks held by this service', 'restart': 'stop then start', } def format_desc(svc=False): desc = "Supported commands:\n" for a in action_desc.keys(): if svc and not hasattr(svc, a): continue desc += " {0:13s}{1:65s}\n".format(a, action_desc[a]) return desc class svcOptionParser: def __init__(self, svc=False): __ver = rcEnv.prog + " version " + str(rcEnv.ver) __usage = "%prog [options] command\n\n" + format_desc(svc) parser = optparse.OptionParser(version=__ver, usage=__usage) parser.add_option("--debug", default="False", action="store_true", dest="debug", help="debug mode") parser.add_option("-f", "--force", default="False", action="store_true", dest="force", help="force action, ignore sanity check warnings") (self.options, self.args) = parser.parse_args() if len(self.args) > 1: parser.error("More than one action") if len(self.args) is 0: parser.error("Missing action") self.action = self.args[0] if svc and not hasattr(svc, self.action): parser.error("unsupported action") opensvc/commands/usr/local/opensvc/lib/rcStatus.py010064400000000000000000000057431132305306600226530ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import os UP = 0 DOWN = 1 WARN = 2 NA = 3 TODO = 4 UNDEF = 5 GREEN = 32 RED = 31 YELLOW = 33 def colorize(color, text): #if os.isatty(1): # return '\033['+str(color)+'m'+text+'\033[m' #else: return text _status_value = { 'up': UP, 'down': DOWN, 'warn': WARN, 'n/a': NA, 'na': NA, 'todo': TODO, 'undef': UNDEF } _status_str = { UP: colorize(GREEN, 'up'), DOWN: colorize(RED, 'down'), WARN: colorize(YELLOW, 'warn'), NA: 'n/a', TODO: 'todo', UNDEF: 'undef' } def status_value(str): if str not in _status_value.keys(): return None return _status_value[str.lower()] def status_str(val): if val not in _status_str.keys(): return None return _status_str[val] def _merge(s1, s2): """Merge too status: WARN and TODO taint UP and DOWN """ if s1 == UNDEF: return s2 if (s1, s2) == (UP, UP): return UP if (s1, s2) == (UP, DOWN): return WARN if (s1, s2) == (UP, WARN): return WARN if (s1, s2) == (UP, NA): return UP if (s1, s2) == (UP, TODO): return WARN if (s1, s2) == (DOWN, DOWN): return DOWN if (s1, s2) == (DOWN, WARN): return WARN if (s1, s2) == (DOWN, NA): return DOWN if (s1, s2) == (DOWN, TODO): return WARN if (s1, s2) == (WARN, WARN): return WARN if (s1, s2) == (WARN, NA): return WARN if (s1, s2) == (WARN, TODO): return WARN if (s1, s2) == (NA, NA): return NA if (s1, s2) == (NA, TODO): return WARN if (s1, s2) == (TODO, TODO): return TODO return _merge(s2, s1) def print_status(resource, status): import string print '{0:70} {1}'.format(resource, status_str(status)) class Status(object): """Class that wraps printing and calculation of resource status """ def reset(self): self.status = UNDEF def __add__(self, s): self.status = _merge(self.status, s.status) return self def __iadd__(self, s): """Merge a status with current global status """ self.status = _merge(self.status, s) return self def __str__(self): return status_str(self.status) def __init__(self, initial_status=UNDEF): self.status = initial_status opensvc/commands/usr/local/opensvc/lib/rcUtilities.py010064400000000000000000000061411132305306600233340ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import os, sys import select import logging from subprocess import * def check_privs(): if os.getuid() != 0: print 'Insufficient privileges. Try:\n sudo ' + ' '.join(sys.argv) sys.exit(1) def banner(text, ch='=', length=78): spaced_text = ' %s ' % text banner = spaced_text.center(length, ch) return banner def is_exe(fpath): """Returns True if file path is executable, False otherwize """ return os.path.exists(fpath) and os.access(fpath, os.X_OK) def which(program): """Returns True if program is in PATH and executable, False otherwize """ fpath, fname = os.path.split(program) if fpath and is_exe(program): return program for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None def call(argv=['/bin/false'], log=None, info=False, errlog=True): if log == None: log = logging.getLogger('CALL') if not argv: return (0, '') if info: log.info(' '.join(argv)) else: log.debug(' '.join(argv)) process = Popen(argv, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() if errlog and len(buff[1]) > 0: log.error('error:\n' + buff[1]) if len(buff[0]) > 0: log.debug('output:\n' + buff[0]) return (process.returncode, buff[0]) def qcall(argv=['/bin/false']) : """qcall Launch Popen it args disgarding output and stderr""" if not argv: return (0, '') process = Popen(argv, stdout=PIPE, stderr=PIPE, close_fds=True) process.communicate() return process.returncode def vcall(argv=['/bin/false'], log=None): return call(argv, log, True) def getmount(path): path = os.path.abspath(path) while path != os.path.sep: if not os.path.islink(path) and os.path.ismount(path): return path path = os.path.abspath(os.path.join(path, os.pardir)) return path def protected_mount(path): if getmount(path) in ['/', '/usr', '/var', '/sys', '/proc', '/tmp', '/opt', '/dev', '/dev/pts', '/home', '/boot', '/dev/shm']: return True return False if __name__ == "__main__": print "call(('id','-a'))" (r,output)=call(("/usr/bin/id","-a")) print "status: ",r,"output:",output opensvc/commands/usr/local/opensvc/lib/resApp.py010064400000000000000000000050701132305306600222660ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # from subprocess import * from datetime import datetime import os import glob from rcGlobalEnv import rcEnv from rcUtilities import is_exe import resources as Res def checks(self): if not os.path.exists(self.svc.initd): self.log.error("%s is not present"%self.svc.initd) return False elif not os.path.islink(self.svc.initd): self.log.error("%s is not a link"%self.svc.initd) return False return True def app(self, name, action): if not is_exe(name): self.vcall(['chmod', '+x', name]) self.log.info('spawn: %s %s' % (name, action)) outf = '/var/tmp/svc_'+self.svc.svcname+'_'+os.path.basename(name)+'.log' f = open(outf, 'w') t = datetime.now() p = Popen([name, action], stdin=None, stdout=f.fileno(), stderr=f.fileno()) p.communicate() len = datetime.now() - t self.log.info('%s done in %s - ret %d - logs in %s' % (action, len, p.returncode, outf)) f.close() return p.returncode class Apps(Res.Resource): def start(self): """Execute each startup script (S* files). Log the return code but don't stop on error. """ if not checks(self): return 1 for name in sorted(glob.glob(os.path.join(self.svc.initd, 'S*'))): app(self, name, 'start') return 0 def stop(self): """Execute each shutdown script (K* files). Log the return code but don't stop on error. """ if not checks(self): return 1 for name in sorted(glob.glob(os.path.join(self.svc.initd, 'K*'))): app(self, name, 'stop') return 0 def status(self): pass def __init__(self, optional=False, disabled=False): Res.Resource.__init__(self, "app", optional, disabled) opensvc/commands/usr/local/opensvc/lib/resDg.py010064400000000000000000000057721132310612600221050ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. """Module providing Generic device group resources """ import resources as Res import rcStatus import rcExceptions as exc from rcGlobalEnv import rcEnv scsiReserv = __import__("scsiReserv"+rcEnv.sysname) def allow_scsireserv(self): if not self.scsiReservation: return False if not scsiReserv.scsireserv_supported(): self.log.error("scsi reservation is enabled but not supported") raise exc.excError return True class Dg(Res.Resource): """ basic Dg resource, must be extend for LVM / Veritas / ZFS """ def __init__(self, name=None, type=None, optional=False, disabled=False, scsireserv=False): Res.Resource.__init__(self, type, optional, disabled) self.name = name self.scsiReservation = scsireserv self.disks = set() def __str__(self): return "%s name=%s" % (Res.Resource.__str__(self),\ self.name) def set_scsireserv(self): self.scsiReservation = True def scsirelease(self): if not allow_scsireserv(self): return return scsiReserv.ScsiReserv(self.disklist()).scsirelease() def scsireserv(self): if not allow_scsireserv(self): return return scsiReserv.ScsiReserv(self.disklist()).scsireserv() def scsicheckreserv(self): if not allow_scsireserv(self): return return scsiReserv.ScsiReserv(self.disklist()).scsicheckreserv() def disklist(self): return self.disks def has_it(self): return False def is_up(self): return False def do_start(self): return False def do_stop(self): return False def stop(self): self.do_stop() self.scsirelease() def start(self): self.scsireserv() self.do_start() def status(self): if self.is_up(): return rcStatus.UP else: return rcStatus.DOWN if __name__ == "__main__": for c in (Dg,) : help(c) print """d=Dg("aGenericDg")""" d=Dg("aGenericDg") print "show d", d print """d.do_action("start")""" d.do_action("start") print """d.do_action("stop")""" d.do_action("stop") opensvc/commands/usr/local/opensvc/lib/resIp.py010064400000000000000000000125671132305306600221270ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. import resources as Res from rcGlobalEnv import * from subprocess import Popen, PIPE from rcUtilities import qcall, which rcIfconfig = __import__('rcIfconfig'+rcEnv.sysname) import socket import rcStatus import rcExceptions as ex class MissImpl(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class IpDevDown(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class IpConflict(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class IpAlreadyUp(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class Ip(Res.Resource): """ basic ip resource """ def __init__(self, ipDev=None, ipName=None, mask=None, optional=False, disabled=False): Res.Resource.__init__(self, "ip", optional, disabled) self.ipDev=ipDev self.ipName=ipName self.mask=mask self.id = 'ip ' + ipName + '@' + ipDev try: self.addr = socket.gethostbyname(ipName) except: self.log.error("could not resolve %s to an ip address"%self.ipName) raise ex.excInitError def __str__(self): return "%s ipdev=%s ipname=%s" % (Res.Resource.__str__(self),\ self.ipDev, self.ipName) def status(self): if self.is_up(): return rcStatus.UP else: return rcStatus.DOWN def arp_announce(self): if not which("arping"): self.log.warning("arp annouce skipped. install 'arping'") return cmd = ["arping", "-U", "-c", "1", "-I", self.ipDev, "-s", self.addr, "0.0.0.0"] self.log.info(' '.join(cmd)) qcall(cmd) def check_ping(self): raise MissImpl('check_ping') def startip_cmd(self): raise MissImpl('startip_cmd') def stopip_cmd(self): raise MissImpl('stopip_cmd') def is_up(self): ifconfig = rcIfconfig.ifconfig() if ifconfig.has_param("ipaddr", self.addr) is not None: self.log.debug("%s@%s is up" % (self.addr, self.ipDev)) return True self.log.debug("%s@%s is down" % (self.addr, self.ipDev)) return False def allow_start(self): ifconfig = rcIfconfig.ifconfig() intf = ifconfig.interface(self.ipDev) if intf is None or not intf.flag_up: self.log.error("Interface %s is not up. Cannot stack over it." % self.ipDev) raise IpDevDown(self.ipDev) if self.is_up() is True: self.log.info("%s is already up on %s" % (self.addr, self.ipDev)) raise IpAlreadyUp(self.addr) if self.check_ping(): self.log.error("%s is already up on another host" % (self.addr)) raise IpConflict(self.addr) return def start(self): try: self.allow_start() except (IpConflict, IpDevDown): raise ex.excError except IpAlreadyUp: return self.log.debug('pre-checks passed') ifconfig = rcIfconfig.ifconfig() if self.mask is None: self.mask = ifconfig.interface(self.ipDev).mask if self.mask == '': self.log.error("No netmask set on parent interface %s" % self.ipDev) raise ex.excError self.stacked_dev = ifconfig.get_stacked_dev(self.ipDev,\ self.addr,\ self.log) (ret, out) = self.startip_cmd() if ret != 0: self.log.error("failed") raise ex.excError self.arp_announce() def stop(self): if self.is_up() is False: self.log.info("%s is already down on %s" % (self.addr, self.ipDev)) return ifconfig = rcIfconfig.ifconfig() self.stacked_dev = ifconfig.get_stacked_dev(self.ipDev,\ self.addr,\ self.log) (ret, out) = self.stopip_cmd() if ret != 0: self.log.error("failed") raise ex.excError if __name__ == "__main__": for c in (Ip,) : help(c) print """i1=Ip("eth0","192.168.0.173")""" i=Ip("eth0","192.168.0.173") print "show i", i print """i.do_action("start")""" i.do_action("start") opensvc/commands/usr/local/opensvc/lib/resIpHP-UX.py010064400000000000000000000030401132305306600226730ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. "Module implement Linux specific ip management" import resIp as Res class Ip(Res.Ip): def check_ping(self): count=1 timeout=5 cmd = ['ping', '-n', repr(count), '-m', repr(timeout), '-i', self.addr] (ret, out) = self.call(cmd) if ret == 0: return True return False def startip_cmd(self): cmd = ['ifconfig', self.stacked_dev, self.addr, 'netmask', self.mask, 'up'] return self.vcall(cmd) def stopip_cmd(self): cmd = ['ifconfig', self.stacked_dev, "0.0.0.0"] return self.vcall(cmd) if __name__ == "__main__": for c in (Ip,) : help(c) opensvc/commands/usr/local/opensvc/lib/resIpLinux.py010064400000000000000000000030541132305306600231360ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. "Module implement Linux specific ip management" import resIp as Res class Ip(Res.Ip): def check_ping(self): count=1 timeout=5 cmd = ['ping', '-c', repr(count), '-W', repr(timeout), '-w', repr(timeout), self.addr] (ret, out) = self.call(cmd) if ret == 0: return True return False def startip_cmd(self): cmd = ['ifconfig', self.stacked_dev, self.addr, 'netmask', self.mask, 'up'] return self.vcall(cmd) def stopip_cmd(self): cmd = ['ifconfig', self.stacked_dev, 'down'] return self.vcall(cmd) if __name__ == "__main__": for c in (Ip,) : help(c) opensvc/commands/usr/local/opensvc/lib/resIpLinuxLxc.py010064400000000000000000000037531132305306600236130ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. "Module implement Linux/LXC specific ip management" import rcExceptions as ex import resIpLinux as Res import resIp import rcIfconfigLinuxlxc as rcIfconfig import rcStatus from subprocess import * class Ip(Res.Ip): def is_up(self): for lxc in self.svc.get_res_sets("container.lxc"): pass if lxc.status() == rcStatus.DOWN: return False ifconfig = rcIfconfig.ifconfig(self.lxcname) if ifconfig.has_param("ipaddr", self.addr) is not None: self.log.debug("%s@%s is up" % (self.addr, self.ipDev)) return True self.log.debug("%s@%s is down" % (self.addr, self.ipDev)) return False def start(self): try: self.allow_start() except (resIp.IpConflict, resIp.IpDevDown): raise ex.excError except resIp.IpAlreadyUp: return self.log.debug('pre-checks passed') def __init__(self, lxcname, ipdev, ipname): Res.Ip.__init__(self, ipdev, ipname) self.lxcname = lxcname if __name__ == "__main__": for c in (Ip,) : help(c) opensvc/commands/usr/local/opensvc/lib/resIpSunOS.py010064400000000000000000000031331132305306600230440ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. "Module implement SunOS specific ip management" import resIp as Res from subprocess import * class Ip(Res.Ip): """ define ip SunOS start/stop doAction """ def check_ping(self): timeout=2 cmd = ['ping', self.addr, "%s" % timeout] (ret, out) = self.call(cmd) if ret == 0: return True return False def startip_cmd(self): cmd=['ifconfig', self.stacked_dev, 'plumb', self.addr, \ 'netmask', '+', 'broadcast', '+', 'up'] return self.vcall(cmd) def stopip_cmd(self): cmd = ['ifconfig', self.stacked_dev, 'unplumb'] return self.vcall(cmd) if __name__ == "__main__": for c in (Ip,) : help(c) opensvc/commands/usr/local/opensvc/lib/resLoop.py010064400000000000000000000030201132305306600224500ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. import resources as Res class Loop(Res.Resource): """ basic loopback device resource """ def __init__(self,loopFile=None,optional=False,disabled=False): Res.Resource.__init__(self,"disk.loop",optional,disabled) self.loopFile = loopFile self.id = 'loop ' + loopFile def __str__(self): return "%s loopfile=%s" % (Res.Resource.__str__(self),\ self.loopFile) if __name__ == "__main__": for c in (Loop,) : help(c) print """v1=vg("myvg")""" v=vg("myvg") print "show v", v print """v.do_action("start")""" v.do_action("start") opensvc/commands/usr/local/opensvc/lib/resLoopLinux.py010064400000000000000000000045431132305306600235030ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import os import re from rcGlobalEnv import * from rcUtilities import call, which import rcStatus import resLoop as Res def file_to_loop(f): """Given a file path, returns the loop device associated. For example, /path/to/file => /dev/loop0 """ if which('losetup') is None: return None if not os.path.isfile(f): return None if rcEnv.sysname != 'Linux': return None (ret, out) = call(['losetup', '-j', f]) if len(out) == 0: return None return out.split()[0].strip(':') class Loop(Res.Loop): def is_up(self): """Returns True if the volume group is present and activated """ self.loop = file_to_loop(self.loopFile) if self.loop is None: return False return True def start(self): if self.is_up(): self.log.info("%s is already up" % self.loopFile) return 0 cmd = [ 'losetup', '-f', self.loopFile ] (ret, out) = self.vcall(cmd) if ret == 0: self.loop = file_to_loop(self.loopFile) self.log.info("%s now loops to %s" % (self.loop, self.loopFile)) return ret def stop(self): if not self.is_up(): self.log.info("%s is already down" % self.loopFile) return 0 cmd = [ 'losetup', '-d', self.loop ] (ret, out) = self.vcall(cmd) return ret def status(self): if self.is_up(): return rcStatus.UP else: return rcStatus.DOWN def __init__(self, loopFile): Res.Loop.__init__(self, loopFile) opensvc/commands/usr/local/opensvc/lib/resMount.py010064400000000000000000000045461132305306600226570ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. import resources as Res import os class Mount(Res.Resource): """Define a mount resource """ def __init__(self,mountPoint=None,device=None,fsType=None,mntOpt=None,optional=False,\ disabled=False, scsireserv=False): Res.Resource.__init__(self, "fs", optional, disabled) self.mountPoint = mountPoint self.device = device self.fsType = fsType self.mntOpt = mntOpt self.scsiReservation = scsireserv self.id = 'fs ' + device + '@' + mountPoint def set_scsireserv(): self.scsiReservation = scsireserv def start(self): if not os.path.exists(self.mountPoint): try: os.makedirs(self.mountPoint) except: self.log.info("failed to create missing mountpoint %s" % self.mountPoint) raise self.log.info("create missing mountpoint %s" % self.mountPoint) def __str__(self): return "%s mnt=%s dev=%s fsType=%s mntOpt=%s" % (Res.Resource.__str__(self),\ self.mountPoint, self.device, self.fsType, self.mntOpt) def __cmp__(self, other): """order so that deepest mountpoint can be umount first """ return cmp(self.mountPoint, other.mountPoint) if __name__ == "__main__": for c in (Mount,) : help(c) print """ m=Mount("/mnt1","/dev/sda1","ext3","rw") """ m=Mount("/mnt1","/dev/sda1","ext3","rw") print "show m", m opensvc/commands/usr/local/opensvc/lib/resMountHP-UX.py010064400000000000000000000066361132305306600234430ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. import os import rcStatus from rcGlobalEnv import rcEnv rcMounts = __import__('rcMounts'+rcEnv.sysname) import resMount as Res from rcUtilities import qcall, protected_mount import rcExceptions as ex def try_umount(self): cmd = ['umount', self.mountPoint] (ret, out) = self.vcall(cmd) if ret == 0: return 0 """ don't try to kill process using the source of a protected bind mount """ if protected_mount(dev): return 1 """ best effort kill of all processes that might block the umount operation. The priority is given to mass action reliability, ie don't contest oprator's will """ cmd = ['sync'] (ret, out) = self.vcall(cmd) for i in range(4): cmd = ['fuser', '-kc', self.mountPoint] (ret, out) = self.vcall(cmd) self.log.info('umount %s'%self.mountPoint) cmd = ['umount', self.mountPoint] ret = qcall(cmd) if ret == 0: break return ret class Mount(Res.Mount): """ define HP-UX mount/umount doAction """ def __init__(self, mountPoint, device, fsType, mntOpt): self.Mounts = rcMounts.Mounts() Res.Mount.__init__(self, mountPoint, device, fsType, mntOpt) def is_up(self): return self.Mounts.has_mount(self.device, self.mountPoint) def status(self): if self.is_up(): return rcStatus.UP else: return rcStatus.DOWN def start(self): Res.Mount.start(self) if self.is_up() is True: self.log.info("fs(%s %s) is already mounted"% (self.device, self.mountPoint)) return 0 if not os.path.exists(self.mountPoint): os.makedirs(self.mountPoint, 0755) if self.fsType != "": fstype = ['-F', self.fsType] else: fstype = [] if self.mntOpt != "": mntopt = ['-o', self.mntOpt] else: mntopt = [] cmd = ['mount']+fstype+mntopt+[self.device, self.mountPoint] (ret, out) = self.vcall(cmd) if ret != 0: raise ex.excError def stop(self): if self.is_up() is False: self.log.info("fs(%s %s) is already umounted"% (self.device, self.mountPoint)) return 0 for i in range(3): ret = try_umount(self) if ret == 0: break if ret != 0: self.log.error('failed to umount %s'%self.mountPoint) raise ex.excError if __name__ == "__main__": for c in (Mount,) : help(c) opensvc/commands/usr/local/opensvc/lib/resMountLinux.py010064400000000000000000000065631132305306700237010ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. import os import rcStatus import rcMountsLinux as rcMounts import resMount as Res from rcUtilities import qcall, protected_mount import rcExceptions as ex def try_umount(self): cmd = ['umount', self.mountPoint] (ret, out) = self.vcall(cmd) if ret == 0: return 0 """ don't try to kill process using the source of a protected bind mount """ if protected_mount(dev): return 1 """ best effort kill of all processes that might block the umount operation. The priority is given to mass action reliability, ie don't contest oprator's will """ cmd = ['sync'] (ret, out) = self.vcall(cmd) for i in range(4): cmd = ['fuser', '-kmv', self.mountPoint] (ret, out) = self.vcall(cmd) self.log.info('umount %s'%self.mountPoint) cmd = ['umount', self.mountPoint] ret = qcall(cmd) if ret == 0: break return ret class Mount(Res.Mount): """ define Linux mount/umount doAction """ def __init__(self, mountPoint, device, fsType, mntOpt): self.Mounts = rcMounts.Mounts() Res.Mount.__init__(self, mountPoint, device, fsType, mntOpt) def is_up(self): return self.Mounts.has_mount(self.device, self.mountPoint) def status(self): if self.is_up(): return rcStatus.UP else: return rcStatus.DOWN def start(self): Res.Mount.start(self) if self.is_up() is True: self.log.info("fs(%s %s) is already mounted"% (self.device, self.mountPoint)) return 0 if not os.path.exists(self.mountPoint): os.makedirs(self.mountPoint, 0755) if self.fsType != "": fstype = ['-t', self.fsType] else: fstype = [] if self.mntOpt != "": mntopt = ['-o', self.mntOpt] else: mntopt = [] cmd = ['mount']+fstype+mntopt+[self.device, self.mountPoint] (ret, out) = self.vcall(cmd) if ret != 0: raise ex.excError def stop(self): if self.is_up() is False: self.log.info("fs(%s %s) is already umounted"% (self.device, self.mountPoint)) return 0 for i in range(3): ret = try_umount(self) if ret == 0: break if ret != 0: self.log.error('failed to umount %s'%self.mountPoint) raise ex.excError if __name__ == "__main__": for c in (Mount,) : help(c) opensvc/commands/usr/local/opensvc/lib/resMountSunOS.py010064400000000000000000000062061132305306700236030ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. "Module implement SunOS specific mounts" import os import rcStatus import rcMountsSunOS as rcMounts import resMount as Res import rcExceptions as ex class Mount(Res.Mount): """ define SunOS mount/umount doAction """ def __init__(self, mountPoint, device, fsType, mntOpt): self.Mounts = rcMounts.Mounts() Res.Mount.__init__(self, mountPoint, device, fsType, mntOpt) def is_up(self): return self.Mounts.has_mount(self.device, self.mountPoint) def status(self): if self.is_up(): return rcStatus.UP else: return rcStatus.DOWN def start(self): Res.Mount.start(self) self.Mounts = rcMounts.Mounts() if self.is_up() is True: self.log.info("fs(%s %s) is already mounted"% (self.device, self.mountPoint)) return if self.fsType == 'zfs' : ret, out = self.vcall(['zfs', 'set', \ 'mountpoint='+self.mountPoint , \ self.device ]) if ret != 0 : raise ex.excError ret, out = self.vcall(['zfs', 'mount', self.device ]) if ret != 0: raise ex.excError return if self.fsType != "": fstype = ['-F', self.fsType] else: fstype = [] if self.mntOpt != "": mntopt = ['-o', self.mntOpt] else: mntopt = [] if not os.path.exists(self.mountPoint): os.makedirs(self.mountPoint, 0755) cmd = ['mount']+fstype+mntopt+[self.device, self.mountPoint] (ret, out) = self.vcall(cmd) if ret != 0: raise ex.excError def stop(self): if self.is_up() is False: self.log.info("fs(%s %s) is already umounted"% (self.device, self.mountPoint)) return (ret, out) = self.vcall(['umount', self.mountPoint]) if ret == 0 : return if self.fsType != 'lofs' : (ret, out) = self.vcall(['umount', '-f', self.mountPoint]) if ret == 0 : return self.log.error("failed") raise ex.excError if __name__ == "__main__": for c in (Mount,) : help(c) opensvc/commands/usr/local/opensvc/lib/resRsync.py010064400000000000000000000216351132305306700226520ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import os import logging from rcGlobalEnv import rcEnv from rcUtilities import which import rcExceptions as ex import rcStatus import resources as Res import datetime def lookup_snap_mod(): if rcEnv.sysname == 'Linux': return __import__('snapLvmLinux') elif rcEnv.sysname == 'HP-UX': return __import__('snapVxfsHP-UX') else: raise ex.excError def remote_fs_mounted(self, node): """Verify the remote fs is mounted before we send data. """ if self.dstfs is None: """No check has been configured. Assume the admin knows better. """ return True cmd = rcEnv.rsh.split(' ')+[node, '--', 'df', self.dst] (ret, out) = self.call(cmd) if ret != 0: raise ex.excError if self.dstfs not in out.split(): self.log.error("The destination fs %s is not mounted on node %s. refuse to sync %s to protect parent fs"%(self.dstfs, node, self.dst)) return False return True cache_remote_node_type = {} def remote_node_type(self, node, type): if type == 'drpnodes': expected_type = 'DEV' elif type == 'nodes': expected_type = self.svc.svctype else: self.log.error('expected remote node type is bogus: %s'%type) raise if node not in cache_remote_node_type: host_mode_f = os.path.join(rcEnv.pathvar, 'host_mode') cmd = rcEnv.rsh.split(' ')+[node, '--', 'LANG=C', 'cat', host_mode_f] (ret, out) = self.call(cmd) if ret != 0: raise ex.excError cache_remote_node_type[node] = out.split()[0] if cache_remote_node_type[node] == expected_type: return True self.log.error("node %s type is not '%s'. Check %s:%s"%\ (node, expected_type, node, host_mode_f)) return False def nodes_to_sync(self, type=None): """Discard the local node from the set """ if type in self.target.keys(): targets = self.target[type] else: return set([]) targets -= set([rcEnv.nodename]) for node in targets.copy(): if not remote_node_type(self, node, type): targets -= set([node]) if not need_sync(self, node): targets -= set([node]) if len(targets) == 0: raise ex.syncNoNodesToSync return targets def get_timestamp_filename(self, node): sync_timestamp_d = os.path.join(rcEnv.pathvar, 'sync', node) sync_timestamp_f = os.path.join(sync_timestamp_d, self.svc.svcname+'!'+self.dst.replace('/', '_')) return sync_timestamp_f def sync_timestamp(self, node): sync_timestamp_f = get_timestamp_filename(self, node) sync_timestamp_d = os.path.dirname(sync_timestamp_f) if not os.path.isdir(sync_timestamp_d): os.makedirs(sync_timestamp_d ,0755) with open(sync_timestamp_f, 'w') as f: f.write(str(datetime.datetime.now())+'\n') f.close() def need_sync(self, node): sync_timestamp_f = get_timestamp_filename(self, node) if not os.path.exists(sync_timestamp_f): return True try: with open(sync_timestamp_f, 'r') as f: d = f.read() if datetime.datetime.now() < datetime.datetime.strptime(d,"%Y-%m-%d %H:%M:%S.%f\n") + datetime.timedelta(minutes=self.sync_min_delay): return False f.close() except: self.log.info("failed to determine last sync date for %s to %s"%(self.src, node)) return True return True def sync(self, type): if hasattr(self, "alt_src"): """ The pre_action() has provided us with a better source to sync from. Use that """ src = self.alt_src else: src = self.src if type not in self.target.keys(): self.log.debug('%s => %s sync not applicable to %s', (src, self.dst, type)) return 0 targets = nodes_to_sync(self, type) if len(src) == 0: self.log.debug("no files to sync") raise ex.syncNoFilesToSync if self.bwlimit is not None: bwlimit = [ '--bwlimit='+self.bwlimit ] elif self.svc.bwlimit is not None: bwlimit = [ '--bwlimit='+self.svc.bwlimit ] else: bwlimit = [] for node in targets: if not need_sync(self, node): self.log.debug("skip sync of %s to %s because last sync too close"%(self.src, node)) continue if not remote_fs_mounted(self, node): continue dst = node + ':' + self.dst cmd = ['rsync'] + self.options + bwlimit + self.exclude + src cmd.append(dst) (ret, out) = self.vcall(cmd) if ret != 0: self.log.error("node %s synchronization failed (%s => %s)" % (node, src, dst)) continue sync_timestamp(self, node) return class Rsync(Res.Resource): """Defines a rsync job from local node to its remote nodes. Target nodes can be restricted to production sibblings or to disaster recovery nodes, or both. """ timeout = 3600 options = [ '-HpogDtrlvx', '--stats', '--delete', '--force', '--timeout='+str(timeout) ] def pre_action(self, rset, action): """Actions to do before resourceSet iterates through the resources to trigger action() on each one """ """Don't sync PRD services when running on !PRD node """ if self.svc.svctype == 'PRD' and rcEnv.host_mode != 'PRD': self.log.debug("won't sync a PRD service running on a !PRD node") raise ex.excAbortAction """Accept to sync from here only if the service is up """ if self.svc.status() != 0: self.log.debug("won't sync a service not up") raise ex.excAbortAction """ Is there at least one node to sync ? """ targets = set([]) rtargets = {0: set([])} need_snap = False for i, r in enumerate(rset.resources): if r.is_disabled(): continue rtargets[i] = set([]) try: if action == "syncnodes": rtargets[i] |= nodes_to_sync(r, 'nodes') else: rtargets[i] |= nodes_to_sync(r, 'drpnodes') except ex.syncNoNodesToSync: pass for node in rtargets[i].copy(): if not need_sync(r, node): rtargets[i] -= set([node]) elif r.snap: need_snap = True for i in rtargets: targets |= rtargets[i] if len(targets) == 0: self.log.debug("no node to sync") raise ex.excAbortAction if not need_snap: return snap = lookup_snap_mod() try: rset.snaps = snap.snap(self, rset, action) except ex.syncNotSnapable: raise ex.excError def post_action(self, rset, action): """Actions to do after resourceSet has iterated through the resources to trigger action() on each one """ snap = lookup_snap_mod() snap.snap_cleanup(self, rset) def syncnodes(self): try: sync(self, "nodes") except ex.syncNoFilesToSync: pass except ex.syncNoNodesToSync: self.log.debug("no node to sync") raise ex.excAbortAction def syncdrp(self): try: sync(self, "drpnodes") except ex.syncNoFilesToSync: pass except ex.syncNoNodesToSync: self.log.debug("no node to sync") raise ex.excAbortAction def __init__(self, src, dst, exclude=[], target={}, dstfs=None, snap=False, bwlimit=None, sync_min_delay=30, optional=False, disabled=False, internal=False): self.src = src self.dst = dst self.dstfs = dstfs self.exclude = exclude self.snap = snap self.target = target self.bwlimit = bwlimit self.internal = internal self.sync_min_delay = sync_min_delay Res.Resource.__init__(self, "rsync", optional, disabled) def __str__(self): return "%s src=%s dst=%s exclude=%s target=%s" % (Res.Resource.__str__(self),\ self.src, self.dst, self.exclude, str(self.target)) opensvc/commands/usr/local/opensvc/lib/resVgHP-UX.py010064400000000000000000000124671132305306700227150ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import re import os import rcExceptions as ex import resDg from subprocess import * from rcUtilities import qcall from rcGlobalEnv import rcEnv class Vg(resDg.Dg): def __init__(self, name=None, type=None, optional=False, disabled=False, scsireserv=False): self.id = 'vg ' + name resDg.Dg.__init__(self, name, 'disk.vg', optional, disabled, scsireserv) def mapfile_name(self): return os.path.join(rcEnv.pathvar, 'vg_' + self.svc.svcname + '_' + self.name + '.map') def has_it(self): """ returns True if the volume is present """ if self.is_active(): return True if not os.path.exists(self.mapfile_name()): return False if self.is_imported(): return True return False def diskupdate(self): """ this one is exported as a service command line arg """ cmd = [ 'vgexport', '-m', self.mapfile_name(), '-p', '-s', self.name ] ret = qcall(cmd) if ret != 0: raise ex.excError def is_active(self): cmd = [ 'vgdisplay', self.name ] process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() if not "available" in buff[0]: return False return True def is_imported(self): if not os.path.exists(self.mapfile_name()): return False if self.dsf: dsfflag = '-N' else: dsfflag = '' cmd = [ 'vgimport', '-m', self.mapfile_name(), '-s', '-p', dsfflag, self.name ] process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() if not "already exists" in buff[1]: return False return True def is_up(self): """Returns True if the volume group is present and activated """ if not self.is_imported(): return False if not self.is_active(): return False return True def do_import(self): if self.is_imported(): self.log.info("%s is already imported" % self.name) return if self.dsf: dsfflag = '-N' else: dsfflag = '' cmd = [ 'vgimport', '-m', self.mapfile_name(), '-s', dsfflag, self.name ] self.log.info(' '.join(cmd)) process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) buff = process.communicate() if len(buff[1]) > 0 and buff[1] != "vgimport: ": self.log.error('error:\n' + buff[1]) if len(buff[0]) > 0: self.log.debug('output:\n' + buff[0]) if process.returncode != 0: raise ex.excError def do_export(self): if not self.is_imported(): self.log.info("%s is already exported" % self.name) return cmd = [ 'vgexport', '-m', self.mapfile_name(), '-s', self.name ] (ret, out) = self.vcall(cmd) if ret != 0: raise ex.excError def do_activate(self): if self.is_active(): self.log.info("%s is already available" % self.name) return cmd = ['vgchange', '-a', 'y', self.name] (ret, out) = self.vcall(cmd) if ret != 0: raise ex.excError def do_deactivate(self): if not self.is_active(): self.log.info("%s is already unavailable" % self.name) return cmd = ['vgchange', '-a', 'n', self.name] (ret, out) = self.vcall(cmd) if ret != 0: raise ex.excError def do_start(self): self.do_import() self.do_activate() def do_stop(self): self.do_deactivate() self.do_export() def disklist(self): need_export = False if not self.is_imported(): self.do_import() need_export = True cmd = ['strings', '/etc/lvmtab'] (ret, out) = self.call(cmd) if ret != 0: raise ex.excError tab = out.split('\n') insection = False self.disks = set([]) for e in tab: """ move to the first disk of the vg """ if e == '/dev/'+self.name: insection = True continue if not insection: continue if e == "_KDI": continue if "/dev/dsk" not in e and "/dev/disk" not in e: break self.disks |= set([e]) if need_export: self.do_export() return self.disks opensvc/commands/usr/local/opensvc/lib/resVgHP-VM.py010064400000000000000000000040671132354410400226750ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import re import os import rcExceptions as ex import resDg from subprocess import * from rcUtilities import qcall from rcGlobalEnv import rcEnv class Vg(resDg.Dg): def __init__(self, name=None, type=None, optional=False, disabled=False, scsireserv=False): self.id = 'vm dg ' + name resDg.Dg.__init__(self, name, 'disk.vg', optional, disabled, scsireserv) def has_it(self): return True def is_up(self): return True def do_start(self): pass def do_stop(self): pass def disklist(self): cmd = ['hpvmstatus', '-P', self.svc.vmname] (ret, out) = self.call(cmd) if ret != 0: raise ex.excError tab = out.split('\n') insection = False self.disks = set([]) for e in tab: """ move to the first disk of the vg """ if e == '/dev/'+self.name: insection = True continue if not insection: continue if e == "_KDI": continue if "/dev/dsk" not in e and "/dev/disk" not in e: break self.disks |= set([e]) if need_export: self.do_export() return self.disks opensvc/commands/usr/local/opensvc/lib/resVgLinux.py010064400000000000000000000110641132305306700231430ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import re import os import rcExceptions as ex import resDg def get_blockdev_sd_slaves(syspath): slaves = set() for s in os.listdir(syspath): if re.match('^sd[a-z]*', s) is not None: slaves.add('/dev/' + s) continue deeper = os.path.join(syspath, s, 'slaves') if os.path.isdir(deeper): slaves |= get_blockdev_sd_slaves(deeper) return slaves def major(driver): path = os.path.join(os.path.sep, 'proc', 'devices') try: f = open(path) except: raise for line in f.readlines(): words = line.split() if len(words) == 2 and words[1] == driver: f.close() return int(words[0]) f.close() raise class Vg(resDg.Dg): def __init__(self, name=None, type=None, optional=False, disabled=False, scsireserv=False): self.id = 'vg ' + name resDg.Dg.__init__(self, name, 'disk.vg', optional, disabled, scsireserv) def has_it(self): """Returns True if the volume is present """ cmd = [ 'vgs', '--noheadings', '-o', 'name' ] (ret, out) = self.call(cmd) if self.name in out.split(): return True return False def is_up(self): """Returns True if the volume group is present and activated """ if not self.has_it(): return False cmd = [ 'lvs', '--noheadings', '-o', 'lv_attr', self.name ] (ret, out) = self.call(cmd) if re.match(' ....-[-o]', out, re.MULTILINE) is None: return True return False def do_start(self): if self.is_up(): self.log.info("%s is already up" % self.name) return 0 cmd = [ 'vgchange', '-a', 'y', self.name ] (ret, out) = self.vcall(cmd) if ret != 0: raise ex.excError def do_stop(self): if not self.is_up(): self.log.info("%s is already down" % self.name) return 0 cmd = [ 'vgchange', '-a', 'n', self.name ] (ret, out) = self.vcall(cmd) if ret != 0: raise ex.excError def disklist(self): if not self.has_it(): return set() if self.disks != set() : return self.disks disks = set() """Get volume group's PV from the clear text metadata backup file """ config = os.path.join(os.path.sep, 'etc', 'lvm', 'backup', self.name) if not os.path.exists(config): return disks try: f = open(config) except: self.log.error("can not open %s" % config) raise pvs = set() for line in f.readlines(): words = line.split() if len(words) > 3 and words[0] == 'device': pvs.add(words[2].strip('"')) """If PV is a device map, replace by its sysfs name (dm-*) If device map has slaves, replace by its slaves """ dm_major = major('device-mapper') try: lo_major = major('loop') except: lo_major = 0 for pv in pvs: try: statinfo = os.stat(pv) except: self.log.error("can not stat %s" % pv) raise if os.major(statinfo.st_rdev) == dm_major: dm = 'dm-' + str(os.minor(statinfo.st_rdev)) syspath = '/sys/block/' + dm + '/slaves' disks |= get_blockdev_sd_slaves(syspath) elif lo_major != 0 and os.major(statinfo.st_rdev) == lo_major: self.log.debug("skip loop device %s from disklist"%pv) pass else: disks.add(pv) self.log.debug("found disks %s held by vg %s" % (disks, self.name)) self.disks = disks return disks opensvc/commands/usr/local/opensvc/lib/resZfs.py010064400000000000000000000114111132305306700223050ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. """Module providing ZFS resources """ from rcGlobalEnv import rcEnv import resDg from rcUtilities import qcall import re class Pool(resDg.Dg): """ basic pool resource """ def __init__(self, name=None, type=None, optional=False, disabled=False, scsireserv=False): self.id = 'pool ' + name resDg.Dg.__init__(self, name, 'disk.zpool', optional, disabled, scsireserv) def has_it(self): """Returns True if the pool is present """ ret = qcall( [ 'zpool', 'list', self.name ] ) if ret == 0 : return True return False def is_up(self): """Returns True if the pool is present and activated """ if not self.has_it(): return False cmd = [ 'zpool', 'list', '-H', '-o', 'health', self.name ] (ret, out) = self.call(cmd) if out.strip() == "ONLINE" : return True return False def do_start(self): if self.is_up(): self.log.info("%s is already up" % self.name) return 0 cmd = [ 'zpool', 'import', self.name ] (ret, out) = self.vcall(cmd) return ret def do_stop(self): if not self.is_up(): self.log.info("%s is already down" % self.name) return 0 cmd = [ 'zpool', 'export', self.name ] (ret, out) = self.vcall(cmd) return ret def disklist(self): """disklist() search zpool vdevs from output of : zpool status poolname if status cmd == 0 else output of : zpool import output if status cmd == 0 disklist(self) update self.disks[] """ if len(self.disks) > 0 : return self.disks disks = set() cmd = [ 'zpool', 'status', self.name ] (ret, out) = self.call(cmd) if ret != 0 : matchedPool=False cmd = [ 'zpool', 'import' ] (ret, out) = self.call(cmd) if ret != 0 : return [] for line in out.split('\n'): if re.match('^ pool: ', line) is not None: # This is pool: xxxx # set watchNext if it is serached pool # else disable watchNext if line == ' pool: ' + self.name : if matchedPool == True : raise Exception("duplicated pools available") matchedPool = True watchNext = True else : watchNext = False elif watchNext == True : # only look for 'tab c*d vdev entries if re.match('^\t ', line) is not None: if re.match('^\t mirror', line) is not None: continue if re.match('^\t raid', line) is not None: continue disk = line.split()[0] disks.add("/dev/rdsk/" + disk ) else : for line in out.split('\n'): if re.match('^\t ', line) is not None: if re.match('^\t mirror', line) is not None: continue if re.match('^\t raid', line) is not None: continue # vdev entry disk=line.split()[0] if re.match("^.*", disk) is not None : disks.add("/dev/rdsk/" + disk ) self.log.debug("found disks %s held by pool %s" % (disks, self.name)) self.disks = disks return disks if __name__ == "__main__": for c in (Pool,) : help(c) print """p=Pool("svczfs1")""" p=Pool("svczfs1") print "show p", p print """p.do_action("start")""" p.do_action("start") print """p.do_action("stop")""" p.do_action("stop") opensvc/commands/usr/local/opensvc/lib/resources.py010064400000000000000000000145731132305306700230570ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. import rcExceptions as exc import rcStatus import logging import rcUtilities class Resource(object): """Define basic resource properties: type, optional, disabled a Resource should provide do_action(action): with action into (start/stop/status) """ id = None def __init__(self, type=None, optional=False, disabled=False): self.type = type self.optional = optional self.disabled = disabled self.log = logging.getLogger(str(type).upper()) if id is None: self.id = type def __str__(self): output="object=%s type=%s" % (self.__class__.__name__,self.type) if self.optional : output+=" opt="+str(self.optional) if self.disabled : output+=" disa="+str(self.disabled) return output def __cmp__(self, other): """resources needed to be started or stopped in a specific order should redefine that. For now consider all resources of a set equals """ return 0 def is_optional(self): return self.optional def is_disabled(self): return self.disabled def set_optional(self): self.optional=True def unset_optional(self): self.optional=False def disable(self): self.disabled=True def enable(self): self.disabled=False def do_action(self, action): if hasattr(self, action): getattr(self, action)() return """Every class inheriting resource should define start() stop() status() Alert on these minimal implementation requirements """ if action in ("start","stop","status") : raise exc.excUndefined(action,self.__class__.__name__,\ "Resource.do_action") def action(self, action=None): """ action() try to call do_action() on self return if action is not None or if self is disabled return status depends on optional property value: if self is optional then return True else return do_action() return value """ if action == None: return True if self.disabled: return True try : self.do_action(action) except exc.excUndefined , ex: print ex return False except exc.excError: if self.optional: pass else: raise exc.excError def status(self): """aggregate status a ResourceSet """ s = rcStatus.Status() for r in self.resources: if r.is_disabled(): continue s += r.status() return s.status def print_status(self): return rcStatus.print_status(self.id, self.status()) def call(self, cmd=['/bin/false'], info=False, errlog=True): """Use subprocess module functions to do a call """ return rcUtilities.call(cmd, self.log, info, errlog) def vcall(self, cmd): """Use subprocess module functions to do a call and log the command line using the resource logger """ return rcUtilities.vcall(cmd, self.log) def disklist(self): """List disks the resource holds. Some resource have none, and can leave this function as is. """ return set() class ResourceSet(Resource): """ Define Set of same type resources Example 1: ResourceSet("fs",[m1,m2]) Example 2: r=ResourceSet("fs",[ip1]) It define the resource type """ def __init__(self,type=None,resources=[],optional=False,disabled=False): self.resources=resources Resource.__init__(self,type,optional,disabled) def __iadd__(self,r): """Example 1 iadd another ResourceSet: R+=ResSet ... R+=[m1,m2] Example 2 : iadd a single Resource : R+=ip1 """ if isinstance(r,ResourceSet) : self.resources.extend(r.resources) elif isinstance(r,Resource) : """ Setup a back pointer to the resource set """ r.rset = self self.resources.append(r) if hasattr(r, 'pre_action'): self.pre_action = r.pre_action if hasattr(r, 'post_action'): self.post_action = r.post_action return (self) def __str__(self): output="resSet %s [" % ( Resource.__str__(self) ) for r in self.resources: output+= " (%s)" % (r.__str__()) return "%s]" % (output) def pre_action(self, rset=None, action=None): pass def post_action(self, rset=None, action=None): pass def action(self,action=None): """Call action on each resource of the ResourceSet """ if action in ["fs", "start"]: self.resources.sort() else: self.resources.sort(reverse=True) try: self.pre_action(self, action) except exc.excAbortAction: return for r in self.resources: try: r.action(action) except exc.excAbortAction: break self.post_action(self, action) if __name__ == "__main__": for c in (Resource,ResourceSet) : help(c) print """m1=Resource("Type1")""" m1=Resource("Type1") print "m1=",m1 print """m2=Resource("Type1")""" m2=Resource("Type1") print "m1=",m1 print "m2=",m2 print """sets=ResourceSet("TypeRes2")""" sets=ResourceSet("TypeRes2") print "sets=", sets print """sets+=m1""" sets+=m1 print "sets=", sets print """sets+=m2""" sets+=m2 print "sets=", sets opensvc/commands/usr/local/opensvc/lib/scsiReserv.py010064400000000000000000000125411132330660600231660ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. import resources as Res import uuid import re import time import rcStatus import rcExceptions as ex from rcUtilities import which from subprocess import * from rcGlobalEnv import rcEnv hostId = __import__('hostid'+rcEnv.sysname) class ScsiReserv(Res.Resource): """Define method to acquire and release scsi SPC-3 persistent reservations on disks held by a service """ def __init__(self, disks): self.hostid = '0x'+hostId.hostid() self.disks = disks self.preempt_timeout = 10 self.prtype = '5' Res.Resource.__init__(self, "scsireserv") def ack_unit_attention(self, d): raise ex.notImplemented def disk_registered(self, disk): raise ex.notImplemented def disk_register(self, disk): raise ex.notImplemented def disk_unregister(self, disk): raise ex.notImplemented def get_reservation_key(self, disk): raise ex.notImplemented def disk_reserved(self, disk): raise ex.notImplemented def disk_release(self, disk): raise ex.notImplemented def disk_reserve(self, disk): raise ex.notImplemented def disk_preempt_reservation(self, disk, oldkey): raise ex.notImplemented def ack_all_unit_attention(self): for d in self.disks: if self.ack_unit_attention(d) != 0: return 1 return 0 def register(self): r = 0 for d in self.disks: try: r += self.ack_unit_attention(d) r += self.disk_register(d) except ex.excScsiPrNotsupported: continue return r def unregister(self): r = 0 for d in self.disks: try: r += self.ack_unit_attention(d) if not self.disk_registered(d): continue r += self.disk_unregister(d) except ex.excScsiPrNotsupported: continue return r def disk_wait_reservation(self, disk): i = 0 while i>0: i -= 1 if self.disk_reserved(disk): self.log.info("reservation acquired for disk %s" % disk) return 0 time.sleep(1) self.log.error("timed out waiting for reservation for disk %s" % disk) return 1 def reserve(self): r = 0 for d in self.disks: try: r += self.ack_unit_attention(d) key = self.get_reservation_key(d) if key is None: r += self.disk_reserve(d) elif key == self.hostid: continue else: r += self.disk_preempt_reservation(d, key) r += self.disk_wait_reservation(d) except ex.excScsiPrNotsupported: continue return r def release(self): r = 0 for d in self.disks: try: r += self.ack_unit_attention(d) if not self.disk_reserved(d): continue r += self.disk_release(d) except ex.excScsiPrNotsupported: continue return r def checkreserv(self): if self.ack_all_unit_attention() != 0: return rcStatus.WARN r = rcStatus.Status() for d in self.disks: try: key = self.get_reservation_key(d) if key is None: self.log.debug("disk %s is not reserved" % d) r += rcStatus.WARN elif key != self.hostid: self.log.debug("disk %s is reserved by another host whose key is %s" % (d, key)) r += rcStatus.DOWN else: self.log.debug("disk %s is correctly reserved" % d) r += rcStatus.UP except ex.excScsiPrNotsupported: continue return r.status def scsireserv(self): r = 0 r += self.register() r += self.reserve() return r def scsirelease(self): r = 0 r += self.release() r += self.unregister() return r def scsicheckreserv(self): return self.checkreserv() def status(self): return self.scsicheckreserv() def start(self): if self.scsireserv() != 0: raise ex.excError def stop(self): if self.scsirelease() != 0: raise ex.excError opensvc/commands/usr/local/opensvc/lib/scsiReservHP-UX.py010064400000000000000000000123651132335742600237620ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. import resources as Res import uuid import re import time import rcStatus import rcExceptions as ex from rcUtilities import which from subprocess import * import scsiReserv def scsireserv_supported(): if which('scu') is None: return False return True def mpath_to_path(disks): l = [] for disk in disks: if "/dev/dsk" in disk: l.append(disk.replace("/dev/dsk", "/dev/rdsk")) continue if "/dev/disk" not in disk: continue cmd = ['ioscan', '-F', '-m', 'dsf', disk] p = Popen(cmd, stderr=None, stdout=PIPE, close_fds=True) buff = p.communicate() ret = p.returncode if ret != 0: continue a = buff[0].split(':') if len(a) != 2: continue b = a[1].split() for d in b: l.append(d.replace("/dev/dsk", "/dev/rdsk")) return l class ScsiReserv(scsiReserv.ScsiReserv): def __init__(self, disks): scsiReserv.ScsiReserv.__init__(self, disks) self.prtype = 'wero' self.disks = mpath_to_path(disks) self.leg_mpath_disable() def leg_mpath_disable(self): cmd = ['scsimgr', 'get_attr', '-p', '-a', 'leg_mpath_enable'] p = Popen(cmd, stderr=None, stdout=PIPE, close_fds=True) buff = p.communicate() ret = p.returncode if ret != 0: self.log.error("can not fetch 'leg_mpath_enable' value") raise ex.excError if 'false' in buff[0]: return cmd = ['scsimgr', 'save_attr', '-a', 'leg_mpath_enable=false'] self.log.info(' '.join(cmd)) p = Popen(cmd, stderr=None, stdout=PIPE, close_fds=True) buff = p.communicate() ret = p.returncode if ret != 0: self.log.error("can not set 'leg_mpath_enable' value") raise ex.excError def ack_unit_attention(self, d): return 0 def disk_registered(self, disk): cmd = [ 'scu', '-f', disk, 'show', 'keys' ] (ret, out) = self.call(cmd) if ret != 0: self.log.error("failed to read registrations for disk %s" % disk) if self.hostid in out: return True return False def disk_register(self, disk): cmd = [ 'scu', '-f', disk, 'preserve', 'register', 'skey', self.hostid ] (ret, out) = self.vcall(cmd) if ret != 0: self.log.error("failed to register key %s with disk %s" % (self.hostid, disk)) return ret def disk_unregister(self, disk): cmd = [ 'scu', '-f', disk, 'preserve', 'register', 'skey', '0', 'key', self.hostid ] (ret, out) = self.vcall(cmd) if ret != 0: self.log.error("failed to unregister key %s with disk %s" % (self.hostid, disk)) return ret def get_reservation_key(self, disk): cmd = [ 'scu', '-f', disk, 'show', 'reservation' ] (ret, out) = self.call(cmd) if ret != 0: self.log.error("failed to list reservation for disk %s" % disk) if 'Reservation Key' not in out: return None for line in out.split('\n'): if 'Reservation Key' in line: return line.split()[-1] raise Exception() def disk_reserved(self, disk): cmd = [ 'scu', '-f', disk, 'show', 'reservation' ] (ret, out) = self.call(cmd) if ret != 0: self.log.error("failed to read reservation for disk %s" % disk) if self.hostid in out: return True return False def disk_release(self, disk): cmd = [ 'scu', '-f', disk, 'preserve', 'release', 'key', self.hostid, 'type', self.prtype ] (ret, out) = self.vcall(cmd) if ret != 0: self.log.error("failed to release disk %s" % disk) return ret def disk_reserve(self, disk): cmd = [ 'scu', '-f', disk, 'preserve', 'reserve', 'key', self.hostid, 'type', self.prtype ] (ret, out) = self.vcall(cmd) if ret != 0: self.log.error("failed to reserve disk %s" % disk) return ret def disk_preempt_reservation(self, disk, oldkey): cmd = [ 'scu', '-f', disk, 'preserve', 'preempt', 'key', self.hostid, 'skey', oldkey, 'type', self.prtype ] (ret, out) = self.vcall(cmd) if ret != 0: self.log.error("failed to preempt reservation for disk %s" % disk) return ret opensvc/commands/usr/local/opensvc/lib/scsiReservLinux.py010064400000000000000000000110341132311734500242020ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. import resources as Res import uuid import re import time import rcStatus import rcExceptions as ex from rcUtilities import which from subprocess import * import scsiReserv def scsireserv_supported(): if which('sg_persist') is None: return False return True class ScsiReserv(scsiReserv.ScsiReserv): def ack_unit_attention(self, d): i = self.preempt_timeout while i>0: i -= 1 cmd = [ 'sg_persist', '-n', '-r', d ] p = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True) out = p.communicate() ret = p.returncode if "unsupported service action" in out[1]: self.log.error("disk %s does not support persistent reservation" % d) raise ex.excScsiPrNotsupported if "Unit Attention" in out[0] or ret != 0: self.log.info("disk %s reports 'Unit Attention' ... waiting" % d) time.sleep(1) continue break if i == 0: self.log.error("timed out waiting for 'Unit Attention' to go away on disk %s" % d) return 1 return 0 def disk_registered(self, disk): cmd = [ 'sg_persist', '-n', '-k', disk ] (ret, out) = self.call(cmd) if ret != 0: self.log.error("failed to read registrations for disk %s" % disk) if self.hostid in out: return True return False def disk_register(self, disk): cmd = [ 'sg_persist', '-n', '--out', '--register-ignore', '--param-sark='+self.hostid, disk ] (ret, out) = self.vcall(cmd) if ret != 0: self.log.error("failed to register key %s with disk %s" % (self.hostid, disk)) return ret def disk_unregister(self, disk): cmd = [ 'sg_persist', '-n', '--out', '--register-ignore', '--param-rk='+self.hostid, disk ] (ret, out) = self.vcall(cmd) if ret != 0: self.log.error("failed to unregister key %s with disk %s" % (self.hostid, disk)) return ret def get_reservation_key(self, disk): cmd = [ 'sg_persist', '-n', '-r', disk ] (ret, out) = self.call(cmd) if ret != 0: self.log.error("failed to list reservation for disk %s" % disk) if 'Key=' not in out: return None for w in out.split(): if 'Key=' in w: return w.split('=')[1] raise Exception() def disk_reserved(self, disk): cmd = [ 'sg_persist', '-n', '-r', disk ] (ret, out) = self.call(cmd) if ret != 0: self.log.error("failed to read reservation for disk %s" % disk) if self.hostid in out: return True return False def disk_release(self, disk): cmd = [ 'sg_persist', '-n', '--out', '--release', '--param-rk='+self.hostid, '--prout-type='+self.prtype, disk ] (ret, out) = self.vcall(cmd) if ret != 0: self.log.error("failed to release disk %s" % disk) return ret def disk_reserve(self, disk): cmd = [ 'sg_persist', '-n', '--out', '--reserve', '--param-rk='+self.hostid, '--prout-type='+self.prtype, disk ] (ret, out) = self.vcall(cmd) if ret != 0: self.log.error("failed to reserve disk %s" % disk) return ret def disk_preempt_reservation(self, disk, oldkey): cmd = [ 'sg_persist', '-n', '--out', '--preempt-abort', '--param-sark='+oldkey, '--param-rk='+self.hostid, '--prout-type='+self.prtype, disk ] (ret, out) = self.vcall(cmd) if ret != 0: self.log.error("failed to preempt reservation for disk %s" % disk) return ret opensvc/commands/usr/local/opensvc/lib/snapLvmLinux.py010064400000000000000000000125441132305306700235010ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import os from rcGlobalEnv import rcEnv from rcUtilities import which, qcall, protected_mount import rcExceptions as ex def find_mount(rs, dir): """Sort mounts from deepest to shallowest and return the first mount whose 'mountPoint' is matching 'dir' """ for m in sorted(rs.resources, reverse=True): if m.mountPoint in dir: return m return None def find_mounts(self, mounts_h): rs = self.svc.get_res_sets("fs")[0] if rs is None: self.log.error("can not find fs resources encapsulating %s to snap"%r.src) raise ex.syncNotSnapable for src in self.src: m = find_mount(rs, src) if m is None: self.log.error("can not find fs resources encapsulating %s to snap"%self.src) raise ex.syncNotSnapable mounts_h[src] = m return mounts_h def lv_exists(self, device): if qcall(['lvs', device]) == 0: return True return False def lv_info(self, device): (ret, buff) = self.call(['lvs', '-o', 'vg_name,lv_name,lv_size', '--noheadings', '--units', 'm', device]) if ret != 0: return (None, None, None) info = buff.split() lv_size = float(info[2].split('M')[0]) return (info[0], info[1], lv_size) def snap(self, rset, action): mounts_h = {} for r in rset.resources: if r.snap is not True and r.snap is not False: r.log.error("service configuration error: 'snap' must be 'true' or 'false'. default is 'false'") raise ex.syncConfigSyntaxError if not r.snap: continue if (action == "syncnodes" and not 'nodes' in r.target) or \ (action == "syncdrp" and not 'drpnodes' in r.target): continue mounts_h = find_mounts(r, mounts_h) mounts = set(mounts_h.values()) snaps = {} try: for m in mounts: snap_name = '' snap_mnt = '' (vg_name, lv_name, lv_size) = lv_info(self, m.device) if lv_name is None: self.log.error("can not snap %s: not a logical volume"%m.device) raise ex.syncNotSnapable snap_name = 'osvc_sync_'+lv_name if lv_exists(self, os.path.join(os.sep, 'dev', vg_name, snap_name)): self.log.error("snap of %s already exists"%(lv_name)) raise ex.syncSnapExists (ret, buff) = self.vcall(['lvcreate', '-s', '-L'+str(lv_size//10)+'M', '-n', snap_name, os.path.join(vg_name, lv_name)]) if ret != 0: raise ex.syncSnapCreateError snap_mnt = '/service/tmp/osvc_sync_'+vg_name+'_'+lv_name if not os.path.exists(snap_mnt): os.makedirs(snap_mnt, 0755) snap_dev = os.path.join(os.sep, 'dev', vg_name, snap_name) (ret, buff) = self.vcall(['mount', '-o', 'ro', snap_dev, snap_mnt]) if ret != 0: raise ex.syncSnapMountError snaps[m.mountPoint] = dict(lv_name=lv_name, vg_name=vg_name, snap_name=snap_name, snap_mnt=snap_mnt, snap_dev=snap_dev) except (ex.syncNotSnapable, ex.syncSnapExists, ex.syncSnapMountError): """Clean up the mess """ snap_cleanup(self, snaps) raise ex.excError except: raise """Update src dirs of every sync resource to point to an existing snap """ for i, r in enumerate(rset.resources): r.alt_src = list(r.src) for j, src in enumerate(r.alt_src): if not mounts_h.has_key(src): continue mnt = mounts_h[src].mountPoint snap_mnt = snaps[mnt]['snap_mnt'] rset.resources[i].alt_src[j] = src.replace(os.path.join(mnt), os.path.join(snap_mnt), 1) return snaps def snap_cleanup(self, rset): if not hasattr(rset, 'snaps'): return snaps = rset.snaps for s in snaps.keys(): if protected_mount(snaps[s]['snap_mnt']): self.log.error("the snapshot is no longer mounted in %s. panic."%snaps[s]['snap_mnt']) raise ex.excError cmd = ['fuser', '-kmv', snaps[s]['snap_mnt']] (ret, out) = self.vcall(cmd) cmd = ['umount', snaps[s]['snap_mnt']] (ret, out) = self.vcall(cmd) cmd = ['lvremove', '-f', snaps[s]['snap_dev']] (ret, buff) = self.vcall(cmd) for i, r in enumerate(rset.resources): if hasattr(rset.resources[i], 'alt_src'): delattr(rset.resources[i], 'alt_src') opensvc/commands/usr/local/opensvc/lib/snapVxfsHP-UX.py010064400000000000000000000131421132305306700234260ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import os from rcGlobalEnv import rcEnv from rcUtilities import which, qcall, protected_mount import rcExceptions as ex def find_mount(rs, dir): """Sort mounts from deepest to shallowest and return the first mount whose 'mountPoint' is matching 'dir' """ for m in sorted(rs.resources, reverse=True): if m.mountPoint in dir: return m return None def find_mounts(self, mounts_h): rs = self.svc.get_res_sets("fs")[0] if rs is None: self.log.error("can not find fs resources encapsulating %s to snap"%r.src) raise ex.syncNotSnapable for src in self.src: m = find_mount(rs, src) if m is None: self.log.error("can not find fs resources encapsulating %s to snap"%self.src) raise ex.syncNotSnapable mounts_h[src] = m return mounts_h def lv_exists(self, device): if qcall(['lvdisplay', device]) == 0: return True return False def lv_info(self, device): (ret, buff) = self.call(['lvdisplay', device]) if ret != 0: return (None, None, None) vg_name = None lv_name = None lv_size = 0 for line in buff.split('\n'): if "VG Name" in line: vg_name = line.split()[-1] if "LV Name" in line: lv_name = line.split()[-1] if "LV Size" in line: lv_size = int(line.split()[-1]) return (vg_name, lv_name, lv_size) def snap(self, rset, action): mounts_h = {} for r in rset.resources: if r.snap is not True and r.snap is not False: r.log.error("service configuration error: 'snap' must be 'true' or 'false'. default is 'false'") raise ex.syncConfigSyntaxError if not r.snap: continue if (action == "syncnodes" and not 'nodes' in r.target) or \ (action == "syncdrp" and not 'drpnodes' in r.target): continue mounts_h = find_mounts(r, mounts_h) mounts = set(mounts_h.values()) snaps = {} try: for m in mounts: snap_name = '' snap_mnt = '' (vg_name, lv_name, lv_size) = lv_info(self, m.device) if lv_name is None: self.log.error("can not snap %s: not a logical volume"%m.device) raise ex.syncNotSnapable snap_name = 'osvc_sync_'+os.path.basename(lv_name) if lv_exists(self, os.path.join(vg_name, snap_name)): self.log.error("snap of %s already exists"%(lv_name)) raise ex.syncSnapExists (ret, buff) = self.vcall(['lvcreate', '-L', str(lv_size//10)+'M', '-n', snap_name, vg_name]) if ret != 0: raise ex.syncSnapCreateError snap_mnt = '/service/tmp/osvc_sync_'+os.path.basename(vg_name)+'_'+os.path.basename(lv_name) if not os.path.exists(snap_mnt): os.makedirs(snap_mnt, 0755) snap_dev = os.path.join(vg_name, snap_name) (ret, buff) = self.vcall(['mount', '-F', 'vxfs', '-o', 'ro,snapof='+m.device, snap_dev, snap_mnt]) if ret != 0: raise ex.syncSnapMountError snaps[m.mountPoint] = dict(lv_name=lv_name, vg_name=vg_name, snap_name=snap_name, snap_mnt=snap_mnt, snap_dev=snap_dev) except (ex.syncNotSnapable, ex.syncSnapExists, ex.syncSnapMountError): """Clean up the mess """ snap_cleanup(self, snaps) raise ex.excError except: raise """Update src dirs of every sync resource to point to an existing snap """ for i, r in enumerate(rset.resources): r.alt_src = list(r.src) for j, src in enumerate(r.alt_src): if not mounts_h.has_key(src): continue mnt = mounts_h[src].mountPoint snap_mnt = snaps[mnt]['snap_mnt'] rset.resources[i].alt_src[j] = src.replace(os.path.join(mnt), os.path.join(snap_mnt), 1) return snaps def snap_cleanup(self, rset): if not hasattr(rset, 'snaps'): return snaps = rset.snaps for s in snaps.keys(): if protected_mount(snaps[s]['snap_mnt']): self.log.error("the snapshot is no longer mounted in %s. panic."%snaps[s]['snap_mnt']) raise ex.excError """ fuser on HP-UX outs to stderr ... """ cmd = ['fuser', '-kc', snaps[s]['snap_mnt']] ret = qcall(cmd) cmd = ['umount', snaps[s]['snap_mnt']] (ret, out) = self.vcall(cmd) cmd = ['lvremove', '-f', snaps[s]['snap_dev']] (ret, buff) = self.vcall(cmd) for i, r in enumerate(rset.resources): if hasattr(rset.resources[i], 'alt_src'): delattr(rset.resources[i], 'alt_src') opensvc/commands/usr/local/opensvc/lib/svc.py010064400000000000000000000200131132305306700216220ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. from resources import Resource, ResourceSet from freezer import Freezer import rcStatus from rcGlobalEnv import rcEnv import rcExceptions as ex from lock import svclock, svcunlock import xmlrpcClient def fork_dblogger(self, action, begin, end, actionlogfile): import os try: if os.fork() > 0: """ return to parent execution """ return except: """ no dblogging will be done. too bad. """ return """ separate the son from the father """ os.chdir('/') os.setsid() os.umask(0) try: pid = os.fork() if pid > 0: os._exit(0) except: os._exit(1) xmlrpcClient.end_action(self, action, begin, end, actionlogfile) xmlrpcClient.svcmon_update(self, self.group_status()) os.unlink(actionlogfile) os._exit(0) class Svc(Resource, Freezer): """Service class define a Service Resource It contain list of ResourceSet where each ResourceSets contain same resource type """ def __init__(self, svcname=None, type="hosted", optional=False, disabled=False): """usage : aSvc=Svc(type)""" if self.frozen(): delattr(self.startip) delattr(self.stopip) delattr(self.mount) delattr(self.umount) self.svcname = svcname self.hostid = rcEnv.nodename self.resSets = [] self.type2resSets = {} self.disks = set([]) Resource.__init__(self, type, optional, disabled) Freezer.__init__(self, svcname) def __cmp__(self, other): """order by service name """ return cmp(self.svcname, other.svcname) def __iadd__(self, r): """svc+=aResourceSet svc+=aResource """ if r.type in self.type2resSets: self.type2resSets[r.type] += r elif isinstance(r, ResourceSet): self.resSets.append(r) self.type2resSets[r.type] = r elif isinstance(r, Resource): R = ResourceSet(r.type, [r]) self.__iadd__(R) else: # Error pass return self def get_res_sets(self, type): return [ r for r in self.resSets if r.type == type ] def has_res_set(self, type): if len(get_res_sets(type)) > 0: return True else: return False def sub_set_action(self, type=None, action=None): """Call action on each member of the subset of specified type """ for r in self.get_res_sets(type): try: r.action(action) except ex.excAbortAction: break def __str__(self): output="Service %s available resources:" % (Resource.__str__(self)) for k in self.type2resSets.keys() : output += " %s" % k output+="\n" for r in self.resSets: output+= " [%s]" % (r.__str__()) return output def status(self, type_list): """aggregate status a service """ s = rcStatus.Status() for t in type_list: for r in self.get_res_sets(t): s += r.status() return s.status def print_status(self, type_list): """print each resource status for a service """ for t in type_list: for r in self.get_res_sets(t): r.action("print_status") rcStatus.print_status("overall", self.status()) def group_status(self, type_list): """print each resource status for a service """ status = {} groups = ["container", "ip", "disk", "fs"] moregroups = groups + ["overall"] for group in moregroups: status[group] = rcStatus.Status(rcStatus.NA) for t in type_list: group = t.split('.')[0] if group not in groups: raise for r in self.get_res_sets(t): status[group] += r.status() status["overall"] += r.status() return status def disklist(self): """List all disks held by all resources of this service """ disks = set() for rs in self.resSets: for r in rs.resources: disks |= r.disklist() self.log.debug("found disks %s held by service" % disks) return disks def startapp(self): self.sub_set_action("app", "start") def stopapp(self): self.sub_set_action("app", "stop") def syncnodes(self): self.sub_set_action("rsync", "syncnodes") def syncdrp(self): self.sub_set_action("rsync", "syncdrp") def scsirelease(self): self.sub_set_action("disk.vg", "scsirelease") self.sub_set_action("disk.zpool", "scsirelease") def scsireserv(self): self.sub_set_action("disk.vg", "scsireserv") self.sub_set_action("disk.zpool", "scsireserv") def scsicheckreserv(self): self.sub_set_action("disk.vg", "scsicheckreserv") self.sub_set_action("disk.zpool", "scsicheckreserv") def diskupdate(self): self.sub_set_action("disk.vg", "diskupdate") def action(self, action): from datetime import datetime import tempfile import logging begin = datetime.now() """Provision a database entry to store action log later """ xmlrpcClient.begin_action(self, action, begin) """Per action logfile to push to database at the end of the action """ f = tempfile.NamedTemporaryFile(delete=False, dir='/var/tmp', prefix=self.svcname+'.'+action) actionlogfile = f.name f.close() log = logging.getLogger() actionlogformatter = logging.Formatter("%(asctime)s;%(name)s;%(levelname)s;%(message)s;%(process)d;EOL") actionlogfilehandler = logging.FileHandler(actionlogfile) actionlogfilehandler.setFormatter(actionlogformatter) log.addHandler(actionlogfilehandler) """Trigger action """ err = 0 try: svclock(self) getattr(self, action)() except ex.excError: err = 1 pass except: """Save the error for deferred raising """ err = 1 import traceback traceback.print_exc() """Push result and logs to database """ actionlogfilehandler.close() log.removeHandler(actionlogfilehandler) end = datetime.now() svcunlock(self) fork_dblogger(self, action, begin, end, actionlogfile) return err def restart(self): """ stop then start service""" # FIXME should test stop() status before start() self.stop() self.start() if __name__ == "__main__" : for c in (Svc,) : help(c) print """s1=Svc("Zone")""" s1=Svc("Zone") print "s1=",s1 print """s2=Svc("basic")""" s2=Svc("basic") print "s2=",s2 print """s1+=Resource("ip")""" s1+=Resource("ip") print "s1=",s1 print """s1+=Resource("ip")""" s1+=Resource("ip") print """s1+=Resource("fs")""" s1+=Resource("fs") print """s1+=Resource("fs")""" s1+=Resource("fs") print "s1=",s1 print """s1.action("status")""" s1.action("status") opensvc/commands/usr/local/opensvc/lib/svcBuilder.py010064400000000000000000000422161132337442700231500ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import os import sys import ConfigParser import logging import glob import re import socket from rcGlobalEnv import * from freezer import Freezer from rcNode import discover_node from rcUtilities import * import rcOptParser import rcLogger import rcAddService import resRsync import resApp import rcExceptions as ex check_privs() pathsvc = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) pathetc = os.path.join(pathsvc, 'etc') os.environ['LANG'] = 'C' os.environ['PATH'] = '/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin' def svcmode_mod_name(svcmode=''): """Returns (moduleName, serviceClassName) implementing the class for a given service mode. For example: lxc => ('svcLxc', 'SvcLxc') zone => ('svcZone', 'SvcZone') hosted => ('svcHosted', 'SvcHosted') """ if svcmode == 'lxc': return ('svcLxc', 'SvcLxc') elif svcmode == 'zone': return ('svcZone', 'SvcZone') elif svcmode == 'hosted': return ('svcHosted', 'SvcHosted') return 1 # raise something instead ? def set_optional(resource, conf, section): if conf.has_option(section, 'optional') and \ conf.getboolean(section, "optional") == True: resource.set_optional() def set_disable(resource, conf, section): if conf.has_option(section, 'disable') and \ conf.getboolean(section, "disable") == True: resource.disable() def set_optional_and_disable(resource, conf, section): set_optional(resource, conf, section) set_disable(resource, conf, section) def set_scsireserv(resource, conf, section): """scsireserv = true can be set globally or in a specific resource section """ if conf.has_option('default', 'scsireserv') and \ conf.getboolean('default', 'scsireserv') == True: resource.set_scsireserv() if conf.has_option(section, 'scsireserv') and \ conf.getboolean(section, 'scsireserv') == True: resource.set_scsireserv() def add_ips(svc, conf): """Parse the configuration file and add an ip object for each [ip#n] section. Ip objects are stored in a list in the service object. """ for s in conf.sections(): if re.match('ip#[0-9]', s, re.I) is None: continue if conf.has_option(s, "ipname@"+rcEnv.nodename): ipname = conf.get(s, "ipname@"+rcEnv.nodename) elif conf.has_option(s, "ipname"): ipname = conf.get(s, "ipname") else: svc.log.error("nor ipname and ipname@%s defined in config file section %s"%(rcEnv.nodename, s)) ipname = None continue if conf.has_option(s, "ipdev@"+rcEnv.nodename): ipdev = conf.get(s, "ipdev@"+rcEnv.nodename) elif conf.has_option(s, "ipdev"): ipdev = conf.get(s, "ipdev") else: svc.log.debug('add_ips ipdev not found in ip section' + s) ipdev = None continue if conf.has_option(s, "netmask"): netmask = conf.get(s, "netmask") else: netmask = None if svc.svcmode == 'lxc': ip = __import__('resIp'+rcEnv.sysname+'Lxc') r = ip.Ip(svc.svcname, ipdev, ipname) else: ip = __import__('resIp'+rcEnv.sysname) r = ip.Ip(ipdev, ipname, netmask) set_optional_and_disable(r, conf, s) r.svc = svc svc += r def add_loops(svc, conf): """Parse the configuration file and add a loop object for each [loop#n] section. Loop objects are stored in a list in the service object. """ for s in conf.sections(): if re.match('loop#[0-9]', s, re.I) is None: continue file = conf.get(s, "file") loop = __import__('resLoop'+rcEnv.sysname) r = loop.Loop(file) set_optional_and_disable(r, conf, s) r.svc = svc svc += r def add_vgs(svc, conf): """Parse the configuration file and add a vg object for each [vg#n] section. Vg objects are stored in a list in the service object. """ for s in conf.sections(): if re.match('vg#[0-9]', s, re.I) is None: continue name = conf.get(s, "vgname") if conf.has_option(s, "dsf"): dsf = conf.getboolean(s, "dsf") else: dsf = True vg = __import__('resVg'+rcEnv.sysname) r = vg.Vg(name) set_optional_and_disable(r, conf, s) set_scsireserv(r, conf, s) r.svc = svc r.dsf = dsf svc += r def add_pools(svc, conf): """Parse the configuration file and add a pool object for each [pool#n] section. Pools objects are stored in a list in the service object. """ for s in conf.sections(): if re.match('pool#[0-9]', s, re.I) is None: continue name = conf.get(s, "poolname") pool = __import__('resZfs') r = pool.Pool(name) set_optional_and_disable(r, conf, s) set_scsireserv(r, conf, s) r.svc = svc svc += r def add_filesystems(svc, conf): """Parse the configuration file and add a fs object for each [fs#n] section. Fs objects are stored in a list in the service object. """ for s in conf.sections(): if re.match('fs#[0-9]', s, re.I) is None: continue dev = conf.get(s, "dev") mnt = conf.get(s, "mnt") if mnt[-1] == '/': """ Remove trailing / to not risk losing rsync src trailing / upon snap mountpoint substitution. """ mnt = mnt[0:-1] try: type = conf.get(s, "type") except: type = "" try: mnt_opt = conf.get(s, "mnt_opt") except: mnt_opt = "" mount = __import__('resMount'+rcEnv.sysname) r = mount.Mount(mnt, dev, type, mnt_opt) set_optional_and_disable(r, conf, s) #set_scsireserv(r, conf, s) r.svc = svc svc += r def add_mandatory_syncs(svc): """Mandatory files to sync: 1/ to all nodes: service definition 2/ to drpnodes: system files to replace on the drpnode in case of startdrp Set sync_min_delay to 24h for system's files sync to DR nodes """ """1 """ src = [] src.append(os.path.join(rcEnv.pathetc, svc.svcname)) src.append(os.path.join(rcEnv.pathetc, svc.svcname+'.env')) src.append(os.path.join(rcEnv.pathetc, svc.svcname+'.d')) mapfiles_pattern = os.path.join(rcEnv.pathvar, 'vg_'+svc.svcname+'_*.map') mapfiles = glob.glob(mapfiles_pattern) if len(mapfiles) > 0: src += mapfiles dst = os.path.join("/") exclude = [] targethash = {'nodes': svc.nodes, 'drpnodes': svc.drpnodes} r = resRsync.Rsync(src, dst, ['-R']+exclude, targethash, internal=True) r.svc = svc svc += r """2 """ targethash = {'drpnodes': svc.drpnodes} """ Reparent all PRD backed-up file in drp_path/node on the drpnode """ dst = os.path.join(rcEnv.drp_path, rcEnv.nodename) for src, exclude in rcEnv.drp_sync_files: """'-R' triggers rsync relative mode """ src = [ s for s in src if os.path.exists(s) ] if len(src) == 0: continue r = resRsync.Rsync(src, dst, ['-R']+exclude, targethash, internal=True, sync_min_delay=1430) r.svc = svc svc += r def add_syncs(svc, conf): """Add mandatory node-to-nodes and node-to-drpnode synchronizations, plus the those described in the config file. """ add_mandatory_syncs(svc) for s in conf.sections(): if re.match('sync#[0-9]', s, re.I) is None: continue if not conf.has_option(s, 'src') or \ not conf.has_option(s, 'dst'): log.error("config file section %s must have src and dst set" % s) return 1 src = conf.get(s, "src").split() dst = conf.get(s, "dst") if conf.has_option(s, 'dstfs'): dstfs = conf.get(s, 'dstfs') else: dstfs = None if conf.has_option(s, 'exclude'): exclude = conf.get(s, 'exclude').split() else: exclude = [] if conf.has_option(s, 'snap'): snap = conf.getboolean(s, 'snap') else: snap = False if conf.has_option(s, 'target'): target = conf.get(s, 'target').split() else: target = ['nodes', 'drpnodes'] if conf.has_option(s, 'bwlimit'): bwlimit = conf.get(s, 'bwlimit') else: bwlimit = None if conf.has_option(s, 'sync_min_delay'): sync_min_delay = conf.get(s, 'sync_min_delay') elif conf.has_option('default', 'sync_min_delay'): sync_min_delay = conf.get('default', 'sync_min_delay') else: sync_min_delay = 30 targethash = {} if 'nodes' in target: targethash['nodes'] = svc.nodes if 'drpnodes' in target: targethash['drpnodes'] = svc.drpnodes r = resRsync.Rsync(src=src, dst=dst, exclude=exclude, target=targethash, dstfs=dstfs, bwlimit=bwlimit, sync_min_delay=sync_min_delay, snap=snap) set_optional_and_disable(r, conf, s) r.svc = svc svc += r def add_apps(svc, conf): r = resApp.Apps() r.svc = svc svc += r def setup_logging(): """Setup logging to stream + logfile, and logfile rotation class Logger instance name: 'log' """ logging.setLoggerClass(rcLogger.Logger) global log log = logging.getLogger('INIT') if '--debug' in sys.argv: rcEnv.loglevel = logging.DEBUG log.setLevel(logging.DEBUG) elif '--warn' in sys.argv: rcEnv.loglevel = logging.WARNING log.setLevel(logging.WARNING) elif '--error' in sys.argv: rcEnv.loglevel = logging.ERROR log.setLevel(logging.ERROR) else: rcEnv.loglevel = logging.INFO log.setLevel(logging.INFO) def syncnodes(self): """Run all sync jobs to peer nodes for the service """ for s in self.syncs: if s.syncnodes() != 0: return 1 def syncdrp(self): """Run all sync jobs to drp nodes for the service """ for s in self.syncs: if s.syncdrp() != 0: return 1 def build(name): """build(name) is in charge of Svc creation it return None if service Name is not managed by local node else it return new Svc instance """ # # file tree abstraction # rcEnv.pathsvc = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) rcEnv.pathbin = os.path.join(rcEnv.pathsvc, 'bin') rcEnv.pathetc = os.path.join(rcEnv.pathsvc, 'etc') rcEnv.pathlib = os.path.join(rcEnv.pathsvc, 'lib') rcEnv.pathlog = os.path.join(rcEnv.pathsvc, 'log') rcEnv.pathtmp = os.path.join(rcEnv.pathsvc, 'tmp') rcEnv.pathvar = os.path.join(rcEnv.pathsvc, 'var') rcEnv.pathlock = os.path.join(rcEnv.pathvar, 'lock') rcEnv.sysname, rcEnv.nodename, x, x, rcEnv.machine = os.uname() rcEnv.nodename = socket.gethostname() svcconf = os.path.join(rcEnv.pathetc, name) + '.env' svcinitd = os.path.join(rcEnv.pathetc, name) + '.d' logfile = os.path.join(rcEnv.pathlog, name) + '.log' rcEnv.logfile = logfile setup_logging() if name == "rcService": log.error("do not execute rcService directly") return None # # print stuff we determined so far # log.debug('sysname = ' + rcEnv.sysname) log.debug('nodename = ' + rcEnv.nodename) log.debug('machine = ' + rcEnv.machine) log.debug('pathsvc = ' + rcEnv.pathsvc) log.debug('pathbin = ' + rcEnv.pathbin) log.debug('pathetc = ' + rcEnv.pathetc) log.debug('pathlib = ' + rcEnv.pathlib) log.debug('pathlog = ' + rcEnv.pathlog) log.debug('pathtmp = ' + rcEnv.pathtmp) log.debug('service name = ' + name) log.debug('service config file = ' + svcconf) log.debug('service log file = ' + logfile) # # node discovery is hidden in a separate module to # keep it separate from the framework stuff # discover_node() # # parse service configuration file # class RawConfigParser instance name: 'conf' # svcmode = "hosted" conf = None if os.path.isfile(svcconf): conf = ConfigParser.RawConfigParser() conf.read(svcconf) if conf.has_option("default", "mode"): svcmode = conf.get("default", "mode") # # dynamically import the module matching the service mode # and instanciate a service # log.debug('service mode = ' + svcmode) mod , svc_class_name = svcmode_mod_name(svcmode) svcMod = __import__(mod) svc = getattr(svcMod, svc_class_name)(name) svc.svcmode = svcmode # # Store useful properties # svc.logfile = logfile svc.conf = svcconf svc.initd = svcinitd # # Setup service properties from config file content # if conf.has_option("default", "nodes"): svc.nodes = set(conf.get("default", "nodes").split()) svc.nodes -= set(['']) else: svc.nodes = set([]) if conf.has_option("default", "drpnodes"): svc.drpnodes = set(conf.get("default", "drpnodes").split()) svc.drpnodes -= set(['']) else: svc.drpnodes = set([]) if conf.has_option("default", "drpnode"): svc.drpnode = conf.get("default", "drpnode") svc.drpnodes |= set([svc.drpnode]) svc.drpnodes -= set(['']) else: svc.drpnode = '' """ prune not managed service """ if rcEnv.nodename not in svc.nodes | svc.drpnodes: log.error('service %s not managed here' % name) del(svc) return None if conf.has_option("default", "service_type"): svc.svctype = conf.get("default", "service_type") else: svc.svctype = '' allowed_svctype = ['PRD', 'DEV', 'TMP', 'TST'] if svc.svctype not in allowed_svctype: log.error('service %s type %s is not a known service type (%s)'%(svc.svcname, svc.svctype, ', '.join(allowed_svctype))) del(svc) return None """ prune service whose service type does not match host mode """ if svc.svctype != 'PRD' and rcEnv.host_mode == 'PRD': log.error('service %s type %s is not allowed to run on this node (host mode %s)' % (svc.svcname, svc.svctype, rcEnv.host_mode)) del(svc) return None if conf.has_option("default", "autostart_node"): svc.autostart_node = conf.get("default", "autostart_node") else: svc.autostart_node = '' if conf.has_option("default", "drp_type"): svc.drp_type = conf.get("default", "drp_type") else: svc.drp_type = '' if conf.has_option("default", "comment"): svc.comment = conf.get("default", "comment") else: svc.comment = '' if conf.has_option("default", "app"): svc.app = conf.get("default", "app") else: svc.app = '' if conf.has_option("default", "drnoaction"): svc.drnoaction = conf.get("default", "drnoaction") else: svc.drnoaction = False if conf.has_option("default", "bwlimit"): svc.bwlimit = conf.get("default", "bwlimit") else: svc.bwlimit = None # # instanciate resources # try: add_ips(svc, conf) add_loops(svc, conf) add_vgs(svc, conf) add_pools(svc, conf) add_filesystems(svc, conf) add_syncs(svc, conf) add_apps(svc, conf) except ex.excInitError: return None return svc def is_service(f): rcService = os.path.join(pathsvc, 'bin', 'rcService') if os.path.realpath(f) != os.path.realpath(rcService): return False if not os.path.exists(f + '.env'): return False return True def build_services(status=None, svcnames=[], onlyprimary=False): """returns a list of all services of status matching the specified status. If no status is specified, returns all services """ services = {} for name in os.listdir(pathetc): if len(svcnames) > 0 and name not in svcnames: continue if not is_service(os.path.join(pathetc, name)): continue svc = build(name) if svc is None : continue if status is not None and svc.status() != status: continue if onlyprimary and svc.autostart_node != rcEnv.nodename: continue services[svc.svcname] = svc return [ s for n ,s in sorted(services.items()) ] opensvc/commands/usr/local/opensvc/lib/svcHosted.py010064400000000000000000000105571132305306700230050ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. import svc class SvcHosted(svc.Svc): """Define hosted services """ status_types = ["disk.loop", "fs", "disk.vg", "disk.zpool", "ip"] def __init__(self, svcname, optional=False, disabled=False): svc.Svc.__init__(self, svcname, "Hosted", optional, disabled) def start(self): """start a hosted service: start ips start loops start VGs start Pools start fs start apps """ self.sub_set_action("ip", "start") self.sub_set_action("disk.loop", "start") self.sub_set_action("disk.vg", "start") self.sub_set_action("disk.zpool", "start") self.sub_set_action("fs", "start") self.sub_set_action("app", "start") def stop(self): """stop a hosted service: stop apps stop fs stop VGs stop ips """ self.sub_set_action("app", "stop") self.sub_set_action("fs", "stop") self.sub_set_action("disk.vg", "stop") self.sub_set_action("disk.zpool", "stop") self.sub_set_action("disk.loop", "stop") self.sub_set_action("ip", "stop") def status(self): """status of the resources of a Lxc service""" return svc.Svc.status(self, self.status_types) def print_status(self): """status of the resources of a Lxc service""" return svc.Svc.print_status(self, self.status_types) def group_status(self): """status of the resources of a Lxc service""" return svc.Svc.group_status(self, self.status_types) def diskstart(self): """start a hosted service: start loops start VGs start Pools start fs """ self.sub_set_action("disk.loop", "start") self.sub_set_action("disk.vg", "start") self.sub_set_action("disk.zpool", "start") self.sub_set_action("fs", "start") def diskstop(self): """stop a hosted service: stop apps stop fs stop VGs stop Pools stop ips """ self.sub_set_action("fs", "stop") self.sub_set_action("disk.vg", "stop") self.sub_set_action("disk.zpool", "stop") self.sub_set_action("disk.loop", "stop") def startip(self): self.sub_set_action("ip", "start") def stopip(self): self.sub_set_action("ip", "stop") def startloop(self): self.sub_set_action("disk.loop", "start") def stoploop(self): self.sub_set_action("disk.loop", "stop") def startvg(self): self.sub_set_action("disk.vg", "start") def stopvg(self): self.sub_set_action("disk.vg", "stop") def startpool(self): self.sub_set_action("disk.zpool", "start") def stoppool(self): self.sub_set_action("disk.zpool", "stop") def mount(self): self.sub_set_action("fs", "start") def umount(self): self.sub_set_action("fs", "stop") if __name__ == "__main__": for c in (SvcHosted,) : help(c) import mountSunOS as mount import ipSunOS as ip print """ S=SvcHosted() S+=mount.Mount("/mnt1","/dev/sda") S+=mount.Mount("/mnt2","/dev/sdb") S+=ip.Ip("eth0","192.168.0.173") S+=ip.Ip("eth0","192.168.0.174") """ S=SvcSone() S+=mount.Mount("/mnt1","/dev/sda") S+=mount.Mount("/mnt2","/dev/sdb") S+=ip.Ip("eth0","192.168.0.173") S+=ip.Ip("eth0","192.168.0.174") print "Show S: ", S print "start S:" S.start() print "stop S:" S.stop() opensvc/commands/usr/local/opensvc/lib/svcLxc.py010064400000000000000000000073021132305306700222770ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. import svc import lxc import rcStatus class SvcLxc(svc.Svc): """ Define Lxc services""" status_types = ["container.lxc", "disk.loop", "fs", "disk.vg", "ip"] def __init__(self, svcname, optional=False, disabled=False): svc.Svc.__init__(self, svcname, optional, disabled) self += lxc.Lxc(svcname) def start(self): """start a Lxc check ping start loops start VGs start fs start lxc start apps """ self.sub_set_action("ip", "start") self.sub_set_action("disk.loop", "start") self.sub_set_action("disk.vg", "start") self.sub_set_action("fs", "start") self.sub_set_action("container.lxc", "start") self.sub_set_action("app", "start") def stop(self): """stop a zone: stop apps stop lxc stop fs stop VGs stop loops """ self.sub_set_action("app", "stop") self.sub_set_action("container.lxc", "stop") self.sub_set_action("fs", "stop") self.sub_set_action("disk.vg", "stop") self.sub_set_action("disk.loop", "stop") def status(self): """status of the resources of a Lxc service""" return svc.Svc.status(self, self.status_types) def print_status(self): """status of the resources of a Lxc service""" return svc.Svc.print_status(self, self.status_types) def group_status(self): """status of the resources of a Lxc service""" return svc.Svc.group_status(self, self.status_types) def startlxc(self): self.sub_set_action("container.lxc", "start") def stoplxc(self): self.sub_set_action("container.lxc", "stop") def startip(self): self.sub_set_action("ip", "start") def stopip(self): self.sub_set_action("ip", "stop") def startloop(self): self.sub_set_action("disk.loop", "start") def stoploop(self): self.sub_set_action("disk.loop", "stop") def startvg(self): self.sub_set_action("disk.vg", "start") def stopvg(self): self.sub_set_action("disk.vg", "stop") def mount(self): self.sub_set_action("fs", "start") def umount(self): self.sub_set_action("fs", "stop") if __name__ == "__main__": for c in (SvcLxc,) : help(c) import mountLinux as mount import ipLinux as ip print """ Z=SvcLxc() Z+=mount.Mount("/mnt1","/dev/sda") Z+=mount.Mount("/mnt2","/dev/sdb") Z+=ip.Ip("eth0","192.168.0.173") Z+=ip.Ip("eth0","192.168.0.174") """ Z=SvcLxc() Z+=mount.Mount("/mnt1","/dev/sda") Z+=mount.Mount("/mnt2","/dev/sdb") Z+=ip.Ip("eth0","192.168.0.173") Z+=ip.Ip("eth0","192.168.0.174") print "Show Z: ", Z print "start Z:" Z.start() print "stop Z:" Z.stop() opensvc/commands/usr/local/opensvc/lib/svcZone.py010064400000000000000000000065201132305306700224650ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # # To change this template, choose Tools | Templates # and open the template in the editor. __author__="cgaliber" __date__ ="$11 oct. 2009 21:56:59$" import svc class SvcZone(svc.Svc): """ Define Zone services""" status_types = ["container.zone", "ip", "disk.vg", "fs"] def __init__(self,optional=False,disabled=False): svc.Svc.__init__(self,"container.zone",optional, disabled) def start(self): """start a zone check ping zone ready start ips start zone start VGs start fs start apps """ print "starting %s" % self.__class__.__name__ self.sub_set_action("ip", "check_ping") self.sub_set_action("container.zone", "ready") self.sub_set_action("ip", "start") self.sub_set_action("container.zone", "boot") self.sub_set_action("disk.vg", "start") self.sub_set_action("fs", "start") self.sub_set_action("app", "start") def stop(self): """stop a zone: stop apps stop fs stop VGs stop zone stop ips """ print "stopping %s" % self.__class__.__name__ self.sub_set_action("app", "stop") self.sub_set_action("fs", "stop") self.sub_set_action("disk.vg", "stop") self.sub_set_action("container.zone", "stop") self.sub_set_action("ip", "stop") def startip(self): self.sub_set_action("ip", "check_ping") self.sub_set_action("ip", "start") def stopip(self): self.sub_set_action("ip", "stop") def startloop(self): self.sub_set_action("disk.loop", "start") def stoploop(self): self.sub_set_action("disk.loop", "stop") def startvg(self): self.sub_set_action("disk.vg", "start") def stopvg(self): self.sub_set_action("disk.vg", "stop") def mount(self): self.sub_set_action("fs", "start") def umount(self): self.sub_set_action("fs", "stop") if __name__ == "__main__": for c in (SvcZone,) : help(c) import mountSunOS as mount import ipSunOS as ip print """ Z=SvcZone() Z+=mount.Mount("/mnt1","/dev/sda") Z+=mount.Mount("/mnt2","/dev/sdb") Z+=ip.Ip("eth0","192.168.0.173") Z+=ip.Ip("eth0","192.168.0.174") """ Z=SvcZone() Z+=mount.Mount("/mnt1","/dev/sda") Z+=mount.Mount("/mnt2","/dev/sdb") Z+=ip.Ip("eth0","192.168.0.173") Z+=ip.Ip("eth0","192.168.0.174") print "Show Z: ", Z print "start Z:" Z.start() print "stop Z:" Z.stop() opensvc/commands/usr/local/opensvc/lib/xmlrpcClient.py010064400000000000000000000123541132355271500235100ustar00rootroot00000000000000#!/usr/bin/python # # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # from datetime import datetime import xmlrpclib import os from rcGlobalEnv import rcEnv sysname, nodename, x, x, machine = os.uname() hostId = __import__('hostid'+sysname) hostid = hostId.hostid() proxy = xmlrpclib.ServerProxy(rcEnv.dbopensvc) def begin_action(svc, action, begin): try: proxy.begin_action( ['svcname', 'action', 'hostname', 'hostid', 'begin',], [repr(svc.svcname), repr(action), repr(rcEnv.nodename), repr(hostid), repr(str(begin))] ) except: pass def end_action(svc, action, begin, end, logfile): err = 'ok' dateprev = None lines = open(logfile, 'r').read() """ If logfile is empty, default to current process pid """ pid = os.getpid() """Example logfile line: 2009-11-11 01:03:25,252;DISK.VG;INFO;unxtstsvc01_data is already up;10200;EOL """ for line in lines.split(';EOL\n'): if line.count(';') != 4: continue date = line.split(';')[0] """Push to database the previous line, so that begin and end date are available. """ if dateprev is not None: try: proxy.res_action( ['svcname', 'action', 'hostname', 'hostid', 'pid', 'begin', 'end', 'status_log', 'status'], [repr(svc.svcname), repr(res.lower()+' '+action), repr(rcEnv.nodename), repr(hostid), repr(pid), repr(str(dateprev)), repr(str(date)), repr(str(msg)), repr(str(res_err))] ) except: pass res_err = 'ok' (date, res, lvl, msg, pid) = line.split(';') if lvl is None or lvl == 'DEBUG': continue if lvl == 'ERROR': err = 'err' res_err = 'err' if lvl == 'WARNING' and err != 'err': err = 'warn' if lvl == 'WARNING' and res_err != 'err': res_err = 'warn' dateprev = date """Push the last log entry, using 'end' as end date """ try: proxy.res_action( ['svcname', 'action', 'hostname', 'hostid', 'pid', 'begin', 'end', 'status_log', 'status'], [repr(svc.svcname), repr(res.lower()+' '+action), repr(rcEnv.nodename), repr(hostid), repr(pid), repr(str(dateprev)), repr(str(end)), repr(str(msg)), repr(str(res_err))] ) except: pass """Complete the wrap-up database entry """ try: proxy.end_action( ['svcname', 'action', 'hostname', 'hostid', 'pid', 'begin', 'end', 'time', 'status'], [repr(svc.svcname), repr(action), repr(rcEnv.nodename), repr(hostid), repr(pid), repr(str(begin)), repr(str(end)), repr(str(end-begin)), repr(str(err))] ) except: pass def svcmon_update(svc, status): try: vars = [\ "mon_svcname", "mon_svctype", "mon_nodname", "mon_nodtype", "mon_hostid", "mon_ipstatus", "mon_diskstatus", "mon_containerstatus", "mon_fsstatus", "mon_overallstatus", "mon_updated", "mon_prinodes"] vals = [\ repr(svc.svcname), repr(svc.svctype), repr(rcEnv.nodename), repr(rcEnv.host_mode), repr(hostid), repr(str(status["ip"])), repr(str(status["disk"])), repr(str(status["container"])), repr(str(status["fs"])), repr(str(status["overall"])), repr(str(datetime.now())), repr(' '.join(svc.nodes))] proxy.svcmon_update(vars, vals) except: pass opensvc/commands/usr/local/opensvc/log/004075500000000000000000000000003777777777700205515ustar00rootroot00000000000000opensvc/commands/usr/local/opensvc/tmp/004075500000000000000000000000003777777777700205705ustar00rootroot00000000000000opensvc/commands/usr/local/opensvc/usr/004075500000000000000000000000003777777777700206015ustar00rootroot00000000000000opensvc/commands/usr/local/opensvc/usr/share/004075500000000000000000000000003777777777700217035ustar00rootroot00000000000000opensvc/commands/usr/local/opensvc/usr/share/AUTHORS010064400000000000000000000000601132063442300226700ustar00rootroot00000000000000Christophe Varoqui opensvc/commands/usr/local/opensvc/usr/share/BANNER010064400000000000000000000014661132063442300225230ustar00rootroot00000000000000# # Copyright (c) 2009 Christophe Varoqui ' # Copyright (c) 2009 Cyril Galibern ' # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # opensvc/commands/usr/local/opensvc/usr/share/COPYING010064400000000000000000000635041132063442300226670ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! opensvc/commands/usr/local/opensvc/usr/share/doc/004075500000000000000000000000003777777777700224505ustar00rootroot00000000000000opensvc/commands/usr/local/opensvc/usr/share/doc/template.env010064400000000000000000000230671132236563200247330ustar00rootroot00000000000000# # OpenSVC config files are written in standard ini file format: # # "The configuration file consists of sections, led by a [section] header and # followed by name: value entries, with continuations in the style of RFC 822 # (see section 3.1.1, “LONG HEADER FIELDS”); name=value is also accepted. Note # that leading whitespace is removed from values. # Lines beginning with '#' or ';' are ignored and may be used to provide # comments." # extract from http://docs.python.org/library/configparser.html # # Resource are label [resource_name#index_in_resourse_set], like [ip#1], # [ip#2], [fs#1], [fs#2]... # # Every resource accept two options: # 'disable' # optional. Possible values are 'true' or 'false'. # A disabled resource will be ignored on service startup and shutdown. # # 'optional' # optional. Possible values are 'true' or 'false'. # Actions on resource will be tried upon service startup and shutdown, # but action failures will be logged and passed over. Useful for resources # like dump filesystems for example. # # # Every service config file must have a default section. # [default] # # 'app' # is used to identify who is responsible for is service, who is billable # and provides a most useful filtering key. Better keep it a short code. # ;app = OSVC # # 'comment' # is optional, but helps users understand the role of the service, # which is nice to on-call support people having to operate on a # service they are usualy responsible for. # ;comment = opensvc web front-end # # 'mode' # supported modes are 'lxc', 'zone' or 'hosted'. The default is 'hosted'. # the mode decides upon disposition OpenSVC takes to bring a service up # or down : 'lxc' and 'zone' need a special action to prepare and boot the # container for example, which is not needed for 'hosted' services. # ;mode = lxc # # 'drp_type' # supported values are 'standby' or 'srdf'. The default is 'standby'. # Not used for the moment. # ;drp_type = standby # # 'service_type' # supported values are 'DEV' and 'PRD'. There is no default, and this # setting is mandatory, as important rules apply to it : # 1/ a DEV service can not be brought up on a PRD node, but a PRD service # can be startup on a DEV node (in a DRP situation). # ;service_type = DEV # # 'nodes' # mandatory list of cluster nodes able to start the service when not in # a DRP situation # ;nodes = zezette # # 'autostart_node' # the node from 'nodes' where the service will try to start on upon node # reboot. The start-up will fail if the service is already up on another # node though. # If not specified, the service will never be started at node boot-time, # which is rarely the expected behaviour. # ;autostart_node = zezette # # 'drpnode' # optional. The backup node where the service is activated in a DRP # situation. This node is also a data synchronization target for 'sync' # resources (see below) # ;drpnode = vm5 # # 'drpnodes' # optional. Alternate backup nodes, where the service could be activated # in a DRP situation if the 'drpnode' is not available. These nodes are # also data synchronization targets for 'sync' resources (see below) # ;drpnodes = vm6 vm7 # # 'rsh' 'rcp' # the commands used to trigger remote executions of system commands on # 'nodes' and 'drpnodes'. # ;rsh = /usr/bin/ssh -o StrictHostKeyChecking=no -o ForwardX11=no -o PasswordAuthentication=no -o ConnectTimeout=10 ;rcp = /usr/bin/scp -o StrictHostKeyChecking=no -o ForwardX11=no -o PasswordAuthentication=no -o ConnectTimeout=10 # # 'scsireserv' # optional. Possible values are 'true' or 'false'. Default is 'false'. # If set to 'true', OpenSVC will try to acquire a type-5 (write exclusive, # registrant only) scsi3 persistent reservation on every path to disks of # every disk group attached to this service. Existing reservations are # preempted to not block service start-up. If the start-up was not # legitimate the data are still protected from being written over from both # nodes. # If set to 'false' or not set, 'scsireserv' can be activated on a per- # resource basis. # ;scsireserv = false # # 'bwlimit' # optional. Bandwidth limit in KB applied to all rsync transfers # ;bwlimit = 3000 # # 'sync_min_delay' # optional. Set the minimum delay between syncs in minutes. If a sync is # triggered through crond or manually, it is skipped if last sync occured # less than 'sync_min_delay' ago. # The mecanism is enforced by a timestamp created upon each sync completion # in /service/var/sync/[service]![dst] # ;sync_min_delay = 30 # # 'ip' resources # describe which ip to plumb for the service. Any number of ips can be # attached to the service, but ips are to be uniquely assigned to it. # In case of ip conflict, the service refuses to start. # ;[ip#1] ;disable = true ;optional = true # # 'ipname' # the DNS name of the ip resource. Can be different from one node to the # other, in which case '@nodename' can be specified. This is most # useful to specify a different ip when the service starts in DRP mode, # where subnets are likely to be different than those of the production # datacenter. # ;ipname@zezette = unxdevweb ;ipname@vm5 = unxdrpweb # # 'ipdev' # the interface name over which OpenSVC will try to stack the service # ip. Can be different from one node to the other, in which case the # '@nodename' can be specified. # ;ipdev@zezette = br0 ;ipdev@vm5 = eth0 # # 'netmask' # optional if an ip is already plumbed on the root interface (if which # case the netmask is deduced from this ip). Mandatory if the interface # is dedicated to the service (dummy interface are likely to be in this # case). # the format is decimal, ex: 255.255.252.0 # ;netmask = 255.255.255.0 # # 'sync' resource # describes a rsync-based data synchronization job. By default the sync # is run daily. # ;[sync#1] ;disable = true ;optional = true # # 'src' # source of the sync. Can be a whitespace-separated list of files or dirs # passed as-is to rsync. Beware of the meaningful ending '/'. Refer to # the rsync man page for details. # ;src = /unxdevweb/ # # 'dst' # destination of the sync. Beware of the meaningful ending '/'. Refer to # the rsync man page for details. # ;dst = /unxdevweb # # 'exclude' # optional. A whitespace-separated list of --exclude params passed unchanged # to rsync. # ;exclude = --exclude=cache # # 'target' # mandatory. Possible values are 'nodes', 'drpnodes' or 'nodes drpnodes'. # Describes which nodes should receive this data sync from the PRD node # where the service is up and running. # # SAN storage shared 'nodes' must not be sync to 'nodes'. # SRDF-like paired storage must not be sync to 'drpnodes'. # ;target = nodes drpnodes # # 'snap' # optional. Possible values are 'true' or 'false'. Default is 'false'. # If set to true, OpenSVC will try to snapshot the first snapshottable # parent of the source of the sync and try to sync from the snap. # ;snap = true # # 'dstfs' # optional. If set to a remote mount point, OpenSVC will verify that the # specified mount point is really hosting a mounted FS. This can be used # as a safety net to not overflow the parent FS (may be root). # ;dstfs = /remote/dir # # 'bwlimit' # optional. Bandwidth limit in KB applied to this rsync transfer. Takes # precedence over 'bwlimit' set in [default]. # ;bwlimit = 3000 # # 'sync_min_delay' # optional. Set the minimum delay between syncs in minutes. If a sync is # triggered through crond or manually, it is skipped if last sync occured # less than 'sync_min_delay' ago. If no set in a resource section, fallback # to the value set in the 'default' section. The mecanism is enforced by a # timestamp created upon each sync completion in # /service/var/sync/[service]![dst] # ;sync_min_delay = 30 # # 'vg' resource # Disk group in the sense of volume managers, whatever the implementation. # Attaching a 'vg' to a service will make OpenSVC check and drive its # imported/exported status. # ;[vg#1] ;disable = true ;optional = true # # 'vgname' # nothing special there # ;vgname = unxtstsvc02 # # 'dsf' # optional. Boolean. HP-UX only. Default value is True. # 'dsf' must be set to false for LVM to use never-multipathed /dev/dsk/... # devices. Otherwize, ad-hoc multipathed /dev/disk/... devices. # ;dsf = true # # 'scsireserv' # optional. Possible values are 'true' or 'false'. Default is 'false'. # If set to 'true', OpenSVC will try to acquire a type-5 (write exclusive, # registrant only) scsi3 persistent reservation on every path to disks of # every disk group attached to this service. Existing reservations are # preempted to not block service start-up. If the start-up was not # legitimate the data are still protected from being written over from both # nodes. # If set to 'false' or not set, 'scsireserv' can still be activated globally # from the 'default' section. # ;scsireserv = false # # 'fs' resource # describes filesystems to mount on service startup and umount on service # shutdown. # The options are aligned to the Unix fstab fields. Whatever is possibly # described in the fstab should be supported in there. # ;[fs#1] ;disable = true ;optional = true ;dev = /opt/unxtstsvc01.img ;mnt = /opt/unxtstsvc01 ;mnt_opt = rw,loop ;type = ext4 # # 'loop' resource # linux-only. # describes a loop device attached to the service. startup triggers the # allocation of a block device (usualy major 7) mapped over the specified # file. The created loop dev can be used to stack disk group also attached # to the service. # ;[loop#1] ;disable = true ;optional = true ;file = /opt/unxtstsvc02.img opensvc/commands/usr/local/opensvc/var/004075500000000000000000000000003777777777700205605ustar00rootroot00000000000000