Пример #1
0
        public DatabaseData ReloadDatabase(DatabaseData srcDatabase)
        {
            if (!databases.ContainsKey(srcDatabase.Definition.Path))
            {
                throw new ApplicationException("Database to reload don't exist");
            }

            try
            {
                RrdDb        database = new RrdDb(srcDatabase.Definition.Path);
                DatabaseData data     = new DatabaseData();
                data.Saved       = true;
                data.Definition  = database.getRrdDef();
                data.LastUpdated = database.getLastUpdateDateTime();
                data.LastValue   = database.getLastDatasourceValue(database.getDsNames()[0]);
                databases[srcDatabase.Definition.Path] = data;
                database.close();
                return(data);
            }
            catch (Exception ex)
            {
                Logger.Error("Fail to add database", ex);
                throw;
            }
        }
Пример #2
0
		// state variables

		internal DataSource(RrdDb parentDb, DsDef dsDef)
		{
			bool shouldInitialize = dsDef != null;
			this.parentDb = parentDb;
			dsName = new RrdString(this);
			dsType = new RrdString(this);
			heartbeat = new RrdLong(this);
			minValue = new RrdDouble(this);
			maxValue = new RrdDouble(this);
			lastValue = new RrdDouble(this);
			accumValue = new RrdDouble(this);
			nanSeconds = new RrdLong(this);
			if (shouldInitialize)
			{
				dsName.Set(dsDef.Name);
				primitiveDsName = null;
				dsType.Set(dsDef.Type.ToString());
				primitiveDsType = null;
				heartbeat.Set(dsDef.Heartbeat);
				minValue.Set(dsDef.MinValue);
				maxValue.Set(dsDef.MaxValue);
				lastValue.Set(Double.NaN);
				accumValue.Set(0.0);
				Header header = parentDb.Header;
				nanSeconds.Set(header.LastUpdateTime%header.Step);
			}
		}
Пример #3
0
        public DatabaseData SetDatabaseAsEdit(DatabaseData srcDatabaseData)
        {
            if (!databases.ContainsKey(srcDatabaseData.Definition.Path))
            {
                throw new ApplicationException("Database not open in model");
            }

            // Make a clone of the source database definition and give it a new name
            RrdDb rrdDb = new RrdDb(srcDatabaseData.Definition.Path, true);

            databaseDefinition = rrdDb.getRrdDef();
            rrdDb.close();

            DatabaseData dstDatabaseData = new DatabaseData();

            dstDatabaseData.SourceDatabasePath = srcDatabaseData.Definition.Path;
            dstDatabaseData.Saved           = false;
            dstDatabaseData.Definition      = databaseDefinition;
            dstDatabaseData.Definition.Path = Path.GetFileNameWithoutExtension(databaseDefinition.Path) + "_";
            dstDatabaseData.LastUpdated     = dstDatabaseData.Definition.getStartDateTime();
            dstDatabaseData.LastValue       = double.NaN;
            DatabaseDirty       = true;
            EditingDatabaseData = dstDatabaseData;
            databases.Add(dstDatabaseData.Definition.Path, dstDatabaseData);
            return(dstDatabaseData);
        }
Пример #4
0
 public void Release(RrdDb rrdDb)
 {
     if(rrdDb == null)
     {
         // we don't want NullPointerException
         return;
     }
     RrdFile rrdFile = rrdDb.RrdFile;
     if(rrdFile == null)
     {
         throw new RrdException("Cannot release: already closed");
     }
     string path = rrdFile.FilePath;
     string keypath = GetCanonicalPath(path);
     if(rrdMap.ContainsKey(keypath))
     {
         RrdEntry rrdEntry = (RrdEntry) rrdMap[keypath];
         rrdEntry.Release();
         Debug("RELEASED: " + rrdEntry.Dump());
     }
     else
     {
         throw new RrdException("RrdDb with path " + keypath + " not in pool");
     }
     GC();
 }
Пример #5
0
		private void openToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if(theOpenFileDialog.ShowDialog() == DialogResult.OK)
			{
				if(theRRdDb != null)
				{
					theRrdtreeView.Nodes.Clear();
					theRRdDb.Close();
				}
				theRRdDb = RrdDb.Open(theOpenFileDialog.FileName,true);
				TreeNode dataSourceNode = theRrdtreeView.Nodes.Add("DataSources", "Data Sources");
				TreeNode archivesNode = theRrdtreeView.Nodes.Add("Archives", "Archives");
				foreach (var dataSource in theRRdDb.DataSources)
				{
					TreeNode node = new TreeNode(dataSource.Name);
					node.Tag = dataSource;
					dataSourceNode.Nodes.Add(node);
				}
				foreach (var archive in theRRdDb.Archives)
				{
					TreeNode node = new TreeNode();
					node.Tag = archive;
					node.Text = String.Format("{0}-{1}-{2}-{3}", archive.ConsolidationFunction, archive.Xff, archive.Steps,archive.Rows);
					archivesNode.Nodes.Add(node);
				}

			}
		}
Пример #6
0
        public void UpdateDataSource(DatabaseData srcDatabase, DsDef updatedDsDef, DsDef originalDsDef)
        {
            RrdDb database = null;

            try
            {
                database = new RrdDb(srcDatabase.Definition.Path, false);
                Datasource datasource = database.getDatasource(originalDsDef.getDsName());
                if (datasource == null)
                {
                    throw new ArgumentException(updatedDsDef.getDsName() + " datasource don't exist");
                }
                if (datasource.DsName != updatedDsDef.DsName)
                {
                    datasource.setDsName(updatedDsDef.getDsName());
                }
                datasource.setDsType(updatedDsDef.getDsType());
                datasource.setHeartbeat(updatedDsDef.getHeartbeat());
                datasource.setMaxValue(updatedDsDef.getMaxValue(), true);
                datasource.setMinValue(updatedDsDef.getMinValue(), true);
            }
            catch (FileNotFoundException ex)
            {
                Logger.Error("Update datasource failed", ex);
                throw new ApplicationException("Can't update datasource until database saved!", ex);
            }
            finally
            {
                if (database != null)
                {
                    database.close();
                }
            }
        }
Пример #7
0
 internal Header(RrdDb parentDb, RrdDef rrdDef)
 {
     this.parentDb = parentDb;
     signature = new RrdString(SIGNATURE, this);
     step = new RrdLong(rrdDef.Step, this);
     dsCount = new RrdInt(rrdDef.DsCount, this);
     arcCount = new RrdInt(rrdDef.ArcCount, this);
     lastUpdateTime = new RrdLong(rrdDef.StartTime, this);
 }
Пример #8
0
 internal FetchRequest(RrdDb parentDb, string consolFun, long fetchStart, long fetchEnd, long resolution)
 {
     this.parentDb = parentDb;
     this.consolFun = consolFun;
     this.fetchStart = fetchStart;
     this.fetchEnd = fetchEnd;
     this.resolution = resolution;
     Validate();
 }
Пример #9
0
        public RrdDb GetDb()
        {
            const int heartBeat = 5 * 60;             // * 1000

            string _dbPath = Settings.Default.GetAppDataPath() + "xgsnapshots.db";

            try
            {
                var db           = new RrdDb(_dbPath);
                var sourcesToAdd = new HashSet <int>();

                for (int a = 0; a <= 29; a++)
                {
                    if (!db.containsDs(a + ""))
                    {
                        sourcesToAdd.Add(a);
                    }
                }

                if (sourcesToAdd.Count > 0)
                {
                    db.close();
                    foreach (int a in sourcesToAdd)
                    {
                        var dsDef = new DsDef(a + "", DsTypes.DT_GAUGE, heartBeat * 2, 0, Double.MaxValue);
                        RrdToolkit.addDatasource(_dbPath, _dbPath + ".new", dsDef);
                        FileSystem.DeleteFile(_dbPath);
                        FileSystem.MoveFile(_dbPath + ".new", _dbPath);
                    }
                    db = new RrdDb(_dbPath);
                }

                return(db);
            }
            catch (FileNotFoundException)
            {
                var rrdDef = new RrdDef(_dbPath, heartBeat);
                for (int a = 0; a <= 29; a++)
                {
                    rrdDef.addDatasource(a + "", DsTypes.DT_GAUGE, heartBeat * 2, 0, Double.MaxValue);
                }

                rrdDef.addArchive(ConsolFuns.CF_AVERAGE, 0.5, 1, 12 * 24);                 // one day > 1 step = 5 minutes, 12 times per hour * 24 hours
                rrdDef.addArchive(ConsolFuns.CF_AVERAGE, 0.5, 12, 24 * 7);                 // one week > 12 steps = 1 hour, 24 times per day * 7 days
                rrdDef.addArchive(ConsolFuns.CF_AVERAGE, 0.5, 4 * 12, 6 * 31);             // one month > 4 * 12 steps = 4 hours, 6 times per day * 31 days
                rrdDef.addArchive(ConsolFuns.CF_AVERAGE, 0.5, 2 * 24 * 12, 183);           // one year > 2 * 24 * 12 steps = 2 days, 183 days

                try
                {
                    new RrdDb(rrdDef).close();
                }
                catch (NullReferenceException) {}
                return(new RrdDb(_dbPath));
            }
        }
Пример #10
0
        public RrdDb GetDb()
        {
            const int heartBeat = 5 * 60; // * 1000

            string _dbPath = Settings.Default.GetAppDataPath() + "xgsnapshots.db";
            try
            {
                var db = new RrdDb(_dbPath);
                var sourcesToAdd = new HashSet<int>();

                for (int a = 0; a <= 29; a++)
                {
                    if (!db.containsDs(a + ""))
                    {
                        sourcesToAdd.Add(a);
                    }
                }

                if (sourcesToAdd.Count > 0)
                {
                    db.close();
                    foreach (int a in sourcesToAdd)
                    {
                        var dsDef = new DsDef(a + "", DsTypes.DT_GAUGE, heartBeat * 2, 0, Double.MaxValue);
                        RrdToolkit.addDatasource(_dbPath, _dbPath + ".new", dsDef);
                        FileSystem.DeleteFile(_dbPath);
                        FileSystem.MoveFile(_dbPath + ".new", _dbPath);
                    }
                    db = new RrdDb(_dbPath);
                }

                return db;
            }
            catch (FileNotFoundException)
            {
                var rrdDef = new RrdDef(_dbPath, heartBeat);
                for (int a = 0; a <= 29; a++)
                {
                    rrdDef.addDatasource(a + "", DsTypes.DT_GAUGE, heartBeat * 2, 0, Double.MaxValue);
                }

                rrdDef.addArchive(ConsolFuns.CF_AVERAGE, 0.5, 1, 12 * 24); // one day > 1 step = 5 minutes, 12 times per hour * 24 hours
                rrdDef.addArchive(ConsolFuns.CF_AVERAGE, 0.5, 12, 24 * 7); // one week > 12 steps = 1 hour, 24 times per day * 7 days
                rrdDef.addArchive(ConsolFuns.CF_AVERAGE, 0.5, 4 * 12, 6 * 31); // one month > 4 * 12 steps = 4 hours, 6 times per day * 31 days
                rrdDef.addArchive(ConsolFuns.CF_AVERAGE, 0.5, 2 * 24 * 12, 183); // one year > 2 * 24 * 12 steps = 2 days, 183 days

                try
                {
                    new RrdDb(rrdDef).close();
                }
                catch (NullReferenceException) {}
                return new RrdDb(_dbPath);
            }
        }
Пример #11
0
		internal DataSource(RrdDb parentDb, DataImporter reader, int dsIndex) : this(parentDb, null)
		{
			dsName.Set(reader.GetDataSourceName(dsIndex));
			primitiveDsName = null;
			dsType.Set(reader.GetDataSourceType(dsIndex));
			primitiveDsType = null;
			heartbeat.Set(reader.GetDataSourceHeartbeat(dsIndex));
			minValue.Set(reader.GetDataSourceMinValue(dsIndex));
			maxValue.Set(reader.GetDataSourceMaxValue(dsIndex));
			lastValue.Set(reader.GetDataSourceLastValue(dsIndex));
			accumValue.Set(reader.GetDataSourceAccumulatedValue(dsIndex));
			nanSeconds.Set(reader.GetDataSourceNanSeconds(dsIndex));
		}
Пример #12
0
 internal Header(RrdDb parentDb)
 {
     this.parentDb = parentDb;
     signature = new RrdString(this);
     if(!signature.Get().Equals(SIGNATURE))
     {
         throw new RrdException("Not an RRDSharp file");
     }
     step = new RrdLong(this);
     dsCount = new RrdInt(this);
     arcCount = new RrdInt(this);
     lastUpdateTime = new RrdLong(this);
 }
Пример #13
0
		internal Header(RrdDb parentDb, DataImporter reader) : this(parentDb, (RrdDef) null)
		{
			String version = reader.Version;
			int intVersion = int.Parse(version);
			if (intVersion > 3)
			{
				throw new RrdException("Could not unserialize xml version " + version);
			}
			signature.Set(DEFAULT_SIGNATURE);
			step.Set(reader.Step);
			dsCount.Set(reader.DataSourceCount);
			arcCount.Set(reader.ArchiveCount);
			lastUpdateTime.Set(reader.LastUpdateTime);
		}
Пример #14
0
        public void ImportData(string dataPath, DatabaseData databaseData, TimeSpan expectedTick)
        {
            if (model.ReadOnly)
            {
                throw new ApplicationException("Can't import data. Database readonly");
            }


            List <string>      columns     = new List <string>();
            List <FetchedData> unifiedData = ReadAndUnifyData(dataPath, out columns);

            string databasePath = databaseData.Definition.Path;
            RrdDb  database     = new RrdDb(databasePath, false);

            int[] dsIndexes = new int[columns.Count];
            for (int i = 0; i < columns.Count; i++)
            {
                dsIndexes[i] = database.getDsIndex(columns[i]);
            }


            string[] dsNames = database.getDsNames();
            rrd4n.DataAccess.Data.Sample sample = new rrd4n.DataAccess.Data.Sample(databasePath, dsNames, 0);

            foreach (var data in unifiedData)
            {
                sample.setDateTime(data.TimeStamp);
                for (int i = 0; i < data.Values.Count; i++)
                {
                    sample.setValue(dsIndexes[i], data.Values[i]);
                }

                try
                {
                    // When using file access abstraction
                    //dbAccess.StoreData(sample);

                    //Without abstraction
                    database.store(sample);
                    sample.clearValues();
                }
                catch (ArgumentException)
                {
                }
                model.DatabaseDirty = true;
            }
            database.close();
            OpenDatabase(databasePath);
        }
Пример #15
0
            private void UpdateRrdOne(CoCEnum.EventNotify id, stCoCRrdData data, long start)
            {
                string path1Db = CoCRrdUtil.getRrdDbPath(id, this._parent._rootpath);

                if ((string.IsNullOrWhiteSpace(path1Db)) || (!File.Exists(path1Db)))
                {
                    return;
                }
                RrdDb  rrdDb  = new RrdDb(path1Db);
                Sample sample = rrdDb.CreateSample(start);

                sample.SetValue("a", data.a);
                sample.Update();
                rrdDb.Close();
            }
Пример #16
0
 public void addDatasource(String sourcePath, String destPath, DsDef newDatasource)
 {
     if (Util.sameFilePath(sourcePath, destPath))
     {
         throw new RrdException("Source and destination paths are the same");
     }
     RrdDb rrdSource = new RrdDb(sourcePath);
     RrdDef rrdDef = rrdSource.getRrdDef();
     rrdDef.setPath(destPath);
     rrdDef.addDatasource(newDatasource);
     RrdDb rrdDest = new RrdDb(rrdDef);
     rrdSource.copyStateTo(rrdDest);
     rrdSource.close();
     rrdDest.close();
 }
Пример #17
0
        public App()
        {
            Scheduler = new StdSchedulerFactory().GetScheduler();

            _dao           = new Dao();
            _dao.Scheduler = Scheduler;
            LoadObjects();

            FileActions.OnNotificationAdded += NotificationAdded;

            _plugins = new Plugins();
            _rrdDb   = new Rrd().GetDb();

            Objects.CheckAndRemoveDuplicates(Servers);
            ClearOldDownloads();
            TryToRecoverOpenFiles();
        }
Пример #18
0
		internal Header(RrdDb parentDb, RrdDef rrdDef)
		{
			bool shouldInitialize = rrdDef != null;
			this.parentDb = parentDb;
			signature = new RrdString(this); // NOT constant, may NOT be cached
			step = new RrdLong(this, true); // constant, may be cached
			dsCount = new RrdInt(this, true); // constant, may be cached
			arcCount = new RrdInt(this, true); // constant, may be cached
			lastUpdateTime = new RrdLong(this);
			if (shouldInitialize)
			{
				signature.Set(DEFAULT_SIGNATURE);
				step.Set(rrdDef.Step);
				dsCount.Set(rrdDef.DataSourceDefinitions.Length);
				arcCount.Set(rrdDef.ArchiveDefinitions.Length);
				lastUpdateTime.Set(rrdDef.StartTime);
			}
		}
Пример #19
0
        public App()
        {
            Scheduler = new StdSchedulerFactory().GetScheduler();

            _dao = new Dao();
            _dao.Scheduler = Scheduler;
            LoadObjects();

            FileActions.OnNotificationAdded += NotificationAdded;

            _plugins = new Plugins();
            _rrdDb = new Helper.Rrd().GetDb();

            CheckForDuplicates();
            ResetObjects();
            ClearOldDownloads();
            TryToRecoverOpenFiles();
        }
Пример #20
0
        public void StoreData(rrd4n.DataAccess.Data.Sample sample)
        {
            RrdDb rrdDb = null;

            try
            {
                rrdDb = new RrdDb(DataPath + sample.DatabasePath, false);
                Sample coreSample = new Sample(rrdDb.getPath(), rrdDb.getDsNames(), sample.Time);
                coreSample.setValues(sample.Values);
                rrdDb.store(coreSample);
            }
            finally
            {
                if (rrdDb != null)
                {
                    rrdDb.close();
                }
            }
        }
Пример #21
0
        public RemoteFetchData FetchData(string databaseName, long startTimeTick, long endTimeTick, string consolFunctionName, long resolution)
        {
            RrdDb database = null;

            try
            {
                log.DebugFormat("Read data from {0}", databaseName);

                var    nameValueCollection = (NameValueCollection)ConfigurationManager.GetSection("rrdbfileserver");
                string dataBasePath        = nameValueCollection["databasepath"];

                log.DebugFormat("Database path:{0}", dataBasePath + databaseName);
                database = new RrdDb(dataBasePath + databaseName, true);
                FetchRequest fetchRequest = new FetchRequest(null, consolFunctionName, startTimeTick, endTimeTick, resolution);
                FetchData    data         = database.fetchData(fetchRequest);
                database.close();

                RemoteFetchData remoteData = new RemoteFetchData();
                remoteData.Timestamps          = data.getTimestamps();
                remoteData.Values              = data.getValues();
                remoteData.ArchiveEndTimeTicks = data.getArcEndTime();
                remoteData.ArchiveSteps        = data.getArcStep();
                remoteData.DatasourceNames     = data.getDsNames();
                if (debugEnabled)
                {
                    log.DebugFormat("Read data from {0} to {1}.", rrd4n.Common.Util.getDate(startTimeTick), rrd4n.Common.Util.getDate(endTimeTick));
                }
                return(remoteData);
            }
            catch (Exception ex)
            {
                log.Error("Fetchdata exception", ex);
                throw;
            }
            finally
            {
                if (database != null)
                {
                    database.close();
                }
            }
        }
Пример #22
0
        internal ValueExtractor Fetch(RrdDb rrd, long startTime, long endTime)
        {
            long rrdStep = rrd.RrdDef.Step;

            FetchData[] result = new FetchData[datasources.Length];

            string[] names  = new string[numSources];
            int      tblPos = 0;

            for (int i = 0; i < datasources.Length; i++)
            {
                if (datasources[i].Count > 0)
                {
                    // Set the list of ds names
                    string[] dsNames = new string[datasources[i].Count];
                    string[] vNames  = new string[datasources[i].Count];

                    for (int j = 0; j < dsNames.Length; j++)
                    {
                        string[] spair = (string[])datasources[i][j];
                        dsNames[j] = spair[0];
                        vNames[j]  = spair[1];
                    }

                    // Fetch datasources
                    FetchRequest request = rrd.CreateFetchRequest(cfNames[i], startTime, endTime + rrdStep);
                    request.SetFilter(dsNames);

                    FetchData data = request.FetchData();

                    for (int j = 0; j < vNames.Length; j++)
                    {
                        names[data.GetDsIndex(dsNames[j]) + tblPos] = vNames[j];
                    }
                    tblPos += dsNames.Length;

                    result[i] = data;
                }
            }

            return(new ValueExtractor(names, result));
        }
Пример #23
0
        public void StoreData(string databaseName, long timeStamp, double[] newValues)
        {
            RrdDb database = null;

            try
            {
                database = new RrdDb(databaseName, false);
                database.store(timeStamp, newValues);
            }
            catch (Exception ex)
            {
                log.Error("Store data exception", ex);
                throw;
            }
            finally
            {
                if (database != null)
                {
                    database.close();
                }
            }
        }
Пример #24
0
        public void CreateDatabase(string databasePath)
        {
            if (model.EditingDatabaseData == null)
            {
                throw new ApplicationException("Not in edit mode");
            }

            string oldpath     = model.EditingDatabaseData.Definition.Path;
            RrdDb  srcDatabase = null;

            if (!string.IsNullOrEmpty(model.EditingDatabaseData.SourceDatabasePath))
            {
                srcDatabase = new RrdDb(model.EditingDatabaseData.SourceDatabasePath);
            }
            RrdDef rrdDef = model.EditingDatabaseData.Definition;

            rrdDef.setPath(databasePath);
            RrdDb dstDatabase = new RrdDb(rrdDef);

            if (srcDatabase != null)
            {
                srcDatabase.copyStateTo(dstDatabase);
            }

            if (srcDatabase != null)
            {
                srcDatabase.close();
            }
            dstDatabase.close();
            model.DatabaseDirty       = false;
            model.EditingDatabaseData = null;
            DatabaseData databaseData = model.AddDatabase(databasePath);

            rrdDbForm.SetDatabaseDefinition(databaseData);

            TreeForm.RemoveDatabaseDefinition(oldpath);
            TreeForm.SetDatabaseDefinition(databaseData);
            TreeForm.SetEditMode(false);
        }
Пример #25
0
        public rrd4n.DataAccess.Data.FetchData GetData(rrd4n.DataAccess.Data.FetchRequest request)
        {
            RrdDb rrdDb = null;

            try
            {
                string dataPath;
                if (DataPath.Contains("${APPDATA}"))
                {
                    dataPath  = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    dataPath += DataPath.Substring(10);
                }
                else
                {
                    dataPath = DataPath;
                }


                rrdDb = new RrdDb(dataPath + request.DatabasePath);
                FetchRequest coreRequest   = new FetchRequest(rrdDb.getPath(), request.ConsolidateFunctionName, request.FetchStart, request.FetchEnd, request.Resolution);
                FetchData    coreFetchData = rrdDb.fetchData(coreRequest);

                return(new rrd4n.DataAccess.Data.FetchData(coreFetchData.getArcStep(), coreFetchData.getArcEndTime(), coreFetchData.getDsNames())
                {
                    Values = coreFetchData.getValues(),
                    Timestamps = coreFetchData.getTimestamps()
                });
            }
            finally
            {
                if (rrdDb != null)
                {
                    rrdDb.close();
                }
            }
        }
Пример #26
0
 public DatabaseData AddDatabase(string databasePath)
 {
     if (databases.ContainsKey(databasePath))
     {
         return(databases[databasePath]);
     }
     try
     {
         RrdDb        database = new RrdDb(databasePath);
         DatabaseData data     = new DatabaseData();
         data.Saved       = true;
         data.Definition  = database.getRrdDef();
         data.LastUpdated = database.getLastUpdateDateTime();
         data.LastValue   = database.getLastDatasourceValue(database.getDsNames()[0]);
         databases.Add(databasePath, data);
         database.close();
         return(databases[databasePath]);
     }
     catch (Exception ex)
     {
         Logger.Error("Fail to add database", ex);
         throw;
     }
 }
Пример #27
0
        public FetchData GetArchiveData(DatabaseData databaseData, string dataSourceName, ArcDef archiveDefinition)
        {
            RrdDb database = null;

            try
            {
                database = new RrdDb(databaseData.Definition.getPath(), true);
                int      datasourceIndex  = database.getDsIndex(dataSourceName);
                Archive  archive          = database.getArchive(new ConsolFun(archiveDefinition.getConsolFun().Name), archiveDefinition.Steps);
                Robin    robin            = archive.getRobin(datasourceIndex);
                double[] values           = robin.getValues();
                DateTime archiveStartTime = archive.getStartDateTime();
                TimeSpan tick             = new TimeSpan(archive.getArcStep() * TimeSpan.TicksPerSecond);

                FetchData fetchedData = new FetchData(archive.getArcStep(), archive.getEndTime(), new string[] { dataSourceName });
                long[]    timestamps  = new long[archive.getRows()];
                long      offset      = archive.getStartTime();
                for (var i = 0; i < archive.getRows(); i++)
                {
                    timestamps[i] = offset;
                    offset       += archive.getArcStep();
                }
                fetchedData.setTimestamps(timestamps);
                double[][] value = new double[1][];
                value[0] = values;
                fetchedData.setValues(value);
                return(fetchedData);
            }
            finally
            {
                if (database != null)
                {
                    database.close();
                }
            }
        }
Пример #28
0
 private void Add(string keypath, RrdDb rrdDb)
 {
     RrdEntry newEntry = new RrdEntry(rrdDb);
     Debug("NEW: " + newEntry.Dump());
     rrdMap.Add(keypath, newEntry);
     GC();
 }
Пример #29
0
 public RrdDb RequestRrdDb(RrdDef rrdDef)
 {
     string path = rrdDef.Path;
     string keypath = GetCanonicalPath(path);
     ValidateInactive(keypath);
     RrdDb rrdDb = new RrdDb(rrdDef);
     Put(keypath, rrdDb);
     return rrdDb;
 }
Пример #30
0
 public RrdDb RequestRrdDb(string path)
 {
     lock(this)
     {
         string keypath = GetCanonicalPath(path);
         if(rrdMap.ContainsKey(keypath))
         {
             // already open
             RrdEntry rrdEntry = (RrdEntry) rrdMap[keypath];
             rrdEntry.ReportUsage();
             Debug("EXISTING: " + rrdEntry.Dump());
             return rrdEntry.RrdDb;
         }
         else
         {
             // not found, open it
             RrdDb rrdDb = new RrdDb(path);
             Put(keypath, rrdDb);
             return rrdDb;
         }
     }
 }
Пример #31
0
        public void resizeArchive(String sourcePath, String destPath, String consolFun,
			int numSteps, int newRows)
        {
            if (Util.sameFilePath(sourcePath, destPath))
            {
                throw new RrdException("Source and destination paths are the same");
            }
            if (newRows < 2)
            {
                throw new RrdException("New arcihve size must be at least 2");
            }
            RrdDb rrdSource = new RrdDb(sourcePath);
            RrdDef rrdDef = rrdSource.getRrdDef();
            ArcDef arcDef = rrdDef.findArchive(consolFun, numSteps);
            if (arcDef.getRows() != newRows)
            {
                arcDef.setRows(newRows);
                rrdDef.setPath(destPath);
                RrdDb rrdDest = new RrdDb(rrdDef);
                rrdSource.copyStateTo(rrdDest);
                rrdDest.close();
            }
            rrdSource.close();
        }
Пример #32
0
        internal ValueExtractor Fetch( RrdDb rrd, long startTime, long endTime )
        {
            long rrdStep			= rrd.RrdDef.Step;
            FetchData[] result		= new FetchData[datasources.Length];

            string[] names 			= new string[numSources];
            int tblPos		= 0;

            for (int i = 0; i < datasources.Length; i++)
            {
                if ( datasources[i].Count > 0 )
                {
                    // Set the list of ds names
                    string[] dsNames 	= new string[ datasources[i].Count ];
                    string[] vNames		= new string[ datasources[i].Count ];

                    for (int j = 0; j < dsNames.Length; j++ )
                    {
                        string[] spair	= (string[]) datasources[i][j];
                        dsNames[j]	 	= spair[0];
                        vNames[j]		= spair[1];
                    }

                    // Fetch datasources
                    FetchRequest request 		= rrd.CreateFetchRequest( cfNames[i], startTime, endTime + rrdStep);
                    request.SetFilter(dsNames);

                    FetchData data				= request.FetchData();

                    for (int j = 0; j < vNames.Length; j++)
                        names[ data.GetDsIndex(dsNames[j]) + tblPos ] = vNames[j];
                    tblPos				+= dsNames.Length;

                    result[i]					= data;
                }
            }

            return new ValueExtractor( names, result );
        }
Пример #33
0
        public void StressTest()
        {
            string RRD_PATH = "stress.rrd";
            long RRD_START = 946710000L;
            long RRD_STEP = 30;
            string RRD_DATASOURCE_NAME = "T";
            int RRD_DATASOURCE_COUNT = 6;
            long TIME_START = 1060142010L;
            long TIME_END = 1080013472L;
            string PNG_PATH = "stress.png";
            int PNG_WIDTH = 400;
            int PNG_HEIGHT = 250;

            //Stress test
            DateTime testBegin = DateTime.UtcNow;
            printLapTime("Beginning Stress Test at " + testBegin.ToString());
            // create RRD database
            printLapTime("Creating RRD definition");
            RrdDef def = new RrdDef(RRD_PATH);
            def.StartTime = RRD_START;
            def.Step = RRD_STEP;
            for(int i = 0; i < RRD_DATASOURCE_COUNT; i++)
            {
                def.AddDatasource(RRD_DATASOURCE_NAME + i, "GAUGE", 90, -60, 85);
            }
            def.AddArchive("LAST", 0.5, 1, 5760);
            def.AddArchive("MIN", 0.5, 1, 5760);
            def.AddArchive("MAX", 0.5, 1, 5760);
            def.AddArchive("AVERAGE", 0.5, 5, 13824);
            def.AddArchive("MIN", 0.5, 5, 13824);
            def.AddArchive("MAX", 0.5, 5, 13824);
            def.AddArchive("AVERAGE", 0.5, 60, 16704);
            def.AddArchive("MIN", 0.5, 60, 16704);
            def.AddArchive("MAX", 0.5, 60, 16704);
            def.AddArchive("AVERAGE", 0.5, 1440, 50000);
            def.AddArchive("MIN", 0.5, 1440, 50000);
            def.AddArchive("MAX", 0.5, 1440, 50000);
            printLapTime("Definition created, creating RRD file");

            RrdDb rrd = new RrdDb(def);
            printLapTime("RRD file created: " + RRD_PATH);

            FileStream fs = File.OpenRead("stress-test.txt");
            byte[] memBuffer = new byte[fs.Length];
            fs.Read(memBuffer, 0, memBuffer.Length);
            fs.Close();
            StreamReader memoryReader = new StreamReader(new MemoryStream(memBuffer));

            //StreamReader diskReader = File.OpenText("stress-test.txt");
            //string allLines = diskReader.ReadToEnd();
            //diskReader.Close();
            //StringReader memoryReader = new StringReader(allLines);

            //StreamReader memoryReader = File.OpenText("stress-test.txt");

            printLapTime("Input data loaded into memory, processing data");

            int count = 0;
            DateTime updateStart = DateTime.UtcNow;
            string line;

            while ((line = memoryReader.ReadLine()) != null)
            {
                Sample sample = rrd.CreateSample();
                try
                {
                    sample.SetAndUpdate(line);
                    if(++count % 1000 == 0)
                    {
                        DateTime now = DateTime.UtcNow;
                        long speed = (long)(count * 1000.0 / (Util.TicksToMillis(now.Ticks) - Util.TicksToMillis(updateStart.Ticks)));
                        printLapTime(count + " samples stored, " + speed + " updates/sec");
                    }
                }
                catch(RrdException)
                {
                    printLapTime("RRD ERROR: " + line);
                }
            }
            memoryReader.Close();
            rrd.Close();

            printLapTime("FINISHED: " + count + " samples stored");

            // GRAPH
            printLapTime("Creating composite graph definition");
            RrdGraphDef gdef = new RrdGraphDef(TIME_START, TIME_END);
            gdef.Title = "Temperatures";
            gdef.VerticalLabel = "Fahrenheit";
            Color [] colors =  {Color.Red, Color.Lime, Color.Blue, Color.Magenta,Color.Cyan, Color.Orange };
            // datasources
            for(int i = 0; i < RRD_DATASOURCE_COUNT; i++)
            {
                string name = RRD_DATASOURCE_NAME + i;
                gdef.Datasource(name, RRD_PATH, name, "AVERAGE");
            }
            // lines
            for(int i = 0; i < RRD_DATASOURCE_COUNT; i++)
            {
                string name = RRD_DATASOURCE_NAME + i;
                gdef.Line(name, colors[i], name);
            }
            gdef.Comment("@c");
            gdef.Comment("\nOriginal data provided by diy-zoning.sf.net@c");
            printLapTime("Graph definition created");
            RrdGraph g = new RrdGraph(gdef);
            g.SaveAsPNG(PNG_PATH, PNG_WIDTH, PNG_HEIGHT);
            printLapTime("Graph saved: " + PNG_PATH);
            DateTime testEnd = DateTime.UtcNow;
            printLapTime("Finished at " + testEnd.ToString());
            Console.WriteLine("Total Time: " + testEnd.Subtract(testBegin).ToString());
        }
Пример #34
0
        public void Test1()
        {
            Console.WriteLine("Beginning Test1...");
            RrdDef rrdDef = new RrdDef("test1.rrd");
            rrdDef.StartTime = 978300900L;
            rrdDef.AddDatasource("a", "COUNTER", 600, Double.NaN, Double.NaN);
            rrdDef.AddDatasource("b", "GAUGE", 600, Double.NaN, Double.NaN);
            rrdDef.AddDatasource("c", "DERIVE", 600, Double.NaN, Double.NaN);
            rrdDef.AddDatasource("d", "ABSOLUTE", 600, Double.NaN, Double.NaN);
            rrdDef.AddArchive("AVERAGE", 0.5, 1, 10);
            RrdDb rrdDb = new RrdDb(rrdDef);
            Sample sample = rrdDb.CreateSample();
            sample.SetAndUpdate("978301200:300:1:600:300");
            sample.SetAndUpdate("978301500:600:3:1200:600");
            sample.SetAndUpdate("978301800:900:5:1800:900");
            sample.SetAndUpdate("978302100:1200:3:2400:1200");
            sample.SetAndUpdate("978302400:1500:1:2400:1500");
            sample.SetAndUpdate("978302700:1800:2:1800:1800");
            sample.SetAndUpdate("978303000:2100:4:0:2100");
            sample.SetAndUpdate("978303300:2400:6:600:2400");
            sample.SetAndUpdate("978303600:2700:4:600:2700");
            sample.SetAndUpdate("978303900:3000:2:1200:3000");
            rrdDb.Close();

            RrdGraphDef graphDef = new RrdGraphDef();
            graphDef.SetTimePeriod(978300600L, 978304200L);
            graphDef.Title = "This is a cool title";
            graphDef.VerticalLabel = "Vertical Label";
            graphDef.Datasource("linea", "test1.rrd", "a", "AVERAGE");
            graphDef.Datasource("lineb", "test1.rrd", "b", "AVERAGE");
            graphDef.Datasource("linec", "test1.rrd", "c", "AVERAGE");
            graphDef.Datasource("lined", "test1.rrd", "d", "AVERAGE");
            graphDef.Line("linea", Color.Red,  "Line A", 3);
            graphDef.Line("lineb", Color.Lime,  "Line B", 3);
            graphDef.Line("linec", Color.Blue,  "Line C", 3);
            graphDef.Line("lined", Color.Cyan,  "Line D", 3);
            RrdGraph graph = new RrdGraph(graphDef);
            graph.SaveAsPNG("test1.png", 400, 400);
            Console.WriteLine("Test1 Complete.");
        }
Пример #35
0
            private void CreateOne(CoCEnum.EventNotify id)
            {
                string path = CoCRrdUtil.getRrdDbPath(id, this._parent._rootpath);

                if ((string.IsNullOrWhiteSpace(path)) || (File.Exists(path)))
                {
                    return;
                }
                stCoCRrdData data = this._data.Where(o => (o.Key == id)).Select(o =>
                {
                    return((stCoCRrdData)o.Value);
                }).FirstOrDefault();

                if (data == null)
                {
                    return;
                }

                RrdDef rrdDef = null;
                RrdDb  rrdDb  = null;

                try
                {
                    rrdDef           = new RrdDef(path);
                    rrdDef.StartTime = this._startTime;
                    rrdDef.Step      = (this._periodTime * 60);

                    rrdDef.AddDatasource("a", data.type, (rrdDef.Step * 2), Double.NaN, Double.NaN);

                    rrdDef.AddArchive("AVERAGE", 0, 1, 1);
                    rrdDef.AddArchive("AVERAGE", 0, 1, RrdPeriod.Week(this._periodTime));
                    rrdDef.AddArchive("AVERAGE", 0, 1, RrdPeriod.Month(this._periodTime));
                    rrdDef.AddArchive("AVERAGE", 0, 1, RrdPeriod.Year(this._periodTime));

                    rrdDef.AddArchive("MIN", 0, 1, RrdPeriod.Day(this._periodTime));
                    rrdDef.AddArchive("MIN", 0, 1, RrdPeriod.Week(this._periodTime));
                    rrdDef.AddArchive("MIN", 0, 1, RrdPeriod.Month(this._periodTime));
                    rrdDef.AddArchive("MIN", 0, 1, RrdPeriod.Year(this._periodTime));

                    rrdDef.AddArchive("MAX", 0, 1, RrdPeriod.Day(this._periodTime));
                    rrdDef.AddArchive("MAX", 0, 1, RrdPeriod.Week(this._periodTime));
                    rrdDef.AddArchive("MAX", 0, 1, RrdPeriod.Month(this._periodTime));
                    rrdDef.AddArchive("MAX", 0, 1, RrdPeriod.Year(this._periodTime));

                    rrdDb = new RrdDb(rrdDef);
                }
                catch (Exception e)
                {
                    if (this._parent.isLogEnable)
                    {
                        this._parent._ilog.LogError(e.Message);
                    }
                }
                finally
                {
                    if (rrdDb != null)
                    {
                        rrdDb.Close();
                    }
                }
            }
Пример #36
0
        static void Main(string[] args)
        {
            DateTime EPOC = new DateTime(1970, 01, 1);
            long     startTimeInSeconds = 920804400;
            DateTime startTime          = EPOC.AddSeconds(startTimeInSeconds);
            long     endTimeInSeconds   = 920808000;
            string   rrdPath            = @"net_test.rrd";
            String   imgPath            = @"net_test.png";

            Console.WriteLine("== Starting demo");

            RrdDb        rrdDb;
            FetchRequest request;
            FetchData    fetchData;


            //List<FetchedData> unified = ReadAndUnifyData(@"C:\Development\CS_Project\rrd4n\RrDbTest\el.csv",
            //                                             new TimeSpan(0, 10, 0));

            bool createDb = true;

            if (createDb)
            {
                rrdDb = BuildRRd(rrdPath, startTime);
                Console.WriteLine(rrdDb.dump());
                rrdDb.close();
                //rrdDb = new RrdDb(rrdPath, false);

                int[] values = new int[] {
                    12345, 12357, 12363, 12363, 12363, 12373, 12383, 12393, 12399, 12405, 12411, 12415, 12420, 12422, 12423
                };

                //rrdtool update net_test.rrd 920804700:12345 920805000:12357 920805300:12363
                //rrdtool update net_test.rrd 920805600:12363 920805900:12363 920806200:12373
                //rrdtool update net_test.rrd 920806500:12383 920806800:12393 920807100:12399
                //rrdtool update net_test.rrd 920807400:12405 920807700:12411 920808000:12415
                //rrdtool update net_test.rrd 920808300:12420 920808600:12422 920808900:12423

                for (int i = 0; i < 15; i++)
                {
                    UpdateRRd(rrdPath, 920804700 + (i * 300), "speed", values[i]);
                }
                //rrdDb.close();

                // Read back test
                rrdDb = new RrdDb(rrdPath, true);
                Console.WriteLine("File reopen in read-only mode");
                Console.WriteLine("== Last update time was: " + rrdDb.getLastUpdateTime());
                Console.WriteLine("== Last info was: " + rrdDb.getInfo());

                // fetch data
                Console.WriteLine("== Fetching data");
                request = rrdDb.createFetchRequest(new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), startTimeInSeconds, endTimeInSeconds);
                Console.WriteLine(request.dump());
                fetchData = rrdDb.fetchData(request);
                Console.WriteLine("== Data fetched. " + fetchData.getRowCount() + " points obtained");
                Console.WriteLine(fetchData.toString());
                Console.WriteLine("== Fetch completed");
            }


            DateTime startDateTime = rrd4n.Common.Util.getDate(920804400);
            DateTime endDateTime   = rrd4n.Common.Util.getDate(920808000);

            GraphParser parser = new GraphParser("net_speed_1.png --start \"" + startDateTime.ToString() + "\" --end \"" + endDateTime.ToString() + "\" --imgformat PNG DEF:myspeed=" + rrdPath + ":speed:AVERAGE LINE2:myspeed#FF0000");
            RrdGraphDef gDef_1 = parser.CreateGraphDef();

            RrdDbAccessInterface rrdDbAccess = container["databaseaccessor.local"] as RrdDbAccessInterface;
            RrdGraph             graph_1     = new RrdGraph(gDef_1, rrdDbAccess);

            // Create graph
            // rrdtool graph net_speed.png --start 920804400 --end 920808000
            //  DEF:myspeed=net_test.rrd:speed:AVERAGE
            //  LINE2:myspeed#FF0000
            //  --font "DEFAULT:0:C:\Windows\fonts\cour.ttf"
            Console.WriteLine("Creating graph ");
            RrdGraphDef gDef = new RrdGraphDef();

            gDef.setWidth(IMG_WIDTH);
            gDef.setHeight(IMG_HEIGHT);
            gDef.setFilename(imgPath);
            gDef.setStartTime(startTimeInSeconds);
            gDef.setEndTime(endTimeInSeconds);
            gDef.setTitle("Speed");
            //            gDef.setVerticalLabel("temperature");
            gDef.datasource("myspeed", rrdPath, "speed", new rrd4n.Common.ConsolFun(rrd4n.Common.ConsolFun.ConsolFunTypes.AVERAGE));
            gDef.line("myspeed", Color.Red, "My sPeedj", 2);
            gDef.hrule(0.02, Color.Red, "Maximum 200", 3);

            //            gDef.print("shade", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), "avgShade = %.3f%S\\r");
            //            gDef.setImageInfo("<img src='%s' width='%d' height = '%d'>");
            gDef.setPoolUsed(false);
            gDef.setImageFormat("png");
            //Console.WriteLine("Rendering graph " + rrd4n.Common.Util.getLapTime());
            // create graph finally
            RrdGraph graph = new RrdGraph(gDef, rrdDbAccess);

            // Create bar chart test graph
            //rrdtool graph speed3.png --start 920804400 --end 920808000 --vertical-label km/h DEF:myspeed=test.rrd:speed:AVERAGE "CDEF:kmh=myspeed,3600,*" CDEF:fast=kmh,100,GT,kmh,0,IF CDEF:good=kmh,100,GT,0,kmh,IF HRULE:100#0000FF:"Maximum allowed" AREA:good#00FF00:"Good speed" AREA:fast#FF0000:"Too fast" --font "DEFAULT:0:C:\Windows\fonts\cour.ttf"
            imgPath = @"net_test_bar.png";

            Console.WriteLine("Creating bar graph ");
            gDef = new RrdGraphDef();
            gDef.setWidth(IMG_WIDTH);
            gDef.setHeight(IMG_HEIGHT);
            gDef.setFilename(imgPath);
            gDef.setStartTime(startTimeInSeconds);
            gDef.setEndTime(endTimeInSeconds + 900);
            gDef.setTitle("Speed");
            gDef.setVerticalLabel("km/h");
            //DEF:myspeed=test.rrd:speed:AVERAGE
            gDef.datasource("myspeed", rrdPath, "speed", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE));
            //"CDEF:kmh=myspeed,3600,*"
            gDef.datasource("kmh", "myspeed,3600,*");
            //CDEF:fast=kmh,100,GT,kmh,0,IF
            gDef.datasource("fast", "kmh,100,GT,kmh,0,IF");
            //CDEF:good=kmh,100,GT,0,kmh,IF HRULE:100#0000FF:"Maximum allowed" AREA:good#00FF00:"Good speed" AREA:fast#FF0000:"Too fast"
            gDef.datasource("good", "kmh,100,GT,0,kmh,IF");
            //HRULE:100#0000FF:"Maximum allowed"
            gDef.hrule(100, Color.Red, "Maximum allowed", 3);
            gDef.hrule(200, Color.Red, "Maximum 200", 3);
            // AREA:good#00FF00:"Good speed"
            gDef.area("good", Color.Green, "Good speed");
            // AREA:fast#FF0000:"Too fast"
            gDef.area("fast", Color.Red, "Too fast");
            gDef.setPoolUsed(false);
            gDef.setImageFormat("png");
            //Console.WriteLine("Rendering graph " + Util.getLapTime());
            // create graph finally
            graph = new RrdGraph(gDef, rrdDbAccess);

            //rrdtool graph speed4.png --start 920804400 --end 920808000 --vertical-label km/h DEF:myspeed=test.rrd:speed:AVERAGE CDEF:nonans=myspeed,UN,0,myspeed,IF CDEF:kmh=nonans,3600,* CDEF:fast=kmh,100,GT,100,0,IF CDEF:over=kmh,100,GT,kmh,100,-,0,IF CDEF:good=kmh,100,GT,0,kmh,IF HRULE:100#0000FF:"Maximum allowed" AREA:good#00FF00:"Good speed" AREA:fast#550000:"Too fast"  STACK:over#FF0000:"Over speed" --font "DEFAULT:0:C:\Windows\fonts\cour.ttf"
            Console.WriteLine("Creating stack graph ");
            imgPath = @"net_test_stack.png";
            gDef    = new RrdGraphDef();
            gDef.setWidth(IMG_WIDTH);
            gDef.setHeight(IMG_HEIGHT);
            gDef.setFilename(imgPath);
            gDef.setStartTime(startTimeInSeconds + 300);
            gDef.setEndTime(endTimeInSeconds + 1200);
            gDef.setTitle("Speed");
            //--vertical-label km/h
            gDef.setVerticalLabel("km/h");
            // DEF:myspeed=test.rrd:speed:AVERAGE
            gDef.datasource("myspeed", rrdPath, "speed", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE));
            // CDEF:nonans=myspeed,UN,0,myspeed,IF
            gDef.datasource("nonans", "myspeed,UN,0,myspeed,IF");
            //CDEF:kmh=nonans,3600,*
            gDef.datasource("kmh", "nonans,3600,*");
            //CDEF:fast=kmh,100,GT,100,0,IF
            gDef.datasource("fast", "kmh,100,GT,100,0,IF");
            //CDEF:over=kmh,100,GT,kmh,100,-,0,IF
            gDef.datasource("over", "kmh,100,GT,kmh,100,-,0,IF");
            //CDEF:good=kmh,100,GT,0,kmh,IF
            gDef.datasource("good", "kmh,100,GT,0,kmh,IF");
            //HRULE:100#0000FF:"Maximum allowed"
            gDef.hrule(100, Color.Blue, "Maximum allowed", 3);
            // AREA:good#00FF00:"Good speed"
            gDef.area("good", Color.Green, "Good speed");
            // AREA:fast#550000:"Too fast"
            gDef.area("fast", Color.Black, "Too fast");
            //STACK:over#FF0000:"Over speed"
            gDef.stack("over", Color.Red, "Over speed");

            gDef.setPoolUsed(false);
            gDef.setImageFormat("png");
            //Console.WriteLine("Rendering graph " + Util.getLapTime());
            // create graph finally
            graph = new RrdGraph(gDef, rrdDbAccess);



            long startMillis = DateTime.Now.Millisecond;

            return;
            //if (args.Length > 0)
            //{
            //   Console.WriteLine("Setting default backend factory to " + args[0]);
            //   RrdDb.setDefaultFactory(args[0]);
            //}
            //long start = START;
            //long end = END;
            ////rrdPath = Util.getRrd4nDemoPath(FILE + ".rrd");
            ////String xmlPath = Util.getRrd4nDemoPath(FILE + ".xml");
            ////String rrdRestoredPath = Util.getRrd4nDemoPath(FILE + "_restored.rrd");
            ////imgPath = Util.getRrd4nDemoPath(FILE + ".png");
            ////String logPath = Util.getRrd4nDemoPath(FILE + ".log");
            ////PrintWriter log = new PrintWriter(new BufferedOutputStream(new FileOutputStream(logPath, false)));
            //// creation
            ////Console.WriteLine("== Creating RRD file " + rrdPath);
            ////RrdDef rrdDef = new RrdDef(rrdPath, start - 1, 300);
            ////rrdDef.addDatasource("sun", new DsType(DsType.DsTypes.GAUGE), 600, 0, Double.NaN);
            ////rrdDef.addDatasource("shade", new DsType(DsType.DsTypes.GAUGE), 600, 0, Double.NaN);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), 0.5, 1, 600);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), 0.5, 6, 700);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), 0.5, 24, 775);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), 0.5, 288, 797);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.MAX), 0.5, 1, 600);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.MAX), 0.5, 6, 700);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.MAX), 0.5, 24, 775);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.MAX), 0.5, 288, 797);
            ////Console.WriteLine(rrdDef.dump());
            //////log.Console.WriteLine(rrdDef.dump());
            ////Console.WriteLine("Estimated file size: " + rrdDef.getEstimatedSize());
            ////RrdDb rrdDb = new RrdDb(rrdDef);
            ////Console.WriteLine("== RRD file created.");
            ////if (rrdDb.getRrdDef().equals(rrdDef))
            ////{
            ////    Console.WriteLine("Checking RRD file structure... OK");
            ////}
            ////else
            ////{
            ////    Console.WriteLine("Invalid RRD file created. This is a serious bug, bailing out");
            ////    return;
            ////}
            ////rrdDb.close();
            ////Console.WriteLine("== RRD file closed.");

            ////// update database
            ////GaugeSource sunSource = new GaugeSource(1200, 20);
            ////GaugeSource shadeSource = new GaugeSource(300, 10);
            ////Console.WriteLine("== Simulating one month of RRD file updates with step not larger than " +
            ////        MAX_STEP + " seconds (* denotes 1000 updates)");
            ////long t = start;
            ////int n = 0;
            ////rrdDb = new RrdDb(rrdPath);
            ////Sample sample = rrdDb.createSample();

            ////while (t <= end + 86400L)
            ////{
            ////    sample.setTime(t);
            ////    sample.setValue("sun", sunSource.getValue());
            ////    sample.setValue("shade", shadeSource.getValue());
            ////    //log.Console.WriteLine(sample.dump());
            ////    sample.update();
            ////    t += (long)(RANDOM.NextDouble() * MAX_STEP) + 1;
            ////    if (((++n) % 1000) == 0)
            ////    {
            ////        Console.Write("*");
            ////    }
            ////}

            ////rrdDb.close();

            ////Console.WriteLine("");
            ////Console.WriteLine("== Finished. RRD file updated " + n + " times");

            //// test read-only access!
            //rrdDb = new RrdDb(rrdPath, true);
            //Console.WriteLine("File reopen in read-only mode");
            //Console.WriteLine("== Last update time was: " + rrdDb.getLastUpdateTime());
            //Console.WriteLine("== Last info was: " + rrdDb.getInfo());

            //// fetch data
            //Console.WriteLine("== Fetching data for the whole month");
            //request = rrdDb.createFetchRequest(new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), start, end);
            //Console.WriteLine(request.dump());
            ////  log.Console.WriteLine(request.dump());
            //fetchData = request.fetchData();
            //Console.WriteLine("== Data fetched. " + fetchData.getRowCount() + " points obtained");
            //Console.WriteLine(fetchData.toString());
            //Console.WriteLine("== Dumping fetched data to XML format");
            ////  Console.WriteLine(fetchData.exportXml());
            //Console.WriteLine("== Fetch completed");

            //// dump to XML file
            //Console.WriteLine("== Dumping RRD file to XML file " + xmlPath + " (can be restored with RRDTool)");
            ////  rrdDb.exportXml(xmlPath);
            //Console.WriteLine("== Creating RRD file " + rrdRestoredPath + " from XML file " + xmlPath);
            ////  RrdDb rrdRestoredDb = new RrdDb(rrdRestoredPath, xmlPath);

            //// close files
            //Console.WriteLine("== Closing both RRD files");
            //rrdDb.close();
            //Console.WriteLine("== First file closed");
            ////  rrdRestoredDb.close();
            //Console.WriteLine("== Second file closed");

            //// create graph
            //Console.WriteLine("Creating graph " + Util.getLapTime());
            //Console.WriteLine("== Creating graph from the second file");
            //gDef = new RrdGraphDef();
            //gDef.setWidth(IMG_WIDTH);
            //gDef.setHeight(IMG_HEIGHT);
            //gDef.setFilename(imgPath);
            //gDef.setStartTime(start);
            //gDef.setEndTime(end);
            //gDef.setTitle("Temperatures in May 2003");
            //gDef.setVerticalLabel("temperature");
            //gDef.datasource("sun", rrdPath/*rrdRestoredPath*/, "sun", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE));
            //gDef.datasource("shade", rrdPath/*rrdRestoredPath*/, "shade", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE));
            //gDef.datasource("median", "sun,shade,+,2,/");
            //gDef.datasource("diff", "sun,shade,-,ABS,-1,*");
            //gDef.datasource("sine", "TIME," + start + ",-," + (end - start) +
            //        ",/,2,PI,*,*,SIN,1000,*");
            //gDef.line("sun", Color.Green, "sun temp");
            //gDef.line("shade", Color.Blue, "shade temp");
            //gDef.line("median", Color.Magenta, "median value");
            //gDef.area("diff", Color.Yellow, "difference\\r");
            //gDef.line("diff", Color.Red, null);
            //gDef.line("sine", Color.Cyan, "sine function demo\\r");
            //gDef.hrule(2568, Color.Green, "hrule");
            //gDef.vrule((start + 2 * end) / 3, Color.Magenta, "vrule\\r");
            //gDef.gprint("sun", new ConsolFun(ConsolFun.ConsolFunTypes.MAX), "maxSun = %.3f%s");
            //gDef.gprint("sun", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), "avgSun = %.3f%S\\r");
            //gDef.gprint("shade", new ConsolFun(ConsolFun.ConsolFunTypes.MAX), "maxShade = %.3f%S");
            //gDef.gprint("shade", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), "avgShade = %.3f%S\\r");
            //gDef.print("sun", new ConsolFun(ConsolFun.ConsolFunTypes.MAX), "maxSun = %.3f%s");
            //gDef.print("sun", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), "avgSun = %.3f%S\\r");
            //gDef.print("shade", new ConsolFun(ConsolFun.ConsolFunTypes.MAX), "maxShade = %.3f%S");
            //gDef.print("shade", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), "avgShade = %.3f%S\\r");
            //gDef.setImageInfo("<img src='%s' width='%d' height = '%d'>");
            //gDef.setPoolUsed(false);
            //gDef.setImageFormat("png");
            //Console.WriteLine("Rendering graph " + Util.getLapTime());
            //// create graph finally
            //graph = new RrdGraph(gDef);

            //Console.WriteLine(graph.getRrdGraphInfo().dump());
            //Console.WriteLine("== Graph created " + Util.getLapTime());
            //// locks info
            ////Console.WriteLine("== Locks info ==");
            ////Console.WriteLine(RrdSafeFileBackend.getLockInfo());
            //// demo ends
            ////log.close();
            //Console.WriteLine("== Demo completed in " +
            //        ((DateTime.Now.Millisecond - startMillis) / 1000.0) + " sec");
        }
Пример #37
0
		public App()
		{
			Scheduler = new StdSchedulerFactory().GetScheduler();

			_dao = new Dao();
			_dao.Scheduler = Scheduler;
			LoadObjects();

			FileActions.OnNotificationAdded += NotificationAdded;

			_plugins = new Plugins();
			_rrdDb = new Rrd().GetDb();

			Objects.CheckAndRemoveDuplicates(Servers);
			ClearOldDownloads();
			TryToRecoverOpenFiles();
		}
Пример #38
0
 public void setDsHeartbeat(String sourcePath, String datasourceName, long newHeartbeat)
 {
     RrdDb rrd = new RrdDb(sourcePath);
     Datasource ds = rrd.getDatasource(datasourceName);
     ds.setHeartbeat(newHeartbeat);
     rrd.close();
 }
Пример #39
0
        public void ImportDataIntoDatabase(string databasePath, string xmlFilePath)
        {
            RrdDb database = new RrdDb(databasePath, xmlFilePath);

            model.ExportDatabase(databasePath, xmlFilePath);
        }
Пример #40
0
        public void ExportDatabase(string databasePath, string xmlFilePath)
        {
            RrdDb exportDatabase = new RrdDb(databasePath, true);

            exportDatabase.dumpXml(xmlFilePath);
        }
Пример #41
0
 public RrdEntry(RrdDb rrdDb)
 {
     this.rrdDb = rrdDb;
     ReportUsage();
 }
Пример #42
0
 public void removeArchive(String sourcePath, String destPath, String consolFun, int steps)
 {
     if (Util.sameFilePath(sourcePath, destPath))
     {
         throw new RrdException("Source and destination paths are the same");
     }
     RrdDb rrdSource = new RrdDb(sourcePath);
     RrdDef rrdDef = rrdSource.getRrdDef();
     rrdDef.setPath(destPath);
     rrdDef.removeArchive(consolFun, steps);
     RrdDb rrdDest = new RrdDb(rrdDef);
     rrdSource.copyStateTo(rrdDest);
     rrdSource.close();
     rrdDest.close();
 }
Пример #43
0
 public void setDsMinValue(String sourcePath, String datasourceName, double newMinValue, boolean filterArchivedValues)
 {
     RrdDb rrd = new RrdDb(sourcePath);
     Datasource ds = rrd.getDatasource(datasourceName);
     ds.setMinValue(newMinValue, filterArchivedValues);
     rrd.close();
 }
Пример #44
0
 internal void ReleaseRrd(RrdDb rrdDb)
 {
     rrdDb.Close();
 }
Пример #45
0
        public void Test2()
        {
            Console.WriteLine("Beginning Test2...");
            RrdDef rrdDef = new RrdDef("test2.rrd");
            rrdDef.StartTime = 920804400L;
            rrdDef.AddDatasource("speed", "COUNTER", 600, Double.NaN, Double.NaN);
            rrdDef.AddArchive("AVERAGE", 0.5, 1, 24);
            rrdDef.AddArchive("AVERAGE", 0.5, 6, 10);
            RrdDb rrdDb = new RrdDb(rrdDef);
            rrdDb.Close();

            rrdDb = new RrdDb("test2.rrd");
            Sample sample = rrdDb.CreateSample();
            sample.SetAndUpdate("920804700:12345");
            sample.SetAndUpdate("920805000:12357");
            sample.SetAndUpdate("920805300:12363");
            sample.SetAndUpdate("920805600:12363");
            sample.SetAndUpdate("920805900:12363");
            sample.SetAndUpdate("920806200:12373");
            sample.SetAndUpdate("920806500:12383");
            sample.SetAndUpdate("920806800:12393");
            sample.SetAndUpdate("920807100:12399");
            sample.SetAndUpdate("920807400:12405");
            sample.SetAndUpdate("920807700:12411");
            sample.SetAndUpdate("920808000:12415");
            sample.SetAndUpdate("920808300:12420");
            sample.SetAndUpdate("920808600:12422");
            sample.SetAndUpdate("920808900:12423");
            rrdDb.Close();

            RrdGraphDef graphDef = new RrdGraphDef();
            graphDef.SetTimePeriod(920804400L, 920808000L);
            graphDef.Datasource("myspeed", "test2.rrd", "speed", "AVERAGE");
            graphDef.Datasource("realspeed", "myspeed,1000,*");
            graphDef.Line("realspeed", Color.Red, "speed", 2);
            RrdGraph graph = new RrdGraph(graphDef);
            graph.SaveAsPNG("test2a.png", 400, 100);

            graphDef = new RrdGraphDef();
            graphDef.SetTimePeriod(920804400L, 920808000L);
            graphDef.VerticalLabel = "km/h";
            graphDef.Overlay = "Sunset.jpg";
            graphDef.Datasource("myspeed", "test2.rrd", "speed", "AVERAGE");
            graphDef.Datasource("kmh", "myspeed,3600,*");
            graphDef.Datasource("fast", "kmh,100,GT,kmh,0,IF");
            graphDef.Datasource("good", "kmh,100,GT,0,kmh,IF");
            graphDef.Area("good", Color.Lime, "Good speed");
            graphDef.Area("fast", Color.Red, "Too fast");
            graphDef.Hrule(100, Color.Blue, "Maximum allowed");
            graph = new RrdGraph(graphDef);
            graph.SaveAsPNG("test2b.png", 400, 100);
            Console.WriteLine("Test2 Complete.");
        }
Пример #46
0
        public void JonasTest2()
        {
            UInt32 start_time = 1370000000; // 31th may 2013, 11:33:20
            UInt32 end_time = start_time + 300 * 300;
            RrdDef rrdDef = new RrdDef("jonas.rrd");
            rrdDef.StartTime = start_time;
            rrdDef.AddDatasource("battery", "GAUGE", 300, 1.0, 5.0); // Five minutes
            rrdDef.AddArchive("LAST", 0.5, 1, 576);         //
            rrdDef.AddArchive("MIN", 0.5, 1, 576);          // 24 hours average, 2.5 minutes resolution
            rrdDef.AddArchive("MAX", 0.5, 1, 576);          // 24 hours average, 2.5 minutes resolution
            rrdDef.AddArchive("AVERAGE", 0.5, 6, 672);     // 7 days average, 15 min resolution
            rrdDef.AddArchive("MIN", 0.5, 6, 672);         // 7 days average, 15 min resolution
            rrdDef.AddArchive("MAX", 0.5, 6, 672);         // 7 days average, 15 min resolution
            rrdDef.AddArchive("AVERAGE", 0.5, 24, 87600);   // 10 year average, 1 hour resolution
            rrdDef.AddArchive("MIN", 0.5, 24, 87600);       // 10 year average, 1 hour resolution
            rrdDef.AddArchive("MAX", 0.5, 24, 87600);       // 10 year average, 1 hour resolution
            RrdDb db = new RrdDb(rrdDef);
            db.Close();

            RrdDb rrd = new RrdDb("jonas.rrd");
            Random rand = new Random();
            //Sample s = rrd.CreateSample();
            // update
            for(long t = start_time + 300; t <= end_time; t += 300)
            {
                double r = (double)rand.Next(1, 6);
                //s.SetAndUpdate(String.Format("{0}:{1}", t, r));
                Sample sample = rrd.CreateSample(t);
                sample.SetValue("battery", (double)r);
                sample.Update();
                Console.WriteLine(r);
            }

            FetchRequest fr = rrd.CreateFetchRequest("LAST", start_time, end_time - 300);
            FetchData fd = fr.FetchData();
            for (int i = 0; i < fd.RowCount; i++)
            {
                FetchPoint fp = fd.GetRow(i);
                Console.WriteLine("{0}: {1}", fp.Time, fp.Values[0]);
            }

            rrd.Close();

            // Create new graph for the last 12 hours
            RrdGraphDef gdef = new RrdGraphDef(new DateTime(2013, 05, 31, 12, 00, 00), new DateTime(2013, 05, 31, 18, 59, 59));
            gdef.Title = "Battery voltage";
            gdef.VerticalLabel = "U (V)";
            gdef.SetValueAxis(1.0, 1.0);
            gdef.SetGridRange(1.000, 5.000, true);
            gdef.Datasource("vbat", "jonas.rrd", "battery", "LAST");
            //gdef.Datasource("vbat_avg", "jonas.rrd", "battery", "AVERAGE");
            gdef.Datasource("vbat_trend", "vbat,900,TREND");
            gdef.Line("vbat", System.Drawing.Color.Green, "Battery voltage", 1);
            //gdef.Line("vbat_avg", System.Drawing.Color.Red, "Average over 15 min", 1);
            gdef.Line("vbat_trend", System.Drawing.Color.Red, "Trend over 15 min", 1);
            gdef.Gprint("vbat", "LAST", "Current: @2V@r");
            gdef.Gprint("vbat", "AVERAGE", "Average: @2V@r");
            gdef.Gprint("vbat", "MAX", "Max: @2V@r");
            gdef.Gprint("vbat", "MIN", "Min: @2V@r");
            RrdGraph graph = new RrdGraph(gdef);
            graph.SaveAsPNG("battery2_2h.png", 700, 300);
        }
Пример #47
0
        public void Test3()
        {
            long start = Util.Time, end = start + 300 * 300;
            string rrdFile = "test3.rrd";
            string pngFile = "test3.png";

            Console.WriteLine("Beginning Test3...");
            RrdDef rrdDef = new RrdDef(rrdFile, start - 1, 300);
            rrdDef.AddDatasource("a", "GAUGE", 600, Double.NaN, Double.NaN);
            rrdDef.AddArchive("AVERAGE", 0.5, 1, 300);
            rrdDef.AddArchive("MIN", 0.5, 12, 300);
            rrdDef.AddArchive("MAX", 0.5, 12, 300);
            RrdDb rrdDb = new RrdDb(rrdDef);
            // update
            for(long t = start; t <  end; t += 300)
            {
                Sample sample = rrdDb.CreateSample(t);
                sample.SetValue("a", Math.Sin(t / 3000.0) * 50 + 50);
                sample.Update();
            }
            rrdDb.Close();
            // graph
            RrdGraphDef gDef = new RrdGraphDef();
            gDef.SetTimePeriod(start, start + 86400);
            gDef.Title = "RRDTool's MINMAX.pl demo";
            gDef.TimeAxisLabel = "time";
            gDef.Datasource("a", rrdFile, "a", "AVERAGE");
            gDef.Datasource("b", rrdFile, "a", "MIN");
            gDef.Datasource("c", rrdFile, "a", "MAX");
            gDef.Area("a", Color.LightBlue, "real");
            gDef.Line("b", Color.Blue, "min");
            gDef.Line("c", Color.Lime, "max");
            RrdGraph graph = new RrdGraph(gDef);
            graph.SaveAsPNG(pngFile, 450, 0);
            Console.WriteLine("Test3 Complete.");
        }
Пример #48
0
 internal void ReleaseRrd(RrdDb rrdDb)
 {
     rrdDb.Close();
 }
Пример #49
0
 public void setArcXff(String sourcePath, String consolFun, int steps, double newXff)
 {
     RrdDb rrd = new RrdDb(sourcePath);
     Archive arc = rrd.getArchive(consolFun, steps);
     arc.setXff(newXff);
     rrd.close();
 }
Пример #50
0
 internal static int GetMatchingDatasourceIndex(RrdDb rrd1, int dsIndex, RrdDb rrd2)
 {
     string dsName = rrd1.GetDatasource(dsIndex).DsName;
     try
     {
         return rrd2.GetDsIndex(dsName);
     }
     catch (RrdException)
     {
         return -1;
     }
 }