Exemplo n.º 1
0
        protected override void Dispose(bool disposing)
        {
            if (_isDisposed)
            {
                return;
            }
            _isDisposed = true;

            if (disposing)
            {
                if (_socket != null)
                {
                    _socket.Dispose();
                    _socket = null;
                }

                if (_stream != null)
                {
                    _stream.Dispose();
                    _stream = null;
                }

                if (_aliveTimer != null)
                {
                    _aliveTimer.Dispose();
                    _aliveTimer = null;
                }

                if (_taskManager != null)
                {
                    _taskManager.Dispose();
                    _taskManager = null;
                }
            }
        }
        public MulticastMessageEditWindow(Tag tag, string comment, AmoebaManager amoebaManager)
        {
            _tag           = tag;
            _amoebaManager = amoebaManager;

            _digitalSignatureCollection.AddRange(Settings.Instance.Global_DigitalSignatures.ToArray());

            InitializeComponent();

            this.Title = LanguagesManager.Instance.MulticastMessageEditWindow_Title + " - " + MessageConverter.ToTagString(tag);

            {
                var icon = new BitmapImage();

                icon.BeginInit();
                icon.StreamSource = new FileStream(Path.Combine(_serviceManager.Paths["Icons"], "Amoeba.ico"), FileMode.Open, FileAccess.Read, FileShare.Read);
                icon.EndInit();
                if (icon.CanFreeze)
                {
                    icon.Freeze();
                }

                this.Icon = icon;
            }

            _signatureComboBox.ItemsSource   = _digitalSignatureCollection;
            _signatureComboBox.SelectedIndex = 0;

            _commentTextBox.Text = comment;

            _watchTimer  = new WatchTimer(this.WatchThread, 0, 1000);
            this.Closed += (sender, e) => _watchTimer.Dispose();

            _textEditor_Helper.Setup(_textEditor);
        }
Exemplo n.º 3
0
        public DownloadManager(string configPath, NetworkManager networkManager, CacheManager cacheManager, BufferManager bufferManager)
        {
            _networkManager = networkManager;
            _cacheManager   = cacheManager;
            _bufferManager  = bufferManager;

            _settings = new Settings(configPath);

            _downloadTaskManager = new TaskManager(this.DownloadingThread);

            for (int i = 0; i < _threadCount; i++)
            {
                _decodeTaskManagers.Add(new TaskManager(this.DecodingThread));
            }

            _volatileDownloadItemInfoManager              = new VolatileDownloadItemInfoManager();
            _volatileDownloadItemInfoManager.AddEvent    += (info) => this.Event_AddInfo(info);
            _volatileDownloadItemInfoManager.RemoveEvent += (info) => this.Event_RemoveInfo(info);

            _downloadItemInfoManager               = new DownloadItemInfoManager();
            _downloadItemInfoManager.AddEvents    += (info) => this.Event_AddInfo(info);
            _downloadItemInfoManager.RemoveEvents += (info) => this.Event_RemoveInfo(info);

            _protectCacheInfoManager = new ProtectedCacheInfoManager(_cacheManager);

            _watchTimer = new WatchTimer(this.WatchThread);
            _watchTimer.Start(new TimeSpan(0, 1, 0));

            _cacheManager.AddedBlockEvents   += (hashes) => this.Update_DownloadBlockStates(true, hashes);
            _cacheManager.RemovedBlockEvents += (hashes) => this.Update_DownloadBlockStates(false, hashes);
        }
        public MulticastMessageEditWindow(Tag tag, string comment, AmoebaManager amoebaManager)
        {
            _tag = tag;
            _amoebaManager = amoebaManager;

            _digitalSignatureCollection.AddRange(Settings.Instance.Global_DigitalSignatures.ToArray());

            InitializeComponent();

            this.Title = LanguagesManager.Instance.MulticastMessageEditWindow_Title + " - " + MessageConverter.ToTagString(tag);

            {
                var icon = new BitmapImage();

                icon.BeginInit();
                icon.StreamSource = new FileStream(Path.Combine(_serviceManager.Paths["Icons"], "Amoeba.ico"), FileMode.Open, FileAccess.Read, FileShare.Read);
                icon.EndInit();
                if (icon.CanFreeze) icon.Freeze();

                this.Icon = icon;
            }

            _signatureComboBox.ItemsSource = _digitalSignatureCollection;
            _signatureComboBox.SelectedIndex = 0;

            _commentTextBox.Text = comment;

            _watchTimer = new WatchTimer(this.WatchThread, 0, 1000);
            this.Closed += (sender, e) => _watchTimer.Dispose();

            _textEditor_Helper.Setup(_textEditor);
        }
Exemplo n.º 5
0
            protected override void Dispose(bool isDisposing)
            {
                if (_isDisposed)
                {
                    return;
                }
                _isDisposed = true;

                if (isDisposing)
                {
                    if (_watchTimer != null)
                    {
                        try
                        {
                            _watchTimer.Stop();
                            _watchTimer.Dispose();
                        }
                        catch (Exception)
                        {
                        }

                        _watchTimer = null;
                    }
                }
            }
Exemplo n.º 6
0
        protected override void Dispose(bool isDisposing)
        {
            if (_isDisposed)
            {
                return;
            }
            _isDisposed = true;

            if (isDisposing)
            {
                if (_watchTimer != null)
                {
                    try
                    {
                        _watchTimer.Stop();
                        _watchTimer.Dispose();
                    }
                    catch (Exception)
                    {
                    }

                    _watchTimer = null;
                }

                _downloadTaskManager.Stop();

                foreach (var taskManager in _decodeTaskManagers)
                {
                    taskManager.Stop();
                }
                _decodeTaskManagers.Clear();

                _protectCacheInfoManager.Dispose();
            }
        }
Exemplo n.º 7
0
            public ProtectCacheInfoManager(CacheManager cacheManager)
            {
                _cacheManager = cacheManager;
                _infos        = new LockedList <ProtectCacheInfo>();

                _watchTimer = new WatchTimer(() => this.WatchThread());
                _watchTimer.Start(new TimeSpan(0, 1, 0));
            }
Exemplo n.º 8
0
 private void btnStop_Click(object sender, EventArgs e)
 {
     WatchTimer.Stop();
     btnStart.Enabled = true;
     btnStop.Enabled  = false;
     btnPause.Enabled = false;
     movieMaker.Stop();
 }
Exemplo n.º 9
0
            public I2pConnectionManager(string configPath, BufferManager bufferManager)
            {
                _bufferManager = bufferManager;

                _settings = new Settings(configPath);

                _watchTimer = new WatchTimer(this.WatchThread);
            }
Exemplo n.º 10
0
        public ServerManager(BufferManager bufferManager)
        {
            _bufferManager = bufferManager;

            _settings = new Settings();

            _watchTimer = new WatchTimer(this.WatchTimer, Timeout.Infinite);
        }
Exemplo n.º 11
0
        public TcpConnectionManager(string configPath, CatharsisManager catharsisManager, BufferManager bufferManager)
        {
            _bufferManager    = bufferManager;
            _catharsisManager = catharsisManager;

            _settings = new Settings(configPath);

            _watchTimer = new WatchTimer(this.WatchListenerThread);
        }
Exemplo n.º 12
0
        public MessagingManager(Socket socket, BufferManager bufferManager)
        {
            _socket        = socket;
            _stream        = new NetworkStream(_socket);
            _bufferManager = bufferManager;

            _taskManager = new TaskManager(this.EventLoop);
            _aliveTimer  = new WatchTimer(() => this.Alive());
        }
        public BackgroundUploadManager(ConnectionsManager connectionsManager, CacheManager cacheManager, BufferManager bufferManager)
        {
            _connectionsManager = connectionsManager;
            _cacheManager = cacheManager;
            _bufferManager = bufferManager;

            _settings = new Settings();

            _watchTimer = new WatchTimer(this.WatchTimer, Timeout.Infinite);
        }
Exemplo n.º 14
0
        public CacheManager(string configPath, string blocksPath, BufferManager bufferManager)
        {
            _bufferManager      = bufferManager;
            _blocksManager      = new BlocksManager(Path.Combine(configPath, "Blocks"), blocksPath, _bufferManager);
            _contentInfoManager = new ContentInfosManager();

            _settings = new Settings(configPath);

            _checkTimer = new WatchTimer(this.CheckTimer);
        }
Exemplo n.º 15
0
        private void Setting_CheckDiskSpace()
        {
            bool watchFlag = true;

            _checkDiskSpaceTimer = new WatchTimer(() =>
            {
                if (!watchFlag)
                {
                    return;
                }

                try
                {
                    bool flag = false;

                    if (_amoebaInterfaceManager.Report.Core.Cache.FreeSpace < NetworkConverter.FromSizeString("10GB"))
                    {
                        flag |= true;
                    }

                    if (!flag)
                    {
                        if (_amoebaInterfaceManager.State == ManagerState.Stop)
                        {
                            _amoebaInterfaceManager.Start();
                            Log.Information("Start");
                        }
                    }
                    else
                    {
                        if (_amoebaInterfaceManager.State == ManagerState.Start)
                        {
                            _amoebaInterfaceManager.Stop();
                            Log.Information("Stop");

                            watchFlag = false;

                            App.Current.Dispatcher.InvokeAsync(() =>
                            {
                                if (_dialogService.ShowDialog(LanguagesManager.Instance.MainWindow_SpaceNotFound_Message,
                                                              MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
                                {
                                    watchFlag = true;
                                }
                            });
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            });
            _checkDiskSpaceTimer.Start(new TimeSpan(0, 0, 0), new TimeSpan(0, 3, 0));
        }
Exemplo n.º 16
0
            protected override void Dispose(bool isDisposing)
            {
                if (_isDisposed)
                {
                    return;
                }
                _isDisposed = true;

                if (isDisposing)
                {
                    _addedBlockEventQueue.Dispose();
                    _removedBlockEventQueue.Dispose();

                    if (_sectorsManager != null)
                    {
                        try
                        {
                            _sectorsManager.Dispose();
                        }
                        catch (Exception)
                        {
                        }

                        _sectorsManager = null;
                    }

                    if (_fileStream != null)
                    {
                        try
                        {
                            _fileStream.Dispose();
                        }
                        catch (Exception)
                        {
                        }

                        _fileStream = null;
                    }

                    if (_updateTimer != null)
                    {
                        try
                        {
                            _updateTimer.Dispose();
                        }
                        catch (Exception)
                        {
                        }

                        _updateTimer = null;
                    }
                }
            }
Exemplo n.º 17
0
            public CatharsisManager(string configPath, BufferManager bufferManager)
            {
                _bufferManager = bufferManager;

                _settings = new Settings(configPath);

                _watchTimer  = new WatchTimer(this.WatchThread);
                _updateTimer = new WatchTimer(() => _ipv4ResultMap?.Update());
                _updateTimer.Start(new TimeSpan(0, 30, 0));

                _ipv4ResultMap = new VolatileHashDictionary <Ipv4, bool>(new TimeSpan(0, 30, 0));
            }
Exemplo n.º 18
0
        protected override void Dispose(bool isDisposing)
        {
            if (_isDisposed)
            {
                return;
            }
            _isDisposed = true;

            if (isDisposing)
            {
                _removedBlockEventQueue.Dispose();

                if (_blocksManager != null)
                {
                    try
                    {
                        _blocksManager.Dispose();
                    }
                    catch (Exception)
                    {
                    }

                    _blocksManager = null;
                }

                if (_checkTimer != null)
                {
                    try
                    {
                        _checkTimer.Dispose();
                    }
                    catch (Exception)
                    {
                    }

                    _checkTimer = null;
                }

                if (_checkTimer != null)
                {
                    try
                    {
                        _checkTimer.Dispose();
                    }
                    catch (Exception)
                    {
                    }

                    _checkTimer = null;
                }
            }
        }
Exemplo n.º 19
0
        public ConnectionManager(string configPath, CoreManager coreManager, BufferManager bufferManager)
        {
            _bufferManager           = bufferManager;
            _coreManager             = coreManager;
            _catharsisManager        = new CatharsisManager(Path.Combine(configPath, "Catharsis"), _bufferManager);
            _tcpConnectionManager    = new TcpConnectionManager(Path.Combine(configPath, "TcpConnection"), _catharsisManager, _bufferManager);
            _i2pConnectionManager    = new I2pConnectionManager(Path.Combine(configPath, "I2pConnection"), _bufferManager);
            _customConnectionManager = new CustomConnectionManager(Path.Combine(configPath, "CustomConnection"), _catharsisManager, _bufferManager);

            _coreManager.ConnectCapEvent = (_, uri) => this.ConnectCap(uri);
            _coreManager.AcceptCapEvent  = (object _, out string uri) => this.AcceptCap(out uri);

            _watchTimer = new WatchTimer(this.WatchThread);
        }
Exemplo n.º 20
0
        public UploadManager(ConnectionsManager connectionsManager, CacheManager cacheManager, BufferManager bufferManager)
        {
            _connectionsManager = connectionsManager;
            _cacheManager = cacheManager;
            _bufferManager = bufferManager;

            _settings = new Settings();

            _threadCount = Math.Max(1, Math.Min(System.Environment.ProcessorCount, 32) / 2);

            _watchTimer = new WatchTimer(this.WatchTimer, Timeout.Infinite);

            _cacheManager.ShareRemoveEvents += this.ShareRemoveThread;
        }
Exemplo n.º 21
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            StartTime = DateTime.Now;
            WatchTimer.Start();
            btnStart.Enabled = false;
            btnStop.Enabled  = true;
            btnPause.Enabled = true;
            movieMaker       = new MovieMaker();
            if (!Directory.Exists(VideosPath))
            {
                Directory.CreateDirectory(VideosPath);
            }
            var    name     = movieMaker.GenerateName();
            string filename = Path.Combine(VideosPath, name);

            movieMaker.Start(filename);
        }
Exemplo n.º 22
0
        private void btnPause_Click(object sender, EventArgs e)
        {
            if (movieMaker.IsRecording)
            {
                btnPause.Text = "Resume";

                movieMaker.Pause();
                WatchTimer.Stop();
            }
            else
            {
                btnPause.Text = "Pause";
                movieMaker.Resume();
                WatchTimer.Start();
            }
            btnPause.TextAlign = ContentAlignment.MiddleCenter;
        }
Exemplo n.º 23
0
        public MessageManager(string configPath, CoreManager coreManager, BufferManager bufferManager)
        {
            _bufferManager = bufferManager;
            _coreManager   = coreManager;

            _settings = new Settings(configPath);

            _cache_Profiles     = new VolatileHashDictionary <BroadcastMetadata, BroadcastMessage <Profile> >(new TimeSpan(0, 30, 0));
            _cache_Stores       = new VolatileHashDictionary <BroadcastMetadata, BroadcastMessage <Store> >(new TimeSpan(0, 30, 0));
            _cache_MailMessages = new VolatileHashDictionary <Signature, LockedHashDictionary <UnicastMetadata, UnicastMessage <MailMessage> > >(new TimeSpan(0, 30, 0));
            _cache_ChatMessages = new VolatileHashDictionary <Tag, LockedHashDictionary <MulticastMetadata, MulticastMessage <ChatMessage> > >(new TimeSpan(0, 30, 0));

            _watchTimer = new WatchTimer(this.WatchTimer);
            _watchTimer.Start(new TimeSpan(0, 0, 30));

            _coreManager.GetLockSignaturesEvent = (_) => this.Config.SearchSignatures;
        }
Exemplo n.º 24
0
        protected override void Dispose(bool isDisposing)
        {
            if (_isDisposed)
            {
                return;
            }
            _isDisposed = true;

            if (isDisposing)
            {
                if (_timer != null)
                {
                    _timer.Stop();
                    _timer.Dispose();
                    _timer = null;
                }
            }
        }
Exemplo n.º 25
0
        private void Setting_CheckDiskSpace()
        {
            _checkDiskSpaceTimer = new WatchTimer(() =>
            {
                try
                {
                    bool flag = false;


                    if (_serviceManager.Report.Core.Cache.FreeSpace < NetworkConverter.FromSizeString("32GB") &&
                        _serviceManager.Report.Core.Cache.FreeSpace < (_serviceManager.Size / 3))
                    {
                        flag |= true;
                    }

                    if (!flag)
                    {
                        if (_serviceManager.State == ManagerState.Stop)
                        {
                            _serviceManager.Start();
                            Log.Information("Start");
                        }
                    }
                    else
                    {
                        if (_serviceManager.State == ManagerState.Start)
                        {
                            _serviceManager.Stop();
                            Log.Information("Stop");
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            });
            _checkDiskSpaceTimer.Start(new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 30));
        }
Exemplo n.º 26
0
    IEnumerator SpawnWithDelay()
    {
        CardType   tmp_type = selected_type; // remember becouse can be set to None during Coroutine
        GameObject tmp_card = selected_card;

        // unselect first to allow multiple coroutines at the same time
        Unselect(false);    // dont destroy instance, yet

        float      seconds  = cm.cards[(int)tmp_type].spawnTime;
        GameObject timerObj = Instantiate(Resources.Load("Prefabs/UI/WatchTimer") as GameObject);
        WatchTimer timer    = timerObj.GetComponent <WatchTimer>();

        Assert.IsTrue(timer != null);
        timer.seconds_per_revolution = seconds;
        timer.transform.position     = tmp_card.transform.position + Vector3.back * 3;

        yield return(new WaitForSeconds(seconds));

        Destroy(timerObj);

        Assert.IsTrue(tmp_card != null);

        GameObject squadObj = cm.PlayType(tmp_type);

        squadObj.transform.position   = tmp_card.transform.position;
        squadObj.transform.localScale = tmp_card.transform.localScale;

        PlayerTeam player = squadObj.GetComponent <PlayerTeam>();

        Assert.IsTrue(player != null);
        // squad stuff
        player.team = team;
        // remove from deck
        cards_to_play_count--;
        UpdateText();

        // destroy card instance
        Destroy(tmp_card);
    }
Exemplo n.º 27
0
        private void Setting_Backup()
        {
            var sw = Stopwatch.StartNew();

            _backupTimer = new WatchTimer(() =>
            {
                if (sw.Elapsed.TotalMinutes > 30)
                {
                    sw.Restart();

                    try
                    {
                        Backup.Instance.Run();
                        this.GarbageCollect();
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                    }
                }
            });
            _backupTimer.Start(new TimeSpan(0, 0, 30));
        }
Exemplo n.º 28
0
        protected override void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }
            _disposed = true;

            if (disposing)
            {
                if (_watchTimer != null)
                {
                    _watchTimer.Dispose();
                    _watchTimer = null;
                }

                if (_updateTimer != null)
                {
                    _updateTimer.Dispose();
                    _updateTimer = null;
                }
            }
        }
Exemplo n.º 29
0
            protected override void Dispose(bool isDisposing)
            {
                if (_isDisposed)
                {
                    return;
                }
                _isDisposed = true;

                if (isDisposing)
                {
                    if (_watchTimer != null)
                    {
                        _watchTimer.Dispose();
                        _watchTimer = null;
                    }

                    if (_samManager != null)
                    {
                        _samManager.Dispose();
                        _samManager = null;
                    }
                }
            }
Exemplo n.º 30
0
            public static readonly int SectorSize = 1024 * 256; // 256 KB

            public BlocksManager(string configPath, string blocksPath, BufferManager bufferManager)
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    const FileOptions FileFlagNoBuffering = (FileOptions)0x20000000;
                    _fileStream = new FileStream(blocksPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, SectorSize, FileFlagNoBuffering);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    _fileStream = new FileStream(blocksPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, SectorSize);
                }
                else
                {
                    throw new NotSupportedException();
                }

                _bufferManager     = bufferManager;
                _sectorsManager    = new SectorsManager(_bufferManager);
                _protectionManager = new ProtectionManager();

                _settings = new Settings(configPath);

                _updateTimer = new WatchTimer(this.UpdateTimer);
            }
Exemplo n.º 31
0
        private void Setting_Backup()
        {
            var sw = Stopwatch.StartNew();

            _backupTimer = new WatchTimer(() =>
            {
                if ((!Process.GetCurrentProcess().IsActivated() && sw.Elapsed.TotalMinutes > 30) ||
                    sw.Elapsed.TotalHours > 3)
                {
                    sw.Restart();

                    try
                    {
                        Backup.Instance.Run();
                        this.GarbageCollect();
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                    }
                }
            });
            _backupTimer.Start(new TimeSpan(0, 0, 30));
        }
 public PacketControlManager()
 {
     _refreshTimer = new WatchTimer(this.RefreshTimer, new TimeSpan(0, 0, 30));
 }
Exemplo n.º 33
0
        //#endif
        public ConnectionsManager(ClientManager clientManager, ServerManager serverManager, CacheManager cacheManager, BufferManager bufferManager)
        {
            _clientManager = clientManager;
            _serverManager = serverManager;
            _cacheManager = cacheManager;
            _bufferManager = bufferManager;

            _settings = new Settings();

            _routeTable = new Kademlia<Node>(256, 20);

            _connectionManagers = new LockedList<ConnectionManager>();

            _packetControlManager = new PacketControlManager();
            _packetControlManager.GetLockNodesEvent = (object sender) =>
            {
                lock (_thisLock)
                {
                    return _connectionManagers.Select(n => n.Node).ToArray();
                }
            };

            _creatingNodes = new LockedList<Node>();

            _waitingNodes = new VolatileHashSet<Node>(new TimeSpan(0, 0, 30));
            _removeNodes = new VolatileHashSet<Node>(new TimeSpan(0, 30, 0));

            _succeededUris = new VolatileHashSet<string>(new TimeSpan(1, 0, 0));

            _downloadBlocks = new VolatileHashSet<Key>(new TimeSpan(0, 30, 0));

            _pushBroadcastMetadatasRequestList = new VolatileHashSet<string>(new TimeSpan(0, 3, 0));
            _pushUnicastMetadatasRequestList = new VolatileHashSet<string>(new TimeSpan(0, 3, 0));
            _pushMulticastMetadatasRequestList = new VolatileHashSet<Tag>(new TimeSpan(0, 3, 0));

            _relayBlocks = new VolatileHashSet<Key>(new TimeSpan(0, 30, 0));

            _refreshTimer = new WatchTimer(this.RefreshTimer, new TimeSpan(0, 0, 5));
            _mediateTimer = new WatchTimer(this.MediateTimer, new TimeSpan(0, 1, 0));
            _reduceTimer = new WatchTimer(this.ReduceTimer, new TimeSpan(0, 3, 0));
        }
Exemplo n.º 34
0
        protected override void Dispose(bool disposing)
        {
            if (_disposed) return;
            _disposed = true;

            if (disposing)
            {
                _blockUploadedEventQueue.Dispose();

                if (_refreshTimer != null)
                {
                    try
                    {
                        _refreshTimer.Dispose();
                    }
                    catch (Exception)
                    {

                    }

                    _refreshTimer = null;
                }

                if (_mediateTimer != null)
                {
                    try
                    {
                        _mediateTimer.Dispose();
                    }
                    catch (Exception)
                    {

                    }

                    _mediateTimer = null;
                }

                if (_reduceTimer != null)
                {
                    try
                    {
                        _reduceTimer.Dispose();
                    }
                    catch (Exception)
                    {

                    }

                    _reduceTimer = null;
                }

                if (_packetControlManager != null)
                {
                    try
                    {
                        _packetControlManager.Dispose();
                    }
                    catch (Exception)
                    {

                    }

                    _packetControlManager = null;
                }

                if (_bandwidthLimit != null)
                {
                    try
                    {
                        _bandwidthLimit.Dispose();
                    }
                    catch (Exception)
                    {

                    }

                    _bandwidthLimit = null;
                }
            }
        }
Exemplo n.º 35
0
        public void Run()
        {
            // カレントディレクトリをexeと同じディレクトリパスへ変更。
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));

            // ハンドルしていない例外をログ出力させる。
            AppDomain.CurrentDomain.UnhandledException += this.Program_UnhandledException;
            Thread.GetDomain().UnhandledException += this.Program_UnhandledException;

#if !DEBUG
            // Tomlファイルを読み込み。
            DaemonConfig config = null;
            {
                // コマンドライン引数を解析。
                var options = CommandLine.Parser.Default.ParseArguments <AmoebaDaemonOptions>(Environment.GetCommandLineArgs())
                              .MapResult(
                    (AmoebaDaemonOptions x) => x,
                    errs => null);
                if (options == null)
                {
                    return;
                }

                if (File.Exists(options.ConfigFilePath))
                {
                    var tomlSettings = TomlSettings.Create(builder => builder
                                                           .ConfigureType <Version>(type => type
                                                                                    .WithConversionFor <TomlString>(convert => convert
                                                                                                                    .ToToml(tt => tt.ToString())
                                                                                                                    .FromToml(ft => Version.Parse(ft.Value)))));

                    config = Toml.ReadFile <DaemonConfig>(options.ConfigFilePath, tomlSettings);
                }

                if (config == null)
                {
                    return;
                }
            }
#else
            DaemonConfig config = null;
            {
                var basePath = Environment.GetCommandLineArgs()[0];
                if (!Directory.Exists(basePath))
                {
                    Directory.CreateDirectory(basePath);
                }

                config = new DaemonConfig(
                    new Version(0, 0, 0),
                    new DaemonConfig.CacheConfig(Path.Combine(basePath, "Cache.blocks")),
                    new DaemonConfig.PathsConfig(
                        Path.Combine(basePath, "Temp"),
                        Path.Combine(basePath, "Config/Service"),
                        Path.Combine(basePath, "Log")));
            }
#endif

            // 既定のフォルダを作成する。
            {
                foreach (var propertyInfo in typeof(DaemonConfig.PathsConfig).GetProperties())
                {
                    string path = propertyInfo.GetValue(config.Paths) as string;
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                }
            }

            // Tempフォルダを環境変数に登録。
            {
                // Tempフォルダ内を掃除。
                try
                {
                    foreach (string path in Directory.GetFiles(config.Paths.TempDirectoryPath, "*", SearchOption.AllDirectories))
                    {
                        File.Delete(path);
                    }

                    foreach (string path in Directory.GetDirectories(config.Paths.TempDirectoryPath, "*", SearchOption.AllDirectories))
                    {
                        Directory.Delete(path, true);
                    }
                }
                catch (Exception)
                {
                }

                Environment.SetEnvironmentVariable("TMP", Path.GetFullPath(config.Paths.TempDirectoryPath), EnvironmentVariableTarget.Process);
                Environment.SetEnvironmentVariable("TEMP", Path.GetFullPath(config.Paths.TempDirectoryPath), EnvironmentVariableTarget.Process);
            }

            // ログファイルを設定する。
            this.Setting_Log(config);

            // 30分置きにLOHの圧縮を実行する。
            _timer = new WatchTimer(() =>
            {
                GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
                GC.Collect();
            });
            _timer.Start(new TimeSpan(0, 30, 0));

            Socket targetSocket = null;

            // サービス開始。
            try
            {
#if !DEBUG
                for (int i = 50000; i < 60000; i++)
                {
                    try
                    {
                        using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                        {
                            var endpoint = new IPEndPoint(IPAddress.Loopback, i);
                            socket.Bind(endpoint);
                            socket.Listen(1);

                            Console.Out.WriteLine(endpoint.ToString());

                            var sw = Stopwatch.StartNew();

                            for (; ;)
                            {
                                if (socket.Poll(0, SelectMode.SelectRead))
                                {
                                    break;
                                }
                                if (sw.Elapsed.TotalSeconds > 30)
                                {
                                    return;
                                }

                                Thread.Sleep(1000);
                            }

                            targetSocket = socket.Accept();

                            break;
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
#else
                try
                {
                    using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                    {
                        var endpoint = new IPEndPoint(IPAddress.Loopback, 60000);
                        socket.Bind(endpoint);
                        socket.Listen(1);

                        Console.Out.WriteLine(endpoint.ToString());

                        var sw = Stopwatch.StartNew();

                        for (; ;)
                        {
                            if (socket.Poll(0, SelectMode.SelectRead))
                            {
                                break;
                            }
                            if (sw.Elapsed.TotalSeconds > 30)
                            {
                                return;
                            }

                            Thread.Sleep(1000);
                        }

                        targetSocket = socket.Accept();
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
#endif

                using (var bufferManager = new BufferManager(1024 * 1024 * 1024))
                    using (var serviceManager = new ServiceManager(config.Paths.ConfigDirectoryPath, config.Cache.BlocksFilePath, bufferManager))
                        using (var daemonManager = new AmoebaDaemonManager <ServiceManager>(targetSocket, serviceManager, bufferManager))
                        {
                            try
                            {
                                daemonManager.Watch();
                            }
                            catch (Exception e)
                            {
                                Log.Error(e);

                                Console.WriteLine(e.Message);
                            }
                        }
            }
            catch (Exception e)
            {
                Log.Error(e);

                Console.WriteLine(e.Message);
            }
            finally
            {
                if (targetSocket != null)
                {
                    targetSocket.Dispose();
                }
            }
        }
        protected override void Dispose(bool disposing)
        {
            if (_disposed) return;
            _disposed = true;

            if (disposing)
            {
                if (_watchTimer != null)
                {
                    try
                    {
                        _watchTimer.Dispose();
                    }
                    catch (Exception)
                    {

                    }

                    _watchTimer = null;
                }
            }
        }
Exemplo n.º 37
0
        private void Setting_CheckDiskSpace()
        {
            bool watchFlag = true;

            _checkDiskSpaceTimer = new WatchTimer(() =>
            {
                if (!watchFlag)
                {
                    return;
                }

                try
                {
                    var paths = new List <string>();
                    paths.Add(AmoebaEnvironment.Config.Cache.BlocksPath);

                    bool flag = false;

                    foreach (string path in paths)
                    {
                        var drive = new DriveInfo(Path.GetFullPath(path));

                        if (drive.AvailableFreeSpace < NetworkConverter.FromSizeString("256MB"))
                        {
                            flag |= true;
                            break;
                        }
                    }

                    if (_serviceManager.Report.Core.Cache.FreeSpace < NetworkConverter.FromSizeString("10GB"))
                    {
                        flag |= true;
                    }

                    if (!flag)
                    {
                        if (_serviceManager.State == ManagerState.Stop)
                        {
                            _serviceManager.Start();
                            Log.Information("Start");
                        }
                    }
                    else
                    {
                        if (_serviceManager.State == ManagerState.Start)
                        {
                            _serviceManager.Stop();
                            Log.Information("Stop");

                            watchFlag = false;

                            App.Current.Dispatcher.InvokeAsync(() =>
                            {
                                var viewModel       = new NoticeWindowViewModel(LanguagesManager.Instance.MainWindow_SpaceNotFound_Message);
                                viewModel.Callback += () => watchFlag = true;

                                _dialogService.Show(viewModel);
                            });
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            });
            _checkDiskSpaceTimer.Start(new TimeSpan(0, 0, 0), new TimeSpan(0, 3, 0));
        }
Exemplo n.º 38
0
        private void Setting_ChechUpdate()
        {
            _checkUpdateTimer = new WatchTimer(() =>
            {
                try
                {
                    var updateInfo = SettingsManager.Instance.UpdateInfo;
                    if (!updateInfo.IsEnabled)
                    {
                        return;
                    }

                    var store = _serviceManager.GetStore(updateInfo.Signature, CancellationToken.None).Result;
                    if (store == null)
                    {
                        return;
                    }

                    var updateBox = store.Value.Boxes.FirstOrDefault(n => n.Name == "Update")?.Boxes.FirstOrDefault(n => n.Name == "Windows");
                    if (updateBox == null)
                    {
                        return;
                    }

                    Seed targetSeed = null;

                    {
                        var map   = new Dictionary <Seed, Version>();
                        var regex = new Regex(@"Amoeba.+?((\d*)\.(\d*)\.(\d*)).*?\.zip", RegexOptions.Compiled);

                        foreach (var seed in updateBox.Seeds)
                        {
                            var match = regex.Match(seed.Name);
                            if (!match.Success)
                            {
                                continue;
                            }

                            var version = new Version(match.Groups[1].Value);
                            if (version <= AmoebaEnvironment.Version)
                            {
                                continue;
                            }

                            map.Add(seed, version);
                        }

                        if (map.Count > 0)
                        {
                            var sortedList = map.ToList();
                            sortedList.Sort((x, y) => y.Value.CompareTo(x.Value));

                            targetSeed = sortedList.First().Key;
                        }
                    }

                    if (targetSeed == null)
                    {
                        return;
                    }

                    string fullPath = Path.GetFullPath(Path.Combine(AmoebaEnvironment.Paths.UpdatePath, targetSeed.Name));
                    if (File.Exists(fullPath))
                    {
                        return;
                    }

                    var downloadItemInfo = new DownloadItemInfo(targetSeed, fullPath);
                    SettingsManager.Instance.DownloadItemInfos.Add(downloadItemInfo);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            });
            _checkUpdateTimer.Start(new TimeSpan(0, 0, 0), new TimeSpan(0, 3, 0));
        }