Using the below code its possible to update the start up policy of ntpd service in an ESXi server,
con = connect.SmartConnect(host=host, user=user, pwd=pwd)
content = con.RetrieveContent()
cv = content.viewManager.CreateContainerView(
container=content.rootFolder, type=[vim.HostSystem], recursive=True)
for child in cv.view:
child.configManager.serviceSystem.UpdatePolicy(id='ntpd', policy='on')
There is no clue in the service
(vim.host.Service) {
dynamicType = <unset>,
dynamicProperty = (vmodl.DynamicProperty) [],
key = 'ntpd',
label = 'NTP Daemon',
required = false,
uninstallable = false,
running = false,
ruleset = (str) [
'ntpClient'
],
policy = 'off',
sourcePackage = (vim.host.Service.SourcePackage) {
dynamicType = <unset>,
dynamicProperty = (vmodl.DynamicProperty) [],
sourcePackageName = 'esx-base',
description = 'This VIB contains all of the base functionality of
vSphere ESXi.'
}
}
But how to mark the NTP Client Enabled check box for ESXi using Pyvmomi?
VMware version - 6.0.0
host.configManager.firewallSystem.EnableRuleset(id='ntpClient')
Related
I need to pass the database host name (that is dynamically generated) as an environmental variable into my task definition. I thought I could set locals and have the variable map refer to a local but it seems to not work, as I receive this error: “error="failed to check table existence: dial tcp: lookup local.grafana-db-address on 10.0.0.2:53: no such host". I am able to execute the terraform plan without issues and the code works when I hard code the database host name, but that is not optimal.
My Variables and Locals
//MySql Database Grafana Username (Stored as ENV Var in Terraform Cloud)
variable "username_grafana" {
description = "The username for the DB grafana user"
type = string
sensitive = true
}
//MySql Database Grafana Password (Stored as ENV Var in Terraform Cloud)
variable "password_grafana" {
description = "The password for the DB grafana password"
type = string
sensitive = true
}
variable "db-port" {
description = "Port for the sql db"
type = string
default = "3306"
}
locals {
gra-db-user = var.username_grafana
}
locals {
gra-db-password = var.password_grafana
}
locals {
db-address = aws_db_instance.grafana-db.address
}
locals {
grafana-db-address = "${local.db-address}.${var.db-port}"
}
variable "app_environments_vars" {
type = list(map(string))
description = "Database environment variables needed by Grafana"
default = [
{
"name" = "GF_DATABASE_TYPE",
"value" = "mysql"
},
{
"name" = "GF_DATABASE_HOST",
"value" = "local.grafana-db-address"
},
{
"name" = "GF_DATABASE_USER",
"value" = "local.gra-db-user"
},
{
"name" = "GF_DATABASE_PASSWORD",
"value" = "local.gra-db-password"
}
]
}
Task Definition Variable reference
"environment": ${jsonencode(var.app_environments_vars)},
Thank you to everyone who has helped me with this project. I am new to all of this and could not have done it without help from this community.
You can't use dynamic references in your app_environments_vars. So your default values "value" = "local.grafana-db-address" will never get resolved by TF. If will be just a literal string "local.grafana-db-address".
You have to modify your code so that all these dynamic references in app_environments_vars get populated in locals.
UPDATE
Your app_environments_vars should be local variable for it to be resolved:
locals {
app_environments_vars = [
{
"name" = "GF_DATABASE_TYPE",
"value" = "mysql"
},
{
"name" = "GF_DATABASE_HOST",
"value" = local.grafana-db-address
},
{
"name" = "GF_DATABASE_USER",
"value" = local.gra-db-user
},
{
"name" = "GF_DATABASE_PASSWORD",
"value" = local.gra-db-password
}
]
}
then you pass that local to your template for the task definition.
I am attempting (and can successfully do so) to connect to an API and loop through several iterations of the API call in order to grab the next_page value, put it in a list and then call the list.
Unfortunately, when this is published to the PBI service I am unable to refresh there and indeed 'Data Source Settings' tells me I have a 'hand-authored query'.
I have attempted to follow Chris Webbs' blog post around the usage of query parameters and relative path, but if I use this I just get a constant loop of the first page that's hit.
The Start Epoch Time is a helper to ensure I only grab data less than 3 months old.
let
iterations = 10000, // Number of MAXIMUM iterations
url = "https://www.zopim.com/api/v2/" & "incremental/" & "chats?fields=chats(*)" & "&start_time=" & Number.ToText( StartEpochTime ),
FnGetOnePage =
(url) as record =>
let
Source1 = Json.Document(Web.Contents(url, [Headers=[Authorization="Bearer MY AUTHORIZATION KEY"]])),
data = try Source1[chats] otherwise null, //get the data of the first page
next = try Source1[next_page] otherwise null, // the script ask if there is another page*//*
res = [Data=data, Next=next]
in
res,
GeneratedList =
List.Generate(
()=>[i=0, res = FnGetOnePage(url)],
each [i]<iterations and [res][Data]<>null,
each [i=[i]+1, res = FnGetOnePage([res][Next])],
each [res][Data])
Lookups
If Source1 exists, but [chats] may not, you can simplify
= try Source1[chats] otherwise null
to
= Source1[chats]?
Plus it you don't lose non-lookup errors.
m-spec-operators
Chris Web Method
should be something closer to this.
let
Headers = [
Accept="application/json"
],
BaseUrl = "https://www.zopim.com", // very important
Options = [
RelativePath = "api/v2/incremental/chats",
Headers = [
Accept="application/json"
],
Query = [
fields = "chats(*)",
start_time = Number.ToText( StartEpocTime )
],
Response = Web.Contents(BaseUrl, Options),
Result = Json.Document(Response) // skip if it's not JSON
in
Result
Here's an example of a reusable Web.Contents function
helper function
let
/*
from: <https://github.com/ninmonkey/Ninmonkey.PowerQueryLib/blob/master/source/WebRequest_Simple.pq>
Wrapper for Web.Contents returns response metadata
for options, see: <https://learn.microsoft.com/en-us/powerquery-m/web-contents#__toc360793395>
Details on preventing "Refresh Errors", using 'Query' and 'RelativePath':
- Not using Query and Relative path cause refresh errors:
<https://blog.crossjoin.co.uk/2016/08/23/web-contents-m-functions-and-dataset-refresh-errors-in-power-bi/>
- You can opt-in to Skip-Test:
<https://blog.crossjoin.co.uk/2019/04/25/skip-test-connection-power-bi-refresh-failures/>
- Debugging and tracing the HTTP requests
<https://blog.crossjoin.co.uk/2019/11/17/troubleshooting-web-service-refresh-problems-in-power-bi-with-the-power-query-diagnostics-feature/>
update:
- MaybeErrResponse: Quick example of parsing an error result.
- Raw text is returned, this is useful when there's an error
- now response[json] does not throw, when the data isn't json to begin with (false errors)
*/
WebRequest_Simple
= (
base_url as text,
optional relative_path as nullable text,
optional options as nullable record
)
as record =>
let
headers = options[Headers]?, //or: ?? [ Accept = "application/json" ],
merged_options = [
Query = options[Query]?,
RelativePath = relative_path,
ManualStatusHandling = options[ManualStatusHandling]? ?? { 400, 404, 406 },
Headers = headers
],
bytes = Web.Contents(base_url, merged_options),
response = Binary.Buffer(bytes),
response_metadata = Value.Metadata( bytes ),
status_code = response_metadata[Response.Status]?,
response_text = Text.Combine( Lines.FromBinary(response,null,null, TextEncoding.Utf8), "" ),
json = Json.Document(response),
IsJsonX = not (try json)[HasError],
Final = [
request_url = metadata[Content.Uri](),
response_text = response_text,
status_code = status_code,
metadata = response_metadata,
IsJson = IsJsonX,
response = response,
json = if IsJsonX then json else null
]
in
Final,
tests = {
WebRequest_Simple("https://httpbin.org", "json"), // expect: json
WebRequest_Simple("https://www.google.com"), // expect: html
WebRequest_Simple("https://httpbin.org", "/headers"),
WebRequest_Simple("https://httpbin.org", "/status/codes/406"), // exect 404
WebRequest_Simple("https://httpbin.org", "/status/406"), // exect 406
WebRequest_Simple("https://httpbin.org", "/get", [ Text = "Hello World"])
},
FinalResults = Table.FromRecords(tests,
type table[
status_code = Int64.Type, request_url = text,
metadata = record,
response_text = text,
IsJson = logical, json = any,
response = binary
],
MissingField.Error
)
in
FinalResults
I have created a ecommerce site. Now i want to integrate payment method. By adding SSLCommerce to my site, all payment method will be taken care of in Bangladesh. But I don't know how can I add it to my Django app. Please help!
They said something session. But I did not get it. Here is thier github repo https://github.com/sslcommerz/SSLCommerz-Python?fbclid=IwAR0KkEH3H-AOwaWneQy0POGkTw6O3vvL9NiRM4amflyQEt54_W1g1rgYB48
There is a wrapper library called "sslcommerz-lib". To use it, you'll first need an account on their sandbox environment. After completing the registration, collect your user credentials from email.
First install the package with pip install sslcommerz-lib
Import the library on your module from sslcommerz_lib import SSLCOMMERZ
Instantiate an object of the SSLCOMMERZ class with sandbox user credentials
sslcz = SSLCOMMERZ({ 'store_id': <your_store_id>, 'store_pass': <your_password>, 'issandbox': True })
Build a dictionary with some info about the transaction and customer. In a real application, most of these data will be collected from user input.
data = {
'total_amount': "100.26",
'currency': "BDT",
'tran_id': "tran_12345",
'success_url': "http://127.0.0.1:8000/payment-successful", # if transaction is succesful, user will be redirected here
'fail_url': "http://127.0.0.1:8000/payment-failed", # if transaction is failed, user will be redirected here
'cancel_url': "http://127.0.0.1:8000/payment-cancelled", # after user cancels the transaction, will be redirected here
'emi_option': "0",
'cus_name': "test",
'cus_email': "test#test.com",
'cus_phone': "01700000000",
'cus_add1': "customer address",
'cus_city': "Dhaka",
'cus_country': "Bangladesh",
'shipping_method': "NO",
'multi_card_name': "",
'num_of_item': 1,
'product_name': "Test",
'product_category': "Test Category",
'product_profile': "general",
}
Get the api reponse
response = sslcz.createSession(data)
After doing chores like updating db etc, redirect the user to 'GatewayPageURL' from the response we got earlier -
from django.shortcuts import redirect
return redirect(response['GatewayPageURL'])
SSLCOMMERZ - Python (sslcommerz-lib)
Note: If you're using this wrapper with our sandbox environment issandbox is true and live issandbox is false. (Details: Test Or Sandbox Account).
settings = { 'store_id': 'testbox', 'store_pass': 'qwerty', 'issandbox': True }
sslcommerz = SSLCOMMERZ(settings)
Installation
pip install sslcommerz-lib
Authentication Keys
You can find your store_id and store_pass at the API Documentation Page. Create an account on SSLCOMMERZ, log in and visit this link: https://developer.sslcommerz.com/registration/
Usage
Create a Initial Payment Request Session
from sslcommerz_lib import SSLCOMMERZ
settings = { 'store_id': 'testbox', 'store_pass': 'qwerty', 'issandbox': True }
sslcz = SSLCOMMERZ(settings)
post_body = {}
post_body['total_amount'] = 100.26
post_body['currency'] = "BDT"
post_body['tran_id'] = "12345"
post_body['success_url'] = "your success url"
post_body['fail_url'] = "your fail url"
post_body['cancel_url'] = "your cancel url"
post_body['emi_option'] = 0
post_body['cus_name'] = "test"
post_body['cus_email'] = "test#test.com"
post_body['cus_phone'] = "01700000000"
post_body['cus_add1'] = "customer address"
post_body['cus_city'] = "Dhaka"
post_body['cus_country'] = "Bangladesh"
post_body['shipping_method'] = "NO"
post_body['multi_card_name'] = ""
post_body['num_of_item'] = 1
post_body['product_name'] = "Test"
post_body['product_category'] = "Test Category"
post_body['product_profile'] = "general"
response = sslcz.createSession(post_body) # API response
print(response)
# Need to redirect user to response['GatewayPageURL']
Vaidate payment with IPN
from sslcommerz_lib import SSLCOMMERZ
settings = { 'store_id': 'test_testemi', 'store_pass': 'test_testemi#ssl', 'issandbox': True }
sslcz = SSLCOMMERZ(settings)
post_body = {}
post_body['tran_id'] = '5E121A0D01F92'
post_body['val_id'] = '200105225826116qFnATY9sHIwo'
post_body['amount'] = "10.00"
post_body['card_type'] = "VISA-Dutch Bangla"
post_body['store_amount'] = "9.75"
post_body['card_no'] = "418117XXXXXX6675"
post_body['bank_tran_id'] = "200105225825DBgSoRGLvczhFjj"
post_body['status'] = "VALID"
post_body['tran_date'] = "2020-01-05 22:58:21"
post_body['currency'] = "BDT"
post_body['card_issuer'] = "TRUST BANK, LTD."
post_body['card_brand'] = "VISA"
post_body['card_issuer_country'] = "Bangladesh"
post_body['card_issuer_country_code'] = "BD"
post_body['store_id'] = "test_testemi"
post_body['verify_sign'] = "d42fab70ae0bcbda5280e7baffef60b0"
post_body['verify_key'] = "amount,bank_tran_id,base_fair,card_brand,card_issuer,card_issuer_country,card_issuer_country_code,card_no,card_type,currency,currency_amount,currency_rate,currency_type,risk_level,risk_title,status,store_amount,store_id,tran_date,tran_id,val_id,value_a,value_b,value_c,value_d"
post_body['verify_sign_sha2'] = "02c0417ff467c109006382d56eedccecd68382e47245266e7b47abbb3d43976e"
post_body['currency_type'] = "BDT"
post_body['currency_amount'] = "10.00"
post_body['currency_rate'] = "1.0000"
post_body['base_fair'] = "0.00"
post_body['value_a'] = ""
post_body['value_b'] = ""
post_body['value_c'] = ""
post_body['value_d'] = ""
post_body['risk_level'] = "0"
post_body['risk_title'] = "Safe"
if sslcz.hash_validate_ipn(post_body):
response = sslcz.validationTransactionOrder(post_body['val_id'])
print(response)
else:
print("Hash validation failed")
Get the status or details of a Payment Request by sessionkey
from sslcommerz_lib import SSLCOMMERZ
settings = { 'store_id': 'testbox', 'store_pass': 'qwerty', 'issandbox': True }
sslcz = SSLCOMMERZ(settings)
sessionkey = 'A8EF93B75B8107E4F36049E80B4F9149'
response = sslcz.transaction_query_session(sessionkey)
print(response)
Get the status or details of a Payment Request by tranid
from sslcommerz_lib import SSLCOMMERZ
settings = { 'store_id': 'testbox', 'store_pass': 'qwerty', 'issandbox': True }
sslcz = SSLCOMMERZ(settings)
tranid = '59C2A4F6432F8'
response = sslcz.transaction_query_tranid(tranid)
print(response)
I am using the Python Zeep library to call Maximo web services and able to fetch the WSDL without any issues. When I am trying to query using one of the method in Web service, it is throwing error
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))
multiasset_wsdl = "http://maximoqa.xyz.com:9080/meaweb/services/MULTIASSET?wsdl"
work_order = 'NA0000211'
# set the session
session = Session()
session.auth = HTTPBasicAuth(Username, Password)
session.verify = False
transport = Transport(session=session)
settings = Settings(strict=False ,force_https = False)
maximo_multiasset_client = Client(multiasset_wsdl, transport=transport, settings=settings
multiasset_type_factory = maximo_multiasset_client.type_factory('ns0')
mult_asset_query = multiasset_type_factory.QueryMULTIASSETType(
baseLanguage = "?",
creationDateTime = tt.get_now(),
maximoVersion = "?",
maxItems = "1",
messageID = "?",
rsStart = "0",
transLanguage = "EN",
uniqueResult = False,
MULTIASSETQuery = multiasset_type_factory.MULTIASSETQueryType
(
operandMode = multiasset_type_factory.OperandModeType('AND'),
orderby = "?",
WHERE = f"WONUM='{work_order}'",
WORKORDER = None
)
)
print('Calling Query MultiAsset')
query_response = maximo_multiasset_client.service.QueryMULTIASSET(mult_asset_query)
Appreciate any help on this issue.
I've been trying to write a bazel rule to wrap compiling for risc-v source files, does some other stuff, etc, but I've been having some trouble with getting a CcToolchainInfo provider.
I have a rule that works that looks like
rv_cc_toolchain_config = rule(
implementation = _impl,
attrs = {},
provides = [CcToolchainConfigInfo],
)
in order to provide config info. I have the following in toolchains/BUILD:
load(":cc_toolchain_config.bzl", "rv_cc_toolchain_config")
package(default_visibility = ['//visibility:public'])
rv_cc_toolchain_config(name="rv_toolchain_cfg")
cc_toolchain(
name='rv_toolchain',
toolchain_identifier='rv-toolchain',
toolchain_config=':rv_toolchain_cfg',
all_files=':nofile',
strip_files=':nofile',
objcopy_files=':nofile',
dwp_files=':nofile',
compiler_files=':nofile',
linker_files=':nofile',
)
This seems to all work fine; I then have my custom rule to compile with riscv:
def _compile_impl(ctx):
deps = []
cc_toolchain = find_cpp_toolchain(ctx)
print(ctx.attr._cc_toolchain)
compilation_contexts = [dep[CcInfo].compilation_context for dep in deps]
print(type(cc_toolchain))
feature_configuration = cc_common.configure_features( #fails here
ctx = ctx,
cc_toolchain = cc_toolchain,
requested_features = ctx.features, #currently does nothing
unsupported_features = ctx.disabled_features,
)
rv_compile = rule(
_compile_impl,
output_to_genfiles = True,
attrs = {
"srcs": attr.label_list(
doc = "List of source files",
mandatory = False,
allow_files = [".cc", ".cpp", ".h", ".c"],
),
"hdrs": attr.label_list(
doc = "List of header files",
allow_files = [".h"],
),
"_cc_toolchain": attr.label(
#default = Label("#bazel_tools//tools/cpp:current_cc_toolchain"),
default = Label("//toolchains:rv_toolchain")
),
},
provides = [
DefaultInfo,
CcInfo,
],
toolchains = [
"#bazel_tools//tools/cpp:toolchain_type",
],
fragments = ["cpp"]
)
Where I fail when trying to configure the toolchain because cc_toolchain is of type ToolchainInfo and not the required CcToolchainInfo. Does anyone have any insight on how to provide CcToolchainInfo within a rule? Or is there a better way of doing this? Documentation seems to go dark on this.
Oops -- figured this out after trolling through github. Turns out the problem is directly referencing cc_toolchain is incorrect, and that CcToolchainInfo is provided via cc_toolchain_suite
updating toolchains/BUILD to look something like
load(":cc_toolchain_config.bzl", "rv_cc_toolchain_config")
package(default_visibility = ['//visibility:public'])
rv_cc_toolchain_config(name="rv_toolchain_cfg")
filegroup(name = 'empty')
cc_toolchain(
name='rv_toolchain',
toolchain_identifier='sanity-toolchain',
toolchain_config=':rv_toolchain_cfg',
all_files=':empty',
strip_files=':empty',
objcopy_files=':empty',
dwp_files=':empty',
compiler_files=':empty',
linker_files=':empty',
)
cc_toolchain_suite(
name='rv',
toolchains={
'darwin': ':rv_toolchain', #use whatever OS you need here...
}
)
and the rv compile rule to something like
rv_compile = rule(
_compile_impl,
output_to_genfiles = True,
attrs = {
"srcs": attr.label_list(
doc = "List of source files",
mandatory = False,
allow_files = [".cc", ".cpp", ".h", ".c"],
),
"hdrs": attr.label_list(
doc = "List of header files",
allow_files = [".h"],
),
"_cc_toolchain": attr.label(
#default = Label("#bazel_tools//tools/cpp:current_cc_toolchain"),
default = Label("//toolchains:rv")
),
},
provides = [
DefaultInfo,
CcInfo,
],
toolchains = [
"#bazel_tools//tools/cpp:toolchain_type",
],
fragments = ["cpp"]
)
works like a charm :) anyone reading this should also enable expirimental skylark cpp apis as well. if anyone knows how to make cc_toolchain_suite cpu agnostic, i'd love to hear it. cheers.