internal static async Task AttemptConnectionAsync()

in MySQL.Data/src/Failover/FailoverManager.cs [174:239]


    internal static async Task<string> AttemptConnectionAsync(MySqlConnection connection, string originalConnectionString, bool execAsync, CancellationToken cancellationToken, bool mySqlPoolManager = false)
    {
      if (mySqlPoolManager)
        if (MySqlPoolManager.Hosts == null)
        {
          MySqlPoolManager.Hosts = FailoverGroup.Hosts;
          MySqlPoolManager.DemotedHosts = new ConcurrentQueue<FailoverServer>();
        }
        else
          FailoverGroup.Hosts = MySqlPoolManager.Hosts;

      FailoverServer currentHost = FailoverGroup.ActiveHost;
      FailoverServer initialHost = currentHost;
      Driver driver = null;
      int attempts = 0;
      MySqlConnectionStringBuilder msb;
      string connectionString;

      do
      {
        // Attempt to connect to each host by retrieving the next host based on the failover method being used
        connectionString = "server=" + currentHost.Host + ";" + originalConnectionString.Substring(originalConnectionString.IndexOf(';') + 1);
        if (currentHost != null && currentHost.Port != -1)
          connectionString += ";port=" + currentHost.Port;
        msb = new MySqlConnectionStringBuilder(connectionString, connection.IsConnectionStringAnalyzed);

        if ((FailoverGroup.Hosts.Count == 1 && !mySqlPoolManager) ||
          (mySqlPoolManager && MySqlPoolManager.Hosts.Count == 1 && MySqlPoolManager.DemotedHosts.IsEmpty))
          return msb.ConnectionString;

        try
        {
          driver = await Driver.CreateAsync(msb, execAsync, cancellationToken).ConfigureAwait(false);
          if (!mySqlPoolManager)
            connection.driver = driver;
          break;
        }
        catch (Exception ex)
        {
          if (ex.GetType() == typeof(MySqlException) && attempts == FailoverGroup.Hosts.Count)
            throw;
        }

        var tmpHost = currentHost;
        currentHost = FailoverGroup.GetNextHost();

        if (mySqlPoolManager)
        {
          tmpHost.DemotedTime = DateTime.Now;
          MySqlPoolManager.Hosts.Remove(tmpHost);
          MySqlPoolManager.DemotedHosts.Enqueue(tmpHost);

          if (MySqlPoolManager.DemotedServersTimer == null)
            MySqlPoolManager.DemotedServersTimer = new Timer(new TimerCallback(MySqlPoolManager.ReleaseDemotedHosts),
              null, MySqlPoolManager.DEMOTED_TIMEOUT, Timeout.Infinite);
        }

        attempts++;
      } while (!currentHost.Equals(initialHost));

      // All connection attempts failed.
      if (driver == null)
        throw new MySqlException(Resources.UnableToConnectToHost);

      return msb.ConnectionString;
    }