Started by main() on a single thread, this code manages reading UDP packets
480726
@SuppressWarnings("resource")
  public void run() {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY-1);
    DatagramChannel sock = H2O._udpSocket, errsock = null;
    boolean saw_error = false;

    while( true ) {
      try {
        // Cleanup from any prior socket failures.  Rare unless we're really sick.
        if( errsock != null ) { // One time attempt a socket close
          final DatagramChannel tmp2 = errsock; errsock = null;
          tmp2.close();       // Could throw, but errsock cleared for next pass
        }
        if( saw_error ) Thread.sleep(1000); // prevent deny-of-service endless socket-creates
        saw_error = false;

        // ---
        // Common-case setup of a socket
        if( sock == null ) {
          sock = DatagramChannel.open();
          sock.socket().bind(H2O.SELF._key);
        }

        // Receive a packet & handle it
        basic_packet_handling(new AutoBuffer(sock));

      } catch( java.nio.channels.AsynchronousCloseException ex ) {
        break;                  // Socket closed for shutdown
      } catch( java.nio.channels.ClosedChannelException ex ) {
        break;                  // Socket closed for shutdown
      } catch( Exception e ) {
        // On any error from anybody, close all sockets & re-open
        Log.err("UDP Receiver error on port "+H2O.H2O_PORT,e);
        saw_error = true;
        errsock  = sock ;  sock  = null; // Signal error recovery on the next loop
      }
    }
  }
1196252
@Override
	public void run() {
		try {
			byte[] bytes = new byte[8192];

			int pos = 0;

			// Read the first part of the header
			while (true) {
				int read = input.read();
				if (read == -1) {
					break;
				}
				bytes[pos] = (byte) read;
				if (pos >= 4) {
					// Find \r\n\r\n
					if (bytes[pos - 3] == '\r' && bytes[pos - 2] == '\n' && bytes[pos - 1] == '\r' && bytes[pos] == '\n') {
						break;
					}
				}
				pos++;
			}

			// Read from the header data
			BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes, 0, pos)));

			// Read the first line, defined as the status line
			String l = reader.readLine();

			// Sanity check, after not returning data the client MIGHT attempt
			// to send something back and it will end up being something we
			// cannot read.
			if (l == null) {
				sendError(HttpStatus.BAD_REQUEST, HttpStatus.BAD_REQUEST.toString());
				return;
			}

			// Otherwise continue on
			int idx = l.indexOf(' ');

			// Split out the method and path
			String methodString = l.substring(0, idx);
			HttpMethod method = null;

			for (HttpMethod m : HttpMethod.values()) {
				if (m.name().equals(methodString)) {
					method = m;
				}
			}

			// If it's an unknown method it won't be defined in the enum
			if (method == null) {
				sendError(HttpStatus.METHOD_NOT_ALLOWED, "This server currently does not support this method.");
				return;
			}

			// The URI
			String path = l.substring(idx + 1, l.lastIndexOf(' '));

			// Parse the headers
			Map<String, String> headers = new HashMap<String, String>();
			while ((l = reader.readLine()) != null) {
				// End header.
				if (l.equals(""))
					break;

				// Headers are usually Key: Value
				String key = l.substring(0, l.indexOf(':'));
				String value = l.substring(l.indexOf(':') + 1).trim();

				// Put the header in the map, correcting the header key if
				// needed.
				headers.put(HttpUtil.capitalizeHeader(key), value);
			}

			// Close the reader used for the header
			reader.close();

			HttpRequest request = new HttpRequest(this, method, path, headers);

			int questionIdx = path.indexOf('?');
			if (questionIdx != -1) {
				String queryString = path.substring(questionIdx + 1);
				request.setQueryString(queryString);
				request.setGetData(HttpUtil.parseData(queryString));

				path = path.substring(0, questionIdx);
				request.setUri(path);
			}

			// Parse cookies, only if the server has the capability enabled (to save time, processing power, and memory if it isn't used)
			if (headers.containsKey(HttpHeader.COOKIE) && server.hasCapability(HttpCapability.COOKIES)) {
				List<HttpCookie> cookies = new LinkedList<HttpCookie>();
				StringTokenizer tok = new StringTokenizer(headers.get(HttpHeader.COOKIE), ";");
				while (tok.hasMoreTokens()) {
					String token = tok.nextToken();
					int eqIdx = token.indexOf('=');
					if (eqIdx == -1) {
						// Invalid cookie
						continue;
					}
					String key = token.substring(0, eqIdx);
					String value = token.substring(eqIdx + 1);

					cookies.add(new HttpCookie(key, value));
				}
				request.setCookies(cookies);
			}

			// Read the request data
			if (method == HttpMethod.POST) {
				boolean acceptsStandard = server.hasCapability(HttpCapability.STANDARD_POST), acceptsMultipart = server.hasCapability(HttpCapability.MULTIPART_POST);
				// Make sure the server will accept POST or Multipart POST
				// before we start checking the content
				if (acceptsStandard || acceptsMultipart) {
					// Validate that there's a length header
					if (!headers.containsKey(HttpHeader.CONTENT_LENGTH)) {
						// If there isn't, send the correct response
						sendError(HttpStatus.LENGTH_REQUIRED, HttpStatus.LENGTH_REQUIRED.toString());
					} else {
						// Otherwise, continue on
						int contentLength = Integer.parseInt(headers.get(HttpHeader.CONTENT_LENGTH));

						String contentTypeHeader = headers.get(HttpHeader.CONTENT_TYPE);

						// Copy it to trim to what we need, keeping the original
						// to parse the boundary
						String contentType = contentTypeHeader;

						if (contentTypeHeader.indexOf(';') != -1) {
							contentType = contentTypeHeader.substring(0, contentTypeHeader.indexOf(';'));
						}
						// Check the content type
						if (contentType.equalsIgnoreCase("multipart/form-data")) {
							if (acceptsMultipart) {
								// The server will accept post requests with
								// multipart data
								String boundary = contentTypeHeader.substring(contentTypeHeader.indexOf(';')).trim();
								boundary = boundary.substring(boundary.indexOf('=') + 1);
								// Parse file uploads etc.
								request.setPostData(readMultipartData(boundary));
							} else {
								// The server has the multipart post
								// capabilities disabled
								sendError(HttpStatus.BAD_REQUEST, "This server does not support multipart/form-data requests.");
							}
						} else {
							if (acceptsStandard) {
								// Read the reported content length, TODO some
								// kind of check/timeout to make sure it won't
								// hang the thread?
								byte[] b = new byte[contentLength];
								int read, totalRead = 0;
								while (contentLength - totalRead > 0 && (read = input.read(b, totalRead, contentLength - totalRead)) > -1) {
									totalRead += read;
								}
								// We either read all of the data, or the
								// connection closed.
								if (totalRead < contentLength) {
									sendError(HttpStatus.BAD_REQUEST, "Unable to read correct amount of data!");
								} else {
									String data = new String(b);
									if (contentType.equalsIgnoreCase("application/x-www-form-urlencoded")) {
										// It is FOR SURE regular data.
										request.setPostData(HttpUtil.parseData(data));
									} else {
										// Could be JSON or XML etc
										request.setData(data);
									}
								}
							} else {
								// The server has the Standard post capabilities
								// disabled
								sendError(HttpStatus.BAD_REQUEST, "This server does not support POST requests.");
							}
						}
					}
				} else {
					// The server has the Standard and Multipart capabilities
					// disabled
					sendError(HttpStatus.METHOD_NOT_ALLOWED, "This server does not support POST requests.");
				}
			}

			this.request = request;

			server.dispatchRequest(request);
		} catch (SocketException e) {
			//Socket was closed probably
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
99060
public void run() {
        try {
            mServer = new ServerSocket(mPort, VIEW_SERVER_MAX_CONNECTIONS, InetAddress.getLocalHost());
        } catch (Exception e) {
            Log.w(LOG_TAG, "Starting ServerSocket error: ", e);
        }

        while (mServer != null && Thread.currentThread() == mThread) {
            // Any uncaught exception will crash the system process
            try {
                Socket client = mServer.accept();
                if (mThreadPool != null) {
                    mThreadPool.submit(new ViewServerWorker(client));
                } else {
                    try {
                        client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                Log.w(LOG_TAG, "Connection error: ", e);
            }
        }
    }
284144
def main():
    """"""
    # First open a socket to the kernel. Same one used for sending and receiving.
    sk = nl_socket_alloc()  # Creates an `nl_sock` instance.
    ret = nl_connect(sk, NETLINK_ROUTE)  # Create file descriptor and bind socket.
    if ret < 0:
        reason = errmsg[abs(ret)]
        return error('nl_connect() returned {0} ({1})'.format(ret, reason))

    # Next we send the request to the kernel.
    rt_hdr = rtgenmsg(rtgen_family=socket.AF_PACKET)
    ret = nl_send_simple(sk, RTM_GETLINK, NLM_F_REQUEST | NLM_F_DUMP, rt_hdr, rt_hdr.SIZEOF)
    if ret < 0:
        reason = errmsg[abs(ret)]
        return error('nl_send_simple() returned {0} ({1})'.format(ret, reason))
    print('Sent {0} bytes to the kernel.'.format(ret))

    # Finally we'll retrieve the kernel's answer, process it, and call any callbacks attached to the `nl_sock` instance.
    nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, callback, None)  # Add callback to the `nl_sock` instance.
    ret = nl_recvmsgs_default(sk)  # Get kernel's answer, and call attached callbacks.
    if ret < 0:
        reason = errmsg[abs(ret)]
        return error('nl_recvmsgs_default() returned {0} ({1})'.format(ret, reason))
589678
function main() {
  var server = new grpc.Server();
  server.addService(hello_proto.Greeter.service, {sayHello: sayHello});
  server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
  server.start();
}
537144
def read_packets(self):
        """"""
        while self.running:
            packet_length = self.client.recv(2)
            if len(packet_length) < 2:
                self.stop()
                continue
            packet_length = struct.unpack("<h", packet_length)[0] - 2

            data = self.client.recv(packet_length)
            packno = data[0]

            try:
                parser = "Packet" + format(packno, 'x').upper() + "Parser"
                packet_class = getattr(packets, parser)
                packet_class().parse(self.world, self.player, data, self._evman)
            except AttributeError as e:
                pass

            if packno == 2:
                self.stop()
                continue
154313
def run(self):
        
        # Bind the socket to the port
        logging.info("Server starts socket on {addr}".format(addr=self.server_address))

        # Create a UDS socket
        if six.PY2:
            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.listen(sock)
            sock.close()
        else:
            with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
                self.listen(sock)
        try:
            os.unlink(self.server_address)
        except OSError:
            if os.path.exists(self.server_address):
                raise
        return
1053820
def main_loop():
    ''''''
    while True:
        if mestate is None or mestate.exit:
            return
        while not mestate.input_queue.empty():
            line = mestate.input_queue.get()
            cmds = line.split(';')
            for c in cmds:
                process_stdin(c)
        time.sleep(0.1)
1274355
def router_main(self):    
        '''
        
        '''
        while True:
            gotpkt = True
            try:
                timestamp,dev,pkt = self.net.recv_packet(timeout=1.0)
            except NoPackets:
                log_debug("No packets available in recv_packet")
                gotpkt = False
            except Shutdown:
                log_debug("Got shutdown signal")
                break

            if gotpkt:
                log_debug("Got a packet: {}".format(str(pkt)))
607678
@Override
	public void run() {
		try {

			// Loop
			while (true) {

				// Waiting for sockets
				int n;
				try {
					n = selector.select(3000);
				} catch (NullPointerException nullPointer) {
					continue;
				} catch (Exception cause) {
					break;
				}

				// Open new connections
				SendBuffer buffer = opened.poll();
				SelectionKey key = null;
				while (buffer != null) {
					try {
						InetSocketAddress address;
						try {
							address = new InetSocketAddress(buffer.host, buffer.port);
						} catch (UnresolvedAddressException dnsError) {

							// Workaround: unable to resolve host name
							Tree info = transporter.getDescriptor(buffer.nodeID);
							if (info == null) {
								throw dnsError;
							}
							String ip = getHostOrIP(false, info);
							if (ip == null || buffer.host.equalsIgnoreCase(ip)) {
								throw dnsError;
							}
							if (debug) {
								logger.info("Unable to resolve hostname \"" + buffer.host + "\", trying with \"" + ip
										+ "\"...");
							}
							address = new InetSocketAddress(ip, buffer.port);
						}
						SocketChannel channel = SocketChannel.open(address);
						channel.configureBlocking(false);

						channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
						channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
						channel.setOption(StandardSocketOptions.SO_LINGER, -1);

						key = channel.register(selector, SelectionKey.OP_WRITE);
						key.attach(buffer);
						buffer.connected(key, channel);
						if (debug) {
							logger.info("Client channel opened to \"" + buffer.nodeID + "\".");
						}

					} catch (Throwable cause) {
						if (buffer != null) {
							synchronized (buffers) {
								buffers.remove(buffer.nodeID);
							}
							transporter.unableToSend(buffer.nodeID, buffer.getUnsentPackets(), cause);
						}
					}
					buffer = opened.poll();
				}

				if (n < 1) {
					continue;
				}
				Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
				while (keys.hasNext()) {
					key = keys.next();
					if (key == null) {
						continue;
					}
					if (!key.isValid()) {
						keys.remove();
						continue;
					}
					if (key.isWritable()) {

						// Write data
						buffer = null;
						try {
							buffer = (SendBuffer) key.attachment();
							if (buffer != null) {
								buffer.write();
							}
						} catch (Exception cause) {
							if (buffer != null) {
								synchronized (buffers) {
									buffers.remove(buffer.nodeID);
								}
								transporter.unableToSend(buffer.nodeID, buffer.getUnsentPackets(), cause);
							}
							close(key, cause);
						}
					}
					keys.remove();
				}
			}

		} catch (Exception fatal) {
			logger.error("TCP writer closed!", fatal);
		}
	}
503773
void start() {
    for (int i = 0; i < threadCount; i++) {
      Runnable r = null;
      switch (config.getPayloadConfig().getPayloadCase()) {
        case SIMPLE_PARAMS: {
          if (config.getClientType() == Control.ClientType.ASYNC_CLIENT) {
            if (config.getRpcType() == Control.RpcType.UNARY) {
              r = new AsyncUnaryWorker(clients[i % clients.length]);
            } else if (config.getRpcType() == Control.RpcType.STREAMING) {
              r = new AsyncPingPongWorker(mat, clients[i % clients.length]);
            }
          }
          break;
        }
        default: {
          throw Status.UNIMPLEMENTED.withDescription(
              "Unknown payload case " + config.getPayloadConfig().getPayloadCase().name())
              .asRuntimeException();
        }
      }
      if (r == null) {
        throw new IllegalStateException(config.getRpcType().name()
            + " not supported for client type "
            + config.getClientType());
      }
      fixedThreadPool.execute(r);
    }
    if (osBean != null) {
      lastMarkCpuTime = osBean.getProcessCpuTime();
    }
  }
335362
@Override
    public long processSyncReadRequest(long numBytes, int timeout) throws IOException {
        long bytesRead = 0L;
        if (numBytes != 0L) {
            if (this.blockWait == null) {
                this.blockWait = new SimpleSync();
            }

            this.blockingIOError = null;

            // before we read, signal that we want to do the read ourselves
            // and not the worker threads.
            this.blockedThread = true;

            VirtualConnection vc = readInternal(numBytes, null, false, timeout);

            while (vc == null) {
                // block until we are told to read
                this.blockWait.simpleWait();

                if (this.blockingIOError == null) {
                    vc = ((NioTCPChannel) getTCPConnLink().getTCPChannel()).getWorkQueueManager().processWork(this, 1);
                } else {
                    break;
                }
            }
            this.blockedThread = false;

            if (this.blockingIOError != null) {
                throw this.blockingIOError;
            }
            // return the number of bytes read
            bytesRead = getIOCompleteAmount();
        } else {
            // read immediately and return
            setJITAllocateAction(false);

            if ((getJITAllocateSize() > 0) && (getBuffers() == null)) {
                // User wants us to allocate the buffer
                if (getConfig().getAllocateBuffersDirect()) {
                    setBuffer(ChannelFrameworkFactory.getBufferManager().allocateDirect(getJITAllocateSize()));
                } else {
                    setBuffer(ChannelFrameworkFactory.getBufferManager().allocate(getJITAllocateSize()));
                }
                setJITAllocateAction(true);
            }
            WsByteBuffer wsBuffArray[] = getBuffers();
            NioSocketIOChannel channel = (NioSocketIOChannel) getTCPConnLink().getSocketIOChannel();
            if (wsBuffArray.length == 1) {
                bytesRead = channel.read(wsBuffArray[0].getWrappedByteBufferNonSafe());
            } else {
                bytesRead = channel.read(getByteBufferArray());
            }

            if (bytesRead < 0) {
                if (getJITAllocateAction()) {
                    getBuffer().release();
                    setBuffer(null);
                    setJITAllocateAction(false);
                }
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Tr.event(this, tc, "Sync read throwing IOException");
                }

                // Add local and remote address information
                String s = "Read failed.  End of data reached.";
                try {
                    SocketAddress iaLocal = getTCPConnLink().getSocketIOChannel().getSocket().getLocalSocketAddress();
                    SocketAddress iaRemote = getTCPConnLink().getSocketIOChannel().getSocket().getRemoteSocketAddress();
                    s = s + " local=" + iaLocal + " remote=" + iaRemote;
                } catch (Exception x) {
                    // do not alter the message if the socket got nuked while we tried to look at it
                }
                throw new IOException(s);
            }
        }
        return bytesRead;
    }
1049309
def start(self):
        

        if threading.current_thread().name == 'MainThread':
            signal.signal(signal.SIGINT, self.stop)

        logging.info('Started on {}'.format(self.address))

        while True:
            self.process()
783249
private void peek(String command, Socket socket, DataInputStream din) throws IOException {

        DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
        byte[] obs;
        boolean done;

        lock.lock();
        try {
            obs = getObservation(false);
            done = envState.done;
        } finally {
            lock.unlock();
        }

        dout.writeInt(obs.length);
        dout.write(obs);

        dout.writeInt(1);
        dout.writeByte(done ? 1 : 0);

        dout.flush();
    }
705779
public void run() {

	InputStream in   = null;
	OutputStream out = null;

	try {
	    in  = socket.getInputStream();
	    out = socket.getOutputStream();

	    try {

		String line;
		line = readLine(in);

		if (DEBUG_ON) debug("header: " + line);

		if (line.startsWith("GET") &&
		    (options & GassServer.READ_ENABLE) != 0) {

		    // copy to client

		    String path =
			line.substring(4, line.indexOf(' ', 4) );

		    do {
			line = readLine(in);
			if (DEBUG_ON) debug("header (get): " + line);
		    } while ( (line.length() != 0)
			      && (line.charAt(0) != '\r')
			      && (line.charAt(0) != '\n') );

		    transfer(out, path);

		} else if (line.startsWith("PUT") &&
			   ( ((options & GassServer.WRITE_ENABLE) != 0) ||
			     ((options & GassServer.CLIENT_SHUTDOWN_ENABLE) != 0) )) {

		    // copy from client

		    String path =
			line.substring(4, line.indexOf(' ', 4) );

		    transfer(in, path, false, out);

		    writeln(out, OKHEADER);

		} else if (line.startsWith("POST") &&
			   ( ((options & GassServer.WRITE_ENABLE) != 0) ||
			     ((options & GassServer.STDOUT_ENABLE) != 0) ||
			     ((options & GassServer.STDERR_ENABLE) != 0) ||
			     ((options & GassServer.CLIENT_SHUTDOWN_ENABLE) != 0) )) {
		    // append from client

		    int index = line.indexOf('?') + 1;
		    String path =
			line.substring(index, line.indexOf(' ', index) );

		    transfer(in, path, true, out);

		    writeln(out, OKHEADER);

		} else {
		    writeln(out, "HTTP/1.1 400 Bad Request" + CRLF);
		}

	    } catch (FileNotFoundException ex) {
		logger.debug("FileNotFoundException occured: " + ex.getMessage(), ex);

		StringBuffer buf = new StringBuffer(HEADER404)
		    .append(CONNECTION_CLOSE)
		    .append(SERVER)
		    .append(CONTENT_HTML)
		    .append(CONTENT_LENGTH).append(" ").append(MSG404.length())
		    .append(CRLF).append(CRLF)
		    .append(MSG404);

		out.write(buf.toString().getBytes());
		out.flush();
	    } catch (AuthorizationException ex) {
		logger.debug("Exception occured: Authorization failed");
		writeln(out, "HTTP/1.1 401 Authorization Failed" + CRLF);
	    } catch (Exception ex) {
		logger.debug("Exception occured: " + ex.getMessage(), ex);
		writeln(out, "HTTP/1.1 400 " + ex.getMessage() + CRLF);
	    }
	} catch (IOException e) {
	    logger.error("Error writing response: " + e.getMessage(), e);
	} finally {
	    try {
		socket.close();
	    } catch (IOException e) {}
	}
    }
1047490
def main(cls, args, settings=None, userdata=None): # pylint: disable=too-many-branches,too-many-statements
        
        # Packet Configuration
        logger.info('Using Packet configuration from %s', Focus.info(args.conf.name))
        try:
            conf = json.loads(args.conf.read())
        except ValueError as msg:
            logger.error('Unable to parse %s: %s', args.conf.name, msg)
            return 1

        # Handle Tags
        if args.tags and (args.create_spot or args.create_demand):
            logger.info('Assigning the following tags to the instance: %r', args.tags)

        if args.only:
            try:
                args.only = UserData.parse_only_criterias(args.only)
            except ValueError:
                logger.error('-only requires format of: name=value')
                return 1
            logging.info('Using filter %r to return only matching devices.', args.only)

        # Packet Manager
        try:
            cluster = PacketManager(conf)
        except PacketManagerException as msg:
            logger.error(msg)
            return 1
        project = cluster.conf.get('projects').get(args.project)

        # List Operations
        if args.list_projects:
            cluster.print_projects(cluster.list_projects())

        if args.list_plans:
            cluster.print_plans(cluster.list_plans())

        if args.list_spot_prices:
            cluster.print_spot_prices(cluster.list_spot_prices())

        if args.list_operating_systems:
            cluster.print_operating_systems(cluster.list_operating_systems())

        if args.list_facilities:
            cluster.print_facilities(cluster.list_facilities())

        if args.list_devices and args.project:
            cluster.print_devices(cluster.list_devices(project, conditions=args.only))

        if args.create_volume:
            if len(args.create_volume) < 4:
                logger.error('Not enough arguments for creating a volume storage.')
                return 1
            [plan, size, region, label] = args.create_volume
            try:
                cluster.create_volume(project, plan, size, region, label)
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        # Device Pre-Checks
        if (args.create_spot or args.create_demand) \
                and (args.region and args.plan):
            logging.info('Validating requested remote capacities ...')
            try:
                status = cluster.validate_capacity([
                    [args.region, args.plan, str(args.count)]
                ])
                if status:
                    logger.info('Requested capacities are available.')
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        # Device Creation
        if args.create_spot \
                and args.region \
                and args.plan \
                and args.max_spot_price \
                and args.os:
            try:
                devices = cluster.create_spot(project_id=project,
                                              facility=args.region,
                                              plan=args.plan,
                                              operating_system=args.os,
                                              spot_price_max=args.max_spot_price,
                                              tags=args.tags,
                                              userdata=userdata,
                                              count=args.count)
                cluster.print_devices(devices)
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        if args.create_demand \
                and args.region \
                and args.plan \
                and args.os:
            try:
                devices = cluster.create_demand(project_id=project,
                                                facility=args.region,
                                                plan=args.plan,
                                                tags=args.tags,
                                                operating_system=args.os,
                                                userdata=userdata,
                                                count=args.count)
                cluster.print_devices(devices)
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        # Device Operations
        if args.reboot:
            try:
                cluster.reboot(cluster.list_devices(project, conditions=args.only))
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        if args.stop:
            try:
                cluster.stop(cluster.list_devices(project, conditions=args.only))
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        if args.terminate:
            try:
                cluster.terminate(cluster.list_devices(project, conditions=args.only))
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        return 0
909642
public void start() {
        synchronized (LOCK) {
            if (!this.active) {
                this.active = true;
                logger.info("Starting UDP Manager");
                try {
                    generateTasks();
                    logger.info("Initialized UDP interface[" + inet + "]: bind address=" + bindAddress);
                } catch (IOException e) {
                    logger.error("An error occurred while initializing the polling tasks", e);
                    stop();
                }
            }
        }
    }