首页 > 系统相关 >nginx unit WebAssembly 试用

nginx unit WebAssembly 试用

时间:2023-10-24 12:04:44浏览次数:38  
标签:WebAssembly http uwr ctx write nginx wasm unit

nginx unit 已经支持WebAssembly ,刚好体验下

环境准备

基于docker 运行unit,对于wasm 的开发基于rust,实际上测试直接试用了官方的示例代码

  • docker-compose
version: "3"
services:
  app:
     image: unit:1.31.1-wasm
     ports:
       - 8080:8080
       - 8000:8000
     volumes:
       - ./app:/www

rust wasm 开发

基于了官方的示例

  • 安装工具
rustup target add wasm32-wasi
  • 初始化项目
cargo init --lib wasm_on_unit
  • 添加依赖
cargo add unit-wasm
  • 核心代码
/* SPDX-License-Identifier: Apache-2.0 */
 
/*
 * Copyright (C) Andrew Clayton
 * Copyright (C) Timo Stark
 * Copyright (C) F5, Inc.
 */
 
use unit_wasm::rusty::*;
 
use std::ffi::CStr;
use std::os::raw::c_char;
use std::os::raw::c_void;
use std::ptr::null_mut;
 
// Buffer of some size to store the copy of the request
static mut REQUEST_BUF: *mut u8 = null_mut();
 
#[no_mangle]
pub unsafe extern "C" fn uwr_module_end_handler() {
    uwr_free(REQUEST_BUF);
}
 
#[no_mangle]
pub unsafe extern "C" fn uwr_module_init_handler() {
    REQUEST_BUF = uwr_malloc(uwr_mem_get_init_size());
}
 
pub extern "C" fn hdr_iter_func(
    ctx: *mut luw_ctx_t,
    name: *const c_char,
    value: *const c_char,
    _data: *mut c_void,
) -> bool {
    uwr_write_str!(ctx, "{} = {}\n", C2S!(name), C2S!(value));
 
    return true;
}
 
#[no_mangle]
pub extern "C" fn uwr_request_handler(addr: *mut u8) -> i32 {
    // Declare a 0-initialised context structure
    let ctx = &mut UWR_CTX_INITIALIZER();
    // Initialise the context structure.
    //
    // addr is the address of the previously allocated memory shared
    // between the module and unit.
    //
    // The response data will be stored @ addr + offset (of 4096 bytes).
    // This will leave some space for the response headers.
    uwr_init_ctx(ctx, addr, 4096);
 
    // Set where we will copy the request into
    uwr_set_req_buf(ctx, unsafe { &mut REQUEST_BUF }, LUW_SRB_NONE);
 
    // Define the Response Body Text.
 
    uwr_write_str!(
        ctx,
        " * Welcome to WebAssembly in Rust on Unit! \
            [libunit-wasm ({}.{}.{}/{:#010x})] *\n\n",
        LUW_VERSION_MAJOR,
        LUW_VERSION_MINOR,
        LUW_VERSION_PATCH,
        LUW_VERSION_NUMBER,
    );
 
    uwr_write_str!(ctx, "[Request Info]\n");
 
    uwr_write_str!(ctx, "REQUEST_PATH = {}\n", uwr_get_http_path(ctx));
    uwr_write_str!(ctx, "METHOD       = {}\n", uwr_get_http_method(ctx));
    uwr_write_str!(ctx, "VERSION      = {}\n", uwr_get_http_version(ctx));
    uwr_write_str!(ctx, "QUERY        = {}\n", uwr_get_http_query(ctx));
    uwr_write_str!(ctx, "REMOTE       = {}\n", uwr_get_http_remote(ctx));
    uwr_write_str!(ctx, "LOCAL_ADDR   = {}\n", uwr_get_http_local_addr(ctx));
    uwr_write_str!(ctx, "LOCAL_PORT   = {}\n", uwr_get_http_local_port(ctx));
    uwr_write_str!(ctx, "SERVER_NAME  = {}\n", uwr_get_http_server_name(ctx));
 
    uwr_write_str!(ctx, "\n[Request Headers]\n");
 
    uwr_http_hdr_iter(ctx, Some(hdr_iter_func), null_mut());
 
    let method = uwr_get_http_method(ctx);
    if method == "POST" || method == "PUT" {
        uwr_write_str!(ctx, "\n[{} data]\n", method);
        uwr_mem_write_buf(
            ctx,
            uwr_get_http_content(ctx),
            uwr_get_http_content_len(ctx),
        );
        uwr_write_str!(ctx, "\n");
    }
 
    // Init Response Headers
    //
    // Needs the context, number of headers about to add as well as
    // the offset where to store the headers. In this case we are
    // storing the response headers at the beginning of our shared
    // memory at offset 0.
    uwr_http_init_headers(ctx, 2, 0);
    uwr_http_add_header_content_type(ctx, "text/plain");
    uwr_http_add_header_content_len(ctx);
 
    // This calls nxt_wasm_send_headers() in Unit
    uwr_http_send_headers(ctx);
 
    // This calls nxt_wasm_send_response() in Unit
    uwr_http_send_response(ctx);
 
    // This calls nxt_wasm_response_end() in Unit
    uwr_http_response_end();
 
    return 0;
}

启动&效果

  • 启动
docker-compose up -d
  • 配置
    在容器内部运行
 
curl -X PUT --data-binary '{
      "listeners": {
          "0.0.0.0:8080": {
              "pass": "applications/wasm"
          }
      },
 
      "applications": {
          "wasm": {
              "type": "wasm",
              "module": "/www/wasm_on_unit.wasm",
              "request_handler": "uwr_request_handler",
              "malloc_handler": "luw_malloc_handler",
              "free_handler": "luw_free_handler",
              "module_init_handler": "uwr_module_init_handler",
              "module_end_handler": "uwr_module_end_handler"
          }
      }
  }' --unix-socket /var/run/control.unit.sock http://localhost/config/
  • 效果

 

说明

目前api7也提供了一个nginx 的扩展应该也是可以运行wasm的,但是还没测试,社区也有一个修改版本的nginx 可以支持(但是已经不维护了)

参考资料

https://unit.nginx.org/configuration/#configuration-wasm
https://unit.nginx.org/howto/samples/#sample-wasm
https://github.com/WebAssembly/wasi-sdk
https://github.com/rongfengliang/nginx-unit-wasm-learning
https://github.com/api7/wasm-nginx-module
https://syrusakbary.medium.com/running-nginx-with-webassembly-6353c02c08ac
https://github.com/nginx/unit/blob/fb33ec86a3b6ca6a844dfa6980bb9e083094abec/pkg/docker/Dockerfile.wasm

标签:WebAssembly,http,uwr,ctx,write,nginx,wasm,unit
From: https://www.cnblogs.com/rongfengliang/p/17784458.html

相关文章

  • 记录一下nginx遇到的问题
    nginx将ip配置成https,如:https://192.168.1.1/,以及nginx.conf中proxy_pass转发的配置记录。将ip配置httpsnginx:[emerg]no"ssl_certificate"isdefinedforthe"listen...ssl"directivein/usr/local/nginx/conf/conf.d/upstream.conf:14意思是ssl_certificate没有配置,可......
  • 循序渐进介绍基于CommunityToolkit.Mvvm 和HandyControl的WPF应用端开发(1)
    在我们的SqlSugar的开发框架中,整合了Winform端、Vue3+ElementPlus的前端、以及基于UniApp+Vue+ThorUI的移动前端几个前端处理,基本上覆盖了我们日常的应用模式了,本篇随笔进一步介绍前端应用的领域,研究集成WPF的应用端,循序渐进介绍基于CommunityToolkit.Mvvm和HandyControl的WPF应用......
  • centos安装nginx
    目录1、下载安装包2、安装nginx2.1、安装依赖库2.2、安装nginx包2.2.1、解压安装包2.2.2、拷贝文件到/usr/local目录2.2.3、检测当前系统环境2.2.4、编译2.2.5、安装3、配置nginx开机启动4、测试 1、下载安装包官网下载wgethttp://nginx.org/downl......
  • CDN+Nginx反向代理来隐藏c2地址
    思路:通过借助CDN和Nginx反向代理和HTTPS来隐藏真实c2服务器Nginx反向代理:通过Nginx对外部流量转发到本地,再设置防火墙只允许localhost访问cs端口达到IP白名单的效果准备在这个实验环境中,我们需要准备服务器两台(一台服务端、一台靶机)、CDN运营商(这里用的是cloudflare)、域名一......
  • Unity中国、Cocos为OpenHarmony游戏生态插上腾飞的翅膀
    Unity中国、Cocos为OpenHarmony游戏生态插上腾飞的翅膀2023年是OpenHarmony游戏生态百花齐放的一年!为了扩展OpenHarmony游戏生态,OpenHarmony在基金会成立了游戏SIG小组,游戏SIG小组联合cocos,从cocos2dx入手一周内快速适配了cocos2.2.6的MVP版本,随后又分别适配了cocos2dx 3.x、4.x版......
  • Nginx实现内外网穿透
    声明:以下内容均收集与互联网,无法保证绝对可用性,请结合自身情况调整验证。随着网络安全的要求逐步提高,部分应用服务要求部署在内网,但是应用中有需要访问到公网服务,比如发票验真、OCR识别等,可以通过部署在DMZ区的Nginx实现。假设公网API服务地址为:https://api.myserver.com/ocr......
  • Nginx的安装-Linux
    下载地址#如果没有gcc环境,需要安装gcc:[root@localhostlocal]#yuminstallgcc-c++-y#安装依赖包[root@localhostlocal]#yum-yinstallgcczlibzlib-develpcre-developensslopenssl-devel#进入文件夹[root@localhostlocal]#cd/usr/local#在线下载或者上传......
  • Nginx 1
    一、关于Nginx1.NginxNginx同Apache一样都是一种WEB服务器。基于REST架构风格,以统一资源描述符(UniformResourcesIdentifier)URI或者统一资源定位符(UniformResourcesLocator)URL作为沟通依据,通过HTTP协议提供各种网络服务。Nginx是一个跨平台服务器,可以运行在Linux,Windows,Free......
  • Unity3D学习记录04——利用射线实现角色类似LOL的移动
    首先新建一个空白的GameObject,挂在一个MouseManager的脚本实现思路:通过获取鼠标点击的位置,获得该位置的信息,然后使角色移动到该位置MouseManager脚本的代码如下:1usingSystem.Collections;2usingSystem.Collections.Generic;3usingUnityEngine;4usingUnityEngi......
  • Unity中国、Cocos为OpenHarmony游戏生态插上腾飞的翅膀
     2023年是OpenHarmony游戏生态百花齐放的一年!为了扩展OpenHarmony游戏生态,OpenHarmony在基金会成立了游戏SIG小组,游戏SIG小组联合cocos,从cocos2dx入手一周内快速适配了cocos2.2.6的MVP版本,随后又分别适配了cocos2dx 3.x、4.x版本以及cocos creator的2.4.12和3.18版本并在官......