Ejemplo 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");
 }
Ejemplo n.º 2
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);
            }
        }
Ejemplo n.º 3
0
 private static void EnableRequiredServices()
 {
     Systemctl.Start("systemd-networkd.service");
     Systemctl.Start("systemd-resolved.service");
     Systemctl.Enable("systemd-networkd.service");
     Systemctl.Enable("systemd-resolved.service");
 }
Ejemplo n.º 4
0
        public UnitsModule()
            : base("/units")
        {
            Get["/"] = x => {
                List <UnitModel> units = Units.All;
                return(View["page-units", units]);
            };

            Post["/mgmt/enable/{unit}"] = x => {
                string       unit = x.unit;
                CommandModel r    = Systemctl.Enable(unit);
                string       json = JsonConvert.SerializeObject(r.outputTable);
                return(json);
            };

            Post["/mgmt/disable/{unit}"] = x => {
                string       unit = x.unit;
                CommandModel r    = Systemctl.Disable(unit);
                string       json = JsonConvert.SerializeObject(r.outputTable);
                return(json);
            };

            Post["/mgmt/start/{unit}"] = x => {
                string       unit = x.unit;
                CommandModel r    = Systemctl.Start(unit);
                string       json = JsonConvert.SerializeObject(r.outputTable);
                return(json);
            };

            Post["/mgmt/stop/{unit}"] = x => {
                string       unit = x.unit;
                CommandModel r    = Systemctl.Stop(unit);
                string       json = JsonConvert.SerializeObject(r.outputTable);
                return(json);
            };

            Post["/mgmt/restart/{unit}"] = x => {
                string       unit = x.unit;
                CommandModel r    = Systemctl.Restart(unit);
                string       json = JsonConvert.SerializeObject(r.outputTable);
                return(json);
            };

            Post["/mgmt/reload/{unit}"] = x => {
                string       unit = x.unit;
                CommandModel r    = Systemctl.Reload(unit);
                string       json = JsonConvert.SerializeObject(r.outputTable);
                return(json);
            };

            Get["/mgmt/status/{unit}"] = x => {
                string       unit = x.unit;
                CommandModel r    = Systemctl.Status(unit);
                string       json = JsonConvert.SerializeObject(r.outputTable);
                return(json);
            };
        }
Ejemplo n.º 5
0
        private static void Main(string[] args)
        {
            DateTime startTime = DateTime.Now;

            Console.Title = "ANTD";
            Console.WriteLine(ConsoleTime.GetTime(DateTime.Now) + "loading application...");

            SystemConfig.FirstLaunchDefaults();
            Console.WriteLine(ConsoleTime.GetTime(DateTime.Now) + "setting core system configuration...");

            Cfg.FirstLaunchDefaults();
            Console.WriteLine(ConsoleTime.GetTime(DateTime.Now) + "setting core cfg configuration...");

            var stop = new ManualResetEvent(false);

            Console.CancelKeyPress +=
                (sender, e) => {
                Console.WriteLine("^C");
                Database.ShutDown();
                stop.Set();
                e.Cancel = true;
            };
            string uri = SelfConfig.GetAntdUri();

            Console.WriteLine(ConsoleTime.GetTime(DateTime.Now) + "initializing antd");
            using (WebApp.Start <Startup>(uri)) {
                Console.WriteLine(ConsoleTime.GetTime(DateTime.Now) + "loading service");
                Console.WriteLine(ConsoleTime.GetTime(DateTime.Now) + "    service type -> server");
                Console.WriteLine(ConsoleTime.GetTime(DateTime.Now) + "                 -> server url -> {0}", uri);
                Console.WriteLine(ConsoleTime.GetTime(DateTime.Now) + "service is now running");
                var elapsed = DateTime.Now - startTime;
                Console.WriteLine(ConsoleTime.GetTime(DateTime.Now) + "loaded in: " + elapsed);

                Console.WriteLine("");
                ServiceUnitInfo.SetDefaultUnitInfo();
                Console.WriteLine(ConsoleTime.GetTime(DateTime.Now) + "misc -> default unit info saved to database");

                UnitFile.WriteForSelf();
                Console.WriteLine(ConsoleTime.GetTime(DateTime.Now) + "self -> unit file created");

                Systemctl.Enable("antd.service");
                Console.WriteLine(ConsoleTime.GetTime(DateTime.Now) + "self -> unit file enabled");

                //Console.WriteLine("");
                //string[] watchThese = new string[] {
                //    "/cfg",
                //    "/proc/sys",
                //    "/sys/class/net"
                //};
                //foreach (string folder in watchThese) {
                //    new DirectoryWatcher(folder).Watch();
                //    Console.WriteLine(ConsoleTime.GetTime(DateTime.Now) + "watcher enabled for {0}", folder);
                //}

                stop.WaitOne();
            }
        }
Ejemplo n.º 6
0
        public AntdServicesModule()
        {
            Get["/services"] = x => {
                var model       = new PageServicesModel();
                var machineInfo = new MachineInfo();
                var services    = machineInfo.GetUnits("service");
                var mounts      = machineInfo.GetUnits("mount");
                var targets     = machineInfo.GetUnits("target");
                var timers      = machineInfo.GetUnits("timer");
                services.AddRange(mounts);
                services.AddRange(targets);
                services.AddRange(timers);
                model.Units = services;
                return(JsonConvert.SerializeObject(model));
            };

            Get["/services/log"] = x => {
                string unit     = Request.Query.unit;
                var    launcher = new CommandLauncher();
                var    model    = launcher.Launch("journactl-service", new Dictionary <string, string> {
                    { "$service", unit }
                });
                return(JsonConvert.SerializeObject(model));
            };

            Post["/services/start"] = x => {
                string unit = Request.Form.Unit;
                Systemctl.Start(unit);
                return(HttpStatusCode.OK);
            };

            Post["/services/restart"] = x => {
                string unit = Request.Form.Unit;
                Systemctl.Restart(unit);
                return(HttpStatusCode.OK);
            };

            Post["/services/stop"] = x => {
                string unit = Request.Form.Unit;
                Systemctl.Stop(unit);
                return(HttpStatusCode.OK);
            };

            Post["/services/enable"] = x => {
                string unit = Request.Form.Unit;
                Systemctl.Enable(unit);
                return(HttpStatusCode.OK);
            };

            Post["/services/disable"] = x => {
                string unit = Request.Form.Unit;
                Systemctl.Disable(unit);
                return(HttpStatusCode.OK);
            };
        }
Ejemplo n.º 7
0
        public UnitsModule()
        {
            this.RequiresAuthentication();

            Get["/units"] = x => {
                var units = Units.All;
                return(View["page-units", units]);
            };

            Get["/units/list"] = x => {
                return(JsonConvert.SerializeObject(Units.All.OrderBy(u => u.name)));
            };

            Post["/units/mgmt/enable/{unit}"] = x => {
                string unit = x.unit;
                var    r    = Systemctl.Enable(unit);
                return(JsonConvert.SerializeObject(r.outputTable));
            };

            Post["/units/mgmt/disable/{unit}"] = x => {
                string unit = x.unit;
                var    r    = Systemctl.Disable(unit);
                return(JsonConvert.SerializeObject(r.outputTable));
            };

            Post["/units/mgmt/start/{unit}"] = x => {
                string unit = x.unit;
                var    r    = Systemctl.Start(unit);
                return(JsonConvert.SerializeObject(r.outputTable));
            };

            Post["/units/mgmt/stop/{unit}"] = x => {
                string unit = x.unit;
                var    r    = Systemctl.Stop(unit);
                return(JsonConvert.SerializeObject(r.outputTable));
            };

            Post["/units/mgmt/restart/{unit}"] = x => {
                string unit = x.unit;
                var    r    = Systemctl.Restart(unit);
                return(JsonConvert.SerializeObject(r.outputTable));
            };

            Post["/units/mgmt/reload/{unit}"] = x => {
                string unit = x.unit;
                var    r    = Systemctl.Reload(unit);
                return(JsonConvert.SerializeObject(r.outputTable));
            };

            Get["/units/mgmt/status/{unit}"] = x => {
                string unit = x.unit;
                var    r    = Systemctl.Status(unit);
                return(JsonConvert.SerializeObject(r.outputTable));
            };
        }
Ejemplo n.º 8
0
 public void Start()
 {
     if (Systemctl.IsEnabled(ServiceName) == false)
     {
         Systemctl.Enable(ServiceName);
     }
     if (Systemctl.IsActive(ServiceName) == false)
     {
         Systemctl.Restart(ServiceName);
     }
     ConsoleLogger.Log("[kerberos] start");
 }
Ejemplo n.º 9
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);
                }
            }
        }
Ejemplo n.º 10
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");
        }
Ejemplo n.º 11
0
        public static void Launch()
        {
            ConsoleLogger.Log("[gluster] launch");
            var config = ServiceModel;

            SetHostnameFile(config);
            Systemctl.Enable(ServiceName);
            Systemctl.Start(ServiceName);
            ConsoleLogger.Log("[gluster] include nodes");
            foreach (var node in config.Nodes)
            {
                IncludeNode(node.Hostname);
            }
            ConsoleLogger.Log("[gluster] start volumes");
            foreach (var volume in config.Volumes)
            {
                SetVolume(volume, config.Nodes);
            }
        }
Ejemplo n.º 12
0
 public static CommandModel EnableAnthillaAS()
 {
     return(Systemctl.Enable("/cfg/anthilla.units.d/anthillaas.service"));
 }
Ejemplo n.º 13
0
        public void CreateScript()
        {
            var script = new BashScript {
                Comment("Setup environment"),

                Set("INSTANCE_ID", "$(curl -s http://169.254.169.254/latest/meta-data/instance-id)"),

                new IfStatement(IsDefined("$1"), Set("APP_NAME", "$1")),
                new IfStatement(IsDefined("$2"), Set("APP_VERSION", "$2")),

                // TODO: Use shorter syntax...
                new IfStatement(IsDefined("$3"),
                                then: new[] { Set("APP_PACKAGE_URL", "$3") },
                                elseThen: new[] { Set("APP_PACKAGE_URL", "s3://folder/$APP_NAME/$APP_VERSION.tar.gz") }
                                ),

                Set("APP_ROOT", "/var/apps/$APP_NAME/$APP_VERSION"),

                Empty, Echo("Configuring $APP_NAME/$APP_VERSION"),

                // Install depedencies
                Apt.Install("awscli", "nginx", "libunwind8", "libcurl4-openssl-dev"),

                // Configure S3 to allow encrypted package downloads
                "sudo aws configure set s3.signature_version s3v4",

                // Install SSM  agent
                "cd /tmp",

                Wget.Download(
                    new Uri("https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/debian_amd64/amazon-ssm-agent.deb")
                    ),

                "sudo dpkg -i amazon-ssm-agent.deb",

                Systemctl.Enable("amazon-ssm-agent"),

                // Configure Ngnix ------------------------------------------------------------------------------------------------
                Empty, Echo("Configuring nginx"),

                Wget.Download(
                    url: new Uri("https://unknown/nginx.config"),
                    destination: "/etc/nginx/sites-available/default",
                    sudo: true
                    ),

                Nginx.Reload(),

                // Setup program directories
                "mkdir -p $APP_ROOT",

                // Install the app ------------------------------------------------------------------------------------------------

                // Create a working directory for download
                "mkdir -r /tmp/programs/$APP_NAME/$APP_VERSION",

                // Download the app
                Aws.S3.Copy(
                    source: "$APP_PACKAGE_URL",
                    target: "/tmp/programs/$APP_NAME/$APP_VERSION",
                    options: AwsOptions.Quiet,
                    sudo: true
                    ),

                // Extract the app
                Tar.Extract(
                    file: "/tmp/programs/$APP_NAME/$APP_VERSION",
                    directory: "$APP_ROOT",
                    stripFirstLevel: true
                    ),

                // Create a symbolic link
                CreateSymbolicLink(
                    target: "$APP_ROOT",
                    link: "/var/apps/$APP_NAME/latest",
                    options: SymbolicLinkOptions.Symbolic | SymbolicLinkOptions.Force,  // update if it already exists
                    sudo:    true
                    ),

                // Give permissions to www-data
                Chown(owner: "www-data", path: "/var/apps", recursive: true, sudo: true),

                // Configure the service ------------------------------------------------------------------------------------------
                Empty, Echo("Configuring $APP_NAME.service"),

                // Setup the service
                Aws.S3.Copy(
                    source: "s3://folder/$APP_NAME/$APPNAME.service",
                    target: "/etc/systemd/system/$APP_NAME.service",
                    options: AwsOptions.Quiet,
                    sudo: true
                    ),

                Systemctl.Enable("$APP_NAME.service"),
                Systemctl.Start("$APP_NAME.service"),

                // Cleanup -------------------------------------------------------------------------------------------------------
                Empty, Echo("Cleaning up"),

                new Command("rm -r /tmp/programs/$APP_NAME/$APP_VERSION"),

                // Report to homebase ---------------------------------------------------------------------------------------------
                Empty, Echo("Phoning home $INSTANCE_ID"),

                "curl --data \"status=running\" https://cloud/hosts/aws:$INSTANCE_ID"
            };


            Assert.Equal(@"#!/bin/bash
# Setup environment
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
if [ -n ""$1"" ]; then APP_NAME=$1; fi
if [ -n ""$2"" ]; then APP_VERSION=$2; fi
if [ -n ""$3"" ]; then APP_PACKAGE_URL=$3; else APP_PACKAGE_URL=s3://folder/$APP_NAME/$APP_VERSION.tar.gz; fi
APP_ROOT=/var/apps/$APP_NAME/$APP_VERSION

echo ""Configuring $APP_NAME/$APP_VERSION""
sudo apt install -y awscli nginx libunwind8 libcurl4-openssl-dev
sudo aws configure set s3.signature_version s3v4
cd /tmp
wget -v ""https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/debian_amd64/amazon-ssm-agent.deb""
sudo dpkg -i amazon-ssm-agent.deb
sudo systemctl enable amazon-ssm-agent

echo ""Configuring nginx""
sudo wget -v ""https://unknown/nginx.config"" -O /etc/nginx/sites-available/default
sudo nginx -s reload
mkdir -p $APP_ROOT
mkdir -r /tmp/programs/$APP_NAME/$APP_VERSION
sudo aws s3 cp --quiet $APP_PACKAGE_URL /tmp/programs/$APP_NAME/$APP_VERSION
tar -xf /tmp/programs/$APP_NAME/$APP_VERSION --strip 1 -C $APP_ROOT
sudo ln -sfn $APP_ROOT /var/apps/$APP_NAME/latest
sudo chown -R www-data /var/apps

echo ""Configuring $APP_NAME.service""
sudo aws s3 cp --quiet s3://folder/$APP_NAME/$APPNAME.service /etc/systemd/system/$APP_NAME.service
sudo systemctl enable $APP_NAME.service
sudo systemctl start $APP_NAME.service

echo ""Cleaning up""
rm -r /tmp/programs/$APP_NAME/$APP_VERSION

echo ""Phoning home $INSTANCE_ID""
curl --data ""status=running"" https://cloud/hosts/aws:$INSTANCE_ID", script.ToString());
        }
Ejemplo n.º 14
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");
        }
Ejemplo n.º 15
0
        public AssetClusterModule()
        {
            Get["/cluster"] = x => {
                var syncedMachines = ClusterConfiguration.GetNodes();
                var config         = ClusterConfiguration.GetClusterInfo();
                foreach (var node in syncedMachines)
                {
                    var services = _api.Get <List <RssdpServiceModel> >(node.ModelUrl + "device/services");
                    node.Services = services;
                }
                var importPortMapping = syncedMachines
                                        .Select(_ => _.Services)
                                        .Merge()
                                        .Select(_ => _.Name)
                                        .ToHashSet()
                                        .Select(_ => new Cluster.PortMapping {
                    ServiceName = _, ServicePort = "", VirtualPort = ""
                })
                                        .ToList()
                ;
                var existingPortMapping = config.PortMapping.ToList();
                foreach (var i in importPortMapping)
                {
                    if (existingPortMapping.FirstOrDefault(_ => _.ServiceName == i.ServiceName) == null)
                    {
                        existingPortMapping.Add(i);
                    }
                }
                config.PortMapping = existingPortMapping.ToList();
                var model = new PageAssetClusterModel {
                    Info            = config,
                    ClusterNodes    = syncedMachines.OrderBy(_ => _.Hostname).ThenBy(_ => _.PublicIp).ToList(),
                    NetworkAdapters = IPv4.GetAllLocalDescription().ToList()
                };
                return(JsonConvert.SerializeObject(model));
            };

            Post["/cluster/save"] = x => {
                string config = Request.Form.Config;
                string ip     = Request.Form.Ip;
                var    model  = JsonConvert.DeserializeObject <List <NodeModel> >(config);
                var    model2 = JsonConvert.DeserializeObject <Cluster.Configuration>(ip);
                ClusterConfiguration.SaveNodes(model);
                ClusterConfiguration.SaveConfiguration(model2);
                new Do().ClusterChanges();
                DeployClusterConfiguration();
                return(HttpStatusCode.OK);
            };

            Post["Accept Configuration", "/cluster/accept"] = x => {
                string file    = Request.Form.File;
                string content = Request.Form.Content;
                if (string.IsNullOrEmpty(file))
                {
                    return(HttpStatusCode.BadRequest);
                }
                if (string.IsNullOrEmpty(content))
                {
                    return(HttpStatusCode.BadRequest);
                }
                ConsoleLogger.Log($"[cluster] received config for file: {file}");

                DirectoryWatcherCluster.Stop();
                try {
                    FileWithAcl.WriteAllText(file, content, "644", "root", "wheel");
                }
                catch (Exception) {
                    ConsoleLogger.Warn("");
                    DirectoryWatcherCluster.Start();
                    return(HttpStatusCode.InternalServerError);
                }
                DirectoryWatcherCluster.Start();

                var dict = Dicts.DirsAndServices;
                if (dict.ContainsKey(file))
                {
                    ConsoleLogger.Log("[cluster] restart service bind to config file");
                    var services = dict[file];
                    foreach (var svc in services)
                    {
                        Systemctl.Enable(svc);
                        Systemctl.Restart(svc);
                    }
                }
                ConsoleLogger.Log("[cluster] apply changes after new config");
                new Do().HostChanges();
                new Do().NetworkChanges();
                DeployClusterConfiguration();
                return(HttpStatusCode.OK);
            };

            #region [    Handshake + cluster init    ]
            Post["/asset/handshake/start", true] = async(x, ct) => {
                string conf       = Request.Form.HostJson;
                var    remoteNode = JsonConvert.DeserializeObject <NodeModel>(conf);
                if (remoteNode == null)
                {
                    return(HttpStatusCode.InternalServerError);
                }
                const string pathToPrivateKey = "/root/.ssh/id_rsa";
                const string pathToPublicKey  = "/root/.ssh/id_rsa.pub";
                if (!File.Exists(pathToPublicKey))
                {
                    var k = Bash.Execute($"ssh-keygen -t rsa -N '' -f {pathToPrivateKey}");
                    ConsoleLogger.Log(k);
                }
                var key = File.ReadAllText(pathToPublicKey);
                if (string.IsNullOrEmpty(key))
                {
                    return(HttpStatusCode.InternalServerError);
                }
                var dict = new Dictionary <string, string> {
                    { "ApplePie", key }
                };
                var r = new ApiConsumer().Post($"{remoteNode.ModelUrl}asset/handshake", dict);
                if (r != HttpStatusCode.OK)
                {
                    return(HttpStatusCode.InternalServerError);
                }
                //ho fatto l'handshake, quindi il nodo richiesto è pronto per essere integrato nel cluster
                //1. controllo la configurazione
                var clusterConfiguration = ClusterConfiguration.GetClusterInfo();
                if (string.IsNullOrEmpty(clusterConfiguration.Guid))
                {
                    clusterConfiguration.Guid = Guid.NewGuid().ToString();
                }
                if (string.IsNullOrEmpty(clusterConfiguration.Priority))
                {
                    clusterConfiguration.Priority = "100";
                }
                if (string.IsNullOrEmpty(clusterConfiguration.NetworkInterface))
                {
                    clusterConfiguration.NetworkInterface = "";
                }
                if (string.IsNullOrEmpty(clusterConfiguration.VirtualIpAddress))
                {
                    clusterConfiguration.VirtualIpAddress = "";
                }
                //2. salvo la configurazione
                ClusterConfiguration.SaveConfiguration(clusterConfiguration);
                //3. controllo i nodi presenti nella configurazione
                var clusterNodes = ClusterConfiguration.GetNodes();
                var iplocals     = IPv4.GetAllLocalAddress().ToList();
                var disc         = await ServiceDiscovery.Rssdp.Discover();

                //4. per prima cosa controllo l'host locale
                var localNode = disc.FirstOrDefault(_ => iplocals.Contains(_.PublicIp));
                //5. se non c'è lo aggiungo
                if (clusterNodes.FirstOrDefault(_ => _.MachineUid == localNode.MachineUid && _.PublicIp == localNode.PublicIp) == null)
                {
                    clusterNodes.Add(localNode);
                }
                //7. se non c'è lo aggiungo
                if (clusterNodes.FirstOrDefault(_ => _.MachineUid == remoteNode.MachineUid && _.PublicIp == remoteNode.PublicIp) == null)
                {
                    clusterNodes.Add(remoteNode);
                }
                //8. salvo la configurazione dei nodi
                ClusterConfiguration.SaveNodes(clusterNodes);
                //9. riavvio/avvio il servizio di cluster
                new Do().ClusterChanges();
                DeployClusterConfiguration();
                return(HttpStatusCode.OK);
            };

            Post["/asset/handshake"] = x => {
                string apple = Request.Form.ApplePie;
                var    info  = apple.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                if (info.Length < 2)
                {
                    return(HttpStatusCode.InternalServerError);
                }
                var          key        = info[0];
                var          remoteUser = info[1];
                const string user       = "******";
                var          model      = new AuthorizedKeyModel {
                    RemoteUser = remoteUser,
                    User       = user,
                    KeyValue   = key
                };
                var authorizedKeysConfiguration = new AuthorizedKeysConfiguration();
                authorizedKeysConfiguration.AddKey(model);
                try {
                    DirectoryWithAcl.CreateDirectory("/root/.ssh");
                    const string authorizedKeysPath = "/root/.ssh/authorized_keys";
                    if (File.Exists(authorizedKeysPath))
                    {
                        var f = File.ReadAllText(authorizedKeysPath);
                        if (!f.Contains(apple))
                        {
                            FileWithAcl.AppendAllLines(authorizedKeysPath, new List <string> {
                                apple
                            }, "644", "root", "wheel");
                        }
                    }
                    else
                    {
                        FileWithAcl.WriteAllLines(authorizedKeysPath, new List <string> {
                            apple
                        }, "644", "root", "wheel");
                    }
                    Bash.Execute($"chmod 600 {authorizedKeysPath}", false);
                    Bash.Execute($"chown {user}:{user} {authorizedKeysPath}", false);
                    return(HttpStatusCode.OK);
                }
                catch (Exception ex) {
                    ConsoleLogger.Log(ex);
                    return(HttpStatusCode.InternalServerError);
                }
            };

            Post["/cluster/deploy"] = x => {
                var clusterConfiguration = Request.Form.Cluster;
                Cluster.DeployConf model = Newtonsoft.Json.JsonConvert.DeserializeObject <Cluster.DeployConf>(clusterConfiguration);
                ClusterConfiguration.SaveConfiguration(model.Configuration);
                ClusterConfiguration.SaveNodes(model.Nodes);
                new Do().ClusterChanges();
                return(HttpStatusCode.OK);
            };

            //Post["/asset/wol"] = x => {
            //    string mac = Request.Form.MacAddress;
            //    CommandLauncher.Launch("wol", new Dictionary<string, string> { { "$mac", mac } });
            //    return HttpStatusCode.OK;
            //};

            //Get["/asset/nmasp/{ip}"] = x => {
            //    string ip = x.ip;
            //    var result = CommandLauncher.Launch("nmap-ip-fast", new Dictionary<string, string> { { "$ip", ip } }).Where(_ => !_.Contains("MAC Address")).Skip(5).Reverse().Skip(1).Reverse();
            //    var list = new List<NmapScanStatus>();
            //    foreach(var r in result) {
            //        var a = r.SplitToList(" ").ToArray();
            //        var mo = new NmapScanStatus {
            //            Protocol = a[0],
            //            Status = a[1],
            //            Type = a[2]
            //        };
            //        list.Add(mo);
            //    }
            //    list = list.OrderBy(_ => _.Protocol).ToList();
            //    return JsonConvert.SerializeObject(list);
            //};
            #endregion
        }
Ejemplo n.º 16
0
 public static CommandModel EnableAnthillaStorage()
 {
     return(Systemctl.Enable("/cfg/anthilla.units.d/anthillastorage.service"));
 }
Ejemplo n.º 17
0
 public static CommandModel EnableAnthillaFirewall()
 {
     return(Systemctl.Enable("/cfg/anthilla.units.d/anthillafirewall.service"));
 }