Exemplo n.º 1
0
        public static void RuleConfig()
        {
            RuleConfig rule_config = null;

            if (rule_config != null)
            {
                ConfigModel.rule_config = new RuleConfigModel
                {
                    notice       = rule_config.notice,
                    message_node = new MessageTargetConfig
                    {
                        task_count = rule_config.message_task_count,
                        time_out   = rule_config.redis_time_out
                    },
                    pg_node = new PgTargetConfig
                    {
                        total_size = rule_config.pg_total_size
                    },
                    redis_node = new RedisTargetConfig
                    {
                        mem_rate = rule_config.redis_mem_rate,
                        time_out = rule_config.redis_time_out
                    },
                    server_node = new ServerTargetConfig
                    {
                        time_out  = rule_config.server_time_out,
                        mem_rate  = rule_config.server_mem_rate,
                        cpu_rate  = rule_config.server_cpu_rate,
                        disk_rate = rule_config.server_disk_rate
                    }
                };
            }
        }
Exemplo n.º 2
0
        public void Equality_WithEqualProperties_ShouldBeTrue()
        {
            var firstConfig  = new RuleConfig(false, Severity.Error);
            var secondConfig = new RuleConfig(false, Severity.Error);

            Assert.Equal(firstConfig, secondConfig);
        }
Exemplo n.º 3
0
        public void WithInheritance_ShouldReturnValueWithInheritanceSet(bool shouldInherit)
        {
            var originalConfig = new RuleConfig(shouldInherit, Severity.Error);

            RuleConfig config = originalConfig.WithInheritance(!shouldInherit);

            Assert.Equal(!shouldInherit, config.ShouldInherit);
        }
Exemplo n.º 4
0
        public ArticleHandler(RuleConfig ruleConfig)
        {
            this._ruleConfig     = ruleConfig;
            this._fileOperate    = new FileOperate();
            this._articleBuilder = new ArticleBuilder();
            this._sqlOperate     = new SqlOperate();

            this._currentRule = new JsonArticleRule(ruleConfig.Rules);
        }
 public MailboxRulesAgentFactory()
 {
     try
     {
         RuleConfig.Load();
     }
     catch (TransportComponentLoadFailedException ex)
     {
         throw new ExchangeConfigurationException(ex.Message, ex.InnerException);
     }
 }
Exemplo n.º 6
0
    public static void DefaultConfig(out RuleConfig cfg)
    {
        cfg = new RuleConfig();

        cfg.gameCfg = new GameConfig();

        cfg.levelCfgs = new LevelConfig[3];


        cfg.gameCfg.energyScale = 1f;
        cfg.gameCfg.speedScale  = 1f;


        cfg.levelCfgs[0] = new LevelConfig();
        cfg.levelCfgs[1] = new LevelConfig();
        cfg.levelCfgs[2] = new LevelConfig();

        List <ActorConfig> actorCfgList = new List <ActorConfig>();
        var speciesVals = System.Enum.GetValues(typeof(ActorSpecies));

        foreach (var species in speciesVals)
        {
            ActorConfig acfg = new ActorConfig();
            acfg.aspecies = (ActorSpecies)species;
            string speciesName = acfg.aspecies.ToString().ToLower();
            if (speciesName.StartsWith("fish"))
            {
                acfg.atype = ActorType.FISH;
            }
            else if (speciesName.StartsWith("hook"))
            {
                acfg.atype = ActorType.HOOK;
            }
            if (speciesName.StartsWith("boat"))
            {
                acfg.atype = ActorType.BOAT;
            }
            actorCfgList.Add(acfg);
        }

        ActorConfig hookCfg = actorCfgList.Find(x => x.aspecies == ActorSpecies.HookNormal);

        hookCfg.atype = ActorType.HOOK;
        hookCfg.hp    = 20;

        ActorConfig boatCfg = actorCfgList.Find(x => x.aspecies == ActorSpecies.BoatNormal);

        boatCfg.atype = ActorType.BOAT;
        boatCfg.hp    = 2000;

        cfg.actorCfgs = actorCfgList.ToArray();
    }
Exemplo n.º 7
0
            protected override void UpdateXml()
            {
                var customConfig = RuleConfig.XPathSelectElements(string.Format("/ruleset[@name='{0}']", RuleSetName)).Single();

                foreach (var ruleModule in _ruleModuleCollection)
                {
                    var rules    = ruleModule.Rules.Contains("*") ? "*" : string.Join(" | ", ruleModule.Rules);
                    var ruleNode = new XElement("rules",
                                                new XAttribute("include", rules),
                                                new XAttribute("from", ruleModule.FilePath)
                                                );
                    customConfig.Add(ruleNode);
                }
            }
Exemplo n.º 8
0
    /// <summary>
    /// Saves a cfg to file
    /// </summary>
    public static void SaveConfig(string path, RuleConfig cfg)
    {
        // Open up a file stream for ProtoBuf to write to
        using (var fs = new FileStream(path, FileMode.OpenOrCreate))
        {
            // Truncate the file, in case there's any data there from before
            fs.SetLength(0);

            // Serialize!
            Serializer.Serialize(fs, cfg);
        }

        Debug.Log("Config serialized to: " + path);
    }
Exemplo n.º 9
0
        public RuleConfig Load(String ruleConfigFilePath)
        {
            String            extension = GetFileExtension(ruleConfigFilePath);
            IRuleConfigParser parser    = RuleConfigParserFactory.CreateParser(extension);

            if (parser == null)
            {
                throw new InvalidDataException(String.Format("Rule Config File Format Is Not supported: {0}", ruleConfigFilePath));
            }

            String     configText = String.Empty;
            RuleConfig ruleConfig = parser.Parse(configText);

            return(ruleConfig);
        }
Exemplo n.º 10
0
    /// <summary>
    /// Loads a game state from file
    /// </summary>
    public static void LoadConfig(string path, out RuleConfig cfg)
    {
        // Break if file doesn't exit.
        if (!File.Exists(path))
        {
            Debug.LogWarning("Failed to load state, file doesn't exist.");
            cfg = new RuleConfig();
            return;
        }

        using (var fs = new FileStream(path, FileMode.Open))
        {
            cfg = Serializer.Deserialize <RuleConfig>(fs);
            Debug.Log("Config read from: " + path);
        }
    }
Exemplo n.º 11
0
        /// <summary>
        /// </summary>
        /// <param name="ast"></param>
        /// <param name="tc"></param>
        /// <param name="rule"></param>
        /// <param name="visitor"></param>
        private static void ValidateAst(ISqlStatement ast,
                                        TableConfig tc,
                                        RuleConfig rule,
                                        PartitionKeyVisitor visitor)
        {
            if (!(ast is DmlUpdateStatement))
            {
                return;
            }

            IList <Identifier> columns = null;
            var ruleCols = rule.Columns;
            var update   = (DmlUpdateStatement)ast;

            foreach (var pair in update.Values)
            {
                foreach (var ruleCol in ruleCols)
                {
                    if (pair.Key.IdTextUpUnescape == ruleCol)
                    {
                        if (columns == null)
                        {
                            columns = new List <Identifier>(ruleCols.Count);
                        }
                        columns.Add(pair.Key);
                    }
                }
            }

            if (columns == null)
            {
                return;
            }

            var alias = visitor.GetTableAlias();

            foreach (var column in columns)
            {
                var table = column.GetLevelUnescapeUpName(2);
                table = alias.GetValue(table);
                if (table != null && table.Equals(tc.Name))
                {
                    throw new NotSupportedException("partition key cannot be changed");
                }
            }
        }
        private static RuleConfig ToRuleConfig(SonarQubeRule sonarQubeRule)
        {
            // Most rules don't have parameters, so to avoid creating objects unnecessarily
            // we'll leave the parameters as null unless there really are values.
            Dictionary <string, string> parameters = null;

            if ((sonarQubeRule.Parameters?.Count ?? 0) != 0)
            {
                parameters = sonarQubeRule.Parameters.ToDictionary(p => p.Key, p => p.Value);
            }

            var config = new RuleConfig()
            {
                Level      = sonarQubeRule.IsActive ? RuleLevel.On : RuleLevel.Off,
                Parameters = parameters,
                Severity   = Convert(sonarQubeRule.Severity)
            };

            return(config);
        }
Exemplo n.º 13
0
        public static IApi GetApi(ApiType apiType, Stream stream)
        {
            if (apiDic is null)
            {
                IRuleConfig ruleConfig = RuleConfig.GetPageRule(stream);

                apiDic = new Dictionary <ApiType, IApi>();

                foreach (var rule in ruleDic)
                {
                    apiDic.Add(rule.Key, (IApi)Activator.CreateInstance(rule.Value, ruleConfig));
                }
            }

            if (apiDic.ContainsKey(apiType))
            {
                return(apiDic[apiType]);
            }

            return(null);
        }
Exemplo n.º 14
0
        /// <summary>
        /// 修改调度配置
        /// </summary>
        /// <param name="config">配置</param>
        /// <returns>保存结果</returns>
        public static MessageInformation SaveChanges(RuleConfig config)
        {
            var messageInformation = new MessageInformation();

            try {
                config.UniqueCode = Utils.Guid;
                var data = DapperDbContext.GetConnection.QueryFirstOrDefault <RuleConfig>(
                    "Select * from RuleConfig r where (r.jobName = :JobName or triggername = :TriggerName or servicename= :ServiceName) and r.Id <> :Id",
                    config);
                if (data != null)
                {
                    throw new ValidationException("JobName,TriggerName,MethodName必须唯一");
                }
                string sql = @"Update RuleConfig
                               set Cron             = :Cron,
                                   Description      = :Description,
                                   TriggerName      = :TriggerName,
                                   JobName          = :JobName,
                                   Method           = :Method,
                                   PostBody         = :PostBody,
                                   ServiceName      = :ServiceName,
                                   Author           = :Author,
                                   ContentType      = :ContentType,
                                   IsAuthentication = :IsAuthentication,
                                   UserName         = :UserName,
                                   Password         = :Password,
                                   GroupName        = :GroupName,
                                   Address          = :Address,
                                   Status           = :Status,
                                   IsWebService     = :IsWebService,
                                   UniqueCode       = :UniqueCode,
                                   RunStatus        = :RunStatus
                             where Id = :Id ";
                DapperDbContext.Execute(sql, config);
                messageInformation.ExecuteSuccess("数据更新成功");
            } catch (Exception e) {
                messageInformation.ExecuteError(e);
            }
            return(messageInformation);
        }
Exemplo n.º 15
0
            private static ICollection <string> CalcHintDataNodes(RuleConfig rule,
                                                                  string[] cols,
                                                                  object[][] vals,
                                                                  string[] dataNodes)
            {
                ICollection <string> destDataNodes = new HashSet <string>();
                var parameter = new Dictionary <string, object>(cols.Length);

                foreach (var val in vals)
                {
                    for (var i = 0; i < cols.Length; ++i)
                    {
                        parameter[cols[i]] = val[i];
                    }
                    var dataNodeIndexes = CalcDataNodeIndexesByFunction(rule.RuleAlgorithm, parameter);
                    foreach (var index in dataNodeIndexes)
                    {
                        destDataNodes.Add(dataNodes[index]);
                    }
                }
                return(destDataNodes);
            }
Exemplo n.º 16
0
 private void InitializeApiObjects()
 {
     //New API needs to be instantiated here, in the same alphabetical order as above
     acsrf             = new Acsrf(this);
     ajaxspider        = new AjaxSpider(this);
     alert             = new OWASPZAPDotNetAPI.Generated.Alert(this);
     alertFilter       = new AlertFilter(this);
     ascan             = new Ascan(this);
     authentication    = new Authentication(this);
     authorization     = new OWASPZAPDotNetAPI.Generated.Authorization(this);
     autoupdate        = new Autoupdate(this);
     brk               = new Break(this);
     context           = new Context(this);
     core              = new Core(this);
     forcedUser        = new ForcedUser(this);
     httpSessions      = new HttpSessions(this);
     importLogFiles    = new ImportLogFiles(this);
     importurls        = new Importurls(this);
     localProxies      = new LocalProxies(this);
     openapi           = new Openapi(this);
     parameters        = new Params(this);
     pnh               = new Pnh(this);
     pscan             = new Pscan(this);
     replacer          = new Replacer(this);
     reveal            = new Reveal(this);
     ruleConfig        = new RuleConfig(this);
     script            = new Script(this);
     search            = new Search(this);
     selenium          = new Selenium(this);
     sessionManagement = new SessionManagement(this);
     soap              = new Soap(this);
     spider            = new Spider(this);
     stats             = new Stats(this);
     users             = new Users(this);
     websocket         = new Websocket(this);
 }
Exemplo n.º 17
0
 private void InitializeApiObjects()
 {
     //New API needs to be instantiated here, in the same alphabetical order as above
     Acsrf             = new Acsrf(this);
     AjaxSpider        = new AjaxSpider(this);
     Alert             = new Generated.Alert(this);
     AlertFilter       = new AlertFilter(this);
     Ascan             = new Ascan(this);
     Authentication    = new Authentication(this);
     Authorization     = new Authorization(this);
     AutoUpdate        = new AutoUpdate(this);
     Brk               = new Break(this);
     Context           = new Context(this);
     Core              = new Core(this);
     ForcedUser        = new ForcedUser(this);
     HttpSessions      = new HttpSessions(this);
     ImportLogFiles    = new ImportLogFiles(this);
     ImportUrls        = new ImportUrls(this);
     LocalProxies      = new LocalProxies(this);
     OpenApi           = new OpenApi(this);
     Parameters        = new Params(this);
     Pnh               = new Pnh(this);
     PScan             = new PScan(this);
     Replacer          = new Replacer(this);
     Reveal            = new Reveal(this);
     RuleConfig        = new RuleConfig(this);
     Script            = new Script(this);
     Search            = new Search(this);
     Selenium          = new Selenium(this);
     SessionManagement = new SessionManagement(this);
     Soap              = new Soap(this);
     Spider            = new Spider(this);
     Stats             = new Stats(this);
     Users             = new Users(this);
     Websocket         = new Websocket(this);
 }
Exemplo n.º 18
0
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            var methodName       = this.txbMethod.Text;
            var triggerName      = this.txbTrigger.Text;
            var jobName          = this.txbJob.Text;
            var url              = this.txbAddress.Text;
            var method           = this.comboBoxMethod.Text;
            var parameters       = this.txbParameters.Text;
            var contentType      = this.cmbContentType.Text;
            var cron             = this.txbCron.Text;
            var isAuthentication = this.cbIsOData.Checked;
            var userName         = this.txbUserName.Text;
            var password         = this.txbPassword.Text;
            var description      = this.txbDescription.Text;
            var groupName        = this.txbGroupName.Text;

            if (string.IsNullOrEmpty(methodName))
            {
                MessageBoxEx.Show(this, "Method name is required and unique", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(triggerName))
            {
                MessageBoxEx.Show(this, "Trigger name is required and unique", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(jobName))
            {
                MessageBoxEx.Show(this, "JOB identification is required and unique!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(url))
            {
                MessageBoxEx.Show(this, "URL address is required!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(method))
            {
                MessageBoxEx.Show(this, "Method is Required!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(groupName))
            {
                MessageBoxEx.Show(this, "Group name is Required!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(contentType))
            {
                MessageBoxEx.Show(this, "Content-Type is required!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(cron))
            {
                MessageBoxEx.Show(this, "Cron expression is required!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (!Utils.IsValidExpression(cron))
            {
                MessageBoxEx.Show(this, "Cron expression is not valid!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (isAuthentication)
            {
                if (string.IsNullOrEmpty(userName))
                {
                    MessageBoxEx.Show(this, "Username is required when authentication is selected!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (string.IsNullOrEmpty(password))
                {
                    MessageBoxEx.Show(this, "Password is required when authentication is selected", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            if (!rbWebService.Checked && !rbRestful.Checked)
            {
                MessageBoxEx.Show(this, "Webservice or restful is required", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var config     = this.Tag as RuleConfig;
            var ruleConfig = new RuleConfig();

            ruleConfig.Id               = config.Id;
            ruleConfig.ServiceName      = methodName;
            ruleConfig.Cron             = cron;
            ruleConfig.Description      = description;
            ruleConfig.TriggerName      = triggerName;
            ruleConfig.JobName          = jobName;
            ruleConfig.Method           = method;
            ruleConfig.PostBody         = parameters;
            ruleConfig.ContentType      = contentType;
            ruleConfig.IsAuthentication = isAuthentication ? 1 : 0;
            ruleConfig.UserName         = userName;
            ruleConfig.Password         = password;
            ruleConfig.GroupName        = groupName;
            ruleConfig.Address          = url;
            ruleConfig.RunStatus        = config?.RunStatus ?? (int)RunStatus.停用;
            ruleConfig.Status           = config?.Status ?? (int)BasicStatus.效;
            ruleConfig.IsWebService     = rbWebService.Checked ? (int)YesOrNo.是 : (int)YesOrNo.否;
            this.IsLoading              = true;
            var msg = ServiceUtils.SaveChanges(ruleConfig);

            MessageBoxEx.Show(this, msg.Message);
            this.IsLoading = true;
        }
Exemplo n.º 19
0
 public void Save(string fileName)
 {
     UpdateXml();
     RuleConfig.Save(fileName);
 }
Exemplo n.º 20
0
        /// <summary>
        /// 新增调度配置
        /// </summary>
        /// <param name="config">配置</param>
        /// <returns>保存结果</returns>
        public static MessageInformation InsertRule(RuleConfig config)
        {
            var messageInformation = new MessageInformation();

            try {
                config.UniqueCode = Utils.Guid;
                bool isValid =
                    DapperDbContext.GetConnection.QueryFirstOrDefault <RuleConfig>(
                        "Select * from RuleConfig r where r.jobName = :JobName or triggername = :TriggerName or servicename= :ServiceName",
                        config) == null;
                if (!isValid)
                {
                    throw new ValidationException("JobName,TriggerName,MethodName必须唯一");
                }
                string sql = @"insert into RuleConfig
                              (id,
                               cron,
                               description,
                               triggername,
                               jobname,
                               method,
                               postbody,
                               servicename,
                               author,
                               contenttype,
                               isauthentication,
                               username,
                               password,
                               groupname,
                               address,
                               status,
                               isWebService,
                               uniqueCode,
                               runStatus)
                            values
                              (s_RuleConfig.Nextval,
                               :Cron,
                               :Description,
                               :TriggerName,
                               :JobName,
                               :Method,
                               :PostBody,
                               :ServiceName,
                               :Author,
                               :ContentType,
                               :IsAuthentication,
                               :UserName,
                               :Password,
                               :GroupName,
                               :Address,
                               :Status,
                               :IsWebService,
                               :UniqueCode,
                               :RunStatus)";
                DapperDbContext.Execute(sql, config);
                messageInformation.ExecuteSuccess("数据插入成功");
            } catch (Exception e) {
                messageInformation.ExecuteError(e);
            }
            return(messageInformation);
        }
Exemplo n.º 21
0
        public void RuleConfig_ShoudBeCreated()
        {
            var ruleConfig = new RuleConfig(false, Severity.Error);

            Assert.NotNull(ruleConfig);
        }
Exemplo n.º 22
0
 /// <summary>
 /// 初始化决斗规则
 /// </summary>
 public static void InitDuelRule()
 {
     ruleConfig = ConfigManager.GetConfigByName("Rule") as RuleConfig;
 }
 public override void Close()
 {
     RuleConfig.UnLoad();
 }
Exemplo n.º 24
0
        private static RuleMetadata GetEffectiveMetadata(RuleMetadata defaultMetadata, RuleConfig userConfig)
        {
            if (userConfig == null || !userConfig.Severity.HasValue)
            {
                return(defaultMetadata);
            }

            return(new RuleMetadata
            {
                DefaultSeverity = userConfig.Severity.Value,
                Title = defaultMetadata.Title,
                CompatibleLanguages = defaultMetadata.CompatibleLanguages,
                Type = defaultMetadata.Type
            });
        }
Exemplo n.º 25
0
 // Private constructor, we want "CreateRuleConfig" to be the first call
 private RuleConfigBuilder()
 {
     RuleConfig = new RuleConfig();
 }
Exemplo n.º 26
0
            /// <exception cref="System.SqlSyntaxErrorException" />
            public static void RouteFromHint(object frontConn,
                                             SchemaConfig schema,
                                             RouteResultset rrs,
                                             int prefixIndex,
                                             string sql)
            {
                var         hint             = CobarHint.ParserCobarHint(sql, prefixIndex);
                var         outputSql        = hint.OutputSql;
                var         replica          = hint.Replica;
                var         table            = hint.Table;
                var         dataNodes        = hint.DataNodes;
                var         partitionOperand = hint.PartitionOperand;
                TableConfig tableConfig      = null;

                if (table == null ||
                    schema.Tables == null ||
                    (tableConfig = schema.Tables.GetValue(table)) == null)
                {
                    // table not indicated
                    var nodes = new RouteResultsetNode[1];
                    rrs.Nodes = nodes;
                    if (dataNodes != null && !dataNodes.IsEmpty())
                    {
                        var replicaIndex = dataNodes[0].Value;
                        if (replicaIndex >= 0 && RouteResultsetNode.DefaultReplicaIndex != replicaIndex)
                        {
                            // replica index indicated in dataNodes references
                            nodes[0] = new RouteResultsetNode(schema.DataNode, replicaIndex, outputSql);
                            LogExplicitReplicaSet(frontConn, sql, rrs);
                            return;
                        }
                    }
                    nodes[0] = new RouteResultsetNode(schema.DataNode, replica, outputSql);
                    if (replica != RouteResultsetNode.DefaultReplicaIndex)
                    {
                        LogExplicitReplicaSet(frontConn, sql, rrs);
                    }
                    return;
                }

                if (dataNodes != null && !dataNodes.IsEmpty())
                {
                    var nodes = new RouteResultsetNode[dataNodes.Count];
                    rrs.Nodes = nodes;
                    var i          = 0;
                    var replicaSet = false;
                    foreach (var pair in dataNodes)
                    {
                        var dataNodeName = tableConfig.DataNodes[pair.Key];
                        var replicaIndex = dataNodes[i].Value;
                        if (replicaIndex >= 0 && RouteResultsetNode.DefaultReplicaIndex != replicaIndex)
                        {
                            replicaSet = true;
                            nodes[i]   = new RouteResultsetNode(dataNodeName, replicaIndex, outputSql);
                        }
                        else
                        {
                            replicaSet = replicaSet || (replica != RouteResultsetNode.DefaultReplicaIndex);
                            nodes[i]   = new RouteResultsetNode(dataNodeName, replica, outputSql);
                        }
                        ++i;
                    }
                    if (replicaSet)
                    {
                        LogExplicitReplicaSet(frontConn, sql, rrs);
                    }
                    return;
                }

                if (partitionOperand == null)
                {
                    var tableDataNodes = tableConfig.DataNodes;
                    var nodes          = new RouteResultsetNode[tableDataNodes.Length];
                    rrs.Nodes = nodes;
                    for (var i = 0; i < nodes.Length; ++i)
                    {
                        nodes[i] = new RouteResultsetNode(tableDataNodes[i], replica, outputSql);
                    }
                    return;
                }

                var cols = partitionOperand.Key;
                var vals = partitionOperand.Value;

                if (cols == null || vals == null)
                {
                    throw new SqlSyntaxErrorException("${partitionOperand} is invalid: " + sql);
                }
                RuleConfig rule  = null;
                var        tr    = tableConfig.Rule;
                var        rules = tr == null ? null : tr.Rules;

                if (rules != null)
                {
                    foreach (var r in rules)
                    {
                        var ruleCols = r.Columns;
                        var match    = true;
                        foreach (var ruleCol in ruleCols)
                        {
                            match &= cols.Contains(ruleCol);
                        }
                        if (match)
                        {
                            rule = r;
                            break;
                        }
                    }
                }

                var tableDataNodes1 = tableConfig.DataNodes;

                if (rule == null)
                {
                    var nodes = new RouteResultsetNode[tableDataNodes1.Length];
                    rrs.Nodes = nodes;
                    var replicaSet = false;
                    for (var i = 0; i < tableDataNodes1.Length; ++i)
                    {
                        replicaSet = replicaSet || (replica != RouteResultsetNode.DefaultReplicaIndex);
                        nodes[i]   = new RouteResultsetNode(tableDataNodes1[i], replica, outputSql);
                    }
                    if (replicaSet)
                    {
                        LogExplicitReplicaSet(frontConn, sql, rrs);
                    }
                    return;
                }

                var destDataNodes = CalcHintDataNodes(rule, cols, vals, tableDataNodes1);
                var nodes1        = new RouteResultsetNode[destDataNodes.Count];

                rrs.Nodes = nodes1;
                var i1          = 0;
                var replicaSet1 = false;

                foreach (var dataNode in destDataNodes)
                {
                    replicaSet1  = replicaSet1 || (replica != RouteResultsetNode.DefaultReplicaIndex);
                    nodes1[i1++] = new RouteResultsetNode(dataNode, replica, outputSql);
                }
                if (replicaSet1)
                {
                    LogExplicitReplicaSet(frontConn, sql, rrs);
                }
            }
Exemplo n.º 27
0
        //private static readonly Logger Logger = Logger.GetLogger(typeof(ServerRouter));

        public static RouteResultset Route(SchemaConfig schema,
                                           string stmt,
                                           string charset,
                                           object info)
        {
            var rrs = new RouteResultset(stmt);
            // 检查是否含有cobar hint
            var prefixIndex = HintRouter.IndexOfPrefix(stmt);

            if (prefixIndex >= 0)
            {
                HintRouter.RouteFromHint(info, schema, rrs, prefixIndex, stmt);
                return(rrs);
            }

            // 检查schema是否含有拆分库
            if (schema.IsNoSharding)
            {
                if (schema.IsKeepSqlSchema)
                {
                    var ast     = SqlParserDelegate.Parse(stmt, charset ?? MySqlParser.DefaultCharset);
                    var visitor = new PartitionKeyVisitor(schema.Tables);
                    visitor.SetTrimSchema(schema.Name);
                    ast.Accept(visitor);
                    if (visitor.IsSchemaTrimmed())
                    {
                        stmt = GenSql(ast, stmt);
                    }
                }
                var nodes = new RouteResultsetNode[1];
                nodes[0]  = new RouteResultsetNode(schema.DataNode, stmt);
                rrs.Nodes = nodes;
                return(rrs);
            }

            // 生成和展开AST
            var ast1     = SqlParserDelegate.Parse(stmt, charset ?? MySqlParser.DefaultCharset);
            var visitor1 = new PartitionKeyVisitor(schema.Tables);

            visitor1.SetTrimSchema(schema.IsKeepSqlSchema ? schema.Name : null);
            ast1.Accept(visitor1);
            // 如果sql包含用户自定义的schema,则路由到default节点
            if (schema.IsKeepSqlSchema && visitor1.IsCustomedSchema())
            {
                if (visitor1.IsSchemaTrimmed())
                {
                    stmt = GenSql(ast1, stmt);
                }
                var nodes = new RouteResultsetNode[1];
                nodes[0]  = new RouteResultsetNode(schema.DataNode, stmt);
                rrs.Nodes = nodes;
                return(rrs);
            }

            // 元数据语句路由
            if (visitor1.IsTableMetaRead())
            {
                MetaRouter.RouteForTableMeta(rrs, schema, ast1, visitor1, stmt);
                if (visitor1.IsNeedRewriteField())
                {
                    rrs.Flag = RouteResultset.RewriteField;
                }
                return(rrs);
            }

            // 匹配规则
            TableConfig matchedTable = null;
            RuleConfig  rule         = null;
            IDictionary <string, IList <object> > columnValues = null;
            var astExt = visitor1.GetColumnValue();
            var tables = schema.Tables;

            foreach (var e in astExt)
            {
                var col2Val = e.Value;
                var tc      = tables.GetValue(e.Key);
                if (tc == null)
                {
                    continue;
                }
                if (matchedTable == null)
                {
                    matchedTable = tc;
                }
                if (col2Val == null || col2Val.IsEmpty())
                {
                    continue;
                }
                var tr = tc.Rule;
                if (tr != null)
                {
                    foreach (var rc in tr.Rules)
                    {
                        var match = true;
                        foreach (var ruleColumn in rc.Columns)
                        {
                            match &= col2Val.ContainsKey(ruleColumn);
                        }

                        if (match)
                        {
                            columnValues = col2Val;
                            rule         = rc;
                            matchedTable = tc;
                            goto ft_break;
                        }
                    }
                }
            }
ft_break:
            ;

            // 规则匹配处理,表级别和列级别。
            if (matchedTable == null)
            {
                var sql = visitor1.IsSchemaTrimmed() ? GenSql(ast1, stmt) : stmt;
                var rn  = new RouteResultsetNode[1];
                if (string.Empty.Equals(schema.DataNode) && IsSystemReadSql(ast1))
                {
                    rn[0] = new RouteResultsetNode(schema.RandomDataNode, sql);
                }
                else
                {
                    rn[0] = new RouteResultsetNode(schema.DataNode, sql);
                }
                rrs.Nodes = rn;
                return(rrs);
            }
            if (rule == null)
            {
                if (matchedTable.IsRuleRequired)
                {
                    throw new ArgumentException(string.Format("route rule for table {0} is required: {1}",
                                                              matchedTable.Name, stmt));
                }
                var dataNodes = matchedTable.DataNodes;
                var sql       = visitor1.IsSchemaTrimmed() ? GenSql(ast1, stmt) : stmt;
                var rn        = new RouteResultsetNode[dataNodes.Length];
                for (var i = 0; i < dataNodes.Length; ++i)
                {
                    rn[i] = new RouteResultsetNode(dataNodes[i], sql);
                }
                rrs.Nodes = rn;
                SetGroupFlagAndLimit(rrs, visitor1);
                return(rrs);
            }

            // 规则计算
            ValidateAst(ast1, matchedTable, rule, visitor1);
            var dnMap = RuleCalculate(matchedTable, rule, columnValues);

            if (dnMap == null || dnMap.IsEmpty())
            {
                throw new ArgumentException("No target dataNode for rule " + rule);
            }

            // 判断路由结果是单库还是多库
            if (dnMap.Count == 1)
            {
                var dataNode = matchedTable.DataNodes[dnMap.Keys.FirstOrDefault()];
                //string dataNode = matchedTable.GetDataNodes()[dnMap.Keys.GetEnumerator().Current];
                var sql = visitor1.IsSchemaTrimmed() ? GenSql(ast1, stmt) : stmt;
                var rn  = new RouteResultsetNode[1];
                rn[0]     = new RouteResultsetNode(dataNode, sql);
                rrs.Nodes = rn;
            }
            else
            {
                var rn = new RouteResultsetNode[dnMap.Count];
                if (ast1 is DmlInsertReplaceStatement)
                {
                    var ir = (DmlInsertReplaceStatement)ast1;
                    DispatchInsertReplace(rn, ir, rule.Columns, dnMap, matchedTable, stmt, visitor1);
                }
                else
                {
                    DispatchWhereBasedStmt(rn, ast1, rule.Columns, dnMap, matchedTable, stmt, visitor1);
                }
                rrs.Nodes = rn;
                SetGroupFlagAndLimit(rrs, visitor1);
            }
            return(rrs);
        }
Exemplo n.º 28
0
        /// <returns>dataNodeIndex -&gt; [partitionKeysValueTuple+]</returns>
        private static IDictionary <int, IList <object[]> > RuleCalculate(TableConfig matchedTable,
                                                                          RuleConfig rule,
                                                                          IDictionary <string, IList <object> > columnValues)
        {
            var map         = new Dictionary <int, IList <object[]> >();
            var algorithm   = rule.RuleAlgorithm;
            var cols        = rule.Columns;
            var parameter   = new Dictionary <string, object>(cols.Count);
            var colsValIter = new List <IList <object> >(columnValues.Count);
            var columnCount = 0;

            foreach (var rc in cols)
            {
                var list = columnValues.GetValue(rc);
                if (list == null)
                {
                    var msg = "route err: rule column " + rc + " dosn't exist in extract: " + columnValues;
                    throw new ArgumentException(msg);
                }
                if (columnCount <= 0)
                {
                    columnCount = list.Count;
                }

                colsValIter.Add(list);
            }

            try
            {
                var countIndex = 0;
                while (countIndex < columnCount)
                {
                    var tuple = new object[cols.Count];
                    for (int i = 0, len = cols.Count; i < len; ++i)
                    {
                        var value = colsValIter[i][countIndex];
                        tuple[i]           = value;
                        parameter[cols[i]] = value;
                    }

                    var dataNodeIndexes = CalcDataNodeIndexesByFunction(algorithm, parameter);
                    for (var i1 = 0; i1 < dataNodeIndexes.Length; ++i1)
                    {
                        var dataNodeIndex = dataNodeIndexes[i1];
                        var list          = map.GetValue(dataNodeIndex);
                        if (list == null)
                        {
                            list = new List <object[]>();
                            map[dataNodeIndex] = list;
                        }
                        list.Add(tuple);
                    }

                    countIndex++;
                }
            }
            catch (Exception e)
            {
                var msg = "route err: different rule columns should have same value number:  " + columnValues;
                throw new ArgumentException(msg, e);
            }
            return(map);
        }