Application Insights requests count metrics vs query don't match - azure-application-insights

I am trying to retrieve the number of requests for the last day from Application Insights using the API.
When I do it via the /metrics/requests/count?timespan=P1D endpoint
I get a sum of 35871.
But if I do it via the
/query?query=requests | where timestamp > ago(1d) | count; endpoint
I get a count of 4510.
Lastly, if I do it via the
/events/requests?timespan=P1D&$count=true endpoint I get a
#odata.count of 4510, the same as from "query".
Why may the requests count difference between metrics and query be so big?
Edit:
I have run the following query in Application Insights Logs:
requests
| summarize totalCount=sum(itemCount) by bin(timestamp, 1d)
And that returns (currently it is 12/7/2021, 8:14:47.562 PM):
timestamp [UTC] totalCount
12/7/2021, 12:00:00.000 AM 35,871
That retrieves (I believe) the number of requests since the beginning of today.
Surprisingly, that matches the count obtained via /metrics:
{'value': {'start': '2021-12-06T20:13:46.054Z', 'end': '2021-12-07T20:13:46.054Z', 'requests/count': {'sum': 35871}}}
But the range of dates via /metrics/ covers roughly the last 24h (1d).

I think that the requests table in "Application Insights Logs" (/query endpoint) contains a list of requests where each entry can be the same name (uri) but with a different resultCode.
I haven't found documentation though that clearly suggests that.
With that assumption I have been able to match the requests count to that of /metrics.
Here is the query that I was chasing:
let TOTAL = requests | where timestamp > ago(1d) | summarize TotalRequests=sum(itemCount) | extend Foo=1;
let CACHED_TOTAL = materialize(TOTAL);
let FAILED = requests
| where timestamp > ago(1d)
| where resultCode hasprefix "4"
| summarize Failed=sum(itemCount)
| extend Foo=1;
let CACHED_FAILED = materialize(FAILED);
CACHED_FAILED
| join kind=inner CACHED_TOTAL on Foo
| extend PercentFailed = round(todouble(Failed * 100) / TotalRequests, 2)
| project TotalRequests, Failed, PercentFailed;

Related

Modifying Kusto to get the logs output

I have my below kql which when ran in Log Analytics give me the right result. But Now I have moved my logs to a storage account and created an ADX external table to query the same logs using Kusto. however I am finding it difficult to Query as same query wont work and will need some modification. I would need help if someone can advice on what all changes should I do in existing Kusto to get the same result.
In log Analytics this works:
"AzureDiagnostics
| where Category == 'kube-audit'
| where TimeGenerated between (datetime("$querystart") .. datetime("$queryend"))
| where (strlen(log_s) >= 32000
and not(log_s contains \"aksService\")
and not(log_s contains \"system:serviceaccount:crossplane-system:crossplane\")
and not(log_s contains \"system:serviceaccount:elastic-system:elastic-operator\")
and not(log_s contains \"system:serviceaccount:internal-services:cert-manager-cainjector\")
and not(log_s contains \"system:serviceaccount:internal-services:spinnaker\")
and not(log_s contains \"system:serviceaccount:kube-system:daemon-set-controller\")
and not(log_s contains \"system:serviceaccount:kube-system:deployment-controller\")
and not(log_s contains \"system:serviceaccount:kube-system:endpoint-controller\")
and not(log_s contains \"system:serviceaccount:kube-system:node-controller\")
and not(log_s contains \"system:serviceaccount:kube-system:replicaset-controller\")
and not(log_s contains \"system:serviceaccount:kube-system:statefulset-controller\"))
or strlen(log_s) < 32000
| extend op = parse_json(log_s)
| where not(tostring(op.verb) in (\"list\", \"get\", \"watch\"))
| where not(tostring(op.user.username) hasprefix \"system:\")
| where not(tostring(op.user.username) in (\"hcpService\", \"aksService\", \"aksProblemDetector\", \"readinessChecker\", \"nodeclient\", \"masterclient\"))
| where substring(tostring(op.responseStatus.code), 0, 1) == \"2\"
| where not(tostring(op.requestURI) in (\"/apis/authorization.k8s.io/v1/selfsubjectaccessreviews\"))
| extend user = op.user.username
| extend decision = tostring(parse_json(tostring(op.annotations)).[\"authorization.k8s.io/decision\"])
| extend requestURI = tostring(op.requestURI)
| extend name = tostring(parse_json(tostring(op.objectRef)).name)
| extend namespace = tostring(parse_json(tostring(op.objectRef)).namespace)
| extend verb = tostring(op.verb)
| project TimeGenerated, SubscriptionId, ResourceId, namespace, name, requestURI, verb, decision, ['user']
| order by TimeGenerated asc"
and the output in Log Analytics for query
AzureDiagnostics
| where Category == 'kube-audit'
On exporting to storage account and then creating an External table in ADX over it, I dont see the same schema, the result I have in ADX external table for kube-audit is something like this:
"operationName": Microsoft.ContainerService/managedClusters/diagnosticLogs/Read,
"category": kube-audit,
"ccpNamespace": 5c40f,
"resourceId": /SUBSCRIPTIONS/53AEB/RESOURCEGROUPS/AZURE-DEV/PROVIDERS/MICROSOFT.CONTAINERSERVICE/MANAGEDCLUSTERS/AZURE-DEV,
"properties": {
"log": "{\"kind\":\"Event\",\"apiVersion\":\"audit.k8s.io/v1\",\"level\":\"Request\",\"auditID\":\"d80ca0b72-75eaf\",\"stage\":\"ResponseComplete\",\"requestURI\":\"/apis/apps/v1/namespaces/events/deployments/api/scale\",\"verb\":\"get\",\"user\":{\"username\":\"system:serviceaccount:kube-system:horizontal-pod-autoscaler\",\"uid\":\"d5d7-ba1cfb172033\",\"groups\":[\"system:serviceaccounts\",\"system:serviceaccounts:kube-system\",\"system:authenticated\"]},\"sourceIPs\":[\"100.11.11.0\"],\"userAgent\":\"kube-controller-manager/v1.22.6 (linux/amd64) kubernetes/0795921/system:serviceaccount:kube-system:horizontal-pod-autoscaler\",\"objectRef\":{\"resource\":\"deployments\",\"namespace\":\"events\",\"name\":\"api\",\"apiGroup\":\"apps\",\"apiVersion\":\"v1\",\"subresource\":\"scale\"},\"responseStatus\":{\"metadata\":{},\"code\":200},\"requestReceivedTimestamp\":\"2022-05-23T13:44:59.985416Z\",\"stageTimestamp\":\"2022-05-23T13:45:00.002107Z\",\"annotations\":{\"authorization.k8s.io/decision\":\"allow\",\"authorization.k8s.io/reason\":\"RBAC: allowed by ClusterRoleBinding \\\"system:controller:horizontal-pod-autoscaler\\\" of ClusterRole \\\"system:controller:horizontal-pod-autoscaler\\\" to ServiceAccount \\\"horizontal-pod-autoscaler/cfxyz\\\"\"}}\n",
"stream": "stdout",
"pod": "kube-apiserver-7d-q6v"
},
"time": 2022-05-23T13:45:00Z,
"Cloud": AzureCloud,
"Environment": prod,
"UnderlayClass": hcp-underlay,
"UnderlayName": hcp-underlay-norteurope-cx-624,
External table schema:
"TableName": logsKube,
"Schema": operationName:string,category:string,ccpNamespace:string,resourceId:string,properties:dynamic,['time']:datetime,Cloud:string,Environment:string,UnderlayClass:string,UnderlayName:string,
"DatabaseName": logsstorage,
"Folder": ,
"DocString": ,
How can I run the above query in ADX to get the result?
Create the external table manually, using the original columns' names.
Create and alter Azure Storage external tables
Should be somthing like that:
.create-or-alter external table logsKube (TenantId:string,TimeGenerated:datetime,ResourceId:string,Category:string,ResourceGroup:string,SubscriptionId:string,ResourceProvider:string,Resource:string,ResourceType:string,OperationName:string,ResultType:string,CorrelationId:string,ResultDescription:string,Tenant_g:string,JobId_g:string,RunbookName_s:string,StreamType_s:string,Caller_s:string,requestUri_s:string,Level:string,DurationMs:string,CallerIPAddress:string,OperationVersion:string,ResultSignature:string,id_s:string,status_s:string,LogicalServerName_s:string,Message:string,clientInfo_s:string,httpStatusCode_d:string,identity_claim_appid_g:string,identity_claim_http_schemas_microsoft_com_identity_claims_objectidentifier_g:string,userAgent_s:string,ruleName_s:string,identity_claim_http_schemas_xmlsoap_org_ws_2005_05_identity_claims_upn_s:string,systemId_g:string,isAccessPolicyMatch_b:string,EventName_s:string,httpMethod_s:string,subnetId_s:string,type_s:string,instanceId_s:string,macAddress_s:string,vnetResourceGuid_g:string,direction_s:string,subnetPrefix_s:string,primaryIPv4Address_s:string,conditions_sourcePortRange_s:string,priority_d:string,conditions_destinationPortRange_s:string,conditions_destinationIP_s:string,conditions_None_s:string,conditions_sourceIP_s:string,httpVersion_s:string,matchedConnections_d:string,startTime_t:string,endTime_t:string,DatabaseName_s:string,clientIP_s:string,host_s:string,requestQuery_s:string,sslEnabled_s:string,clientPort_d:string,httpStatus_d:string,receivedBytes_d:string,sentBytes_d:string,timeTaken_d:string,resultDescription_ErrorJobs_s:string,resultDescription_ChildJobs_s:string,identity_claim_http_schemas_microsoft_com_identity_claims_scope_s:string,workflowId_s:string,resource_location_s:string,resource_workflowId_g:string,resource_resourceGroupName_s:string,resource_subscriptionId_g:string,resource_runId_s:string,resource_workflowName_s:string,_schema_s:string,correlation_clientTrackingId_s:string,properties_sku_Family_s:string,properties_sku_Name_s:string,properties_tenantId_g:string,properties_enabledForDeployment_b:string,code_s:string,resultDescription_Summary_MachineId_s:string,resultDescription_Summary_ScheduleName_s:string,resultDescription_Summary_Status_s:string,resultDescription_Summary_StatusDescription_s:string,resultDescription_Summary_MachineName_s:string,resultDescription_Summary_TotalUpdatesInstalled_d:string,resultDescription_Summary_RebootRequired_b:string,resultDescription_Summary_TotalUpdatesFailed_d:string,resultDescription_Summary_InstallPercentage_d:string,resultDescription_Summary_StartDateTimeUtc_t:string,resource_triggerName_s:string,resultDescription_Summary_InitialRequiredUpdatesCount_d:string,properties_enabledForTemplateDeployment_b:string,resultDescription_Summary_EndDateTimeUtc_s:string,resultDescription_Summary_DurationInMinutes_s:string,resource_originRunId_s:string,properties_enabledForDiskEncryption_b:string,resource_actionName_s:string,correlation_actionTrackingId_g:string,resultDescription_Summary_EndDateTimeUtc_t:string,resultDescription_Summary_DurationInMinutes_d:string,conditions_protocols_s:string,identity_claim_ipaddr_s:string,ElasticPoolName_s:string,identity_claim_http_schemas_microsoft_com_claims_authnmethodsreferences_s:string,RunOn_s:string,query_hash_s:string,SourceSystem:string,MG:string,ManagementGroupName:string,Computer:string,RawData:string,certificatePolicyProperties_certificateProperties_subject_s:string,certificatePolicyProperties_certificateProperties_validityInMonths_d:string,certificatePolicyProperties_keyProperties_type_s:string,certificatePolicyProperties_keyProperties_size_d:string,certificatePolicyProperties_keyProperties_export_b:string,certificatePolicyProperties_secretProperties_type_s:string,certificatePolicyProperties_certificateIssuerProperties_name_s:string,error_state_d:string,location_s:string,Tenant_s:string,RecoveryJobDestination_s:string,RecoveryJobRPLocation_s:string,RecoveryLocationType_s:string,upstreamSourcePort_s:string,ProtectedContainerOSType_s:string,ProtectedContainerOSVersion_s:string,GatewayManagerVersion_s:string,targetResources_CertificateName_s:string,displayResourceId_s:string,executionClusterType_s:string,clientResponseTime_d:string,targetResources_NodeConfigurationName_s:string,targetResources_NodeId_g:string,targetResources_CredentialId_g:string,targetResources_CredentialName_s:string,targetResources_DscConfigurationName_s:string,targetResources_VariableId_g:string,targetResources_VariableName_s:string,targetResources_RunbookId_g:string,targetResources_RunbookName_s:string,targetResources_ModuleId_g:string,targetResources_ModuleName_s:string,targetResources_ScheduleId_g:string,targetResources_ScheduleName_s:string,clientInfo_TenantId_g:string,clientInfo_Issuer_s:string,clientInfo_ObjectId_g:string,clientInfo_AppId_g:string,targetResources_JobScheduleId_g:string,targetResources_JobName_s:string,clientInfo_IpAddress_s:string,clientInfo_PrincipalName_s:string,clientInfo_ClientRequestId_g:string,targetResources_Resource_s:string,targetResources_JobId_g:string,targetResources_JobName_g:string,clusterType_s:string,identity_claim_upn_s:string,DataCenterName_s:string,identity_claim_scp_s:string,identity_claim_unique_name_s:string,identity_claim_amr_s:string,identity_claim_oid_g:string,identity_claim_home_oid_g:string,removedAccessPolicy_Permissions_storage_s:string,replicationHealthErrors_s:string,eventGridEventProperties_topic_s:string,eventGridEventProperties_subject_s:string,eventGridEventProperties_eventType_s:string,eventGridEventProperties_eventTime_t:string,eventGridEventProperties_data_Id_s:string,eventGridEventProperties_data_VaultName_s:string,eventGridEventProperties_data_ObjectType_s:string,eventGridEventProperties_data_ObjectName_s:string,eventGridEventProperties_data_Version_s:string,eventGridEventProperties_dataVersion_s:string,properties_networkAcls_bypass_s:string,properties_networkAcls_defaultAction_s:string,properties_softDeleteRetentionInDays_d:string,error_number_d:string,Severity:string,user_defined_b:string,state_d:string,PolicyUniqueId_s:string,ProtectedContainerName_g:string,identity_claim_http_schemas_xmlsoap_org_ws_2005_05_identity_claims_name_s:string,retryHistory_s:string,network_s:string,nexthop_s:string,locprf_s:string,weight_s:string,path_s:string,addressfamily_s:string,ClientOperationId_g:string,CorrelationRequestId_g:string,Region_s:string,ScaleUnit_s:string,ActivityId_g:string,EventTimeString_s:string,EventProperties_s:string,SKU_s:string,virtual_core_count_s:string,avg_cpu_percent_s:string,reserved_storage_mb_s:string,storage_space_used_mb_s:string,io_requests_s:string,io_bytes_read_s:string,io_bytes_written_s:string,timeOfOccurence_t:string,eventType_s:string,description_s:string,healthErrors_s:string,logId_g:string,removedAccessPolicy_TenantId_g:string,removedAccessPolicy_ObjectId_g:string,removedAccessPolicy_Permissions_keys_s:string,removedAccessPolicy_Permissions_secrets_s:string,removedAccessPolicy_Permissions_certificates_s:string,addedAccessPolicy_TenantId_g:string,addedAccessPolicy_ObjectId_g:string,addedAccessPolicy_Permissions_keys_s:string,addedAccessPolicy_Permissions_secrets_s:string,addedAccessPolicy_Permissions_certificates_s:string,addedAccessPolicy_Permissions_storage_s:string,properties_enableSoftDelete_b:string,JobOperationSubType_s:string,DataTransferredInMB_s:string,ProtectedInstanceCount_s:string,StorageConsumedInMBs_s:string,StorageType_s:string,StorageName_s:string,OldestRecoveryPointTime_s:string,OldestRecoveryPointLocation_s:string,LatestRecoveryPointTime_s:string,LatestRecoveryPointLocation_s:string,BackupItemFrontEndSize_s:string,StorageUniqueId_s:string,AlertConsolidationStatus_s:string,CountOfAlertsConsolidated_s:string,AlertRaisedOn_s:string,AlertCode_s:string,RecommendedAction_s:string,AlertUniqueId_s:string,AlertType_s:string,AlertStatus_s:string,AlertOccurrenceDateTime_s:string,AlertSeverity_s:string,TelemetryProperties_s:string,AdHocOrScheduledJob_s:string,affectedResourceId_s:string,JobUniqueId_g:string,JobOperation_s:string,JobStatus_s:string,JobFailureCode_s:string,JobStartDateTime_s:string,JobDurationInSecs_s:string,RecoveryJobRPDateTime_s:string,affectedResourceName_s:string,affectedResourceId_g:string,affectedResourceType_s:string,logId_d:string,DeploymentUnit_s:string,CloudStorageInBytes_s:string,ProtectedInstances_s:string,trustedService_s:string,OptionName_s:string,OptionDesiredState_s:string,OptionActualState_s:string,OptionDisableReason_s:string,IsDisabledBySystem_d:string,DatabaseDesiredMode_s:string,DatabaseActualMode_s:string,RegisteredContainerId_s:string,ProtectedServerType_s:string,ProtectedServerFriendlyName_s:string,BackupManagementServerUniqueId_s:string,BackupItemId_s:string,ProtectedServerName_s:string,ProtectionState_s:string,ProtectedServerUniqueId_s:string,exec_type_d:string,wait_category_s:string,total_query_wait_time_ms_d:string,max_query_wait_time_ms_d:string,is_parameterizable_s:string,statement_type_s:string,statement_key_hash_s:string,query_param_type_d:string,interval_start_time_d:string,interval_end_time_d:string,logical_io_writes_d:string,max_logical_io_writes_d:string,physical_io_reads_d:string,max_physical_io_reads_d:string,logical_io_reads_d:string,max_logical_io_reads_d:string,execution_type_d:string,count_executions_d:string,cpu_time_d:string,max_cpu_time_d:string,dop_d:string,max_dop_d:string,rowcount_d:string,max_rowcount_d:string,query_max_used_memory_d:string,max_query_max_used_memory_d:string,duration_d:string,max_duration_d:string,num_physical_io_reads_d:string,max_num_physical_io_reads_d:string,log_bytes_used_d:string,max_log_bytes_used_d:string,query_id_d:string,plan_id_d:string,query_plan_hash_s:string,statement_sql_handle_s:string,tags_displayName_s:string,error_code_s:string,error_message_s:string,start_utc_date_t:string,end_utc_date_t:string,wait_type_s:string,delta_max_wait_time_ms_d:string,delta_signal_wait_time_ms_d:string,delta_wait_time_ms_d:string,delta_waiting_tasks_count_d:string,LogBackupFrequency_s:string,LogBackupRetentionDuration_s:string,PolicyTimeZone_s:string,PolicyName_s:string,BackupFrequency_s:string,BackupTimes_s:string,BackupDaysOfTheWeek_s:string,DailyRetentionDuration_s:string,DailyRetentionTimes_s:string,ProtectedContainerFriendlyName_s:string,ProtectedContainerWorkloadType_s:string,ProtectedContainerName_s:string,ProtectedContainerProtectionState_s:string,ProtectedContainerLocation_s:string,ProtectedContainerType_s:string,listenerName_s:string,backendPoolName_s:string,backendSettingName_s:string,originalRequestUriWithArgs_s:string,transactionId_g:string,sslCipher_s:string,sslProtocol_s:string,sslClientVerify_s:string,sslClientCertificateFingerprint_s:string,sslClientCertificateIssuerName_s:string,serverRouted_s:string,serverStatus_s:string,serverResponseLatency_s:string,originalHost_s:string,EndpointName_s:string,Status_s:string,NodeId_g:string,NodeName_s:string,NodeComplianceStatus_s:string,DscReportId_g:string,DscReportStatus_s:string,LastSeenTime_t:string,ReportStartTime_t:string,ReportEndTime_t:string,ConfigurationMode_s:string,HostName_s:string,NumberOfResources_d:string,IPAddress:string,DscResourceId_s:string,DscResourceName_s:string,DscResourceStatus_s:string,DscModuleName_s:string,DscModuleVersion_s:string,DscConfigurationName_s:string,DscResourceDuration_d:string,ErrorCode_s:string,ErrorMessage_s:string,BackupItemProtectionState_s:string,BackupItemAppVersion_s:string,BackupItemUniqueId_s:string,BackupItemName_s:string,BackupItemFriendlyName_s:string,BackupItemType_s:string,BackupManagementType_s:string,ProtectedContainerUniqueId_s:string,PolicyUniqueId_g:string,timeStamp_t:string,lastRecoveryPoint_t:string,latestAppConsistentRecoveryPoint_t:string,replicatingDisksCount_d:string,uploadRPOInSeconds_d:string,uploadRPOUpdateTime_t:string,processedRPOInSeconds_d:string,processedRPOUpdateTime_t:string,EventId_d:string,VaultUniqueId_s:string,VaultName_s:string,AzureDataCenter_s:string,VaultTags_s:string,ResourceGroupName_s:string,StorageReplicationType_s:string,SchemaVersion_s:string,State_s:string,InstanceName_s:string,Value_s:string,ProviderName_s:string,TaskName_s:string,agentVersion_s:string,recoveryRegion_s:string,multiVmGroupId_g:string,multiVmGroupName_s:string,multiVmGroupCreateOption_s:string,recoveryNetworkId_s:string,lastHeartbeat_t:string,multiVmSyncStatus_s:string,targetVmNicDetails_s:string,recoveryServicesProviderId_g:string,replicationHealth_s:string,failoverHealth_s:string,name_s:string,id_g:string,primaryFabricName_s:string,recoveryFabricName_s:string,primaryFabricType_s:string,recoveryFabricType_s:string,primaryContainerName_s:string,recoveryContainerName_s:string,protectionState_s:string,activeLocation_s:string,policyName_s:string,replicationProviderName_s:string,osFamily_s:string,initialReplicationProgressPercentage_d:string,itemType_s:string,failoverHealthErrors_s:string,rpoInSeconds_d:string,lastRpoCalculatedTime_t:string,version_s:string,attrs_s:string,containerID_s:string,ccpNamespace_s:string,log_s:string,stream_s:string,pod_s:string,Cloud_s:string,Environment_s:string,UnderlayClass_s:string,UnderlayName_s:string,msg_s:string,AdditionalFields:string,Type:string,_ResourceId:string)
kind=storage
dataformat=csv
(
h#'abfss://filesystem#storageaccount.dfs.core.windows.net/path;secretKey'
)
with (includeHeaders=all)

KQL / Azure Resource Graph Explorer: combine values from multiple records

I am trying to fetch all public ips and fqdns configured for a set of load balancers in azure resource graph explorer. I am getting all the data I need with the following query:
Resources
| where type =~ 'Microsoft.Network/loadBalancers'
| where subscriptionId =~ '11111111-2222-3333-4444-555555555555'
| where resourceGroup =~ 'resource-group-name'
| mv-expand ipConfig=properties.frontendIPConfigurations
| project name, publicIpId = tostring(ipConfig.properties.publicIPAddress.id)
| join kind=leftouter (
Resources
| where type =~ 'microsoft.network/publicipaddresses'
| project publicIpId = id, publicIpAddress = tostring(properties.ipAddress), fqdn = tostring(properties.dnsSettings.fqdn)
)
on publicIpId
| summarize by name, publicIpAddress, fqdn
But the result is in the form of:
name publicIpAddress fqdn
outbound-lb x.y.z.1 a domain
frontend-lb x.y.z.2 another domain
frontend-lb x.y.z.3 third domain
services-lb x.y.z.4 fourth domain
and what I need is:
name publicIpAddress fqdn
outbound-lb x.y.z.1 a domain
frontend-lb x.y.z.2, x.y.z.3 another domain, third domain
services-lb x.y.z.4 fourth domain
I have been looking at the summarize make_list() function but was not successful in getting the result I need!
you could try replacing this:
| summarize by name, publicIpAddress, fqdn
with this:
| summarize publicIpAddress = strcat_array(make_set(publicIpAddress), ", "),
fqdn = strcat_array(make_set(fqdn), ", ")
by name

kusto function to parse json which is number

i could not able to parse the below json value , I tried with parse_json() and todynamic() ,I m getting the result column values to be empty
]1
the issue is that your payload includes an internal invalid JSON payload.
it is possible to "fix" it using the query language (see usages of replace() in the example below), however it'd be best if you can write a valid JSON payload to begin with.
try running this:
print s = #'{"pipelineId":"63dfc1f6-5a43-5bca-bffe-6a36a435e19d","vmId":"9252382a-814f-4d02-9b1b-305db4caa208/usl-exepipe-dev/westus/usl-exepipe-lab-dev/asuvp306563","artifactResult":{"Id":"execution-job-2","SourceName":"USL Repository","ArtifactName":"install-lcu","Status":"Succeeded","Parameters":null,"Log":"[{\"code\":\"ComponentStatus/StdOut/succeeded\",\"level\":\"Info\",\"displayStatus\":\"Provisioning succeeded\",\"message\":\"2020-06-02T14:33:04.711Z | I | Starting artifact ''install-lcu''\r\n2020-06-02T14:33:04.867Z | I | Starting Installation\r\n2020-06-02T14:33:04.899Z | I | C:\\USL\\LCU\\4556803.msu Exists.\r\n2020-06-02T14:33:04.914Z | I | Starting installation process ''C:\\USL\\LCU\\4556803.msu /quiet /norestart''\r\n2020-06-02T14:43:14.169Z | I | Process completed with exit code ''3010''\r\n2020-06-02T14:43:14.200Z | I | Need to restart computer after hotfix 4556803 installation\r\n2020-06-02T14:43:14.200Z | I | Finished Installation\r\n2020-06-02T14:43:14.200Z | I | Artifact ''install-lcu'' succeeded\r\n\",\"time\":null},{\"code\":\"ComponentStatus/StdErr/succeeded\",\"level\":\"Info\",\"displayStatus\":\"Provisioning succeeded\",\"message\":\"\",\"time\":null}]","DeploymentLog":null,"StartTime":"2020-06-02T14:32:40.9882134Z","ExecutionTime":"00:11:21.2468597","BSODCount":0},"attempt":1,"instanceId":"a301aaa0c2394e76832867bfeec04b5d:0","parentInstanceId":"78d0b036a5c548ecaafc5e47dcc76ee4:2","eventName":"Artifact Result"}'
| mv-expand log = parse_json(replace("\r\n", " ", replace(#"\\", #"\\\\", tostring(parse_json(tostring(parse_json(s).artifactResult)).Log))))
| project log.code, log.level, log.displayStatus, log.message

how to delete an account after a post request

On my method accountRepo.deleteAll()
return error:
2020-06-04 15:37:05.069 ERROR 78168 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : ОШИБКА: UPDATE or DELETE in table "account" violates foreign key constraint "fk8k31xl4ld2m810mxfkqp2xg8g" from table "tokens"
Details: on a key (account_id)=(2) there are still links in the table "tokens".
2020-06-04 15:37:05.071 INFO 78168 --- [ main] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
What could be the problem? This happens when creating a post-request with the registration of a user who will fall into accountRepo
My test and post-request:
#Test
#Throws(Exception::class)
fun shouldRegistrationExpected201() {
val headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_JSON
val request = HttpEntity<String>("{\"username\": \"holker228\", \"password\": \"123456QQwerty&&\",\"email\":\"test2#mail.ru\",\"is_collective\": \"false\" }", headers)
val responseEntity = restTemplate.postForEntity("http://localhost:$port/api/user/registration", request, String::class.java)
assertEquals(responseEntity.statusCode, HttpStatus.CREATED)
}
The issue seems to be in constrains configured in your database. BTW, which one do you use? In your particular case the constraint disallows DELETE (UPDATE?) operation as the row you're trying to delete seems to have dependent rows in another table.
E.g, imagine you have a table "users" and "comments":
users:
-------------
| ID | Name |
-------------
| 1 | Max |
-------------
| 2 | Vova |
-------------
| 3 | Vlad |
-------------
comments:
---------------------------------
| ID | User ID | Text |
---------------------------------
| 1 | 1 | Max was here! |
---------------------------------
| 2 | 1 | Vova + Vlad = ❤️ |
---------------------------------
| 3 | 2 | Don't listen to Max! |
---------------------------------
Here, if the constrains are configured, you cannot delete Max (1) or Vova (2) from "users" as they have comments. Imagine, you're rendering an HTML page and you need to render a comment's author's name? What would you do, if the author is deleted? (well, you can use "Anonymous", but let's not think about it). You cannot either change Max's or Vova's IDs for the same reason. So that's what constraints are for: they prevent such unconsistencies.
Ways to deal with this situation:
Update the related entities in the same transaction.
Use CASCADE for DELETEs. Take a look at this answer, for example
Freeze the IDs and do not change them.

Keystone client project list does not display all the projects

I am trying to list all the keystone projects present on my setup. The snippet i am using displays only few of them.
CODE-1:
from keystoneclient.auth.identity import v3
from keystoneclient import session
from keystoneclient.v3 import client as ksclient3
auth_url = "http://192.16.66.10:5000/v3"
token = '0112efcb75e9411b965b423edb321827'
auth = v3.Token(auth_url=auth_url, token=token, unscoped=True)
sess = session.Session(auth=auth)
ks = ksclient3.Client(session=sess);
project_list = [t.name for t in ks.projects.list(user=sess.get_user_id())]
print project_list
OUTPUT
[A', B', C']
CODE-2
from keystoneclient import session
from keystoneclient.v3 import client
from keystoneclient.auth.identity import v3
auth = v3.Password(auth_url='http://127.0.0.1:5000/v3',user_id='idm',password='idm',project_id='2545070293684905b9623095768b019d')
sess = session.Session(auth=auth)
keystone = client.Client(session=sess)
keystone.users.list()
OUTPUT
keystoneclient.exceptions.Unauthorized: The request you have made requires authentication. (HTTP 401)
EXPECTED OUTPUT
openstack project list
+----------------------------------+----------------+
| ID | Name |
+----------------------------------+----------------+
| 3efabc809570458180b2e20ce099ef1a | A |
| 546636e4532246f9a440e44deaad82d6 | B |
| 63494b0b0e164e7e82281c94efc709e4 | C |
| 71dbcec67a3e49979a9a9f519409785d | D |
| 8699a715c6834ac1a42350e593879695 | E |
| af88b7d76ab44e13ba73b80b39d2644b | F |
| b431f905a52448298980a0fe0b7751be | G |
| ba3053eb5c534052914f133aa065865d | H |
+----------------------------------+----------------+
Things i want to understand:
Why CODE-1 displays few of the them from the list
Why CODE-2 fails
How to get the keystone project IDS from keystone client
Why CODE-1 displays few of the them from the list
Your code does filter the tenants, if you like to see all tenants list do not filter them like this:
ks.projects.list()
Your filter "user=sess.get_user_id()" returns all tenants that was created by current user.
Why CODE-2 fails
I suppose the error is in args, you give user_id='idm', if you use user name, then argument should be username='idm', if you pass in arg user_id, then you need to pass user id, eg user_id='56d88dd0a3ab4c4c8d1d15534352d7de'
You can take id from horizon
http://localhost/horizon/identity/users/
In source code there are example of client creation:
from keystoneauth1.identity import v3
from keystoneauth1 import session
from keystoneclient.v3 import client
auth = v3.Password(user_domain_name=DOMAIN_NAME,
username=USER,
password=PASS,
project_domain_name=PROJECT_DOMAIN_NAME,
project_name=PROJECT_NAME,
auth_url=KEYSTONE_URL)
sess = session.Session(auth=auth)
keystone = client.Client(session=sess)
keystone.projects.list()
user = keystone.users.get(USER_ID)
user.delete()
How to get the keystone project IDS from keystone client
If you like to see all tenants ids(suppose admin credentials)
project_list = [proj.id for proj in ks.projects.list(all_tenants=True)]

Resources