Search in sources :

Example 1 with RestContext

use of jetbrains.buildServer.server.rest.data.RestContext in project teamcity-rest by JetBrains.

the class ProjectRequestTest method memoryTest.

// @Test
public void memoryTest() throws InterruptedException {
    final ProjectRequest request = new ProjectRequest();
    request.setInTests(myProjectFinder, myBranchFinder, myBeanContext);
    final String locator = "archived:false,affectedProject:_Root";
    final String fields = "count,project(id,internalId,name,parentProjectId,archived,readOnlyUI,buildTypes(buildType(id,paused,internalId,projectId,name,type,description)),description)";
    Queue<Pair<Integer, ProjectEx>> q = new ArrayDeque<>();
    q.add(new Pair<>(0, myProject));
    final int max = 2;
    final int children = 4;
    int counter = 0;
    while (!q.isEmpty()) {
        Pair<Integer, ProjectEx> p = q.poll();
        String prefix = "Bt" + StringUtils.repeat('a', 10 * p.getFirst());
        for (int i = 0; i < children; i++) {
            ProjectEx c = myFixture.createProject("z-" + p.first + "-" + counter++, p.second);
            if (p.first < max) {
                q.add(new Pair<>(p.first + 1, c));
            }
            for (int j = 0; j < children * 4; j++) c.createBuildType(prefix + j);
        }
    }
    System.out.println(counter + " projects created.");
    Thread[] ts = new Thread[100];
    for (int i = 0; i < ts.length; i++) {
        final int threadIdx = i;
        ts[i] = new Thread(() -> {
            new RestContext(z -> null).run(() -> {
                for (int j = 0; j < 100; j++) {
                    final PagedSearchResult<SProject> result = myProjectFinder.getItems(locator);
                    Projects projects = new Projects(result.myEntries, null, new Fields(fields), myBeanContext);
                    projects.projects.stream().flatMap(p -> p.buildTypes.buildTypes.stream()).forEach(bt -> {
                        bt.getId();
                        bt.isPaused();
                        bt.getInternalId();
                        bt.getProjectId();
                        bt.getName();
                        bt.getType();
                        bt.getDescription();
                    });
                    System.out.println(String.format("Finished %d requests in thread %d", j, threadIdx));
                }
                return null;
            });
        });
        ts[i].start();
    }
    for (Thread t : ts) t.join();
}
Also used : Fields(jetbrains.buildServer.server.rest.model.Fields) java.util(java.util) Test(org.testng.annotations.Test) PagedSearchResult(jetbrains.buildServer.server.rest.data.PagedSearchResult) SProjectFeatureDescriptor(jetbrains.buildServer.serverSide.SProjectFeatureDescriptor) StringUtils(org.apache.commons.lang3.StringUtils) Branch(jetbrains.buildServer.server.rest.model.build.Branch) Projects(jetbrains.buildServer.server.rest.model.project.Projects) Option(jetbrains.buildServer.util.Option) VcsRootInstance(jetbrains.buildServer.vcs.VcsRootInstance) CollectionsUtil(jetbrains.buildServer.util.CollectionsUtil) RestContext(jetbrains.buildServer.server.rest.data.RestContext) SVcsRoot(jetbrains.buildServer.vcs.SVcsRoot) ProjectFeatureDescriptorFactory(jetbrains.buildServer.serverSide.impl.ProjectFeatureDescriptorFactory) MockVcsSupport(jetbrains.buildServer.serverSide.impl.MockVcsSupport) OperationRequestor(jetbrains.buildServer.vcs.OperationRequestor) BuildFinderTestBase(jetbrains.buildServer.server.rest.data.BuildFinderTestBase) Branches(jetbrains.buildServer.server.rest.model.build.Branches) BaseFinderTest(jetbrains.buildServer.server.rest.data.BaseFinderTest) BeforeMethod(org.testng.annotations.BeforeMethod) RepositoryStateData.createVersionState(jetbrains.buildServer.vcs.RepositoryStateData.createVersionState) Util.map(jetbrains.buildServer.util.Util.map) ProjectEx(jetbrains.buildServer.serverSide.impl.ProjectEx) BuildTypeEx(jetbrains.buildServer.serverSide.BuildTypeEx) Pair(com.intellij.openapi.util.Pair) SProject(jetbrains.buildServer.serverSide.SProject) BeanContext(jetbrains.buildServer.server.rest.util.BeanContext) Projects(jetbrains.buildServer.server.rest.model.project.Projects) RestContext(jetbrains.buildServer.server.rest.data.RestContext) ProjectEx(jetbrains.buildServer.serverSide.impl.ProjectEx) Fields(jetbrains.buildServer.server.rest.model.Fields) PagedSearchResult(jetbrains.buildServer.server.rest.data.PagedSearchResult) Pair(com.intellij.openapi.util.Pair)

Example 2 with RestContext

use of jetbrains.buildServer.server.rest.data.RestContext in project teamcity-rest by JetBrains.

the class APIController method doHandle.

protected ModelAndView doHandle(@NotNull final HttpServletRequest request, @NotNull final HttpServletResponse response) throws Exception {
    if (TeamCityProperties.getBoolean("rest.disable")) {
        final String message = TeamCityProperties.getProperty("rest.disable.message", "REST API is disabled on this TeamCity server with 'rest.disable' internal property.");
        reportRestErrorResponse(response, HttpServletResponse.SC_NOT_IMPLEMENTED, null, message, Level.INFO, request);
        return null;
    }
    if (matches(WebUtil.getRequestUrl(request), myDisabledRequests.getParsedValues(TeamCityProperties.getProperty("rest.disable.requests"), TeamCityProperties.getProperty("rest.disable.requests.delimiter")))) {
        final String defaultMessage = "Requests for URL \"" + WebUtil.getRequestUrl(request) + "\" are disabled in REST API on this server with 'rest.disable.requests' internal property.";
        final String message = TeamCityProperties.getProperty("rest.disable.message", defaultMessage);
        reportRestErrorResponse(response, HttpServletResponse.SC_NOT_IMPLEMENTED, null, message, Level.INFO, request);
        return null;
    }
    final Stopwatch requestStart = Stopwatch.createStarted();
    boolean shouldLogToDebug = shouldLogToDebug(request);
    String requestType = getRequestType(request);
    if (shouldLogToDebug && TeamCityProperties.getBoolean("rest.log.debug.requestStart") && LOG.isDebugEnabled()) {
        LOG.debug(() -> "REST API " + requestType + " request received: " + WebUtil.getRequestDump(request));
    }
    try {
        initJerseyWebComponent(() -> "during request " + WebUtil.getRequestDump(request));
    } catch (Throwable throwable) {
        reportRestErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, throwable, "Error initializing REST API", Level.ERROR, request);
        return null;
    }
    boolean runAsSystem = false;
    if (TeamCityProperties.getBoolean("rest.use.authToken")) {
        String authToken = request.getParameter("authToken");
        if (StringUtil.isNotEmpty(authToken) && StringUtil.isNotEmpty(getAuthToken())) {
            if (authToken.equals(getAuthToken())) {
                runAsSystem = true;
            } else {
                synchronized (this) {
                    // to prevent brute-forcing
                    Thread.sleep(10000);
                }
                reportRestErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, null, "Wrong authToken specified", Level.INFO, request);
                return null;
            }
        }
    }
    final AtomicBoolean errorEncountered = new AtomicBoolean(false);
    final boolean runAsSystemActual = runAsSystem;
    try {
        final boolean corsRequest = myAllowedOrigins.processCorsOriginHeaders(request, response, LOG);
        if (corsRequest && request.getMethod().equalsIgnoreCase("OPTIONS")) {
            // handling browser pre-flight requests
            LOG.debug("Pre-flight OPTIONS request detected, replying with status 204");
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            return null;
        }
        if (myInternalAuthProcessing && SessionUser.getUser(request) == null && !requestForMyPathNotRequiringAuth(request)) {
            if (processRequestAuthentication(request, response, myAuthManager)) {
                return null;
            }
            // TeamCity API issue: SecurityContext.getAuthorityHolder is "SYSTEM" if request is not authorized
            final boolean notAuthorizedRequest = mySecurityContext.isSystemAccess();
            if (notAuthorizedRequest) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("TeamCity core was unable to handle authentication (no current user).");
                LOG.warn("TeamCity core was unable to handle authentication (no current user), replying with 401 status. Request details: " + WebUtil.getRequestDump(request));
                return null;
            }
        }
        patchThread(() -> WebUtil.getRequestDump(request), requestType, () -> {
            // workaround for http://jetbrains.net/tracker/issue2/TW-7656
            doUnderContextClassLoader(myClassloader, new FuncThrow<Void, Throwable>() {

                public Void apply() throws Throwable {
                    return new RestContext(name -> request.getAttribute(CONTEXT_REQUEST_ARGUMENTS_PREFIX + name)).run(() -> {
                        // patching request
                        final HttpServletRequest actualRequest = new RequestWrapper(patchRequestWithAcceptHeader(request), myRequestPathTransformInfo);
                        if (runAsSystemActual) {
                            if (shouldLogToDebug && LOG.isDebugEnabled())
                                LOG.debug("Executing request with system security level");
                            mySecurityContext.runAsSystem(() -> {
                                myWebComponent.doFilter(actualRequest, response, null);
                            });
                        } else {
                            myWebComponent.doFilter(actualRequest, response, null);
                        }
                        return null;
                    });
                }
            });
            return null;
        });
    } catch (Throwable throwable) {
        errorEncountered.set(true);
        processException(request, response, throwable);
    } finally {
        if (shouldLogToDebug && LOG.isDebugEnabled()) {
            LOG.debug(() -> "REST API " + requestType + " request processing finished in " + TimePrinter.createMillisecondsFormatter().formatTime(requestStart.elapsed(TimeUnit.MILLISECONDS)) + (errorEncountered.get() ? " with errors, original " : ", ") + "status code: " + getStatus(response) + ", request: " + WebUtil.getRequestDump(request));
        }
    }
    return null;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Stopwatch(com.google.common.base.Stopwatch) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) RestContext(jetbrains.buildServer.server.rest.data.RestContext)

Aggregations

RestContext (jetbrains.buildServer.server.rest.data.RestContext)2 Stopwatch (com.google.common.base.Stopwatch)1 Pair (com.intellij.openapi.util.Pair)1 java.util (java.util)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)1 BaseFinderTest (jetbrains.buildServer.server.rest.data.BaseFinderTest)1 BuildFinderTestBase (jetbrains.buildServer.server.rest.data.BuildFinderTestBase)1 PagedSearchResult (jetbrains.buildServer.server.rest.data.PagedSearchResult)1 Fields (jetbrains.buildServer.server.rest.model.Fields)1 Branch (jetbrains.buildServer.server.rest.model.build.Branch)1 Branches (jetbrains.buildServer.server.rest.model.build.Branches)1 Projects (jetbrains.buildServer.server.rest.model.project.Projects)1 BeanContext (jetbrains.buildServer.server.rest.util.BeanContext)1 BuildTypeEx (jetbrains.buildServer.serverSide.BuildTypeEx)1 SProject (jetbrains.buildServer.serverSide.SProject)1 SProjectFeatureDescriptor (jetbrains.buildServer.serverSide.SProjectFeatureDescriptor)1 MockVcsSupport (jetbrains.buildServer.serverSide.impl.MockVcsSupport)1 ProjectEx (jetbrains.buildServer.serverSide.impl.ProjectEx)1