diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2917b4f --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/.gradle +/.idea +/.vscode +/build +/bin +/data/*.csv +/result.txt diff --git a/0.csv b/0.csv deleted file mode 100644 index 2f7dfb7..0000000 --- a/0.csv +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:eae61feac01cb36de9d6dd148a5b3fb76ad506fd8b283b20306df16f246e511e -size 3406784 diff --git a/1.csv b/1.csv deleted file mode 100644 index 3a258b0..0000000 --- a/1.csv +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7b2681409003d07d3ca063eb34339a0cdea9b688d16723b0e284091afd6bf806 -size 7078520 diff --git a/2.csv b/2.csv deleted file mode 100644 index 4cdd100..0000000 --- a/2.csv +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ea9a50aa300dfe7e766eb419b2a963d31cfe68644acb23f654df7abe852d3a76 -size 10737171 diff --git a/3.csv b/3.csv deleted file mode 100644 index afbe78d..0000000 --- a/3.csv +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6268fae7b50879a151a6f6de4852e4f39d2e22a8315290e87dcda71f4e10b866 -size 14530705 diff --git a/4.csv b/4.csv deleted file mode 100644 index 9ff08df..0000000 --- a/4.csv +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b4adf0d42097f1b2c9e68731460c5a7c52cb7ac7238addab7a796817cee9d00b -size 18299520 diff --git a/5.csv b/5.csv deleted file mode 100644 index 3980291..0000000 --- a/5.csv +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:212b6d6b07197921eaedaa271d781431b8bb034c5328622d63231a2967df1702 -size 22053240 diff --git a/6.csv b/6.csv deleted file mode 100644 index 5906dc6..0000000 --- a/6.csv +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:81f65085c6ce29a8f766244dc4b21d41d565ea3d6231b3b1c0b6739d67cd1d53 -size 25790880 diff --git a/7.csv b/7.csv deleted file mode 100644 index df43af3..0000000 --- a/7.csv +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4e73ff71a37438ec216fc522d77e3902c5670e24a917d0be047ed101dbeea914 -size 29524261 diff --git a/README.md b/README.md index 948dc85..b8e38ee 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ +[![Review Assignment Due Date](https://classroom.github.com/assets/deadline-readme-button-22041afd0340ce965d47ae6ef1cefeee28c7c493a6346c4f15d667ab976d596c.svg)](https://classroom.github.com/a/-hH64FG6) ## Лабораторная работа: Реализация MapReduce для анализа данных о продажах с ипользованием HADOOP!!! # Цель работы diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..515ca23 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,32 @@ +plugins { + java +} + +group = "org.itmo" +version = "0.0.1" + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(8) + } +} + + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.apache.hadoop:hadoop-common:3.2.1") + implementation("org.apache.hadoop:hadoop-client:3.2.1") + + compileOnly("org.projectlombok:lombok:1.18.36") + annotationProcessor("org.projectlombok:lombok:1.18.36") + + testCompileOnly("org.projectlombok:lombok:1.18.36") + testAnnotationProcessor("org.projectlombok:lombok:1.18.36") +} + +tasks.withType { + useJUnitPlatform() +} diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..3c052af --- /dev/null +++ b/compose.yml @@ -0,0 +1,27 @@ +volumes: + hadoop_namenode: + hadoop_datanode: + +services: + namenode: + image: bde2020/hadoop-namenode:2.0.0-hadoop3.2.1-java8 + container_name: namenode + restart: unless-stopped + ports: + - "9870:9870" + - "9000:9000" + volumes: + - hadoop_namenode:/hadoop/dfs/name + environment: + CLUSTER_NAME: "local-cluster" + CORE_CONF_fs_defaultFS: "hdfs://namenode:9000" + HDFS_CONF_dfs_replication: "1" + + datanode: + image: bde2020/hadoop-datanode:2.0.0-hadoop3.2.1-java8 + container_name: datanode + restart: unless-stopped + volumes: + - hadoop_datanode:/hadoop/dfs/data + environment: + CORE_CONF_fs_defaultFS: "hdfs://namenode:9000" diff --git a/data/.gitkeep b/data/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..1af9e09 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/hadoop.png b/hadoop.png new file mode 100644 index 0000000..3543e7a Binary files /dev/null and b/hadoop.png differ diff --git a/scripts/build_jar.ps1 b/scripts/build_jar.ps1 new file mode 100644 index 0000000..85fa03a --- /dev/null +++ b/scripts/build_jar.ps1 @@ -0,0 +1 @@ +pwsh -Command {$env:JAVA_HOME="C:\Users\Bromles\.gradle\jdks\temurin-8-amd64-windows\jdk8u422-b05"; .\gradlew.bat jar } diff --git a/scripts/cleanup_hdfs.sh b/scripts/cleanup_hdfs.sh new file mode 100644 index 0000000..1c7b458 --- /dev/null +++ b/scripts/cleanup_hdfs.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash + +hdfs dfs -rm -r /user/root/output +hdfs dfs -rm -r /user/root/output-intermediate diff --git a/scripts/do_all.ps1 b/scripts/do_all.ps1 new file mode 100644 index 0000000..7d674aa --- /dev/null +++ b/scripts/do_all.ps1 @@ -0,0 +1,4 @@ +.\scripts\build_jar.ps1 +.\scripts\load_jar.ps1 +.\scripts\load_data.ps1 +.\scripts\load_scripts.ps1 diff --git a/scripts/do_all_hdfs.sh b/scripts/do_all_hdfs.sh new file mode 100644 index 0000000..bbf3175 --- /dev/null +++ b/scripts/do_all_hdfs.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +if ! [[ "$PWD" = tmp ]] +then + cd /tmp || exit 1 +fi + +./setup_hdfs.sh +./load_data_hdfs.sh +./launch_job_hdfs.sh +./extract_result_hdfs.sh +./cleanup_hdfs.sh diff --git a/scripts/extract_result.ps1 b/scripts/extract_result.ps1 new file mode 100644 index 0000000..0853e60 --- /dev/null +++ b/scripts/extract_result.ps1 @@ -0,0 +1 @@ +docker cp namenode:/tmp/result.txt . diff --git a/scripts/extract_result_hdfs.sh b/scripts/extract_result_hdfs.sh new file mode 100644 index 0000000..0c48a53 --- /dev/null +++ b/scripts/extract_result_hdfs.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +if ! [[ "$PWD" = tmp ]] +then + cd /tmp || exit 1 +fi + +hdfs dfs -cat /user/root/output/part-r-00000 > /tmp/result.txt diff --git a/scripts/launch_job_hdfs.sh b/scripts/launch_job_hdfs.sh new file mode 100644 index 0000000..50a28af --- /dev/null +++ b/scripts/launch_job_hdfs.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +if [[ -n $1 ]] +then + reducerCount=$1 +else + reducerCount=1 +fi + +if [[ -n $2 ]] +then + datablockSizeKb=$2 +else + datablockSizeKb=16384 +fi + +if ! [[ "$PWD" = tmp ]] +then + cd /tmp || exit 1 +fi + +hadoop jar lab4-parcalc-bromles-0.0.1.jar org.itmo.lab4.SalesAnalyzer input output "$reducerCount" "$datablockSizeKb" diff --git a/scripts/load_data.ps1 b/scripts/load_data.ps1 new file mode 100644 index 0000000..e716f20 --- /dev/null +++ b/scripts/load_data.ps1 @@ -0,0 +1,8 @@ +docker cp .\data\0.csv namenode:/tmp +docker cp .\data\1.csv namenode:/tmp +docker cp .\data\2.csv namenode:/tmp +docker cp .\data\3.csv namenode:/tmp +docker cp .\data\4.csv namenode:/tmp +docker cp .\data\5.csv namenode:/tmp +docker cp .\data\6.csv namenode:/tmp +docker cp .\data\7.csv namenode:/tmp diff --git a/scripts/load_data_hdfs.sh b/scripts/load_data_hdfs.sh new file mode 100644 index 0000000..f6a41ed --- /dev/null +++ b/scripts/load_data_hdfs.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +if ! [[ "$PWD" = "tmp" ]] +then + cd /tmp || exit 1 +fi + +hdfs dfs -put -f ./*.csv /user/root/input diff --git a/scripts/load_jar.ps1 b/scripts/load_jar.ps1 new file mode 100644 index 0000000..cf62b1d --- /dev/null +++ b/scripts/load_jar.ps1 @@ -0,0 +1 @@ +docker cp .\build\libs\lab4-parcalc-bromles-0.0.1.jar namenode:/tmp diff --git a/scripts/load_scripts.ps1 b/scripts/load_scripts.ps1 new file mode 100644 index 0000000..8002e9b --- /dev/null +++ b/scripts/load_scripts.ps1 @@ -0,0 +1,6 @@ +docker cp .\scripts\setup_hdfs.sh namenode:/tmp +docker cp .\scripts\load_data_hdfs.sh namenode:/tmp +docker cp .\scripts\launch_job_hdfs.sh namenode:/tmp +docker cp .\scripts\extract_result_hdfs.sh namenode:/tmp +docker cp .\scripts\cleanup_hdfs.sh namenode:/tmp +docker cp .\scripts\do_all_hdfs.sh namenode:/tmp diff --git a/scripts/setup_hdfs.sh b/scripts/setup_hdfs.sh new file mode 100644 index 0000000..92eb725 --- /dev/null +++ b/scripts/setup_hdfs.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash + +hdfs dfs -mkdir -p /user/root +hdfs dfs -mkdir /user/root/input diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..b882dba --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "lab4-parcalc-bromles" diff --git a/src/main/java/org/itmo/lab4/SalesAnalyzer.java b/src/main/java/org/itmo/lab4/SalesAnalyzer.java new file mode 100644 index 0000000..7840640 --- /dev/null +++ b/src/main/java/org/itmo/lab4/SalesAnalyzer.java @@ -0,0 +1,46 @@ +package org.itmo.lab4; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.util.ToolRunner; +import org.itmo.lab4.analyse.AnalysisJob; +import org.itmo.lab4.sort.SortingJob; + +public class SalesAnalyzer { + public static void main(String[] args) throws Exception { + if (args.length != 4) { + System.err.println("Usage: hadoop jar /tmp/lab4-parcalc-bromles-0.0.1.jar org.itmo.lab4.SalesAnalyzer "); + System.exit(-1); + } + + String inputDir = args[0]; + String outputDir = args[1]; + int reducerCount = Integer.parseInt(args[2]); + int datablockSizeBytes = Integer.parseInt(args[3]) * 1024; // * 1 kb + String intermediateResultDir = outputDir + "-intermediate"; + + Configuration configuration = new Configuration(); + configuration.set("mapreduce.input.fileinputformat.split.maxsize", Integer.toString(datablockSizeBytes)); + + long startTime = System.currentTimeMillis(); + + String[] analysisArgs = new String[]{inputDir, intermediateResultDir, String.valueOf(reducerCount)}; + + // Data analysis + int exitCode = ToolRunner.run(configuration, new AnalysisJob(), analysisArgs); + + if (exitCode != 0) { + System.out.println("Analysis job failed"); + System.exit(1); + } + + String[] sortingArgs = new String[]{intermediateResultDir, outputDir, String.valueOf(reducerCount)}; + + // Data sorting + exitCode = ToolRunner.run(configuration, new SortingJob(), sortingArgs); + + long endTime = System.currentTimeMillis(); + System.out.println("Jobs completed in " + (endTime - startTime) + " milliseconds."); + + System.exit(exitCode); + } +} diff --git a/src/main/java/org/itmo/lab4/analyse/AnalysisJob.java b/src/main/java/org/itmo/lab4/analyse/AnalysisJob.java new file mode 100644 index 0000000..05bc061 --- /dev/null +++ b/src/main/java/org/itmo/lab4/analyse/AnalysisJob.java @@ -0,0 +1,47 @@ +package org.itmo.lab4.analyse; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.conf.Configured; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.io.Text; +import org.apache.hadoop.mapreduce.Job; +import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; +import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; +import org.apache.hadoop.util.Tool; + +public class AnalysisJob extends Configured implements Tool { + @Override + public int run(String[] args) throws Exception { + String inputDir = args[0]; + String outputDir = args[1]; + int reducerCount = Integer.parseInt(args[2]); + + Configuration configuration = getConf(); + + Job analysisJob = Job.getInstance(configuration, "analysis"); + + analysisJob.setNumReduceTasks(reducerCount); // reducer scaling + + analysisJob.setJarByClass(AnalysisJob.class); + + analysisJob.setMapperClass(AnalysisMapper.class); + analysisJob.setReducerClass(AnalysisReducer.class); + + analysisJob.setMapOutputKeyClass(Text.class); + analysisJob.setMapOutputValueClass(SalesData.class); + + analysisJob.setOutputKeyClass(Text.class); + analysisJob.setOutputValueClass(Text.class); + + FileInputFormat.addInputPath(analysisJob, new Path(inputDir)); + FileOutputFormat.setOutputPath(analysisJob, new Path(outputDir)); + + boolean success = analysisJob.waitForCompletion(true); + + if (!success) { + return 1; + } + + return 0; + } +} diff --git a/src/main/java/org/itmo/lab4/analyse/AnalysisMapper.java b/src/main/java/org/itmo/lab4/analyse/AnalysisMapper.java new file mode 100644 index 0000000..48648a0 --- /dev/null +++ b/src/main/java/org/itmo/lab4/analyse/AnalysisMapper.java @@ -0,0 +1,21 @@ +package org.itmo.lab4.analyse; + +import org.apache.hadoop.io.Text; +import org.apache.hadoop.mapreduce.Mapper; + +import java.io.IOException; + +public class AnalysisMapper extends Mapper { + @Override + protected void map(Object key, Text value, Context context) throws IOException, InterruptedException { + String[] fields = value.toString().split(","); + + if (fields.length == 5 && !fields[0].equals("transaction_id")) { + String category = fields[2]; + double price = Double.parseDouble(fields[3]); + int quantity = Integer.parseInt(fields[4]); + + context.write(new Text(category), new SalesData(price * quantity, quantity)); + } + } +} diff --git a/src/main/java/org/itmo/lab4/analyse/AnalysisReducer.java b/src/main/java/org/itmo/lab4/analyse/AnalysisReducer.java new file mode 100644 index 0000000..4a58385 --- /dev/null +++ b/src/main/java/org/itmo/lab4/analyse/AnalysisReducer.java @@ -0,0 +1,21 @@ +package org.itmo.lab4.analyse; + +import org.apache.hadoop.io.Text; +import org.apache.hadoop.mapreduce.Reducer; + +import java.io.IOException; + +public class AnalysisReducer extends Reducer { + @Override + protected void reduce(Text key, Iterable values, Context context) throws IOException, InterruptedException { + double totalRevenue = 0.0; + int totalQuantity = 0; + + for (SalesData val : values) { + totalRevenue += val.getRevenue(); + totalQuantity += val.getQuantity(); + } + + context.write(key, new Text(String.format("%.2f\t%d", totalRevenue, totalQuantity))); + } +} diff --git a/src/main/java/org/itmo/lab4/analyse/SalesData.java b/src/main/java/org/itmo/lab4/analyse/SalesData.java new file mode 100644 index 0000000..2f748f9 --- /dev/null +++ b/src/main/java/org/itmo/lab4/analyse/SalesData.java @@ -0,0 +1,29 @@ +package org.itmo.lab4.analyse; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.apache.hadoop.io.Writable; + +import java.io.DataOutput; +import java.io.IOException; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class SalesData implements Writable { + private double revenue; + private int quantity; + + @Override + public void write(DataOutput out) throws IOException { + out.writeDouble(revenue); + out.writeInt(quantity); + } + + @Override + public void readFields(java.io.DataInput in) throws IOException { + revenue = in.readDouble(); + quantity = in.readInt(); + } +} diff --git a/src/main/java/org/itmo/lab4/sort/CompositeData.java b/src/main/java/org/itmo/lab4/sort/CompositeData.java new file mode 100644 index 0000000..4fbc891 --- /dev/null +++ b/src/main/java/org/itmo/lab4/sort/CompositeData.java @@ -0,0 +1,30 @@ +package org.itmo.lab4.sort; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.apache.hadoop.io.Writable; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class CompositeData implements Writable { + private String category; + private int quantity; + + @Override + public void write(DataOutput out) throws IOException { + out.writeUTF(category); + out.writeInt(quantity); + } + + @Override + public void readFields(DataInput in) throws IOException { + category = in.readUTF(); + quantity = in.readInt(); + } +} diff --git a/src/main/java/org/itmo/lab4/sort/SortingComparator.java b/src/main/java/org/itmo/lab4/sort/SortingComparator.java new file mode 100644 index 0000000..eb289be --- /dev/null +++ b/src/main/java/org/itmo/lab4/sort/SortingComparator.java @@ -0,0 +1,16 @@ +package org.itmo.lab4.sort; + +import org.apache.hadoop.io.DoubleWritable; +import org.apache.hadoop.io.WritableComparable; +import org.apache.hadoop.io.WritableComparator; + +public class SortingComparator extends WritableComparator { + public SortingComparator() { + super(DoubleWritable.class, true); + } + + @Override + public int compare(WritableComparable a, WritableComparable b) { + return -1 * a.compareTo(b); + } +} diff --git a/src/main/java/org/itmo/lab4/sort/SortingJob.java b/src/main/java/org/itmo/lab4/sort/SortingJob.java new file mode 100644 index 0000000..430c6e6 --- /dev/null +++ b/src/main/java/org/itmo/lab4/sort/SortingJob.java @@ -0,0 +1,50 @@ +package org.itmo.lab4.sort; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.conf.Configured; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.io.DoubleWritable; +import org.apache.hadoop.io.Text; +import org.apache.hadoop.mapreduce.Job; +import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; +import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; +import org.apache.hadoop.util.Tool; + +public class SortingJob extends Configured implements Tool { + @Override + public int run(String[] args) throws Exception { + String inputDir = args[0]; + String outputDir = args[1]; + int reducerCount = Integer.parseInt(args[2]); + + Configuration configuration = getConf(); + + Job sortingJob = Job.getInstance(configuration, "sorting"); + + sortingJob.setNumReduceTasks(reducerCount); // reducer scaling + + sortingJob.setJarByClass(SortingJob.class); + + sortingJob.setSortComparatorClass(SortingComparator.class); + + sortingJob.setMapperClass(SortingMapper.class); + sortingJob.setReducerClass(SortingReducer.class); + + sortingJob.setMapOutputKeyClass(DoubleWritable.class); + sortingJob.setMapOutputValueClass(CompositeData.class); + + sortingJob.setOutputKeyClass(Text.class); + sortingJob.setOutputValueClass(Text.class); + + FileInputFormat.addInputPath(sortingJob, new Path(inputDir)); + FileOutputFormat.setOutputPath(sortingJob, new Path(outputDir)); + + boolean success = sortingJob.waitForCompletion(true); + + if (!success) { + return 1; + } + + return 0; + } +} diff --git a/src/main/java/org/itmo/lab4/sort/SortingMapper.java b/src/main/java/org/itmo/lab4/sort/SortingMapper.java new file mode 100644 index 0000000..adec986 --- /dev/null +++ b/src/main/java/org/itmo/lab4/sort/SortingMapper.java @@ -0,0 +1,22 @@ +package org.itmo.lab4.sort; + +import org.apache.hadoop.io.DoubleWritable; +import org.apache.hadoop.io.Text; +import org.apache.hadoop.mapreduce.Mapper; + +import java.io.IOException; + +public class SortingMapper extends Mapper { + @Override + protected void map(Object key, Text value, Context context) throws IOException, InterruptedException { + String[] fields = value.toString().split("\t"); + + if (fields.length == 3) { + String category = fields[0]; + double revenue = Double.parseDouble(fields[1]); + int quantity = Integer.parseInt(fields[2]); + + context.write(new DoubleWritable(revenue), new CompositeData(category, quantity)); + } + } +} diff --git a/src/main/java/org/itmo/lab4/sort/SortingReducer.java b/src/main/java/org/itmo/lab4/sort/SortingReducer.java new file mode 100644 index 0000000..e09b7c5 --- /dev/null +++ b/src/main/java/org/itmo/lab4/sort/SortingReducer.java @@ -0,0 +1,18 @@ +package org.itmo.lab4.sort; + +import org.apache.hadoop.io.DoubleWritable; +import org.apache.hadoop.io.Text; +import org.apache.hadoop.mapreduce.Reducer; + +import java.io.IOException; + +public class SortingReducer extends Reducer { + @Override + protected void reduce(DoubleWritable key, Iterable values, Context context) throws IOException, InterruptedException { + for (CompositeData value : values) { + Text category = new Text(value.getCategory()); + + context.write(category, new Text(String.format("%.2f\t%d", key.get(), value.getQuantity()))); + } + } +}