Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adapt to new logging mechanism #303

Draft
wants to merge 15 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 41 additions & 37 deletions as-ap-currinfo/as_ap_currinfo/as_ap_currinfo.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
"""CurrInfo Soft IOC."""

import os as _os
import sys as _sys
import signal as _signal
import logging as _log
import sys as _sys

import pcaspy as _pcaspy
import pcaspy.tools as _pcaspy_tools

from siriuspy import util as _util
from siriuspy.envars import VACA_PREFIX as _vaca_prefix
from siriuspy.currinfo import BOCurrInfoApp as _BOCurrInfoApp, \
SICurrInfoApp as _SICurrInfoApp, LICurrInfoApp as _LICurrInfoApp, \
LICurrInfoApp as _LICurrInfoApp, SICurrInfoApp as _SICurrInfoApp, \
TSCurrInfoApp as _TSCurrInfoApp

from siriuspy.envars import VACA_PREFIX as _VACA_PREFIX
from siriuspy.logging import configure_logging, get_logger

INTERVAL = 0.5
STOP_EVENT = False


def _stop_now(signum, frame):
_ = frame
print(_signal.Signals(signum).name+' received at '+_util.get_timestamp())
get_logger(_stop_now).warning(
_signal.Signals(signum).name + " received at " + _util.get_timestamp()
)
_sys.stdout.flush()
_sys.stderr.flush()
global STOP_EVENT
Expand All @@ -30,28 +30,29 @@ def _stop_now(signum, frame):

def _attribute_access_security_group(server, dbase):
for k, val in dbase.items():
if k.endswith(('-RB', '-Sts', '-Cte', '-Mon')):
val.update({'asg': 'rbpv'})
if k.endswith(("-RB", "-Sts", "-Cte", "-Mon")):
val.update({"asg": "rbpv"})
path_ = _os.path.abspath(_os.path.dirname(__file__))
server.initAccessSecurityFile(path_ + '/access_rules.as')
server.initAccessSecurityFile(path_ + "/access_rules.as")


def _get_app(acc):
acc = acc.lower()
if acc == 'bo':
if acc == "bo":
return _BOCurrInfoApp()
elif acc == 'si':
elif acc == "si":
return _SICurrInfoApp()
elif acc == 'li':
elif acc == "li":
return _LICurrInfoApp()
elif acc == 'ts':
elif acc == "ts":
return _TSCurrInfoApp()
else:
raise ValueError('There is no App defined for accelarator '+acc+'.')
raise ValueError(
"There is no App defined for accelarator " + acc + "."
)


class _PCASDriver(_pcaspy.Driver):

def __init__(self, app):
"""Initialize driver."""
super().__init__()
Expand All @@ -69,7 +70,7 @@ def read(self, reason):
def write(self, reason, value):
"""Write IOC pvs according to main application."""
ret_val = self.app.write(reason, value)
if reason.endswith('-Cmd'):
if reason.endswith("-Cmd"):
value = self.getParam(reason) + 1
if ret_val:
return super().write(reason, value)
Expand All @@ -84,65 +85,68 @@ def update_pv(self, pvname, value, **kwargs):

def run(acc):
"""Main module function."""
logger = get_logger(run)
acc = acc.upper()

# define abort function
_signal.signal(_signal.SIGINT, _stop_now)
_signal.signal(_signal.SIGTERM, _stop_now)

# configure log file
_util.configure_log_file()
_log.info('Starting...')
configure_logging()
logger.info("Starting...")

# define IOC, init pvs database and create app object
_version = _util.get_last_commit_hash()
_ioc_prefix = _vaca_prefix + ('-' if _vaca_prefix else '')
if acc == 'BO':
_ioc_prefix += acc + '-Glob:AP-CurrInfo:'
_log.debug('Creating App Object.')
_ioc_prefix = _VACA_PREFIX + ("-" if _VACA_PREFIX else "")
if acc == "BO":
_ioc_prefix += acc + "-Glob:AP-CurrInfo:"
logger.debug("Creating App Object.")
app = _get_app(acc)
dbase = app.pvs_database
if acc == 'BO':
dbase['Version-Cte']['value'] = _version
if acc == "BO":
dbase["Version-Cte"]["value"] = _version
else:
dbase[acc+'-Glob:AP-CurrInfo:Version-Cte']['value'] = _version
dbase[acc + "-Glob:AP-CurrInfo:Version-Cte"]["value"] = _version

# check if another IOC is running
pvname = _ioc_prefix + next(iter(dbase))
if _util.check_pv_online(pvname, use_prefix=False):
raise ValueError('Another instance of this IOC is already running!')
raise ValueError("Another instance of this IOC is already running!")

# check if another IOC is running
_util.print_ioc_banner(
ioc_name=acc.lower()+'-ap-currinfo',
ioc_name=acc.lower() + "-ap-currinfo",
db=dbase,
description=acc.upper()+'-AP-CurrInfo Soft IOC',
description=acc.upper() + "-AP-CurrInfo Soft IOC",
version=_version,
prefix=_ioc_prefix)
prefix=_ioc_prefix,
)

# create a new simple pcaspy server and driver to respond client's requests
_log.info('Creating Server.')
logger = get_logger(run)
logger.info("Creating Server.")
server = _pcaspy.SimpleServer()
_attribute_access_security_group(server, dbase)
_log.info('Setting Server Database.')
logger.info("Setting Server Database.")
server.createPV(_ioc_prefix, dbase)
_log.info('Creating Driver.')
logger.info("Creating Driver.")
_PCASDriver(app)
app.init_database()

# initiate a new thread responsible for listening for client connections
server_thread = _pcaspy_tools.ServerThread(server)
_log.info('Starting Server Thread.')
logger.info("Starting Server Thread.")
server_thread.start()

# main loop
while not STOP_EVENT:
app.process(INTERVAL)

app.close()
_log.info('Stoping Server Thread...')
logger.info("Stoping Server Thread...")
# send stop signal to server thread
server_thread.stop()
server_thread.join()
_log.info('Server Thread stopped.')
_log.info('Good Bye.')
logger.info("Server Thread stopped.")
logger.info("Good Bye.")
52 changes: 29 additions & 23 deletions as-ap-currinfo/as_ap_currinfo/lifetime/lifetime.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
"""CurrInfo Lifetime Soft IOC."""

import os as _os
import sys as _sys
import signal as _signal
import logging as _log
import sys as _sys

import pcaspy as _pcaspy
import pcaspy.tools as _pcaspy_tools

from siriuspy import util as _util
from siriuspy.envars import VACA_PREFIX as _vaca_prefix

from siriuspy.currinfo import SILifetimeApp as _SILifetimeApp

from siriuspy.envars import VACA_PREFIX as _VACA_PREFIX
from siriuspy.logging import configure_logging, get_logger

INTERVAL = 0.1
STOP_EVENT = False


def _stop_now(signum, frame):
_ = frame
print(_signal.Signals(signum).name+' received at '+_util.get_timestamp())
get_logger(_stop_now).warning(
_signal.Signals(signum).name + " received at " + _util.get_timestamp()
)
_sys.stdout.flush()
_sys.stderr.flush()
global STOP_EVENT
Expand All @@ -29,14 +28,13 @@ def _stop_now(signum, frame):

def _attribute_access_security_group(server, dbase):
for k, val in dbase.items():
if k.endswith(('-RB', '-Sts', '-Cte', '-Mon')):
val.update({'asg': 'rbpv'})
if k.endswith(("-RB", "-Sts", "-Cte", "-Mon")):
val.update({"asg": "rbpv"})
path_ = _os.path.abspath(_os.path.dirname(__file__))
server.initAccessSecurityFile(path_ + '/access_rules.as')
server.initAccessSecurityFile(path_ + "/access_rules.as")


class _PCASDriver(_pcaspy.Driver):

def __init__(self, app):
"""Initialize driver."""
super().__init__()
Expand All @@ -54,7 +52,7 @@ def read(self, reason):
def write(self, reason, value):
"""Write IOC pvs according to main application."""
ret_val = self.app.write(reason, value)
if reason.endswith('-Cmd'):
if reason.endswith("-Cmd"):
value = self.getParam(reason) + 1
if ret_val:
return super().write(reason, value)
Expand All @@ -69,52 +67,60 @@ def update_pv(self, pvname, value, **kwargs):

def run():
"""Main module function."""
logger = get_logger(run)
# define abort function
_signal.signal(_signal.SIGINT, _stop_now)
_signal.signal(_signal.SIGTERM, _stop_now)

# configure log file
_util.configure_log_file()
configure_logging()
logger.info("Starting...")

# define IOC, init pvs database and create app object
_version = _util.get_last_commit_hash()
_ioc_prefix = _vaca_prefix + ('-' if _vaca_prefix else '')
_ioc_prefix += 'SI-Glob:AP-CurrInfo:'
_ioc_prefix = _VACA_PREFIX + ("-" if _VACA_PREFIX else "")
_ioc_prefix += "SI-Glob:AP-CurrInfo:"
logger.debug("Creating App Object.")
app = _SILifetimeApp()
dbase = app.pvs_database
dbase['VersionLifetime-Cte']['value'] = _version
dbase["VersionLifetime-Cte"]["value"] = _version

# check if another IOC is running
pvname = _ioc_prefix + next(iter(dbase))
if _util.check_pv_online(pvname, use_prefix=False):
raise ValueError('Another instance of this IOC is already running!')
raise ValueError("Another instance of this IOC is already running!")

# print ioc banner
_util.print_ioc_banner(
ioc_name='si-ap-currinfo-lifetime',
ioc_name="si-ap-currinfo-lifetime",
db=dbase,
description='SI-AP-CurrInfo-Lifetime Soft IOC',
description="SI-AP-CurrInfo-Lifetime Soft IOC",
version=_version,
prefix=_ioc_prefix)
prefix=_ioc_prefix,
)

# create a new simple pcaspy server and driver to respond client's requests
_log.info('Creating Server.')
logger.info("Creating Server.")
server = _pcaspy.SimpleServer()
_attribute_access_security_group(server, dbase)
_log.info('Setting Server Database.')
logger.info("Setting Server Database.")
server.createPV(_ioc_prefix, dbase)
_log.info('Creating Driver.')
logger.info("Creating Driver.")
pcas_driver = _PCASDriver(app)
app.init_database()

# initiate a new thread responsible for listening for client connections
server_thread = _pcaspy_tools.ServerThread(server)
logger.info("Starting Server Thread.")
server_thread.start()

# main loop
while not STOP_EVENT:
pcas_driver.app.process(INTERVAL)
logger.info("Stoping Server Thread...")

# sends stop signal to server thread
server_thread.stop()
server_thread.join()
logger.info("Server Thread stopped.")
logger.info("Good Bye.")
Loading