Skip to content

Commit

Permalink
minor changes
Browse files Browse the repository at this point in the history
  • Loading branch information
asingh003 committed Oct 30, 2018
1 parent 59f843d commit c3faaa3
Show file tree
Hide file tree
Showing 6 changed files with 197 additions and 252 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
*.pyc
*.pyc
.vscode/
114 changes: 114 additions & 0 deletions .vscode/.ropeproject/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# The default ``config.py``
# flake8: noqa


def set_prefs(prefs):
"""This function is called before opening the project"""

# Specify which files and folders to ignore in the project.
# Changes to ignored resources are not added to the history and
# VCSs. Also they are not returned in `Project.get_files()`.
# Note that ``?`` and ``*`` match all characters but slashes.
# '*.pyc': matches 'test.pyc' and 'pkg/test.pyc'
# 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc'
# '.svn': matches 'pkg/.svn' and all of its children
# 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o'
# 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o'
prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject',
'.hg', '.svn', '_svn', '.git', '.tox']

# Specifies which files should be considered python files. It is
# useful when you have scripts inside your project. Only files
# ending with ``.py`` are considered to be python files by
# default.
# prefs['python_files'] = ['*.py']

# Custom source folders: By default rope searches the project
# for finding source folders (folders that should be searched
# for finding modules). You can add paths to that list. Note
# that rope guesses project source folders correctly most of the
# time; use this if you have any problems.
# The folders should be relative to project root and use '/' for
# separating folders regardless of the platform rope is running on.
# 'src/my_source_folder' for instance.
# prefs.add('source_folders', 'src')

# You can extend python path for looking up modules
# prefs.add('python_path', '~/python/')

# Should rope save object information or not.
prefs['save_objectdb'] = True
prefs['compress_objectdb'] = False

# If `True`, rope analyzes each module when it is being saved.
prefs['automatic_soa'] = True
# The depth of calls to follow in static object analysis
prefs['soa_followed_calls'] = 0

# If `False` when running modules or unit tests "dynamic object
# analysis" is turned off. This makes them much faster.
prefs['perform_doa'] = True

# Rope can check the validity of its object DB when running.
prefs['validate_objectdb'] = True

# How many undos to hold?
prefs['max_history_items'] = 32

# Shows whether to save history across sessions.
prefs['save_history'] = True
prefs['compress_history'] = False

# Set the number spaces used for indenting. According to
# :PEP:`8`, it is best to use 4 spaces. Since most of rope's
# unit-tests use 4 spaces it is more reliable, too.
prefs['indent_size'] = 4

# Builtin and c-extension modules that are allowed to be imported
# and inspected by rope.
prefs['extension_modules'] = []

# Add all standard c-extensions to extension_modules list.
prefs['import_dynload_stdmods'] = True

# If `True` modules with syntax errors are considered to be empty.
# The default value is `False`; When `False` syntax errors raise
# `rope.base.exceptions.ModuleSyntaxError` exception.
prefs['ignore_syntax_errors'] = False

# If `True`, rope ignores unresolvable imports. Otherwise, they
# appear in the importing namespace.
prefs['ignore_bad_imports'] = False

# If `True`, rope will insert new module imports as
# `from <package> import <module>` by default.
prefs['prefer_module_from_imports'] = False

# If `True`, rope will transform a comma list of imports into
# multiple separate import statements when organizing
# imports.
prefs['split_imports'] = False

# If `True`, rope will remove all top-level import statements and
# reinsert them at the top of the module when making changes.
prefs['pull_imports_to_top'] = True

# If `True`, rope will sort imports alphabetically by module name instead
# of alphabetically by import statement, with from imports after normal
# imports.
prefs['sort_imports_alphabetically'] = False

# Location of implementation of
# rope.base.oi.type_hinting.interfaces.ITypeHintingFactory In general
# case, you don't have to change this value, unless you're an rope expert.
# Change this value to inject you own implementations of interfaces
# listed in module rope.base.oi.type_hinting.providers.interfaces
# For example, you can add you own providers for Django Models, or disable
# the search type-hinting in a class hierarchy, etc.
prefs['type_hinting_factory'] = (
'rope.base.oi.type_hinting.factory.default_type_hinting_factory')


def project_opened(project):
"""This function is called after opening the project"""
# Do whatever you like here!
1 change: 1 addition & 0 deletions .vscode/.ropeproject/objectdb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
�}q.
86 changes: 20 additions & 66 deletions btfiler.py → fileutils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#!/usr/bin/python

from btpeer import *
from peerconnection import *

PEERNAME = "NAME" # request a peer's canonical id
PEERNAME = "NAME"
LISTPEERS = "LIST"
INSERTPEER = "JOIN"
QUERY = "QUER"
Expand All @@ -17,24 +17,18 @@
# Assumption in this program:
# peer id's in this application are just "host:port" strings

#==============================================================================
class FilerPeer(BTPeer):
#==============================================================================
class FilerPeer(Peer):
""" Implements a file-sharing peer-to-peer entity based on the generic
BerryTella P2P framework.
P2P framework.
"""

#--------------------------------------------------------------------------
def __init__(self, maxpeers, serverport):
#--------------------------------------------------------------------------
""" Initializes the peer to support connections up to maxpeers number
of peers, with its server listening on the specified port. Also sets
the dictionary of local files to empty and adds handlers to the
BTPeer framework.
Peer framework.
"""
BTPeer.__init__(self, maxpeers, serverport)
Peer.__init__(self, maxpeers, serverport)

self.files = {} # available files: name --> peerid mapping

Expand All @@ -51,21 +45,13 @@ def __init__(self, maxpeers, serverport):
for mt in handlers:
self.addhandler(mt, handlers[mt])

# end FilerPeer constructor



#--------------------------------------------------------------------------
def __debug(self, msg):
#--------------------------------------------------------------------------
if self.debug:
btdebug(msg)

debug(msg)


#--------------------------------------------------------------------------
def __router(self, peerid):
#--------------------------------------------------------------------------
if peerid not in self.getpeerids():
return (None, None, None)
else:
Expand All @@ -74,16 +60,12 @@ def __router(self, peerid):
return rt



#--------------------------------------------------------------------------
def __handle_insertpeer(self, peerconn, data):
#--------------------------------------------------------------------------
""" Handles the INSERTPEER (join) message type. The message data
should be a string of the form, "peerid host port", where peer-id
is the canonical name of the peer that desires to be added to this
peer's list of peers, host and port are the necessary data to connect
to the peer.
"""
self.peerlock.acquire()
try:
Expand All @@ -110,13 +92,8 @@ def __handle_insertpeer(self, peerconn, data):
finally:
self.peerlock.release()

# end handle_insertpeer method



#--------------------------------------------------------------------------
def __handle_listpeers(self, peerconn, data):
#--------------------------------------------------------------------------
""" Handles the LISTPEERS message type. Message data is not used. """
self.peerlock.acquire()
try:
Expand All @@ -129,51 +106,40 @@ def __handle_listpeers(self, peerconn, data):
self.peerlock.release()



#--------------------------------------------------------------------------
def __handle_peername(self, peerconn, data):
#--------------------------------------------------------------------------
""" Handles the NAME message type. Message data is not used. """
""" Handles the NAME message type. Message data is not used.
"""
peerconn.senddata(REPLY, self.myid)



# QUERY arguments: "return-peerid key ttl"
#--------------------------------------------------------------------------
def __handle_query(self, peerconn, data):
#--------------------------------------------------------------------------
""" Handles the QUERY message type. The message data should be in the
format of a string, "return-peer-id key ttl", where return-peer-id
is the name of the peer that initiated the query, key is the (portion
of the) file name being searched for, and ttl is how many further
levels of peers this query should be propagated on.
"""
# self.peerlock.acquire()

try:
peerid, key, ttl = data.split()
peerconn.senddata(REPLY, 'Query ACK: %s' % key)
except:
self.__debug('invalid query %s: %s' % (str(peerconn), data))
peerconn.senddata(ERROR, 'Query: incorrect arguments')
# self.peerlock.release()

t = threading.Thread(target=self.__processquery,
args=[peerid, key, int(ttl)])
t.start()



#
#--------------------------------------------------------------------------
def __processquery(self, peerid, key, ttl):
#--------------------------------------------------------------------------
""" Handles the processing of a query message after it has been
received and acknowledged, by either replying with a QRESPONSE message
if the file is found in the local list of files, or propagating the
message onto all immediate neighbors.
"""

for fname in self.files.keys():
if key in fname:
fpeerid = self.files[fname]
Expand All @@ -194,16 +160,13 @@ def __processquery(self, peerid, key, ttl):
self.sendtopeer(nextpid, QUERY, msgdata)



#--------------------------------------------------------------------------
def __handle_qresponse(self, peerconn, data):
#--------------------------------------------------------------------------
""" Handles the QRESPONSE message type. The message data should be
in the format of a string, "file-name peer-id", where file-name is
the file that was queried about and peer-id is the name of the peer
that has a copy of the file.
"""

try:
fname, fpeerid = data.split()
if fname in self.files:
Expand All @@ -216,15 +179,12 @@ def __handle_qresponse(self, peerconn, data):
traceback.print_exc()



#--------------------------------------------------------------------------
def __handle_fileget(self, peerconn, data):
#--------------------------------------------------------------------------
""" Handles the FILEGET message type. The message data should be in
the format of a string, "file-name", where file-name is the name
of the file to be fetched.
"""

fname = data
if fname not in self.files:
self.__debug('File not found %s' % fname)
Expand All @@ -234,7 +194,7 @@ def __handle_fileget(self, peerconn, data):
fd = file(fname, 'r')
filedata = ''
while True:
data = fd.read(2048)
data = fd.read(204800)
if not len(data):
break
peerconn.senddata(REPLY, data)
Expand All @@ -245,15 +205,14 @@ def __handle_fileget(self, peerconn, data):
peerconn.senddata(ERROR, 'Error reading file')
return

#--------------------------------------------------------------------------

def __handle_quit(self, peerconn, data):
#--------------------------------------------------------------------------
""" Handles the QUIT message type. The message data should be in the
format of a string, "peer-id", where peer-id is the canonical
name of the peer that wishes to be unregistered from this
peer's directory.
"""

self.peerlock.acquire()
try:
peerid = data.lstrip().rstrip()
Expand All @@ -269,21 +228,17 @@ def __handle_quit(self, peerconn, data):
finally:
self.peerlock.release()



# precondition: may be a good idea to hold the lock before going
# into this function
#--------------------------------------------------------------------------
def buildpeers(self, host, port, hops=1):
#--------------------------------------------------------------------------
""" buildpeers(host, port, hops)
Attempt to build the local peer list up to the limit stored by
self.maxpeers, using a simple depth-first search given an
initial host and port as starting point. The depth of the
search is limited by the hops parameter.
"""

if self.maxpeersreached() or not hops:
return

Expand Down Expand Up @@ -321,10 +276,9 @@ def buildpeers(self, host, port, hops=1):
self.removepeer(peerid)



#--------------------------------------------------------------------------
def addlocalfile(self, filename):
#--------------------------------------------------------------------------
""" Registers a locally-stored file with the peer. """
""" Registers a locally-stored file with the peer.
"""

self.files[filename] = None
self.__debug("Added local file %s" % filename)
Loading

0 comments on commit c3faaa3

Please sign in to comment.