Example #1
0
 private void ToBytes(IBytesSink sink)
 {
     LedgerIndex.ToBytes(sink);
     TotalDrops.ToBytes(sink);
     ParentHash.ToBytes(sink);
     TransactionHash.ToBytes(sink);
     StateHash.ToBytes(sink);
     ParentCloseTime.ToBytes(sink);
     CloseTime.ToBytes(sink);
     CloseResolution.ToBytes(sink);
     CloseFlags.ToBytes(sink);
 }
        public HashTransformer(StateHash hash)
        {
            mHash = hash;
            if (hash == null)
                return;

            mHasher = new SHA256Cng();

            var bytes = mHash.GetBytes();
            mHasher.TransformBlock(bytes, 0, bytes.Length, null, 0);

            mCryptoStream = new CryptoStream(new FakeStream(), mHasher, CryptoStreamMode.Write);
        }
Example #3
0
        /// <summary>
        /// Construtor para um automata recebendo o estado inicial e a lista de todos os estados já com suas transições.
        /// </summary>
        /// <param name="initialState">Estado inicial do automato</param>
        /// <param name="stateList">Lista dos estados com suas transições</param>
        /// <param name="nullSymbol">Representa o valor nulo ou vazio do automato</param>
        public Automata(State <T, E> initialState, List <State <T, E> > stateList, List <E> transictionList, E nullSymbol)
        {
            _initialState = initialState;
            _stateList    = stateList;

            foreach (State <T, E> state in stateList)
            {
                StateHash.Add(state.StateValue, state);
            }

            _transictionList = transictionList;
            _nullSymbol      = nullSymbol;
        }
        public StateHash CalculateTransform(StateHash currentHash)
        {
            if (mKnownState != null)
                return mKnownState;

            using (var transform = new HashTransformer(currentHash))
            {
                foreach (var db in mDatabases.OrderBy(x => x.Name))
                {
                    transform.TransformWithFileSmart(db.BackupFilePath);
                }

                return transform.GetResult();
            }
        }
Example #5
0
        public GameState(GameState prevState, MapTile pos1, MapTile pos2, MapTile pos3, MapTile pos4, MapTile[] contrActors, Direction moveDir, StateHash hash)
        {
            this.PrevState   = prevState;
            this.pos1        = pos1;
            this.pos2        = pos2;
            this.pos3        = pos3;
            this.pos4        = pos4;
            this.ContrActors = contrActors;
            this.moveDir     = moveDir;
            this.Hash        = hash;

            if (prevState != null)
            {
                turn = prevState.turn + 1;
            }
        }
        public void Add(DatabaseConnectionConfig dbConfig, string dbName, StateHash hash)
        {
            var db = GetDatabaseDir(dbName, true);
            var file = Path.Combine(db.FullName, GetFileName(hash));

            if (File.Exists(file))
                return;

            if (mAutoGC)
                GarbageCollect(true);

            var exitCode = 0;
            mLog.LogFormat("Caching {0} to {1}", dbName, file);

            if (!mDryRun)
            {
                using (var process = SqlUtils.BackupDatabase(dbConfig, dbName, file, mAllowCompression))
                using (mLog.IndentScope())
                {
                    foreach (var line in process.GetOutput())
                    {
                        mLog.Log(line.Line);
                    }

                    exitCode = process.ExitCode;
                }
            }

            if (exitCode != 0)
            {
                mLog.LogFormat("WARNING: Error caching {0}. Continuing anyways.", dbName);
                File.Delete(file);
            }
            else
            {
                UpdateHit(dbName, hash);
            }
        }
        public StateHash RunTransform(StateHash currentHash, bool dryRun, ILog log)
        {
            if (mKnownState != null)
            {
                foreach (var db in mDatabases.OrderBy(x => x.Name))
                {
                    RestoreDatabase(db, dryRun, log);
                }

                return mKnownState;
            }

            using (var transform = new HashTransformer(currentHash))
            {
                foreach (var db in mDatabases.OrderBy(x => x.Name))
                {
                    transform.TransformWithFileSmart(db.BackupFilePath);
                    RestoreDatabase(db, dryRun, log);
                }

                return transform.GetResult();
            }
        }
 public StatEntry(string database, StateHash hash, string file, DateTime? lastHit)
 {
     mDatabase = database;
     mHash = hash;
     mFile = file;
     mLastHit = lastHit;
 }
        private void UpdateHit(string dbName, StateHash hash)
        {
            if (mDryRun)
                return;

            UpdateHits(Enumerable.Repeat(Tuple.Create(dbName, hash), 1));
        }
Example #10
0
 private static string GetFileName(StateHash hash)
 {
     return hash.ToHexString();
 }
Example #11
0
        public bool TryGet(string dbName, StateHash hash, bool updateHit, out string path)
        {
            path = null;

            var root = GetCachesDir(false);
            if (!root.Exists)
                return false;

            var db = new DirectoryInfo(Path.Combine(root.FullName, dbName));
            if (!db.Exists)
                return false;

            var file = new FileInfo(Path.Combine(db.FullName, GetFileName(hash)));
            if (!file.Exists)
                return false;

            if (updateHit)
                UpdateHit(dbName, hash);

            path = file.FullName;

            return true;
        }
Example #12
0
        private StateHash ExecuteCore(TaskExecutionContext context, StateHash hash, bool execute)
        {
            RecipeConfig recipe;
            if (!mTaskDefinition.Commands.TryGetRecipe(context.Context.Action, out recipe))
                return hash;

            if (execute)
                context.Log.LogFormat("Running task '{0}'", Name);

            using (context.IndentScope())
            {
                foreach (var taskConfig in recipe)
                {
                    var task = mManager.CreateTask(taskConfig);

                    if (execute)
                        context.Log.LogFormat("Running sub-task '{0}'", task.Name);

                    using (context.IndentScope())
                    {
                        var ctx = new TaskExecutionContext(context.Context, context.Feature, taskConfig, context.Replacer.WithSubTask(mTaskDefinition, taskConfig));
                        if (execute)
                            task.Execute(ctx, ref hash);
                        else
                            task.Simulate(ctx, ref hash);
                    }
                }
            }

            return hash;
        }
        /// <summary>
        /// Método para gerar as transições a partir de regra de um dado estado
        /// </summary>
        /// <param name="state">Novo estado</param>
        /// <param name="before">Estado que está apontando diretamente para este novo estado</param>
        private void GenerateTransictions(State <string, Symbol> state, State <string, Symbol> before)
        {
            //StateValue é, no caso, a regra com o ponto
            Symbol symbol = GetNextToPoint(state.StateValue);

            if (symbol != null)
            {
                //Preciso verificar se já existe transição para aquele símbolo, se já existir, não faz nada
                if (before.TransictionIn(symbol) != null)
                {
                    return;
                }

                if (symbol is NonTerminal)
                {
                    #region Regra 2
                    NonTerminal nonTerminal = (NonTerminal)symbol;

                    //Regra 2

                    //Criar uma nova regra para as substituições do não terminal e adiciona as transições em vazio para elas
                    string   nonTerminalRule = nonTerminal.Rule;
                    string[] parameters      = new string[] { };

                    if (nonTerminalRule.Contains("|"))
                    {
                        parameters = nonTerminalRule.Split('|');
                    }
                    else
                    {
                        parameters = new string[] { nonTerminalRule };
                    }

                    bool         exists   = false;
                    GrammarState newState = null;
                    foreach (string ruleElement in parameters)
                    {
                        //Criar apenas um estado para a substituição do não terminal
                        string pointedRule = nonTerminal.Value + ":. " + ruleElement;

                        //Verifica se o estado já existe
                        exists   = false;
                        newState = null;
                        if (StateHash.ContainsKey(pointedRule))
                        {
                            newState = (GrammarState)StateHash[pointedRule];
                            exists   = true;
                        }
                        else
                        {
                            newState = new GrammarState(pointedRule);
                            StateHash.Add(pointedRule, newState);
                        }

                        state.AddTransiction(Terminal.Empty, newState);

                        //Se o estado não existia ainda, gerar as transições a partir dele
                        if (!exists)
                        {
                            GenerateTransictions(newState, state);
                        }

                        //Mover o point
                        string newRule = MovePointToRight(state.StateValue);

                        exists   = false;
                        newState = null;
                        if (StateHash.ContainsKey(newRule))
                        {
                            newState = (GrammarState)StateHash[newRule];
                            exists   = true;
                        }
                        else
                        {
                            newState = new GrammarState(newRule);
                            StateHash.Add(newRule, newState);
                        }

                        if (!exists)
                        {
                            state.AddTransiction(nonTerminal, newState);
                            GenerateTransictions(newState, state);
                        }
                    }

                    if (nonTerminal.FirstContainsEmpty())
                    {
                        state.IsFinal = true;
                    }

                    #endregion
                }
                else
                {
                    Terminal terminal = (Terminal)symbol;
                    if (terminal.Equals(Terminal.FinalPoint))
                    {
                        //Estado de item completo
                        state.IsFinal = true;
                    }
                    else
                    {
                        if (terminal.Equals(Terminal.Empty))
                        {
                            //Estado anterior é final
                            before.IsFinal = true;
                        }
                        #region Regra 3
                        //Regra 3

                        //Mover o ponto, criar um estado com a nova regra e a transição será neste terminal
                        string newRule = MovePointToRight(state.StateValue);

                        bool         exists   = false;
                        GrammarState newState = null;
                        if (StateHash.ContainsKey(newRule))
                        {
                            newState = (GrammarState)StateHash[newRule];
                            exists   = true;
                        }
                        else
                        {
                            newState = new GrammarState(newRule);
                            StateHash.Add(newRule, newState);
                        }

                        state.AddTransiction(terminal, newState);

                        if (!exists)
                        {
                            GenerateTransictions(newState, state);
                        }
                    }
                    #endregion
                }
            }
        }
 public void Add(DatabaseConnectionConfig dbConfig, string dbName, StateHash hash)
 {
 }
            public StateHash Run(DeployContext context, StateHash hash, ICacheManager cacheManager, bool first = true, bool last = true)
            {
                if (mLogPre != null)
                    context.ApplicationContext.Log.Log(mLogPre);

                if (mTransform != null)
                {
                    var stopWatch = new Stopwatch();
                    stopWatch.Start();
                    hash = mTransform.RunTransform(hash, context.DryRun, context.ApplicationContext.Log);
                    stopWatch.Stop();

                    if (!context.DryRun)
                    {
                        var rhf = GetResumeHashFile(context);
                        File.WriteAllText(rhf.FullName, hash.ToHexString());
                    }

                    if (!first && !last && stopWatch.Elapsed >= context.ApplicationContext.UserConfig.Cache.MinDeployTime)
                    {
                        foreach (var db in context.ApplicationContext.ProjectConfig.Databases)
                        {
                            cacheManager.Add(context.ApplicationContext.UserConfig.Databases.Connection, db, hash);
                        }
                    }
                }
                else if (mChildren.Count > 0)
                {
                    using (context.ApplicationContext.Log.IndentScope())
                    {
                        for (var i = 0; i < mChildren.Count; i++)
                        {
                            var child = mChildren[i];
                            hash = child.Run(context, hash, cacheManager, first, last && i == mChildren.Count - 1);
                            first = false;
                        }
                    }
                }

                if (mLogPost != null)
                    context.ApplicationContext.Log.Log(mLogPost);

                return hash;
            }
Example #16
0
        /// <summary>
        /// Construtor default de um automato de gramática. Criado a partir da gramática setada em Symbol.
        /// </summary>
        public GrammarDeterministicAutomata()
        {
            GrammarNonDeterministicAutomata nonDeterministic = new GrammarNonDeterministicAutomata();

            //Cria uma referência aos terminais para comparações
            Dictionary <string, Terminal>    terminalHash    = Symbol.TerminalHash;
            Dictionary <string, NonTerminal> nonTerminalHash = Symbol.NonTerminalHash;

            GrammarState initialState = GrammarState.ConvertFrom(nonDeterministic.InitialState);

            Dictionary <GrammarState, GrammarPowerSet> hash = new Dictionary <GrammarState, GrammarPowerSet>();

            List <Symbol> transictionList = new List <Symbol>();

            transictionList.AddRange(Symbol.TerminalList);
            transictionList.AddRange(Symbol.NonTerminalList);

            //Retorna com o hash completo com todos os fechos
            GrammarPowerSet initialPowerSet = GeneratePowerSet(initialState, transictionList, Terminal.Empty, hash);

            //Carrega o valor do estado do primeiro fecho transitivo
            initialState = initialPowerSet.PowerSetToState();

            //Carrega a lista com os estados do fecho transitivo criado
            List <GrammarState> stateList = new List <GrammarState>();

            foreach (GrammarState state in hash.Keys)
            {
                GrammarPowerSet powerSet = hash[state];
                stateList.Add(powerSet.PowerSetToState());
            }

            InitialState = initialPowerSet.PowerSetToState();
            //StateList = stateList;
            foreach (GrammarState state in stateList)
            {
                StateList.Add(state.ConvertTo());
                StateHash.Add(state.StateValue, state);
            }
            TransictionList = transictionList;
            NullSymbol      = Terminal.Empty;

            #region código abandonado
            //List<Symbol> transictionList = new List<Symbol>();
            //foreach (string name in terminalHash.Keys)
            //{
            //    transictionList.Add(terminalHash[name]);
            //}
            //foreach (string name in nonTerminalHash.Keys)
            //{
            //    transictionList.Add(nonTerminalHash[name]);
            //}

            //Automata<string, Symbol> afd = Automata<string, Symbol>.AFNtoAFD(afn, transictionList, Terminal.Empty);

            //InitialState = afd.InitialState;
            //StateList = afd.StateList;
            //TransictionList = afd.TransictionList;
            //NullSymbol = afd.NullSymbol;

            ////Popular o hash
            //foreach(State<string, Symbol> afdState in StateList)
            //{
            //    StateHash.Add(afdState.StateValue, afdState);
            //}
            #endregion
        }
 public RestoreDatabasesTransform(DatabaseConnectionConfig databaseConnection, DatabaseBackupInfo[] databases, StateHash knownState = null)
 {
     mDatabaseConnection = databaseConnection;
     mDatabases = databases;
     mKnownState = knownState;
 }
            public Tuple<ExecutionNode, StateHash, bool, StateHash> Calculate(DeployContext context, StateHash hash, StateHash startingHash, ICacheManager cacheManager)
            {
                if (mTransform != null)
                {
                    hash = mTransform.CalculateTransform(hash);
                    if (hash == startingHash)
                        return Tuple.Create((ExecutionNode)null, hash, true, (StateHash)null);

                    var backups = GetCachedBackups(cacheManager, hash, context.ApplicationContext.ProjectConfig.Databases);
                    if (backups != null)
                    {
                        var node = new ExecutionNode("Restoring state from cache...", "Cache restored");
                        node.AddChild(new ExecutionNode(new RestoreDatabasesTransform(context.ApplicationContext.UserConfig.Databases.Connection, backups, hash)));

                        return Tuple.Create(node, hash, true, hash);
                    }
                }
                else if (mChildren.Count > 0)
                {
                    var result = new ExecutionNode(mLogPre, mLogPost);
                    var changed = false;
                    StateHash cacheHash = null;

                    foreach (var child in mChildren)
                    {
                        var calc = child.Calculate(context, hash, startingHash, cacheManager);
                        if (calc.Item3)
                        {
                            changed = true;
                            result.mChildren.Clear();
                        }

                        if (calc.Item1 != null)
                            result.mChildren.Add(calc.Item1);

                        hash = calc.Item2;
                        if (calc.Item4 != null)
                            cacheHash = calc.Item4;
                    }

                    if (result.mChildren.Count == 0)
                        result = null;

                    return Tuple.Create(result, hash, changed, cacheHash);
                }

                return Tuple.Create(this, hash, false, (StateHash)null);
            }
Example #19
0
 public void Execute(TaskExecutionContext context, ref StateHash hash)
 {
     hash = ExecuteCore(context, hash, true);
 }
            private static DatabaseBackupInfo[] GetCachedBackups(ICacheManager cacheManager, StateHash hash, IReadOnlyCollection<string> dbs)
            {
                var result = new DatabaseBackupInfo[dbs.Count];
                var i = 0;

                foreach (var db in dbs)
                {
                    string path;
                    if (!cacheManager.TryGet(db, hash, false, out path))
                        return null;

                    result[i++] = new DatabaseBackupInfo(db, path);
                }

                return result;
            }
Example #21
0
 public void Simulate(TaskExecutionContext context, ref StateHash hash)
 {
     hash = ExecuteCore(context, hash, false);
 }
 public bool TryGet(string dbName, StateHash hash, bool updateHit, out string path)
 {
     path = null;
     return false;
 }
Example #23
0
 public override string ToString()
 {
     return(StateHash.ToString() + ": " + MeshVertexBuffer.VertexCount);
 }