Skip to content
This repository has been archived by the owner on Oct 3, 2020. It is now read-only.

Commit

Permalink
Add checks to prevent concurrent executions of local-cname.
Browse files Browse the repository at this point in the history
  • Loading branch information
Neki committed Jun 20, 2019
1 parent fc1a59a commit 6a128bf
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
27 changes: 24 additions & 3 deletions local_cname/cli.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import argparse
import socket
import sys
import time
from pathlib import Path

from clickclick import Action, info
from clickclick import Action, info, error
from filelock import FileLock, Timeout


def main():
Expand All @@ -13,11 +15,30 @@ def main():
args = parser.parse_args()

hosts_file = Path('/etc/hosts')
backup_file = hosts_file.with_suffix('.local-cname-backup')
lock_file = hosts_file.with_suffix('.local-cname-lock')

lock = FileLock(str(lock_file))
try:
with lock.acquire(timeout=1):
edit_etc_hosts(hosts_file, backup_file, args)
except Timeout:
error('Another instance of local-cname seems to be running.')
info('(if a previous process crashed, remove {} '
'and check the contents of {} and {})'.format(lock_file, hosts_file, backup_file))
sys.exit(1)


def edit_etc_hosts(hosts_file, backup_file, args):
with hosts_file.open() as fd:
old_contents = fd.read()

backup_file = hosts_file.with_suffix('.local-cname-backup')
HEADER = '#### Start of entries generated by local-cname'
if HEADER in old_contents:
error('{} seems to have already been modified by local-cname.'.format(hosts_file))
info('Remove the local-cname header line from this file to proceed.')
sys.exit(1)

with backup_file.open('w') as fd:
fd.write(old_contents)

Expand All @@ -40,7 +61,7 @@ def main():
with Action('Writing {} ..'.format(hosts_file)):
with hosts_file.open('w') as fd:
fd.write(old_contents)
fd.write('#### Start of entries generated by local-cname\n')
fd.write('{}\n'.format(HEADER))
for hostname, ip in entries:
fd.write('{} {}\n'.format(ip, hostname))

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def readme():
keywords='dns hosts local',
license='GNU General Public License v3 (GPLv3)',
setup_requires=['flake8'],
install_requires=['clickclick'],
install_requires=['clickclick', 'filelock'],
tests_require=[],
classifiers=[
'Programming Language :: Python',
Expand Down

0 comments on commit 6a128bf

Please sign in to comment.