Exemplo n.º 1
0
        public async Task <IActionResult> ReCheckTaskSolutions(int taskId)
        {
            var sols = _db.StudentResults.Where(r => r.TaskId == taskId).Select(r => r.Solution).ToList();

            if (sols is null || sols.Count == 0)
            {
                return(NotFound());
            }

            //запускаем тестирование посылая сообщение микросервису
            try
            {
                var msgQueue = RabbitHutch.CreateBus(_config.MessageQueueInfo, _config.FrontEnd);

                foreach (var sol in sols)
                {
                    sol.ResultCode = ResultCode.NT;
                    var request = new SolutionTestingRequest
                    {
                        SolutionId = sol.Id,
                        ReCheck    = true,
                    };
                    await msgQueue.SendAsync(_config.MessageQueueInfo.TestingQueueName, request);
                }
            }
            catch (RabbitMQ.Client.Exceptions.BrokerUnreachableException e)
            {
                return(Content("error"));
            }

            _db.SaveChanges();

            return(Content("ok"));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> ReCheckSolution(int id)
        {
            var sol = _db.Solutions.Find(id);

            if (sol is null)
            {
                return(NotFound());
            }

            sol.ResultCode = ResultCode.NT;

            //запускаем тестирование посылая сообщение микросервису
            try
            {
                var msgQueue = RabbitHutch.CreateBus(_config.MessageQueueInfo, _config.FrontEnd);

                var request = new SolutionTestingRequest
                {
                    SolutionId = sol.Id,
                    ReCheck    = true,
                };
                await msgQueue.SendAsync(_config.MessageQueueInfo.TestingQueueName, request);
            }
            catch (RabbitMQ.Client.Exceptions.BrokerUnreachableException e)
            {
                return(Content("error"));
            }

            _db.SaveChanges();

            return(Content("ok"));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> CheckSolution(IFormFile file, int taskId, string framework)
        {
            var task = _db.StudentTasks.Find(taskId);

            if (task == null)
            {
                var response1 = new
                {
                    status = "error",
                    data   = "No task found!"
                };
                return(Json(response1));
            }

            if (!CanSend(task, curId))
            {
                var response2 = new
                {
                    status = "error",
                    data   = "Can't send new solutions!"
                };
                return(Json(response2));
            }

            if (file != null)
            {
                string dirPath = "c:/TemporaryTaskDownloads";

                dirPath += "/" + Guid.NewGuid().ToString();
                while (Directory.Exists(dirPath))
                {
                    dirPath += "/" + Guid.NewGuid().ToString();
                }

                var dir = Directory.CreateDirectory(dirPath);

                string fullZipFilePath = dirPath + "/" + file.FileName;
                string fullDirPath     = dirPath + "/unpacked";

                // сохраняем файл в папку
                using (var fileStream = new FileStream(fullZipFilePath, FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
                ZipFile.ExtractToDirectory(fullZipFilePath, fullDirPath, true);

                //ищем файл проекта
                var pathToProj = FindProjectFile(dir);

                if (pathToProj == null)
                {
                    var response2 = new
                    {
                        status = "error",
                        data   = "No project file found!"
                    };
                    return(Json(response2));
                }

                //чистим от бинарных файлов
                CleanSolutionFiles(fullDirPath);

                //сжимаем очищенные файлы обратно в архив
                string newfullZipFilePath = dirPath + "/cleaned_" + file.FileName;
                ZipFile.CreateFromDirectory(fullDirPath, newfullZipFilePath);

                //записываем файл с архивом в базу
                var dataBytes = System.IO.File.ReadAllBytes(newfullZipFilePath);

                int fileId = _db.UploadFile(file.FileName, dataBytes);

                if (fileId == -1)
                {
                    var response2 = new
                    {
                        status = "error",
                        data   = "Can't upload file to db!"
                    };
                    return(Json(response2));
                }

                dir.Delete(true);

                //записываем новое решение в базу
                var solution = new Solution
                {
                    TaskId        = taskId,
                    FrameworkType = framework,
                    FileId        = fileId,
                    StudentId     = curId,
                    ResultCode    = ResultCode.NT,
                    Time          = DateTime.Now,
                };

                var  x           = _db.Solutions.Add(solution);
                var  beforeState = x.State;
                int  r           = _db.SaveChanges();
                var  afterState  = x.State;
                bool ok          = beforeState == EntityState.Added && afterState == EntityState.Unchanged && r == 1;

                if (!ok)
                {
                    var response2 = new
                    {
                        status = "error",
                        data   = "Error on writing solution to db!"
                    };
                    return(Json(response2));
                }

                //если это первое решение - записываем как результат
                var studentResult = _db.StudentResults.Find(curId, taskId);

                if (studentResult is null)
                {
                    var newResult = new StudentResult
                    {
                        StudentId  = curId,
                        TaskId     = taskId,
                        SolutionId = solution.Id
                    };

                    var x1 = _db.StudentResults.Add(newResult);
                    beforeState = x1.State;
                    r           = _db.SaveChanges();
                    afterState  = x1.State;
                    ok          = beforeState == EntityState.Added && afterState == EntityState.Unchanged && r == 1;

                    if (!ok)
                    {
                        var response2 = new
                        {
                            status = "error",
                            data   = "Error on writing result to db!"
                        };
                        return(Json(response2));
                    }
                }


                //запускаем тестирование посылая сообщение микросервису
                try
                {
                    var msgQueue = RabbitHutch.CreateBus(_config.MessageQueueInfo, _config.FrontEnd);

                    var request = new SolutionTestingRequest
                    {
                        SolutionId = solution.Id,
                    };
                    await msgQueue.SendAsync(_config.MessageQueueInfo.TestingQueueName, request);
                }
                catch (RabbitMQ.Client.Exceptions.BrokerUnreachableException e)
                {
                    var response1 = new
                    {
                        status = "connectionError",
                        msg    = "Can't connect to RabbitMQ!",
                        data   = GetStudentTaskView(taskId, curId)
                    };
                    return(Json(response1));
                }

                var response = new
                {
                    status = "success",
                    data   = GetStudentTaskView(taskId, curId)
                };
                return(Json(response));
            }

            var response3 = new
            {
                status = "error",
                data   = "Error while sending file!"
            };

            return(Json(response3));
        }
Exemplo n.º 4
0
        public async Task<TestingSystemResponse> CheckSolution(SolutionTestingRequest solutionRequest)
        {
            try
            {
                var solution = _db.Solutions.Find(solutionRequest.SolutionId);

                if (solution != null && solution.File != null)
                {
                    var taskTests = _db.TaskTests.Where(t => t.TaskId == solution.TaskId).ToArray();

                    if (taskTests != null && taskTests.Length > 0)
                    {
                        var isAlive = await CheckIfAlive(_config.CompilerServicesOrchestrator);

                        if (isAlive)
                        {
                            //var dataBytes = await file.GetBytes();                        
                            var codeStyleTask = taskTests.FirstOrDefault(t => t.TestType == "codeStyleTest");

                            var req = new TestRequest
                            {
                                SolutionId = solutionRequest.SolutionId,
                                TestId = codeStyleTask is null ? -1 : codeStyleTask.Id,
                                ReCheck = solutionRequest.ReCheck,
                            };

                            string url = _config.CompilerServicesOrchestrator.GetFullTestLinkFrom(_config.TestingSystemWorker);
                            using var httpClient = new HttpClient();
                            using var form = JsonContent.Create(req);
                            HttpResponseMessage response = await httpClient.PostAsync(url, form);
                            string apiResponse = await response.Content.ReadAsStringAsync();
                            if (response.IsSuccessStatusCode)
                            {
                                TestResponse compResponse = JsonConvert.DeserializeObject<TestResponse>(apiResponse);

                                if (compResponse.OK && compResponse.Result == ResultCode.OK)
                                {
                                    var compResult = _db.CompilationResults.Find(solutionRequest.SolutionId);

                                    if (compResult != null)
                                    {
                                        if (compResult.ResultCode != ResultCode.CE && compResult.File != null)
                                        {
                                            var testTasks = new List<Task<TestResponse>>();
                                            foreach (var test in taskTests)
                                            {
                                                if (_config.Tests.ContainsKey(test.TestType))
                                                {
                                                    testTasks.Add(StartTest(test.TestType, solutionRequest.SolutionId, test.Id, solutionRequest.ReCheck));
                                                }
                                                else
                                                {
                                                    testTasks.Add(Task.Run(() => NoTestFound(test.TestType, solutionRequest.SolutionId, test.Id)));
                                                }
                                            }
                                            await Task.WhenAll(testTasks);

                                            var responses = testTasks.Select(t => t.Result).ToArray();
                                            var results = responses.Join(taskTests, i => i.TestId, o => o.Id, (i, o) => new { Result = i, Definition = o }).ToArray();

                                            double totalScore = 0;
                                            ResultCode totalResult = results.Select(r => r.Result.Result).Max();

                                            foreach (var res in results)
                                            {
                                                if (res.Definition.Block && res.Result.Score == 0)
                                                {
                                                    totalScore = 0;

                                                    break;
                                                }
                                                else
                                                {
                                                    totalScore += res.Result.Score * res.Definition.Weight;
                                                }
                                            }

                                            return WriteToDb(solution, totalResult, totalScore, "success", true, responses);
                                        }
                                        else
                                        {
                                            return WriteToDb(solution, compResult.ResultCode, 0, "compilation error!", true);
                                        }
                                    }
                                    else
                                    {
                                        return WriteToDb(solution, compResponse.Result, 0, "can't find compilation! Inner message: " + compResponse.Message, false);
                                    }
                                }
                                else
                                {
                                    return WriteToDb(solution, compResponse.Result, 0, "something went wrong during compilation! Inner message: " + compResponse.Message, false);
                                }
                            }
                            else
                            {
                                return WriteToDb(solution, ResultCode.IE, 0, "bad response from compilation container: " + response.StatusCode, false);
                            }
                        }
                        else
                        {
                            return WriteToDb(solution, ResultCode.IE, 0, "Compiler Service Is Dead!", false);
                        }
                    }
                    else
                    {
                        return WriteToDb(null, ResultCode.IE, 0, "Can't find task tests!", false);
                    }
                }
                else
                {
                    return WriteToDb(null, ResultCode.IE, 0, "Can't find solution!", false);
                }
            }
            catch
            {
                return new TestingSystemResponse();
            }
        }