reset history

This commit is contained in:
2022-01-21 10:01:31 +00:00
commit 803cf31aa2
8 changed files with 446 additions and 0 deletions

153
.gitignore vendored Normal file
View File

@@ -0,0 +1,153 @@
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# 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/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
config.yaml

16
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,16 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"module": "onlyone",
"console": "integratedTerminal",
"args": ["--configFile","config.yaml", "--server"]
}
]
}

9
LICENSE Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

4
README.md Normal file
View File

@@ -0,0 +1,4 @@
# onlyone
pip install PyYAML

6
config.example.yaml Normal file
View File

@@ -0,0 +1,6 @@
defaultProcess: nano
processes:
- key: cat
cmd: cat
- key: nano
cmd: nano

138
onlyone/__init__.py Normal file
View File

@@ -0,0 +1,138 @@
from distutils.command.config import config
import os
import psutil
import logging
import yaml
from typing import List
from onlyone import namedpipes
DEFAULT_CONFIG_PATH = "/etc/onlyone/config.yaml"
log = logging.getLogger(__name__)
def config_file_to_dict(path:str):
if not os.path.isfile(path):
log.error("missing file " + path)
raise "missing file " + path
return
log.info("trying to read file : " + path)
configTxt = open(path, "r").read()
log.info("config file content : " + configTxt)
log.info("trying read yaml")
retval = yaml.safe_load(configTxt)
return retval
def __is_process(cmd:str, arr):
item = " ".join(arr)
#log.info("[onlyone][startprocess] -> " + item + " ends with " + cmd)
if(item.endswith(cmd)):
return True
#log.info("[onlyone][startprocess] -> " + item + " ends with " + cmd.replace("\"", ""))
if(item.endswith(cmd.replace("\"", ""))):
return True
#log.info("[onlyone][startprocess] -> " + item + " eq " + cmd)
if(item == cmd):
return True
#log.info("[onlyone][startprocess] -> " + item + " eq " + cmd.replace("\"", ""))
if(item == cmd.replace("\"", "")):
return True
#log.info("compare finished not equal")
return False
def isrunning(cmd:str):
return __is_process(cmd, psutil.process_iter())
def __isrunning(cmd:str, processes):
for proc in processes:
if __is_process(cmd,proc.cmdline()):
return True
return False
def startprocess(cmd):
try:
os.popen(cmd)
log.info("[onlyone][startprocess] -> processed started : " + cmd)
except OSError as e:
log.error("eror")
except:
log.error("eror")
def __killprocesses(killcmds:List, sysprocesses: List):
if killcmds == None :
return False
for proc in sysprocesses:
if any( __is_process(x, proc.cmdline()) for x in killcmds):
try:
proc.kill()
log.info("[onlyone][__killprocesses] -> processed killed : " + proc.name())
except:
log.info("[onlyone][__killprocesses] -> error killing process")
return False
def killprocesses(killcmds:List):
return __killprocesses(killcmds, psutil.process_iter())
def onlyone(cmd:str, killcmds:list):
log.info("[onlyone][onlyone] -> invoked start " + cmd + ", kill " + str(killcmds))
processes = psutil.process_iter()
__killprocesses(killcmds, processes)
if (not(__isrunning(cmd, processes))):
startprocess(cmd)
#__forceoneprocessinstance(cmd, processes)
class Manager:
def __init__(self):
self.__processes=[]
self.__current=None
def load(self, dict:dict, loadDefault:bool):
if(dict == None):return
if("processes" in dict):
for p in dict["processes"]:
if "key" in p and "cmd" in p:
self.addprocess(p["key"], p["cmd"])
if(loadDefault and "defaultProcess" in dict):
self.current(dict["defaultProcess"])
def addprocess(self, key, cmd):
self.__processes.append({"key": key, "cmd":cmd})
def current(self):
if self.__current == None:
return None
else:
return self.__current["key"]
def current(self, key):
item = None
if key!=None:
for x in self.__processes:
if x["key"] == key:
item =x
if item == None:
killprocesses([x["cmd"] for x in self.__processes])
self._current = None
return
onlyone(item["cmd"], [x["cmd"] for x in self.__processes if x["key"]!=item["key"]])
self._current = item["key"]
class Server:
def __init__(self, configPath):
self.manager = Manager()
if(configPath != None and configPath!=""):
configDict = config_file_to_dict(configPath)
self.manager.load(configDict, True)
self.npserver = namedpipes.Server(self.manager)

31
onlyone/__main__.py Normal file
View File

@@ -0,0 +1,31 @@
from asyncio.base_events import Server
import logging
import argparse
from types import new_class
from typing import List
import sys
import yaml
import os
import onlyone
import onlyone.namedpipes
logging.basicConfig(level="DEBUG")
log = logging.getLogger(__name__)
parser = argparse.ArgumentParser(description='onlyone')
parser.add_argument('--configFile', type=str, required=False, help='configfile')
parser.add_argument('--server', action='store_const', const=True, help='server mode')
args = parser.parse_args()
log.info("arguments - " + str(sys.argv))
log.info("Current Path:" + os.getcwd())
if args.server:
configPath = onlyone.DEFAULT_CONFIG_PATH
if args.configFile:
configPath = args.configFile
server = onlyone.Server(configPath)

View File

@@ -0,0 +1,89 @@
import os
import errno
import logging
from signal import default_int_handler
import threading
import subprocess
FIFO_PATH="/tmp/onlyone_fifo"
SECURITY_GROUP="onlyone"
log = logging.getLogger(__name__)
def securitygroup_check(groupName:str):
if not securitygroup_exists(groupName):
securitygroup_create(groupName)
def securitygroup_create(groupName:str):
try:
subprocess.run(['groupadd', groupName])
except:
print(f"Failed to create group " + groupName)
raise
def securityfifo_checkpermissions(fifoPath:str, groupName:str):
try:
subprocess.run(['chown', 'root:' + groupName, fifoPath])
subprocess.run(['chmod', '660', fifoPath])
except:
print(f"Failed to set permissions")
raise
def securitygroup_exists(groupName:str):
with open("/etc/group", "r") as groupFile:
for line in groupFile:
if line.startswith(groupName):
return True
return False
def createfifo(path):
try:
os.mkfifo(path)
except OSError as oe:
if oe.errno != errno.EEXIST:
raise
class Server:
def __init__(self, manager):
self.manager=manager
self__fifoname=""
securitygroup_check(SECURITY_GROUP)
createfifo(FIFO_PATH)
securityfifo_checkpermissions(FIFO_PATH, SECURITY_GROUP)
readTask = ReadTask(self)
self.__readThread = threading.Thread(target=readTask.run, args = (FIFO_PATH,) )
self.__readThread.start()
def kill(self):
self.__readThread.kill()
class ReadTask:
def __init__(self, server):
self.__kill=False
self.server=server
def kill(self):
self.__kill=True
def read(self, fifoname):
log.info("waiting FIFO...")
with open(fifoname) as fifo:
log.info("FIFO opened")
while True:
data = fifo.read()
if len(data) == 0:
log.info("FIFO closed")
break
log.info('FIFO Data: "{0}"'.format(data))
self.server.manager.current(format(data).strip())
def run(self, fifoname):
while True:
if self.__kill:
return
self.read(fifoname)