Skip to content
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
29 changes: 15 additions & 14 deletions BlockServer/core/ioc_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@
# along with this program; if not, you can obtain a copy from
# https://www.eclipse.org/org/documents/epl-v10.php or
# http://opensource.org/licenses/eclipse-1.0.php

from time import sleep, time
from typing import List

from BlockServer.alarm.load_alarm_config import AlarmConfigLoader
from BlockServer.epics.procserv_utils import ProcServWrapper
from server_common.common_exceptions import MaxAttemptsExceededException
from server_common.constants import IOCS_NOT_TO_STOP
from server_common.utilities import print_and_log

from BlockServer.alarm.load_alarm_config import AlarmConfigLoader
from BlockServer.epics.procserv_utils import ProcServWrapper


class IocControl:
"""A class for starting, stopping and restarting IOCs"""
Expand All @@ -45,7 +45,7 @@ def start_ioc(self, ioc: str, restart_alarm_server: bool = True) -> None:
self._proc.start_ioc(ioc)
if ioc != "ALARM" and restart_alarm_server:
AlarmConfigLoader.restart_alarm_server(self)
except Exception as err:
except OSError as err:
print_and_log(f"Could not start IOC {ioc}: {err}", "MAJOR")

def restart_ioc(self, ioc: str, force: bool = False, restart_alarm_server: bool = True) -> None:
Expand All @@ -66,7 +66,7 @@ def restart_ioc(self, ioc: str, force: bool = False, restart_alarm_server: bool
self._proc.restart_ioc(ioc)
if ioc != "ALARM" and restart_alarm_server:
AlarmConfigLoader.restart_alarm_server(self)
except Exception as err:
except OSError as err:
print_and_log(f"Could not restart IOC {ioc}: {err}", "MAJOR")

def stop_ioc(self, ioc: str, force: bool = False) -> None:
Expand All @@ -83,7 +83,7 @@ def stop_ioc(self, ioc: str, force: bool = False) -> None:
self._proc.stop_ioc(ioc)
if ioc != "ALARM":
AlarmConfigLoader.restart_alarm_server(self)
except Exception as err:
except OSError as err:
print_and_log(f"Could not stop IOC {ioc}: {err}", "MAJOR")

def get_ioc_status(self, ioc: str) -> str:
Expand All @@ -108,7 +108,7 @@ def ioc_restart_pending(self, ioc: str) -> bool:
"""
return self._proc.ioc_restart_pending(ioc)

def start_iocs(self, iocs: List[str]) -> None:
def start_iocs(self, iocs: list[str]) -> None:
"""Start a number of IOCs.

Args:
Expand All @@ -117,14 +117,14 @@ def start_iocs(self, iocs: List[str]) -> None:
for ioc in iocs:
self.start_ioc(ioc)

def restart_iocs(self, iocs: List[str], reapply_auto: bool = False) -> None:
def restart_iocs(self, iocs: list[str], reapply_auto: bool = False) -> None:
"""Restart a number of IOCs.

Args:
iocs (list): The IOCs to restart
reapply_auto (bool): Whether to reapply auto restart settings automatically
"""
auto = dict()
auto = {}
for ioc in iocs:
auto[ioc] = self.get_autorestart(ioc)
self.restart_ioc(ioc)
Expand All @@ -135,7 +135,7 @@ def restart_iocs(self, iocs: List[str], reapply_auto: bool = False) -> None:
self.waitfor_running(ioc)
self.set_autorestart(ioc, auto[ioc])

def stop_iocs(self, iocs: List[str]) -> None:
def stop_iocs(self, iocs: list[str]) -> None:
"""Stop a number of IOCs.

Args:
Expand All @@ -156,7 +156,7 @@ def ioc_exists(self, ioc: str) -> bool:
try:
self.get_ioc_status(ioc)
return True
except Exception:
except OSError:
return False

def set_autorestart(self, ioc: str, enable: bool) -> None:
Expand All @@ -178,7 +178,7 @@ def set_autorestart(self, ioc: str, enable: bool) -> None:
print_and_log(f"Auto-restart for IOC {ioc} is already {enable}")
else:
print_and_log(f"Auto-restart for IOC {ioc} unchanged as IOC is not running")
except Exception as err:
except MaxAttemptsExceededException as err:
print_and_log(f"Could not set auto-restart IOC {ioc}: {err}", "MAJOR")

def get_autorestart(self, ioc: str) -> bool:
Expand All @@ -192,8 +192,9 @@ def get_autorestart(self, ioc: str) -> bool:
"""
try:
return self._proc.get_autorestart(ioc)
except Exception as err:
except MaxAttemptsExceededException as err:
print_and_log(f"Could not get auto-restart setting for IOC {ioc}: {err}", "MAJOR")
return False

def waitfor_running(self, ioc: str, timeout: int = 15) -> None:
"""Waits for the IOC to start running.
Expand Down
37 changes: 23 additions & 14 deletions BlockServer/epics/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,28 +23,35 @@
from server_common.helpers import CONTROL_SYSTEM_PREFIX
from server_common.utilities import print_and_log

from BlockServer.config.block import Block

ALIAS_HEADER = """\
##
EVALUATION ORDER ALLOW, DENY

"""

ALIAS_FOOTER = r"""
## serve blockserver internal variables, including Flag variables needed by blockserver process to restart gateway
## serve blockserver internal variables, including Flag variables needed by
## blockserver process to restart gateway
{0}CS:GATEWAY:BLOCKSERVER:.* ALLOW ANYBODY 1
## allow anybody to generate gateway reports
{0}CS:GATEWAY:BLOCKSERVER:report[1-9]Flag ALLOW ANYBODY 1
## ignore any request related to run control/alerts etc. (RC,AC,DC) on blocks, these are handled by RUNCTRL ioc
## ignore any request related to run control/alerts etc. (RC,AC,DC) on blocks,
## these are handled by RUNCTRL ioc
{0}CS:SB:[^:]*:[ADR]C:.* DENY
## ignore any request not related to local blocks or gateway itself
!{0}CS:\(SB\|GATEWAY\):.* DENY
""" # noqa: E501
"""


def build_block_alias_lines(
full_block_pv: str, pv_suffix: str, underlying_pv: str, include_comments: bool = True
full_block_pv: str,
pv_suffix: str | None,
underlying_pv: str,
include_comments: bool = True,
) -> list[str]:
lines = list()
lines = []
if underlying_pv.endswith(":SP"):
# The block points at a setpoint
if include_comments:
Expand All @@ -53,7 +60,7 @@ def build_block_alias_lines(
"genie_python will append an additional :SP"
)

full_block_pv = r"{}\(:SP\)?".format(full_block_pv)
full_block_pv = rf"{full_block_pv}\(:SP\)?"

# Pattern match is for picking up any extras like :RBV or .EGU
lines.append(f"{full_block_pv}\\([.:].*\\) ALIAS {underlying_pv}\\2")
Expand Down Expand Up @@ -121,7 +128,7 @@ def exists(self) -> bool:
"""
return ChannelAccess.caget(self._gateway_prefix + "pvtotal") is not None

def _reload(self) -> None:
def reload(self) -> None:
print_and_log("Reloading gateway")
try:
# Have to wait after put as the gateway does not do completion callbacks
Expand All @@ -131,16 +138,16 @@ def _reload(self) -> None:
while ChannelAccess.caget(self._gateway_prefix + "newAsFlag") == 1:
time.sleep(1)
print_and_log("Gateway reloaded")
except Exception as err:
except OSError as err:
print_and_log(f"Problem with reloading the gateway {err}")

def _generate_alias_file(self, blocks=None) -> None:
def _generate_alias_file(self, blocks: dict[str, Block] | None = None) -> None:
# Generate blocks.pvlist for gateway
with open(self._pvlist_file, "w") as f:
header = ALIAS_HEADER.format(self._inst_prefix)
f.write(header)
if blocks is not None:
for name, value in blocks.items():
for value in blocks.values():
lines = self.generate_alias(value.name, value.pv, value.local)
f.write("\n".join(lines) + "\n")
f.write(ALIAS_FOOTER.format(self._inst_prefix))
Expand Down Expand Up @@ -175,7 +182,9 @@ def generate_alias(self, block_name: str, underlying_pv: str, local: bool) -> li
lines.append("") # New line to seperate out each block
return lines

def set_new_aliases(self, blocks, configures_block_gateway: bool, config_dir: str) -> None:
def set_new_aliases(
self, blocks: dict[str, Block] | None, configures_block_gateway: bool, config_dir: str
) -> None:
"""Creates the aliases for the blocks and restarts the gateway.

Args:
Expand All @@ -187,11 +196,11 @@ def set_new_aliases(self, blocks, configures_block_gateway: bool, config_dir: st
"""
pvlist_file = os.path.join(config_dir, "gwblock.pvlist")
if configures_block_gateway and os.path.exists(pvlist_file):
print_and_log("Using {} to configure block gateway".format(pvlist_file))
print_and_log(f"Using {pvlist_file} to configure block gateway")
copyfile(pvlist_file, self._pvlist_file)
elif configures_block_gateway:
print_and_log("File: {} not found generating gwblock.pvlist".format(pvlist_file))
print_and_log(f"File: {pvlist_file} not found generating gwblock.pvlist")
self._generate_alias_file(blocks)
else:
self._generate_alias_file(blocks)
self._reload()
self.reload()
22 changes: 12 additions & 10 deletions BlockServer/epics/procserv_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,23 @@
# along with this program; if not, you can obtain a copy from
# https://www.eclipse.org/org/documents/epl-v10.php or
# http://opensource.org/licenses/eclipse-1.0.php
import typing

from server_common.channel_access import ChannelAccess
from server_common.utilities import ioc_restart_pending, print_and_log, retry


class ProcServWrapper:
"""A wrapper for accessing some of the functionality of ProcServ."""

def __init__(self, prefix: str):
def __init__(self, prefix: str) -> None:
"""Constructor.
Args:
prefix (string): The prefix for the instrument
"""
self.procserv_prefix = f"{prefix}CS:PS:"

def start_ioc(self, ioc: str):
def start_ioc(self, ioc: str) -> None:
"""Starts the specified IOC.

Args:
Expand All @@ -36,7 +38,7 @@ def start_ioc(self, ioc: str):
print_and_log(f"Starting IOC {ioc}")
ChannelAccess.caput(f"{self.procserv_prefix}{ioc}:START", 1)

def stop_ioc(self, ioc: str):
def stop_ioc(self, ioc: str) -> None:
"""Stops the specified IOC.

Args:
Expand All @@ -45,7 +47,7 @@ def stop_ioc(self, ioc: str):
print_and_log(f"Stopping IOC {ioc}")
ChannelAccess.caput(f"{self.procserv_prefix}{ioc}:STOP", 1, wait=True)

def restart_ioc(self, ioc: str):
def restart_ioc(self, ioc: str) -> None:
"""Restarts the specified IOC.

Args:
Expand All @@ -54,7 +56,7 @@ def restart_ioc(self, ioc: str):
print_and_log(f"Restarting IOC {ioc}")
ChannelAccess.caput(f"{self.procserv_prefix}{ioc}:RESTART", 1)

def ioc_restart_pending(self, ioc: str):
def ioc_restart_pending(self, ioc: str) -> bool:
"""Tests to see if an IOC restart is pending

Args:
Expand All @@ -65,7 +67,7 @@ def ioc_restart_pending(self, ioc: str):
"""
return ioc_restart_pending(f"{self.procserv_prefix}{ioc}", ChannelAccess)

def get_ioc_status(self, ioc: str):
def get_ioc_status(self, ioc: str) -> str:
"""Gets the status of the specified IOC.

Args:
Expand All @@ -75,12 +77,12 @@ def get_ioc_status(self, ioc: str):
string : The status
"""
pv_name = f"{self.procserv_prefix}{ioc}:STATUS"
ans = ChannelAccess.caget(pv_name, as_string=True)
ans = typing.cast(str, ChannelAccess.caget(pv_name, as_string=True))
if ans is None:
raise Exception(f"Could not find IOC {ioc} (using pv {pv_name})")
raise OSError(f"Could not find IOC {ioc} (using pv {pv_name})")
return ans.upper()

def toggle_autorestart(self, ioc: str):
def toggle_autorestart(self, ioc: str) -> None:
"""Toggles the auto-restart property.

Args:
Expand All @@ -91,7 +93,7 @@ def toggle_autorestart(self, ioc: str):
ChannelAccess.caput(f"{self.procserv_prefix}{ioc}:TOGGLE", 1)

@retry(50, 0.1, ValueError) # Retry for 5 seconds to get a valid value on failure
def get_autorestart(self, ioc: str):
def get_autorestart(self, ioc: str) -> bool:
"""Gets the current auto-restart setting of the specified IOC.

Args:
Expand Down
Loading
Loading