Esempio n. 1
0
// Connect - Will connect and ping connection in hope that all is ok
func (m *Connection) Connect() error {
	m.Logger.Debug("Connecting to MySQL server (uri: %s) ...", m.URI)

	var err error

	m.DB, err = gorm.Open("mysql", m.URI)
	//m.DB.SetLogger(m.Logger)

	if err != nil {
		m.Logger.Error("Got error while attempting to create mysql connection: %s", err)
		return err
	}

	if err := m.DB.DB().Ping(); err != nil {
		m.Logger.Error("Got error while attempting to PING database: %s", err)
		return err
	}

	concurrency := utils.GetConcurrencyCount("PU_GO_MAX_CONCURRENCY")

	// Setting up max idle conns based on concurrency
	m.DB.DB().SetMaxIdleConns(int(concurrency))
	m.DB.DB().SetMaxOpenConns(int(concurrency))

	return nil
}
Esempio n. 2
0
// Start -
func (c *Connection) Start(done chan bool) error {
	opts := MQTT.NewClientOptions().AddBroker(c.GetBrokerAddr())
	opts.SetClientID(c.GetBrokerClientID())
	opts.SetDefaultPublishHandler(c.BrokerHandler)
	opts.SetAutoReconnect(true)

	username, password := c.GetBrokerCredentials()
	opts.SetUsername(username)
	opts.SetPassword(password)

	concurrency := utils.GetConcurrencyCount("PU_GO_MAX_CONCURRENCY")
	c.events = make(chan events.Event, concurrency)

	errors := make(chan error)
	connected := make(chan bool)

	go func() {
		for {
			c.Info("Starting MQTT (connection: %s) on (addr: %s)...", c.Name(), c.GetBrokerAddr())

			reload := make(chan bool)
			c.conn = MQTT.NewClient(opts)

			if token := c.conn.Connect(); token.Wait() && token.Error() != nil {
				errors <- fmt.Errorf("Failed to establish connection with mqtt server (error: %s)", token.Error())
				continue
			}

			if !c.conn.IsConnected() {
				continue
			}

			c.Subscribe(c.GetBrokerTopicName(), MaxTopicSubscribeAttempts)

			// Notify rest of the app that we're ready ...
			close(connected)

			go func() {
				cct := time.Tick(2 * time.Second)

				for {
					select {
					case <-cct:
						if !c.conn.IsConnected() {
							reload <- true
							return
						}
					case <-done:
						c.Warning("Received stop signal for mqtt (worker: %s). Will not attempt to restart worker ...", c.Name())
						return
					}
				}
			}()

		reloadloop:
			for {
				select {
				case <-reload:
					c.Warning("Mqtt (worker: %s) seems not to be connected. Restarting loop in 2 seconds ...", c.Name())
					time.Sleep(2 * time.Second)
					break reloadloop
				}
			}

		}
	}()

	select {
	case <-connected:
		c.Info(
			"Successfully established mqtt connection for (worker: %s) on (addr: %s)",
			c.Name(), c.GetBrokerAddr(),
		)
		break

	// @TODO - Figure out how to handle multiple errors ...
	case err := <-errors:
		return err
	case <-time.After(time.Duration(InitialConnectionTimeout) * time.Second):
		errors <- fmt.Errorf(
			"Could not establish mqtt connection for (worker: %s) on (addr: %s) due to initial connection (timeout: %ds)",
			c.Name(), c.GetBrokerAddr(), InitialConnectionTimeout,
		)
		break
	}

	return nil
}