2017-01-16 15:50:47 -05:00
|
|
|
// This file is part of Moonfire NVR, a security camera digital video recorder.
|
|
|
|
// Copyright (C) 2016 Scott Lamb <slamb@slamb.org>
|
|
|
|
//
|
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
|
|
|
// In addition, as a special exception, the copyright holders give
|
|
|
|
// permission to link the code of portions of this program with the
|
|
|
|
// OpenSSL library under certain conditions as described in each
|
|
|
|
// individual source file, and distribute linked combinations including
|
|
|
|
// the two.
|
|
|
|
//
|
|
|
|
// You must obey the GNU General Public License in all respects for all
|
|
|
|
// of the code used other than OpenSSL. If you modify file(s) with this
|
|
|
|
// exception, you may extend this exception to your version of the
|
|
|
|
// file(s), but you are not obligated to do so. If you do not wish to do
|
|
|
|
// so, delete this exception statement from your version. If you delete
|
|
|
|
// this exception statement from all source files in the program, then
|
|
|
|
// also delete it here.
|
|
|
|
//
|
|
|
|
// This program is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU General Public License
|
|
|
|
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
2018-12-28 22:53:29 -05:00
|
|
|
use base::clock;
|
|
|
|
use crate::stream;
|
|
|
|
use crate::streamer;
|
|
|
|
use crate::web;
|
|
|
|
use db::{dir, writer};
|
2019-06-19 18:17:50 -04:00
|
|
|
use failure::{Error, bail, format_err};
|
2018-02-12 01:45:51 -05:00
|
|
|
use fnv::FnvHashMap;
|
2017-09-22 00:51:58 -04:00
|
|
|
use futures::{Future, Stream};
|
2018-12-28 22:53:29 -05:00
|
|
|
use log::{error, info, warn};
|
|
|
|
use serde::Deserialize;
|
2018-08-30 01:26:19 -04:00
|
|
|
use std::error::Error as StdError;
|
2017-01-16 15:50:47 -05:00
|
|
|
use std::sync::Arc;
|
|
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
|
|
use std::thread;
|
2018-08-30 01:26:19 -04:00
|
|
|
use tokio;
|
2017-03-02 22:29:28 -05:00
|
|
|
use tokio_signal::unix::{Signal, SIGINT, SIGTERM};
|
2017-01-16 15:50:47 -05:00
|
|
|
|
2017-10-22 02:57:13 -04:00
|
|
|
// These are used in a hack to get the name of the current time zone (e.g. America/Los_Angeles).
|
2018-04-06 16:49:18 -04:00
|
|
|
// They seem to be correct for Linux and macOS at least.
|
2017-10-22 02:57:13 -04:00
|
|
|
const LOCALTIME_PATH: &'static str = "/etc/localtime";
|
2018-08-31 20:19:24 -04:00
|
|
|
const TIMEZONE_PATH: &'static str = "/etc/timezone";
|
2018-04-06 16:49:18 -04:00
|
|
|
const ZONEINFO_PATHS: [&'static str; 2] = [
|
|
|
|
"/usr/share/zoneinfo/", // Linux, macOS < High Sierra
|
|
|
|
"/var/db/timezone/zoneinfo/" // macOS High Sierra
|
|
|
|
];
|
2017-10-22 02:57:13 -04:00
|
|
|
|
2017-01-16 15:50:47 -05:00
|
|
|
const USAGE: &'static str = r#"
|
|
|
|
Usage: moonfire-nvr run [options]
|
|
|
|
|
|
|
|
Options:
|
|
|
|
-h, --help Show this message.
|
|
|
|
--db-dir=DIR Set the directory holding the SQLite3 index database.
|
|
|
|
This is typically on a flash device.
|
|
|
|
[default: /var/lib/moonfire-nvr/db]
|
2018-03-03 09:43:36 -05:00
|
|
|
--ui-dir=DIR Set the directory with the user interface files
|
|
|
|
(.html, .js, etc).
|
2017-10-22 00:54:27 -04:00
|
|
|
[default: /usr/local/lib/moonfire-nvr/ui]
|
2017-01-16 15:50:47 -05:00
|
|
|
--http-addr=ADDR Set the bind address for the unencrypted HTTP server.
|
|
|
|
[default: 0.0.0.0:8080]
|
|
|
|
--read-only Forces read-only mode / disables recording.
|
2019-06-19 18:17:50 -04:00
|
|
|
--allow-unauthenticated-permissions=PERMISSIONS
|
|
|
|
Allow unauthenticated access to the web interface,
|
|
|
|
with the given permissions (may be empty).
|
|
|
|
PERMISSIONS should be a text Permissions protobuf
|
|
|
|
such as "view_videos: true". NOTE: even an empty
|
|
|
|
string allows some basic access that would be
|
|
|
|
rejected if the argument were omitted.
|
2018-11-28 17:22:30 -05:00
|
|
|
--trust-forward-hdrs Trust X-Real-IP: and X-Forwarded-Proto: headers on
|
|
|
|
the incoming request. Set this only after ensuring
|
|
|
|
your proxy server is configured to set them and that
|
|
|
|
no untrusted requests bypass the proxy server.
|
|
|
|
You may want to specify --http-addr=127.0.0.1:8080.
|
2017-01-16 15:50:47 -05:00
|
|
|
"#;
|
|
|
|
|
2017-06-11 15:57:55 -04:00
|
|
|
#[derive(Debug, Deserialize)]
|
2017-01-16 15:50:47 -05:00
|
|
|
struct Args {
|
|
|
|
flag_db_dir: String,
|
|
|
|
flag_http_addr: String,
|
2017-10-22 00:54:27 -04:00
|
|
|
flag_ui_dir: String,
|
2017-01-16 15:50:47 -05:00
|
|
|
flag_read_only: bool,
|
2019-06-19 18:17:50 -04:00
|
|
|
flag_allow_unauthenticated_permissions: Option<String>,
|
2018-11-28 17:22:30 -05:00
|
|
|
flag_trust_forward_hdrs: bool,
|
2017-01-16 15:50:47 -05:00
|
|
|
}
|
|
|
|
|
2018-08-30 01:26:19 -04:00
|
|
|
fn setup_shutdown() -> impl Future<Item = (), Error = ()> + Send {
|
|
|
|
let int = Signal::new(SIGINT).flatten_stream().into_future();
|
|
|
|
let term = Signal::new(SIGTERM).flatten_stream().into_future();
|
|
|
|
int.select(term)
|
|
|
|
.map(|_| ())
|
|
|
|
.map_err(|_| ())
|
2017-03-02 22:29:28 -05:00
|
|
|
}
|
|
|
|
|
2018-08-31 20:19:24 -04:00
|
|
|
fn trim_zoneinfo(p: &str) -> &str {
|
2018-04-06 16:49:18 -04:00
|
|
|
for zp in &ZONEINFO_PATHS {
|
|
|
|
if p.starts_with(zp) {
|
2018-08-31 20:19:24 -04:00
|
|
|
return &p[zp.len()..];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return p;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Attempt to resolve the timezone of the server.
|
|
|
|
/// The Javascript running in the browser needs this to match the server's timezone calculations.
|
|
|
|
fn resolve_zone() -> Result<String, Error> {
|
|
|
|
// If the environmental variable `TZ` exists, is valid UTF-8, and doesn't just reference
|
|
|
|
// `/etc/localtime/`, use that.
|
|
|
|
if let Ok(tz) = ::std::env::var("TZ") {
|
|
|
|
let mut p: &str = &tz;
|
|
|
|
|
|
|
|
// Strip of an initial `:` if present. Having `TZ` set in this way is a trick to avoid
|
|
|
|
// repeated `tzset` calls:
|
|
|
|
// https://blog.packagecloud.io/eng/2017/02/21/set-environment-variable-save-thousands-of-system-calls/
|
|
|
|
if p.starts_with(':') {
|
|
|
|
p = &p[1..];
|
|
|
|
}
|
|
|
|
|
|
|
|
p = trim_zoneinfo(p);
|
|
|
|
|
|
|
|
if !p.starts_with('/') {
|
|
|
|
return Ok(p.to_owned());
|
|
|
|
}
|
|
|
|
if p != LOCALTIME_PATH {
|
|
|
|
bail!("Unable to resolve env TZ={} to a timezone.", &tz);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If `LOCALTIME_PATH` is a symlink, use that. On some systems, it's instead a copy of the
|
|
|
|
// desired timezone, which unfortunately doesn't contain its own name.
|
|
|
|
match ::std::fs::read_link(LOCALTIME_PATH) {
|
|
|
|
Ok(localtime_dest) => {
|
|
|
|
let localtime_dest = match localtime_dest.to_str() {
|
|
|
|
Some(d) => d,
|
|
|
|
None => bail!("{} symlink destination is invalid UTF-8", LOCALTIME_PATH),
|
|
|
|
};
|
|
|
|
let p = trim_zoneinfo(localtime_dest);
|
|
|
|
if p.starts_with('/') {
|
|
|
|
bail!("Unable to resolve {} symlink destination {} to a timezone.",
|
|
|
|
LOCALTIME_PATH, &localtime_dest);
|
|
|
|
}
|
|
|
|
return Ok(p.to_owned());
|
|
|
|
},
|
|
|
|
Err(e) => {
|
|
|
|
use ::std::io::ErrorKind;
|
|
|
|
if e.kind() != ErrorKind::NotFound && e.kind() != ErrorKind::InvalidInput {
|
|
|
|
bail!("Unable to read {} symlink: {}", LOCALTIME_PATH, e);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
// If `TIMEZONE_PATH` is a file, use its contents as the zone name.
|
|
|
|
match ::std::fs::read_to_string(TIMEZONE_PATH) {
|
|
|
|
Ok(z) => return Ok(z),
|
|
|
|
Err(e) => {
|
|
|
|
bail!("Unable to resolve timezone from TZ env, {}, or {}. Last error: {}",
|
|
|
|
LOCALTIME_PATH, TIMEZONE_PATH, e);
|
2018-04-06 16:49:18 -04:00
|
|
|
}
|
2017-10-22 02:57:13 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-12 01:45:51 -05:00
|
|
|
struct Syncer {
|
|
|
|
dir: Arc<dir::SampleFileDir>,
|
2018-03-04 15:24:24 -05:00
|
|
|
channel: writer::SyncerChannel<::std::fs::File>,
|
2018-02-12 01:45:51 -05:00
|
|
|
join: thread::JoinHandle<()>,
|
|
|
|
}
|
|
|
|
|
2017-01-16 15:50:47 -05:00
|
|
|
pub fn run() -> Result<(), Error> {
|
|
|
|
let args: Args = super::parse_args(USAGE)?;
|
2018-03-23 16:31:23 -04:00
|
|
|
let clocks = clock::RealClocks {};
|
2017-01-16 17:21:08 -05:00
|
|
|
let (_db_dir, conn) = super::open_conn(
|
|
|
|
&args.flag_db_dir,
|
|
|
|
if args.flag_read_only { super::OpenMode::ReadOnly } else { super::OpenMode::ReadWrite })?;
|
2018-03-09 20:41:53 -05:00
|
|
|
let db = Arc::new(db::Database::new(clocks.clone(), conn, !args.flag_read_only).unwrap());
|
2017-01-16 15:50:47 -05:00
|
|
|
info!("Database is loaded.");
|
|
|
|
|
2018-02-15 02:10:10 -05:00
|
|
|
{
|
|
|
|
let mut l = db.lock();
|
|
|
|
let dirs_to_open: Vec<_> =
|
|
|
|
l.streams_by_id().values().filter_map(|s| s.sample_file_dir_id).collect();
|
|
|
|
l.open_sample_file_dirs(&dirs_to_open)?;
|
|
|
|
}
|
|
|
|
info!("Directories are opened.");
|
|
|
|
|
2018-11-28 17:22:30 -05:00
|
|
|
let time_zone_name = resolve_zone()?;
|
|
|
|
info!("Resolved timezone: {}", &time_zone_name);
|
2019-06-19 18:17:50 -04:00
|
|
|
let allow_unauthenticated_permissions = args.flag_allow_unauthenticated_permissions
|
|
|
|
.map(|s| protobuf::text_format::parse_from_str(&s))
|
|
|
|
.transpose()
|
|
|
|
.map_err(|_| format_err!("Unable to parse --allow-unauthenticated-permissions"))?;
|
2018-11-28 17:22:30 -05:00
|
|
|
let s = web::Service::new(web::Config {
|
|
|
|
db: db.clone(),
|
|
|
|
ui_dir: Some(&args.flag_ui_dir),
|
2019-06-19 18:17:50 -04:00
|
|
|
allow_unauthenticated_permissions,
|
2018-11-28 17:22:30 -05:00
|
|
|
trust_forward_hdrs: args.flag_trust_forward_hdrs,
|
|
|
|
time_zone_name,
|
|
|
|
})?;
|
2017-10-22 00:54:27 -04:00
|
|
|
|
2018-01-23 14:05:07 -05:00
|
|
|
// Start a streamer for each stream.
|
2017-03-02 22:29:28 -05:00
|
|
|
let shutdown_streamers = Arc::new(AtomicBool::new(false));
|
2017-01-16 15:50:47 -05:00
|
|
|
let mut streamers = Vec::new();
|
2018-02-12 01:45:51 -05:00
|
|
|
let syncers = if !args.flag_read_only {
|
2017-01-16 15:50:47 -05:00
|
|
|
let l = db.lock();
|
2018-02-12 01:45:51 -05:00
|
|
|
let mut dirs = FnvHashMap::with_capacity_and_hasher(
|
|
|
|
l.sample_file_dirs_by_id().len(), Default::default());
|
2018-01-23 14:05:07 -05:00
|
|
|
let streams = l.streams_by_id().len();
|
2018-02-12 01:45:51 -05:00
|
|
|
let env = streamer::Environment {
|
2017-01-16 15:50:47 -05:00
|
|
|
db: &db,
|
|
|
|
opener: &*stream::FFMPEG,
|
2017-03-02 22:29:28 -05:00
|
|
|
shutdown: &shutdown_streamers,
|
2017-01-16 15:50:47 -05:00
|
|
|
};
|
2018-02-12 01:45:51 -05:00
|
|
|
|
2018-02-15 02:10:10 -05:00
|
|
|
// Get the directories that need syncers.
|
2018-02-12 01:45:51 -05:00
|
|
|
for stream in l.streams_by_id().values() {
|
|
|
|
if let (Some(id), true) = (stream.sample_file_dir_id, stream.record) {
|
|
|
|
dirs.entry(id).or_insert_with(|| {
|
|
|
|
let d = l.sample_file_dirs_by_id().get(&id).unwrap();
|
|
|
|
info!("Starting syncer for path {}", d.path);
|
2018-02-15 02:10:10 -05:00
|
|
|
d.get().unwrap()
|
2018-02-12 01:45:51 -05:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Then, with the lock dropped, create syncers.
|
|
|
|
drop(l);
|
|
|
|
let mut syncers = FnvHashMap::with_capacity_and_hasher(dirs.len(), Default::default());
|
|
|
|
for (id, dir) in dirs.drain() {
|
2018-03-04 15:24:24 -05:00
|
|
|
let (channel, join) = writer::start_syncer(db.clone(), id)?;
|
2018-02-12 01:45:51 -05:00
|
|
|
syncers.insert(id, Syncer {
|
|
|
|
dir,
|
|
|
|
channel,
|
|
|
|
join,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Then start up streams.
|
|
|
|
let l = db.lock();
|
2018-01-23 14:05:07 -05:00
|
|
|
for (i, (id, stream)) in l.streams_by_id().iter().enumerate() {
|
2018-01-30 18:29:19 -05:00
|
|
|
if !stream.record {
|
|
|
|
continue;
|
|
|
|
}
|
2018-01-23 14:05:07 -05:00
|
|
|
let camera = l.cameras_by_id().get(&stream.camera_id).unwrap();
|
2018-02-12 01:45:51 -05:00
|
|
|
let sample_file_dir_id = match stream.sample_file_dir_id {
|
|
|
|
Some(s) => s,
|
|
|
|
None => {
|
|
|
|
warn!("Can't record stream {} ({}/{}) because it has no sample file dir",
|
|
|
|
id, camera.short_name, stream.type_.as_str());
|
|
|
|
continue;
|
|
|
|
},
|
|
|
|
};
|
2018-01-23 14:05:07 -05:00
|
|
|
let rotate_offset_sec = streamer::ROTATE_INTERVAL_SEC * i as i64 / streams as i64;
|
2018-02-12 01:45:51 -05:00
|
|
|
let syncer = syncers.get(&sample_file_dir_id).unwrap();
|
|
|
|
let mut streamer = streamer::Streamer::new(&env, syncer.dir.clone(),
|
|
|
|
syncer.channel.clone(), *id, camera, stream,
|
|
|
|
rotate_offset_sec,
|
2017-01-16 15:50:47 -05:00
|
|
|
streamer::ROTATE_INTERVAL_SEC);
|
2018-02-12 01:45:51 -05:00
|
|
|
info!("Starting streamer for {}", streamer.short_name());
|
2018-01-23 14:05:07 -05:00
|
|
|
let name = format!("s-{}", streamer.short_name());
|
2017-01-16 15:50:47 -05:00
|
|
|
streamers.push(thread::Builder::new().name(name).spawn(move|| {
|
|
|
|
streamer.run();
|
|
|
|
}).expect("can't create thread"));
|
|
|
|
}
|
2018-02-12 01:45:51 -05:00
|
|
|
drop(l);
|
|
|
|
Some(syncers)
|
2017-01-16 15:50:47 -05:00
|
|
|
} else { None };
|
|
|
|
|
|
|
|
// Start the web interface.
|
2017-03-02 22:29:28 -05:00
|
|
|
let addr = args.flag_http_addr.parse().unwrap();
|
2018-08-30 01:26:19 -04:00
|
|
|
let server = ::hyper::server::Server::bind(&addr).tcp_nodelay(true).serve(
|
2019-06-14 11:47:11 -04:00
|
|
|
move || Ok::<_, Box<dyn StdError + Send + Sync>>(s.clone()));
|
2017-03-02 22:29:28 -05:00
|
|
|
|
2018-08-30 01:26:19 -04:00
|
|
|
let shutdown = setup_shutdown().shared();
|
2017-03-02 22:29:28 -05:00
|
|
|
|
2017-01-16 15:50:47 -05:00
|
|
|
info!("Ready to serve HTTP requests");
|
2018-08-30 01:26:19 -04:00
|
|
|
let reactor = ::std::thread::spawn({
|
|
|
|
let shutdown = shutdown.clone();
|
|
|
|
|| tokio::run(server.with_graceful_shutdown(shutdown.map(|_| ()))
|
|
|
|
.map_err(|e| error!("hyper error: {}", e)))
|
|
|
|
});
|
|
|
|
shutdown.wait().unwrap();
|
2017-01-16 15:50:47 -05:00
|
|
|
|
2017-03-02 22:29:28 -05:00
|
|
|
info!("Shutting down streamers.");
|
|
|
|
shutdown_streamers.store(true, Ordering::SeqCst);
|
2017-01-16 15:50:47 -05:00
|
|
|
for streamer in streamers.drain(..) {
|
|
|
|
streamer.join().unwrap();
|
|
|
|
}
|
2017-03-02 22:29:28 -05:00
|
|
|
|
2018-02-12 01:45:51 -05:00
|
|
|
if let Some(mut ss) = syncers {
|
2018-02-22 19:35:34 -05:00
|
|
|
// The syncers shut down when all channels to them have been dropped.
|
|
|
|
// The database maintains one; and `ss` holds one. Drop both.
|
|
|
|
db.lock().clear_on_flush();
|
2018-02-12 01:45:51 -05:00
|
|
|
for (_, s) in ss.drain() {
|
|
|
|
drop(s.channel);
|
|
|
|
s.join.join().unwrap();
|
|
|
|
}
|
2017-01-16 15:50:47 -05:00
|
|
|
}
|
2017-03-02 22:29:28 -05:00
|
|
|
|
2019-01-21 18:58:52 -05:00
|
|
|
db.lock().clear_watches();
|
|
|
|
|
2018-08-30 01:26:19 -04:00
|
|
|
info!("Waiting for HTTP requests to finish.");
|
|
|
|
reactor.join().unwrap();
|
2017-01-16 15:50:47 -05:00
|
|
|
info!("Exiting.");
|
2017-03-26 03:01:48 -04:00
|
|
|
Ok(())
|
2017-01-16 15:50:47 -05:00
|
|
|
}
|