mutation syntax error : grapgql update string - nestjs

here is my mutation . that was working fine . from yesterday it throw error on condition key
condition: "{\"data\":{\"a\":{\"source\":\"ENTITY_STATE\",\"id\":\"4b026027-7458-4ba4-9079-f3dd4f16b65b\"}},\"rules\":{\"==\":[{\"var\":\"a.on\"},false]}}"
here is my full mutation :
mutation {
rule {
create(
input: {
name: "After every minute ?"
description: "Will turn on device after every minute"
triggers: [
{
name: "TimeTrigger"
options: {
cron: "* * * * 1"
# time: "after 10 seconds"
}
}
]
condition: "{\"data\":{\"a\":{\"source\":\"ENTITY_STATE\",\"id\":\"4b026027-7458-4ba4-9079-f3dd4f16b65b\"}},\"rules\":{\"==\":[{\"var\":\"a.on\"},false]}}"
actions: [
{
name: "EntitySetStateAction"
options: {
entityId: "4b026027-7458-4ba4-9079-f3dd4f16b65b"
state: "{\"on\": true,\"thermostat.mode\": \"cool\",\"thermostat.setpoint\": 20,\"fanSpeed.mode\": \"high\"}"
# state: {on: true}
}
}
]
}
) {
id
embedded
name
description
active
actions {
options
} # triggers
# condition {rulenes data}
# triggers
}
}
}

Related

Azure Service Bus autoscaling in bicep template

On our project we are using Service Bus, for the Infrastructure as Code we are using bicep template in order to deploy this Service Bus. Lately we came to the conclusion that we should enable scaling for our service bus as we were having some serious issues with the capacity of just 1 single Message Unit.
Does anyone know if there is anyway to add the autoscaling in the bicep template for a service bus Azure Resource ? I cannot really find something in the MS official documentation.
Google didn't helped ...
If you have a look at the documentation, there is an ARM template that show how to configure autoscaling:
Automatically update messaging units of an Azure Service Bus namespace.
The equivalent bicep (using az bicep decompile) looks like this:
#description('Name of the Service Bus namespace')
param serviceBusNamespaceName string
#description('Name of the Queue')
param serviceBusQueueName string
#description('Name of the auto scale setting.')
param autoScaleSettingName string
#description('Location for all resources.')
param location string = resourceGroup().location
resource serviceBusNamespaceName_resource 'Microsoft.ServiceBus/namespaces#2021-11-01' = {
name: serviceBusNamespaceName
location: location
sku: {
name: 'Premium'
}
properties: {
}
}
resource serviceBusNamespaceName_serviceBusQueueName 'Microsoft.ServiceBus/namespaces/queues#2021-11-01' = {
parent: serviceBusNamespaceName_resource
name: '${serviceBusQueueName}'
properties: {
lockDuration: 'PT5M'
maxSizeInMegabytes: 1024
requiresDuplicateDetection: false
requiresSession: false
defaultMessageTimeToLive: 'P10675199DT2H48M5.4775807S'
deadLetteringOnMessageExpiration: false
duplicateDetectionHistoryTimeWindow: 'PT10M'
maxDeliveryCount: 10
autoDeleteOnIdle: 'P10675199DT2H48M5.4775807S'
enablePartitioning: false
enableExpress: false
}
}
resource autoScaleSettingName_resource 'Microsoft.Insights/autoscaleSettings#2021-05-01-preview' = {
name: autoScaleSettingName
location: 'East US'
tags: {
}
properties: {
name: autoScaleSettingName
enabled: true
predictiveAutoscalePolicy: {
scaleMode: 'Disabled'
scaleLookAheadTime: null
}
targetResourceUri: serviceBusNamespaceName_resource.id
profiles: [
{
name: 'Increase messaging units to 2 on weekends'
capacity: {
minimum: '2'
maximum: '2'
default: '2'
}
rules: []
recurrence: {
frequency: 'Week'
schedule: {
timeZone: 'Eastern Standard Time'
days: [
'Saturday'
'Sunday'
]
hours: [
6
]
minutes: [
0
]
}
}
}
{
name: '{"name":"Scale Out at 75% CPU and Scale In at 25% CPU","for":"Increase messaging units to 4 on weekends"}'
capacity: {
minimum: '1'
maximum: '8'
default: '2'
}
rules: [
{
scaleAction: {
direction: 'Increase'
type: 'ServiceAllowedNextValue'
value: '1'
cooldown: 'PT5M'
}
metricTrigger: {
metricName: 'NamespaceCpuUsage'
metricNamespace: 'microsoft.servicebus/namespaces'
metricResourceUri: serviceBusNamespaceName_resource.id
operator: 'GreaterThan'
statistic: 'Average'
threshold: 75
timeAggregation: 'Average'
timeGrain: 'PT1M'
timeWindow: 'PT10M'
dimensions: []
dividePerInstance: false
}
}
{
scaleAction: {
direction: 'Decrease'
type: 'ServiceAllowedNextValue'
value: '1'
cooldown: 'PT5M'
}
metricTrigger: {
metricName: 'NamespaceCpuUsage'
metricNamespace: 'microsoft.servicebus/namespaces'
metricResourceUri: serviceBusNamespaceName_resource.id
operator: 'LessThan'
statistic: 'Average'
threshold: 25
timeAggregation: 'Average'
timeGrain: 'PT1M'
timeWindow: 'PT10M'
dimensions: []
dividePerInstance: false
}
}
]
recurrence: {
frequency: 'Week'
schedule: {
timeZone: 'Eastern Standard Time'
days: [
'Saturday'
'Sunday'
]
hours: [
18
]
minutes: [
0
]
}
}
}
]
notifications: []
targetResourceLocation: 'East US'
}
}

How to set multipe values in CascadeChoiceParameter's for referencedParameters

Trying to set multiple values in CascadeChoiceParameter's for referencedParameters. What the format should be? Docs documentation said that it should be 'string', but in case of setting referencedParameters: 'param1,param2' it goes to fallback script.
here is the class:
[$class: 'CascadeChoiceParameter',
name: 'SOME_PARAM',
description: 'some description',
randomName: '',
script: [$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: true,
script: 'return ["item_1"]'
],
script: [
classpath: [],
sandbox: true,
script: """
if(PARAM_2.equals("some_value") && PARAM_3.equals("some_value")) {
return ["item_1", "item_2", "item_3"]
} else if((PARAM_2.equals("E2E_Tests") || (PARAM_2.equals("Real_API")) && PARAM_3.equals("knox_guard")) {
return ["item_1", "item_2", "item_4"]
} else {
return ["item_1"]
}
""".stripIndent()
]
],
choiceType: 'PT_SINGLE_SELECT',
referencedParameters: 'PARAM_2,PARAM_3',
filterable: false,
filterLength: 1
],
The fallback script is used if/when there is any kind of exception/error when attempting to execute the main script. In your case, there is a compilation error in the else if((PARAM_2.equals("E2E_Tests") || (PARAM_2.equals("Real_API")) && PARAM_3.equals("knox_guard")) line. All the open parenthesis haven't been closed - there are 6 open parenthesis and only 5 close parenthesis. Anyway, I haven't tested a CascadeChoiceParameter version of the pipeline. I have tested using activeChoiceReactiveParam. Below is a working job DSL:
String choicesScript = """
if(PARAM_2.equals("some_value") && PARAM_3.equals("some_value")) {
return ["item_1", "item_2", "item_3"]
} else if((PARAM_2.equals("E2E_Tests") || (PARAM_2.equals("Real_API")) && PARAM_3.equals("knox_guard"))) {
return ["item_1", "item_2", "item_4"]
} else {
return ["item_5"]
}
""".stripIndent()
String pipeline = '''
pipeline {
agent any
stages {
stage('Show parameter values') {
steps {
echo "PARAM_2: ${params.PARAM_2}, PARAM_3: ${params.PARAM_3}, SOME_PARAM: ${params.SOME_PARAM}"
}
}
}
}
'''.stripIndent()
pipelineJob('reactive-params') {
parameters {
activeChoiceParam('PARAM_2') {
description('First test parameter')
choiceType('SINGLE_SELECT')
groovyScript {
script('return ["some_value", "E2E_Tests", "Real_API"]')
}
}
activeChoiceParam('PARAM_3') {
description('Second test parameter')
choiceType('SINGLE_SELECT')
groovyScript {
script('return ["some_value", "knox_guard"]')
}
}
activeChoiceReactiveParam('SOME_PARAM') {
description('some description')
choiceType('SINGLE_SELECT')
referencedParameter('PARAM_2')
referencedParameter('PARAM_3')
groovyScript {
script(choicesScript)
fallbackScript('return ["item_1"]')
}
}
}
definition {
cps {
script(pipeline)
}
}
}

Jenkinsfile - Pipeline job stuck at input() step

I'm running terraform pipeline through Jenkinsfile, where I'm using a input(...) block for the user approval, before apply. This is the code snippet:
stage('tf_plan') {
agent {
label: 'Jenkins-Linux-Dev'
}
steps {
sh(
label: 'Terraform Plan',
script: '''
#!/usr/bin/env bash
terraform plan -input=false -no-color -out=plan.tfplan'
'''
)
}
}
stage('tf_approve') {
when { expression { return env.Action == 'apply' } }
options {
timeout( time: 1, unit: 'MINUTES' )
}
steps {
input(
message: 'Proceed with above Terraform Plan??',
ok: 'Proceed'
)
}
}
stage('tf_apply') {
agent {
label: 'Jenkins-Linux-Dev'
}
when { expression { return env.Action == 'apply' } }
steps {
sh(
label: 'Terraform Apply',
script: '''
#!/usr/bin/env bash
terraform apply -auto-approve -input=false -no-color plan.tfplan'
'''
)
}
}
stage('tf_plan') is working absolutely fine but when env.Action = 'apply', it's not moving any further after stage('tf_approve'). It's stuck at Proceed or Abort step - not moving forward at all clicking either of 'em. Any idea what might be the problem?
Any help would be very much appreciated.
-S
My setup:
Jenkins 2.277.1
Groovy 2.3
Pipeline 2.6
Pipeline Utility Steps 2.6.1
And the following code works fine:
pipeline {
agent any
parameters {
choice(choices: ['-', 'apply'], name: 'Action')
}
stages {
stage('Trigger Promotion') {
when { expression { return env.Action == 'apply' } }
options {
timeout( time: 1, unit: 'MINUTES' )
}
steps {
script {
input(
message: 'Proceed with above Terraform Plan??',
ok: 'Proceed'
)
}
}
}
}
}
Therefore, I don't think the issue is with the input step. Need more info on what's going on with Jenkins and its workers at that moment. Try grabbing logs of Jenkins main node.
P.S.: I'd suggest avoiding PascalCase variables in Groovy. It's usually used to declare classses

Python: Fetching nested dictionary values GCP Recommendations

I am trying to illicit certain key values out of an API JSON output from GCP Recommendations API using Python, and am newer to using Python. Most of the values that I am trying to illicit I can fetch without an issue, however, when I try to illicit certain values within a more deeply nested code block in the JSON, it fails with the error: TypeError: 'OperationGroup' object is not subscriptable
The full output of the JSON response is here (some of the values are changed to protect company information):
name: "projects/12345678910/locations/us-central1-a/recommenders/google.compute.instance.MachineTypeRecommender/recommendations/abcd-efg-hijk-lmnop-qrstuv-123456"
description: "Save cost by changing machine type from e2-medium to e2-small."
last_refresh_time {
seconds: 1623222401
}
primary_impact {
category: COST
cost_projection {
cost {
currency_code: "USD"
units: -12
nanos: -98539964
}
duration {
seconds: 2592000
}
}
}
content {
operation_groups {
operations {
action: "test"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/xyz/zones/us-central1-a/instances/abcname123"
path: "/machineType"
value_matcher {
matches_pattern: ".*zones/us-central1-a/machineTypes/e2-medium"
}
}
operations {
action: "replace"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/xyz/zones/us-central1-a/instances/abcname123"
path: "/machineType"
value {
string_value: "zones/us-central1-a/machineTypes/e2-small"
}
}
}
}
state_info {
state: ACTIVE
}
etag: "\"abc-123-def-456\""
recommender_subtype: "CHANGE_MACHINE_TYPE"
name: "projects/12345678910/locations/us-central1-a/recommenders/google.compute.instance.MachineTypeRecommender/recommendations/abcdefg-hijklmnop-123-456"
description: "Save cost by changing machine type from e2-medium to e2-small."
last_refresh_time {
seconds: 1623222401
}
primary_impact {
category: COST
cost_projection {
cost {
currency_code: "USD"
units: -12
nanos: -99648292
}
duration {
seconds: 2592000
}
}
}
content {
operation_groups {
operations {
action: "test"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/xyz/zones/us-central1-a/instances/instance-example1"
path: "/machineType"
value_matcher {
matches_pattern: ".*zones/us-central1-a/machineTypes/e2-medium"
}
}
operations {
action: "replace"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/xyz/zones/us-central1-a/instances/instance-example1"
path: "/machineType"
value {
string_value: "zones/us-central1-a/machineTypes/e2-small"
}
}
}
}
state_info {
state: ACTIVE
}
etag: "\"abcdefg12345\""
recommender_subtype: "CHANGE_MACHINE_TYPE"
name: "projects/12345678910/locations/us-central1-a/recommenders/google.compute.instance.MachineTypeRecommender/recommendations/abcd1234"
description: "Save cost by changing machine type from e2-medium to e2-small."
last_refresh_time {
seconds: 1623222401
}
primary_impact {
category: COST
cost_projection {
cost {
currency_code: "USD"
units: -11
nanos: -568971875
}
duration {
seconds: 2592000
}
}
}
content {
operation_groups {
operations {
action: "test"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/abcd/zones/us-central1-a/instances/instance-example2"
path: "/machineType"
value_matcher {
matches_pattern: ".*zones/us-central1-a/machineTypes/e2-medium"
}
}
operations {
action: "replace"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/abcd/zones/us-central1-a/instances/instance-example2"
path: "/machineType"
value {
string_value: "zones/us-central1-a/machineTypes/e2-small"
}
}
}
}
state_info {
state: ACTIVE
}
etag: "\"abcd1234\""
recommender_subtype: "CHANGE_MACHINE_TYPE"
Here is my code in Python:
from google.cloud import recommender
import os
client = recommender.RecommenderClient()
def main():
name = client.list_recommendations(parent='projects/xyzproject/locations/us-central1-a/recommenders/google.compute.instance.MachineTypeRecommender')
for element in name:
# print(element)
print(element.description)
print(element.primary_impact.category)
print(element.primary_impact.cost_projection.cost.currency_code)
print(element.primary_impact.cost_projection.cost.units)
print(element.state_info.state)
print(element.content.operation_groups)
for item in element.content.operation_groups:
print(item['resource_type'])
main()
The following portions of the above work:
print(element.description)
print(element.primary_impact.category)
print(element.primary_impact.cost_projection.cost.currency_code)
print(element.primary_impact.cost_projection.cost.units)
print(element.state_info.state)
print(element.content.operation_groups)
but the one that I'm having the error and trouble with is:
for item in element.content.operation_groups:
print(item['resource_type'])
Whenever I try to use that portion of the python script it fails with the error:
TypeError: 'OperationGroup' object is not subscriptable
So, can someone help me understand how I can properly tap into the JSON response and illicit the information within the below block (e.g. the 'resource_type')?
content {
operation_groups {
operations {
action: "test"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/abcd/zones/us-central1-a/instances/instance-example2"
path: "/machineType"
value_matcher {
matches_pattern: ".*zones/us-central1-a/machineTypes/e2-medium"
}
}
operations {
action: "replace"
resource_type: "compute.googleapis.com/Instance"
resource: "//compute.googleapis.com/projects/abcd/zones/us-central1-a/instances/instance-example2"
path: "/machineType"
value {
string_value: "zones/us-central1-a/machineTypes/e2-small"
}
}
}
}
I took the code in your question and rewrote it to match the Python Recommender API. The primary issue is that you are accessing internal member and field names. I have changed the code to use public interfaces.
Review the type definitions for the API:
Types for Recommender API Client
GitHub Gist: Python example demonstrating the Google Cloud Compute Recommender list recommendations api
# pip install google-cloud-recommender
from google.cloud import recommender
import os
# Enter values for your Project ID and Zone
PROJECT=
LOCATION=
RECOMMENDER = 'google.compute.instance.MachineTypeRecommender'
def print_recommendations():
client = recommender.RecommenderClient()
parent = client.recommender_path(PROJECT, LOCATION, RECOMMENDER)
recommendations = client.list_recommendations(parent=parent)
for recommendation in recommendations:
print('Recommendation:')
print(' Description: ', recommendation.description)
print(' Impact Category: ', recommendation.primary_impact.category)
print(' Currency Code: ', recommendation.primary_impact.cost_projection.cost.currency_code)
print(' Units: ', recommendation.primary_impact.cost_projection.cost.units)
print(' State: ', recommendation.state_info.state)
print('')
for op_group in recommendation.content._pb.operation_groups:
for operation in op_group.operations:
print(' Operation:')
print(' Action: ', operation.action)
print(' Resource Type: ', operation.resource_type)
print(' Path: ', operation.path)
print(' Value: ', operation.value.string_value)
print('')
print_recommendations()
Example output:
Recommendation:
Description: Save cost by changing machine type from e2-standard-4 to e2-highmem-2.
Impact Category: Category.COST
Currency Code: USD
Units: -31
State: State.ACTIVE
Operation:
Action: test
Resource Type: compute.googleapis.com/Instance
Path: /machineType
Value:
Operation:
Action: replace
Resource Type: compute.googleapis.com/Instance
Path: /machineType
Value: zones/us-east1-b/machineTypes/e2-highmem-2

Best way to do Karate match using "==" and "contains" using generic script

This question is resulting from a previous question here
Lets says our implemented server v1 and v2 response looks as follows
* def v1Response = { id: "1", name: "awesome" }
* def v2Response = { id: "2", name: "awesome", value: "karate" }
Similarly we define the client schema for v1 and v2 like as follows
* def v1Schema = { id: "#string", name: "#string }
* def v2Schema = { id: "#string", name: "#string, value: "#string" }
From the above given data, all I want is to test following three cases in a single generic line and they must pass
1. * match v1Response == v1Schema
2. * match v2Response == v2Schema
3. * match v2Response contains v1Schema
using a single generic line as follows
* match response ==/contains schema <--- should be able to test all above three cases above and they must pass.
See my proposed suggestion in previous question for maybe possible ways to achieve this.
I have already tried the solution noted in previous question using karate.filterKeys(), however the third case will fail because it focuses on filtering the keys not the comparison itself so the below last line will not be able to test all three cases above.
* def response = { id: "2", name: "awesome", value: "karate" }
* def schema = { id: "#string", name: "#string" }
* match response == karate.filterKeys(schema, response) <--- This will fail
For an accepted answer all three case must pass
Looks like you over-engineered so much you forgot about contains :P
* def schemas =
"""
{
v1: { id: "#string", name: "#string" },
v2: { id: "#string", name: "#string", value: "#string" }
}
"""
* def env = 'v1'
* def response = { id: "1", name: "awesome" }
* match response contains karate.filterKeys(schemas[env], response)
* def response = { id: "2", name: "awesome", value: "karate" }
* match response contains karate.filterKeys(schemas[env], response)
* def env = 'v2'
* def response = { id: "1", name: "awesome" }
* match response contains karate.filterKeys(schemas[env], response)
* def response = { id: "2", name: "awesome", value: "karate" }
* match response contains karate.filterKeys(schemas[env], response)

Resources