Streaming videos

Problem statement for Online Qualification Round, Hash Code 2017

Introduction

Have you ever wondered what happens behind the scenes when you watch a YouTube video? As more and more people watch online videos (and as the size of these videos increases), it is critical that video-serving infrastructure is optimized to handle requests reliably and quickly.

This typically involves putting in place cache servers, which store copies of popular videos. When a user request for a particular video arrives, it can be handled by a cache server close to the user, rather than by a remote data center thousands of kilometers away.

But how should you decide which videos to put in which cache servers?

Task

Given a description of cache servers, network endpoints and videos, along with predicted requests for individual videos, decide which videos to put in which cache server in order to minimize the average waiting time for all requests.

Problem description

The picture below represents the video serving network.

Videos

Each video has a size given in megabytes (MB). The data center stores ​ all videos​ . Additionally, each video can be put in 0, 1, or more cache servers​. Each cache server has a maximum capacity given in megabytes.

Endpoints

Each endpoint represents a group of users connecting to the Internet in the same geographical area (for example, a neighborhood in a city). Every endpoint is connected to the data center. Additionally, each endpoint may (but doesn’t have to) be connected to 1 or more cache servers​ .

Each endpoint is characterized by the latency of its connection to the data center (how long it takes to serve a video from the data center to a user in this endpoint), and by the latencies to each cache server that the endpoint is connected to (how long it takes to serve a video stored in the given cache server to a user in this endpoint).

Requests

The predicted requests provide data on how many times a particular video is requested from a particular endpoint.

Input data set

The input data is provided as a data set file – a plain text file containing exclusively ASCII characters with a single \n character at the end of each line (UNIX-​ style line endings).

File format

All numbers mentioned in the specification are natural numbers that fit within the indicated ranges. When multiple numbers appear in a single line, they are separated by a single space.

The first line of the input contains the following numbers:

V ( 1 ≤ V ≤ 10000) – the number of videos

E ( 1 ≤ E ≤ 1000) – the number of endpoints

R ( 1 ≤ R ≤ 1000000) – the number of request descriptions

C ( 1 ≤ C ≤ 1000) – the number of cache servers

X ( 1 ≤ X ≤ 500000) – the capacity of each cache server in megabytes

The next line contains ​V numbers describing the sizes of individual videos in megabytes: S0, S1, … SV-1. Si is the size of video i​ in megabytes ( 1 ≤ Si ≤ 1000).

The next section describes each of the endpoints one after another, from endpoint 0 to endpoint E − 1 . The description of each endpoint consists of the following lines:

a line containing two numbers:

LD ( 2 ≤ LD ≤ 4000) – the latency of serving a video request from the data center to this endpoint, in milliseconds

K ( 0 ≤ K ≤ C ) – the number of cache servers that this endpoint is connected to

K lines describing the connections from the endpoint to each of the K connected cache servers.
Each line contains the following numbers:

c ( 0 ≤ c < C ) – the ID of the cache server

Lc ( 1 ≤ Lc ≤ 500) – the latency of serving a video request from this cache server to this endpoint, in milliseconds. You can assume that latency from the cache is strictly lower than latency from the data center ( 1 ≤ Lc < LD

Finally, the last section contains R request descriptions in separate lines. Each line contains the following numbers:

Rv ( 0 ≤ Rv < V ) – the ID of the requested video

Re ( 0 ≤ Re < E ) – the ID of the endpoint from which the requests are coming from

Connections and latencies between the endpoints and caches of example input.

Submissions

File format

Your submission should start with a line containing a single number N ( 0 ≤ N ≤ C ) – the number of cache server descriptions to follow.

Each of the subsequent N lines should describe the videos cached in a single cache server. It should contain the following numbers:

c ( 0 ≤ c < C ) – the ID of the cache server being described,

the IDs of the videos stored in this cache server: v0, …, vn ( 0 ≤ vi < V) (at least 0 and at most V numbers), given in any order without repetitions

Each cache server should be described in at most one line. It is not necessary to describe all cache servers: if a cache does not occur in the submission, this cache server will be considered as empty. Cache servers can be described in any order.

Validation

the total size of videos stored in each cache server does not exceed the maximum cache server capacity

Scoring

The score is the average time saved per request, in microseconds. (Note that the latencies in the input file are given in milliseconds. The score is given in microseconds to provide a better resolution of results.)
For each request description ( Rv, Re, Rn) in the input file, we choose the best way to stream the video Rv to the endpoint Re. We pick the lowest possible latency L = min(LD, L0, … , Lk−1) , where L​D is the latency of serving a video to the endpoint Re from the data center, and L0, … , Lk−1 are latencies of serving a video to the endpoint Re from each cache server that:

To compute the total score for the data set, we sum the time saved for individual request descriptions in milliseconds, multiply by 1000 and divide it by the total number of requests in all request descriptions, rounding down.

A schematic representation of the example submission file above​ .

In the example​ above, there are three request descriptions for the endpoint 0

Like many people, we use Jenkins to perform several tasks automatically.Jenkins is an open source automation server, it provides hundreds of plugins to support building, deploying and automating any project.

One of the features of Jenkins is the option to send an email to the user under certain circumstances, e.g. after a build was complete.
The default layout of those emails is not so pretty, so we did some changes to it. Note: below we present how to make the changes apply to the whole system, if you do not want to do that, you could apply these changes to individual projects only.

Using an administrative account, click on Manage Jenkins option on the left menu and in the new screen click on Configure System on the right column.
These actions will take you to the configuration page of your Jenkins installation (e.g. http://jenkins:8080/configure).

Scroll down to the category Extended E-mail Notification.

From the drop down menu, change the value of Default Content Type to HTML (text/html).

Update the value of Default Subject to [$BUILD_STATUS] - $PROJECT_NAME - Build # $BUILD_NUMBER ($BUILD_ID). We prefer to have the build status first (like a tag).

The email you will receive after a successful execution will be similar to the one below:

Subject: [Successful] - banana - Build # 77 (77)
Body:

Press the Apply button to save the changes.

You will notice that in the email we mention the following: If you cannot connect to the build server, check the attached logs..
To enable the option to attach the logs, you need to configure your project itself.
Select your project from the main screen and then click on Configure on the left column.

The following code has two threads.
The main thread spawns a pthread and then blocks on a condition waiting for a signal from the pthread.
The pthread will perform its task and then signal the main thread.
Once the main thread receives its signal, it will join the pthread and terminate.

#include <stdio.h>
#include <sys/types.h>
#include <pthread.h>
#include <asm/errno.h>
#define MAX_WAIT_TIME_IN_SECONDS (6)
struct thread_info_t
{
// Used to identify a thread.
pthread_t thread_id;
// A condition is a synchronization device that allows threads to suspend execution and relinquish the processors until some predicate on shared data is satisfied.
// The basic operations on conditions are: signal the condition (when the predicate becomes true), and wait for the condition, suspending the thread execution until another thread signals the condition.
pthread_cond_t condition;
// A mutex is a MUTual EXclusion device, and is useful for protecting shared data structures from concurrent modifications, and implementing critical sections and monitors.
// A mutex has two possible states: unlocked (not owned by any thread), and locked (owned by one thread).
// A mutex can never be owned by two different threads simultaneously.
// A thread attempting to lock a mutex that is already locked by another thread is suspended until the owning thread unlocks the mutex first.
pthread_mutex_t mutex;
};
void error_pthread_mutex_unlock(const int unlock_rv)
{
fprintf(stderr, "Failed to unlock mutex.\n");
switch (unlock_rv)
{
case EINVAL:
fprintf(stderr, "The value specified by mutex does not refer to an initialized mutex object.\n");
break;
case EAGAIN:
fprintf(stderr, "The mutex could not be acquired because the maximum number of recursive locks for mutex has been exceeded.\n");
break;
case EPERM:
fprintf(stderr, "The current thread does not own the mutex.\n");
break;
default:
break;
}
}
void error_pthread_mutex_lock(const int lock_rv)
{
fprintf(stderr, "Failed to lock mutex.\n");
switch (lock_rv)
{
case EINVAL:
fprintf(stderr, "The value specified by mutex does not refer to an initialized mutex object or the mutex was created with the protocol attribute having the value PTHREAD_PRIO_PROTECT and the calling thread's priority is higher than the mutex's current priority ceiling.\n");
break;
case EAGAIN:
fprintf(stderr, "The mutex could not be acquired because the maximum number of recursive locks for mutex has been exceeded.\n");
break;
case EDEADLK:
fprintf(stderr, "A deadlock condition was detected or the current thread already owns the mutex.\n");
break;
default:
break;
}
}
void error_pthread_cond_signal(const int signal_rv)
{
fprintf(stderr, "Could not signal.\n");
if (signal_rv == EINVAL)
{
fprintf(stderr, "The value cond does not refer to an initialised condition variable.\n");
}
}
void error_pthread_setcanceltype(const int setcanceltype_rv)
{
fprintf(stderr, "Could not change cancelability type of thread.\n");
if (setcanceltype_rv == EINVAL)
{
fprintf(stderr, "Invalid value for type.\n");
}
}
void error_pthread_create(const int create_rv)
{
fprintf(stderr, "Could not create thread.\n");
switch (create_rv)
{
case EAGAIN:
fprintf(stderr, "Insufficient resources to create another thread or a system-imposed limit on the number of threads was encountered.\n");
break;
case EINVAL:
fprintf(stderr, "Invalid settings in attr.\n");
break;
case EPERM:
fprintf(stderr, "No permission to set the scheduling policy and parameters specified in attr.\n");
break;
default:
break;
}
}
void error_pthread_cond_timedwait(const int timed_wait_rv)
{
fprintf(stderr, "Conditional timed wait, failed.\n");
switch (timed_wait_rv)
{
case ETIMEDOUT:
fprintf(stderr, "The time specified by abstime to pthread_cond_timedwait() has passed.\n");
break;
case EINVAL:
fprintf(stderr, "The value specified by abstime, cond or mutex is invalid.\n");
break;
case EPERM:
fprintf(stderr, "The mutex was not owned by the current thread at the time of the call.\n");
break;
default:
break;
}
}
void error_pthread_join(const int join_rv)
{
fprintf(stderr, "Could not join thread.\n");
switch (join_rv)
{
case EINVAL:
fprintf(stderr, "The implementation has detected that the value specified by thread does not refer to a joinable thread.\n");
break;
case ESRCH:
fprintf(stderr, "No thread could be found corresponding to that specified by the given thread ID.\n");
break;
case EDEADLK:
fprintf(stderr, "A deadlock was detected or the value of thread specifies the calling thread.\n");
break;
default:
break;
}
}
void error_clock_gettime(const int gettime_rv)
{
fprintf(stderr, "Could not get time from clock.\n");
switch (gettime_rv)
{
case EFAULT:
fprintf(stderr, "tp points outside the accessible address space.\n");
break;
case EINVAL:
fprintf(stderr, "The clk_id specified is not supported on this system.\n");
break;
case EPERM:
fprintf(stderr, "clock_settime() does not have permission to set the clock indicated.\n");
break;
default:
break;
}
}
// This is the thread that will be called by pthread_create() and it will be executed by the new thread.
void *worker_thread(void *data)
{
// We know that the input data pointer is pointing to a thread_info_t so we are casting it to the right type.
struct thread_info_t *thread_info = (struct thread_info_t *) data;
// We block this thread trying to lock the mutex, this way we will make sure that the parent thread had enough time to call pthread_cond_timedwait().
// When the parent thread calls pthread_cond_timedwait() it will unlock the mutex and this thread will be able to proceed.
const int lock_rv = pthread_mutex_lock(&(thread_info->mutex));
if (lock_rv)
{
error_pthread_mutex_lock(lock_rv);
}
int oldtype;
// The pthread_setcanceltype() sets the cancelability type of the calling thread to the value given in type.
// The previous cancelability type of the thread is returned in the buffer pointed to by oldtype.
// The argument PTHREAD_CANCEL_ASYNCHRONOUS means that the thread can be canceled at any time.
const int setcanceltype_rv = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype);
if (setcanceltype_rv)
{
error_pthread_setcanceltype(setcanceltype_rv);
}
// TODO: This is the place you should implement the functionality that is needed for this thread
// The pthread_cond_signal() call unblocks at least one of the threads that are blocked on the specified condition variable cond (if any threads are blocked on cond).
const int signal_rv = pthread_cond_signal(&(thread_info->condition));
if (signal_rv)
{
error_pthread_cond_signal(signal_rv);
}
// The pthread_mutex_unlock() function shall release the mutex object referenced by mutex.
const int unlock_rv = pthread_mutex_unlock(&(thread_info->mutex));
if (unlock_rv)
{
error_pthread_mutex_unlock(unlock_rv);
}
return NULL;
}
int main()
{
struct thread_info_t thread_info;
pthread_cond_init(&thread_info.condition, NULL);
pthread_mutex_init(&thread_info.mutex, NULL);
const int lock_rv = pthread_mutex_lock(&thread_info.mutex);
if (lock_rv)
{
error_pthread_mutex_lock(lock_rv);
}
const int create_rv = pthread_create(&(thread_info.thread_id), NULL, &worker_thread, (void *) &thread_info);
if (create_rv)
{
error_pthread_create(create_rv);
const int unlock_rv = pthread_mutex_unlock(&thread_info.mutex);
if (unlock_rv)
{
error_pthread_mutex_unlock(unlock_rv);
}
}
else
{
// timespec is a structure holding an interval broken down into seconds and nanoseconds.
struct timespec max_wait = {0, 0};
// The clock_gettime system call has higher precision than its successor the gettimeofday().
// It has the ability to request specific clocks using the clock id.
// It fills in a timespec structure with the seconds and nanosecond count of the time since the Epoch (00:00 1 January, 1970 UTC).
// CLOCK_REALTIME argument represents a system-wide real-time clock. This clock is supported by all implementations and returns the number of seconds and nanoseconds since the Epoch.
const int gettime_rv = clock_gettime(CLOCK_REALTIME, &max_wait);
if (gettime_rv)
{
error_clock_gettime(gettime_rv);
}
max_wait.tv_sec += MAX_WAIT_TIME_IN_SECONDS;
// The pthread_cond_timedwait() function blocks on a condition variable.
// It must be called with a mutex locked by the calling thread or undefined behavior results will occur.
// This function atomically releases the mutex and causes the calling thread to block on the condition variable cond;
// atomically here means "atomically with respect to access by another thread to the mutex and then the condition variable".
// That is, if another thread is able to acquire the mutex after the about-to-block thread has released it, then a subsequent call to pthread_cond_broadcast() or pthread_cond_signal() in that thread shall behave as if it were issued after the about-to-block thread has blocked.
const int timed_wait_rv = pthread_cond_timedwait(&thread_info.condition, &thread_info.mutex, &max_wait);
if (timed_wait_rv)
{
error_pthread_cond_timedwait(timed_wait_rv);
}
// The pthread_join() function suspends execution of the calling thread until the target thread terminates, unless the target thread has already terminated.
const int join_rv = pthread_join(thread_info.thread_id, NULL);
if (join_rv)
{
error_pthread_join(join_rv);
}
}
return 0;
}

Our Jenkins setup has a lot of cool features and configuration.
It has ‘project-based security’, it has parametrized projects, multiple source code management blocks per project and fairly extensive tests implemented with several build steps.
Of course, we do not want to lose them, so we make backups often.
The commands we use for the backup are the following.

In backup_folder="$HOME/jenkins/`date +%F`"; we used the $HOME variable instead of the tilde ~ as this would create a folder in the current directory called ~ instead of creating a new folder called jenkins in the home directory.

(cd "$jenkins_folder"/jobs/; find . -mindepth 3 -type d -regex '.*/[0-9]*$' -print) navigates to the directory of jenkins before performing the search, this way the result file names will be relative to the installation location which we need later to pass to rsync.
Then we search for all folders which their name is numeric and they at least on depth 3. We filter by depth as well to avoid matching folders directly in the jobs folder.

sed 's|./|jobs/|' replaces the prefix ./ with jobs/ to match the relative path from where rsync will work from

sudo rsync --archive --exclude 'workspace/*' --exclude-from=- "$jenkins_folder" "$backup_folder"; it will copy everything from $jenkins_folder to the folder $backup_folder while excluding the data in workspace and the folders matched from find (the job build folders).--exclude-from=- instructs rsync to read from stdin the list of files to exclude.

Using the parameter -l (or --listening) it will show only listening sockets/ports (which are omitted by default.).--numeric-ports shows numerical port numbers but does not affect the resolution of host or user names (e.g. instead of showing the name ssh, it will show the value 22).

We used netstat using the following syntax to check which sockets/ports are open on the current machine:

Check a specific port if it is open from a remote machine

In case you want to check a specific port if it is open from a remote machine, you can use nmap.
Using nmap to scan specific ports allows you to check if a remote machine appears to have open ports available to you.nmap is a network exploration tool and security / port scanner.

The following example checks ports 80 and 8080 on 192.168.1.199 if they are open.

From this information we got the hash value in front of the commit which we wanted to use to restore, which was 271f0084.

Then, we checked out that version using

git checkout 271f0084;

When we tried to push the branch back to the server the Git pre commit hooks blocked the operation.
Based on the rsa key used, we could only submit changes that were committed by the owner of that key.
The option to disable temporarily the pre commit hooks was unfortunately out of the question. So we had to replace all author names and emails with the name of the one holding the key.

To do so we used the following command before pushing to the server once more:

git filter-branch lets you rewrite Git revision history by rewriting the branches mentioned, in our case it was HEAD, applying custom filters on each revision. Those filters can modify each tree (e.g. removing a file or running a perl rewrite on all files) or information about each commit. Otherwise, all information (including original commit times or merge information) will be preserved.

HEAD is a reference to the currently checked out commit. In normal states, it’s actually a symbolic reference to the branch you have checked out.
Looking at the contents of .git/HEAD you’ll see something similar to ref: refs/heads/master.
The branch itself is a reference to the commit at the tip of the branch.

The following two examples demonstrate the use of bit fields to reduce memory consumption of certain applications.

In the first example we create a compressed ‘bit’ struct and on the second we create a weird struct representation for bytes to show that the size of that struct is significantly less that the original one.

Recently, we needed to filter the results of ps x using two different patterns.
The first pattern was ./ where we needed to match that exact character sequence.
The . period character is treated as a special character in regular expressions (it matches a single character of any value, except for the end of line), so we decided to use the -F parameter to remove this special handling.
Doing this change prevented us from writing a regular expression that uses the OR | operator.

-F (or --fixed-strings) is a matching control option that instructs grep to interpret the patterns as a list of fixed strings (instead of regular expressions), separated by newlines, any of which is to be matched.
We tried assigning the different patterns as different lines to a variable and then using them on the pipe, like in the following example:

patterns="./
banana";
ps x | grep -F $patterns;

..but it failed.

Solution

grep supports a matching control option -e that allows us to define multiple patterns using different strings.

-e PATTERN (or --regexp=PATTERN) uses the value PATTERN as the pattern. If this option is used multiple times or it is combined with the -f (--file) option, grep will search for all patterns given.

In the end, our command was transformed to the following, which worked just fine!