Load settings, initialize the {@link SocketWriter} pool and test the connection to the graphite server.

A {@link Logger#warn(String)} message is emitted if the connection to the graphite server fails.
348662
@Override
    public void start() {
        int port = getIntSetting(SETTING_PORT, DEFAULT_GRAPHITE_SERVER_PORT);
        String host = getStringSetting(SETTING_HOST);
        graphiteServerHostAndPort = new HostAndPort(host, port);

        logger.info("Start Graphite writer connected to '{}'...", graphiteServerHostAndPort);

        metricPathPrefix = getStringSetting(SETTING_NAME_PREFIX, DEFAULT_NAME_PREFIX);
        metricPathPrefix = getStrategy().resolveExpression(metricPathPrefix);
        if (!metricPathPrefix.isEmpty() && !metricPathPrefix.endsWith(".")) {
            metricPathPrefix = metricPathPrefix + ".";
        }

        GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
        config.setTestOnBorrow(getBooleanSetting("pool.testOnBorrow", true));
        config.setTestWhileIdle(getBooleanSetting("pool.testWhileIdle", true));
        config.setMaxTotal(getIntSetting("pool.maxActive", -1));
        config.setMaxIdlePerKey(getIntSetting("pool.maxIdle", -1));
        config.setMinEvictableIdleTimeMillis(getLongSetting("pool.minEvictableIdleTimeMillis", TimeUnit.MINUTES.toMillis(5)));
        config.setTimeBetweenEvictionRunsMillis(getLongSetting("pool.timeBetweenEvictionRunsMillis", TimeUnit.MINUTES.toMillis(5)));
        config.setJmxNameBase("org.jmxtrans.embedded:type=GenericKeyedObjectPool,writer=GraphiteWriter,name=");
        config.setJmxNamePrefix(graphiteServerHostAndPort.getHost() + "_" + graphiteServerHostAndPort.getPort());

        int socketConnectTimeoutInMillis = getIntSetting("graphite.socketConnectTimeoutInMillis", SocketWriterPoolFactory.DEFAULT_SOCKET_CONNECT_TIMEOUT_IN_MILLIS);

        String protocol = getStringSetting(SETTING_PROTOCOL, null);
        if (protocol != null && protocol.equalsIgnoreCase(PROTOCOL_UDP)) {
            socketWriterPool = new GenericKeyedObjectPool<HostAndPort, SocketWriter>(new UDPSocketWriterPoolFactory(UTF_8), config);
        } else {
            if (protocol == null) {
                // protocol not specified, use default one
                logger.info("Protocol unspecified, default protocol '{}' will be used.", PROTOCOL_TCP);
            } else if (PROTOCOL_TCP.equalsIgnoreCase(protocol) == false) {
                // unknown or protocol, use default one
                logger.warn("Unknown protocol specified '{}', default protocol '{}' will be used instead.", protocol, PROTOCOL_TCP);
            }
            String socketFactoryClassName = getStringSetting(SETTING_SOCKET_FACTORY, null);
            boolean useTls = getBooleanSetting(SETTING_USE_TLS, false);
            SocketFactory socketFactory;

            if (!StringUtils2.isNullOrEmpty(socketFactoryClassName)) {
                try {
                    socketFactory = (SocketFactory) Class.forName(socketFactoryClassName, true, Thread.currentThread().getContextClassLoader()).newInstance();
                } catch (Exception e) {
                    throw new RuntimeException("Exception instantiating SocketFactory '" + socketFactoryClassName + "'");
                }
            } else if (useTls) {
                boolean tlsInsecure = getBooleanSetting(SETTING_TLS_INSECURE, false);
                if (tlsInsecure) {
                    socketFactory = SslUtils.getTrustAllSSLSocketFactory();
                } else {
                    String keyStore = getStringSetting(SETTING_TLS_KEY_STORE, null);
                    String keyStorePassword = getStringSetting(SETTING_TLS_KEY_STORE_PASSWORD, null);
                    String trustStore = getStringSetting(SETTING_TLS_TRUST_STORE, null);
                    String trustStorePassword = getStringSetting(SETTING_TLS_TRUST_STORE_PASSWORD, null);
                    socketFactory = SslUtils.getSSLSocketFactory(keyStore, keyStorePassword, trustStore, trustStorePassword);
                }
            } else {
                socketFactory = SocketFactory.getDefault();
            }
            socketWriterPool = new GenericKeyedObjectPool<HostAndPort, SocketWriter>(new SocketWriterPoolFactory(socketFactory, UTF_8, socketConnectTimeoutInMillis), config);
        }

        if (isEnabled()) {
            try {
                SocketWriter socketWriter = socketWriterPool.borrowObject(graphiteServerHostAndPort);
                socketWriterPool.returnObject(graphiteServerHostAndPort, socketWriter);
            } catch (Exception e) {
                logger.warn("Test Connection: FAILURE to connect to Graphite server '{}'", graphiteServerHostAndPort, e);
            }
        }
    }
854913
void startEngine() throws ServerStartException {

		// setting up the server
		final boolean isDaemon = true;
		final boolean isSilent = false;

		final HsqlProperties hsqlProp = new HsqlProperties();

		// gives the chance to the descriptors to contribute to the server configuration.
		final AtomicInteger dbCounter = new AtomicInteger(0);
		for (HsqlDatabaseDescriptor db : dbs) {
			
			db.contributeToServerConfiguration(new LocationConfiguration() {

				@Override
				public void setLocation(String dbName, String location) {

					log.info("Registering db #{} : '{}' stored on '{}'", dbCounter, dbName, location);
					int dbIndex = dbCounter.getAndAdd(1);
					if (!(location.startsWith("file:") || location.startsWith("res:") || location
							.startsWith("mem:"))) {
						throw new IllegalArgumentException(location);
					}
					
					hsqlProp.setProperty("server.database." + dbIndex, location);
					hsqlProp.setProperty("server.dbname." + dbIndex, dbName);
				}

			});

		}
		// avoid to open a db remotely
		server = new Server();
		hsqlProp.setProperty("server.remote_open", false);
		try {
			server.setProperties(hsqlProp);
		} catch (IOException | AclFormatException e1) {
			throw new ServerStartException(e1);
		}

		server.setLogWriter(lubricantLoggerWriter.asPrintWriter());
		server.setDaemon(isDaemon);
		server.setSilent(isSilent);
		server.setTrace(false);
		server.setNoSystemExit(true);

		if (definedPort != null) {
			server.setPort(definedPort);
		}
		if (this.address != null) {
			server.setAddress(this.address);
		}

		for (int i = 0; i < this.dbs.size(); i++) {
			log.info("db " + i);
			log.info(server.getDatabaseType(i));
			log.info(server.getDatabaseName(i, true));
			log.info(server.getDatabasePath(i, true));
		}

		// dump config
		log.info("Starting HSQL standalone DBMS...");
		log.info("is daemon: {}", isDaemon);
		log.info("is silent: {}", isSilent);
		log.info("port: {} ", (definedPort != null ? definedPort
				: "HSQL default"));
		log.info("address: {} ", (address != null ? address : "HSQL default"));

		log.info("Waiting for hsql engine to start...");
		
		
		Integer state = server.start();
		Throwable serverError = server.getServerError();
		if(serverError!=null){
			throw new ServerStartException(serverError);
		}			
		do {
			state = server.getState();
			Thread.yield();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// nothing special
			}			
		}while(state != 1);
		
		log.info("Hsql engine started.");

		try{
			log.info("Starting databases post setup...");
			for (int i = 0; i < dbs.size(); i++) {
				final HsqlDatabaseDescriptor db = dbs.get(i);
				log.info("Post start up for db '{}', {}/{}.", db.getDbName(), i+1, dbs.size());
				db.postStartSetUp();
				db.goReady();
			}
			log.info("Post setup completed.");			
		}catch(Exception e){
			throw new ServerStartException("An error occurred during post setup.", e);
		}

		log.info("Dump connection strings:");
		for (HsqlDatabaseDescriptor db : dbs) {
			log.info("Connection to db {}: {}, account {}/{} ", db.getDbName(),
					db.getUrl(), db.getDbName(), db.getPassword());
		}

		log.info("HSQL standalone DBMS is ready");

	}
1080269
@Override
	public void warn(String msg, Throwable e) {
		LoggerFactory.getLogger(from).warn(msg);
	}
1263903
private void init(ResourceLoader resourceLoader) throws IOException {
    if (config == null && configs == null) {
      if (typeArgument == null && configArgument == null) {
        throw new IOException("no configuration");
      } else {
        if (typeArgument != null) {
          config = new MtasConfiguration();
          config.attributes.put(MtasConfiguration.CHARFILTER_CONFIGURATION_TYPE,
              typeArgument);
          config.attributes.put(
              MtasConfiguration.CHARFILTER_CONFIGURATION_PREFIX,
              prefixArgument);
          config.attributes.put(
              MtasConfiguration.CHARFILTER_CONFIGURATION_POSTFIX,
              postfixArgument);
        }
        if (configArgument != null) {
          if (resourceLoader != null) {
            try {
              configs = MtasConfiguration.readMtasCharFilterConfigurations(
                  resourceLoader, configArgument);
            } catch (IOException e) {
              throw new IOException(
                  "problem loading configurations from " + configArgument, e);
            }
          }
        }
      }
    }
  }
451231
public void warn(Object message, Throwable t)
    {
        getLogger().warn(message.toString(), t);
    }
235425
public void warn(String message, Object ... args) {
    if (log.isWarnEnabled()) {
      log.warn(String.format(message, args));
    }
  }
62518
public void warn(Object message, Throwable t)
    {
        if (IS12)
        {
            getLogger().log(FQCN, Level.WARN, message, t);
        }
        else
        {
            getLogger().log(FQCN, Level.WARN, message, t);
        }
    }
1363008
def init(init_type='plaintext_tcp', *args, **kwargs):
    
    global _module_instance
    reset()

    validate_init_types = ['plaintext_tcp', 'plaintext', 'pickle_tcp',
                           'pickle', 'plain']

    if init_type not in validate_init_types:
        raise GraphiteSendException(
            "Invalid init_type '%s', must be one of: %s" %
            (init_type, ", ".join(validate_init_types)))

    # Use TCP to send data to the plain text receiver on the graphite server.
    if init_type in ['plaintext_tcp', 'plaintext', 'plain']:
        _module_instance = GraphiteClient(*args, **kwargs)

    # Use TCP to send pickled data to the pickle receiver on the graphite
    # server.
    if init_type in ['pickle_tcp', 'pickle']:
        _module_instance = GraphitePickleClient(*args, **kwargs)

    return _module_instance
338865
def _sendMsg(self, msg):
    """"""
    if not self.sock:
      self.connect()
    if not isinstance(msg, binary_type):
      msg = msg.encode("UTF-8")

    backoff = 0.001
    while True:
      try:
        self.sock.sendall(msg)
        break
      except socket.error:
        log.warning('Graphite connection error', exc_info = True)
        self.disconnect()
        time.sleep(random.uniform(0, 2.0*backoff))
        backoff = min(backoff*2.0, 5.0)
        self.connect()
270389
public void warn(String format, Object arg1, Object arg2) {
        if (!logger.isWarnEnabled())
            return;

        if (instanceofLAL) {
            String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
            ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
        } else {
            logger.warn(format, arg1, arg2);
        }
    }
581371
@Override
    public void write(Iterable<QueryResult> results) {
        logger.debug("Export to '{}' results {}", graphiteHttpUrl, results);
        HttpURLConnection urlConnection = null;
        OutputStreamWriter urlWriter;
        try {
            StringBuilder sbUrlWriter = new StringBuilder("");
            for (QueryResult result : results) {
                String msg = metricPathPrefix + result.getName() + " " + result.getValue() + " " + result.getEpoch(TimeUnit.SECONDS) + "\n";
                logger.debug("Export '{}'", msg);
                sbUrlWriter.append(msg);
            }
            if (sbUrlWriter.length() > 0) {
                sbUrlWriter.insert(0, "data=");
                urlConnection = (HttpURLConnection) graphiteHttpUrl.openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoOutput(true);
                urlWriter = new OutputStreamWriter(urlConnection.getOutputStream(), Charset.forName("UTF-8"));
                urlWriter.write(sbUrlWriter.toString());
                urlWriter.flush();
                IoUtils2.closeQuietly(urlWriter);
                int responseCode = urlConnection.getResponseCode();
                if (responseCode != 200) {
                    logger.warn("Failure {}:'{}' to send result to Graphite HTTP proxy'{}' ", responseCode, urlConnection.getResponseMessage(), graphiteHttpUrl);
                }
                if (logger.isTraceEnabled()) {
                    IoUtils2.copy(urlConnection.getInputStream(), System.out);
                }
            }
        } catch (Exception e) {
            logger.warn("Failure to send result to Graphite HTTP proxy '{}'", graphiteHttpUrl, e);
        } finally {
            // Release the connection.
            if (urlConnection != null) {
                try {
                    InputStream in = urlConnection.getInputStream();
                    IoUtils2.copy(in, IoUtils2.nullOutputStream());
                    IoUtils2.closeQuietly(in);
                    InputStream err = urlConnection.getErrorStream();
                    if (err != null) {
                        IoUtils2.copy(err, IoUtils2.nullOutputStream());
                        IoUtils2.closeQuietly(err);
                    }
                } catch (IOException e) {
                    logger.warn("Exception flushing http connection", e);
                }
            }
        }
    }
378849
public static void warn(Object warnMsg) {
        if (level.ordinal() >= Level.WARN.ordinal())
            if (warnMsg instanceof Throwable) {
                singleton.warn(null, (Throwable) warnMsg, loggerName());
            } else {
                singleton.warn(warnMsg, null, loggerName());
            }
    }
1182116
function () {
		
		LOG.warn('starting [' + SR.Settings.SERVER_INFO.type + '] server at base port: ' + l_ip_port.port, l_name);
		
		// NOTE: name will determine which handler set to get/store
		// create a listener that'll listen to the default socket port for this server
		l_server = new SR.Listener({
			port:           l_ip_port.port + SR.Settings.PORT_INC_SOCKET,
			conn_module:    config.conn_handler
		});
		
		// always load system.js (NOTE: before other handlers)
		SR.Handler.addByFile({name: 'system',	file: 'system.js', owner: 'SR'}, config.path);
		
		// result may be true or false
		l_server.init(function (result) {
			if (result === false) {
				LOG.error('server init fail, listen port: ' + l_ip_port.port, l_name);
				
				// NOTE: this is redundant judgement with frontier's 
				//LOG.warn('treat this server as APP server, loading AppConnector...', l_name);
				//SR.Module.addStep(SR.Component.AppConnector());
				
				// TODO: try to close down more gracefully, right now this will trigger many 
				// unnecessary shutdown steps (& print too many error messages not useful)
				//l_dispose();
			}
			else {
				LOG.warn('server is ready & running...', l_name);
								
				// for entry server, we report the entry server HTTP base port
				// TODO: cleaner approach?
				if (SR.Settings.SERVER_INFO.type === 'entry')
					SR.Settings.SERVER_INFO.port = SR.Settings.PORT_ENTRY_ACTUAL;
				
				// NOTE: this is redundant judgement with frontier's 
				//else if (SR.Settings.SERVER_INFO.type === 'lobby') {
				//	LOG.warn('treat this server as LOBBY server, loading AppManager...', l_name);
				//	SR.Module.addStep(SR.Component.AppManager());
				//}
			}
			
			UTIL.safeCall(onDone, true);
		});
	}
19291
@Override
    public void init (ConnectionManager cmgr, SocketChannel channel, long createStamp)
        throws IOException
    {
        super.init(cmgr, channel, createStamp);
        _pcmgr = (PresentsConnectionManager)cmgr;
    }
1141980
@Override
    public void warn(String msg) {
        logger.log(FQCN, Level.WARN, msg, null);
    }
627282
protected void initNode() {
        /**
         * quick fix for integration tests. if hosts property set to "embedded" then a local node is start.
         * maven dependencies need to be defined correctly for this to work
         */
        ClassLoader cl = Thread.currentThread().getContextClassLoader();

        try {
            // Need to use the classloader for Elasticsearch to pick up the property files when
            // running in an OSGi environment
            Thread.currentThread().setContextClassLoader(TransportClient.class.getClassLoader());

            final Properties properties = new Properties();
            try {
                InputStream stream = null;

                if (System.getProperties().containsKey("jboss.server.config.dir")) {
                    File file = new File(System.getProperty("jboss.server.config.dir") + File.separatorChar +
                            HAWKULAR_ELASTICSEARCH_PROPERTIES);
                    stream = new FileInputStream(file);
                } else {
                    stream = this.getClass().getResourceAsStream(File.separatorChar +
                                    HAWKULAR_ELASTICSEARCH_PROPERTIES);
                }
                properties.load(stream);
                stream.close();
            } catch (IOException e) {
                log.log(Level.SEVERE, "Failed to load elasticsearch properties", e);
            }

            node = NodeBuilder.nodeBuilder()
                    .settings(ImmutableSettings.settingsBuilder()
                            .put(properties)).node();

            node.start();
            client = node.client();
        } finally {
            Thread.currentThread().setContextClassLoader(cl);
        }

        if (log.isLoggable(Level.FINEST)) {
            log.finest("Initialized Elasticsearch node=" + node + " client=" + client);
        }
    }
453290
public void warn(Throwable t) {
        if (isEnabled() && isWarnEnabled()) {
            dispatchLogException(new LogEvent(this, LogEvent.WARN_TYPE, t));
        }
    }