<commit_before>/*
   Copyright 2015 <NAME>, courtesy Booking.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package inst

import (
	"fmt"
	"regexp"
	"time"

	"github.com/github/orchestrator/go/config"
	"github.com/github/orchestrator/go/db"
	"github.com/github/orchestrator/go/process"
	"github.com/github/orchestrator/go/raft"
	"github.com/github/orchestrator/go/util"

	"github.com/openark/golib/log"
	"github.com/openark/golib/sqlutils"
	"github.com/patrickmn/go-cache"
	"github.com/rcrowley/go-metrics"
)

var analysisChangeWriteAttemptCounter = metrics.NewCounter()
var analysisChangeWriteCounter = metrics.NewCounter()

var recentInstantAnalysis *cache.Cache

func init() {
	metrics.Register("analysis.change.write.attempt", analysisChangeWriteAttemptCounter)
	metrics.Register("analysis.change.write", analysisChangeWriteCounter)

	go initializeAnalysisDaoPostConfiguration()
}

func initializeAnalysisDaoPostConfiguration() {
	config.WaitForConfigurationToBeLoaded()

	recentInstantAnalysis = cache.New(time.Duration(config.RecoveryPollSeconds*2)*time.Second, time.Second)
}

// GetReplicationAnalysis will check for replication problems (dead master; unreachable master; etc)
func GetReplicationAnalysis(clusterName string, hints *ReplicationAnalysisHints) ([]ReplicationAnalysis, error) {
	result := []ReplicationAnalysis{}

	args := sqlutils.Args(ValidSecondsFromSeenToLastAttemptedCheck(), config.Config.ReasonableReplicationLagSeconds, clusterName)
	analysisQueryReductionClause := ``
	if config.Config.ReduceReplicationAnalysisCount {
		analysisQueryReductionClause = `
			HAVING
				(MIN(
					master_instance.last_checked <= master_instance.last_seen
					and master_instance.last_attempted_check <= master_instance.last_seen + interval ? second
       	 ) = 1 /* AS is_last_check_valid */) = 0
				OR (IFNULL(SUM(replica_instance.last_checked <= replica_instance.last_seen
		                    AND replica_instance.slave_io_running = 0
		                    AND replica_instance.last_io_error like '%error %connecting to master%'
		                    AND replica_instance.slave_sql_running = 1),
		                0) /* AS count_replicas_failing_to_connect_to_master */ > 0)
				OR (IFNULL(SUM(replica_instance.last_checked <= replica_instance.last_seen),
		                0) /* AS count_valid_slaves */ < COUNT(replica_instance.server_id) /* AS count_replicas */)
				OR (IFNULL(SUM(replica_instance.last_checked <= replica_instance.last_seen
		                    AND replica_instance.slave_io_running != 0
		                    AND replica_instance.slave_sql_running != 0),
		                0) /* AS count_valid_replicating_slaves */ < COUNT(replica_instance.server_id) /* AS count_replicas */)
				OR (MIN(
		            master_instance.slave_sql_running = 1
		            AND master_instance.slave_io_running = 0
		            AND master_instance.last_io_error like '%error %connecting to master%'
		          ) /* AS is_failing_to_connect_to_master */)
				OR (COUNT(replica_instance.server_id) /* AS count_replicas */ > 0)
			`
		args = append(args, ValidSecondsFromSeenToLastAttemptedCheck())
	}
	// "OR count_replicas > 0" above is a recent addition, which, granted, makes some previous conditions redundant.
	// It gives more output, and more "NoProblem" messages that I am now interested in for purpose of auditing in database_instance_analysis_changelog
	query := fmt.Sprintf(`
		    SELECT
		        master_instance.hostname,
		        master_instance.port,
						MIN(master_instance.data_center) AS data_center,
						MIN(master_instance.physical_environment) AS physical_environment,
		        MIN(master_instance.master_host) AS master_host,
		        MIN(master_instance.master_port) AS master_port,
		        MIN(master_instance.cluster_name) AS cluster_name,
			    master_instance.read_only AS master_readonly,
		        MIN(IFNULL(cluster_alias.alias, master_instance.cluster_name)) AS cluster_alias,
		        MIN(
							master_instance.last_checked <= master_instance.last_seen
							and master_instance.last_attempted_check <= master_instance.last_seen + interval ? second
		        	) = 1 AS is_last_check_valid,
						MIN(master_instance.last_check_partial_success) as last_check_partial_success,
		        MIN(master_instance.master_host IN ('' , '_')
		            OR master_instance.master_port = 0
								OR substr(master_instance.master_host, 1, 2) = '//') AS is_master,
		        MIN(master_instance.is_co_master) AS is_co_master,
		        MIN(CONCAT(master_instance.hostname,
		                ':',
		                master_instance.port) = master_instance.cluster_name) AS is_cluster_master,<commit_msg>fix indentation<commit_after>/*
   Copyright 2015 <NAME>, courtesy Booking.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package inst

import (
	"fmt"
	"regexp"
	"time"

	"github.com/github/orchestrator/go/config"
	"github.com/github/orchestrator/go/db"
	"github.com/github/orchestrator/go/process"
	"github.com/github/orchestrator/go/raft"
	"github.com/github/orchestrator/go/util"

	"github.com/openark/golib/log"
	"github.com/openark/golib/sqlutils"
	"github.com/patrickmn/go-cache"
	"github.com/rcrowley/go-metrics"
)

var analysisChangeWriteAttemptCounter = metrics.NewCounter()
var analysisChangeWriteCounter = metrics.NewCounter()

var recentInstantAnalysis *cache.Cache

func init() {
	metrics.Register("analysis.change.write.attempt", analysisChangeWriteAttemptCounter)
	metrics.Register("analysis.change.write", analysisChangeWriteCounter)

	go initializeAnalysisDaoPostConfiguration()
}

func initializeAnalysisDaoPostConfiguration() {
	config.WaitForConfigurationToBeLoaded()

	recentInstantAnalysis = cache.New(time.Duration(config.RecoveryPollSeconds*2)*time.Second, time.Second)
}

// GetReplicationAnalysis will check for replication problems (dead master; unreachable master; etc)
func GetReplicationAnalysis(clusterName string, hints *ReplicationAnalysisHints) ([]ReplicationAnalysis, error) {
	result := []ReplicationAnalysis{}

	args := sqlutils.Args(ValidSecondsFromSeenToLastAttemptedCheck(), config.Config.ReasonableReplicationLagSeconds, clusterName)
	analysisQueryReductionClause := ``
	if config.Config.ReduceReplicationAnalysisCount {
		analysisQueryReductionClause = `
			HAVING
				(MIN(
					master_instance.last_checked <= master_instance.last_seen
					and master_instance.last_attempted_check <= master_instance.last_seen + interval ? second
       	 ) = 1 /* AS is_last_check_valid */) = 0
				OR (IFNULL(SUM(replica_instance.last_checked <= replica_instance.last_seen
		                    AND replica_instance.slave_io_running = 0
		                    AND replica_instance.last_io_error like '%error %connecting to master%'
		                    AND replica_instance.slave_sql_running = 1),
		                0) /* AS count_replicas_failing_to_connect_to_master */ > 0)
				OR (IFNULL(SUM(replica_instance.last_checked <= replica_instance.last_seen),
		                0) /* AS count_valid_slaves */ < COUNT(replica_instance.server_id) /* AS count_replicas */)
				OR (IFNULL(SUM(replica_instance.last_checked <= replica_instance.last_seen
		                    AND replica_instance.slave_io_running != 0
		                    AND replica_instance.slave_sql_running != 0),
		                0) /* AS count_valid_replicating_slaves */ < COUNT(replica_instance.server_id) /* AS count_replicas */)
				OR (MIN(
		            master_instance.slave_sql_running = 1
		            AND master_instance.slave_io_running = 0
		            AND master_instance.last_io_error like '%error %connecting to master%'
		          ) /* AS is_failing_to_connect_to_master */)
				OR (COUNT(replica_instance.server_id) /* AS count_replicas */ > 0)
			`
		args = append(args, ValidSecondsFromSeenToLastAttemptedCheck())
	}
	// "OR count_replicas > 0" above is a recent addition, which, granted, makes some previous conditions redundant.
	// It gives more output, and more "NoProblem" messages that I am now interested in for purpose of auditing in database_instance_analysis_changelog
	query := fmt.Sprintf(`
		    SELECT
		        master_instance.hostname,
		        master_instance.port,
						MIN(master_instance.data_center) AS data_center,
						MIN(master_instance.physical_environment) AS physical_environment,
		        MIN(master_instance.master_host) AS master_host,
		        MIN(master_instance.master_port) AS master_port,
		        MIN(master_instance.cluster_name) AS cluster_name,
			master_instance.read_only AS master_readonly,
		        MIN(IFNULL(cluster_alias.alias, master_instance.cluster_name)) AS cluster_alias,
		        MIN(
							master_instance.last_checked <= master_instance.last_seen
							and master_instance.last_attempted_check <= master_instance.last_seen + interval ? second
		        	) = 1 AS is_last_check_valid,
						MIN(master_instance.last_check_partial_success) as last_check_partial_success,
		        MIN(master_instance.master_host IN ('' , '_')
		            OR master_instance.master_port = 0
								OR substr(master_instance.master_host, 1, 2) = '//') AS is_master,
		        MIN(master_instance.is_co_master) AS is_co_master,
		        MIN(CONCAT(master_instance.hostname,
		                ':',
		                master_instance.port) = master_instance.cluster_name) AS is_cluster_master,
{'fraction_non_alphanumeric': 0.08562040974101276, 'fraction_numerical': 0.0052183996907614995, 'mean_word_length': 3.6785714285714284, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '320059', 'n_tokens_mistral': 3310, 'n_tokens_neox': 2964, 'n_words': 652}