Пример #1
0
            public async Task CreateReservedSessions()
            {
                var s = ReserveSessionsCount;

                for (var i = 0; i < s; i++)
                {
                    _readonlySessions.Add(await EsentSession.CreateReadOnlySession(MainSession, Waiters));
                }
            }
Пример #2
0
        public IList <IdNode> GetIdNodes()
        {
            IList <IdNode> nodes = new List <IdNode>();

            using (EsentSession session = new EsentSession(_database))
            {
                session.Open();

                JET_SESID   sessionId  = session.GetSessionId();
                JET_DBID    databaseId = session.GetDatabaseId();
                JET_TABLEID tableId;

                if (DatabaseTableExists(sessionId, databaseId, TABLE_DEVICES))
                {
                    Api.OpenTable(sessionId, databaseId, TABLE_DEVICES, OpenTableGrbit.ReadOnly, out tableId);

                    Api.MoveBeforeFirst(session.GetSessionId(), tableId);

                    while (Api.TryMoveNext(sessionId, tableId))
                    {
                        IDictionary <string, JET_COLUMNID> columnDictionary = Api.GetColumnDictionary(sessionId, tableId);

                        IdNode node = new IdNode()
                        {
                            ConfigurationID    = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["ConfigurationID"]),
                            TargetName         = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["TargetName"]),
                            NodeCompliant      = Api.RetrieveColumnAsBoolean(sessionId, tableId, columnDictionary["NodeCompliant"]).GetValueOrDefault(),
                            Dirty              = Api.RetrieveColumnAsBoolean(sessionId, tableId, columnDictionary["Dirty"]).GetValueOrDefault(),
                            LastHeartbeatTime  = Api.RetrieveColumnAsDateTime(sessionId, tableId, columnDictionary["LastHeartbeatTime"]).GetValueOrDefault(),
                            LastComplianceTime = Api.RetrieveColumnAsDateTime(sessionId, tableId, columnDictionary["LastComplianceTime"]).GetValueOrDefault(),
                            StatusCode         = Api.RetrieveColumnAsInt32(sessionId, tableId, columnDictionary["StatusCode"]).GetValueOrDefault(),
                            ServerCheckSum     = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["ServerCheckSum"]),
                            TargetCheckSum     = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["TargetCheckSum"])
                        };

                        nodes.Add(node);
                    }

                    Api.JetCloseTable(sessionId, tableId);
                }
                else
                {
                    _logger.Log(10091, String.Format("Database table {0} not found!", TABLE_DEVICES), LogLevel.Warning);
                }
            }

            return(nodes);
        }
Пример #3
0
        private IEsentSession CreateInstance(SingleThreadDispatcher dispatcher)
        {
            var databasePath = GetEdbFilePath();
            var instance     = DoCreateInstance();

            try
            {
                IEsentSession result;
                if (!File.Exists(databasePath))
                {
                    var session1 = new Session(instance);
                    try
                    {
                        JET_DBID database;

                        Api.JetCreateDatabase(session1, databasePath, null, out database, CreateDatabaseGrbit.None);
                    }
                    finally
                    {
                        session1.Dispose();
                    }
                }
                var session = new Session(instance);
                try
                {
                    JET_DBID database;

                    Api.JetAttachDatabase(session, databasePath, AttachDatabaseGrbit.None);
                    Api.OpenDatabase(session, databasePath, out database, OpenDatabaseGrbit.None);
                    result = new EsentSession(instance, session, database, databasePath, this, dispatcher, false);
                }
                catch
                {
                    session.Dispose();
                    throw;
                }
                return(result);
            }
            catch
            {
                instance.Dispose();
                throw;
            }
        }
Пример #4
0
        public IList <NamesNode> GetNamesNodes()
        {
            IList <NamesNode> nodes = new List <NamesNode>();

            using (EsentSession session = new EsentSession(_database))
            {
                session.Open();

                JET_SESID   sessionId  = session.GetSessionId();
                JET_DBID    databaseId = session.GetDatabaseId();
                JET_TABLEID tableId;

                if (DatabaseTableExists(sessionId, databaseId, TABLE_REGISTRATION_DATA))
                {
                    Api.OpenTable(sessionId, databaseId, TABLE_REGISTRATION_DATA, OpenTableGrbit.ReadOnly, out tableId);

                    Api.MoveBeforeFirst(session.GetSessionId(), tableId);

                    while (Api.TryMoveNext(sessionId, tableId))
                    {
                        IDictionary <string, JET_COLUMNID> columnDictionary = Api.GetColumnDictionary(sessionId, tableId);

                        NamesNode node = new NamesNode()
                        {
                            AgentId            = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["AgentId"]),
                            NodeName           = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["NodeName"]),
                            LCMVersion         = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["LCMVersion"]),
                            IPAddress          = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["IPAddress"]),
                            ConfigurationNames = ((List <string>)Api.DeserializeObjectFromColumn(sessionId, tableId, columnDictionary["ConfigurationNames"]))
                        };

                        nodes.Add(node);
                    }

                    Api.JetCloseTable(sessionId, tableId);
                }
                else
                {
                    _logger.Log(10091, String.Format("Database table {0} not found!", TABLE_REGISTRATION_DATA), LogLevel.Warning);
                }
            }

            return(nodes);
        }
Пример #5
0
        public IList <Report> GetReports()
        {
            List <Report> reportsToReturn   = new List <Report>();
            List <Report> reportsInDatabase = new List <Report>();

            using (EsentSession session = new EsentSession(_database)) {
                session.Open();

                JET_SESID   sessionId  = session.GetSessionId();
                JET_DBID    databaseId = session.GetDatabaseId();
                JET_TABLEID tableId;

                if (DatabaseTableExists(sessionId, databaseId, TABLE_STATUS_REPORT))
                {
                    Api.OpenTable(sessionId, databaseId, TABLE_STATUS_REPORT, OpenTableGrbit.None, out tableId);

                    //Get all columns in the table
                    IDictionary <string, JET_COLUMNID> columnDictionary = Api.GetColumnDictionary(sessionId, tableId);

                    //Create a search index
                    if (Api.GetTableIndexes(sessionId, tableId).Any(index => index.Name == "EndTimeIndex") == false)
                    {
                        var             indexKey       = "+EndTime\0\0";
                        JET_INDEXCREATE startDateIndex = new JET_INDEXCREATE {
                            szKey       = indexKey,
                            cbKey       = indexKey.Length,
                            szIndexName = "EndTimeIndex",
                        };

                        Api.JetCreateIndex2(sessionId, tableId, new JET_INDEXCREATE[] { startDateIndex }, 1);
                    }

                    Api.JetSetCurrentIndex(sessionId, tableId, "EndTimeIndex");

                    //Create search keys.
                    Api.MakeKey(sessionId, tableId, DateTime.Now.AddHours(-2), MakeKeyGrbit.NewKey);

                    if (Api.TrySeek(sessionId, tableId, SeekGrbit.SeekGE))
                    {
                        do
                        {
                            Report reportRow = new Report()
                            {
                                Id                   = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["Id"]),
                                JobId                = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["JobId"]),
                                NodeName             = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["NodeName"]),
                                IPAddress            = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["IPAddress"]),
                                RerfreshMode         = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["RefreshMode"]),
                                OperationType        = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["OperationType"]),
                                Status               = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["Status"]),
                                RebootRequested      = Api.RetrieveColumnAsBoolean(sessionId, tableId, columnDictionary["RebootRequested"]).GetValueOrDefault(),
                                StartTime            = Api.RetrieveColumnAsDateTime(sessionId, tableId, columnDictionary["StartTime"]).GetValueOrDefault(),
                                EndTime              = Api.RetrieveColumnAsDateTime(sessionId, tableId, columnDictionary["EndTime"]).GetValueOrDefault(),
                                LastModifiedTime     = Api.RetrieveColumnAsDateTime(sessionId, tableId, columnDictionary["LastModifiedTime"]).GetValueOrDefault(),
                                LCMVersion           = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["LCMVersion"]),
                                ConfigurationVersion = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["ConfigurationVersion"]),
                                ReportFormatVersion  = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["ReportFormatVersion"]),
                                Errors               = (List <string>)Api.DeserializeObjectFromColumn(sessionId, tableId, columnDictionary["Errors"]),
                            };

                            List <string> statusDataList = (List <string>)Api.DeserializeObjectFromColumn(sessionId, tableId, columnDictionary["StatusData"]);
                            if (statusDataList.Count > 0)
                            {
                                reportRow.StatusData = statusDataList[0];
                            }
                            ;
                            // Field AdditionalData is only available on WS2016 and WMF 5.1
                            if (columnDictionary.Keys.Contains("AdditionalData"))
                            {
                                reportRow.AdditionalData = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["AdditionalData"]);
                            }

                            reportsInDatabase.Add(reportRow);
                        } while (Api.TryMovePrevious(sessionId, tableId));

                        foreach (string node in GetNamesNodes().Select(node => node.NodeName).ToArray())
                        {
                            string NotCompliantResources = string.Empty;
                            string status = string.Empty;

                            Report            latestReportForNode = reportsInDatabase.Where(r => r.NodeName == node).OrderByDescending(r => r.EndTime).First();
                            StatusDataElement dataElement         = JsonConvert.DeserializeObject <StatusDataElement>(latestReportForNode.StatusData);

                            if (dataElement.ResourcesNotInDesiredState?.Count != null)
                            {
                                StringBuilder sb = new StringBuilder();

                                foreach (ResourceState resource in dataElement.ResourcesNotInDesiredState)
                                {
                                    if (sb.Length != 0)
                                    {
                                        sb.Append(';');
                                        sb.Append(resource.ResourceId);
                                    }
                                    else
                                    {
                                        sb.Append(resource.ResourceId);
                                    }
                                }

                                latestReportForNode.NotCompliantResources = sb.ToString();
                            }
                            else
                            {
                                latestReportForNode.NotCompliantResources = string.Empty;
                            }

                            reportsToReturn.Add(latestReportForNode);
                        }
                    }
                    else
                    {
                        Report report = new Report()
                        {
                            Id                   = string.Empty,
                            JobId                = string.Empty,
                            NodeName             = null,
                            IPAddress            = string.Empty,
                            RerfreshMode         = string.Empty,
                            OperationType        = string.Empty,
                            Status               = "No status repot found for the last 2 hours!",
                            RebootRequested      = false,
                            StartTime            = null,
                            EndTime              = null,
                            LastModifiedTime     = null,
                            LCMVersion           = string.Empty,
                            ConfigurationVersion = string.Empty,
                            ReportFormatVersion  = string.Empty,
                            Errors               = new List <string>()
                            {
                                string.Empty
                            },
                            StatusData            = string.Empty,
                            NotCompliantResources = string.Empty
                        };

                        reportsToReturn.Add(report);
                    }
                    Api.JetCloseTable(sessionId, tableId);
                }
                else
                {
                    _logger.Log(10091, String.Format("Database table {0} not found!", TABLE_STATUS_REPORT), LogLevel.Warning);
                }
            }

            return(reportsToReturn.OrderBy(r => r.StartTime).ToList());
        }
Пример #6
0
            public async ValueTask <(IEsentSession session, IDisposable disposable)> GetAvailableSession(bool autoUse)
            {
                async Task <Nothing> DoDisposeExccessSessions()
                {
                    async Task DoDispose(EsentSession s)
                    {
                        try
                        {
                            await s.DisposeInternal();
                        }
                        catch
                        {
                            // Игнорируем ошибки
                        }
                    }

                    List <EsentSession> toDispose = new List <EsentSession>();

                    lock (Waiters.UsingLock)
                    {
                        var allSessions  = _readonlySessions.Count;
                        var freeSessions = _readonlySessions.Where(s => s.UsingsCount == 0).ToArray();
                        if (allSessions > MaxReserveSessionsCount)
                        {
                            toDispose.AddRange(freeSessions.Skip(ReserveSessionsCount));
                        }
                        foreach (var s in toDispose)
                        {
                            _readonlySessions.Remove(s);
                        }
                    }
                    if (toDispose.Count > 0)
                    {
                        var t1 = Task.WhenAll(toDispose.Select(DoDispose));
                        var t2 = Task.Delay(TimeSpan.FromSeconds(15));
                        await Task.WhenAny(t1, t2);
                    }
                    return(Nothing.Value);
                }

                lock (Waiters.UsingLock)
                {
                    var freeSessions = _readonlySessions.Where(s => s.UsingsCount == 0).ToArray();
                    if (freeSessions.Length > 0)
                    {
                        EsentSession r;
                        IDisposable  d = null;
                        if (freeSessions.Length == 1)
                        {
                            r = freeSessions[0];
                        }
                        else
                        {
                            r = freeSessions[_rnd.Next(0, freeSessions.Length)];
                        }
                        if (autoUse)
                        {
                            r.UsingsCount++;
                            d = r.CreateUsageDisposable();
                        }
                        return(r, d);
                    }
                }
                var newSession = await EsentSession.CreateReadOnlySession(MainSession, Waiters);

                IDisposable d2 = null;

                lock (Waiters.UsingLock)
                {
                    _readonlySessions.Add(newSession);
                    if (autoUse)
                    {
                        newSession.UsingsCount++;
                        d2 = newSession.CreateUsageDisposable();
                    }
                }
                CoreTaskHelper.RunUnawaitedTaskAsync(DoDisposeExccessSessions);
                return(newSession, d2);
            }
Пример #7
0
        public IList <Report> GetReports()
        {
            List <Report> reports = new List <Report>();

            using (EsentSession session = new EsentSession(_database))
            {
                session.Open();

                JET_SESID   sessionId  = session.GetSessionId();
                JET_DBID    databaseId = session.GetDatabaseId();
                JET_TABLEID tableId;

                if (DatabaseTableExists(sessionId, databaseId, TABLE_STATUS_REPORT))
                {
                    Api.OpenTable(sessionId, databaseId, TABLE_STATUS_REPORT, OpenTableGrbit.ReadOnly, out tableId);

                    Api.MoveBeforeFirst(session.GetSessionId(), tableId);

                    while (Api.TryMoveNext(sessionId, tableId))
                    {
                        IDictionary <string, JET_COLUMNID> columnDictionary = Api.GetColumnDictionary(sessionId, tableId);

                        Report report = new Report()
                        {
                            Id                   = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["Id"]),
                            JobId                = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["JobId"]),
                            NodeName             = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["NodeName"]),
                            IPAddress            = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["IPAddress"]),
                            RerfreshMode         = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["RefreshMode"]),
                            OperationType        = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["OperationType"]),
                            Status               = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["Status"]),
                            RebootRequested      = Api.RetrieveColumnAsBoolean(sessionId, tableId, columnDictionary["RebootRequested"]).GetValueOrDefault(),
                            StartTime            = Api.RetrieveColumnAsDateTime(sessionId, tableId, columnDictionary["StartTime"]).GetValueOrDefault(),
                            EndTime              = Api.RetrieveColumnAsDateTime(sessionId, tableId, columnDictionary["EndTime"]).GetValueOrDefault(),
                            LastModifiedTime     = Api.RetrieveColumnAsDateTime(sessionId, tableId, columnDictionary["LastModifiedTime"]).GetValueOrDefault(),
                            LCMVersion           = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["LCMVersion"]),
                            ConfigurationVersion = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["ConfigurationVersion"]),
                            ReportFormatVersion  = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["ReportFormatVersion"]),
                            Errors               = (List <string>)Api.DeserializeObjectFromColumn(sessionId, tableId, columnDictionary["Errors"]),
                            StatusData           = (List <string>)Api.DeserializeObjectFromColumn(sessionId, tableId, columnDictionary["StatusData"])
                        };

                        // Field AdditionalData is only available on WS2016 and WMF 5.1
                        if (columnDictionary.Keys.Contains("AdditionalData"))
                        {
                            report.AdditionalData = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["AdditionalData"]);
                        }

                        reports.Add(report);
                    }

                    Api.JetCloseTable(sessionId, tableId);
                }
                else
                {
                    _logger.Log(10091, String.Format("Database table {0} not found!", TABLE_STATUS_REPORT), LogLevel.Warning);
                }
            }

            return(reports.OrderBy(r => r.StartTime).ToList());
        }