# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

worker_processes  1;
daemon off;
error_log /dev/stdout error;

events {
    worker_connections 1024;
}

http {
    resolver local=on ipv6=off;
    # lua_package_path "/usr/local/openresty/luajit/share/lua/5.1/skywalking/?.lua;;";
    # Buffer represents the register inform and the queue of the finished segment
    lua_shared_dict tracing_buffer 100m;

    # Init is the timer setter and keeper
    # Setup an infinite loop timer to do register and trace report.
    init_worker_by_lua_block {
        local metadata_buffer = ngx.shared.tracing_buffer

        metadata_buffer:set('serviceName', 'User_Service_Name')
        -- Instance means the number of Nginx deployment, does not mean the worker instances
        metadata_buffer:set('serviceInstanceName', 'User_Service_Instance_Name')

        require("skywalking.client"):startBackendTimer("http://oap:12800")
    }

    log_format sw_trace escape=json "$uri $request_body";

    server {
        listen 8080;

        location /nginx/info {

            rewrite_by_lua_block {
                require("skywalking.tracer"):start("User_Service_Name", {nginx = "nginx_value"})
            }

            proxy_pass http://provider-end:9090/nginx/end/info;

            body_filter_by_lua_block {
                require("skywalking.tracer"):finish()
            }

            log_by_lua_block {
                require("skywalking.tracer"):prepareForReport()
            }
        }
    }
}
