
Huawei Cloud Functiongraph Function Create
- 93 installs
- 19 repo stars
- Updated July 31, 2026
- huaweicloud/huaweicloud-skills
Create Huawei Cloud FunctionGraph serverless functions from a name, runtime, and code content using the FunctionGraph Python SDK.
About
Creates FunctionGraph serverless functions on Huawei Cloud from user-provided name, runtime, and code via the FunctionGraph Python SDK. A developer uses it to deploy cloud functions programmatically without console login, including batch creation and CI/CD integration.
- Creates functions from name, runtime, and code content
- Supports batch creation and CI/CD deployment
Huawei Cloud Functiongraph Function Create by the numbers
- 93 all-time installs (skills.sh)
- +17 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #578 of 1,042 Cloud & Infrastructure skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/huaweicloud/huaweicloud-skills --skill huawei-cloud-functiongraph-function-createAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 93 |
|---|---|
| repo stars | ★ 19 |
| Last updated | July 31, 2026 |
| Repository | huaweicloud/huaweicloud-skills ↗ |
What it does
Create Huawei Cloud FunctionGraph serverless functions from a name, runtime, and code content using the FunctionGraph Python SDK.
Files
FunctionGraph Function Creation Skill
Overview
This skill creates FunctionGraph functions on Huawei Cloud based on user-provided parameters including function name, runtime, and code content.
Architecture: Uses Huawei Cloud FunctionGraph Python SDK to interact with FunctionGraph service.
Applicable Scenarios:
- Quickly create cloud functions without manual console login
- Batch creation of multiple functions
- Foundation component for workflow deployment
- CI/CD integration for function deployment
Typical Use Cases:
1. "Create a Python function named my_handler" 2. "Deploy this code to FunctionGraph" 3. "Batch create 10 functions from template"
Prerequisites
1. Python Environment
- Python 3.9+
- Verify:
python --version
2. SDK Installation
pip install huaweicloudsdkfunctiongraph3. Authentication Configuration
- Valid Huawei Cloud credentials (AK/SK mode)
- Configure via environment variables:
export HUAWEI_AK="your-access-key"
export HUAWEI_SK="your-secret-key"
export HUAWEI_REGION="cn-north-4"
export HUAWEI_PROJECT_ID="your-project-id"Security Rules:
- NEVER expose AK/SK values in code or logs
- NEVER let users input AK/SK directly in conversation
- ALWAYS use environment variables for credentials
- Recommend using IAM user instead of main account
4. IAM Permission Requirements
functiongraph:function:create- Create functionfunctiongraph:function:get- Query function detailsfunctiongraph:function:list- List functions
See IAM Policies for detailed permission configuration.
Usage
Command
cd scripts
python create_function.py --name <function_name> --runtime <runtime> --han
dler <handler> --code <code_content> --memory <memory_size> --timeout <timeout>Parameter Confirmation
|| Parameter | Required/Optional | Description | Default || || ----------- | ------------------ | ------------- | --------- || || function_name | Required | Function name, must follow naming rules | - || || runtime | Required | Runtime environment (Python3.9, etc.) | - || || code_content | Required | Function code content | - || || handler | Required | Function entry point (e.g., index.handler) | - || || memory_size | Optional | Memory size in MB | 128 || || timeout | Optional | Timeout in seconds | 3 || || description | Optional | Function description | - ||
Runtime Options
|| Runtime | Handler Format | Example || || --------- | ---------------- | --------- || || Python3.9 | index.handler | def handler(event, context): || || Node.js14.18 | index.handler | exports.handler = (event, context) => {} || || Java8 | com.example.Handler::handleRequest | Java class method || || Go1.x | handler | Go function name ||
Verification Method
See Verification Method for detailed procedures.
Quick Verification
## Verify function exists using SDK
from huaweicloudsdkfunctiongraph.v2.functiongraph_client import FunctionGraphClient
from huaweicloudsdkfunctiongraph.v2.model import ListFunctionsRequest
# List functions to verify creation
client = FunctionGraphClient.new_builder().build()
request = ListFunctionsRequest()
response = client.list_functions(request)
print(f"Total functions: {len(response.functions)}")Output Format
The skill returns a structured JSON object with the following fields:
function_urn: Unique resource identifier of the created functionfunction_name: Name of the created functionruntime: Runtime environmentmemory_size: Allocated memory in MBtimeout: Function timeout in secondshandler: Function entry pointdescription: Function description (if provided)
Example output:
{
"function_urn": "urn:fss:cn-north-4:project_id:function:default:my_function",
"function_name": "my_function",
"runtime": "Python3.9",
"memory_size": 128,
"timeout": 3,
"handler": "index.handler",
"description": "Test function created by skill"
}Best Practices
1. Test before production: Always test in a development environment first 2. Monitor resources: Set up monitoring for function invocations and errors 3. Use environment variables: Store sensitive data in environment variables 4. Implement error handling: Add proper error handling in function code 5. Set appropriate timeouts: Configure timeout based on function logic
Error Handling
|| Error Code | Description | Resolution || || ------------ | ------------- | ------------ || || InvalidParameter | Invalid input parameters | Check parameter format and valu es || || InsufficientPermission | Insufficient permissions | Check IAM permissions || || QuotaExceeded | Resource quota exceeded | Request quota increase or delete un used functions || || FunctionAlreadyExists | Function with same name exists | Use different functi on name or delete existing function ||
References
- FunctionGraph Documentation
- Python SDK Documentation
- IAM Policies Guide
- Verification Method
Acceptance Criteria
This document defines the acceptance criteria, test cases, and success standards for the FunctionGraph function creation workflow.
Overview
Scope
| Component | Description |
|---|---|
| Feature | FunctionGraph function creation |
| Platform | Huawei Cloud FunctionGraph |
| Methods | CLI and SDK |
| Regions | All supported regions |
Test Categories
| Category | Priority | Coverage |
|---|---|---|
| Smoke Tests | Critical | Core functionality |
| Functional Tests | High | All features |
| Integration Tests | Medium | External integrations |
| Performance Tests | Medium | Performance benchmarks |
| Security Tests | High | Security compliance |
Test Cases
TC-001: Basic Function Creation
| Attribute | Value |
|---|---|
| ID | TC-001 |
| Name | Basic function creation |
| Priority | Critical |
| Type | Smoke Test |
Preconditions:
- KooCLI is installed and configured
- IAM permissions are granted
- Valid runtime code is prepared
Test Steps:
# Step 1: Create function
hcloud FunctionGraph function create \
--func_name=test-function-001 \
--package_type=Zip \
--runtime=Python3.9 \
--handler=index.handler \
--memory_size=128 \
--timeout=10 \
--code_url=https://obs-bucket.obs.cn-north-4.myhuaweicloud.com/code.zip
# Step 2: Verify creation
hcloud FunctionGraph function show \
--func_urn=urn:fg:cn-north-4:PROJECT_ID:function:test-function-001:latestExpected Results:
- Function is created successfully
- Status is ACTIVE
- All configuration matches input parameters
Pass Criteria:
- [ ] Function exists in function list
- [ ] Status equals ACTIVE
- [ ] func_name matches specification
- [ ] runtime matches specification
- [ ] memory_size matches specification
- [ ] timeout matches specification
---
TC-002: Function with VPC Configuration
| Attribute | Value |
|---|---|
| ID | TC-002 |
| Name | Function with VPC configuration |
| Priority | High |
| Type | Functional Test |
Test Steps:
hcloud FunctionGraph function create \
--func_name=test-function-vpc \
--package_type=Zip \
--runtime=Python3.9 \
--handler=index.handler \
--memory_size=256 \
--timeout=30 \
--vpc_id=VPC_ID \
--subnet_id=SUBNET_ID \
--security_group_id=SECURITY_GROUP_IDExpected Results:
- Function is created with VPC configuration
- VPC connectivity is established
- Network isolation is verified
Pass Criteria:
- [ ] VPC configuration is saved
- [ ] Function can access VPC resources
- [ ] Network connectivity is verified
---
TC-003: Function with Environment Variables
| Attribute | Value |
|---|---|
| ID | TC-003 |
| Name | Function with environment variables |
| Priority | High |
| Type | Functional Test |
Test Steps:
hcloud FunctionGraph function create \
--func_name=test-function-env \
--package_type=Zip \
--runtime=Python3.9 \
--handler=index.handler \
--memory_size=128 \
--timeout=10 \
--environment_variables='{"DB_HOST": "localhost", "DB_PORT": "3306", "DEBUG": "false"}'Expected Results:
- Environment variables are set correctly
- Variables are accessible in function execution
Pass Criteria:
- [ ] All environment variables are saved
- [ ] Variables are accessible at runtime
- [ ] Sensitive variables are masked in output
---
TC-004: Function with Layers
| Attribute | Value |
|---|---|
| ID | TC-004 |
| Name | Function with layers |
| Priority | Medium |
| Type | Functional Test |
Test Steps:
# Create layer first
hcloud FunctionGraph layer create \
--layer_name=my-layer \
--runtime=Python3.9 \
--code_url=https://obs-bucket/layer.zip
# Create function with layer
hcloud FunctionGraph function create \
--func_name=test-function-layer \
--package_type=Zip \
--runtime=Python3.9 \
--handler=index.handler \
--layers='[{"urn": "urn:fg:cn-north-4:PROJECT_ID:layer:my-layer:1"}]'Expected Results:
- Layer is attached to function
- Layer dependencies are available
Pass Criteria:
- [ ] Layer is associated with function
- [ ] Layer packages are accessible
- [ ] Function executes with layer dependencies
---
TC-005: Function Invocation
| Attribute | Value |
|---|---|
| ID | TC-005 |
| Name | Function invocation |
| Priority | Critical |
| Type | Smoke Test |
Test Steps:
# Create test event
cat > test-event.json << EOF
{
"key1": "value1",
"key2": 100,
"source": "acceptance-test"
}
EOF
# Invoke function
hcloud FunctionGraph function invoke \
--func_urn=FUNCTION_URN \
--body=@test-event.jsonExpected Results:
- Function executes successfully
- Returns expected response
- Execution logs are captured
Pass Criteria:
- [ ] Invocation returns success status
- [ ] Response matches expected format
- [ ] Execution time is within limits
- [ ] No errors in execution logs
---
TC-006: Trigger Creation
| Attribute | Value |
|---|---|
| ID | TC-006 |
| Name | API Gateway trigger |
| Priority | High |
| Type | Integration Test |
Test Steps:
# Create API trigger
hcloud FunctionGraph trigger create \
--func_urn=FUNCTION_URN \
--trigger_type=apig \
--trigger_data='{
"group_id": "API_GROUP_ID",
"env_id": "DEFAULT_ENV",
"auth": "IAM"
}'
# Verify trigger
hcloud FunctionGraph trigger list --func_urn=FUNCTION_URN
# Test via HTTP
curl -X POST https://API_ENDPOINT/invoke \
-H "Content-Type: application/json" \
-H "X-Auth-Token: TOKEN" \
-d '{"test": "http"}'Expected Results:
- Trigger is created successfully
- HTTP endpoint is accessible
- Function is invoked via trigger
Pass Criteria:
- [ ] Trigger appears in trigger list
- [ ] HTTP endpoint is valid
- [ ] Function invocation succeeds via trigger
---
TC-007: Error Handling
| Attribute | Value |
|---|---|
| ID | TC-007 |
| Name | Error handling validation |
| Priority | High |
| Type | Functional Test |
Test Cases:
| Scenario | Input | Expected Error |
|---|---|---|
| Invalid runtime | runtime=InvalidRuntime | Validation error |
| Invalid memory | memory_size=999999 | Validation error |
| Invalid timeout | timeout=9999 | Validation error |
| Invalid handler | handler=invalid | Handler not found |
| Missing code | code_url=invalid | Code not found |
Pass Criteria:
- [ ] Appropriate error messages returned
- [ ] No resource created on validation failure
- [ ] Error codes match API documentation
---
TC-008: Update Function
| Attribute | Value |
|---|---|
| ID | TC-008 |
| Name | Update function configuration |
| Priority | High |
| Type | Functional Test |
Test Steps:
# Update memory size
hcloud FunctionGraph function update \
--func_urn=FUNCTION_URN \
--memory_size=512
# Verify update
hcloud FunctionGraph function show \
--func_urn=FUNCTION_URN \
--cli-query="memory_size"Expected Results:
- Configuration is updated
- New configuration is active
Pass Criteria:
- [ ] Memory size updated to 512
- [ ] Other configurations unchanged
- [ ] Status remains ACTIVE
Success Standards
Functional Requirements
| Requirement | Metric | Threshold |
|---|---|---|
| Function creation success rate | Percentage | ≥ 99% |
| Function invocation success rate | Percentage | ≥ 99.5% |
| Configuration accuracy | Percentage | 100% |
| Error handling completeness | Percentage | 100% |
Performance Requirements
| Metric | Unit | Acceptable | Good | Excellent |
|---|---|---|---|---|
| Cold start latency | ms | < 1000 | < 500 | < 200 |
| Warm invocation latency | ms | < 200 | < 100 | < 50 |
| API response time | ms | < 5000 | < 2000 | < 1000 |
| Throughput | req/sec | ≥ 10 | ≥ 50 | ≥ 100 |
Security Requirements
| Requirement | Description | Verification |
|---|---|---|
| Authentication | Valid AK/SK required | Verify with invalid credentials |
| Authorization | IAM permissions enforced | Verify with limited permissions |
| Data encryption | HTTPS enforced | Verify HTTP is rejected |
| Input validation | Invalid input rejected | TC-007 tests |
| Secrets management | Sensitive data masked | Verify in logs |
Reliability Requirements
| Requirement | Metric | Target |
|---|---|---|
| Availability | Uptime | ≥ 99.9% |
| Retry success | Percentage | ≥ 95% |
| Graceful degradation | Error handling | All paths covered |
Test Execution Matrix
Environment Coverage
| Region | Runtime | VPC | Priority |
|---|---|---|---|
| cn-north-4 | Python3.9 | No | Critical |
| cn-north-4 | Python3.9 | Yes | High |
| cn-north-4 | Node.js14.18 | No | High |
| cn-north-4 | Java11 | No | Medium |
| cn-south-1 | Python3.9 | No | Medium |
Test Suite Execution
#!/bin/bash
# run_acceptance_tests.sh
echo "=== FunctionGraph Acceptance Test Suite ==="
# Test execution tracking
TOTAL=0
PASSED=0
FAILED=0
run_test() {
local test_id=$1
local test_name=$2
TOTAL=$((TOTAL + 1))
echo ""
echo "Running $test_id: $test_name"
if execute_test $test_id; then
PASSED=$((PASSED + 1))
echo "✓ PASSED"
else
FAILED=$((FAILED + 1))
echo "✗ FAILED"
fi
}
# Execute test cases
run_test "TC-001" "Basic Function Creation"
run_test "TC-002" "Function with VPC Configuration"
run_test "TC-003" "Function with Environment Variables"
run_test "TC-004" "Function with Layers"
run_test "TC-005" "Function Invocation"
run_test "TC-006" "Trigger Creation"
run_test "TC-007" "Error Handling"
run_test "TC-008" "Update Function"
# Summary
echo ""
echo "=== Test Summary ==="
echo "Total: $TOTAL"
echo "Passed: $PASSED"
echo "Failed: $FAILED"
echo "Pass Rate: $(awk "BEGIN {printf \"%.1f\", ($PASSED/$TOTAL)*100}")%"
# Exit code
if [ $FAILED -gt 0 ]; then
exit 1
fiAcceptance Sign-off
Approval Criteria
| Role | Responsibility | Required |
|---|---|---|
| Test Lead | Test execution completeness | Yes |
| Developer | Code quality approval | Yes |
| Product Owner | Feature acceptance | Yes |
| Security | Security requirements | Yes |
Sign-off Checklist
- [ ] All critical test cases passed
- [ ] All high-priority test cases passed
- [ ] Performance requirements met
- [ ] Security requirements verified
- [ ] Documentation complete
- [ ] No critical defects remaining
- [ ] Test coverage ≥ 80%
- [ ] Success rate ≥ 95%
Defect Classification
| Severity | Description | Resolution |
|---|---|---|
| Critical | Function creation fails | Block release |
| High | Major feature broken | Fix before release |
| Medium | Feature partially working | Fix in next iteration |
| Low | Minor issue, workaround exists | Schedule for fix |
Reporting
Test Report Template
Test Execution Report
=====================
Date: YYYY-MM-DD
Environment: Production/Staging
Region: cn-north-4
Summary:
- Total Tests: XX
- Passed: XX
- Failed: XX
- Skipped: XX
Details:
[Detailed results for each test case]
Defects:
[List of identified defects]
Recommendations:
[Go/No-Go recommendation]Related Documentation
IAM Policies for FunctionGraph
This document defines the required IAM (Identity and Access Management) policies for creating and managing Huawei Cloud FunctionGraph functions.
Required Permissions
Core Permissions for Function Creation
| Permission | Description | Action Type |
|---|---|---|
| functiongraph:function:create | Create a new function | Write |
| functiongraph:function:list | List functions in a project | List |
| functiongraph:function:get | Get function details | Read |
| functiongraph:function:update | Update function configuration | Write |
| functiongraph:function:delete | Delete a function | Write |
Additional Permissions for Deployment
| Permission | Description | Action Type |
|---|---|---|
| functiongraph:function:invoke | Invoke a function | Write |
| functiongraph:alias:create | Create function alias | Write |
| functiongraph:alias:list | List function aliases | List |
| functiongraph:version:list | List function versions | List |
| functiongraph:trigger:create | Create trigger for function | Write |
| functiongraph:trigger:list | List function triggers | List |
Policy Templates
Full Access Policy
{
"Version": "1.1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"functiongraph:*:*"
],
"Resource": "*"
}
]
}Function Creation Policy (Minimum Required)
{
"Version": "1.1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"functiongraph:function:create",
"functiongraph:function:list",
"functiongraph:function:get",
"functiongraph:function:update"
],
"Resource": [
"urn:fg:*:*:function:*"
]
}
]
}Resource-Specific Policy
{
"Version": "1.1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"functiongraph:function:create",
"functiongraph:function:get",
"functiongraph:function:update",
"functiongraph:function:invoke"
],
"Resource": [
"urn:fg:cn-north-4:*:function:my-function-*"
],
"Condition": {
"StringEquals": {
"fg:app_id": "app-12345678"
}
}
}
]
}Policy Application Methods
Method 1: Console-Based Configuration
1. Log in to Huawei Cloud Console 2. Navigate to Identity and Access Management > Policies 3. Click Create Custom Policy 4. Select JSON view and paste policy document 5. Click OK to create the policy 6. Attach policy to user or group
Method 2: KooCLI-Based Configuration
# Create custom policy
hcloud IAM policy create \
--cli-region=cn-north-4 \
--body='{
"policy": {
"name": "FunctionGraphCreatePolicy",
"description": "Policy for creating FunctionGraph functions",
"policy_document": {
"Version": "1.1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"functiongraph:function:create",
"functiongraph:function:list",
"functiongraph:function:get"
],
"Resource": "*"
}
]
}
}
}'
# Attach policy to user
hcloud IAM user attach-policy \
--user_id=USER_ID \
--policy_id=POLICY_IDCross-Service Permissions
FunctionGraph may require permissions for other services:
| Service | Required Permission | Purpose |
|---|---|---|
| OBS | obs:bucket:get, obs:object:get | Reading function code packages |
| VPC | vpc:vpc:get, vpc:subnet:get | VPC configuration for functions |
| DIS | dis:stream:put | DIS trigger integration |
| APIG | apig:api:create | API Gateway trigger creation |
| LTS | lts:log:create | Log transmission to LTS |
Cross-Service Policy Example
{
"Version": "1.1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"functiongraph:function:*",
"obs:bucket:get",
"obs:object:get",
"vpc:vpc:get",
"vpc:subnet:get"
],
"Resource": "*"
}
]
}Permission Verification
Verify Current User Permissions
# List attached policies
hcloud IAM user list-policies --user_name=YOUR_USERNAME
# Test FunctionGraph access
hcloud FunctionGraph function list --cli-region=cn-north-4
# Attempt to create test function (dry-run)
hcloud FunctionGraph function create \
--cli-region=cn-north-4 \
--func_name=permission-test \
--package_type=Zip \
--runtime=Python3.9 \
--handler=index.handler \
--memory_size=128 \
--timeout=10Permission Scopes
Project-Level Scope
Policies applied at project level only affect resources within that project:
{
"Version": "1.1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"functiongraph:function:*"
],
"Resource": "*",
"Scope": {
"Project": [
"cn-north-4"
]
}
}
]
}Domain-Level Scope
Policies applied at domain level affect all projects:
{
"Version": "1.1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"functiongraph:function:*"
],
"Resource": "*"
}
]
}Security Best Practices
| Practice | Description |
|---|---|
| Least Privilege | Grant only minimum required permissions |
| Resource Restrictions | Use specific resource URNs instead of wildcards |
| Condition Keys | Apply conditions for additional constraints |
| Regular Audits | Review and remove unused permissions |
| Separate Environments | Use different policies for dev/test/prod |
Troubleshooting Permission Issues
Common Errors
| Error Code | Message | Solution |
|---|---|---|
| 403 | Permission denied | Add required permission to policy |
| 403 | User has no permission to access resource | Check resource-level permissions |
| 403 | Cross-project access denied | Verify project-level scope |
Diagnostic Steps
# Check user information
hcloud IAM user show --user_name=YOUR_USERNAME
# Verify policy attachments
hcloud IAM policy list-attachments --policy_id=POLICY_ID
# Enable debug mode for detailed error
hcloud --debug FunctionGraph function create --func_name=testRelated Documentation
SDK Installation Guide
This guide provides step-by-step instructions for installing the Huawei Cloud FunctionGraph Python SDK.
Prerequisites
| Requirement | Description |
|---|---|
| Operating System | Windows, Linux, or macOS |
| Python | Version 3.9 or higher |
| Network | Internet access to PyPI |
| Account | Huawei Cloud account with appropriate permissions |
Python Installation
Windows
# Download from python.org
# Or use chocolatey
choco install python
# Verify
python --version
pip --versionLinux
# Ubuntu/Debian
sudo apt update
sudo apt install python3.9 python3-pip
# CentOS/RHEL
sudo yum install python39 python39-pip
# Verify
python3 --version
pip3 --versionmacOS
# Using Homebrew
brew install python@3.9
# Verify
python3 --version
pip3 --versionSDK Installation
# Install FunctionGraph SDK
pip install huaweicloudsdkfunctiongraph
# Verify installation
python -c "from huaweicloudsdkfunctiongraph.v2.functiongraph_client import FunctionGraphClient; print('SDK installed successfully')"Authentication Configuration
Environment Variables (Recommended)
# Linux/macOS
export HUAWEI_AK="your-access-key"
export HUAWEI_SK="your-secret-key"
export HUAWEI_REGION="cn-north-4"
export HUAWEI_PROJECT_ID="your-project-id"
# Windows (Command Prompt)
set HUAWEI_AK=your-access-key
set HUAWEI_SK=your-secret-key
set HUAWEI_REGION=cn-north-4
set HUAWEI_PROJECT_ID=your-project-id
# Windows (PowerShell)
$env:HUAWEI_AK="your-access-key"
$env:HUAWEI_SK="your-secret-key"
$env:HUAWEI_REGION="cn-north-4"
$env:HUAWEI_PROJECT_ID="your-project-id"Security Best Practices
- 🚫 NEVER commit AK/SK to version control
- 🚫 NEVER hardcode credentials in source code
- ✅ ALWAYS use environment variables or configuration files
- ✅ Recommend using IAM user with minimal permissions
- ✅ Enable MFA for production accounts
Common Regions
| Region Code | Region Name |
|---|---|
| cn-north-4 | North China - Beijing 4 |
| cn-north-1 | North China - Beijing 1 |
| cn-east-3 | East China - Shanghai 1 |
| cn-south-1 | South China - Guangzhou |
| ap-southeast-1 | Hong Kong |
Verification Script
#!/usr/bin/env python3
import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkfunctiongraph.v2.functiongraph_client import FunctionGraphClient
from huaweicloudsdkfunctiongraph.v2.region.functiongraph_region import FunctionGraphRegion
# Get credentials from environment
ak = os.environ.get('HUAWEI_AK')
sk = os.environ.get('HUAWEI_SK')
region = os.environ.get('HUAWEI_REGION', 'cn-north-4')
project_id = os.environ.get('HUAWEI_PROJECT_ID')
if not all([ak, sk, project_id]):
print("❌ Missing credentials. Please set HUAWEI_AK, HUAWEI_SK, and HUAWEI_PROJECT_ID")
exit(1)
# Create credentials
credentials = BasicCredentials(ak, sk, project_id)
# Create client
client = FunctionGraphClient.new_builder() \
.with_credentials(credentials) \
.with_region(FunctionGraphRegion.value_of(region)) \
.build()
print(f"✅ SDK configured successfully for region: {region}")Troubleshooting
ImportError
# If import fails, reinstall SDK
pip uninstall huaweicloudsdkfunctiongraph
pip install huaweicloudsdkfunctiongraph
# Or upgrade pip first
pip install --upgrade pip
pip install huaweicloudsdkfunctiongraphAuthentication Error
- Verify AK/SK are correct
- Check if IAM user has required permissions
- Confirm project_id matches the region
Network Error
- Check internet connectivity
- Verify firewall allows HTTPS (443) to Huawei Cloud endpoints
- Try using a different region
Additional Resources
Verification Methods
This document provides comprehensive verification methods for FunctionGraph function creation, status checking, and functional testing.
Function Creation Verification
Step 1: Verify Function Existence
# List all functions
hcloud FunctionGraph function list \
--cli-region=cn-north-4 \
--cli-query="functions[?func_name=='YOUR_FUNCTION_NAME']"
# Get specific function details
hcloud FunctionGraph function show \
--func_urn=urn:fg:cn-north-4:PROJECT_ID:function:FUNCTION_NAME:latestExpected Output
{
"func_urn": "urn:fg:cn-north-4:project-123:function:my-function:latest",
"func_name": "my-function",
"runtime": "Python3.9",
"handler": "index.handler",
"memory_size": 256,
"timeout": 30,
"code_type": "Zip",
"code_url": "https://obs.bucket/code.zip",
"status": "ACTIVE"
}Step 2: Verify Function Configuration
| Parameter | Verification Method | Expected Result |
|---|---|---|
| func_name | Check in list output | Matches specified name |
| runtime | Validate runtime value | Supported runtime version |
| memory_size | Compare with config | 128-4096 MB range |
| timeout | Compare with config | 1-900 seconds range |
| handler | Verify entry point | Correct file:function format |
| status | Check state | ACTIVE or PENDING |
Status Checking
Function Status Values
| Status | Description | Action Required |
|---|---|---|
| ACTIVE | Function is operational | None |
| PENDING | Creation in progress | Wait for completion |
| FAILED | Creation failed | Check error logs |
| DELETING | Deletion in progress | Wait for completion |
| INACTIVE | Function is disabled | Enable if needed |
Status Check Commands
# Get function status
hcloud FunctionGraph function show \
--func_urn=FUNCTION_URN \
--cli-query="status"
# Monitor status with retry
for i in {1..10}; do
status=$(hcloud FunctionGraph function show --func_urn=FUNCTION_URN --cli-query="status")
if [ "$status" == '"ACTIVE"' ]; then
echo "Function is ACTIVE"
break
fi
echo "Status: $status, retrying... ($i/10)"
sleep 5
doneVersion and Alias Status
# List function versions
hcloud FunctionGraph version list \
--func_urn=FUNCTION_URN
# List function aliases
hcloud FunctionGraph alias list \
--func_urn=FUNCTION_URN
# Verify alias points to correct version
hcloud FunctionGraph alias show \
--func_urn=FUNCTION_URN \
--alias_name=prodFunctional Testing
Test Method 1: Synchronous Invocation
# Invoke function with test event
hcloud FunctionGraph function invoke \
--func_urn=FUNCTION_URN \
--body='{
"test": "data",
"source": "verification"
}'
# Invoke with file input
hcloud FunctionGraph function invoke \
--func_urn=FUNCTION_URN \
--body=@test-event.jsonTest Method 2: Asynchronous Invocation
# Invoke asynchronously
hcloud FunctionGraph function invoke \
--func_urn=FUNCTION_URN \
--invocation_type=Async \
--body='{"async": true}'
# Check invocation result
# Note: Requires OBS or DIS for async result storageTest Method 3: API Gateway Trigger
# Create test API trigger
hcloud FunctionGraph trigger create \
--func_urn=FUNCTION_URN \
--trigger_type=apig \
--trigger_data='{
"group_id": "API_GROUP_ID",
"env_id": "ENV_ID",
"auth": "NONE"
}'
# Test via HTTP request
curl -X POST https://API_ENDPOINT/path \
-H "Content-Type: application/json" \
-d '{"test": "http"}'Verification Checklist
Pre-Creation Verification
| Check | Command | Expected Result |
|---|---|---|
| CLI installed | hcloud version | Version displayed |
| Credentials configured | hcloud configure list | AK/SK present |
| Region accessible | hcloud FunctionGraph function list --cli-region=REGION | No error |
| IAM permissions | Test create operation | Permission granted |
Post-Creation Verification
| Check | Command | Expected Result |
|---|---|---|
| Function exists | List functions | Function in list |
| Status active | Show function | Status: ACTIVE |
| Configuration correct | Show function | All params match |
| Code uploaded | Check code_size | Size > 0 |
| Handler valid | Test invocation | No handler error |
Integration Verification
| Check | Description | Method |
|---|---|---|
| VPC connectivity | Verify VPC config | Show function VPC settings |
| Network access | Test outbound calls | Invoke with network test |
| OBS access | Read from OBS | Invoke with OBS operation |
| Database access | Query database | Invoke with DB query |
Automated Verification Script
#!/bin/bash
# verify_function.sh - Automated function verification
FUNC_URN=$1
REGION=${2:-"cn-north-4"}
echo "=== Function Verification Script ==="
echo "Function URN: $FUNC_URN"
echo "Region: $REGION"
echo ""
# Check 1: Function exists
echo "[1/6] Checking function existence..."
result=$(hcloud FunctionGraph function show --func_urn=$FUNC_URN --cli-region=$REGION 2>&1)
if echo "$result" | grep -q "func_name"; then
echo "✓ Function exists"
else
echo "✗ Function not found"
exit 1
fi
# Check 2: Status is ACTIVE
echo "[2/6] Checking function status..."
status=$(hcloud FunctionGraph function show --func_urn=$FUNC_URN --cli-region=$REGION --cli-query="status")
if [ "$status" == '"ACTIVE"' ]; then
echo "✓ Function is ACTIVE"
else
echo "✗ Function status: $status"
exit 1
fi
# Check 3: Runtime verification
echo "[3/6] Verifying runtime..."
runtime=$(hcloud FunctionGraph function show --func_urn=$FUNC_URN --cli-region=$REGION --cli-query="runtime")
echo "✓ Runtime: $runtime"
# Check 4: Memory and timeout
echo "[4/6] Verifying configuration..."
memory=$(hcloud FunctionGraph function show --func_urn=$FUNC_URN --cli-region=$REGION --cli-query="memory_size")
timeout=$(hcloud FunctionGraph function show --func_urn=$FUNC_URN --cli-region=$REGION --cli-query="timeout")
echo "✓ Memory: $memory MB, Timeout: $timeout seconds"
# Check 5: Test invocation
echo "[5/6] Testing function invocation..."
invocation=$(hcloud FunctionGraph function invoke --func_urn=$FUNC_URN --body='{"verification": true}' 2>&1)
if echo "$invocation" | grep -q "error"; then
echo "✗ Invocation failed: $invocation"
else
echo "✓ Invocation successful"
fi
# Check 6: Version info
echo "[6/6] Checking version information..."
version=$(hcloud FunctionGraph function show --func_urn=$FUNC_URN --cli-region=$REGION --cli-query="version")
echo "✓ Version: $version"
echo ""
echo "=== Verification Complete ==="Performance Verification
Cold Start Performance
# Measure cold start time
start_time=$(date +%s%N)
hcloud FunctionGraph function invoke --func_urn=FUNCTION_URN --body='{"test": "cold"}'
end_time=$(date +%s%N)
cold_start_ms=$(( (end_time - start_time) / 1000000 ))
echo "Cold start time: ${cold_start_ms}ms"Warm Invocation Performance
# Measure warm invocation time (after initial invocation)
for i in {1..10}; do
start=$(date +%s%N)
hcloud FunctionGraph function invoke --func_urn=FUNCTION_URN --body='{"test": "warm"}' > /dev/null
end=$(date +%s%N)
echo "Invocation $i: $(( (end - start) / 1000000 ))ms"
donePerformance Benchmarks
| Metric | Target | Measurement Method |
|---|---|---|
| Cold start | < 500ms | Time to first response |
| Warm invocation | < 100ms | Average of 10 invocations |
| Memory usage | Within limit | Function metrics in console |
| Init duration | < 200ms | Check execution logs |
Logging and Debugging
View Function Logs
# Query recent function logs via LTS
hcloud LTS logs query \
--log_group_id=LOG_GROUP_ID \
--log_stream_id=LOG_STREAM_ID \
--start_time="2024-01-01 00:00:00" \
--end_time="2024-01-01 23:59:59"Enable Debug Logging
# Invoke with environment variable for debug
hcloud FunctionGraph function update \
--func_urn=FUNCTION_URN \
--environment_variables='{"DEBUG": "true", "LOG_LEVEL": "debug"}'Related Documentation
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
FunctionGraph function creation tool
Create FunctionGraph functions on Huawei Cloud based on user input
"""
import os
import sys
import json
import logging
import base64
from typing import Dict, Any, Optional, Tuple
try:
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkcore.exceptions.exceptions import ClientRequestException
from huaweicloudsdkfunctiongraph.v2.functiongraph_client import FunctionGraphClient
from huaweicloudsdkfunctiongraph.v2.region.functiongraph_region import FunctionGraphRegion
from huaweicloudsdkfunctiongraph.v2.model.create_function_request import CreateFunctionRequest
from huaweicloudsdkfunctiongraph.v2.model.func_code import FuncCode
from huaweicloudsdkfunctiongraph.v2.model.create_function_request_body import CreateFunctionRequestBody
except ImportError as e:
print(f"Please install SDK first: pip install huaweicloudsdkfunctiongraph (Error: {e})")
sys.exit(1)
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class FunctionCreator:
"""FunctionGraph function creator"""
SUPPORTED_RUNTIMES = [
'Python3.9', 'Python3.10', 'Python3.11',
'Node.js14.18', 'Node.js16.17', 'Node.js18.15',
'Java11', 'Java17',
'Go1.x', 'Custom'
]
def __init__(self, ak: str, sk: str, region: str = 'cn-north-4', project_id: str = None):
self.ak = ak
self.sk = sk
self.region = region
self.project_id = project_id
self.client = self._init_client()
def _init_client(self) -> FunctionGraphClient:
credentials = BasicCredentials(ak=self.ak, sk=self.sk, project_id=self.project_id)
client = FunctionGraphClient.new_builder() \
.with_credentials(credentials) \
.with_region(FunctionGraphRegion.value_of(self.region)) \
.build()
return client
def validate_params(self, params: Dict[str, Any]) -> Tuple[bool, str]:
required_fields = ['function_name', 'runtime', 'code_content', 'handler']
for field in required_fields:
if not params.get(field):
return False, f"Missing required parameter: {field}"
function_name = params['function_name']
if not function_name.replace('_', '').replace('-', '').isalnum():
return False, "Function name can only contain letters, numbers, underscores and hyphens"
if len(function_name) < 1 or len(function_name) > 64:
return False, "Function name length must be between 1-64 characters"
runtime = params['runtime']
if runtime not in self.SUPPORTED_RUNTIMES:
return False, f"Unsupported runtime: {runtime}, supported: {', '.join(self.SUPPORTED_RUNTIMES)}"
memory_size = params.get('memory_size', 128)
if memory_size < 128 or memory_size > 4096 or memory_size % 128 != 0:
return False, "Memory size must be between 128-4096MB and a multiple of 128"
timeout = params.get('timeout', 3)
if timeout < 1 or timeout > 900:
return False, "Timeout must be between 1-900 seconds"
return True, ""
def create_function(self, params: Dict[str, Any]) -> Dict[str, Any]:
is_valid, error_msg = self.validate_params(params)
if not is_valid:
return {'status': 'failed', 'error_code': 'InvalidParameter', 'message': error_msg}
try:
encoded_code = base64.b64encode(params['code_content'].encode('utf-8')).decode('utf-8')
func_code = FuncCode(file=encoded_code)
request_body = CreateFunctionRequestBody(
func_name=params['function_name'],
package='default',
runtime=params['runtime'],
handler=params['handler'],
code_type='inline',
func_code=func_code,
memory_size=params.get('memory_size', 128),
timeout=params.get('timeout', 3),
description=params.get('description', '')
)
request = CreateFunctionRequest()
request.body = request_body
logger.info(f"Creating function: {params['function_name']}")
response = self.client.create_function(request)
result = {
'status': 'success',
'function_urn': response.func_urn,
'function_name': response.func_name,
'runtime': response.runtime,
'handler': response.handler,
'memory_size': response.memory_size,
'timeout': response.timeout,
'code_size': response.code_size,
'message': 'Function created successfully'
}
logger.info(f"Function created successfully: {response.func_urn}")
return result
except ClientRequestException as e:
error_code = e.error_code if hasattr(e, 'error_code') else 'Unknown'
error_msg = e.error_msg if hasattr(e, 'error_msg') else str(e)
logger.error(f"Failed to create function: {error_code} - {error_msg}")
return {'status': 'failed', 'error_code': error_code, 'message': error_msg}
except Exception as e:
logger.error(f"Exception creating function: {str(e)}")
return {'status': 'failed', 'error_code': 'InternalError', 'message': str(e)}
def load_config() -> Dict[str, str]:
config = {
'ak': os.environ.get('HUAWEI_AK'),
'sk': os.environ.get('HUAWEI_SK'),
'region': os.environ.get('HUAWEI_REGION', 'cn-north-4'),
'project_id': os.environ.get('HUAWEI_PROJECT_ID')
}
if not config['ak'] or not config['sk']:
raise ValueError("Please set environment variables HUAWEI_AK and HUAWEI_SK")
return config
def main():
import argparse
parser = argparse.ArgumentParser(description='Create FunctionGraph function')
parser.add_argument('--name', required=True, help='Function name')
parser.add_argument('--runtime', required=True, help='Runtime environment')
parser.add_argument('--handler', required=True, help='Function entry point')
parser.add_argument('--code', required=True, help='Code file path or code content')
parser.add_argument('--memory', type=int, default=128, help='Memory size (MB)')
parser.add_argument('--timeout', type=int, default=3, help='Timeout (seconds)')
parser.add_argument('--description', default='', help='Function description')
args = parser.parse_args()
try:
config = load_config()
except ValueError as e:
print(f"Config error: {e}")
sys.exit(1)
if os.path.isfile(args.code):
with open(args.code, 'r', encoding='utf-8') as f:
code_content = f.read()
else:
code_content = args.code
params = {
'function_name': args.name,
'runtime': args.runtime,
'handler': args.handler,
'code_content': code_content,
'memory_size': args.memory,
'timeout': args.timeout,
'description': args.description
}
creator = FunctionCreator(
ak=config['ak'],
sk=config['sk'],
region=config['region'],
project_id=config['project_id']
)
result = creator.create_function(params)
print(json.dumps(result, indent=2, ensure_ascii=False))
if result['status'] != 'success':
sys.exit(1)
if __name__ == '__main__':
main()