<commit_before>/**
 *    Retz
 *    Copyright (C) 2016-2017 Nautilus Technologies, Inc.
 *
 *    Licensed 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.
 */
package io.github.retz.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import io.github.retz.auth.AuthHeader;
import io.github.retz.cli.TimestampHelper;
import io.github.retz.db.Database;
import io.github.retz.mesosc.MesosHTTPFetcher;
import io.github.retz.misc.Pair;
import io.github.retz.misc.Triad;
import io.github.retz.planner.AppJobPair;
import io.github.retz.protocol.*;
import io.github.retz.protocol.data.Application;
import io.github.retz.protocol.data.DirEntry;
import io.github.retz.protocol.data.FileContent;
import io.github.retz.protocol.data.Job;
import io.github.retz.scheduler.*;
import org.apache.commons.io.IOUtils;
import org.apache.mesos.Protos;
import org.apache.mesos.SchedulerDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.Request;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static io.github.retz.web.WebConsole.validateOwner;
import static spark.Spark.halt;

public class JobRequestHandler {
    private static final Logger LOG = LoggerFactory.getLogger(JobRequestHandler.class);
    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static Optional<RetzScheduler> scheduler = Optional.empty();
    private static Optional<SchedulerDriver> driver = Optional.empty();
    private static int MAX_LIST_JOB_SIZE = Integer.MAX_VALUE;

    static {
        MAPPER.registerModule(new Jdk8Module());
    }

    static void setScheduler(RetzScheduler sched) {
        scheduler = Optional.ofNullable(sched);
    }

    static void setDriver(SchedulerDriver d) {
        driver = Optional.ofNullable(d);
    }

    static void setMaxListJobSize(int v) {
        LOG.info("Setting max list-job size as {}", v);
        MAX_LIST_JOB_SIZE = v;
    }

    static String listJob(spark.Request req, spark.Response res) throws IOException {
        Optional<AuthHeader> authHeaderValue = WebConsole.getAuthInfo(req);
        LOG.debug("list jobs owned by {}", authHeaderValue.get().key());
        ListJobRequest listJobRequest = MAPPER.readValue(req.body(), ListJobRequest.class);
        LOG.debug("q: state={}, tag={}",
                listJobRequest.state(), listJobRequest.tag());
        String user = Objects.requireNonNull(authHeaderValue.get().key());
        try {
            List<Job> jobs = JobQueue.list(user, listJobRequest.state(), listJobRequest.tag(), MAX_LIST_JOB_SIZE);

            boolean more = false;
            if (jobs.size() > ListJobResponse.MAX_JOB_NUMBER) {
                more = true;
                jobs = jobs.subList(0, ListJobResponse.MAX_JOB_NUMBER);
            }
            ListJobResponse listJobResponse = new ListJobResponse(jobs, more);
            listJobResponse.ok();
            res.status(200);
            res.type("application/json");
            return MAPPER.writeValueAsString(listJobResponse);
        } catch (SQLException e) {
            LOG.error(e.toString(), e);
            res.status(500);
            return "\"Internal Error\"";
        }
    }

    private static Optional<Job> getJobAndVerify(Request req) throws IOException {
        int id = Integer.parseInt(req.params(":id"));
        Optional<AuthHeader> authHeaderValue = WebConsole.getAuthInfo(req);

        if (!authHeaderValue.isPresent()) {
            LOG.debug("Authorization header lacking?");
            return Optional.empty();
        }
        LOG.debug("get-xxx id={}, user={}", id, authHeaderValue.get().key());

        Optional<AppJobPair> maybePair = Database.getInstance().getAppJob(id);
        if (maybePair.isPresent()) {
            AppJobPair pair = maybePair.get();
            if (pair.application().getOwner().equals(authHeaderValue.get().key())) {
                return Optional.of(pair.job());
            }
        }
        return Optional.empty();
    }

    static String getJob(spark.Request req, spark.Response res) throws IOException {
        Optional<Job> maybeJob = getJobAndVerify(req);

        res.type("application/json");

        Response response = new GetJobResponse(maybeJob);
        response.status("ok");
        res.status(200);
        return MAPPER.writeValueAsString(response);
    }

    static String getFile(spark.Request req, spark.Response res) throws IOException {
        Optional<Job> job = getJobAndVerify(req);

        String file = req.queryParams("path");
        long offset = Long.parseLong(req.queryParams("offset"));
        long length = Long.parseLong(req.queryParams("length"));

        LOG.debug("get-file: path={}, offset={}, length={}", file, offset, length);
        res.type("application/json");

        Optional<FileContent> fileContent;
        if (job.isPresent() && job.get().url() != null // If url() is null, the job hasn't yet been started at Mesos
                && MesosHTTPFetcher.statHTTPFile(job.get().url(), file)) {
            Pair<Integer, String> payload = MesosHTTPFetcher.fetchHTTPFile(job.get().url(), file, offset, length);
            LOG.debug("Payload length={}, offset={}", payload.right().length(), offset);
            // TODO: what the heck happens when a file is not UTF-8 encodable???? How Mesos works?
            if (payload.left() == 200) {
                fileContent = Optional.ofNullable(MAPPER.readValue(payload.right(), FileContent.class));
            } else {
                return MAPPER.writeValueAsString(new ErrorResponse(payload.right()));
            }
        } else {
            fileContent = Optional.empty();
        }
        GetFileResponse getFileResponse = new GetFileResponse(job, fileContent);
        getFileResponse.ok();
        res.status(200);

        return MAPPER.writeValueAsString(getFileResponse);
    }

    // A new HTTP endpoint to support binaries
    static String downloadFile(spark.Request req, spark.Response res) throws IOException {
        Optional<Job> job = getJobAndVerify(req);
        String file = req.queryParams("path");
        LOG.debug("download: path={}", file);

        if (job.isPresent() && job.get().url() != null) { // If url() is null, the job hasn't yet been started at Mesos
            MesosHTTPFetcher.downloadHTTPFile(job.get().url(), file, (Triad<Integer, String, Pair<Long, InputStream>> triad) -> {
                Integer statusCode = triad.left();
                res.status(statusCode);
                if (statusCode == 200) {
                    Long length = triad.right().left();
                    InputStream io = triad.right().right();
                    Long maxFileSize = scheduler.get().maxFileSize();
                    if (0 < maxFileSize && maxFileSize < length) {
                        throw new IOException("Stream file too large: " + length + " < " + maxFileSize);
                    }
                    res.raw().setHeader("Content-Length", length.toString());
                    LOG.debug("start streaming of {} bytes for {}", length, file);
                    IOUtils.copyLarge(io, res.raw().getOutputStream());
                    LOG.debug("end streaming for {}", file);
                } else {
                    res.body(triad.center());
                }
            });
            return "";
        } else {
            res.status(404);
            return "";
        }
    }

    static String getDir(spark.Request req, spark.Response res) throws JsonProcessingException {
        Optional<Job> job;
        try {<commit_msg>Update max streaming file size condition<commit_after>/**
 *    Retz
 *    Copyright (C) 2016-2017 Nautilus Technologies, Inc.
 *
 *    Licensed 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.
 */
package io.github.retz.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import io.github.retz.auth.AuthHeader;
import io.github.retz.cli.TimestampHelper;
import io.github.retz.db.Database;
import io.github.retz.mesosc.MesosHTTPFetcher;
import io.github.retz.misc.Pair;
import io.github.retz.misc.Triad;
import io.github.retz.planner.AppJobPair;
import io.github.retz.protocol.*;
import io.github.retz.protocol.data.Application;
import io.github.retz.protocol.data.DirEntry;
import io.github.retz.protocol.data.FileContent;
import io.github.retz.protocol.data.Job;
import io.github.retz.scheduler.*;
import org.apache.commons.io.IOUtils;
import org.apache.mesos.Protos;
import org.apache.mesos.SchedulerDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.Request;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static io.github.retz.web.WebConsole.validateOwner;
import static spark.Spark.halt;

public class JobRequestHandler {
    private static final Logger LOG = LoggerFactory.getLogger(JobRequestHandler.class);
    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static Optional<RetzScheduler> scheduler = Optional.empty();
    private static Optional<SchedulerDriver> driver = Optional.empty();
    private static int MAX_LIST_JOB_SIZE = Integer.MAX_VALUE;

    static {
        MAPPER.registerModule(new Jdk8Module());
    }

    static void setScheduler(RetzScheduler sched) {
        scheduler = Optional.ofNullable(sched);
    }

    static void setDriver(SchedulerDriver d) {
        driver = Optional.ofNullable(d);
    }

    static void setMaxListJobSize(int v) {
        LOG.info("Setting max list-job size as {}", v);
        MAX_LIST_JOB_SIZE = v;
    }

    static String listJob(spark.Request req, spark.Response res) throws IOException {
        Optional<AuthHeader> authHeaderValue = WebConsole.getAuthInfo(req);
        LOG.debug("list jobs owned by {}", authHeaderValue.get().key());
        ListJobRequest listJobRequest = MAPPER.readValue(req.body(), ListJobRequest.class);
        LOG.debug("q: state={}, tag={}",
                listJobRequest.state(), listJobRequest.tag());
        String user = Objects.requireNonNull(authHeaderValue.get().key());
        try {
            List<Job> jobs = JobQueue.list(user, listJobRequest.state(), listJobRequest.tag(), MAX_LIST_JOB_SIZE);

            boolean more = false;
            if (jobs.size() > ListJobResponse.MAX_JOB_NUMBER) {
                more = true;
                jobs = jobs.subList(0, ListJobResponse.MAX_JOB_NUMBER);
            }
            ListJobResponse listJobResponse = new ListJobResponse(jobs, more);
            listJobResponse.ok();
            res.status(200);
            res.type("application/json");
            return MAPPER.writeValueAsString(listJobResponse);
        } catch (SQLException e) {
            LOG.error(e.toString(), e);
            res.status(500);
            return "\"Internal Error\"";
        }
    }

    private static Optional<Job> getJobAndVerify(Request req) throws IOException {
        int id = Integer.parseInt(req.params(":id"));
        Optional<AuthHeader> authHeaderValue = WebConsole.getAuthInfo(req);

        if (!authHeaderValue.isPresent()) {
            LOG.debug("Authorization header lacking?");
            return Optional.empty();
        }
        LOG.debug("get-xxx id={}, user={}", id, authHeaderValue.get().key());

        Optional<AppJobPair> maybePair = Database.getInstance().getAppJob(id);
        if (maybePair.isPresent()) {
            AppJobPair pair = maybePair.get();
            if (pair.application().getOwner().equals(authHeaderValue.get().key())) {
                return Optional.of(pair.job());
            }
        }
        return Optional.empty();
    }

    static String getJob(spark.Request req, spark.Response res) throws IOException {
        Optional<Job> maybeJob = getJobAndVerify(req);

        res.type("application/json");

        Response response = new GetJobResponse(maybeJob);
        response.status("ok");
        res.status(200);
        return MAPPER.writeValueAsString(response);
    }

    static String getFile(spark.Request req, spark.Response res) throws IOException {
        Optional<Job> job = getJobAndVerify(req);

        String file = req.queryParams("path");
        long offset = Long.parseLong(req.queryParams("offset"));
        long length = Long.parseLong(req.queryParams("length"));

        LOG.debug("get-file: path={}, offset={}, length={}", file, offset, length);
        res.type("application/json");

        Optional<FileContent> fileContent;
        if (job.isPresent() && job.get().url() != null // If url() is null, the job hasn't yet been started at Mesos
                && MesosHTTPFetcher.statHTTPFile(job.get().url(), file)) {
            Pair<Integer, String> payload = MesosHTTPFetcher.fetchHTTPFile(job.get().url(), file, offset, length);
            LOG.debug("Payload length={}, offset={}", payload.right().length(), offset);
            // TODO: what the heck happens when a file is not UTF-8 encodable???? How Mesos works?
            if (payload.left() == 200) {
                fileContent = Optional.ofNullable(MAPPER.readValue(payload.right(), FileContent.class));
            } else {
                return MAPPER.writeValueAsString(new ErrorResponse(payload.right()));
            }
        } else {
            fileContent = Optional.empty();
        }
        GetFileResponse getFileResponse = new GetFileResponse(job, fileContent);
        getFileResponse.ok();
        res.status(200);

        return MAPPER.writeValueAsString(getFileResponse);
    }

    // A new HTTP endpoint to support binaries
    static String downloadFile(spark.Request req, spark.Response res) throws IOException {
        Optional<Job> job = getJobAndVerify(req);
        String file = req.queryParams("path");
        LOG.debug("download: path={}", file);

        if (job.isPresent() && job.get().url() != null) { // If url() is null, the job hasn't yet been started at Mesos
            MesosHTTPFetcher.downloadHTTPFile(job.get().url(), file, (Triad<Integer, String, Pair<Long, InputStream>> triad) -> {
                Integer statusCode = triad.left();
                res.status(statusCode);
                if (statusCode == 200) {
                    Long length = triad.right().left();
                    InputStream io = triad.right().right();
                    Long maxFileSize = scheduler.get().maxFileSize();
                    if (length < 0) {
                        throw new IOException("content length is negative: " + length);
                    } else if (0 <= maxFileSize && maxFileSize < length) { // negative maxFileSize indicates no limit
                        throw new IOException("stream file too large: " + length + " < " + maxFileSize);
                    }
                    res.raw().setHeader("Content-Length", length.toString());
                    LOG.debug("start streaming of {} bytes for {}", length, file);
                    IOUtils.copyLarge(io, res.raw().getOutputStream());
                    LOG.debug("end streaming for {}", file);
                } else {
                    res.body(triad.center());
                }
            });
            return "";
        } else {
            res.status(404);
            return "";
        }
    }

    static String getDir(spark.Request req, spark.Response res) throws JsonProcessingException {
        Optional<Job> job;
        try {
{'fraction_non_alphanumeric': 0.11996940456578019, 'fraction_numerical': 0.004883502000470699, 'mean_word_length': 2.644296740994854, 'pattern_counts': {'":': 2, '<': 40, '<?xml version=': 0, '>': 37, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 8}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '533277', 'n_tokens_mistral': 4763, 'n_tokens_neox': 4587, 'n_words': 1107}