Exemplo n.º 1
0
 public static void Start()
 {
     if (Systemctl.IsEnabled(ServiceName1) == false)
     {
         Systemctl.Enable(ServiceName1);
     }
     if (Systemctl.IsActive(ServiceName1) == false)
     {
         Systemctl.Restart(ServiceName1);
     }
     if (Systemctl.IsEnabled(ServiceName2) == false)
     {
         Systemctl.Enable(ServiceName2);
     }
     if (Systemctl.IsActive(ServiceName2) == false)
     {
         Systemctl.Restart(ServiceName2);
     }
     if (Systemctl.IsEnabled(ServiceName3) == false)
     {
         Systemctl.Enable(ServiceName3);
     }
     if (Systemctl.IsActive(ServiceName3) == false)
     {
         Systemctl.Restart(ServiceName3);
     }
     ConsoleLogger.Log("[samba] start");
 }
Exemplo n.º 2
0
        private static bool SetUnitForTunnel(string remoteHost)
        {
            var lines = new List <string> {
                "[Unit]",
                "Description=ExtUnit, VpnConnection",
                "",
                "[Service]",
                $"ExecStart=/usr/bin/ssh -o Tunnel=ethernet -f -w 1:1 root@{remoteHost} true",
                "SuccessExitStatus=1 2 3 4 5 6 7 8 9 0",
                "RemainAfterExit=yes",
                "Type=oneshot",
                "",
                "[Install]",
                "WantedBy=antd.target"
            };
            var unitName = $"/mnt/cdrom/Units/antd.target.wants/antd-{remoteHost}-vpn.service";

            ConsoleLogger.Log(unitName);
            if (!File.Exists(unitName))
            {
                FileWithAcl.WriteAllLines(unitName, lines, "644", "root", "wheel");
                Systemctl.DaemonReload();
            }
            Systemctl.Restart($"antd-{remoteHost}-vpn.service");
            return(Systemctl.IsActive($"antd-{remoteHost}-vpn.service"));
        }
Exemplo n.º 3
0
        public void Setup()
        {
            if (Systemctl.IsEnabled("systemd-networkd.service") == false)
            {
                Systemctl.Enable("systemd-networkd.service");
            }
            if (Systemctl.IsActive("systemd-networkd.service") == false)
            {
                Systemctl.Start("systemd-networkd.service");
            }
            if (Systemctl.IsEnabled("systemd-resolved.service") == false)
            {
                Systemctl.Enable("systemd-resolved.service");
            }
            if (Systemctl.IsActive("systemd-resolved.service") == false)
            {
                Systemctl.Start("systemd-resolved.service");
            }

            _bash.Execute("ln -s /run/systemd/resolve/resolv.conf /etc/resolv.conf", false);

            if (!Directory.Exists(NetworkdFolder))
            {
                Directory.CreateDirectory(NetworkdFolder);
            }
        }
Exemplo n.º 4
0
        public void SyncClock(string ntpServer = "")
        {
            var launcher = new CommandLauncher();

            ApplyNtpdate();
            if (Systemctl.IsActive("ntpd"))
            {
                ApplyNtpd();
            }
            launcher.Launch("sync-clock");
        }
Exemplo n.º 5
0
 public void Start()
 {
     if (Systemctl.IsEnabled(ServiceName) == false)
     {
         Systemctl.Enable(ServiceName);
     }
     if (Systemctl.IsActive(ServiceName) == false)
     {
         Systemctl.Restart(ServiceName);
     }
     ConsoleLogger.Log("[kerberos] start");
 }
Exemplo n.º 6
0
        public static void Setup()
        {
            if (!Directory.Exists("/mnt/cdrom/Units"))
            {
                return;
            }
            if (!Directory.Exists("/mnt/cdrom/Units/antd.target.wants"))
            {
                return;
            }
            var edit = false;

            if (!File.Exists(Service01PreparePath))
            {
                FileWithAcl.WriteAllLines(Service01PreparePath, Service01Prepare(), "644", "root", "wheel");
                edit = true;
            }

            if (!File.Exists(Service02MountPath))
            {
                FileWithAcl.WriteAllLines(Service02MountPath, Service02Mount(), "644", "root", "wheel");
                edit = true;
            }

            if (!File.Exists(Service03LauncherPath))
            {
                FileWithAcl.WriteAllLines(Service03LauncherPath, Service03Launcher(), "644", "root", "wheel");
                edit = true;
            }

            if (edit)
            {
                Systemctl.DaemonReload();

                if (Systemctl.IsActive(Service01PrepareUnit) == false)
                {
                    Systemctl.Restart(Service01PrepareUnit);
                }

                if (Systemctl.IsActive(Service02MountUnit) == false)
                {
                    Systemctl.Restart(Service02MountUnit);
                }

                if (Systemctl.IsActive(Service03LauncherUnit) == false)
                {
                    Systemctl.Restart(Service03LauncherUnit);
                }
            }
        }
Exemplo n.º 7
0
        public void StopService()
        {
            var svcs = HostParametersConfiguration.Conf.ServicesStop;

            foreach (var svc in svcs)
            {
                if (Systemctl.IsEnabled(svc))
                {
                    Systemctl.Disable(svc);
                }
                if (Systemctl.IsActive(svc))
                {
                    Systemctl.Stop(svc);
                }
            }
        }
Exemplo n.º 8
0
        public void StartService()
        {
            var svcs = HostParametersConfiguration.Conf.ServicesStart;

            foreach (var svc in svcs)
            {
                if (Systemctl.IsEnabled(svc) == false)
                {
                    Systemctl.Enable(svc);
                }
                if (Systemctl.IsActive(svc) == false)
                {
                    Systemctl.Start(svc);
                }
            }
        }
Exemplo n.º 9
0
        private void SaveKeepalived(string publicIp, List <NodeModel> nodes)
        {
            ConsoleLogger.Log("[cluster] init keepalived");
            const string keepalivedService = "keepalived.service";

            if (Systemctl.IsActive(keepalivedService))
            {
                ConsoleLogger.Log("[cluster] stop service");
                Systemctl.Stop(keepalivedService);
            }
            ConsoleLogger.Log("[cluster] set configuration file");
            var clusterInfo = ClusterConfiguration.GetClusterInfo();
            var lines       = new List <string> {
                "vrrp_script chk_haproxy {",
                "    script \"killall -0 haproxy\"",
                "    interval 2",
                "    weight 2",
                "}",
                "",
                "vrrp_instance RH_INT {",
                $"    interface {clusterInfo.NetworkInterface}",
                "    state MASTER",
                "    virtual_router_id 51",
                $"    priority {clusterInfo.Priority}",
                "    virtual_ipaddress {",
                $"        {clusterInfo.VirtualIpAddress}",
                "    }",
                "    track_script {",
                "        chk_haproxy",
                "    }",
                "}",
            };

            FileWithAcl.WriteAllLines(KeepalivedFileOutput, lines);
            //if(Systemctl.IsEnabled(keepalivedService) == false) {
            //    Systemctl.Enable(keepalivedService);
            //    ConsoleLogger.Log("[cluster] keepalived enabled");
            //}
            //if(Systemctl.IsActive(keepalivedService) == false) {
            //    Systemctl.Restart(keepalivedService);
            //    ConsoleLogger.Log("[cluster] keepalived restarted");
            //}
            Systemctl.Enable(keepalivedService);
            ConsoleLogger.Log("[cluster] keepalived enabled");
            Systemctl.Restart(keepalivedService);
            ConsoleLogger.Log("[cluster] keepalived restarted");
        }
Exemplo n.º 10
0
        public AppsManagementModule()
        {
            Get["/apps/management"] = x => {
                var appsConfiguration = new AppsConfiguration();

                var model = new PageAppsManagementModel {
                    AppList = appsConfiguration.Get().Apps
                };
                return(JsonConvert.SerializeObject(model));
            };

            Post["/apps/setup"] = x => {
                string app = Request.Form.AppName;
                if (string.IsNullOrEmpty(app))
                {
                    return(HttpStatusCode.InternalServerError);
                }
                var appsManagement = new AppsManagement();
                appsManagement.Setup(app);
                return(HttpStatusCode.OK);
            };

            Get["/apps/status/{unit}"] = x => {
                string unitName = x.unit;
                var    status   = Systemctl.Status(unitName);
                return(Response.AsJson(status));
            };

            Get["/apps/active/{unit}"] = x => {
                string unitName = x.unit;
                var    status   = Systemctl.IsActive(unitName);
                return(Response.AsJson(status ? "active" : "inactive"));
            };

            Post["/apps/restart"] = x => {
                string unitName = Request.Form.Name;
                Systemctl.Restart(unitName);
                return(HttpStatusCode.OK);
            };

            Post["/apps/stop"] = x => {
                string unitName = Request.Form.Name;
                Systemctl.Stop(unitName);
                return(HttpStatusCode.OK);
            };
        }
Exemplo n.º 11
0
        public static void Setup()
        {
            var edit = false;

            if (!File.Exists(Service01PreparePath))
            {
                File.WriteAllLines(Service01PreparePath, Service01Prepare());
                edit = true;
            }

            if (!File.Exists(Service02MountPath))
            {
                File.WriteAllLines(Service02MountPath, Service02Mount());
                edit = true;
            }

            if (!File.Exists(Service03LauncherPath))
            {
                File.WriteAllLines(Service03LauncherPath, Service03Launcher());
                edit = true;
            }

            if (edit)
            {
                Systemctl.DaemonReload();

                if (Systemctl.IsActive(Service01PrepareUnit) == false)
                {
                    Systemctl.Restart(Service01PrepareUnit);
                }

                if (Systemctl.IsActive(Service02MountUnit) == false)
                {
                    Systemctl.Restart(Service02MountUnit);
                }

                if (Systemctl.IsActive(Service03LauncherUnit) == false)
                {
                    Systemctl.Restart(Service03LauncherUnit);
                }
            }
        }
Exemplo n.º 12
0
        private void SetInterface(NetworkInterface configuration, NetworkInterfaceConfiguration interfaceConfiguration, NetworkGatewayConfiguration gatewayConfiguration)
        {
            if (interfaceConfiguration == null)
            {
                return;
            }

            var deviceName = configuration.Device;

            var nAt = NetworkAdapterType.Other;

            if (Network2Configuration.InterfacePhysical.Contains(deviceName))
            {
                nAt = NetworkAdapterType.Physical;
            }
            else if (Network2Configuration.InterfaceBridge.Contains(deviceName))
            {
                nAt = NetworkAdapterType.Bridge;
            }
            else if (Network2Configuration.InterfaceBond.Contains(deviceName))
            {
                nAt = NetworkAdapterType.Bond;
            }
            else if (Network2Configuration.InterfaceVirtual.Contains(deviceName))
            {
                nAt = NetworkAdapterType.Virtual;
            }

            switch (nAt)
            {
            case NetworkAdapterType.Physical:
                break;

            case NetworkAdapterType.Virtual:
                break;

            case NetworkAdapterType.Bond:
                CommandLauncher.Launch("bond-set", new Dictionary <string, string> {
                    { "$bond", deviceName }
                });
                foreach (var nif in interfaceConfiguration.ChildrenIf)
                {
                    CommandLauncher.Launch("bond-add-if", new Dictionary <string, string> {
                        { "$bond", deviceName }, { "$net_if", nif }
                    });
                    CommandLauncher.Launch("ip4-flush-configuration", new Dictionary <string, string> {
                        { "$net_if", nif }
                    });
                    CommandLauncher.Launch("ip4-enable-if", new Dictionary <string, string> {
                        { "$net_if", nif }
                    });
                }
                break;

            case NetworkAdapterType.Bridge:
                CommandLauncher.Launch("brctl-add", new Dictionary <string, string> {
                    { "$bridge", deviceName }
                });
                foreach (var nif in interfaceConfiguration.ChildrenIf)
                {
                    CommandLauncher.Launch("brctl-add-if", new Dictionary <string, string> {
                        { "$bridge", deviceName }, { "$net_if", nif }
                    });
                    CommandLauncher.Launch("ip4-flush-configuration", new Dictionary <string, string> {
                        { "$net_if", nif }
                    });
                    CommandLauncher.Launch("ip4-enable-if", new Dictionary <string, string> {
                        { "$net_if", nif }
                    });
                }
                break;

            case NetworkAdapterType.Other:
                return;
            }

            CommandLauncher.Launch("ip4-set-mtu", new Dictionary <string, string> {
                { "$net_if", deviceName }, { "$mtu", "6000" }
            });
            CommandLauncher.Launch("ip4-set-txqueuelen", new Dictionary <string, string> {
                { "$net_if", deviceName }, { "$txqueuelen", "10000" }
            });
            CommandLauncher.Launch("ip4-promisc-on", new Dictionary <string, string> {
                { "$net_if", deviceName }
            });

            switch (interfaceConfiguration.Mode)
            {
            case NetworkInterfaceMode.Null:
                return;

            case NetworkInterfaceMode.Static:
                var networkdIsActive = Systemctl.IsActive("systemd-networkd");
                if (networkdIsActive)
                {
                    Systemctl.Stop("systemd-networkd");
                }
                CommandLauncher.Launch("dhcpcd-killall");
                CommandLauncher.Launch("ip4-flush-configuration", new Dictionary <string, string> {
                    { "$net_if", deviceName }
                });
                CommandLauncher.Launch("ip4-add-addr", new Dictionary <string, string> {
                    { "$net_if", deviceName },
                    { "$address", interfaceConfiguration.Ip },
                    { "$range", interfaceConfiguration.Subnet }
                });
                if (networkdIsActive)
                {
                    Systemctl.Start("systemd-networkd");
                }
                break;

            case NetworkInterfaceMode.Dynamic:
                CommandLauncher.Launch("dhcpcd", new Dictionary <string, string> {
                    { "$net_if", deviceName }
                });
                break;

            default:
                return;
            }

            switch (configuration.Status)
            {
            case NetworkInterfaceStatus.Down:
                CommandLauncher.Launch("ip4-disable-if", new Dictionary <string, string> {
                    { "$net_if", deviceName }
                });
                return;

            case NetworkInterfaceStatus.Up:
                CommandLauncher.Launch("ip4-enable-if", new Dictionary <string, string> {
                    { "$net_if", deviceName }
                });
                ConsoleLogger.Log($"[network] interface '{deviceName}' configured");
                break;

            default:
                CommandLauncher.Launch("ip4-disable-if", new Dictionary <string, string> {
                    { "$net_if", deviceName }
                });
                return;
            }

            if (gatewayConfiguration == null)
            {
                return;
            }
            CommandLauncher.Launch("ip4-add-route", new Dictionary <string, string> {
                { "$net_if", deviceName }, { "$ip_address", "default" }, { "$gateway", gatewayConfiguration.GatewayAddress }
            });
        }
Exemplo n.º 13
0
        private static void ManagedProcedures()
        {
            Logger.Info("[config] managed procedures");
            if (!Parameter.IsUnix)
            {
                return;
            }

            #region [    Samba    ]
            if (SambaConfiguration.IsActive())
            {
                SambaConfiguration.Set();
            }
            #endregion

            #region [    Syslog    ]
            if (SyslogNgConfiguration.IsActive())
            {
                SyslogNgConfiguration.Set();
            }
            #endregion

            #region [    Storage    ]
            foreach (var pool in Zpool.ImportList().ToList())
            {
                if (string.IsNullOrEmpty(pool))
                {
                    continue;
                }
                Logger.Info($"pool {pool} imported");
                Zpool.Import(pool);
            }
            Logger.Info("storage ready");
            #endregion

            #region [    Scheduler    ]
            Timers.Setup();
            Timers.Import();
            Timers.Export();
            foreach (var zp in Zpool.List())
            {
                Timers.Create(zp.Name.ToLower() + "snap", "hourly", $"/sbin/zfs snap -r {zp.Name}@${{TTDATE}}");
            }
            Timers.StartAll();
            new SnapshotCleanup().Start(new TimeSpan(2, 00, 00));
            new SyncTime().Start(new TimeSpan(0, 42, 00));
            new RemoveUnusedModules().Start(new TimeSpan(2, 15, 00));
            Logger.Info("scheduled events ready");
            #endregion

            #region [    Acl    ]
            if (AclConfiguration.IsActive())
            {
                AclConfiguration.Set();
                AclConfiguration.ScriptSetup();
            }
            #endregion

            #region [    Sync    ]
            if (GlusterConfiguration.IsActive())
            {
                GlusterConfiguration.Set();
            }
            if (RsyncConfiguration.IsActive())
            {
                RsyncConfiguration.Set();
            }
            #endregion

            #region [    SyncMachine    ]
            if (SyncMachineConfiguration.IsActive())
            {
                SyncMachineConfiguration.Set();
            }
            #endregion

            #region [    C A    ]
            if (CaConfiguration.IsActive())
            {
                CaConfiguration.Set();
            }
            #endregion

            #region [    Apps    ]
            AppTarget.Setup();
            var apps = AppsConfiguration.Get().Apps;
            foreach (var app in apps)
            {
                var units = app.UnitLauncher;
                foreach (var unit in units)
                {
                    if (Systemctl.IsActive(unit) == false)
                    {
                        Systemctl.Restart(unit);
                    }
                }
            }
            //AppTarget.StartAll();
            Logger.Info("apps ready");
            #endregion
        }
Exemplo n.º 14
0
        public static void ApplyInterfaceSetting(NetworkInterfaceConfigurationModel model)
        {
            var netif = model.Interface;

            switch (model.Type)
            {
            case NetworkAdapterType.Physical:
                break;

            case NetworkAdapterType.Virtual:
                break;

            case NetworkAdapterType.Bond:
                CommandLauncher.Launch("bond-set", new Dictionary <string, string> {
                    { "$bond", netif }
                });
                foreach (var nif in model.InterfaceList)
                {
                    CommandLauncher.Launch("bond-add-if", new Dictionary <string, string> {
                        { "$bond", netif }, { "$net_if", nif }
                    });
                }
                break;

            case NetworkAdapterType.Bridge:
                CommandLauncher.Launch("brctl-add", new Dictionary <string, string> {
                    { "$bridge", netif }
                });
                foreach (var nif in model.InterfaceList)
                {
                    CommandLauncher.Launch("brctl-add-if", new Dictionary <string, string> {
                        { "$bridge", netif }, { "$net_if", nif }
                    });
                }
                break;

            case NetworkAdapterType.Other:
                break;
            }

            switch (model.Mode)
            {
            case NetworkInterfaceMode.Null:
                return;

            case NetworkInterfaceMode.Static:
                var networkdIsActive = Systemctl.IsActive("systemd-networkd");
                if (networkdIsActive)
                {
                    Systemctl.Stop("systemd-networkd");
                }
                CommandLauncher.Launch("dhcpcd-killall");
                CommandLauncher.Launch("ip4-flush-configuration", new Dictionary <string, string> {
                    { "$net_if", netif }
                });
                CommandLauncher.Launch("ip4-add-addr", new Dictionary <string, string> {
                    { "$net_if", netif },
                    { "$address", model.StaticAddress },
                    { "$range", model.StaticRange }
                });
                if (networkdIsActive)
                {
                    Systemctl.Start("systemd-networkd");
                }
                break;

            case NetworkInterfaceMode.Dynamic:
                CommandLauncher.Launch("dhcpcd", new Dictionary <string, string> {
                    { "$net_if", netif }
                });
                break;

            default:
                return;
            }
            CommandLauncher.Launch("ip4-set-mtu", new Dictionary <string, string> {
                { "$net_if", netif }, { "$mtu", model.Mtu }
            });
            CommandLauncher.Launch("ip4-set-txqueuelen", new Dictionary <string, string> {
                { "$net_if", netif }, { "$txqueuelen", model.Txqueuelen }
            });

            if (!string.IsNullOrEmpty(model.Route) && !string.IsNullOrEmpty(model.Gateway))
            {
                CommandLauncher.Launch("ip4-add-route", new Dictionary <string, string> {
                    { "$net_if", netif }, { "$gateway", model.Gateway }, { "$ip_address", model.Route }
                });
            }
            var status = model.Status;

            switch (status)
            {
            case NetworkInterfaceStatus.Down:
                CommandLauncher.Launch("ip4-disable-if", new Dictionary <string, string> {
                    { "$net_if", netif }
                });
                break;

            case NetworkInterfaceStatus.Up:
                CommandLauncher.Launch("ip4-enable-if", new Dictionary <string, string> {
                    { "$net_if", netif }
                });
                ConsoleLogger.Log($"[network] interface '{model.Interface}' configured");
                break;

            default:
                CommandLauncher.Launch("ip4-disable-if", new Dictionary <string, string> {
                    { "$net_if", netif }
                });
                break;
            }
        }
Exemplo n.º 15
0
        private static void Main()
        {
            ConsoleLogger.Log("[boot step] starting antd");
            var startTime = DateTime.Now;

            ConsoleLogger.Log("[boot step] core procedures");

            #region [    os Rw    ]
            Bash.Execute("mount -o remount,rw /", false);
            Bash.Execute("mount -o remount,rw /mnt/cdrom", false);
            #endregion

            #region [    Remove Limits    ]
            const string limitsFile = "/etc/security/limits.conf";
            if (File.Exists(limitsFile))
            {
                if (!File.ReadAllText(limitsFile).Contains("root - nofile 1024000"))
                {
                    FileWithAcl.AppendAllLines(limitsFile, new[] { "root - nofile 1024000" }, "644", "root", "wheel");
                }
            }
            Bash.Execute("ulimit -n 1024000", false);
            #endregion

            #region [    Overlay Watcher    ]
            if (Directory.Exists(Parameter.Overlay))
            {
                new OverlayWatcher().StartWatching();
                ConsoleLogger.Log("overlay watcher ready");
            }
            #endregion

            #region [    Working Directories    ]
            Directory.CreateDirectory(Parameter.AntdCfg);
            Directory.CreateDirectory(Parameter.AntdCfgServices);
            Directory.CreateDirectory(Parameter.AntdCfgNetwork);
            Network2Configuration.CreateWorkingDirectories();
            Directory.CreateDirectory(Parameter.AntdCfgParameters);
            Directory.CreateDirectory(Parameter.AntdCfgCluster);
            Directory.CreateDirectory($"{Parameter.AntdCfgServices}/acls");
            Directory.CreateDirectory($"{Parameter.AntdCfgServices}/acls/template");
            Directory.CreateDirectory(Parameter.RepoConfig);
            Directory.CreateDirectory(Parameter.RepoDirs);
            Directory.CreateDirectory(Parameter.AnthillaUnits);
            Directory.CreateDirectory(Parameter.TimerUnits);
            Directory.CreateDirectory(Parameter.AntdCfgVfs);
            Directory.CreateDirectory(Parameter.AntdCfgRssdp);
            ConsoleLogger.Log("working directories created");
            MountManagement.WorkingDirectories();
            ConsoleLogger.Log("working directories mounted");
            #endregion

            #region [    Mounts    ]
            if (MountHelper.IsAlreadyMounted("/mnt/cdrom/Kernel/active-firmware", "/lib64/firmware") == false)
            {
                Bash.Execute("mount /mnt/cdrom/Kernel/active-firmware /lib64/firmware", false);
            }
            var kernelRelease = Bash.Execute("uname -r").Trim();
            var linkedRelease = Bash.Execute("file /mnt/cdrom/Kernel/active-modules").Trim();
            if (MountHelper.IsAlreadyMounted("/mnt/cdrom/Kernel/active-modules") == false &&
                linkedRelease.Contains(kernelRelease))
            {
                var moduleDir = $"/lib64/modules/{kernelRelease}/";
                DirectoryWithAcl.CreateDirectory(moduleDir);
                Bash.Execute($"mount /mnt/cdrom/Kernel/active-modules {moduleDir}", false);
            }
            Bash.Execute("systemctl restart systemd-modules-load.service", false);
            MountManagement.AllDirectories();
            ConsoleLogger.Log("mounts ready");
            #endregion

            #region [    Check Units Location    ]
            var anthillaUnits = Directory.EnumerateFiles(Parameter.AnthillaUnits, "*.*", SearchOption.TopDirectoryOnly);
            if (!anthillaUnits.Any())
            {
                var antdUnits = Directory.EnumerateFiles(Parameter.AntdUnits, "*.*", SearchOption.TopDirectoryOnly);
                foreach (var unit in antdUnits)
                {
                    var trueUnit = unit.Replace(Parameter.AntdUnits, Parameter.AnthillaUnits);
                    if (!File.Exists(trueUnit))
                    {
                        File.Copy(unit, trueUnit);
                    }
                    File.Delete(unit);
                    Bash.Execute($"ln -s {trueUnit} {unit}");
                }
                var appsUnits = Directory.EnumerateFiles(Parameter.AppsUnits, "*.*", SearchOption.TopDirectoryOnly);
                foreach (var unit in appsUnits)
                {
                    var trueUnit = unit.Replace(Parameter.AntdUnits, Parameter.AnthillaUnits);
                    if (!File.Exists(trueUnit))
                    {
                        File.Copy(unit, trueUnit);
                    }
                    File.Delete(unit);
                    Bash.Execute($"ln -s {trueUnit} {unit}");
                }
                var applicativeUnits = Directory.EnumerateFiles(Parameter.ApplicativeUnits, "*.*", SearchOption.TopDirectoryOnly);
                foreach (var unit in applicativeUnits)
                {
                    var trueUnit = unit.Replace(Parameter.AntdUnits, Parameter.AnthillaUnits);
                    if (!File.Exists(trueUnit))
                    {
                        File.Copy(unit, trueUnit);
                    }
                    File.Delete(unit);
                    Bash.Execute($"ln -s {trueUnit} {unit}");
                }
            }
            anthillaUnits = Directory.EnumerateFiles(Parameter.AnthillaUnits, "*.*", SearchOption.TopDirectoryOnly).ToList();
            if (!anthillaUnits.Any())
            {
                foreach (var unit in anthillaUnits)
                {
                    Bash.Execute($"chown root:wheel {unit}");
                    Bash.Execute($"chmod 644 {unit}");
                }
            }
            ConsoleLogger.Log("[check] units integrity");
            #endregion

            #region [    Application Keys    ]
            var ak  = new AsymmetricKeys(Parameter.AntdCfgKeys, KeyName);
            var pub = ak.PublicKey;
            #endregion

            #region [    Secret    ]
            if (!File.Exists(Parameter.AntdCfgSecret))
            {
                FileWithAcl.WriteAllText(Parameter.AntdCfgSecret, Secret.Gen(), "644", "root", "wheel");
            }

            if (string.IsNullOrEmpty(File.ReadAllText(Parameter.AntdCfgSecret)))
            {
                FileWithAcl.WriteAllText(Parameter.AntdCfgSecret, Secret.Gen(), "644", "root", "wheel");
            }
            #endregion

            #region [    License Management    ]
            var appconfig = new AppConfiguration().Get();
            ConsoleLogger.Log($"[cloud] {appconfig.CloudAddress}");
            try {
                var machineIds = Machine.MachineIds.Get;
                ConsoleLogger.Log($"[machineid] {machineIds.PartNumber}");
                ConsoleLogger.Log($"[machineid] {machineIds.SerialNumber}");
                ConsoleLogger.Log($"[machineid] {machineIds.MachineUid}");
                var licenseManagement = new LicenseManagement();
                licenseManagement.Download("Antd", machineIds, pub);
                var licenseStatus = licenseManagement.Check("Antd", machineIds, pub);
                ConsoleLogger.Log(licenseStatus == null
                    ? "[license] license results null"
                    : $"[license] {licenseStatus.Status} - {licenseStatus.Message}");
            }
            catch (Exception ex) {
                ConsoleLogger.Warn(ex.Message);
            }
            #endregion

            #region [    JournalD    ]
            if (JournaldConfiguration.IsActive())
            {
                JournaldConfiguration.Set();
            }
            #endregion

            #region [    Import Existing Configuration    ]

            Network2Configuration.SetWorkingDirectories();

            #region import host2model
            var tmpHost  = HostConfiguration.Host;
            var varsFile = Host2Configuration.FilePath;
            var vars     = new Host2Model {
                HostName              = tmpHost.HostName.StoredValues.FirstOrDefault().Value,
                HostChassis           = tmpHost.HostChassis.StoredValues.FirstOrDefault().Value,
                HostDeployment        = tmpHost.HostDeployment.StoredValues.FirstOrDefault().Value,
                HostLocation          = tmpHost.HostLocation.StoredValues.FirstOrDefault().Value,
                InternalDomainPrimary = tmpHost.InternalDomain,
                ExternalDomainPrimary = tmpHost.ExternalDomain,
                InternalHostIpPrimary = "",
                ExternalHostIpPrimary = "",
                Timezone              = tmpHost.Timezone.StoredValues.FirstOrDefault().Value,
                NtpdateServer         = tmpHost.NtpdateServer.StoredValues.FirstOrDefault().Value,
                MachineUid            = Machine.MachineIds.Get.MachineUid,
                Cloud = Parameter.Cloud
            };

            if (File.Exists(HostConfiguration.FilePath))
            {
                if (!File.Exists(varsFile))
                {
                    ConsoleLogger.Log("[data import] host configuration");
                    Host2Configuration.Export(vars);
                }
                else
                {
                    if (string.IsNullOrEmpty(File.ReadAllText(varsFile)))
                    {
                        ConsoleLogger.Log("[data import] host configuration");
                        Host2Configuration.Export(vars);
                    }
                }
            }
            #endregion

            #region import network2model
            var tmpNet   = NetworkConfiguration.Get();
            var tmpHost2 = Host2Configuration.Host;
            var niflist  = new List <NetworkInterface>();
            foreach (var cif in tmpNet.Interfaces)
            {
                ConsoleLogger.Log($"[data import] network configuration for '{cif.Interface}'");
                var broadcast = "";
                try {
                    broadcast = Cidr.CalcNetwork(cif.StaticAddress, cif.StaticRange).Broadcast.ToString();
                }
                catch (Exception ex) {
                    ConsoleLogger.Error($"[data import] {ex.Message}");
                }
                var hostname             = $"{vars.HostName}{NetworkInterfaceType.Internal}.{vars.InternalDomainPrimary}";
                var subnet               = tmpHost2.InternalNetPrimaryBits;
                var index                = Network2Configuration.InterfaceConfigurationList.Count(_ => _.Type == NetworkInterfaceType.Internal);
                var networkConfiguration = new NetworkInterfaceConfiguration {
                    Id          = cif.Interface + cif.Guid.Substring(0, 8),
                    Adapter     = cif.Type,
                    Alias       = "import " + cif.Interface,
                    Ip          = cif.StaticAddress,
                    Subnet      = subnet,
                    Mode        = cif.Mode,
                    ChildrenIf  = cif.InterfaceList,
                    Broadcast   = broadcast,
                    Type        = NetworkInterfaceType.Internal,
                    Hostname    = hostname,
                    Index       = index,
                    Description = "import " + cif.Interface,
                    RoleVerb    = NetworkRoleVerb.iif
                };

                var tryget = Network2Configuration.InterfaceConfigurationList.FirstOrDefault(_ => _.Id == networkConfiguration.Id);
                if (tryget == null)
                {
                    Network2Configuration.AddInterfaceConfiguration(networkConfiguration);
                }

                var ifConfig = new NetworkInterface {
                    Device                   = cif.Interface,
                    Configuration            = networkConfiguration.Id,
                    AdditionalConfigurations = new List <string>(),
                    GatewayConfiguration     = ""
                };

                var tryget2 = Network2Configuration.Conf.Interfaces.FirstOrDefault(_ => _.Device == cif.Interface);
                if (tryget2 == null)
                {
                    niflist.Add(ifConfig);
                }
            }
            if (niflist.Any())
            {
                Network2Configuration.SaveInterfaceSetting(niflist);
            }
            if (!Network2Configuration.GatewayConfigurationList.Any())
            {
                var defaultGatewayConfiguration = new NetworkGatewayConfiguration {
                    Id             = Random.ShortGuid(),
                    IsDefault      = true,
                    GatewayAddress = vars.InternalHostIpPrimary,
                    Description    = "DFGW"
                };
                Network2Configuration.AddGatewayConfiguration(defaultGatewayConfiguration);
            }
            #endregion

            #region import parameters
            if (!File.Exists($"{Parameter.AntdCfgParameters}/endcommands.conf"))
            {
                var tmpsetup = SetupConfiguration.Get();
                HostParametersConfiguration.SetEndCommandsList(tmpsetup);
            }
            if (!File.Exists($"{Parameter.AntdCfgParameters}/modprobes.conf"))
            {
                var ddd = EnumerableExtensions.Merge(tmpHost.Modprobes.Select(_ => _.StoredValues.Select(___ => ___.Value)));
                HostParametersConfiguration.SetModprobesList(ddd.ToList());
            }
            if (!File.Exists($"{Parameter.AntdCfgParameters}/rmmod.conf"))
            {
                var ddd = tmpHost.RemoveModules.StoredValues.FirstOrDefault().Value.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                HostParametersConfiguration.SetRmmodList(ddd.ToList());
            }
            if (!File.Exists($"{Parameter.AntdCfgParameters}/modulesblacklist.conf"))
            {
                var ddd = tmpHost.ModulesBlacklist;
                HostParametersConfiguration.SetModulesBlacklistList(ddd.ToList());
            }
            if (!File.Exists($"{Parameter.AntdCfgParameters}/osparameters.conf"))
            {
                var list = new List <string> {
                    "/proc/sys/fs/file-max 1024000",
                    "/proc/sys/net/bridge/bridge-nf-call-arptables 0",
                    "/proc/sys/net/bridge/bridge-nf-call-ip6tables 0",
                    "/proc/sys/net/bridge/bridge-nf-call-iptables 0",
                    "/proc/sys/net/bridge/bridge-nf-filter-pppoe-tagged 0",
                    "/proc/sys/net/bridge/bridge-nf-filter-vlan-tagged 0",
                    "/proc/sys/net/core/netdev_max_backlog 300000",
                    "/proc/sys/net/core/optmem_max 40960",
                    "/proc/sys/net/core/rmem_max 268435456",
                    "/proc/sys/net/core/somaxconn 65536",
                    "/proc/sys/net/core/wmem_max 268435456",
                    "/proc/sys/net/ipv4/conf/all/accept_local 1",
                    "/proc/sys/net/ipv4/conf/all/accept_redirects 1",
                    "/proc/sys/net/ipv4/conf/all/accept_source_route 1",
                    "/proc/sys/net/ipv4/conf/all/rp_filter 0",
                    "/proc/sys/net/ipv4/conf/all/forwarding 1",
                    "/proc/sys/net/ipv4/conf/default/rp_filter 0",
                    "/proc/sys/net/ipv4/ip_forward 1",
                    "/proc/sys/net/ipv4/ip_local_port_range 1024 65000",
                    "/proc/sys/net/ipv4/ip_no_pmtu_disc 1",
                    "/proc/sys/net/ipv4/tcp_congestion_control htcp",
                    "/proc/sys/net/ipv4/tcp_fin_timeout 40",
                    "/proc/sys/net/ipv4/tcp_max_syn_backlog 3240000",
                    "/proc/sys/net/ipv4/tcp_max_tw_buckets 1440000",
                    "/proc/sys/net/ipv4/tcp_moderate_rcvbuf 1",
                    "/proc/sys/net/ipv4/tcp_mtu_probing 1",
                    "/proc/sys/net/ipv4/tcp_rmem 4096 87380 134217728",
                    "/proc/sys/net/ipv4/tcp_slow_start_after_idle 1",
                    "/proc/sys/net/ipv4/tcp_tw_recycle 0",
                    "/proc/sys/net/ipv4/tcp_tw_reuse 1",
                    "/proc/sys/net/ipv4/tcp_window_scaling 1",
                    "/proc/sys/net/ipv4/tcp_wmem 4096 65536 134217728",
                    "/proc/sys/net/ipv6/conf/br0/disable_ipv6 1",
                    "/proc/sys/net/ipv6/conf/eth0/disable_ipv6 1",
                    "/proc/sys/net/ipv6/conf/wlan0/disable_ipv6 1",
                    "/proc/sys/vm/swappiness 0"
                };
                HostParametersConfiguration.SetOsParametersList(list);

                ConsoleLogger.Log("[data import] parameters");
            }
            #endregion

            #endregion

            #region [    Adjustments    ]
            new Do().ParametersChangesPre();
            ConsoleLogger.Log("modules, services and os parameters ready");
            #endregion

            ConsoleLogger.Log("[boot step] procedures");

            #region [    Users    ]
            var manageMaster = new ManageMaster();
            manageMaster.Setup();
            UserConfiguration.Import();
            UserConfiguration.Set();
            ConsoleLogger.Log("users config ready");
            #endregion

            #region [    Host Configuration & Name Service    ]
            new Do().HostChanges();
            ConsoleLogger.Log("host configured");
            ConsoleLogger.Log("name service ready");
            #endregion

            #region [    Network    ]
            new Do().NetworkChanges();
            if (File.Exists("/cfg/antd/services/network.conf"))
            {
                File.Delete("/cfg/antd/services/network.conf");
            }
            if (File.Exists("/cfg/antd/services/network.conf.bck"))
            {
                File.Delete("/cfg/antd/services/network.conf.bck");
            }
            ConsoleLogger.Log("network ready");
            #endregion

            #region [    Firewall    ]
            if (FirewallConfiguration.IsActive())
            {
                FirewallConfiguration.Set();
            }
            #endregion

            #region [    Dhcpd    ]
            DhcpdConfiguration.TryImport();
            if (DhcpdConfiguration.IsActive())
            {
                DhcpdConfiguration.Set();
            }
            #endregion

            #region [    Bind    ]
            BindConfiguration.TryImport();
            BindConfiguration.DownloadRootServerHits();
            if (BindConfiguration.IsActive())
            {
                BindConfiguration.Set();
            }
            #endregion

            ConsoleLogger.Log("[boot step] post procedures");

            #region [    Apply Setup Configuration    ]
            new Do().ParametersChangesPost();
            ConsoleLogger.Log("machine configured (apply setup.conf)");
            #endregion

            #region [    Nginx    ]
            NginxConfiguration.TryImport();
            if (NginxConfiguration.IsActive())
            {
                NginxConfiguration.Set();
            }
            #endregion

            #region [    Ssh    ]
            if (SshdConfiguration.IsActive())
            {
                SshdConfiguration.Set();
            }
            DirectoryWithAcl.CreateDirectory(Parameter.RootSsh, "755", "root", "wheel");
            DirectoryWithAcl.CreateDirectory(Parameter.RootSshMntCdrom, "755", "root", "wheel");
            if (!MountHelper.IsAlreadyMounted(Parameter.RootSsh))
            {
                MountManagement.Dir(Parameter.RootSsh);
            }
            var rk = new RootKeys();
            if (rk.Exists == false)
            {
                rk.Create();
            }
            var authorizedKeysConfiguration = new AuthorizedKeysConfiguration();
            var storedKeys = authorizedKeysConfiguration.Get().Keys;
            foreach (var storedKey in storedKeys)
            {
                var home = storedKey.User == "root" ? "/root/.ssh" : $"/home/{storedKey.User}/.ssh";
                var authorizedKeysPath = $"{home}/authorized_keys";
                if (!File.Exists(authorizedKeysPath))
                {
                    File.Create(authorizedKeysPath);
                }
                FileWithAcl.AppendAllLines(authorizedKeysPath, new List <string> {
                    $"{storedKey.KeyValue} {storedKey.RemoteUser}"
                }, "644", "root", "wheel");
                Bash.Execute($"chmod 600 {authorizedKeysPath}");
                Bash.Execute($"chown {storedKey.User}:{storedKey.User} {authorizedKeysPath}");
            }
            ConsoleLogger.Log("ssh ready");
            #endregion

            #region [    Service Discovery    ]
            try {
                ServiceDiscovery.Rssdp.PublishThisDevice();
                ConsoleLogger.Log("[rssdp] published device");
            }
            catch (Exception ex) {
                ConsoleLogger.Log($"[rssdp] {ex.Message}");
            }
            #endregion

            #region [    AntdUI    ]
            UiService.Setup();
            ConsoleLogger.Log("antduisetup");
            #endregion

            ConsoleLogger.Log("[boot step] managed procedures");

            #region [    Samba    ]
            if (SambaConfiguration.IsActive())
            {
                SambaConfiguration.Set();
            }
            #endregion

            #region [    Syslog    ]
            if (SyslogNgConfiguration.IsActive())
            {
                SyslogNgConfiguration.Set();
            }
            #endregion

            #region [    Storage - Zfs   ]
            foreach (var pool in Zpool.ImportList().ToList())
            {
                if (string.IsNullOrEmpty(pool))
                {
                    continue;
                }
                ConsoleLogger.Log($"pool {pool} imported");
                Zpool.Import(pool);
            }
            ConsoleLogger.Log("storage ready");
            #endregion

            #region [    Scheduler    ]
            Timers.MoveExistingTimers();
            Timers.Setup();
            Timers.Import();
            Timers.Export();
            foreach (var zp in Zpool.List())
            {
                Timers.Create(zp.Name.ToLower() + "snap", "hourly", $"/sbin/zfs snap -r {zp.Name}@${{TTDATE}}");
            }
            Timers.StartAll();
            new SnapshotCleanup().Start(new TimeSpan(2, 00, 00));
            new SyncTime().Start(new TimeSpan(0, 42, 00));
            new RemoveUnusedModules().Start(new TimeSpan(2, 15, 00));

            JobManager jobManager = new JobManager();
            jobManager.ExecuteAllJobs();

            ConsoleLogger.Log("scheduled events ready");
            #endregion

            #region [    Acl    ]
            if (AclConfiguration.IsActive())
            {
                AclConfiguration.Set();
                AclConfiguration.ScriptSetup();
            }
            #endregion

            #region [    C A    ]
            if (CaConfiguration.IsActive())
            {
                CaConfiguration.Set();
            }
            #endregion

            #region [    Host Init    ]
            var app  = new AppConfiguration().Get();
            var port = app.AntdPort;
            var uri  = $"http://localhost:{app.AntdPort}/";
            var host = new NancyHost(new Uri(uri));
            host.Start();
            ConsoleLogger.Log("host ready");
            StaticConfiguration.DisableErrorTraces = false;
            ConsoleLogger.Log($"http port: {port}");
            ConsoleLogger.Log("[boot step] antd is running");
            #endregion

            ConsoleLogger.Log("[boot step] working procedures");

            #region [    Apps    ]
            AppTarget.Setup();
            var apps = AppsConfiguration.Get().Apps;
            foreach (var mapp in apps)
            {
                var units = mapp.UnitLauncher;
                foreach (var unit in units)
                {
                    if (Systemctl.IsActive(unit) == false)
                    {
                        Systemctl.Restart(unit);
                    }
                }
            }
            //AppTarget.StartAll();
            ConsoleLogger.Log("apps ready");
            #endregion

            #region [    Sync / Gluster   ]
            if (GlusterConfiguration.IsActive())
            {
                GlusterConfiguration.Launch();
            }
            if (RsyncConfiguration.IsActive())
            {
                RsyncConfiguration.Set();
            }
            #endregion

            #region [    Storage Server    ]
            VfsConfiguration.SetDefaults();
            new Thread(() => {
                try {
                    var srv = new StorageServer(VfsConfiguration.GetSystemConfiguration());
                    srv.Start();
                }
                catch (Exception ex) {
                    ConsoleLogger.Error(ex.Message);
                }
            }).Start();
            #endregion

            #region [    Tor    ]
            if (TorConfiguration.IsActive())
            {
                TorConfiguration.Start();
            }
            #endregion

            #region [    Cluster    ]
            VfsWatcher = new VfsWatcher();
            ClusterConfiguration.Prepare();
            new Do().ClusterChanges();
            ConsoleLogger.Log("[cluster] active");
            #endregion

            #region [    Directory Watchers    ]
            DirectoryWatcherCluster.Start();
            DirectoryWatcherRsync.Start();
            #endregion

            #region [    Check Application File Acls    ]
            var files = Directory.EnumerateFiles(Parameter.RepoApps, "*.squashfs.xz", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                Bash.Execute($"chmod 644 {file}");
                Bash.Execute($"chown root:wheel {file}");
            }
            ConsoleLogger.Log("[check] app-file acl");
            #endregion

            #region [    Check System Components    ]
            MachineInfo.CheckSystemComponents();
            ConsoleLogger.Log("[check] system components health");
            #endregion

            #region [    Test    ]
#if DEBUG
            Test();
#endif
            #endregion

            ConsoleLogger.Log($"loaded in: {DateTime.Now - startTime}");
            KeepAlive();
            ConsoleLogger.Log("antd is closing");
            host.Stop();
            Console.WriteLine("host shutdown");
        }
Exemplo n.º 16
0
        public void Start()
        {
            if (Systemctl.IsEnabled(ServiceName) == false)
            {
                Systemctl.Enable(ServiceName);
            }
            if (Systemctl.IsActive(ServiceName) == false)
            {
                Systemctl.Restart(ServiceName);
            }

            Systemctl.Restart(ServiceName);

            var remoteHost = _serviceModel.RemoteHost;
            var r          = Handshake(remoteHost);

            if (!r)
            {
                ConsoleLogger.Warn($"[vpn] remote host {remoteHost} is unreachable");
                return;
            }

            remoteHost = remoteHost.Split(':').FirstOrDefault();

            var lsmod = Bash.Execute("lsmod").SplitBash().Grep("tun").FirstOrDefault();

            if (lsmod == null)
            {
                Bash.Execute("modprobe tun");
            }
            var lsmodRemote = Bash.Execute($"ssh root@{remoteHost} \"modprobe tun\"").SplitBash().Grep("tun").FirstOrDefault();

            if (lsmodRemote == null)
            {
                Bash.Execute($"ssh root@{remoteHost} \"modprobe tun\"");
            }

            Bash.Execute($"ssh root@{remoteHost} \"systemctl restart {ServiceName}\"");

            var unit = SetUnitForTunnel(remoteHost);

            if (unit == false)
            {
                ConsoleLogger.Warn("[vpn] something went wrong while creating the tunnel");
                return;
            }

            var localTap = Bash.Execute("ip link show").SplitBash().ToList();

            if (!localTap.Any(_ => _.Contains("tap1")))
            {
                ConsoleLogger.Warn("[vpn] something went wrong while setting the local tunnel interface");
                return;
            }
            Bash.Execute("ip link set dev tap1 up");
            Bash.Execute("ip addr flush dev tap1");
            Bash.Execute($"ip addr add {_serviceModel.LocalPoint.Address}/{_serviceModel.LocalPoint.Range} dev tap1");
            localTap = Bash.Execute("ip link show tap1").SplitBash().ToList();
            if (localTap.Any(_ => _.ToLower().Contains("up")))
            {
                ConsoleLogger.Log("[vpn] local tunnel interface is up");
            }

            var remoteTap = Bash.Execute($"ssh root@{remoteHost} \"ip link show\"").SplitBash().ToList();

            if (!remoteTap.Any(_ => _.Contains("tap1")))
            {
                ConsoleLogger.Warn("[vpn] something went wrong while setting the remote tunnel interface");
                return;
            }
            Bash.Execute($"ssh root@{remoteHost} \"ip link set dev tap1 up\"");
            Bash.Execute($"ssh root@{remoteHost} \"ip addr flush dev tap1\"");
            Bash.Execute($"ssh root@{remoteHost} \"ip addr add {_serviceModel.LocalPoint.Address}/{_serviceModel.LocalPoint.Range} dev tap1\"");
            remoteTap = Bash.Execute($"ssh root@{remoteHost} \"ip link show tap1\"").SplitBash().ToList();
            if (remoteTap.Any(_ => _.ToLower().Contains("up")))
            {
                ConsoleLogger.Log("[vpn] remote tunnel interface is up");
            }

            ConsoleLogger.Log("[vpn] connection established");
        }