Exemplo n.º 1
0
        public void Initialize(IFcContext context)
        {
            ILogger logger = context.Logger;

            logger.LogInformation(String.Format("RequestID is {0} ", context.RequestId));
            this.counter = this.counter + 1;
        }
Exemplo n.º 2
0
        public void Initializer(IFcContext context)
        {
            SqlConnection myConn = null;

            try
            {
                myConn = new SqlConnection(connStr);
                myConn.Open();

                SqlCommand myCmd = new SqlCommand(@"
                if not exists(select * from sysobjects where name='users' and xtype='U')
                create table users (
                    id varchar(64) not null,
                    name varchar(128) not null,
                    PRIMARY KEY(id)
                )", myConn);
                myCmd.ExecuteNonQuery();

                Console.WriteLine("表创建成功!");

                myCmd.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (myConn != null)
                {
                    myConn.Close();
                }
            }
        }
Exemplo n.º 3
0
        public void Initializer(IFcContext context)
        {
            MySqlConnection myConn = null;

            try
            {
                myConn = new MySqlConnection(connStr);
                myConn.Open();

                MySqlCommand myCmd = new MySqlCommand(@"CREATE TABLE IF NOT EXISTS users (
                    id  VARCHAR(64) NOT NULL,
                    name    VARCHAR(128) NOT NULL,
                    PRIMARY KEY(id))", myConn);
                myCmd.ExecuteNonQuery();

                Console.WriteLine("表创建成功!");

                myCmd.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (myConn != null)
                {
                    myConn.Close();
                }
            }
        }
Exemplo n.º 4
0
        public Stream TestLogger(Stream input, IFcContext context)
        {
            context.Logger.EnabledLogLevel = LogLevel.Error;
            context.Logger.LogError("console error 1");
            context.Logger.LogInformation("console info 1");
            context.Logger.LogWarning("console warn 1");
            context.Logger.LogDebug("console debug 1");

            context.Logger.EnabledLogLevel = LogLevel.Warning;

            context.Logger.LogError("console error 2");
            context.Logger.LogInformation("console info 2");
            context.Logger.LogWarning("console warn 2");
            context.Logger.LogDebug("console debug 2");

            context.Logger.EnabledLogLevel = LogLevel.Information;
            context.Logger.LogInformation("Handle request: {0}", context.RequestId);

            byte[]       hello  = Encoding.UTF8.GetBytes("hello world");
            MemoryStream output = new MemoryStream();

            output.Write(hello, 0, hello.Length);
            output.Seek(0, SeekOrigin.Begin);
            return(output);
        }
Exemplo n.º 5
0
        // optional serializer class, if it’s not specified, the default serializer (based on JSON.Net) will be used.
        // [FcSerializer(typeof(MySerialization))]
        public Product EchoPoco(Product product, IFcContext context)
        {
            int    Id          = product.Id;
            string Description = product.Description;

            context.Logger.LogInformation("Id {0}, Description {1}", Id, Description);
            return(product);
        }
Exemplo n.º 6
0
        public async Task <Stream> AsyncEchoEvent(Stream input, IFcContext context)
        {
            context.Logger.LogInformation("Handle request: {0}", context.RequestId);
            MemoryStream copy = new MemoryStream();
            await input.CopyToAsync(copy);

            copy.Seek(0, SeekOrigin.Begin);
            return(copy);
        }
Exemplo n.º 7
0
        public Stream Handler(Stream input, IFcContext context)
        {
            ILogger logger = context.Logger;

            logger.LogDebug(string.Format("Handle request {0}", context.RequestId));
            string   data     = new StreamReader(input).ReadToEnd();
            OSSEvent ossEvent = JsonConvert.DeserializeObject <OSSEvent>(data);

            return(HandlePoco(ossEvent, context));
        }
Exemplo n.º 8
0
        public void Handle(Stream input, IFcContext context)
        {
            ILogger logger     = context.Logger;
            var     ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());

            logger.LogInformation($"Handle request: {context.RequestId}");

            foreach (var ipAddress in ipHostInfo.AddressList)
            {
                logger.LogInformation($"IP Address:{ipAddress}");
            }
        }
Exemplo n.º 9
0
        public Stream Handler(Stream input, IFcContext context)
        {
            SqlConnection myConn = null;

            try
            {
                myConn = new SqlConnection(connStr);
                myConn.Open();
                SqlCommand myCmd = new SqlCommand(@"
                merge users as target
                using (values('csharp')) 
                    as source(name)
                    on target.id = '5'
                when matched then
                    update
                    set name = source.name
                when not matched then
                    insert (id, name)
                    values( '5', source.name);
                ", myConn);
                if (myCmd.ExecuteNonQuery() > 0)
                {
                    Console.WriteLine("数据插入成功!");
                }
                myCmd.Dispose();

                myCmd = new SqlCommand("SELECT * FROM users", myConn);
                SqlDataReader rdr = myCmd.ExecuteReader();

                String res = "";
                while (rdr.Read())
                {
                    res += $", {rdr.GetString(1)}";
                }
                res = res.Substring(1, res.Length - 1);
                myCmd.Dispose();

                return(new MemoryStream(Encoding.UTF8.GetBytes(res)));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (myConn != null)
                {
                    myConn.Close();
                }
            }
        }
Exemplo n.º 10
0
        public Stream HandleRequest(Stream input, IFcContext context)
        {
            ILogger logger = context.Logger;

            logger.LogInformation(String.Format("Event {0} ", StreamToString(input)));
            logger.LogInformation(String.Format("Context {0} ", Newtonsoft.Json.JsonConvert.SerializeObject(context)));
            logger.LogInformation(String.Format("Handle request {0} ", context.RequestId));

            byte[]       data   = Encoding.UTF8.GetBytes("Hello World!");
            MemoryStream output = new MemoryStream();

            output.Write(data, 0, data.Length);
            output.Flush();
            return(output);
        }
Exemplo n.º 11
0
        public Stream HandlePoco(OSSEvent ossEvent, IFcContext context)
        {
            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output);

            foreach (OSSEvent.Event evnt in ossEvent.events)
            {
                writer.Write(string.Format("received {0} from {1} @ {2}", evnt.eventName, evnt.eventSource, evnt.region));
                writer.Write(string.Format("received bucket {0}", evnt.oss.bucket.arn));
                writer.Write(string.Format("received object {0} and it's size is {1}", evnt.oss.obj.key, evnt.oss.obj.size));
            }
            writer.Flush();

            return(output);
        }
Exemplo n.º 12
0
        public Stream GetOssFile(OssFileHandlerRequest req, IFcContext context)
        {
            if (req == null)
            {
                throw new ArgumentNullException(nameof(req));
            }
            if (context == null || context.Credentials == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            OssClient ossClient = new OssClient(req.Endpoint, context.Credentials.AccessKeyId, context.Credentials.AccessKeySecret, context.Credentials.SecurityToken);
            OssObject obj       = ossClient.GetObject(req.Bucket, req.Key);

            return(obj.Content);
        }
Exemplo n.º 13
0
        public Stream Handler(Stream input, IFcContext context)
        {
            ILogger logger = context.Logger;

            logger.LogDebug(string.Format("Handle request {0}", context.RequestId));
            var cbor = CBORObject.Read(input);

            // do your things with cbor

            byte[]       hello  = Encoding.UTF8.GetBytes("hello world");
            MemoryStream output = new MemoryStream();

            output.Write(hello, 0, hello.Length);
            output.Seek(0, SeekOrigin.Begin);
            return(output);
        }
Exemplo n.º 14
0
        public string Handler(Stream input, IFcContext context)
        {
            String fileName = Environment.GetEnvironmentVariable("FileName");
            String source   = $"/tmp/{fileName}";
            String dest     = fileName;
            String cmd      = $"tar -cpzf {source} --numeric-owner --ignore-failed-read /var/fc/runtime";

            var process = new Process()
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName  = "/bin/bash",
                    Arguments = $"-c \"{cmd}\"",
                    RedirectStandardOutput = true,
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                }
            };

            process.Start();
            string result = process.StandardOutput.ReadToEnd();

            process.WaitForExit();

            OssClient ossClient = new OssClient(
                Environment.GetEnvironmentVariable("OSSEndpoint"),
                context.Credentials.AccessKeyId,
                context.Credentials.AccessKeySecret,
                context.Credentials.SecurityToken
                );

            try
            {
                // 上传文件。
                ossClient.PutObject(
                    Environment.GetEnvironmentVariable("Bucket"),
                    dest,
                    source
                    );
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            return(result);
        }
Exemplo n.º 15
0
        public Stream Handler(Stream input, IFcContext context)
        {
            MySqlConnection myConn = null;

            try
            {
                myConn = new MySqlConnection(connStr);
                myConn.Open();
                MySqlCommand myCmd = new MySqlCommand("REPLACE INTO users (`id`,`name`) values('5','csharp')", myConn);
                if (myCmd.ExecuteNonQuery() > 0)
                {
                    Console.WriteLine("数据插入成功!");
                }
                myCmd.Dispose();

                myCmd = new MySqlCommand("SELECT * FROM users", myConn);
                MySqlDataReader rdr = myCmd.ExecuteReader();

                String res = "";
                while (rdr.Read())
                {
                    res += $", {rdr.GetString(1)}";
                }
                res = res.Substring(1, res.Length - 1);
                myCmd.Dispose();

                return(new MemoryStream(Encoding.UTF8.GetBytes(res)));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (myConn != null)
                {
                    myConn.Close();
                }
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Convert the JSON document received from API Gateway into the InvokeFeatures object.
        /// InvokeFeatures is then passed into IHttpApplication to create the ASP.NET Core request objects.
        /// </summary>
        /// <param name="features">Features.</param>
        /// <param name="request">Request.</param>
        /// <param name="fcContext">Fc context.</param>
        protected void MarshallRequest(InvokeFeatures features, HttpRequest request, IFcContext fcContext)
        {
            {
                var requestFeatures = (IHttpRequestFeature)features;
                requestFeatures.Scheme = "https";
                requestFeatures.Method = request.Method;

                requestFeatures.Path        = request.Path; // the PathString ensures it starts with "/";
                requestFeatures.PathBase    = request.PathBase;
                requestFeatures.QueryString = request.QueryString.Value;
                requestFeatures.Headers     = request.Headers;
                requestFeatures.Body        = request.Body;

                // Call consumers customize method in case they want to change how API request
                // was marshalled into ASP.NET Core request.
                PostMarshallRequestFeature(requestFeatures, request, fcContext);
            }


            {
                // set up connection features
                var connectionFeatures = (IHttpConnectionFeature)features;
                connectionFeatures.RemoteIpAddress = request?.HttpContext?.Connection?.RemoteIpAddress;
                if (request?.HttpContext?.Connection?.RemotePort != null)
                {
                    connectionFeatures.RemotePort = (request?.HttpContext?.Connection?.RemotePort).Value;
                }

                if (request?.Headers?.ContainsKey("X-Forwarded-Port") == true)
                {
                    connectionFeatures.RemotePort = int.Parse(request.Headers["X-Forwarded-Port"]);
                }

                // Call consumers customize method in case they want to change how API Gateway's request
                // was marshalled into ASP.NET Core request.
                PostMarshallConnectionFeature(connectionFeatures, request, fcContext);
            }
        }
Exemplo n.º 17
0
        public Stream Handler(Stream input, IFcContext context)
        {
            RedisCache cache = new RedisCache(new RedisCacheOptions
            {
                Configuration = connStr
            });

            var counterBytes = cache.Get("dotnet_counter");
            var counter      = 0;

            if (counterBytes != null)
            {
                counter = BitConverter.ToInt32(counterBytes, 0);
            }
            Console.WriteLine($"Counter: {counter}");

            cache.Set("dotnet_counter", BitConverter.GetBytes(counter + 1));

            counterBytes = BitConverter.GetBytes(counter);
            MemoryStream output = new MemoryStream(counterBytes);

            return(output);
        }
Exemplo n.º 18
0
        public Stream Handler(Stream input, IFcContext context)
        {
            var client     = new MongoClient(connectionUrl);
            var database   = client.GetDatabase(dbName);
            var collection = database.GetCollection <BsonDocument>("fc_col");
            var document   = new BsonDocument
            {
                { "DEMO", "FC" },
                { "MSG", "Hello FunctionCompute For MongoDB" }
            };

            collection.InsertOne(document);
            var doc = collection.Find(new BsonDocument {
                { "DEMO", "FC" }
            }).FirstOrDefault();

            Console.WriteLine(doc.ToString());

            byte[]       docBytes = Encoding.UTF8.GetBytes(doc.ToString());
            MemoryStream output   = new MemoryStream();

            output.Write(docBytes, 0, docBytes.Length);
            return(output);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Processes the current request.
        /// </summary>
        /// <param name="fcContext"><see cref="IFcContext"/> implementation.</param>
        /// <param name="context">The hosting application request context object.</param>
        /// <param name="features">An <see cref="InvokeFeatures"/> instance.</param>
        /// <param name="rethrowUnhandledError">
        /// If specified, an unhandled exception will be rethrown for custom error handling.
        /// Ensure that the error handling code calls 'this.MarshallResponse(features, 500);' after handling the error to return a <see cref="HttpResponse"/> to the user.
        /// </param>
        protected async Task <HttpResponse> ProcessRequest(IFcContext fcContext, HostingApplication.Context context, InvokeFeatures features, HttpResponse response, bool rethrowUnhandledError = false)
        {
            var       defaultStatusCode = 200;
            Exception ex = null;

            try
            {
                await this._server.Application.ProcessRequestAsync(context);
            }
            catch (AggregateException agex)
            {
                ex = agex;
                Logger.LogError($"Caught AggregateException: '{agex}'");
                var sb = new StringBuilder();
                foreach (var newEx in agex.InnerExceptions)
                {
                    sb.AppendLine(this.ErrorReport(newEx));
                }

                Logger.LogError(sb.ToString());
                defaultStatusCode = 500;
            }
            catch (ReflectionTypeLoadException rex)
            {
                ex = rex;
                Logger.LogError($"Caught ReflectionTypeLoadException: '{rex}'");
                var sb = new StringBuilder();
                foreach (var loaderException in rex.LoaderExceptions)
                {
                    var fileNotFoundException = loaderException as FileNotFoundException;
                    if (fileNotFoundException != null && !string.IsNullOrEmpty(fileNotFoundException.FileName))
                    {
                        sb.AppendLine($"Missing file: {fileNotFoundException.FileName}");
                    }
                    else
                    {
                        sb.AppendLine(this.ErrorReport(loaderException));
                    }
                }

                Logger.LogError(sb.ToString());
                defaultStatusCode = 500;
            }
            catch (Exception e)
            {
                ex = e;
                if (rethrowUnhandledError)
                {
                    throw;
                }
                Logger.LogError($"Unknown error responding to request: {this.ErrorReport(e)}");
                defaultStatusCode = 500;
            }
            finally
            {
                this._server.Application.DisposeContext(context, ex);
            }

            if (features.ResponseStartingEvents != null)
            {
                await features.ResponseStartingEvents.ExecuteAsync();
            }

            this.MarshallResponse(features, fcContext, response, defaultStatusCode);

            if (features.ResponseCompletedEvents != null)
            {
                await features.ResponseCompletedEvents.ExecuteAsync();
            }

            return(response);
        }
Exemplo n.º 20
0
        public override async Task <HttpResponse> HandleRequest(HttpRequest request, HttpResponse response, IFcContext fcContext)
        {
            response.StatusCode  = 200;
            response.ContentType = "text/plain";
            await response.WriteAsync("hello world");

            return(response);
        }
Exemplo n.º 21
0
        /// <summary>
        /// 阿里系统入口函数
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="fcContext"></param>
        /// <returns></returns>
        public override async Task <HttpResponse> HandleRequest(HttpRequest request, HttpResponse response, IFcContext fcContext)
        {
            string msg = "";

            try
            {
                StreamReader sr = new StreamReader(request.Body);
                // 获取到API的请求参数
                string requestBody = sr.ReadToEnd();
                // Todo 我们的业务逻辑处理 .....

                //组织接口返回的数据
                msg = "{ \"Flag\" : \"true\", \"Msg\" : \"Reviced Data :" + requestBody + "\" }";
            }
            catch (Exception e)
            {
                msg = e.Message + e.StackTrace;
            }
            finally
            {
                response.StatusCode = 200;
                response.Headers.Add("Access-Control-Allow-Origin", "*");
                response.Headers.Add("Cache-Control", "no-cache");
                response.Headers["Content-Type"] = "application/json;charset=utf-8";
                await response.WriteAsync(msg);
            }


            return(response);
        }
Exemplo n.º 22
0
 /// <summary>
 /// This method is called after the FcHttpEntrypoint has marshalled the incoming API Gateway request
 /// into ASP.NET Core's IHttpConnectionFeature. Derived classes can overwrite this method to alter
 /// the how the marshalling was done.
 /// </summary>
 /// <param name="aspNetCoreConnectionFeature">ASP net core connection feature.</param>
 /// <param name="request">Request.</param>
 /// <param name="fcContext">Fc context.</param>
 protected virtual void PostMarshallConnectionFeature(IHttpConnectionFeature aspNetCoreConnectionFeature, HttpRequest request, IFcContext fcContext)
 {
 }
Exemplo n.º 23
0
 /// <summary>
 /// This method is called after the FcHttpEntrypoint has marshalled IHttpResponseFeature that came
 /// back from making the request into ASP.NET Core into API Gateway's response object HttpResonse. Derived classes can overwrite this method to alter
 /// the how the marshalling was done.
 /// </summary>
 /// <param name="aspNetCoreResponseFeature">ASP net core response feature.</param>
 /// <param name="response">Response.</param>
 /// <param name="fcContext">Fc context.</param>
 protected virtual void PostMarshallResponseFeature(IHttpResponseFeature aspNetCoreResponseFeature, HttpResponse response, IFcContext fcContext)
 {
 }
Exemplo n.º 24
0
 public string Handler(Stream input, IFcContext context)
 {
     return("hello word");
 }
Exemplo n.º 25
0
 /// <summary>
 /// This method is called after the HostingApplication.Context has been created. Derived classes can overwrite this method to alter
 /// the context before passing the request to ASP.NET Core to process the request.
 /// </summary>
 /// <param name="context">Context.</param>
 /// <param name="request">Request.</param>
 /// <param name="fcContext">Fc context.</param>
 protected virtual void PostCreateContext(HostingApplication.Context context, HttpRequest request, IFcContext fcContext)
 {
 }
Exemplo n.º 26
0
        /// <summary>
        /// Convert the response coming from ASP.NET Core into APIGatewayProxyResponse which is
        /// serialized into the JSON object that API Gateway expects.
        /// </summary>
        /// <returns>The response.</returns>
        /// <param name="responseFeatures">Response features.</param>
        /// <param name="fcContext">Fc context.</param>
        /// <param name="statusCodeIfNotSet">Status code if not set.</param>
        protected HttpResponse MarshallResponse(IHttpResponseFeature responseFeatures, IFcContext fcContext, HttpResponse response, int statusCodeIfNotSet = 200)
        {
            response.StatusCode = responseFeatures.StatusCode != 0 ? responseFeatures.StatusCode : statusCodeIfNotSet;
            string contentType = null;

            if (responseFeatures.Headers != null)
            {
                foreach (var kvp in responseFeatures.Headers)
                {
                    response.Headers[kvp.Key] = kvp.Value;

                    // Remember the Content-Type for possible later use
                    if (kvp.Key.Equals("Content-Type", StringComparison.CurrentCultureIgnoreCase))
                    {
                        contentType = response.Headers[kvp.Key];
                    }
                }
            }

            if (contentType == null)
            {
                response.Headers["Content-Type"] = StringValues.Empty;
            }

            response.Body = responseFeatures.Body;

            PostMarshallResponseFeature(responseFeatures, response, fcContext);

            return(response);
        }
Exemplo n.º 27
0
        public void Handle(Stream input, IFcContext context)
        {
            ILogger logger = context.Logger;

            logger.LogInformation($"Handle request: {context.RequestId}");
        }
Exemplo n.º 28
0
        public override async Task <HttpResponse> HandleRequest(HttpRequest request, HttpResponse response, IFcContext fcContext)
        {
            //尝试获取环境变量
            //fcContext.Logger.LogInformation("尝试获取环境变量:" + Environment.GetEnvironmentVariable("worktile_url"));
            string worktile_url = Environment.GetEnvironmentVariable("worktile_url");

            if (string.IsNullOrEmpty(worktile_url))
            {
                response.StatusCode = 502;
                fcContext.Logger.LogError("未配置有效的环境变量 worktile_url");
                await response.WriteAsync("not config about worktile url. \n 检查环境变量:worktile_url");

                return(response);
            }

            //尝试获取json
            if (request.ContentLength != null && request.ContentLength.Value > 0)
            {
                var stream = request.Body;
                var buffer = new byte[request.ContentLength.Value];
                stream.Read(buffer, 0, buffer.Length);
                string content = Encoding.UTF8.GetString(buffer);

                //fcContext.Logger.LogInformation("读取到json:\n" + content);


                //解析
                var json_obj = JsonConvert.DeserializeObject <UnityCloudBuildWebHookJsonModel>(content);


                //先直接尝试发送给worktile
                requestWorktile send_obj;
                if (GetWorktileRequest(json_obj, out send_obj))
                {
                    var json_str   = JsonConvert.SerializeObject(send_obj);
                    var json_bytes = Encoding.UTF8.GetBytes(json_str);
                    Post(worktile_url, json_bytes);

                    response.StatusCode = 200;
                    await response.WriteAsync("finish");
                }
                else
                {
                    response.StatusCode = 403;
                    await response.WriteAsync("emmmmm");
                }
            }
            else
            {
                response.StatusCode = 403;
                await response.WriteAsync("error request.");
            }



            return(response);
        }
Exemplo n.º 29
0
        public virtual async Task <HttpResponse> HandleRequest(HttpRequest request, HttpResponse response, IFcContext fcContext)
        {
            Logger = fcContext.Logger;
            if (!IsStarted)
            {
                _pathBase = request.PathBase;
                Logger.LogInformation("Setting global PathBase {0}", _pathBase);
                Start();
            }

            Logger.LogDebug("Incoming {0} requests Path: {1}, Pathbase {2}", request.Method, request.Path, request.PathBase);

            InvokeFeatures features = new InvokeFeatures();

            MarshallRequest(features, request, fcContext);
            Logger.LogDebug($"ASP.NET Core Request PathBase: {((IHttpRequestFeature)features).PathBase}, Path: {((IHttpRequestFeature)features).Path}");

            var httpContext = this.CreateContext(features);

            if (request?.HttpContext?.User != null)
            {
                httpContext.HttpContext.User = request.HttpContext.User;
            }

            // Add along the Lambda objects to the HttpContext to give access to FC to them in the ASP.NET Core application
            httpContext.HttpContext.Items[FC_CONTEXT] = fcContext;

            // Allow the context to be customized before passing the request to ASP.NET Core.
            PostCreateContext(httpContext, request, fcContext);

            await this.ProcessRequest(fcContext, httpContext, features, response);

            return(response);
        }