| 140 | |
| 141 | # Send a command to peer and return response value |
| 142 | def request(self, cmd, params={}, stream_to=None): |
| 143 | if not self.connection or self.connection.closed: |
| 144 | self.connect() |
| 145 | if not self.connection: |
| 146 | self.onConnectionError("Reconnect error") |
| 147 | return None # Connection failed |
| 148 | |
| 149 | self.log("Send request: %s %s %s %s" % (params.get("site", ""), cmd, params.get("inner_path", ""), params.get("location", ""))) |
| 150 | |
| 151 | for retry in range(1, 4): # Retry 3 times |
| 152 | try: |
| 153 | if not self.connection: |
| 154 | raise Exception("No connection found") |
| 155 | res = self.connection.request(cmd, params, stream_to) |
| 156 | if not res: |
| 157 | raise Exception("Send error") |
| 158 | if "error" in res: |
| 159 | self.log("%s error: %s" % (cmd, res["error"])) |
| 160 | self.onConnectionError("Response error") |
| 161 | break |
| 162 | else: # Successful request, reset connection error num |
| 163 | self.connection_error = 0 |
| 164 | self.time_response = time.time() |
| 165 | if res: |
| 166 | return res |
| 167 | else: |
| 168 | raise Exception("Invalid response: %s" % res) |
| 169 | except Exception as err: |
| 170 | if type(err).__name__ == "Notify": # Greenlet killed by worker |
| 171 | self.log("Peer worker got killed: %s, aborting cmd: %s" % (err.message, cmd)) |
| 172 | break |
| 173 | else: |
| 174 | self.onConnectionError("Request error") |
| 175 | self.log( |
| 176 | "%s (connection_error: %s, hash_failed: %s, retry: %s)" % |
| 177 | (Debug.formatException(err), self.connection_error, self.hash_failed, retry) |
| 178 | ) |
| 179 | time.sleep(1 * retry) |
| 180 | self.connect() |
| 181 | return None # Failed after 4 retry |
| 182 | |
| 183 | # Get a file content from peer |
| 184 | def getFile(self, site, inner_path, file_size=None, pos_from=0, pos_to=None, streaming=False): |