public Sensor(string deviceId, string sensorType) { DeviceId = deviceId; SensorType = sensorType; influxDbClient = InfluxDbClient.GetInstance(); }
// Update password for the selected user async Task ChangePassword() { try { var user = SelectedUser; if (user == null) { return; } userPasswordDialog.BindToUser(user); if (userPasswordDialog.ShowDialog() == DialogResult.OK) { var response = await InfluxDbClient.SetPasswordAsync(user.Name, userPasswordDialog.Password); // Select the user and refresh the window if (!response.Success) { AppForm.DisplayError(response.Body); } } } catch (Exception ex) { AppForm.DisplayException(ex); } }
/// <summary> /// Binds the control to server diagnostics information. /// </summary> public async override Task ExecuteRequestAsync() { if (InfluxDbClient == null) { throw new Exception("No InfluxDB client available."); } // Clear current values var blank = "-"; // System pidValue.Text = blank; currentTimeValue.Text = blank; startedValue.Text = blank; uptimeValue.Text = blank; // Build branchValue.Text = blank; commitValue.Text = blank; buildVersionValue.Text = blank; // Runtime goArchValue.Text = blank; goMaxProcsValue.Text = blank; goOsValue.Text = blank; goVersionValue.Text = blank; // Network hostnameValue.Text = blank; // Query new values var diagnostics = await InfluxDbClient.GetDiagnosticsAsync(); if (diagnostics == null) { return; } // System pidValue.Text = diagnostics.PID.ToString(); currentTimeValue.Text = diagnostics.CurrentTime.ToString(); startedValue.Text = diagnostics.Started.ToString(); var ut = diagnostics.Uptime; uptimeValue.Text = string.Format("{0}d {1}h {2}m {3}s {4}ms", ut.Days, ut.Hours, ut.Minutes, ut.Seconds, ut.Milliseconds); // Build branchValue.Text = diagnostics.Branch; commitValue.Text = diagnostics.Commit; buildVersionValue.Text = diagnostics.BuildVersion; // Runtime goArchValue.Text = diagnostics.GoArch; goMaxProcsValue.Text = diagnostics.GoMaxProc.ToString(); goOsValue.Text = diagnostics.GoOs; goVersionValue.Text = diagnostics.GoVersion; // Network hostnameValue.Text = diagnostics.Hostname; }
protected async override Task OnExecuteQuery() { // Get tag keys from the server var tagKeys = await InfluxDbClient.GetTagKeysAsync(Database, Measurement); if (tagKeys == null || tagKeys.Count() == 0) { return; } // Add default row count column listView.Columns.Add(new ColumnHeader() { Text = "#" }); // Add tag key column listView.Columns.Add(new ColumnHeader() { Text = "tagKey" }); // Add values var rowCount = 0; foreach (var tagKey in tagKeys) { listView.Items.Add(new ListViewItem(new string[] { (++rowCount).ToString(), tagKey }) { Tag = tagKey }); } }
static InfluxDbClient Setup() { var client = new InfluxDbClient("http://localhost:8086/", "", "", InfluxDbVersion.Latest); return(client); }
public async Task LogMetrics(string seriesName, string meassurementName, int value) { try { if (influxDbClient == null) { influxDbClient = await CreateClient(); } var pointToWrite = new Point() { Name = seriesName, Tags = new Dictionary <string, object>() { { "host", System.Environment.MachineName } }, Fields = new Dictionary <string, object>() { { "execution_time", value } }, Timestamp = DateTime.UtcNow }; await influxDbClient.Client.WriteAsync(pointToWrite, config.DatabaseInfo.DatabaseName, config.DatabaseInfo.RetentionPolicyName); } catch (Exception ex) { influxDbClient = null; log.LogError(ex, $"Connecting to {config.Url} failed."); throw; } }
// Shows the create policy dialog async Task ShowCreatePolicy() { try { // Clear out the dialog values policyDialog.ResetPolicyValues(); if (policyDialog.ShowDialog() == DialogResult.OK) { var name = policyDialog.PolicyName; var duration = policyDialog.PolicyDuration; var replication = policyDialog.PolicyReplication; var isDefault = policyDialog.PolicyDefault; var response = await InfluxDbClient.CreateRetentionPolicyAsync(SelectedDatabase, name, duration, replication, isDefault); if (!response.Success) { AppForm.DisplayError(response.Body); } // Reload latest data await ExecuteRequestAsync(); } } catch (Exception ex) { AppForm.DisplayException(ex); } }
// Binds the database drop down to the list of database for the current connection async Task BindDatabases() { // Clear current list of databases databaseComboBox.Items.Clear(); // Get the total list of databases var dbNames = await InfluxDbClient.GetDatabaseNamesAsync(); if (dbNames.Count() == 0) { return; } databaseComboBox.BeginUpdate(); foreach (var db in dbNames) { databaseComboBox.Items.Add(db); } databaseComboBox.EndUpdate(); // Select the first database databaseComboBox.SelectedIndex = 0; }
// Drops a Continuous Query async Task DropContinuousQuery() { try { if (SelectedCq == null || Database == null) { return; } // Confirm Drop if (MessageBox.Show(string.Format("Drop CQ: {0}?", SelectedCq.Name), "Confirm Drop", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) { var response = await InfluxDbClient.DropContinuousQueryAsync(Database, SelectedCq.Name); if (response.Success) { SelectedCq = null; await ExecuteRequestAsync(); } else { AppForm.DisplayError(response.Body); } UpdateUIState(); } } catch (Exception ex) { AppForm.DisplayException(ex); } }
// Kills the selected query async Task KillQuery() { try { if (listView.SelectedItems.Count == 0) { return; } var pid = ((InfluxDbRunningQuery)listView.SelectedItems[0].Tag).PID; var response = await InfluxDbClient.KillQueryAsync(pid); if (!response.Success && !response.Body.Contains("query interrupted")) { AppForm.DisplayError(response.Body); } else { listView.BeginUpdate(); listView.SelectedItems[0].Remove(); listView.EndUpdate(); } UpdateUIState(); } catch (Exception ex) { AppForm.DisplayException(ex); } }
/// <summary> /// Binds the form's database drop down to the list of available databases for the /// current connection. /// </summary> public async Task BindInfluxDataSources() { try { // No database assigned if (string.IsNullOrWhiteSpace(Database)) { return; } // Display database name in UI databaseValue.Text = Database; // Clear the current list of measurements and reload destinationComboBox.Items.Clear(); sourceComboBox.Items.Clear(); var measurementNames = await InfluxDbClient.GetMeasurementNamesAsync(Database); foreach (var measurement in measurementNames) { destinationComboBox.Items.Add(measurement); sourceComboBox.Items.Add(measurement); } destinationComboBox.SelectedItem = null; sourceComboBox.SelectedItem = null; } catch (Exception ex) { AppForm.DisplayException(ex); } }
private async Task <InfluxDbClient> CreateClient() { influxDbClient = new InfluxDbClient(config.Url, config.UserName, config.Password, InfluxDbVersion.Latest); await CreateDb(config.DatabaseInfo); return(influxDbClient); }
public InfluxDBMeasurementsCollector(InfluxDBLoginInformation loginInformation) { this.loginInformation = loginInformation; influxDBClient = new InfluxDbClient(loginInformation.DBUri.ToString(), loginInformation.User, loginInformation.Password, InfluxDbVersion.v_1_3); }
public async Task <string> ConsultaBD() { var influxDbClient = new InfluxDbClient("http://host:8086/", "user", "pass", InfluxDbVersion.v_1_3); var query = "SELECT T_PV FROM TFA WHERE time >= '2019-05-21' and time < '2019-05-22' "; var response = await influxDbClient.Client.QueryAsync(query, "dbName"); return(response.ToString()); }
public async override Task ExecuteRequestAsync(bool updateGrid = true) { if (InfluxDbClient == null) { throw new Exception("No InfluxDB client available."); } // Clear current items listView.Items.Clear(); // Start redraw listView.BeginUpdate(); // Query and render var queries = await InfluxDbClient.GetRunningQueriesAsync(); foreach (var q in queries) { listView.Items.Add(new ListViewItem(new string[] { q.PID.ToString(), q.Duration, q.Database.ToString(), q.Query }) { Tag = q }); } // Restore selection if (SelectedQuery != null) { var pid = SelectedQuery.PID.ToString(); foreach (ListViewItem li in listView.Items) { if (li.Text == pid) { li.Selected = true; SelectedQuery = (InfluxDbRunningQuery)li.Tag; } } } // Resize each column //if (listView.Columns.Count > 0) //{ // var columnWidth = (Width - 12) / listView.Columns.Count; // if (columnWidth < 96) columnWidth = 96; // foreach (ColumnHeader col in listView.Columns) col.Width = columnWidth; //} // Render listView.EndUpdate(); UpdateUIState(); }
public InfluxDbContext(InfluxDBOptions options) { Options = options; var client = new InfluxDbClient(options.Host, options.UserName, options.Password, InfluxDbVersion.v_1_0_0); this.Client = client.Client; this.Database = client.Database; Ensure().Wait(); }
static async Task WriteBatch(InfluxDbClient client, long batchSize) { var readings = new List <Point>(); for (var j = 0L; j < batchSize; ++j) { readings.Add(GenerateReading()); } await client.Client.WriteAsync(readings, "CIPTanks"); }
public InfluxdbUtility(string url = "http://localhost:8086/", string user = "******", string pwd = "maoheng0") { //连接InfluxDb的API地址、账号、密码 var infuxUrl = url; var infuxUser = user; var infuxPwd = pwd; //创建InfluxDbClient实例 clientDb = new InfluxDbClient(infuxUrl, infuxUser, infuxPwd, InfluxDbVersion.Latest); }
public BuildingScoreInfluxDBRepository() { // API Address, Account, Password for Connecting Influx Db var infuxUrl = "http://localhost:8086/"; var infuxUser = "******"; var infuxPwd = "scoresuser123"; // Create an instance of Influx DbClient clientDb = new InfluxDbClient(infuxUrl, infuxUser, infuxPwd, InfluxDbVersion.Latest); }
/// <summary> /// Runs the current query against the configured connection and database. /// </summary> public override async Task ExecuteRequestAsync() { if (InfluxDbClient == null) { throw new Exception("No InfluxDB client available."); } // Reset the results count resultsCount = 0; // Get the database and the query var query = EditorText.Trim(); bool isAggregate = query.ToLower().Contains("group by"); // Clear the current results tabControl.Controls.Clear(); // Start timing... stopWatch.Restart(); // Execute the query var results = await InfluxDbClient.QueryAsync(Database, query); // Stop timing... stopWatch.Stop(); // If there are results if (results != null && results.Count() > 0) { var tabCount = 0; var tabLabel = isAggregate ? "Group" : "Results"; foreach (var result in results) { // Create a new tab page to hold the query results control var tab = new TabPage(string.Format("{0} {1}", tabLabel, ++tabCount)); // Create a new query results control var queryResultsControl = new QueryResultsControl(); queryResultsControl.InfluxDbClient = InfluxDbClient; queryResultsControl.Database = Database; queryResultsControl.Dock = DockStyle.Fill; tab.Controls.Add(queryResultsControl); // Add the tab to the control tabControl.TabPages.Add(tab); // Render the results and increment the global total resultsCount += queryResultsControl.UpdateResults(result); } } // Show stat results of query resultsLabel.Text = string.Format("results: {0}, response time: {1:0} ms", resultsCount, stopWatch.Elapsed.TotalMilliseconds); }
/// <summary> /// Dient zum Herstellen einer Verbindung /// zur gewählten Datenbankadresse /// </summary> /// <param name="AdresseDB">Adresse der Datenbank</param> public void SysloggerCreateClient(string AdresseDB) { try { influxDbClient = new InfluxDbClient(AdresseDB, " ", " ", InfluxDbVersion.v_1_3); } catch { throw new Exception("Der eingegebene Server existiert nicht!"); } }
public IntegrationTestsRuntime() { using (var client = new InfluxDbClient(Host)) { var dbNames = client.GetDatabasesAsync().Result; foreach (var databaseName in dbNames.Where(dbName => dbName.StartsWith(DatabaseName))) client.DropDatabaseAsync(databaseName).Wait(); client.CreateDatabaseAsync(DatabaseName).Wait(); } }
// Grant privilege async Task GrantPrivilege() { try { var user = SelectedUser; if (user == null) { return; } grantPrivilegeDialog.InfluxDbClient = InfluxDbClient; await grantPrivilegeDialog.BindToUser(user); if (grantPrivilegeDialog.ShowDialog() == DialogResult.OK) { // Get the selected database and privilege to grant var username = grantPrivilegeDialog.User.Name; var database = grantPrivilegeDialog.SelectedDatabase; var privilege = grantPrivilegeDialog.SelectedPrivilege; // Ensure a database was selected if (string.IsNullOrWhiteSpace(database)) { AppForm.DisplayError("You must supply a database to grant a privilege for."); return; } // Otherwise if "None" was selected (shouldn't be possible), there's nothing to grant... else if (privilege == InfluxDbPrivileges.None) { return; } // Grant the privilege var response = await InfluxDbClient.GrantPrivilegeAsync(username, privilege, database); // Refresh the window if (response.Success) { await ExecuteRequestAsync(); } else { AppForm.DisplayError(response.Body); } // Update interface buttons UpdateUIState(); } } catch (Exception ex) { AppForm.DisplayException(ex); } }
/// <inheritdoc /> /// <summary> /// Construct a sink inserting into InfluxDB with the specified details. /// </summary> /// <param name="connectionInfo">Connection information used to construct InfluxDB client.</param> /// <param name="source">Measurement name in the InfluxDB database.</param> /// <param name="batchSizeLimit">The maximum number of events to post in a single batch.</param> /// <param name="period">The time to wait between checking for event batches.</param> /// <param name="formatProvider"></param> public InfluxDBSink(InfluxDBConnectionInfo connectionInfo, string source, int batchSizeLimit, TimeSpan period, IFormatProvider formatProvider) : base(batchSizeLimit, period) { _connectionInfo = connectionInfo ?? throw new ArgumentNullException(nameof(connectionInfo)); _source = source; _influxDbClient = CreateInfluxDbClient(); _formatProvider = formatProvider; CreateDatabase(); }
// Drops the selected policy async Task ShowDropPolicy() { try { var policy = SelectedRetentionPolicy; if (policy == null || string.IsNullOrWhiteSpace(SelectedDatabase)) { return; } var wasDefault = policy.Default; // Confirm the drop if (DialogResult.OK == MessageBox.Show(string.Format("Drop retention policy: {0}?", policy.Name), "Confirm Drop", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning)) { var response = await InfluxDbClient.DropRetentionPolicyAsync(SelectedDatabase, policy.Name); if (!response.Success) { AppForm.DisplayError(response.Body); } // If this was the default policy and was dropped if (wasDefault) { policies = await InfluxDbClient.GetRetentionPoliciesAsync(SelectedDatabase); if (policies.Count() > 0) { // Try to find the autogen/default var rp = (from r in policies where r.Name.ToLower() == "autogen" select r).FirstOrDefault(); // Otherwise try to find another policy with a different name if (rp == null) { rp = (from r in policies where r.Name != policy.Name select r).FirstOrDefault(); } if (rp != null) { // If a new retention policy was found, make it the default response = await InfluxDbClient.AlterRetentionPolicyAsync(SelectedDatabase, rp.Name, rp.Duration, rp.ReplicationCopies, true); } } } // Reload latest data await ExecuteRequestAsync(); } } catch (Exception ex) { AppForm.DisplayException(ex); } }
/// <inheritdoc /> /// <summary> /// Construct a sink inserting into InfluxDB with the specified details. /// </summary> /// <param name="connectionInfo">Connection information used to construct InfluxDB client.</param> /// <param name="applicationName">Application name in the InfluxDB database.</param> /// <param name="instanceName">Facility name in the InfluxDB database.</param> /// <param name="batchSizeLimit">The maximum number of events to post in a single batch.</param> /// <param name="period">The time to wait between checking for event batches.</param> /// <param name="formatProvider"></param> public InfluxDBSink(InfluxDBConnectionInfo connectionInfo, string applicationName, string instanceName, int batchSizeLimit, TimeSpan period, IFormatProvider formatProvider) : base(batchSizeLimit, period) { _connectionInfo = connectionInfo ?? throw new ArgumentNullException(nameof(connectionInfo)); _applicationName = applicationName; _instanceName = instanceName ?? applicationName; _influxDbClient = CreateInfluxDbClient(); _formatProvider = formatProvider; CreateDatabaseIfNotExists(); }
// Edit the selected user async Task EditUser() { try { var user = SelectedUser; if (user == null) { return; } editUserDialog.BindToUser(user); if (editUserDialog.ShowDialog() == DialogResult.OK) { // If there was no change in user status, there's nothing to do var updatedUser = editUserDialog.CreateUserFromDialog(); if (user.IsAdmin == updatedUser.IsAdmin) { return; } InfluxDbApiResponse response = null; // Otherwise carry out the appropriate API call based on adding or removing admin privileges if (updatedUser.IsAdmin) { response = await InfluxDbClient.GrantAdministratorAsync(updatedUser.Name); } else { response = await InfluxDbClient.RevokeAdministratorAsync(updatedUser.Name); } // Refresh the window if (response.Success) { await ExecuteRequestAsync(); } else { AppForm.DisplayError(response.Body); } // Update interface buttons UpdateUIState(); } } catch (Exception ex) { AppForm.DisplayException(ex); } }
static InfluxDBHelper() { if (AppConfig.GetFinalConfig("bWriteToInfluxDB", false, LogApi.IsWriteToInfluxDB())) { var serverStr = AppConfig.GetFinalConfig("InfluxDBServer_Log", "http://127.0.0.1:8086/;logAdmin;sa123.123", LogApi.GetInfluxDBServer_Log()); //http://127.0.0.1:8086/;logAdmin;sa123.123 var temp = serverStr.Split(';'); influxDbClient = new InfluxDbClient(temp[0], temp[1], temp[2], InfluxDbVersion.Latest); } else { influxDbClient = null; } }
public InfluxDbProvider(InfluxDbConfig influxDbConfig) { if (influxDbConfig == null) { throw new ArgumentNullException("influxDbConfig"); } this.dbName = influxDbConfig.DbName; this.influxDbClient = new InfluxDbClient(influxDbConfig.Host, influxDbConfig.UserName, influxDbConfig.Password, InfluxDbVersion.Latest); }
// Binds to a user's privileges and displays them in the UI async Task BindToPrivileges(InfluxDbUser user) { grantsListView.Items.Clear(); grantsListView.BeginUpdate(); // No need for grants if this is an admin, so disable the panel if (user.IsAdmin) { grantsListView.Enabled = false; } // Otherwise render granted privileges for the user else { grantsListView.Enabled = true; var privileges = await InfluxDbClient.GetPrivilegesAsync(user.Name); if (privileges.Count() > 0) { foreach (var p in privileges) { //Console.WriteLine("{0} => read: {1}, write: {2}, all: {3}", p.Database, p.Read, p.Write, p.All); grantsListView.Items.Add(new ListViewItem(new string[] { p.Database, user.IsAdmin || p.Privilege == InfluxDbPrivileges.Read ? RequestControl.CheckMark : null, user.IsAdmin || p.Privilege == InfluxDbPrivileges.Write ? RequestControl.CheckMark : null, user.IsAdmin || p.Privilege == InfluxDbPrivileges.All ? RequestControl.CheckMark : null, }) { Tag = p }); // Assign the privilege as tag } } } // Restore any selected privilege if (SelectedPrivilegeGrant != null) { var database = selectedPrivilegeGrant.Database; foreach (ListViewItem li in grantsListView.Items) { if (li.Text == database) { li.Selected = true; break; } } } grantsListView.EndUpdate(); }
// Creates a new user async Task CreateUser() { try { // Clear dialog values createUserDialog.ClearCreateValues(); if (createUserDialog.ShowDialog(this) == DialogResult.OK) { // Get the user data var user = createUserDialog.CreateUserFromDialog(); if (user == null) { return; } // Ensure unique username foreach (ListViewItem li in usersListView.Items) { if (li.Text == user.Name) { AppForm.DisplayError("User already exists: " + user.Name, "Create Error"); return; } } // Create the user var response = await InfluxDbClient.CreateUserAsync(user.Name, createUserDialog.Password, user.IsAdmin); // Select the user and refresh the window if (response.Success) { SelectedUser = user; await ExecuteRequestAsync(); } else { AppForm.DisplayError(response.Body); } // Update interface buttons UpdateUIState(); } } catch (Exception ex) { AppForm.DisplayException(ex); } }
public void Dispose() { Client?.Dispose(); Client = null; }
protected IntegrationTests() { Client = new InfluxDbClient(IntegrationTestsRuntime.Host); }