<commit_before>#!/usr/bin/env python2.3
#
# (C) 2004 British Broadcasting Corporation and Kamaelia Contributors(1)
#     All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser General Public License, V2.1
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
#     http://kamaelia.sourceforge.net/AUTHORS - please extend this file,
#     not this notice.
# (2) Reproduced in the COPYING file, and at:
#     http://kamaelia.sourceforge.net/COPYING
# Under section 3.5 of the MPL, we are using this text since we deem the MPL
# notice inappropriate for this file. As per MPL/GPL/LGPL removal of this
# notice is prohibited.
#
# Please contact us via: <EMAIL>
# to discuss alternative licensing.
# -------------------------------------------------------------------------

import socket

import errno
try:
# We use several values of windows only socket errors so it works on Windows too.
    test = errno.WSAEISCONN
except AttributeError, e: 
    # We are running on something other than Windows.  We want to define the used
    # errno values to something that will not occur in real usage.  No numbers can be
    #guaranteed not to be used so I set them to a string.
    errno.WSAEISCONN = "fish"
try:
    test = errno.WSAEISCONN
except AttributeError, e:
    errno.WSAEWOULDBLOCK = "fish"
    
import Axon
from Axon.util import Finality
from Axon.Component import component
from Axon.Ipc import newComponent, status
from Kamaelia.KamaeliaIPC import socketShutdown, newCSA
from Kamaelia.Internet.ConnectedSocketAdapter import ConnectedSocketAdapter
import Axon.CoordinatingAssistantTracker as cat

import Selector

class TCPClient(component):
   Inboxes = ["inbox", "_socketFeedback", "control"]
   Outboxes = ["outbox","signal","_selectorSignal"]
   Usescomponents=[ConnectedSocketAdapter] # List of classes used.

   def __init__(self,host,port,chargen=0,delay=0):
      self.__super.__init__()
      self.host = host
      self.port = port
      self.chargen=chargen
      self.delay=delay

   def main(self):
      import time
      t=time.time()
      while time.time()-t<self.delay:
         yield 1
      for v in self.runClient():
         yield v
      print "We have indeed ceased looking at the connection. "
      print "The stuff going on elsewhere is spurious"
      print "if we're closing down, and we know we're closing down,"
      print "then can send shutdown info from here"

   def setupCSA(self, sock):
      CSA = ConnectedSocketAdapter(sock) #  self.createConnectedSocket(sock)
      self.addChildren(CSA)
      selectorService , newSelector = Selector.selectorComponent.getSelectorService(self.tracker)
      if newSelector:
         self.addChildren(newSelector)

      self.link((self, "_selectorSignal"),selectorService)
      self.link((CSA, "FactoryFeedback"),(self,"_socketFeedback"))
      self.link((CSA, "outbox"), (self, "outbox"), passthrough=2)
      self.link((self, "inbox"), (CSA, "DataSend"), passthrough=1)

      self.send(newCSA(self, (CSA,sock)), "_selectorSignal")
      return self.childComponents()

   def waitCSAClose(self):
      if self.dataReady("_socketFeedback"):
         message = self.recv("_socketFeedback")
         if isinstance(message, socketShutdown):
            return False
      return True

   def safeConnect(self, sock, *sockArgsList):
      try:
         sock.connect(*sockArgsList); # Expect socket.error: (115, 'Operation now in progress')
            # EALREADY
            #   The  socket  is  non-blocking  and  a  previous connection
            #   attempt has not yet been completed.
         self.connecting=0
         self.connected=1
         return True
      except socket.error, socket.msg:
         (errorno, errmsg) = socket.msg.args
         if errorno==errno.EALREADY:
            # The socket is non-blocking and a previous connection attempt has not yet been completed
            # We handle this by allowing  the code to come back and repeatedly retry
            # connecting. This is a valid, if brute force approach.
            assert(self.connecting==1)
            return False
         if errorno==errno.EINPROGRESS or errorno==errno.WSAEWOULDBLOCK:
            #The socket is non-blocking and the connection cannot be completed immediately.
            # We handle this by allowing  the code to come back and repeatedly retry
            # connecting. Rather brute force.
            self.connecting=1
            return False # Not connected should retry until no error
         if errorno == errno.WSAEISCONN:
             # This is a windows error indicating the connection has already been made.
             # This is actually an alternate sucess case to a truth response immediately.
             # self.connected = 1 # If connected is actually used then it should be set here too
             self.connecting = 0 # as with the no exception case.
             return True
         # Anything else is an error we don't handle
         raise socket.msg

   def runClient(self,sock=None):
      # The various numbers yielded here indicate progress through the function, and
      # nothing else specific.
      try:
         print "TCPC: RHUBARB", 87
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM); yield 0.3
         try:
            sock.setblocking(0); yield 0.6
            try:
               while not self.safeConnect(sock,(self.host, self.port)):
                  yield 1
               yield newComponent(*self.setupCSA(sock))
               while self.waitCSAClose():
                  self.pause()
                  yield 2
               print "TCPC: I would expect to get here"
               raise Finality
            except Exception, x:
               print "TCPC: I think we do indeed shutdown?"
               result = sock.shutdown(2) ; yield 3
               print "TCPC: We do indeed :)"
               raise x  # XXXX If X is not finality, an error message needs to get sent _somewhere_ else
               # The logical place to send the error is to the signal outbox
         except Exception, x:<commit_msg>Removal of unused variable.  Just a cleanup operation.<commit_after>#!/usr/bin/env python2.3
#
# (C) 2004 British Broadcasting Corporation and Kamaelia Contributors(1)
#     All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser General Public License, V2.1
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
#     http://kamaelia.sourceforge.net/AUTHORS - please extend this file,
#     not this notice.
# (2) Reproduced in the COPYING file, and at:
#     http://kamaelia.sourceforge.net/COPYING
# Under section 3.5 of the MPL, we are using this text since we deem the MPL
# notice inappropriate for this file. As per MPL/GPL/LGPL removal of this
# notice is prohibited.
#
# Please contact us via: <EMAIL>
# to discuss alternative licensing.
# -------------------------------------------------------------------------

import socket

import errno
try:
# We use several values of windows only socket errors so it works on Windows too.
    test = errno.WSAEISCONN
except AttributeError, e: 
    # We are running on something other than Windows.  We want to define the used
    # errno values to something that will not occur in real usage.  No numbers can be
    #guaranteed not to be used so I set them to a string.
    errno.WSAEISCONN = "fish"
try:
    test = errno.WSAEISCONN
except AttributeError, e:
    errno.WSAEWOULDBLOCK = "fish"
    
import Axon
from Axon.util import Finality
from Axon.Component import component
from Axon.Ipc import newComponent, status
from Kamaelia.KamaeliaIPC import socketShutdown, newCSA
from Kamaelia.Internet.ConnectedSocketAdapter import ConnectedSocketAdapter
import Axon.CoordinatingAssistantTracker as cat

import Selector

class TCPClient(component):
   Inboxes = ["inbox", "_socketFeedback", "control"]
   Outboxes = ["outbox","signal","_selectorSignal"]
   Usescomponents=[ConnectedSocketAdapter] # List of classes used.

   def __init__(self,host,port,chargen=0,delay=0):
      self.__super.__init__()
      self.host = host
      self.port = port
      self.chargen=chargen
      self.delay=delay

   def main(self):
      import time
      t=time.time()
      while time.time()-t<self.delay:
         yield 1
      for v in self.runClient():
         yield v
      print "We have indeed ceased looking at the connection. "
      print "The stuff going on elsewhere is spurious"
      print "if we're closing down, and we know we're closing down,"
      print "then can send shutdown info from here"

   def setupCSA(self, sock):
      CSA = ConnectedSocketAdapter(sock) #  self.createConnectedSocket(sock)
      self.addChildren(CSA)
      selectorService , newSelector = Selector.selectorComponent.getSelectorService(self.tracker)
      if newSelector:
         self.addChildren(newSelector)

      self.link((self, "_selectorSignal"),selectorService)
      self.link((CSA, "FactoryFeedback"),(self,"_socketFeedback"))
      self.link((CSA, "outbox"), (self, "outbox"), passthrough=2)
      self.link((self, "inbox"), (CSA, "DataSend"), passthrough=1)

      self.send(newCSA(self, (CSA,sock)), "_selectorSignal")
      return self.childComponents()

   def waitCSAClose(self):
      if self.dataReady("_socketFeedback"):
         message = self.recv("_socketFeedback")
         if isinstance(message, socketShutdown):
            return False
      return True

   def safeConnect(self, sock, *sockArgsList):
      try:
         sock.connect(*sockArgsList); # Expect socket.error: (115, 'Operation now in progress')
            # EALREADY
            #   The  socket  is  non-blocking  and  a  previous connection
            #   attempt has not yet been completed.
         self.connecting=0
         return True
      except socket.error, socket.msg:
         (errorno, errmsg) = socket.msg.args
         if errorno==errno.EALREADY:
            # The socket is non-blocking and a previous connection attempt has not yet been completed
            # We handle this by allowing  the code to come back and repeatedly retry
            # connecting. This is a valid, if brute force approach.
            assert(self.connecting==1)
            return False
         if errorno==errno.EINPROGRESS or errorno==errno.WSAEWOULDBLOCK:
            #The socket is non-blocking and the connection cannot be completed immediately.
            # We handle this by allowing  the code to come back and repeatedly retry
            # connecting. Rather brute force.
            self.connecting=1
            return False # Not connected should retry until no error
         if errorno == errno.WSAEISCONN:
             # This is a windows error indicating the connection has already been made.
             self.connecting = 0 # as with the no exception case.
             return True
         # Anything else is an error we don't handle
         raise socket.msg

   def runClient(self,sock=None):
      # The various numbers yielded here indicate progress through the function, and
      # nothing else specific.
      try:
         print "TCPC: RHUBARB", 87
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM); yield 0.3
         try:
            sock.setblocking(0); yield 0.6
            try:
               while not self.safeConnect(sock,(self.host, self.port)):
                  yield 1
               yield newComponent(*self.setupCSA(sock))
               while self.waitCSAClose():
                  self.pause()
                  yield 2
               print "TCPC: I would expect to get here"
               raise Finality
            except Exception, x:
               print "TCPC: I think we do indeed shutdown?"
               result = sock.shutdown(2) ; yield 3
               print "TCPC: We do indeed :)"
               raise x  # XXXX If X is not finality, an error message needs to get sent _somewhere_ else
               # The logical place to send the error is to the signal outbox
         except Exception, x:
{'fraction_non_alphanumeric': 0.08890701468189233, 'fraction_numerical': 0.006851549755301794, 'mean_word_length': 2.455749718151071, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2362530', 'n_tokens_mistral': 3407, 'n_tokens_neox': 3277, 'n_words': 1227}