Kaydet (Commit) db4bb8ce authored tarafından Suleyman Poyraz's avatar Suleyman Poyraz

Scomd start manager

üst 96884eaa
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# IPython Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# dotenv
.env
# virtualenv
venv/
ENV/
# Spyder project settings
.spyderproject
# Rope project settings
.ropeproject
language: python 
python:
- "3.3"
- "3.4"
- "3.5"
- "3.5-dev" # 3.5 development branch
- "3.6-dev" # 3.6 development branch
- "nightly" # currently points to 3.7-dev
# command to install dependencies
#install: "pip install gettext"
# command to run tests
script: ./setup.py install
Suleyman POYRAZ < nipalensisaquila [at] gmail.com >
Gürer Özen <gurer [at] pardus.org.tr>
S.Çağlar Onur <caglar [at] pardus.org.tr>
Onur Küçük <onur [at] pardus.org.tr>
Bahadır Kandemir <bahadir [at] pardus.org.tr>
Ozan Çağlayan <ozan [at] pardus.org.tr>
Current maintainer:
Marcin Bojara <marcin [at] pisilinux.org>
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
Mudur
------
Mudur is the first component of Pardus initialization system. It's the main startup script which is
called by init and handles basic initialization and shutdown.
# mudur
sysvinit booting scripts replacement for Lupus
service komutu için:
start iken start, stop iken stop deyince çıkan mesajlar
sadece server tiplileri göster mesajı
belki sıralama seçenekleri?
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This is a script to easily add a user to system with scom
#
import os
import sys
import dbus
import time
from optparse import OptionParser
# uid = -1 means next available uid
# first group in the groups list is the main group
user = {"uid": -1,
"username": "kaplan",
"realname": "Pisi",
"home": "/home/pisi",
"shell": "/bin/bash",
"password": "pisi",
"defaultgroup": "users",
"groups": [],
"admingroups": ["wheel"],
"grants": [],
"blocks": []
}
defaultGroups = "users,cdrom,plugdev,floppy,disk,audio,video,power,dialout,lp,lpadmin"
def fail(_message):
print(_message)
sys.exit(1)
def connectToDBus():
global bus
bus = None
try:
bus = dbus.SystemBus()
except dbus.DBusException:
return False
if bus:
return True
def addUser():
obj = bus.get_object("tr.org.sulin.scom", "/package/baselayout")
try:
obj.addUser(user["uid"], user["username"], user["realname"],
user["home"], user["shell"], user["password"],
user["groups"], user["grants"], user["blocks"],
dbus_interface="tr.org.sulin.scom.User.Manager")
except dbus.DBusException as e:
fail("Error: %s" % e)
if __name__ == "__main__":
usage = "usage: %prog [options] username"
parser = OptionParser(usage=usage)
parser.add_option("-c", "--comment", dest="realname", type="string", default="Pisi",
help="comment for the user, usually used for Full Name")
parser.add_option("-u", "--uid", dest="uid", type="int", default=-1,
help="user id number, default is -1 meaning next available")
parser.add_option("-g", "--gid", dest="defaultgroup", type="string", default=user["defaultgroup"],
help="default group name for user")
parser.add_option("-G", "--groups", dest="groups", type="string", default=defaultGroups,
help="groups that user is member of")
parser.add_option("-p", "--password", dest="password", type="string", default="pisi",
help="password")
parser.add_option("-d", "--home", dest="home", type="string", default="",
help="password")
parser.add_option("-s", "--shell", dest="shell", type="string", default="/bin/bash",
help="default login shell")
parser.add_option("--admin", action="store_true", dest="isadmin", default=False,
help="give user admin rights, adding to wheel group")
parser.add_option("--dry-run", action="store_true", dest="dryrun", default=False,
help="do not add user, only show what will be done")
(opts, args) = parser.parse_args()
if len(args) != 1:
fail("Please provide a username.")
user["username"] = args[0]
groups = opts.groups.split(",")
if opts.home == "":
user["home"] = "/home/%s" % user["username"]
else:
user["home"] = opts.home
if opts.defaultgroup in groups:
groups.remove(user["defaultgroup"])
user["defaultgroup"] = opts.defaultgroup
user["groups"].append(user["defaultgroup"])
if opts.isadmin:
for i in user["admingroups"]:
if i not in groups:
groups.append(i)
user["groups"].extend(groups)
user["shell"] = opts.shell
user["realname"] = opts.realname
user["password"] = opts.password
user["uid"] = opts.uid
if opts.dryrun:
for i in list(user.keys()):
print("%s\t%s" % (i, user[i]))
else:
if os.getuid() != 0:
fail("You must have root permissions to add a user")
if not connectToDBus():
fail("Could not connect to D-Bus, please check your system settings")
addUser()
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017, Suleyman POYRAZ (AquilaNipalensis)
#
# 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. Please read the COPYING file.
#
import subprocess
import sys
import os
# This script populates the /etc/init.d directory by creating symlinks to the
# compat.py. This way, when /etc/init.d/<service_name> <action> is called, the symlink
# delegates this transparently to the /bin/service command.
# Usage:
# python compat.py
# /etc/init.d/samba start
def wrap_service(package, op):
cmd = ["service", package, op]
return subprocess.call(cmd)
def populate_initd():
for name in os.listdir("/var/db/scom3/scripts/System.Service"):
if not os.path.exists("/etc/init.d/%s" % name[:-3]):
os.symlink("compat.py", "/etc/init.d/%s" % name[:-3])
if __name__ == "__main__":
myname = os.path.basename(sys.argv[0])
if len(sys.argv) == 2:
sys.exit(wrap_service(myname, sys.argv[1]))
elif myname == "compat.py" and os.getuid() == 0:
populate_initd()
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This is a script to easily add a user to system with scom
#
import os
import pwd
import sys
import dbus
import time
from optparse import OptionParser
user = {"uid": None,
"deletefiles": False
}
def fail(_message):
print(_message)
sys.exit(1)
def connectToDBus():
global bus
bus = None
try:
bus = dbus.SystemBus()
except dbus.DBusException:
return False
if bus:
return True
def delUser():
obj = bus.get_object("tr.org.sulin.scom", "/package/baselayout")
try:
obj.deleteUser(user["uid"], user["deletefiles"],
dbus_interface="tr.org.sulin.scom.User.Manager")
except dbus.DBusException as e:
fail("Error: %s." % e)
if __name__ == "__main__":
usage = "usage: %prog [options] username"
parser = OptionParser(usage=usage)
parser.add_option("-r", "--remove-home", dest="removehome", action="store_true",
help="Also remove user home directory")
(opts, args) = parser.parse_args()
if len(args) != 1:
fail("please give one username to delete")
try:
user["uid"] = pwd.getpwnam(args[0]).pw_uid
except KeyError:
fail("Error: No such user '%s'" % args[0])
user["deletefiles"] = opts.removehome
if os.getuid() != 0:
fail("you must have root permissions to delete a user")
if not connectToDBus():
fail("Could not connect to DBUS, please check your system settings")
delUser()
This diff is collapsed.
# -*- coding : utf-8 -*-
import os, sys
def mountpoint(path):
status = os.system("mountpoint -q %s" % path)
if status == 0:
return True
else:
return False
class Controller:
def __init__(self, subsysname, hierarchy, num_cgroups, enabled ):
self.subsysname = subsysname
self.hierarchy = hierarchy
self.num_cgroups = num_cgroups
self.enabled = enabled
def mount(self):
if self.enabled == 1:
os.chdir("/sys/fs/cgroup")
if mountpoint(self.subsysname) == False:
s = self.subsysname
status = os.system("mkdir -p %s; mount -n -t cgroup -o %s cgroup %s" % (s, s,s))
if status == 0:
return True
else:
return False
class Cgroupfs:
def __init__(self):
self.controllers = {}
if self.check_fstab == True:
print("cgroupfs in fstab, exiting.")
sys.exit(-1)
if self.kernel_support() == False:
print("No kernel support for cgroupfs, exiting.")
sys.exit(-2)
if self.check_sysfs() == False:
print("/sys/fs/cgroups directory not found, exiting")
sys.exit(-3)
self.mount_cgroup()
self.find_controllers()
for cname, c in list(self.controllers.items()):
c.mount()
def check_fstab(self):
found = False
for line in open("/etc/fstab").readlines():
if line[0] == "#":
continue
else:
if line.find("cgroup"):
found = True
return found
def kernel_support(self):
return os.path.isfile("/proc/cgroups")
def check_sysfs(self):
return os.path.isdir("/sys/fs/cgroup")
def mount_cgroup(self):
if mountpoint("/sys/fs/cgroup") == False:
cmd = " mount -t tmpfs -o uid=0,gid=0,mode=0755 cgroup /sys/fs/cgroup"
return os.system(cmd)
def find_controllers(self):
for line in open("/proc/cgroups").readlines():
line = line.strip()
if line[0] == "#":
continue
else:
subsysname, hierarchy, num_cgroups, enabled = line.split()
enb = int(enabled)
hie = int(hierarchy)
numc= int(num_cgroups)
self.controllers[subsysname] = Controller(subsysname, hie, numc, enb)
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is part of free software (scomd); you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 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
# Library General Public License for more details.
"""
Pisilinux system for creation, deletion and cleaning of volatile and temporary files.
"""
import os
import re
import sys
import stat
import shutil
from pwd import getpwnam
from grp import getgrnam
# search files order
DEFAULT_CONFIG_DIRS_SO = ["/etc/tmpfiles.d", "/run/tmpfiles.d", "/usr/lib/tmpfiles.d"]
# execution order
DEFAULT_CONFIG_DIRS_EO = ["/run/tmpfiles.d", "/usr/lib/tmpfiles.d", "/etc/tmpfiles.d"]
def read_file(path):
with open(path) as f:
return f.read().strip()
def write_file(path, content, mode = "w"):
open(path, mode).write(content)
def create(type, path, mode, uid, gid, age, arg):
if type == "d" and \
os.path.isdir(path) and \
(not uid == os.stat(path).st_uid or not gid == os.stat(path).st_gid):
type = "D"
if type == "L":
if not os.path.islink(path): os.symlink(arg, path)
return
elif type == "D":
if os.path.isdir(path): shutil.rmtree(path)
elif os.path.islink(path): os.remove(path)
elif type == "c":
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
if not os.path.exists(path):
dev = [int(x) for x in arg.split(":")]
os.mknod(path, mode|stat.S_IFCHR, os.makedev(dev[0], dev[1]))
os.chown(path, uid, gid)
if type.lower() == "d":
if not os.path.isdir(path): os.makedirs(path, mode)
os.chown(path, uid, gid)
elif type in ["f", "F", "w"]:
if not os.path.isfile(path) and type == "w": return
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
os.chown(os.path.dirname(path), uid, gid)
write_file(path, arg, mode = "a" if type == "f" else "w")
os.chmod(path, mode)
os.chown(path, uid, gid)
USAGE = """\
%s PATH(S)
\tparsing specified .conf files.
%s
\tparsing .conf files in:
\t%s
""" % (sys.argv[0], sys.argv[0], "; ".join(DEFAULT_CONFIG_DIRS_SO))
def usage():
print(USAGE)
sys.exit(0)
if __name__ == "__main__":
if ("-h" or "--help") in sys.argv: usage()
boot = True if "--boot" in sys.argv else False
config_files = {}
errors = []
def add_config_file(head, tail):
try:
config_files[head].append(tail)
except KeyError:
config_files[head] = [tail]
if sys.argv[1:] and not boot:
for arg in sys.argv[1:]:
(head, tail) = os.path.split(arg)
if not tail.endswith(".conf"): errors.append("%s is not .conf file" % tail)
elif not head: errors.append("Full path is needed for %s args." % sys.argv[0])
elif not os.path.isdir(head): errors.append("Path %s not exists." % head)
elif not os.path.isfile(arg): errors.append("File %s not exists." % arg)
add_config_file(head, tail)
else:
all_files_names = []
for head in DEFAULT_CONFIG_DIRS_SO:
if not os.path.isdir(head): continue
ls = os.listdir(head)
for tail in ls:
# only .conf files and don't override (previous paths have higer priority)
if not tail.endswith(".conf") or tail in all_files_names: continue
all_files_names.append(tail)
add_config_file(head, tail)
if ls and "baselayout.conf" in config_files[head]:
config_files[head].insert(0, config_files[head].pop(config_files[head].index("baselayout.conf")))
for d in DEFAULT_CONFIG_DIRS_EO:
try:
fs = config_files[d]
except KeyError:
continue
for f in fs:
conf = read_file(os.path.join(d, f))
# parse config file
for line in [l for l in conf.split("\n") if l and not (l.startswith("#") or l.isspace())]:
cerr = len(errors)
fields = line.split()
if len(fields) < 3: errors.append("%s is invalid .conf file. Not enough args in line: %s" % (os.path.join(d, f), line))
if len(fields) < 7: fields.extend(["",] * (7 - len(fields)))
elif len(fields) > 7: fields = fields[0:6] + [re.sub(".*?(%s)\s*$" % "\s+".join(fields[6:]), "\\1", line)]
if fields[0] == "c" and not re.search("\d+:\d+", fields[6]): errors.append("%s - wrong argument for type 'c' in file: %s" % (fields[6], os.path.join(d, f)))
for n, i in enumerate(fields):
if i == "-": fields[n] = ""
if not fields[3]: fields[3] = "root"
if not fields[4]: fields[4] = "root"
if fields[0].endswith("!"):
if not boot: continue
else: fields[0] = fields[0].replace("!", "")
if not fields[0] in ["c", "d", "D", "f", "F", "L", "w"]: errors.append("%s - wrong type in file: %s" % (fields[0], os.path.join(d, f)))
elif fields[0] == "L":
if not fields[6]: errors.append("No arg for type 'L' specified in file: %s" % os.path.join(d, f))
elif not os.path.exists(fields[6]): errors.append("%s - wrong path in file: %s" % (fields[6], os.path.join(d, f)))
elif fields[0] in ["f", "F", "w"] and os.path.isdir(fields[1]): errors.append("Cannot write to file. %s is directory." % fields[1])
else:
if not fields[2]: errors.append("No mode specified in file: %s" % os.path.join(d, f))
elif not re.search("^\d{3,4}$", fields[2]): errors.append("%s - wrong mode in file: %s" % (fields[2], os.path.join(d, f)))
else: fields[2] = int(fields[2], 8)
try:
fields[3] = getpwnam(fields[3]).pw_uid
except KeyError:
errors.append("User %s not exists (%s)" % (fields[3], os.path.join(d, f)))
try:
fields[4] = getgrnam(fields[4]).gr_gid
except KeyError:
errors.append("Group %s not exists (%s)" % (fields[4], os.path.join(d, f)))
#
if len(errors) == cerr: create(*fields)
print("\n".join(errors))
This diff is collapsed.
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# A script to update the environment
# Copyright (C) 2017, Suleyman POYRAZ (AquilaNipalensis)
#
# 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. Please read the COPYING file.
#
import os
import sys
import getopt
header = "### This file is automatically generated by update-environment"
header_note = """
#
# Please do not edit this file directly. If you want to change
# anything, please take a look at the files in /etc/env.d
# and read the Pardus initialization system documentation.
#
# Bu otomatik olarak oluşturulmuş bir dosyadır.
# Lütfen bu dosyayı elle değiştirmeyin. Değiştirmek istediğiniz
# şeyler varsa, /etc/env.d dizinindeki dosyalara ve Pardus
# açılış sistemi belgesine bakın.
#
"""
specials = (
"KDEDIRS",
"PATH",
"CLASSPATH",
"MANPATH",
"INFOPATH",
"ROOTPATH",
"CONFIG_PROTECT",
"CONFIG_PROTECT_MASK",
"PRELINK_PATH",
"PRELINK_PATH_MASK",
"PYTHONPATH",
"ADA_INCLUDE_PATH",
"ADA_OBJECTS_PATH",
"PKG_CONFIG_PATH"
)
def read_env_d(envdir):
d = {}
paths = []
for name in os.listdir(envdir):
path = os.path.join(envdir, name)
# skip dirs (.svn, .cvs, etc)
if os.path.isdir(path):
continue
# skip backup and version control files
if name.endswith("~") or name.endswith(".bak") or name.endswith(",v"):
continue
# skip pisi's config file backups
# .oldconfig is obsolete, but checked anyway cause it may still exist at old systems
if name.endswith(".oldconfig") or name.endswith(".newconfig"):
continue
paths.append(path)
paths.sort()
for path in paths:
for line in file(path):
if line == "" or line.startswith("#"):
continue
line = line.rstrip("\n")
if "=" in line:
key, value = line.split("=", 1)
key = key.strip()
value = value.strip()
if value.startswith('"') or value.startswith("'"):
value = value[1:-1]
# Merge for special variables, override for others
if key in specials:
if key in d:
d[key].extend(value.split(":"))
else:
d[key] = value.split(":")
else:
d[key] = value
return d
def generate_profile_env(envdict, format='export %s="%s"\n'):
profile = ""