Exemplo n.º 1
0
        private void TmrServiceStatusCallback(Object o)
        {
            IAMDatabase db = null;

            try
            {
                db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();
                db.Timeout = 600;

                db.ServiceStatus("Report", JSON.Serialize2(new { host = Environment.MachineName, executing = executing }), null);

                db.closeDB();
            }
            catch { }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }

                db = null;
            }
        }
Exemplo n.º 2
0
        private void LicTimer(Object oData)
        {
            using (IAMDatabase db2 = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword))
                using (ServerKey2 sk = new ServerKey2(db2.Connection))
                    try
                    {
                        db2.openDB();

                        TimeSpan ts = sk.ServerCert.NotAfter - DateTime.Now;

                        if (ts.TotalDays < 60)
                        {
                            db2.AddUserLog(LogKey.Certificate_Error, null, "Engine", UserLogLevel.Fatal, 0, 0, 0, 0, 0, 0, 0, "Server certificate will expire in " + sk.ServerCert.NotAfter.ToString("yyyy-MM-dd") + ", please renew", sk.ServerInstallationKey.AbsoluteUri);
                        }
                        else if (ts.TotalDays < 180)
                        {
                            db2.AddUserLog(LogKey.Certificate_Error, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Server certificate will expire in " + sk.ServerCert.NotAfter.ToString("yyyy-MM-dd") + ", please renew", sk.ServerInstallationKey.AbsoluteUri);
                        }
                        else if (ts.TotalDays < 360)
                        {
                            db2.AddUserLog(LogKey.Certificate_Error, null, "Engine", UserLogLevel.Warning, 0, 0, 0, 0, 0, 0, 0, "Server certificate will expire in " + sk.ServerCert.NotAfter.ToString("yyyy-MM-dd") + ", please renew", sk.ServerInstallationKey.AbsoluteUri);
                        }

                        db2.closeDB();
                    }
                    catch { }
        }
Exemplo n.º 3
0
        private void TmrServiceStatusCallback(Object o)
        {
            IAMDatabase db = null;

            try
            {
                db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();
                db.Timeout = 600;

                Double percent = 0;

                percent = ((Double)(filesProcessed) / (Double)filesToProcess) * 100F;

                if (Double.IsNaN(percent) || Double.IsInfinity(percent))
                {
                    percent = 0;
                }

                db.ServiceStatus("Inbound", JSON.Serialize2(new { host = Environment.MachineName, executing = executing, start_time = startTime.ToString("o"), last_status = last_status, total_files = filesToProcess, processed_files = filesProcessed, percent = percent }), null);

                db.closeDB();
            }
            catch { }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }

                db = null;
            }
        }
Exemplo n.º 4
0
        private void TmrServiceStatusCallback(Object o)
        {
            IAMDatabase db = null;

            try
            {
                db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();
                db.Timeout = 600;

                db.ServiceStatus("WorkflowProcessor", JSON.Serialize2(new { host = Environment.MachineName, executing = executing, start_time = startTime.ToString("o"), last_status = last_status }), null);

                db.closeDB();
            }
            catch { }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }

                db = null;
            }
        }
Exemplo n.º 5
0
        private void TmrServiceStatusCallback(Object o)
        {
            IAMDatabase db = null;

            try
            {
                db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();
                db.Timeout = 600;

                db.ServiceStatus("Engine", JSON.Serialize2(new { host = Environment.MachineName, executing = executing, start_time = startTime.ToString("o"), total_registers = totalReg, atual_register = atualReg, percent = iPercent, errors = errors, new_users = newUsers, ignored = ignored, thread_count = (queueManager != null ? queueManager.ThreadCount : 0), queue_count = (queueManager != null ? queueManager.QueueCount : 0), last_status = last_status, queue_description = (queueManager != null ? queueManager.QueueCount2 : "") }), null);

                db.closeDB();
            }
            catch { }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }

                db = null;
            }
        }
Exemplo n.º 6
0
        private void ReportTimer(Object state)
        {
            if (executing)
            {
                return;
            }

            executing = true;

            //TextLog.Log("Report", "Starting report timer");
            try
            {
                //IAMDeploy deploy = new IAMDeploy("report", localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                //deploy.DeployAll();

                IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();

                DataTable dtS = db.Select("select * from report_schedule");

                try
                {
                    //Processa um a um dos agendamentos
                    foreach (DataRow dr in dtS.Rows)
                    {
                        CheckSchedule(db, (Int64)dr["id"], (Int64)dr["report_id"], dr["schedule"].ToString(), (DateTime)dr["next"]);
                    }
                }
                catch (Exception ex)
                {
                    TextLog.Log("Report", "\tError on report timer schedule: " + ex.Message);
                    db.AddUserLog(LogKey.Report, null, "Report", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Error on report scheduler", ex.Message);
                }

                db.closeDB();
            }
            catch (Exception ex1)
            {
                TextLog.Log("Report", "\tError on report timer: " + ex1.Message);
            }
            finally
            {
                //TextLog.Log("Report", "\tScheduled for new report process in 60 seconds");
                //TextLog.Log("Report", "Finishing report timer");
                executing = false;
            }
        }
Exemplo n.º 7
0
        private void DispatcherTimer(Object state)
        {
            if (executing)
            {
                return;
            }

            executing = true;

            TextLog.Log("Dispatcher", "Starting dispatcher timer");
            try
            {
                IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();

                DataTable dtS = db.Select("select * from vw_schedules order by context_id, [order]");

                //Processa um a um dos agendamentos
                foreach (DataRow dr in dtS.Rows)
                {
                    CheckSchedule(db, (Int64)dr["schedule_id"], (Int64)dr["resource_plugin_id"], (Int64)dr["resource_id"], dr["schedule"].ToString(), (DateTime)dr["next"]);
                }

                dtS.Clear();
                dtS = null;

                db.closeDB();
                db.Dispose();
                db = null;
            }
            catch (Exception ex)
            {
                TextLog.Log("Dispatcher", "\tError on dispatcher timer " + ex.Message);
            }
            finally
            {
                TextLog.Log("Dispatcher", "Finishing dispatcher timer");
                executing = false;
            }
        }
Exemplo n.º 8
0
        private void TmrCallback(Object sender)
        {
            if (executing)
            {
                return;
            }

            executing = true;

            TextLog.Log("Engine", "Time access control", "Starting processor timer");
            IAMDatabase db = null;

            try
            {
                db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();
                db.Timeout = 600;

                //Seleciona as entidades/identidades vinculadas a um resource x plugin que tenha controle de acesso por horário
                DataTable dtRegs = db.Select("select i.id, i.temp_locked, e.id entity_id, r.name resource_name from entity e with(nolock) inner join [identity] i with(nolock) on e.id = i.entity_id  inner join resource_plugin rp with(nolock) on i.resource_plugin_id = rp.id and i.resource_plugin_id = rp.id inner join resource r with(nolock) on rp.resource_id = r.id  inner join resource_plugin_role_time_acl acl with(nolock) on acl.resource_plugin_id = rp.id  inner join role r1 with(nolock) on r1.id = acl.role_id inner join identity_role ir with(nolock) on ir.identity_id = i.id and ir.role_id = r1.id where r.enabled = 1 and rp.enabled = 1 group by i.id, i.temp_locked, e.id, r.name");

                if ((dtRegs == null) || (dtRegs.Rows.Count == 0))
                {
                    TextLog.Log("Engine", "Time access control", "\t0 registers to process");
                    return;
                }

                foreach (DataRow dr in dtRegs.Rows)
                {
                    try
                    {
                        using (EntityTimeControl eAcl = new EntityTimeControl(db, (Int64)dr["id"]))
                        {
                            StringBuilder tLog = new StringBuilder();
                            EntityTimeControl.ProccessLog log = new EntityTimeControl.ProccessLog(delegate(String text)
                            {
                                tLog.AppendLine(text);

#if DEBUG
                                TextLog.Log("Engine", "Time access control", text);
#endif
                            });

                            eAcl.OnLog += log;
                            eAcl.Process((Boolean)dr["temp_locked"]);
                            eAcl.OnLog -= log;

                            if ((Boolean)dr["temp_locked"] != eAcl.Locked)
                            {
                                db.AddUserLog((eAcl.Locked ? LogKey.User_TempLocked : LogKey.User_TempUnlocked), null, "Engine", UserLogLevel.Info, 0, 0, 0, 0, 0, Int64.Parse(dr["entity_id"].ToString()), Int64.Parse(dr["id"].ToString()), "Identity of resource " + dr["resource_name"] + (eAcl.Locked ? " locked by the time profile" : " unlocked by the time profile"), tLog.ToString());
                            }

                            tLog.Clear();
                            tLog = null;
                        }
                    }
                    catch (Exception ex) {
                        TextLog.Log("Engine", "Time access control", "\tError on time control processor " + ex.Message);
                    }
                }

                Console.WriteLine("");
            }
            catch (Exception ex)
            {
                db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Error on time control processor", ex.Message);
                TextLog.Log("Engine", "Time access control", "\tError on time control processor timer " + ex.Message);
            }
            finally
            {
                TextLog.Log("Engine", "Time access control", "Finishing processor timer");

                if (db != null)
                {
                    db.closeDB();
                }

                executing = false;
            }
        }
Exemplo n.º 9
0
        private void WatchdogTimerCallback(Object o)
        {
            IAMDatabase db = null;

            try
            {
                //check if we need to stop any service
                db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();
                db.Timeout = 600;

                //Limpa status lixo
                db.ExecuteNonQuery("delete from service_status where last_status < DATEADD(day,-15,getdate())");

                //seleciona os servicos comproblema ou parados
                DataTable dtServices = db.Select("select * from service_status where started_at is null or last_status < DATEADD(hour,-1,getdate()) or case when started_at is null then cast(getdate() as date) else cast(started_at as date) end <> cast(getdate() as date)");
                if (dtServices != null && dtServices.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtServices.Rows)
                    {
                        String svcName = dr["service_name"].ToString();

                        if (svcName.ToLower().IndexOf("watchdog") >= 0)
                        {
                            continue;
                        }

                        TextLog.Log("Watchdog", "Killing service '" + svcName + "'");
                        Killall(svcName);
                        Killall("IAM" + svcName);
                    }
                }

                db.closeDB();
            }
            catch { }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }

                db = null;
            }

            try
            {
                ServiceController[] services = ServiceController.GetServices();

                foreach (ServiceController service in ServiceController.GetServices())
                {
                    try
                    {
                        switch (service.ServiceName.ToLower())
                        {
                        case "iambackup":
                        case "iamdispatcher":
                        case "iamengine":
                        case "iaminbound":
                        case "iamreport":
                        case "iamproxy":
                        case "iammultiproxy":
                        case "iammessenger":
                        case "iamworkflowprocessor":
                            StartupState stMode = StartMode(service.ServiceName);

                            switch (stMode)
                            {
                            case StartupState.Automatic:
                                if ((service.Status.Equals(ServiceControllerStatus.Stopped)) || (service.Status.Equals(ServiceControllerStatus.StopPending)))
                                {
                                    TextLog.Log("Watchdog", "Starting service '" + service.DisplayName + "'");
                                    service.Start();

                                    try
                                    {
                                        db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                                        db.openDB();
                                        db.Timeout = 600;

                                        db.AddUserLog(LogKey.Watchdog, null, "Watchdog", UserLogLevel.Warning, 0, 0, 0, 0, 0, 0, 0, "Starting service '" + service.DisplayName + "'");

                                        db.closeDB();
                                    }
                                    catch { }
                                    finally
                                    {
                                        if (db != null)
                                        {
                                            db.Dispose();
                                        }

                                        db = null;
                                    }
                                }
                                break;

                            default:
                                TextLog.Log("Watchdog", "Unknow action for service start mode '" + stMode.ToString() + "' for service '" + service.DisplayName + "'");
                                break;
                            }

                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        TextLog.Log("Watchdog", "Erro ao processar o controle do serviço '" + service.DisplayName + "': " + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                TextLog.Log("Watchdog", "Erro ao processar o controle dos serviços: " + ex.Message);
            }
        }
Exemplo n.º 10
0
        protected override void OnStart(string[] args)
        {
            /*************
             * Carrega configurações
             */

            localConfig = new ServerLocalConfig();
            localConfig.LoadConfig();

            if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null);
            }

            Int32 cnt      = 0;
            Int32 stepWait = 15000;

            while (cnt <= 10)
            {
                try
                {
                    IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                    db.openDB();

                    db.ServiceStart("Engine", null);

                    db.closeDB();

                    break;
                }
                catch (Exception ex)
                {
                    if (cnt < 10)
                    {
                        TextLog.Log("Engine", "Falha ao acessar o banco de dados: " + ex.Message);
                        Thread.Sleep(stepWait);
                        stepWait = stepWait * 2;
                        cnt++;
                    }
                    else
                    {
                        StopOnError("Falha ao acessar o banco de dados", ex);
                    }
                }
            }



            /*************
             * Gera os certificados do servidor
             * Verifica se o certificade está próximo de vencer
             */
            IAMDatabase db2 = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);

            db2.openDB();
            ServerKey2 sk = new ServerKey2(db2.Connection);

            TimeSpan ts = sk.ServerCert.NotAfter - DateTime.Now;

            if (ts.TotalDays < 360)
            {
                //Inicia o timer que ficará gerando evento
                licTimer = new Timer(new TimerCallback(LicTimer), null, 200, 86400000); //a cada 24 Horas caso este processo não for reiniciado
            }

            db2.closeDB();


            intoTimer = new Timer(new TimerCallback(InfoTimer), null, 200, 900); //a cada 15 minutos

            /*************
             * Inicia as classes de processamento
             */

            RegistryImporter imp = new RegistryImporter(localConfig);

            imp.Start();

            TimeAccessControl acl = new TimeAccessControl(localConfig);

            acl.Start();
        }
Exemplo n.º 11
0
        private void InfoTimer(Object oData)
        {
            TimeSpan tsInfo = lastInfo - new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 0, 0, 0);

            if (infoExec || ((Int32)tsInfo.TotalDays == 0))
            {
                return;
            }

            infoExec = true;

            using (IAMDatabase db2 = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword))
                using (ServerKey2 sk = new ServerKey2(db2.Connection))
                    try
                    {
                        db2.openDB();

                        List <Object> lics    = new List <Object>();
                        Version       version = new Version("0.0");

                        try
                        {
                            DataTable dtLicCount = db2.ExecuteDataTable("select count(e.id) qty, c.enterprise_id from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id where e.deleted = 0 group by c.enterprise_id");
                            if (dtLicCount != null)
                            {
                                foreach (DataRow dr in dtLicCount.Rows)
                                {
                                    String        message = "";
                                    List <String> data    = new List <string>();

                                    DataTable dtLic = db2.ExecuteDataTable("select * from license where enterprise_id in (0, " + dr["enterprise_id"] + ")");
                                    if (dtLic == null)
                                    {
                                        message = "Error on get licenses on server";
                                    }

                                    if (dtLic.Rows.Count == 0)
                                    {
                                        message = "License list is empty";
                                    }

                                    foreach (DataRow dr2 in dtLic.Rows)
                                    {
                                        data.Add(dr2["license_data"].ToString());
                                    }

                                    //Resgata do banco a contagem atual de entidades

                                    var eItem = new {
                                        id      = dr["enterprise_id"].ToString(),
                                        message = message,
                                        entity  = dr["qty"],
                                        data    = data
                                    };

                                    lics.Add(eItem);
                                }
                            }


                            try
                            {
                                version = Assembly.GetEntryAssembly().GetName().Version;
                            }
                            catch { }

                            var info = new
                            {
                                date             = DateTime.UtcNow.ToString("o"),
                                product          = "SafeId",
                                version          = version.ToString(),
                                installation_key = sk.ServerInstallationKey.AbsoluteUri,
                                server_cert      = sk.ServerCertString,
                                licences         = lics
                            };

                            String jData = JSON.Serialize2(info);

                            WebClient client = new WebClient();
                            client.UploadData("https://licencing.safetrend.com.br/si/", Encoding.UTF8.GetBytes(jData));

                            lastInfo = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 0, 0, 0);
                        }
                        catch { }
                        finally
                        {
                            db2.closeDB();
                        }
                    }
                    catch { }

            infoExec = false;
        }
Exemplo n.º 12
0
        private void MessengerTimer(Object state)
        {
            if (executing)
            {
                return;
            }

            executing = true;

            startTime = DateTime.Now;

            try
            {
                IAMDatabase db = null;
                try
                {
                    db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                    db.openDB();
                    db.Timeout = 900;

                    //Lista todas as mensagens pendêntes de entrega
                    //Status: W = Waiting, PE = Protocol error
                    //DataTable dtMessages = db.ExecuteDataTable("select m.*, e.last_uri from [st_messages] m with(nolock) inner join enterprise e with(nolock) on e.id = m.enterprise_id where status in ('W','PE')");
                    DataTable dtMessages = db.ExecuteDataTable("select m.id from [st_messages] m with(nolock) where status in ('W','PE')");
                    if ((dtMessages != null) && (dtMessages.Rows.Count > 0))
                    {
                        try
                        {
                            TextLog.Log("Messenger", "Starting message timer");

                            foreach (DataRow dr in dtMessages.Rows)
                            {
                                try
                                {
                                    using (MessageSender sender = new MessageSender(db, (Int64)dr["id"]))
                                        using (ServerDBConfig conf = new ServerDBConfig(db.Connection, true))
                                            sender.Send(conf.GetItem("mailFrom"), conf.GetItem("smtpServer"), conf.GetItem("username"), conf.GetItem("password"));
                                }
                                catch (Exception ex)
                                {
                                    DbParameterCollection par = new DbParameterCollection();
                                    par.Add("@message_id", typeof(Int64)).Value   = (Int64)dr["id"];
                                    par.Add("@status", typeof(String)).Value      = "Erro no envio";
                                    par.Add("@description", typeof(String)).Value = ex.Message;

                                    db.ExecuteNonQuery("UPDATE st_messages SET [status] = 'E' WHERE id = @message_id; INSERT INTO st_messages_status (message_id,date,error,status,description) VALUES(@message_id,getdate(),1,@status,@description);", par);
                                }
                            }
                        }
                        finally
                        {
                            if (db != null)
                            {
                                db.Dispose();
                            }

                            TextLog.Log("Messenger", "Finishing message timer");
                        }
                    }

                    db.closeDB();
                }
                finally
                {
                    if (db != null)
                    {
                        db.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                TextLog.Log("Messenger", "Error on message timer " + ex.Message);
            }
            finally
            {
                executing   = false;
                last_status = "";
                startTime   = new DateTime(1970, 1, 1);
            }
        }
Exemplo n.º 13
0
        protected override void OnStart(string[] args)
        {
            /*************
             * Carrega configurações
             */

            System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(this.GetType());
            basePath = Path.GetDirectoryName(asm.Location);

            localConfig = new ServerLocalConfig();
            localConfig.LoadConfig();

            if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null);
            }


            Int32 cnt      = 0;
            Int32 stepWait = 15000;

            while (cnt <= 10)
            {
                try
                {
                    IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                    db.openDB();

                    db.ServiceStart("Inbound", null);

                    //Recria a tabela temporária
                    db.ExecuteNonQuery(@"
                    IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'collector_imports_temp'))
                    BEGIN
                        DROP TABLE [collector_imports_temp];
                    END", System.Data.CommandType.Text, null, null);

                    db.ExecuteNonQuery(@"
                    IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'collector_imports_temp'))
                    BEGIN
                        select top 0 * into [collector_imports_temp] from [collector_imports];
                    END", System.Data.CommandType.Text, null, null);


                    db.closeDB();

                    break;
                }
                catch (Exception ex)
                {
                    if (cnt < 10)
                    {
                        TextLog.Log("Inbound", "Falha ao acessar o banco de dados: " + ex.Message);
                        Thread.Sleep(stepWait);
                        stepWait = stepWait * 2;
                        cnt++;
                    }
                    else
                    {
                        StopOnError("Falha ao acessar o banco de dados", ex);
                    }
                }
            }


            /*************
             * Inicia processo de verificação/atualização da base de dados
             */
            try
            {
                using (IAM.GlobalDefs.Update.IAMDbUpdate updt = new GlobalDefs.Update.IAMDbUpdate(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword))
                    updt.Update();
            }
            catch (Exception ex)
            {
                StopOnError("Falha ao atualizar o banco de dados", ex);
            }

            /*************
             * Inicia timer que processa os arquivos
             */

            Int32 maxThreads = 1;

            if (maxThreads > 0)
            {
                maxThreads = localConfig.EngineMaxThreads;
            }

            this.fileQueue = new QueueManager <FileInfo>(maxThreads, ProcQueue);
            this.fileQueue.Start();

            inboundTimer = new Timer(new TimerCallback(InboundTimer), null, 1000, 60000);
            statusTimer  = new Timer(new TimerCallback(TmrServiceStatusCallback), null, 100, 10000);
        }
Exemplo n.º 14
0
        private void ProcQueue(FileInfo f, Object oStarter)
        {
            IAMDatabase db = null;

            try
            {
                db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();
                db.Timeout = 900;
                Boolean rebuildIndex = false;

                String type = "";

                type = "";
                JSONRequest req = null;
                try
                {
                    using (FileStream fs = f.OpenRead())
                        req = JSON.GetRequest(fs);

                    if ((req.host == null) || (req.host == ""))
                    {
                        db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Paramter 'host' is empty on  " + f.Name);
                        return;
                    }

                    if ((req.enterpriseid == null) || (req.enterpriseid == ""))
                    {
                        db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Paramter 'enterpriseid' is empty on  " + f.Name);
                        return;
                    }

                    try
                    {
                        Int64 tst = Int64.Parse(req.enterpriseid);
                    }
                    catch
                    {
                        if ((req.enterpriseid == null) || (req.enterpriseid == ""))
                        {
                            db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Paramter 'enterpriseid' is not Int64  " + f.Name);
                            return;
                        }
                    }

                    ProxyConfig config = new ProxyConfig(true);
                    config.GetDBCertConfig(db.Connection, Int64.Parse(req.enterpriseid), req.host);

                    if (config.fqdn != null) //Encontrou o proxy
                    {
                        JsonGeneric jData = new JsonGeneric();
                        try
                        {
                            String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));
                            using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.server_pkcs12_cert), certPass), Convert.FromBase64String(req.data)))
                                jData.FromJsonBytes(cApi.clearData);
                        }
                        catch (Exception ex)
                        {
                            jData = null;
                            db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, config.proxyID, 0, 0, 0, 0, 0, 0, "Error on decrypt package data " + f.Name + " for enterprise " + req.enterpriseid + " and proxy " + req.host + ", " + ex.Message);
                        }

                        if (jData == null)
                        {
                            return;
                        }

                        type = jData.function.ToLower();

                        switch (type)
                        {
                        case "processimport-disabled":
                            rebuildIndex = true;
                            //ImportRegisters(config, jData, f, req, db);
                            f.Delete();
                            break;

                        case "processimportv2":
                            rebuildIndex = true;
                            last_status  = "Executando importação de registros";
                            ImportRegistersV2(config, jData, f, req, db);
                            f.Delete();
                            break;

                        case "processstructimport":
                            last_status = "Executando importação de registros de estrutura";
                            ImportRegistersStruct(config, jData, f, req, db);
                            f.Delete();
                            break;

                        case "notify":
                            last_status = "Executando importação de notificações";
                            ImportNotify(config, jData, f, req, db);

                            f.Delete();
                            break;

                        case "deleted":
                            last_status = "Executando importação de exclusões";
                            ImportDelete(config, jData, f, req, db);
                            f.Delete();
                            break;

                        case "logrecords":
                            last_status = "Executando importação de logs";
                            ImportLogs(config, jData, f, req, db);
                            f.Delete();
                            //f.MoveTo(f.FullName + ".imported");
                            break;

                        case "packagetrack":
                            last_status = "Executando importação de track dos pacotes";
                            ImportPackageTrack(config, jData, f, req, db);
                            f.Delete();
                            //f.MoveTo(f.FullName + ".imported");
                            break;

                        default:
                            db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, config.proxyID, 0, 0, 0, 0, 0, 0, "Invalid jData function '" + jData.function + "'");
                            break;
                        }
                    }
                    else
                    {
                        db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Proxy config not found for enterprise " + req.enterpriseid + " and proxy " + req.host);
                    }
                    config = null;
                }
                catch (Exception ex)
                {
                    TextLog.Log("Inbound", "Erro on process file '" + f.Name + "' (" + type + "): " + ex.Message);
                    db.AddUserLog(LogKey.Import, null, "Inbound", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Erro processing file '" + f.Name + "' (" + type + "): " + ex.Message);
                }
                finally
                {
                    last_status = "";
                    req         = null;

                    filesProcessed++;
                }

                /*
                 * if (rebuildIndex)
                 * {
                 *  db.Timeout = 900;
                 *  last_status = "Reindexando registros";
                 *  db.ExecuteNonQuery("sp_reindex_imports", CommandType.StoredProcedure, null);
                 * }*/
            }
            catch (Exception ex)
            {
                TextLog.Log("Inbound", "Error importing file (" + f.Name + ")" + ex.Message);
            }
            finally
            {
                if (db != null)
                {
                    db.closeDB();
                }
            }
        }
Exemplo n.º 15
0
        private Int32 _Deploy(Int64 entityId, Int64 resourcePluginId)
        {
            //Busca todos os plugins e recursos a serem publicados
            DataTable dtPlugins = null;
            Dictionary <Int64, LicenseControl> licControl = null;
            DataTable dtEnt        = null;
            Int32     packageCount = 0;

            StringBuilder deployLog = new StringBuilder();

            try
            {
                dtPlugins = db.Select("select r.context_id, p.id, p.scheme, p.uri, p.assembly, p.create_date, rp.id resource_plugin_id, rp.deploy_individual_package, r.id resource_id, r.proxy_id, p1.name as proxy_name, p1.id proxy_id, p1.enterprise_id, rp.deploy_after_login, rp.password_after_login, rp.deploy_process, rp.deploy_all, rp.deploy_password_hash, rp.use_password_salt, rp.password_salt_end, rp.password_salt from plugin p with(nolock)  inner join resource_plugin rp with(nolock) on rp.plugin_id = p.id  inner join [resource] r on r.id = rp.resource_id inner join proxy p1 on r.proxy_id = p1.id  where " + (resourcePluginId > 0 ? " rp.id = " + resourcePluginId + " and " : "") + " r.enabled = 1 and rp.enabled = 1 and rp.enable_deploy = 1 order by rp.[order]");
                if ((dtPlugins == null) || (dtPlugins.Rows.Count == 0))
                {
                    if ((entityId > 0) || (resourcePluginId > 0))
                    {
                        throw new Exception("0 plugin to process");
                    }

                    //TextLog.Log(moduleSender, "\t0 plugin to process");
                    DebugLog(entityId, "0 plugin to process");
                    return(0);
                }

                DebugLog(entityId, dtPlugins.Rows.Count + " plugin to process");

                licControl = new Dictionary <long, LicenseControl>();

                String rolesText = "";

                //Lista todos os plugins e resources habilitados
                foreach (DataRow dr in dtPlugins.Rows)
                {
                    Boolean individualPackage = (Boolean)dr["deploy_individual_package"];

                    deployLog = new StringBuilder();

                    DebugLog(entityId, "proxy_name = " + dr["proxy_name"].ToString() + ", plugin = " + dr["uri"].ToString() + ", deploy_all? " + dr["deploy_all"].ToString());

                    ProxyConfig config = new ProxyConfig(true);
                    config.GetDBCertConfig(db.Connection, Int64.Parse(dr["enterprise_id"].ToString()), dr["proxy_name"].ToString());

                    DirectoryInfo proxyDir = new DirectoryInfo(Path.Combine(outDirBase.FullName, dr["proxy_id"].ToString() + "_" + dr["proxy_name"].ToString() + "\\" + Path.GetFileNameWithoutExtension(dr["assembly"].ToString()) + "\\rp" + dr["resource_plugin_id"].ToString()));

                    List <PluginConnectorBaseDeployPackage> packageList = new List <PluginConnectorBaseDeployPackage>();
                    List <Int64> roles = new List <Int64>();

                    Int64 enterpriseId = (Int64)dr["enterprise_id"];

                    LicenseControl lic = null;
                    if (!licControl.ContainsKey(enterpriseId))
                    {
                        lic = LicenseChecker.GetLicenseData(db.Connection, null, enterpriseId);
                        licControl.Add(enterpriseId, lic);
                    }
                    else
                    {
                        lic = licControl[enterpriseId];
                    }

                    if (!lic.Valid)
                    {
                        if (!lic.Notified)
                        {
                            db.AddUserLog(LogKey.Licence_error, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], (Int64)dr["enterprise_id"], 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "License error: " + lic.Error);
                        }
                        lic.Notified = true;
                        continue;
                    }


                    if (!(Boolean)dr["deploy_all"])
                    {
                        //Busca os "roles" top
                        String rolesSQL = "select rpr.* from resource_plugin_role rpr with(nolock) inner join resource_plugin rp on rpr.resource_plugin_id = rp.id where rp.resource_id =  " + dr["resource_id"].ToString() + " and rp.plugin_id = " + dr["id"];
                        DebugLog(entityId, "Role SQL = " + rolesSQL);

                        DataTable dtRoles = db.Select(rolesSQL);
                        if (dtRoles == null)
                        {
                            db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : ""));
                            continue;
                        }

                        List <String> roleNames = new List <String>();

                        //Busca toda a arvore de "roles" a se buscar
                        foreach (DataRow drR in dtRoles.Rows)
                        {
                            DataTable dtR = db.Select("select * from dbo.fn_selectRoleTree(" + drR["role_id"] + ")");
                            if (dtR == null)
                            {
                                continue;
                            }

                            foreach (DataRow drRT in dtR.Rows)
                            {
                                if (!roles.Contains((Int64)drRT["role_id"]))
                                {
                                    roleNames.Add(drRT["name"].ToString());
                                    roles.Add((Int64)drRT["role_id"]);
                                }
                            }
                        }

                        if (roles.Count == 0)
                        {
                            db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "Not found roles x identities to deploy");
                            continue;
                        }

                        //Para efeitos de log captura o nome dos roles
                        rolesText = String.Join(", ", roleNames);

                        dtRoles.Clear();
                        dtRoles = null;
                    }

                    //Seleciona todas as entidades do mesmo contexto
                    //Esta listagem considera somente as entidades pertencentes aos plugins de entrada
                    String sql = "select e.id, e.last_login, e.change_password, i.id identity_id from entity e with(nolock) inner join resource r with(nolock) on e.context_id = r.context_id inner join [identity] i with(nolock) on i.entity_id = e.id inner join [resource_plugin] rp with(nolock) on i.resource_plugin_id = rp.id where i.deleted = 0 and e.deleted = 0 {0} and e.context_id = " + dr["context_id"] + (entityId > 0 ? " and e.id = " + entityId : "") + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by e.id, e.last_login, e.change_password, i.id";

                    if (!(Boolean)dr["deploy_all"])
                    {
                        sql = "select e.id, e.last_login, e.change_password, i.id identity_id from entity e with(nolock) inner join resource r with(nolock) on e.context_id = r.context_id inner join [identity] i with(nolock) on i.entity_id = e.id inner join [resource_plugin] rp with(nolock) on i.resource_plugin_id = rp.id inner join identity_role ir with(nolock) on ir.identity_id = i.id  inner join (select rpr.role_id from	resource_plugin_role rpr with(nolock) inner join resource_plugin rp with(nolock) on rp.id = rpr.resource_plugin_id inner join resource r with(nolock) on r.id = rp.resource_id where r.id = "+ dr["resource_id"].ToString() + ") ro on ro.role_id =  ir.role_id where i.deleted = 0 and e.deleted = 0 {0} and ir.role_id in (" + String.Join(",", roles) + ")" + (entityId > 0 ? " and e.id = " + entityId : "") + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) and e.context_id = " + dr["context_id"] + " group by e.id, e.last_login, e.change_password, i.id";
                    }

                    DebugLog(entityId, String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1"));

                    //Lista todas as entidades e identidades para exportar
                    dtEnt = db.Select(String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1"));
                    if (dtEnt == null)
                    {
                        DebugLog(entityId, "SQL result is empty");
                        db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : ""));
                        continue;
                    }

                    if (dtEnt.Rows.Count == 0)
                    {
                        DebugLog(entityId, "SQL result is empty, trying with all plugins");
                        DebugLog(entityId, String.Format(sql, ""));

                        //Lista todas as entidades e identidades para exportar
                        dtEnt = db.Select(String.Format(sql, ""));
                        if (dtEnt == null)
                        {
                            DebugLog(entityId, "SQL result is empty");
                            db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : ""));
                            continue;
                        }
                    }
                    sql = null;


                    if ((dtEnt.Rows.Count == 0) && ((Boolean)dr["deploy_all"]))
                    {
                        DebugLog(entityId, "SQL result is empty with all plugins, trying with only entity data");

                        sql = "select e.id, e.last_login, e.change_password, cast(0 as bigint) identity_id from entity e with(nolock) inner join resource r with(nolock) on e.context_id = r.context_id cross join [resource_plugin] rp with(nolock) where e.deleted = 0 {0} and e.context_id = " + dr["context_id"] + (entityId > 0 ? " and e.id = " + entityId : "") + "  group by e.id, e.last_login, e.change_password";

                        DebugLog(entityId, String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1"));

                        //Lista todas as entidades e identidades para exportar
                        dtEnt = db.Select(String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1"));
                        if (dtEnt == null)
                        {
                            DebugLog(entityId, "SQL result is empty");
                            db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : ""));
                            continue;
                        }
                    }
                    sql = null;

                    DebugLog(entityId, "SQL result count " + dtEnt.Rows.Count);

                    if ((dtEnt.Rows.Count > 0) && (entityId == 0))
                    {
                        deployLog.AppendLine("Starting check to deploy " + dtEnt.Rows.Count + " identities for " + ((!(Boolean)dr["deploy_all"]) ? rolesText : "all users"));
                    }

                    Int32 total        = dtEnt.Rows.Count;
                    Int32 licError     = 0;
                    Int32 loguedIgnore = 0;
                    Int32 deploy       = 0;

                    //db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "Deploy with " + dtEnt.Rows.Count + " identities for " + ((!(Boolean)dr["deploy_all"]) ? rolesText : "all users"));
                    foreach (DataRow drE in dtEnt.Rows)
                    {
                        //Checagens de licenciamento
                        lic.Count++;

                        if ((lic.Entities > 0) && (lic.Count > lic.Entities))
                        {
                            db.AddUserLog(LogKey.Licence_error, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "License error: License limit (" + lic.Entities + " entities) exceeded");
                            licError++;
                            continue;
                        }

                        try
                        {
                            if (((Boolean)dr["deploy_after_login"]) && (drE["last_login"] == DBNull.Value))
                            {
                                db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "User NOT addedd in deploy package because the user is not logged in yet");
                                loguedIgnore++;
                                continue;
                            }

                            //db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "Identity addedd in deploy package");

                            PluginConnectorBaseDeployPackage newPkg = DeployPackage.GetPackage(db, (Int64)dr["proxy_id"], (Int64)dr["resource_plugin_id"], (Int64)drE["id"], (Int64)drE["identity_id"], (Boolean)dr["password_after_login"], (drE["change_password"] == DBNull.Value ? null : (DateTime?)drE["change_password"]), (dr["deploy_password_hash"] == DBNull.Value ? "none" : dr["deploy_password_hash"].ToString()), (Boolean)dr["use_password_salt"], (Boolean)dr["password_salt_end"], dr["password_salt"].ToString());
                            packageList.Add(newPkg);

                            deploy++;

#if DEBUG
                            try
                            {
                                db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Debug, 0, enterpriseId, 0, (Int64)dr["resource_id"], (Int64)dr["id"], newPkg.entityId, newPkg.identityId, "Package generated: " + newPkg.pkgId, SafeTrend.Json.JSON.Serialize <PluginConnectorBaseDeployPackage>(newPkg));
                            }
                            catch { }
#endif

                            packageCount++;
                        }
                        catch (Exception ex)
                        {
                            db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "Erro on deploy user: "******"Total identities: " + total);
                    deployLog.AppendLine("Ignored by licence check: " + licError);
                    deployLog.AppendLine("Ignored by first login rule: " + loguedIgnore);
                    deployLog.AppendLine("Published: " + deploy);

                    db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "Deploy package generated for " + ((!(Boolean)dr["deploy_all"]) ? rolesText : "all users"), deployLog.ToString());
                }

                db.closeDB();
                db.Dispose();
            }
            catch (Exception ex)
            {
                DebugLog(entityId, "Erro on Deploy: " + ex.Message);
                throw ex;
            }
            finally
            {
                deployLog.Clear();
                deployLog = null;

                if (dtPlugins != null)
                {
                    dtPlugins.Clear();
                }
                dtPlugins = null;

                if (dtEnt != null)
                {
                    dtEnt.Clear();
                }
                dtEnt = null;

                if (licControl != null)
                {
                    try
                    {
                        List <Int64> k = new List <Int64>();
                        k.AddRange(licControl.Keys);

                        foreach (Int64 l in k)
                        {
                            if (licControl[l] != null)
                            {
                                licControl[l].Dispose();
                                licControl[l] = null;
                            }
                        }

                        k.Clear();
                    }
                    catch { }
                }
                licControl = null;
            }

            return(packageCount);
        }
Exemplo n.º 16
0
        protected override void OnStart(string[] args)
        {
            /*************
             * Carrega configurações
             */

            System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(this.GetType());
            basePath = Path.GetDirectoryName(asm.Location);

            localConfig = new ServerLocalConfig();
            localConfig.LoadConfig();

            if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null);
            }


            Int32 cnt      = 0;
            Int32 stepWait = 15000;

            while (cnt <= 10)
            {
                try
                {
                    IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                    db.openDB();

                    db.ServiceStart("Report", null);

                    db.closeDB();

                    break;
                }
                catch (Exception ex)
                {
                    if (cnt < 10)
                    {
                        TextLog.Log("Report", "Falha ao acessar o banco de dados: " + ex.Message);
                        Thread.Sleep(stepWait);
                        stepWait = stepWait * 2;
                        cnt++;
                    }
                    else
                    {
                        StopOnError("Falha ao acessar o banco de dados", ex);
                    }
                }
            }


            /*************
             * Inicia timer que processa os arquivos
             */

            reportTimer = new Timer(new TimerCallback(ReportTimer), null, 1000, 60000);
            statusTimer = new Timer(new TimerCallback(TmrServiceStatusCallback), null, 100, 10000);
        }
Exemplo n.º 17
0
        private void WorkflowTimer(Object state)
        {
            if (executing)
            {
                return;
            }

            executing = true;

            startTime = DateTime.Now;

            try
            {
                IAMDatabase db = null;
                try
                {
                    db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                    db.openDB();
                    db.Timeout = 900;

                    DataTable dtRequests = db.ExecuteDataTable("select id, workflow_id from [st_workflow_request] r with(nolock) where r.deployed = 0 order by r.create_date");
                    if ((dtRequests != null) && (dtRequests.Rows.Count > 0))
                    {
                        try
                        {
                            TextLog.Log("WorkflowProcessor", "Starting workflow processor timer");

                            foreach (DataRow dr in dtRequests.Rows)
                            {
                                try
                                {
                                    WorkflowRequest request = new WorkflowRequest((Int64)dr["id"]);
                                    request.GetInicialData(db);

                                    WorkflowConfig workflow = new WorkflowConfig();
                                    workflow.GetDatabaseData(db, (Int64)dr["workflow_id"]);

                                    switch (request.Status)
                                    {
                                    case WorkflowRequestStatus.Deny:
                                    case WorkflowRequestStatus.Expired:
                                    case WorkflowRequestStatus.UserCanceled:
                                        //Somente atualiza como deployed, para não ficar verificando
                                        db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                        continue;
                                        break;

                                    case WorkflowRequestStatus.Waiting:
                                        //Verifica escalation
                                        DateTime escalation = request.ActivityCreated.AddDays(request.Activity.EscalationDays);
                                        DateTime expired    = request.ActivityCreated.AddDays(request.Activity.ExpirationDays);
                                        if (expired.CompareTo(DateTime.Now) < 0)
                                        {
                                            request.SetStatus(db, WorkflowRequestStatus.Escalated, request.UserId);
                                            db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                        }
                                        else if (escalation.CompareTo(DateTime.Now) < 0)
                                        {
                                            request.SetStatus(db, WorkflowRequestStatus.Escalated, request.UserId);
                                            db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                        }
                                        break;

                                    case WorkflowRequestStatus.Escalated:
                                        //Verifica escalation
                                        DateTime expired2 = request.ActivityCreated.AddDays(request.Activity.ExpirationDays);
                                        if (expired2.CompareTo(DateTime.Now) < 0)
                                        {
                                            request.SetStatus(db, WorkflowRequestStatus.Expired, request.UserId);
                                            db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                        }
                                        break;

                                    case WorkflowRequestStatus.Approved:
                                        //Somente executa alguma ação quando não há mais nenhuma atividade a ser executada
                                        if (request.NextActivity == null)
                                        {
                                            switch (workflow.AccessType)
                                            {
                                            case WorkflowAccessType.RoleGrant:
                                                WorkflowAccessRoleGrant rg = (WorkflowAccessRoleGrant)workflow.Access;
                                                //Seleciona todas as identidades do usuário e adiciona na role

                                                DataTable drIdent = db.ExecuteDataTable("select i.* from [identity] i with(nolock) inner join resource_plugin rp with(nolock) on i.resource_plugin_id = rp.id where rp.enable_import = 1 and rp.permit_add_entity = 1 and i.entity_id = " + request.UserId);
                                                if ((drIdent == null) || (drIdent.Rows.Count == 0))
                                                {
                                                    using (DbParameterCollection par2 = new DbParameterCollection())
                                                    {
                                                        par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                        par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                        par2.Add("@description", typeof(String)).Value          = "No inbound identity found for allow access";
                                                        par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                        par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                        db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                    }
                                                }
                                                else
                                                {
                                                    //Lista o nome e id de todas as roles que serão utilizadas
                                                    List <String> roleList = new List <String>();
                                                    foreach (Int64 r in rg.Roles)
                                                    {
                                                        roleList.Add(r.ToString());
                                                    }

                                                    DataTable drRoles = db.ExecuteDataTable("select * from [role] where id in (" + String.Join(",", roleList) + ")");
                                                    if ((drRoles == null) || (drRoles.Rows.Count == 0))
                                                    {
                                                        using (DbParameterCollection par2 = new DbParameterCollection())
                                                        {
                                                            par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                            par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                            par2.Add("@description", typeof(String)).Value          = "No role found for allow access";
                                                            par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                            par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                            db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        String roleNames = "";

                                                        //Adiciona as roles
                                                        foreach (DataRow dr2 in drIdent.Rows)
                                                        {
                                                            foreach (DataRow drRole in drRoles.Rows)
                                                            {
                                                                DbParameterCollection par = new DbParameterCollection();
                                                                par.Add("@identity_id", typeof(Int64)).Value = dr2["id"];
                                                                par.Add("@role_id", typeof(Int64)).Value     = drRole["id"];

                                                                Boolean added = db.ExecuteScalar <Boolean>("sp_insert_identity_role", CommandType.StoredProcedure, par);

                                                                if (added)
                                                                {
                                                                    roleNames += drRole["name"] + Environment.NewLine;
                                                                }
                                                            }
                                                        }

                                                        if (roleNames != null)
                                                        {
                                                            db.AddUserLog(LogKey.User_IdentityRoleBind, null, "Workflow", UserLogLevel.Info, 0, 0, 0, 0, 0, request.UserId, 0, "Entity bind to roles by workflow access request", roleNames);
                                                        }


                                                        using (DbParameterCollection par2 = new DbParameterCollection())
                                                        {
                                                            par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                            par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                            par2.Add("@description", typeof(String)).Value          = "Entity bind to roles";
                                                            par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                            par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                            db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                        }
                                                    }
                                                }

                                                db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                                break;
                                            }
                                        }
                                        break;

                                    case WorkflowRequestStatus.Revoked:
                                        //Remove as permissões dadas
                                        switch (workflow.AccessType)
                                        {
                                        case WorkflowAccessType.RoleGrant:
                                            WorkflowAccessRoleGrant rg = (WorkflowAccessRoleGrant)workflow.Access;

                                            //Lista o nome e id de todas as roles que serão utilizadas
                                            List <String> roleList = new List <String>();
                                            foreach (Int64 r in rg.Roles)
                                            {
                                                roleList.Add(r.ToString());
                                            }

                                            String log = "";

                                            DataTable drRoles = db.ExecuteDataTable("select distinct ir.*, r.name role_name from [role] r with(nolock) inner join identity_role ir with(nolock) on ir.role_id = r.id inner join [identity] i with(nolock) on ir.identity_id = i.id where i.entity_id = " + request.UserId + " and r.id in (" + String.Join(",", roleList) + ")");
                                            if ((drRoles != null) && (drRoles.Rows.Count > 0))
                                            {
                                                foreach (DataRow dr2 in drRoles.Rows)
                                                {
                                                    log += "Identity unbind to role " + dr2["role_name"] + Environment.NewLine;

                                                    db.AddUserLog(LogKey.User_IdentityRoleUnbind, null, "Workflow", UserLogLevel.Info, 0, 0, 0, 0, 0, request.UserId, (Int64)dr2["identity_id"], "Identity unbind to role " + dr2["role_name"]);
                                                    db.ExecuteNonQuery("delete from identity_role where identity_id = " + dr2["identity_id"] + " and role_id = " + dr2["role_id"], CommandType.Text, null);
                                                }

                                                using (DbParameterCollection par2 = new DbParameterCollection())
                                                {
                                                    par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                    par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                    par2.Add("@description", typeof(String)).Value          = log;
                                                    par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                    par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                    db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                }
                                            }
                                            else
                                            {
                                                using (DbParameterCollection par2 = new DbParameterCollection())
                                                {
                                                    par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                    par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                    par2.Add("@description", typeof(String)).Value          = "No permission to remove";
                                                    par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                    par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                    db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                }
                                            }

                                            db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                            break;
                                        }
                                        break;

                                    case WorkflowRequestStatus.UnderReview:
                                        //Nada
                                        break;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    db.AddUserLog(LogKey.Workflow, null, "Workflow", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Workflow proccess error", ex.Message);
                                }
                            }
                        }
                        finally
                        {
                            if (db != null)
                            {
                                db.Dispose();
                            }

                            TextLog.Log("WorkflowProcessor", "Finishing workflow processor timer");
                        }
                    }

                    db.closeDB();
                }
                finally
                {
                    if (db != null)
                    {
                        db.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                TextLog.Log("WorkflowProcessor", "Error on message timer " + ex.Message);
            }
            finally
            {
                executing   = false;
                last_status = "";
                startTime   = new DateTime(1970, 1, 1);
            }
        }
Exemplo n.º 18
0
        private void DeployNowTimer(Object state)
        {
            if (executing2)
            {
                return;
            }

            executing2 = true;


            try
            {
                IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();

                DataTable dtS = db.Select("select entity_id, MAX(date) [date] from deploy_now with(nolock) where date < GETDATE() group by entity_id order by MAX(date)");

                if ((dtS == null) || (dtS.Rows.Count == 0))
                {
                    return;
                }

                TextLog.Log("Dispatcher", "Starting deploy now timer");

                //Processa um a um dos agendamentos
                foreach (DataRow dr in dtS.Rows)
                {
                    try
                    {
                        Int32 count = 0;
                        using (IAMDeploy deploy = new IAMDeploy("Dispatcher", localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword))
                        {
                            count = deploy.DeployOne((Int64)dr["entity_id"]);


                            if (count == 0)
                            {
                                db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Error, 0, 0, 0, 0, 0, (Int64)dr["entity_id"], 0, "Erro on deploy now user: no package sent", deploy.ExecutionLog);
                            }
                        }


                        db.ExecuteNonQuery("delete from deploy_now where entity_id = " + dr["entity_id"], CommandType.Text, null);
                    }
                    catch (Exception ex2) {
                        db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Error, 0, 0, 0, 0, 0, (Int64)dr["entity_id"], 0, "Erro on deploy now user: "******"Dispatcher", "\tError on deploy now timer " + ex.Message + ex.StackTrace);
            }
            finally
            {
                TextLog.Log("Dispatcher", "Finishing deploy now timer");
                executing2 = false;
            }
        }