public Sample(RrdDb parentDb, long time) { this.parentDb = parentDb; this.time = time; this.dsNames = parentDb.getDsNames(); clearValues(); }
public FetchRequest(RrdDb parentDb, ConsolFun consolFun, long fetchStart, long fetchEnd, long resolution) { if (consolFun == null) { throw new ArgumentException("Null consolidation function in fetch request"); } if (fetchStart < 0) { throw new ArgumentException("Invalid start time in fetch request: " + fetchStart); } if (fetchEnd < 0) { throw new ArgumentException("Invalid end time in fetch request: " + fetchEnd); } if (fetchStart > fetchEnd) { throw new ArgumentException("Invalid start/end time in fetch request: " + fetchStart + " > " + fetchEnd); } if (resolution <= 0) { throw new ArgumentException("Invalid resolution in fetch request: " + resolution); } this.parentDb = parentDb; this.consolFun = consolFun; this.fetchStart = fetchStart; this.fetchEnd = fetchEnd; this.resolution = resolution; }
public Archive(RrdDb parentDb, ArcDef arcDef) { bool shouldInitialize = arcDef != null; this.parentDb = parentDb; consolFun = new RrdString(this, true); // constant, may be cached xff = new RrdDouble(this); steps = new RrdInt(this, true); // constant, may be cached rows = new RrdInt(this, true); // constant, may be cached if (shouldInitialize) { consolFun.set(arcDef.getConsolFun().Name); xff.set(arcDef.getXff()); steps.set(arcDef.getSteps()); rows.set(arcDef.getRows()); } int n = parentDb.getHeader().getDsCount(); states = new ArcState[n]; robins = new Robin[n]; for (int i = 0; i < n; i++) { states[i] = new ArcState(this, shouldInitialize); int numRows = rows.get(); robins[i] = new Robin(this, numRows, shouldInitialize); } }
/** * Copies object's internal state to another RrdDb object. * * @param other New RrdDb object to copy state to * @Thrown in case of I/O error */ public void copyStateTo(RrdUpdater other) { lock (sync) { if (other.GetType() != typeof(RrdDb)) { throw new ArgumentException("Cannot copy RrdDb object to " + other.GetType().ToString()); } RrdDb otherRrd = (RrdDb)other; header.copyStateTo(otherRrd.header); for (int i = 0; i < Datasources.Length; i++) { int j = getMatchingDatasourceIndex(this, i, otherRrd); if (j >= 0) { Datasources[i].copyStateTo(otherRrd.Datasources[j]); } } for (int i = 0; i < archives.Length; i++) { int j = getMatchingArchiveIndex(this, i, otherRrd); if (j >= 0) { archives[i].copyStateTo(otherRrd.archives[j]); } } } }
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(); } }
/** * Requests a RrdDb reference for the given RRD file path.<p> * <ul> * <li>If the file is already open, previously returned RrdDb reference will be returned. Its usage count * will be incremented by one. * <li>If the file is not already open and the number of already open RRD files is less than * {@link #INITIAL_CAPACITY}, the file will be open and a new RrdDb reference will be returned. * If the file is not already open and the number of already open RRD files is equal to * {@link #INITIAL_CAPACITY}, the method blocks until some RRD file is closed. * </ul> * * @param path Path to existing RRD file * @return reference for the give RRD file * @ Thrown in case of I/O error */ public RrdDb requestRrdDb(String path) { lock (sync) { String canonicalPath = Util.getCanonicalPath(path); while (!rrdMap.ContainsKey(canonicalPath) && rrdMap.Count >= capacity) { Thread.Sleep(10); } if (rrdMap.ContainsKey(canonicalPath)) { // already open, just increase usage count RrdEntry entry = rrdMap[canonicalPath]; entry.count++; return(entry.rrdDb); } else { // not open, open it now and add to the map RrdDb rrdDb = new RrdDb(canonicalPath); rrdMap.Add(canonicalPath, new RrdEntry(rrdDb)); return(rrdDb); } } }
public Datasource(RrdDb parentDb, DsDef dsDef) { bool shouldInitialize = dsDef != null; this.parentDb = parentDb; dsName = new RrdString(this); dsTypeName = new RrdString(this); if (!shouldInitialize) { dsType = new DsType(dsTypeName.get()); } 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.getDsName()); dsType = dsDef.getDsType(); dsTypeName.set(dsType.Name); heartbeat.set(dsDef.getHeartbeat()); minValue.set(dsDef.getMinValue()); maxValue.set(dsDef.getMaxValue()); lastValue.set(Double.NaN); accumValue.set(0.0); Header header = parentDb.getHeader(); nanSeconds.set(header.getLastUpdateTime() % header.getStep()); } }
public Datasource(RrdDb parentDb, DsDef dsDef) { bool shouldInitialize = dsDef != null; this.parentDb = parentDb; dsName = new RrdString(this); dsTypeName = new RrdString(this); if (!shouldInitialize) dsType = new DsType(dsTypeName.get()); 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.getDsName()); dsType = dsDef.getDsType(); dsTypeName.set(dsType.Name); heartbeat.set(dsDef.getHeartbeat()); minValue.set(dsDef.getMinValue()); maxValue.set(dsDef.getMaxValue()); lastValue.set(Double.NaN); accumValue.set(0.0); Header header = parentDb.getHeader(); nanSeconds.set(header.getLastUpdateTime() % header.getStep()); } }
public Sample(string[] dsNames, long time) { this.parentDb = null; this.time = time; this.dsNames = dsNames; clearValues(); }
public Datasource(RrdDb parentDb, DataImporter reader, int dsIndex) : this(parentDb, null) { dsName.set(reader.getDsName(dsIndex)); dsType = new DsType(reader.getDsType(dsIndex)); dsTypeName.set(dsType.Name); heartbeat.set(reader.getHeartbeat(dsIndex)); minValue.set(reader.getMinValue(dsIndex)); maxValue.set(reader.getMaxValue(dsIndex)); lastValue.set(reader.getLastValue(dsIndex)); accumValue.set(reader.getAccumValue(dsIndex)); nanSeconds.set(reader.getNanSeconds(dsIndex)); }
private static int getMatchingDatasourceIndex(RrdDb rrd1, int dsIndex, RrdDb rrd2) { String dsName = rrd1.getDatasource(dsIndex).DsName; try { return(rrd2.getDsIndex(dsName)); } catch (ArgumentException e) { return(-1); } }
/** * Requests a RrdDb reference for the given RRD file definition object.<p> * <ul> * <li>If the file with the path specified in the RrdDef object is already open, * the method blocks until the file is closed. * <li>If the file is not already open and the number of already open RRD files is less than * {@link #INITIAL_CAPACITY}, a new RRD file will be created and a its RrdDb reference will be returned. * If the file is not already open and the number of already open RRD files is equal to * {@link #INITIAL_CAPACITY}, the method blocks until some RRD file is closed. * </ul> * * @param rrdDef Definition of the RRD file to be created * @return Reference to the newly created RRD file * @ Thrown in case of I/O error */ public RrdDb requestRrdDb(RrdDef rrdDef) { lock (sync) { String canonicalPath = Util.getCanonicalPath(rrdDef.getPath()); while (rrdMap.ContainsKey(canonicalPath) || rrdMap.Count >= capacity) { Thread.Sleep(10); } RrdDb rrdDb = new RrdDb(rrdDef); rrdMap.Add(canonicalPath, new RrdEntry(rrdDb)); return(rrdDb); } }
public Header(RrdDb parentDb, DataImporter reader) : this(parentDb, (RrdDef)null) { String version = reader.getVersion(); if (RRDTOOL_VERSION.CompareTo(version) != 0) { throw new ArgumentException("Could not unserialize xml version " + version); } signature.set(DEFAULT_SIGNATURE); step.set(reader.getStep()); dsCount.set(reader.getDsCount()); arcCount.set(reader.getArcCount()); lastUpdateTime.set(reader.getLastUpdateTime()); }
private static int getMatchingArchiveIndex(RrdDb rrd1, int arcIndex, RrdDb rrd2) { Archive archive = rrd1.getArchive(arcIndex); ConsolFun consolFun = archive.getConsolFun(); int steps = archive.getSteps(); try { return(rrd2.getArcIndex(consolFun, steps)); } catch (ArgumentException e) { return(-1); } }
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(); } }
public Header(RrdDb parentDb, RrdDef rrdDef, String initSignature) { this.parentDb = parentDb; signature = new RrdString(this); // NOT constant, may 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 (rrdDef != null) { signature.set(initSignature); step.set(rrdDef.getStep()); dsCount.set(rrdDef.getDsCount()); arcCount.set(rrdDef.getArcCount()); lastUpdateTime.set(rrdDef.getStartTime()); } }
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(); } }
/** * Requests a RrdDb reference for the given path. The file will be created from * external data (from XML dump, RRD file or RRDTool's binary RRD file).<p> * <ul> * <li>If the file with the path specified is already open, * the method blocks until the file is closed. * <li>If the file is not already open and the number of already open RRD files is less than * {@link #INITIAL_CAPACITY}, a new RRD file will be created and a its RrdDb reference will be returned. * If the file is not already open and the number of already open RRD files is equal to * {@link #INITIAL_CAPACITY}, the method blocks until some RRD file is closed. * </ul> * * @param path Path to RRD file which should be created * @param sourcePath Path to external data which is to be converted to Rrd4n's native RRD file format * @return Reference to the newly created RRD file * @ Thrown in case of I/O error */ //public RrdDb requestRrdDb(String path, String sourcePath) { // lock (sync) // { // String canonicalPath = Util.getCanonicalPath(path); // while (rrdMap.containsKey(canonicalPath) || rrdMap.size() >= capacity) // { // Thread.Sleep(10); // } // RrdDb rrdDb = new RrdDb(canonicalPath, sourcePath); // rrdMap.put(canonicalPath, new RrdEntry(rrdDb)); // return rrdDb; // } //} /** * Releases RrdDb reference previously obtained from the pool. When a reference is released, its usage * count is decremented by one. If usage count drops to zero, the underlying RRD file will be closed. * * @param rrdDb RrdDb reference to be returned to the pool * @ Thrown in case of I/O error */ public void release(RrdDb rrdDb) { lock (sync) { // null pointer should not kill the thread, just ignore it if (rrdDb == null) { return; } String canonicalPath = Util.getCanonicalPath(rrdDb.getPath()); if (!rrdMap.ContainsKey(canonicalPath)) { throw new ApplicationException("Could not release [" + canonicalPath + "], the file was never requested"); } RrdEntry entry = rrdMap[canonicalPath]; if (--entry.count <= 0) { // no longer used rrdMap.Remove(canonicalPath); entry.rrdDb.close(); } } }
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(); } }
public FetchRequest(RrdDb parentDb, ConsolFun consolFun, DateTime fetchStart, DateTime fetchEnd, long resolution) : this(parentDb, consolFun, Util.getTimestamp(fetchStart), Util.getTimestamp(fetchEnd), resolution) { }
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"); }
public void ImportDataIntoDatabase(string databasePath, string xmlFilePath) { RrdDb database = new RrdDb(databasePath,xmlFilePath); model.ExportDatabase(databasePath, xmlFilePath); }
public Header(RrdDb parentDb, RrdDef rrdDef) : this(parentDb, rrdDef, DEFAULT_SIGNATURE) { }
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); }
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); }
public RrdEntry(RrdDb rrdDb) { this.rrdDb = rrdDb; this.count = 1; }
private static int getMatchingDatasourceIndex(RrdDb rrd1, int dsIndex, RrdDb rrd2) { String dsName = rrd1.getDatasource(dsIndex).DsName; try { return rrd2.getDsIndex(dsName); } catch (ArgumentException e) { return -1; } }
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; } }
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; } }
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; }
/** * Requests a RrdDb reference for the given RRD file definition object.<p> * <ul> * <li>If the file with the path specified in the RrdDef object is already open, * the method blocks until the file is closed. * <li>If the file is not already open and the number of already open RRD files is less than * {@link #INITIAL_CAPACITY}, a new RRD file will be created and a its RrdDb reference will be returned. * If the file is not already open and the number of already open RRD files is equal to * {@link #INITIAL_CAPACITY}, the method blocks until some RRD file is closed. * </ul> * * @param rrdDef Definition of the RRD file to be created * @return Reference to the newly created RRD file * @ Thrown in case of I/O error */ public RrdDb requestRrdDb(RrdDef rrdDef) { lock (sync) { String canonicalPath = Util.getCanonicalPath(rrdDef.getPath()); while (rrdMap.ContainsKey(canonicalPath) || rrdMap.Count >= capacity) { Thread.Sleep(10); } RrdDb rrdDb = new RrdDb(rrdDef); rrdMap.Add(canonicalPath, new RrdEntry(rrdDb)); return rrdDb; } }
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(); } }
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(); } }
public void ExportDatabase(string databasePath, string xmlFilePath) { RrdDb exportDatabase = new RrdDb(databasePath, true); exportDatabase.dumpXml(xmlFilePath); }
/** * Requests a RrdDb reference for the given RRD file path.<p> * <ul> * <li>If the file is already open, previously returned RrdDb reference will be returned. Its usage count * will be incremented by one. * <li>If the file is not already open and the number of already open RRD files is less than * {@link #INITIAL_CAPACITY}, the file will be open and a new RrdDb reference will be returned. * If the file is not already open and the number of already open RRD files is equal to * {@link #INITIAL_CAPACITY}, the method blocks until some RRD file is closed. * </ul> * * @param path Path to existing RRD file * @return reference for the give RRD file * @ Thrown in case of I/O error */ public RrdDb requestRrdDb(String path) { lock (sync) { String canonicalPath = Util.getCanonicalPath(path); while (!rrdMap.ContainsKey(canonicalPath) && rrdMap.Count >= capacity) { Thread.Sleep(10); } if (rrdMap.ContainsKey(canonicalPath)) { // already open, just increase usage count RrdEntry entry = rrdMap[canonicalPath]; entry.count++; return entry.rrdDb; } else { // not open, open it now and add to the map RrdDb rrdDb = new RrdDb(canonicalPath); rrdMap.Add(canonicalPath, new RrdEntry(rrdDb)); return rrdDb; } } }
private static int getMatchingArchiveIndex(RrdDb rrd1, int arcIndex, RrdDb rrd2) { Archive archive = rrd1.getArchive(arcIndex); ConsolFun consolFun = archive.getConsolFun(); int steps = archive.getSteps(); try { return rrd2.getArcIndex(consolFun, steps); } catch (ArgumentException e) { return -1; } }
public FetchRequest(RrdDb parentDb, ConsolFun consolFun, DateTime fetchStart, DateTime fetchEnd, long resolution) : this(parentDb,consolFun,Util.getTimestamp(fetchStart),Util.getTimestamp(fetchEnd),resolution) { }