private static bool ValidateResourceEtag(string ifMatch, ResourceNode resourceNode)
        {
            var resourceType = resourceNode.Type;
            var etagProp = resourceType.ETagProperty;
            if (etagProp == null)
                throw new InvalidOperationException("Unable to perform If-Match on entity with no etag.");

            if ((string)etagProp.Getter(resourceNode.Value) != ifMatch)
                throw new ResourcePreconditionFailedException("Etag of entity did not match If-Match header.");
            return true;
        }
예제 #2
0
 public void StartTask(ResourceNode target)
 {
     if(GatherTarget != target) {
         GatherTarget = target;
         GatherTimer = 0;
         // Return any other incorrect held resources to a depot before beginning
         if(MoveResourceTaskScript.HeldResourceSpaceAvailable(GatherTarget.resource) == 0) {
             MoveResourceTaskScript.StartTask();
         }
     }
 }
예제 #3
0
        private static InstallationServiceClient GetInstallationServiceClient(ResourceNode node)
        {
            var binding = new BasicHttpBinding
            {
                MaxReceivedMessageSize = 65536,
                MaxBufferSize = 65536,
                CloseTimeout = new TimeSpan(0, 1, 0),
                OpenTimeout = new TimeSpan(0, 1, 0),
                ReceiveTimeout = new TimeSpan(0, 10, 0),
                SendTimeout = new TimeSpan(0, 1, 0)
            };

            var address = new EndpointAddress("http://" + node.NodeAddress + "/Installation");

            return new InstallationServiceClient(binding, address);
        }
예제 #4
0
        public void InstallByTicket(InstallationTicket ticket, ResourceNode node, string localAddress)
        {
            var farmId = ResourceCache.GetByName(node.ResourceName).Resource.Controller.FarmId;
            var fileName = Path.GetFileName(localAddress);

            var uri = new Uri(ticket.StorageAddress);

            var taskId = string.Format("{0}.{1}.{2}", uri.Host, uri.LocalPath,
                    String.Format("{0:dd/MM/yyyy_HH-mm-ss}", DateTime.Now));

            this._uploadFile(node, fileName, localAddress, taskId, farmId);

            using (var client = GetInstallationServiceClient(node))
            {
                ticket.FolderToInstall = client.InstallPackage(farmId, taskId, fileName);
            }
        }
예제 #5
0
 public ObjectInfo(
     bool weighted,
     GeometryEntry g,
     Matrix bindMatrix,
     SkinEntry skin,
     SceneEntry scene,
     InstanceEntry inst,
     ResourceNode parent,
     NodeEntry node)
 {
     _weighted   = weighted;
     _g          = g;
     _bindMatrix = bindMatrix;
     _skin       = skin;
     _scene      = scene;
     _parent     = parent;
     _node       = node;
     _inst       = inst;
 }
예제 #6
0
        void SearchResourceElementTreeNode(IDsDocument module, ResourceNode resTreeNode, ResourceElementNode resElNode)
        {
            var res = options.Filter.GetResult(resElNode);

            if (res.FilterType == FilterType.Hide)
            {
                return;
            }

            if (res.IsMatch)
            {
                bool m = IsMatch(resElNode.Name, resElNode);
                if (!m)
                {
                    var builtin = resElNode.ResourceElement.ResourceData as BuiltInResourceData;
                    if (builtin != null)
                    {
                        var val = builtin.Data;
                        if (builtin.Code == ResourceTypeCode.TimeSpan)
                        {
                            val = ((TimeSpan)val).Ticks;
                        }
                        m = IsMatch(val as string, val);
                    }
                }
                if (!m)
                {
                    m = IsMatch(ToString(resElNode), null);
                }
                if (m)
                {
                    options.OnMatch(new SearchResult {
                        Context                = options.Context,
                        Object                 = resElNode,
                        NameObject             = resElNode,
                        ObjectImageReference   = resElNode.Icon,
                        LocationObject         = resTreeNode,
                        LocationImageReference = resTreeNode.Icon,
                        Document               = module,
                    });
                }
            }
        }
예제 #7
0
        private void LoadModels(ResourceNode node, List <MDL0Node> models)
        {
            switch (node.ResourceType)
            {
            case ResourceType.ARC:
            case ResourceType.MRG:
            case ResourceType.BRES:
            case ResourceType.BRESGroup:
                foreach (ResourceNode n in node.Children)
                {
                    LoadModels(n, models);
                }
                break;

            case ResourceType.MDL0:
                models.Add((MDL0Node)node);
                break;
            }
        }
예제 #8
0
    public static bool FileExists(string filename)
    {
        UpdateFiles();

        if (!filename.ToLower().StartsWith("patch") &&
            !Path.IsPathRooted(filename) && FileExists("patch\\" + filename))
        {
            return(true);
        }

        if (File.Exists(filename))
        {
            return(true);
        }

        ResourceNode node = GetResourceNode(filename);

        return(node != null && !node.IsDirectory);
    }
예제 #9
0
    public ResourceNode FindNearestUnknownResource(Vector3 antPosition, int teamID)
    {
        ResourceNode closest     = null;
        float        minDistance = float.MaxValue;

        foreach (ResourceNode resource in ResourceList)
        {
            if ((resource.TeamIsKnown & (1 << teamID)) == 0)
            {
                float dist = Vector3.Distance(antPosition, resource.GetPosition());
                if (dist < minDistance)
                {
                    closest     = resource;
                    minDistance = dist;
                }
            }
        }
        return(closest);
    }
예제 #10
0
        public DocumentTreeNodeData Create(ModuleDef module, Resource resource, ITreeNodeGroup treeNodeGroup)
        {
            if (module is null)
            {
                throw new ArgumentNullException(nameof(module));
            }
            if (resource is null)
            {
                throw new ArgumentNullException(nameof(resource));
            }
            if (treeNodeGroup is null)
            {
                throw new ArgumentNullException(nameof(treeNodeGroup));
            }
            var node = CreateNode(module, resource, treeNodeGroup);

            ResourceNode.AddResource(node, resource);
            return(node);
        }
예제 #11
0
        private void Install(InstallationTicket ticket, ResourceNode node, IInstallationController controller)
        {
            ShouldReportIfError(ticket, () =>
            {
                _packageObtainer.ObtainPackage(ticket.StorageAddress, (address, error) =>
                {
                    if (error != null)
                    {
                        ReportResult(ticket, error);
                        return;
                    }

                    ShouldReport(ticket, () =>
                    {
                        controller.InstallByTicket(ticket, node, address);
                    });
                });
            });
        }
예제 #12
0
 private bool SaveAs(ResourceNode r)
 {
     if (r != null)
     {
         using (SaveFileDialog d = new SaveFileDialog())
         {
             d.InitialDirectory = r._origPath.Substring(0, r._origPath.LastIndexOf('\\'));
             d.Filter           = String.Format("(*{0})|*{0}", Path.GetExtension(r._origPath));
             d.Title            = "Please choose a location to save this file.";
             if (d.ShowDialog(this) == DialogResult.OK)
             {
                 r.Merge();
                 r.Export(d.FileName);
                 return(true);
             }
         }
     }
     return(false);
 }
예제 #13
0
 public static void AddResourceNode(string path, string parentName, Dictionary <string, ResourceNode> resourcesTable)
 {
     if (resourcesTable.ContainsKey(path))
     {
         ResourceNode node = resourcesTable [path];
         //如果没有重复则检测父命是否不同,,不同则表示该资源被多个资源依赖
         if (!node.repeat)
         {
             if (node.parent != parentName)
             {
                 node.repeat = true;
             }
         }
     }
     else
     {
         resourcesTable.Add(path, new ResourceNode(path, parentName, false));
     }
 }
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (soundsListBox.SelectedIndex < 0)
            {
                return;
            }

            ResourceNode r = soundsListBox.Items[soundsListBox.SelectedIndex] as ResourceNode;

            using (SaveFileDialog dlg = new SaveFileDialog())
            {
                dlg.FileName = r.Name;
                dlg.Filter   = FileFilters.WAV + "|" + FileFilters.Raw;
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    r.Export(dlg.FileName);
                }
            }
        }
예제 #15
0
        public void save()
        {
            if (sc_selmap == null)
            {
                return;
            }

            ResourceNode toSave = common5 ?? sc_selmap;

            try {
                toSave.Merge();
                toSave.Export(_openFilePath);
            } catch (IOException) {
                toSave.Export(_openFilePath + ".out.pac");
                MessageBox.Show(_openFilePath + " could not be accessed.\nFile written to " + _openFilePath + ".out.pac");
            }

            updateFileSize();
        }
예제 #16
0
        private void AddLink(ResourceNode resourceNode, IResourceProperty property, TreeNode parentNode)
        {
            int    iconIndex       = Core.ResourceIconManager.GetPropTypeIconIndex(property.PropId);
            string linkDisplayName = _resourceStore.PropTypes.GetPropDisplayName(property.PropId);

            Tracer._Trace("LINKNAME = " + linkDisplayName + " LINKID = " + property.PropId.ToString());

            TreeNode treeSubNode =
                new TreeNode(linkDisplayName, iconIndex, iconIndex);
            LinkNode linkNode = resourceNode.AddLink(linkDisplayName, property.Name, property.PropId < 0);

            treeSubNode.Tag = new SerializableTag(linkNode, SerializableTag.Type.Link);
            parentNode.Nodes.Add(treeSubNode);
            _resourceTreeView.SetNodeCheckState(treeSubNode, NodeCheckState.Checked);
            if (AddLinkedResources(treeSubNode, resourceNode.Resource, property.PropId, linkNode) == 0)
            {
                parentNode.Nodes.Remove(treeSubNode);
            }
        }
예제 #17
0
        public static void Copy(string kirbypath, string hatpath)
        {
            ResourceNode kirby   = NodeFactory.FromFile(null, kirbypath);
            string       temphat = Path.GetTempFileName();

            File.Copy(hatpath, temphat, true);
            ResourceNode hat = NodeFactory.FromFile(null, temphat);

            TEX0Node skin = (TEX0Node)kirby.FindChildByType("PlyKirby5KSkin", true, ResourceType.TEX0);

            if (skin == null)
            {
                MessageBox.Show(null, "Could not find the texture PlyKirby5KSkin in " + kirbypath, "Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string temptex = Path.GetTempFileName();

            skin.Export(temptex);

            TEX0Node hatskin = (TEX0Node)hat.FindChildByType("WpnKirbyKirbyMewtwoCap", true, ResourceType.TEX0);

            if (hatskin == null)
            {
                MessageBox.Show(null, "Could not find the texture WpnKirbyKirbyMewtwoCap in " + hatpath, "Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            hatskin.Replace(temptex);
            hat.Merge();
            hat.Export(hatpath);

            hat.Dispose();
            kirby.Dispose();

            File.Delete(temphat);
            File.Delete(temptex);

            MessageBox.Show(Path.GetFileName(hatpath) + " has been updated.");
        }
예제 #18
0
    // =================================
    //  helper methods
    // =================================
    //
    private static bool TreeTraverse(FileStream fs, BinaryReader br, ResourceNode node, uint offset, uint first, uint last)
    {
        for (uint i = first; i < last; i++)
        {
            fs.Seek(offset + 0x20 * i, SeekOrigin.Begin);

            br.BaseStream.Position += 4;  // uint r_junk = fsb.ReadUInt32();
            uint   r_offset = br.ReadUInt32();
            uint   r_size   = br.ReadUInt32();
            uint   r_type   = br.ReadUInt32();
            string r_name   = Core.UnpackByteString(866, br.ReadBytes(16));

            ResourceNode subnode = new ResourceNode();
            subnode.IsRoot           = false;
            subnode.Name             = r_name;
            node.Children[i - first] = subnode;

            if (r_type == 1) // directory
            {
                subnode.IsDirectory = true;
                subnode.Offset      = 0;
                subnode.Size        = 0;
                subnode.Children    = new ResourceNode[r_size];
                if (!TreeTraverse(fs, br, subnode, offset, r_offset, r_offset + r_size))
                {
                    return(false);
                }
            }
            else if (r_type == 0) // file
            {
                subnode.IsDirectory = false;
                subnode.Offset      = r_offset;
                subnode.Size        = r_size;
            }
            else
            {
                return(false);
            }
        }

        return(true);
    }
예제 #19
0
        public virtual void LoadModels(ResourceNode node)
        {
            if (_targetModels == null)
            {
                _targetModels = new List <IModel>();
            }

            List <IModel> modelList = ModelPanel.CollectModels(node);

            foreach (IModel m in modelList)
            {
                AppendTarget(m);
            }
            ModelPanel.RefreshReferences();

            if (TargetModel == null && _targetModels.Count > 0)
            {
                TargetModel = _targetModels[0];
            }
        }
예제 #20
0
    private void MoveTowardsNearestResourceNode()
    {
        if (Vector3.Distance(transform.position, nearestResourceNodeGameobject.transform.position) <= gatheringRange)
        {
            float delta = gatheringRate * Time.deltaTime;
            currentMinerals += delta;
            nearestResourceNode.Mine(delta);

            if (currentMinerals >= maxMinerals)
            {
                currentMinerals = maxMinerals;
                nearestResourceNode.FreeUpGathererPoint(nearestResourceNodeGameobject);

                nearestResourceNode           = null;
                nearestResourceNodeGameobject = null;

                returningToBase = true;
            }
        }
    }
예제 #21
0
        protected static void NewEntryAction(object sender, EventArgs e)
        {
            RSTCWrapper  w = GetInstance <RSTCWrapper>();
            ResourceNode r = w._resource;

            if (((RSTCNode)r).cssList.Children.Count >= 100 || ((RSTCNode)r).randList.Children.Count >= 100)
            {
                return;
            }

            HexEntryBox entryID = new HexEntryBox();

            if (entryID.ShowDialog("New Fighter", "CSS Slot ID:", 2) == DialogResult.OK)
            {
                if (entryID.NewValue != -1)
                {
                    GetInstance <RSTCWrapper>().NewEntry((byte)entryID.NewValue);
                }
            }
        }
예제 #22
0
        private ResourceNode GetDoc(int docId, ResourceTypeEnum resourceTypeEnum)
        {
            ResourceNode resDoc = null;
            try
            {
                if (resourceTypeEnum == ResourceTypeEnum.Resource_Doc)
                    resDoc = resourceLibrary.ResourceModelDictionary[docId];
                else if (resourceTypeEnum == ResourceTypeEnum.Procurement_Language)
                    resDoc = resourceLibrary.GetProcurmentLanguageNode(docId);
                else if (resourceTypeEnum == ResourceTypeEnum.Catalog_Recommendation)
                    resDoc = resourceLibrary.GetCatalogRecommendationsNode(docId);
                return resDoc;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception in getting document. DocId: " + docId, ex);
                return null;
            }

        }
예제 #23
0
            public GameObject getAsset(bool needIncrease)
            {
                if (needIncrease)
                {
                    ++_refCount;
                }

                if (!_queue.isEmpty())
                {
                    ResourceNode node = _queue.poll();

                    _parent.pickOne(id);
                    return(node.obj);
                }
                else
                {
                    //直接从LoadControl取
                    return(LoadControl.getAsset(id));
                }
            }
예제 #24
0
        void SearchResourceTreeNodes(IDsDocument module, ResourceNode resTreeNode)
        {
            var res = options.Filter.GetResult(resTreeNode);

            if (res.FilterType == FilterType.Hide)
            {
                return;
            }

            if (res.IsMatch && (IsMatch(resTreeNode.Name, resTreeNode) || IsMatch(ToString(resTreeNode), null)))
            {
                options.OnMatch(new SearchResult {
                    Context                = options.Context,
                    Object                 = resTreeNode,
                    NameObject             = resTreeNode,
                    ObjectImageReference   = resTreeNode.Icon,
                    LocationObject         = module.ModuleDef,
                    LocationImageReference = options.DotNetImageService.GetImageReference(module.ModuleDef),
                    Document               = module,
                });
            }

            res = options.Filter.GetResult((ResourceElementNode)null);
            if (res.FilterType == FilterType.Hide)
            {
                return;
            }

            var resNodes = new List <ResourceElementNode>();

            options.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => {
                resTreeNode.TreeNode.EnsureChildrenLoaded();
                resNodes.AddRange(resTreeNode.TreeNode.DataChildren.OfType <ResourceElementNode>());
            }));

            foreach (var resElNode in resNodes)
            {
                options.CancellationToken.ThrowIfCancellationRequested();
                SearchResourceElementTreeNode(module, resTreeNode, resElNode);
            }
        }
        private static bool TryDrop(ResourceNode dragging, ResourceNode dropping)
        {
            if (dropping.Parent == null)
            {
                return(false);
            }

            bool good      = false;
            int  destIndex = dropping.Index;

            good = CompareTypes(dragging, dropping);

            //if (dropping.Parent is BRESGroupNode)
            foreach (Type t in dropping.Parent.AllowedChildTypes)
            {
                if (good = CompareToType(dragging.GetType(), t))
                {
                    break;
                }
            }

            if (good)
            {
                if (dragging.Parent != null)
                {
                    dragging.Parent.RemoveChild(dragging);
                }
                if (destIndex < dropping.Parent.Children.Count)
                {
                    dropping.Parent.InsertChild(dragging, true, destIndex);
                }
                else
                {
                    dropping.Parent.AddChild(dragging, true);
                }

                dragging.OnMoved();
            }

            return(good);
        }
예제 #26
0
        public static bool Close(bool force)
        {
            //Have to close external files before the root file
            while (ModelEditControl.Instances.Count > 0)
            {
                var control = ModelEditControl.Instances[0];
                if (control.ParentForm != null)
                {
                    control.ParentForm.Close();
                    if (!control.IsDisposed)
                    {
                        return(false);
                    }
                }
                else if (!control.Close())
                {
                    return(false);
                }
            }

            if (_rootNode != null)
            {
                if (_rootNode.IsDirty && !force)
                {
                    DialogResult res = MessageBox.Show("Save changes?", "Closing", MessageBoxButtons.YesNoCancel);
                    if ((res == DialogResult.Yes && !Save()) || res == DialogResult.Cancel)
                    {
                        return(false);
                    }
                }

                _rootNode.Dispose();
                _rootNode = null;

                MainForm.Instance.Reset();
            }

            _rootPath = null;
            MainForm.Instance.UpdateName();
            return(true);
        }
예제 #27
0
        public DialogResult ShowDialog(ResourceNode o)
        {
            _target = o;

            b = new BackgroundWorker();
            b.RunWorkerCompleted        += b_RunWorkerCompleted;
            b.DoWork                    += b_DoWork;
            b.WorkerSupportsCancellation = true;
            b.WorkerReportsProgress      = false;

            _updating = true;
            Collada.ImportOptions i = BrawlLib.Properties.Settings.Default.ColladaImportOptions;
            numCacheSize.Value       = i._cacheSize;
            numMinStripLen.Value     = i._minStripLen;
            chkPushCacheHits.Checked = i._pushCacheHits;
            chkUseStrips.Checked     = i._useTristrips;
            if (_target is MDL0Node)
            {
                if (((MDL0Node)_target)._objList != null)
                {
                    foreach (MDL0ObjectNode w in ((MDL0Node)_target)._objList)
                    {
                        _results.Add(new ObjectOptimization(w));
                    }
                }

                lblOldCount.Text = (_originalPointCount = ((MDL0Node)o)._numFacepoints).ToString();
            }
            else
            {
                _results.Add(new ObjectOptimization((MDL0ObjectNode)_target));
                lblOldCount.Text = (_originalPointCount = ((MDL0ObjectNode)o)._numFacepoints).ToString();
            }

            chkForceCCW.Checked = i._forceCCW;
            _updating           = false;

            Optimize();

            return(ShowDialog());
        }
예제 #28
0
 public void UpdateSSSStockIcons()
 {
     if (common5 == null)
     {
         MessageBox.Show(this.FindForm(), "common5.pac is not loaded - can't update automatically.\n" +
                         "After saving sc_selcharacter.pac,  update the icons manually by replacing sc_selmap's " +
                         "MiscData[40] with sc_selcharacter's MiscData[90].", "Cannot perform operation",
                         MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     else
     {
         ResourceNode css_stockicons = sc_selcharacter.FindChild("MiscData[90]", false);
         string       tempFile       = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".brres";
         css_stockicons.Export(tempFile);
         ResourceNode sss_stockicons = common5.FindChild("sc_selmap_en/MiscData[40]", false);
         sss_stockicons.Replace(tempFile);
         try {
             File.Delete(tempFile);
         } catch (Exception) { }
     }
 }
예제 #29
0
    private IEnumerator ReturnToBase(float seconds = -1f)
    {
        returnSeconds = seconds;
        if (seconds < 0f)
        {
            returnSeconds = Random.Range(30, 40);
        }
        while (returnSeconds > 0f)
        {
            yield return(new WaitForSeconds(0.1f));

            returnSeconds -= 0.1f;
        }
        if (state == State.Scouting)
        {
            target = null;
            ant.StartCoroutine(EnterBase(ant.GetBaseController().GetPosition()));
            state           = State.MovingToStorage;
            preparingReturn = false;
        }
    }
예제 #30
0
        public static bool Close(bool force)
        {
            if (_rootNode != null)
            {
                if ((_rootNode.IsDirty) && (!force))
                {
                    DialogResult res = MessageBox.Show("Save changes?", "Closing", MessageBoxButtons.YesNoCancel);
                    if (((res == DialogResult.Yes) && (!Save())) || (res == DialogResult.Cancel))
                    {
                        return(false);
                    }
                }

                _rootNode.Dispose();
                _rootNode = null;

                MainForm.Instance.Reset();
            }
            _rootPath = null;
            return(true);
        }
예제 #31
0
        public static IEnumerable <string> GetStrings(ResourceNode resource)
        {
            List <string> strings = new List <string>();

            if (resource.data != null)
            {
                strings.AddRange(GetStrings(resource.data));
            }

            if (resource.children == null)
            {
                return(strings);
            }

            foreach (ResourceNode child in resource.children)
            {
                strings.AddRange(GetStrings(child));
            }

            return(strings);
        }
예제 #32
0
    public static int GetNearbyResourceAmount(ResourceGeneratorData resourceGeneratorData, Vector3 position)
    {
        Collider2D[] collider2DArray = Physics2D.OverlapCircleAll(position, resourceGeneratorData.resourceDetectionRadius);

        int nearbyResourceAmount = 0;

        foreach (Collider2D collider2D in collider2DArray)
        {
            ResourceNode resourceNode = collider2D.GetComponent <ResourceNode>();
            if (resourceNode != null)
            {
                if (resourceNode.resourceType == resourceGeneratorData.resourceType)
                {
                    //Same type!
                    nearbyResourceAmount++;
                }
            }
        }
        nearbyResourceAmount = Mathf.Clamp(nearbyResourceAmount, 0, resourceGeneratorData.maxResourceAmount);
        return(nearbyResourceAmount);
    }
예제 #33
0
        private void LoadAnims(ResourceNode node)
        {
            switch (node.ResourceType)
            {
            case ResourceType.ARC:
            case ResourceType.BRES:
            case ResourceType.BRESGroup:
                foreach (ResourceNode n in node.Children)
                {
                    LoadAnims(n);
                }
                break;

            case ResourceType.CHR0:
                listAnims.Items.Add(new ListViewItem(node.Name, (int)node.ResourceType, _CHRGroup)
                {
                    Tag = node
                });
                break;
            }
        }
예제 #34
0
    private void SpawnMoon(GameObject parentPlanet)
    {
        Vector2 pos = Random.insideUnitCircle;

        pos.Normalize();
        pos *= moonDistance;

        GameObject newMoon = Instantiate(planetTemplate, parentPlanet.transform);

        newMoon.transform.parent = parentPlanet.transform;
        newMoon.transform.Translate(pos);

        newMoon.GetComponent <SpriteRenderer>().sprite = _assets.planetSprites["planet_35"];

        newMoon.transform.localScale /= 2;

        newMoon.name = parentPlanet.gameObject.name + " moon";

        // Add resource and production nodes to the new moon.
        StorageNode    newSNode = Instantiate(storageNodeTemplate, newMoon.transform).GetComponent <StorageNode>();
        ResourceNode   newRNode = Instantiate(resourceNodeTemplates[Random.Range(0, resourceNodeTemplates.Length)], newMoon.transform).GetComponent <ResourceNode>();
        ProductionNode newPNode = Instantiate(factoryTemplates[Random.Range(0, factoryTemplates.Length)], newMoon.transform).GetComponent <ProductionNode>();

        // Connect the industry nodes to the storage node.
        newRNode.connectedStorageNode = newSNode;
        newPNode.connectedStorageNode = newSNode;

        // Give the company ownership of the nodes
        productionCompany.AddEmployee(newSNode.gameObject.GetComponent <Employee>());
        productionCompany.AddEmployee(newRNode.gameObject.GetComponent <Employee>());
        productionCompany.AddEmployee(newPNode.gameObject.GetComponent <Employee>());

        Planet planetScript = newMoon.GetComponent <Planet> () as Planet;

        planetScript.industryNodes.Add(newRNode);
        planetScript.industryNodes.Add(newPNode);
        planetScript.industryNodes.Add(newSNode);

        planets.Add(newMoon.GetComponent <Planet>());
    }
예제 #35
0
파일: Model.cs 프로젝트: kbochenina/Kraken
        private static Dictionary<string, double> AutoAdjustCoefsByHistory(PackageEngine engine, ResourceNode node, Dictionary<string, object> fixedCoefs, Dictionary<string, double> adjustableCoefs)
        {
            lock (_historyLock)
            {
                //Log.Info("Adjusting coefs");
                string packageName = engine.CompiledMode.ModeQName.PackageName.ToLowerInvariant();
                var history = GetHistorySamples(packageName, node.ResourceName, node.NodeName);

                if (history.Length < 1)
                {
                    //Log.Debug("Not enough history samples to adjust coefs");
                    return null;
                }

                if (packageName == "bsm")
                {
                    double[] fTime = history.Select(hs => double.Parse(hs.PackParams["ForecastSize"])).ToArray();
                    double[] cTime = history.Select(hs => hs.CalcTime.TotalSeconds).ToArray();

                    double perf = BSMSimpleEstimator.BsmEstimatePerf(fTime, cTime);
                    double dev = BSMSimpleEstimator.BsmRelativeStDev(perf, fTime, cTime);

                    return new Dictionary<string, double>()
                    {
                        { "Perf", perf },
                        { "D", dev }
                    };
                }
                else
                {
                    Log.Warn("Unsupported package to adjust coefs: " + packageName);
                    return null;
                }
            }
        }
예제 #36
0
		void SearchResourceTreeNodes(IDsDocument module, ResourceNode resTreeNode) {
			var res = options.Filter.GetResult(resTreeNode);
			if (res.FilterType == FilterType.Hide)
				return;

			if (res.IsMatch && (IsMatch(resTreeNode.Name, resTreeNode) || IsMatch(ToString(resTreeNode), null))) {
				options.OnMatch(new SearchResult {
					Context = options.Context,
					Object = resTreeNode,
					NameObject = resTreeNode,
					ObjectImageReference = resTreeNode.Icon,
					LocationObject = module.ModuleDef,
					LocationImageReference = options.DotNetImageService.GetImageReference(module.ModuleDef),
					Document = module,
				});
			}

			res = options.Filter.GetResult((ResourceElementNode)null);
			if (res.FilterType == FilterType.Hide)
				return;

			var resNodes = new List<ResourceElementNode>();
			options.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => {
				resTreeNode.TreeNode.EnsureChildrenLoaded();
				resNodes.AddRange(resTreeNode.TreeNode.DataChildren.OfType<ResourceElementNode>());
			}));

			foreach (var resElNode in resNodes) {
				options.CancellationToken.ThrowIfCancellationRequested();
				SearchResourceElementTreeNode(module, resTreeNode, resElNode);
			}
		}
예제 #37
0
		void SearchResourceElementTreeNode(IDsDocument module, ResourceNode resTreeNode, ResourceElementNode resElNode) {
			var res = options.Filter.GetResult(resElNode);
			if (res.FilterType == FilterType.Hide)
				return;

			if (res.IsMatch) {
				bool m = IsMatch(resElNode.Name, resElNode);
				if (!m) {
					var builtin = resElNode.ResourceElement.ResourceData as BuiltInResourceData;
					if (builtin != null) {
						var val = builtin.Data;
						if (builtin.Code == ResourceTypeCode.TimeSpan)
							val = ((TimeSpan)val).Ticks;
						m = IsMatch(val as string, val);
					}
				}
				if (!m)
					m = IsMatch(ToString(resElNode), null);
				if (m) {
					options.OnMatch(new SearchResult {
						Context = options.Context,
						Object = resElNode,
						NameObject = resElNode,
						ObjectImageReference = resElNode.Icon,
						LocationObject = resTreeNode,
						LocationImageReference = resTreeNode.Icon,
						Document = module,
					});
				}
			}
		}
예제 #38
0
 private string GetPartition(ResourceNode node)
 {
     return node.StaticHardwareParams[PARTITION_NAME_PARAM];
 }
        private void WriteMethod(StreamWriter writer, ResourceNode node, DocumentationHeaderSettings headerSettings, SchemaStore schemaStore, ExampleStore exampleStore, int indent)
        {
            MethodDocumentationAttribute attribute = node.Method.GetCustomAttributes<MethodDocumentationAttribute>().FirstOrDefault();

            if (node.AllowsAnonymous())
            {
                string securitySchemes = "null";
                if (attribute != null && attribute.AllowMultipleSecuritySchemes)
                {
                    securitySchemes = string.Concat(securitySchemes, ", oauth_2_0");
                }
                writer.WriteLine(string.Concat(GetIndentString(indent + 1), "securedBy: [", securitySchemes, "]"));
            }

            if (attribute != null)
            {
                if (attribute.Summary != null)
                {
                    writer.WriteLine(string.Concat(GetIndentString(indent + 1), "description: |"));
                    writer.WriteLine(string.Concat(GetIndentString(indent + 2), attribute.Summary));
                    Example example = exampleStore.GetExample(node.Class, node.Method, "");
                    if (example != null)
                    {
                        writer.WriteLine(GetIndentString(indent + 2));
                        writer.WriteLine(string.Concat(GetIndentString(indent + 2), "For more information, go to ", headerSettings.RepositoryFilesURI, "/", example.DocFilename, "#", example.DocHeading));
                    }
                    else if (attribute.RequestTypes != null)
                    {
                        SerialisationLog.Warning(string.Concat("No example to retrieve link to more information for ", node.Class.Name, ".", node.Method.Name));
                    }
                }
                else
                {
                    SerialisationLog.Warning(string.Concat("No summary for ", node.Class.Name, ".", node.Method.Name));
                }

                if (attribute.ResponseTypes != null && attribute.ResponseTypes.Any(r => r.GetProperties().Any(p => p.PropertyType == typeof(PageInfo))))
                {
                    writer.WriteLine(string.Concat(GetIndentString(indent + 1), "queryParameters: "));
                    foreach (KeyValuePair<string, Dictionary<string, string>> field in headerSettings.PagingFields)
                    {
                        writer.WriteLine(string.Concat(GetIndentString(indent + 2), field.Key, ":"));
                        writer.WriteLine(string.Concat(GetIndentString(indent + 3), "displayName: ", field.Value["displayName"]));
                        writer.WriteLine(string.Concat(GetIndentString(indent + 3), "description: ", field.Value["description"]));
                        writer.WriteLine(string.Concat(GetIndentString(indent + 3), "type: ", field.Value["type"]));
                        writer.WriteLine(string.Concat(GetIndentString(indent + 3), "required: ", field.Value["required"]));
                    }
                }

                if (attribute.RequestTypes != null)
                {
                    writer.WriteLine(string.Concat(GetIndentString(indent + 1), "body: "));

                    foreach (Type requestType in attribute.RequestTypes)
                    {
                        ContentTypeAttribute contentTypeAttribute = requestType.GetCustomAttributes<ContentTypeAttribute>().FirstOrDefault();
                        if (contentTypeAttribute == null)
                        {
                            SerialisationLog.Warning(string.Concat("No ContentTypeAttribute for ", requestType.FullName));
                        }

                        if (attribute.RequestTypeNames != null)
                        {
                            foreach (string contentType in attribute.RequestTypeNames)
                            {
                                TDataExchangeFormat dataExchangeFormat = SerialisationUtils.GetDataExchangeFormatFromContentType(contentType);

                                if (dataExchangeFormat != TDataExchangeFormat.None)
                                {
                                    WriteBody(writer, exampleStore, node, dataExchangeFormat, contentType, TMessageType.Request, requestType, indent + 2);
                                }
                                else
                                {
                                    SerialisationLog.Warning(string.Concat("No supported data exchange format for ", contentType));
                                }
                            }
                        }
                        else
                        {
                            foreach (TDataExchangeFormat dataExchangeFormat in Enum.GetValues(typeof(TDataExchangeFormat)))
                            {
                                if (SerialisationUtils.IsStandardDataExchangeFormat(dataExchangeFormat))
                                {
                                    string contentType = GetContentType(contentTypeAttribute, dataExchangeFormat);
                                    WriteBody(writer, exampleStore, node, dataExchangeFormat, contentType, TMessageType.Request, requestType, indent + 2);
                                }
                            }
                        }
                    }
                }

                writer.WriteLine(string.Concat(GetIndentString(indent + 1), "responses:"));

                HttpStatusCode[] statusCodes = attribute.StatusCodes;
                if (node.Class.GetCustomAttributes<AuthorizeAttribute>().FirstOrDefault() != null)
                {
                    statusCodes = statusCodes.Concat(new[] { HttpStatusCode.Unauthorized, HttpStatusCode.Forbidden }).ToArray();
                }
                foreach (HttpStatusCode statusCode in statusCodes)
                {
                    writer.WriteLine(string.Concat(GetIndentString(indent + 2), (int)statusCode, ":"));
                    WriteDefaultDescription(writer, headerSettings, statusCode, indent + 3);

                    if (SerialisationUtils.IsSuccessStatusCode(statusCode) && attribute.ResponseTypes != null)
                    {
                        writer.WriteLine(string.Concat(GetIndentString(indent + 3), "body:"));
                        foreach (Type responseType in attribute.ResponseTypes)
                        {
                            ContentTypeAttribute contentTypeAttribute = responseType.GetCustomAttributes<ContentTypeAttribute>().FirstOrDefault();
                            if (contentTypeAttribute == null)
                            {
                                SerialisationLog.Warning(string.Concat("No ContentTypeAttribute for ", responseType.FullName));
                            }

                            foreach (TDataExchangeFormat dataExchangeFormat in Enum.GetValues(typeof(TDataExchangeFormat)))
                            {
                                if (SerialisationUtils.IsStandardDataExchangeFormat(dataExchangeFormat))
                                {
                                    string contentType = GetContentType(contentTypeAttribute, dataExchangeFormat);
                                    WriteBody(writer, exampleStore, node, dataExchangeFormat, contentType, TMessageType.Response, responseType, indent + 4);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                SerialisationLog.Warning(string.Concat("No method-level documentation for ", node.Class.Name, ".", node.Method.Name));
            }
        }
예제 #40
0
        private void UploadFile(ResourceNode node, string remotePath, string localPath, string taskId, string farmId)
        {
            var binding = new BasicHttpBinding { MaxReceivedMessageSize = 16777216 };

            binding.MessageEncoding = WSMessageEncoding.Mtom;

            var address = new EndpointAddress("http://" + node.NodeAddress + "/FileService");

            var fsservice = new FileStreamServiceClient(binding, address);

            FileStream fs = null;

            try
            {
                fs = new FileStream(localPath, FileMode.Open, FileAccess.Read);

                var lgth = fs.Length;
                var chunkSize = 67108864;
                var itr = lgth / chunkSize;
                if (itr * chunkSize < lgth)
                {
                    itr++;
                }
                for (int i = 0; i < itr; i++)
                {
                    var sm = new MemoryStream();
                    var leftBytes = Math.Min(fs.Length - chunkSize * i, chunkSize);
                    sm.SetLength(leftBytes);
                    fs.Read(sm.GetBuffer(), 0, (int)leftBytes);
                    fs.Flush();

                    fsservice.SendFileChunkAsStream(new ChunkedFileStreamedMessage(chunkSize, farmId, remotePath, i,
                        taskId, sm));
                    //CopyFile(fs, i, chuckSize);
                    Log.Info("send " + i);
                    sm.Close();
                }

            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                throw;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
예제 #41
0
        protected virtual string MakeScript(PackageOnNode pack, string cmdLine, ResourceNode node, string clusterHomeFolder)
        {
            string workDir = clusterHomeFolder.TrimEnd(new[] { '/', '\\' });
            string scriptPath = workDir + "/run.sh";

            var scriptContent = new StringBuilder();
            scriptContent.Append("#!/bin/bash\n");
            scriptContent.Append("#SBATCH --partition=" + GetPartition(node) + "\n");
            scriptContent.Append(@"#SBATCH --workdir=""" + workDir + "\"\n");
            scriptContent.Append(@"#SBATCH --output=std.out" + "\n");
            //scriptContent.Append("#SBATCH --immediate\n"); // не ставить в очередь, а упасть, если нету сразу доступных ресурсов
            //scriptContent.Append("#SBATCH --no-requeue\n"); // не перезапускать в случа падения
            //scriptContent.Append("#SBATCH --wait-all-nodes=1\n"); // не запускать, пока не будут готовы все узлы

            //scriptContent.Append("#SBATCH --gres\n"); // запрос ресурсов
            //scriptContent.Append("#SBATCH --nodes=1-1\n"); //min-max
            //scriptContent.Append("#SBATCH --nodelist=" + node.NodeName + "\n"); // String.Join(",", nodes.Select(n => n.NodeName))

            scriptContent.Append("cd " + workDir + "\n");
            scriptContent.AppendFormat("date +%s%N > {0}\n", ClavireStartFileName);

            foreach (var pair in pack.EnvVars)
                scriptContent.AppendFormat("export {0}={1}\n", pair.Key, pair.Value);

            // -n = do not override files, so user's input file doesn't vanish => copying startup files in reverse order
            foreach (string path in pack.CopyOnStartup.Reverse())
                scriptContent.Append("cp -r -n " + path + " ./\n");

            scriptContent.Append(cmdLine);
            scriptContent.AppendFormat("\ndate +%s%N > {0}\n", ClavireFinishFileName);

            string scriptFilePathLocal = Path.GetTempFileName();
            File.WriteAllText(scriptFilePathLocal, scriptContent.ToString());
            //ScpCopy(node, scriptPath, scriptFilePathLocal);
            UploadFile(node, scriptPath, scriptFilePathLocal);
            File.Delete(scriptFilePathLocal);

            return scriptPath;
        }
예제 #42
0
        public void InstallByTicket(InstallationTicket ticket, ResourceNode node, string localAddress)
        {
            var fileName = Path.GetFileName(localAddress);
                   var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(localAddress);
                   var remotePath = Path.Combine(ticket.FolderToInstall, fileName).Replace('\\','/');
                   this.UploadFile(node, remotePath, localAddress);

                   string result = SshExec(node,
                       string.Format(SshInstallationCommand.InstallUploadedPackage, remotePath, ticket.FolderToInstall, fileNameWithoutExtension));
        }
        private void WriteResources(StreamWriter writer, ResourceNode node, DocumentationHeaderSettings headerSettings, SchemaStore schemaStore, ExampleStore exampleStore, int indent)
        {
            if (node.Parent != null)
            {
                string key = node.Key;
                if (node.Method == null)
                {
                    key = string.Concat("/", key);
                }
                writer.WriteLine(string.Concat(GetIndentString(indent), key, ":"));

                if (node.Class != null && node.HasMethods())
                {
                    // top level resource
                    RouteDocumentationAttribute attribute = node.Class.GetCustomAttributes<RouteDocumentationAttribute>().Where(a => a.Route != null && a.Route.EndsWith(node.GetRoute())).FirstOrDefault();
                    if (attribute != null)
                    {
                        if (attribute.DisplayName != null)
                        {
                            writer.WriteLine(string.Concat(GetIndentString(indent + 1), "displayName: ", attribute.DisplayName));
                        }
                        if (attribute.Summary != null)
                        {
                            writer.WriteLine(string.Concat(GetIndentString(indent + 1), "description: ", attribute.Summary));
                        }
                    }
                    else
                    {
                        SerialisationLog.Warning(string.Concat("No route documentation for route '", node.GetRoute(), "' in ", node.Class.Name));
                    }
                }

                if (node.Method != null)
                {
                    WriteMethod(writer, node, headerSettings, schemaStore, exampleStore, indent);
                }
                else if (node.Class != null)
                {
                    NamedParameterDocumentationAttribute attribute = node.Class.GetCustomAttributes<NamedParameterDocumentationAttribute>()
                        .Where(a => string.Concat("{", a.Name, "}").Equals(node.Key)).FirstOrDefault();
                    if (attribute != null)
                    {
                        writer.WriteLine(string.Concat(GetIndentString(indent + 1), "uriParameters:"));
                        writer.WriteLine(string.Concat(GetIndentString(indent + 2), attribute.Name, ":"));

                        if (attribute.DisplayName != null)
                        {
                            writer.WriteLine(string.Concat(GetIndentString(indent + 3), "displayName: ", attribute.DisplayName));
                        }
                        if (attribute.Type != TNamedParameterType.NotSet)
                        {
                            writer.WriteLine(string.Concat(GetIndentString(indent + 3), "type: ", attribute.Type.ToString().ToLower()));
                        }
                        if (attribute.Description != null)
                        {
                            writer.WriteLine(string.Concat(GetIndentString(indent + 3), "description: ", attribute.Description));
                        }
                    }
                }
            }
            foreach (ResourceNode child in node.Children.Values)
            {
                WriteResources(writer, child, headerSettings, schemaStore, exampleStore, indent + 1);
            }
        }
 //private ConcurrentStack<>
 protected PackageOnNode PackageByName(ResourceNode node, string packageName)
 {
     return node.Packages.First(p => String.Equals(p.Name, packageName, StringComparison.InvariantCultureIgnoreCase));
 }
 public void Serialise(StreamWriter writer, ResourceNode tree, DocumentationHeaderSettings headerSettings, SchemaStore schemaStore, ExampleStore exampleStore)
 {
     throw new NotSupportedException();
 }
예제 #46
0
        private void DownloadFile(ResourceNode node, string remotePath, string localPath, ulong taskId, string farmId)
        {
            var binding = new BasicHttpBinding { MaxReceivedMessageSize = 16777216 };

            binding.MessageEncoding = WSMessageEncoding.Mtom;

            var address = new EndpointAddress("http://" + node.NodeAddress + "/FileService");

            var fsservice = new FileStreamServiceClient(binding, address);

            int m = 0;
            bool finished = false;

            while (!finished)
            {

                const int bufferSize = 2048;
                var buffer = new byte[bufferSize];

                var chunkSize = 67108864;
                using (var outputStream = new FileStream(localPath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    while (!finished)
                    {

                        //(chunkSize, farmId, remotePath, i, taskId, sm))
                        Stream resFileStream = fsservice.GetFileChunkAsStream(new GetFileChunkAsStreamRequest(remotePath,taskId,m,chunkSize)).GetFileChunkAsStreamResult;

                        //resFileStream.Position = m;
                        var bytesRead = resFileStream.Read(buffer, 0, bufferSize);
                        var readFilebytes = 0;
                        while (bytesRead > 0 && readFilebytes < chunkSize)
                        {
                            outputStream.Write(buffer, 0, bytesRead);
                            bytesRead = resFileStream.Read(buffer, 0, bufferSize);
                            readFilebytes += bufferSize;
                        }
                        if (bytesRead == 0 && readFilebytes < chunkSize)
                        {
                            finished = true;
                        }
                        m++;
                        Console.WriteLine(m);
                        resFileStream.Close();
                    }
                    outputStream.Close();
                }
            }
        }
 public void Serialise(StreamWriter writer, ResourceNode tree, DocumentationHeaderSettings headerSettings, SchemaStore schemaStore, ExampleStore exampleStore)
 {
     WriteHeader(writer, headerSettings, schemaStore);
     WriteResources(writer, tree, headerSettings, schemaStore, exampleStore, -1);
 }
예제 #48
0
 public override string ExecuteRun(ResourceNode node, string scriptPath)
 {
     return SshExec(node, GetRunCommand(), scriptPath + " " + UnixPbsCommands.SeparateThread);
 }
		public virtual DocumentTreeNodeFilterResult GetResult(ResourceNode node) => new DocumentTreeNodeFilterResult();
		public virtual DocumentTreeNodeFilterResult GetResult(ResourceNode node) => filter.GetResult(node);
예제 #51
0
        protected void UploadFile(ResourceNode node, string remotePath, string localPath)
        {
            SecureCopier copier = null;

            try
            {
                copier = _copierPool.GetSshSession(true, node);
                copier.UploadFile(node, remotePath, localPath);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            finally
            {
                if (copier != null)
                    _copierPool.PushSession(copier);
            }
        }
 private void WriteBody(StreamWriter writer, ExampleStore exampleStore, ResourceNode node, TDataExchangeFormat dataExchangeFormat, string contentType, TMessageType messageType, Type bodyObjectType, int indent)
 {
     writer.WriteLine(string.Concat(GetIndentString(indent), contentType, ":"));
     if (SerialisationUtils.IsStandardDataExchangeFormat(dataExchangeFormat))
     {
         writer.WriteLine(string.Concat(GetIndentString(indent + 1), "schema: ", GetSchemaKey(bodyObjectType, dataExchangeFormat)));
     }
     WriteExample(writer, exampleStore, node.Class, node.Method, contentType, messageType, dataExchangeFormat, indent + 1);
 }
예제 #53
0
        //todo nbutakov change
        public NodeInfo GetCurrentResourceInfo(ResourceNode node)
        {
            //            Dictionary<string, NodeInfo> resourceInfo = new Dictionary<string, NodeInfo>();
            string sshCommand = GetNodeInfoCommand();

            //            foreach (var node in resource.Nodes)
            //            {
                var data = SshExec(node, sshCommand);

                //resourceInfo.Add(node.NodeName, ObtainInfo(data));
            //            }

            return (NodeInfo)ObtainInfo(data, typeof(NodeInfo)); //resourceInfo;
        }
		public virtual DocumentTreeNodeFilterResult GetResult(ResourceNode node) => new DocumentTreeNodeFilterResult(FilterType.Hide, false);
예제 #55
0
        protected string SshExec(ResourceNode node, string command, string args = "", AErrorResolver errorResolver = null)
        {
            int sshResult = 0;
            string sshOut = "";
            string sshErr = "";
            string sshCommand = command + " " + args;

            var sshCommands = new[] {sshCommand};

            if (sshCommand.Contains('\n'))
            {
                sshCommands = sshCommand.Split('\n');
            }
            /*
            var connectionInfo = new Ssh2.ConnectionInfo(node.Services.ExecutionUrl, node.Credentials.Username, new Ssh2.AuthenticationMethod[] {
                new Ssh2.KeyboardInteractiveAuthenticationMethod(node.Credentials.Username),
                new Ssh2.PasswordAuthenticationMethod(node.Credentials.Username, node.Credentials.Password)
            });
            */

            var sshExec = _sshPool.GetSshSession(true, node);

                //Ssh.SshExec(node.NodeAddress, node.Credentials.Username, node.Credentials.Password);
            //Log.Info("Ssh command to execute : " + command + " ");
            try
            {
                foreach (var s in sshCommands)
                {
                    if (!s.Contains("pbsnodes") && !s.Contains("qstat"))
                        Log.Info("Ssh command to execute: " + s);

                    /*
                    sshExec.Connect();
                    sshResult = sshExec.RunCommand(sshCommand, ref sshOut, ref sshErr);
                    /**/

                    var ssh = sshExec.RunCommand(s); // todo : using (var ssh = new...)
                    //ssh.Execute();

                    sshResult = ssh.ExitStatus;
                    sshErr = ssh.Error;
                    sshOut = ssh.Result;

                    if (!String.IsNullOrWhiteSpace(sshErr))
                    {
                        break;
                    }
                }

                /**/
            }
            catch (Exception e)
            {
                Log.Warn(e.Message);
                throw;
            }
            finally
            {
                /*/*
                sshExec.Close();
                /*
                if (sshExec.IsConnected)
                    sshExec.Disconnect();
                /***/
                _sshPool.PushSession(sshExec);
            }

            //sshErr = sshErr.Replace('.', ' '); // Cert creation emits many dots
            if (errorResolver == null && sshResult != 0 /*!String.IsNullOrWhiteSpace(sshErr)*/)
            {
                throw new Exception(String.Format("Ssh execution error. Command: \"{0}\". Code: {1}, StdOut: {2}, StdErr: {3}", sshCommand, sshResult, sshOut, sshErr));
            }
            if (errorResolver != null && !String.IsNullOrWhiteSpace(sshErr))
            {
                var resIn = new Dictionary<String, Object>();
                resIn[AErrorResolver.SSH_RESULT] = sshOut;
                resIn[AErrorResolver.SSH_EXIT_CODE] = sshResult;
                resIn[AErrorResolver.SSH_COMMAND] = sshCommand;
                resIn[AErrorResolver.SSH_ERROR] = sshErr;

                errorResolver.Resolve(resIn);
            }

            if (!command.Contains("pbsnodes") && !command.Contains("qstat"))
                Log.Info("ssh execution result : " + sshOut);

            return sshOut;
        }
예제 #56
0
파일: Model.cs 프로젝트: kbochenina/Kraken
        private static Dictionary<string, object> GetModelCoefs(PackageEngine engine, ResourceNode node)
        {
            var fixedCoefs = new Dictionary<string, object>(engine.CompiledMode.Models.DefaultCoeffs);
            var adjustableCoefs  = new Dictionary<string, double>();

            string packageName = engine.CompiledMode.ModeQName.PackageName; // engineState._taskDescription.Package
            var packParams = node.PackageByName(packageName).Params;
            foreach (string paramKey in packParams.Keys)
            {
                string paramValue = packParams[paramKey];
                double paramValueAsDouble;
                bool isDouble = double.TryParse(paramValue,
                    System.Globalization.NumberStyles.Float,
                    System.Globalization.CultureInfo.InvariantCulture.NumberFormat,
                    out paramValueAsDouble);

                if (paramKey.ToLowerInvariant().StartsWith(FIXED_COEF_PREFIX))
                {
                    string coefName = paramKey.Remove(0, FIXED_COEF_PREFIX.Length);
                    if (isDouble)
                        fixedCoefs[coefName] = paramValueAsDouble;
                    else
                        fixedCoefs[coefName] = paramValue;
                }
                else
                if (paramKey.ToLowerInvariant().StartsWith(ADJUSTABLE_COEF_PREFIX))
                {
                    string coefName = paramKey.Remove(0, ADJUSTABLE_COEF_PREFIX.Length);
                    if (isDouble)
                        adjustableCoefs[coefName] = paramValueAsDouble;
                    else
                    {
                        fixedCoefs[coefName] = paramValue;
                        Log.Warn(String.Format(
                            "Cannot adjust param '{0}' for pack '{1}' on resource node '{2}.{3}' because it's value is not number",
                            paramKey, packageName,
                            node.ResourceName, node.NodeName
                        ));
                    }
                }
            }

            var adjustedCoefs = AutoAdjustCoefsByHistory(engine, node, fixedCoefs, adjustableCoefs) ?? new Dictionary<string, double>();
            if (adjustableCoefs.Any())
                Log.Info("Model coefs were adjusted");

            var newCoefNames = adjustedCoefs.Keys.Except(adjustableCoefs.Keys);
            if (newCoefNames.Any())
                Log.Warn("Autoadjust created new coefs (ignoring them): " + String.Join(", ", newCoefNames));

            var modelCoefs = new Dictionary<string, object>(fixedCoefs);
            foreach (var coefName in adjustableCoefs.Keys)
            {
                if (adjustedCoefs.ContainsKey(coefName))
                    modelCoefs[coefName] = adjustedCoefs[coefName];
                else
                {
                    modelCoefs[coefName] = adjustableCoefs[coefName];
                    Log.Warn("Coef " + coefName + " was not returned as adjusted. Using non-adjusted value.");
                }
            }
            return modelCoefs;
        }
예제 #57
0
 public void InstallByTicket(InstallationTicket ticket, ResourceNode node, string localAddress)
 {
     var installer = new WindowsInstallerImpl(this.UploadFile);
     installer.InstallByTicket(ticket, node, localAddress);
 }
		public override DocumentTreeNodeFilterResult GetResult(ResourceNode node) {
			var visibleFlags = VisibleMembersFlags.Resource | VisibleMembersFlags.ResourceElement |
								VisibleMembersFlags.Attributes;
			bool isMatch = (flags & VisibleMembersFlags.Resource) != 0;
			if ((flags & visibleFlags) == 0)
				return new DocumentTreeNodeFilterResult(FilterType.Hide, isMatch);
			if (isMatch)
				return new DocumentTreeNodeFilterResult(FilterType.Visible, isMatch);
			return new DocumentTreeNodeFilterResult(FilterType.CheckChildren, isMatch);
		}
예제 #59
0
        //todo nbutakov change
        private static StatisticsServiceClient GetStatisticsServiceClient(ResourceNode node)
        {
            var binding = new BasicHttpBinding { MaxReceivedMessageSize = 16777216 };

            var address = new EndpointAddress("http://" + node.NodeAddress + "/Statistics");

            return new StatisticsServiceClient(binding, address);
        }
예제 #60
0
		public AddUpdatedNodesHelper(Lazy<IMethodAnnotations> methodAnnotations, Lazy<IResourceNodeFactory> resourceNodeFactory, IDocumentTreeView documentTreeView, ModuleDocumentNode modNode, ModuleImporter importer) {
			this.modNode = modNode;
			var dict = new Dictionary<string, List<TypeDef>>(StringComparer.Ordinal);
			foreach (var t in importer.NewNonNestedTypes) {
				List<TypeDef> list;
				var ns = (t.TargetType.Namespace ?? UTF8String.Empty).String;
				if (!dict.TryGetValue(ns, out list))
					dict[ns] = list = new List<TypeDef>();
				list.Add(t.TargetType);
			}
			newTypeNodeCreators = dict.Values.Select(a => new TypeNodeCreator(modNode, a)).ToArray();
			existingTypeNodeUpdaters = importer.MergedNonNestedTypes.Select(a => new ExistingTypeNodeUpdater(methodAnnotations, modNode, a)).ToArray();
			if (!importer.MergedNonNestedTypes.All(a => a.TargetType.Module == modNode.Document.ModuleDef))
				throw new InvalidOperationException();
			newAssemblyDeclSecurities = importer.NewAssemblyDeclSecurities;
			newAssemblyCustomAttributes = importer.NewAssemblyCustomAttributes;
			newModuleCustomAttributes = importer.NewModuleCustomAttributes;
			if (newAssemblyDeclSecurities != null)
				origAssemblyDeclSecurities = modNode.Document.AssemblyDef?.DeclSecurities.ToArray();
			if (newAssemblyCustomAttributes != null)
				origAssemblyCustomAttributes = modNode.Document.AssemblyDef?.CustomAttributes.ToArray();
			if (newModuleCustomAttributes != null)
				origModuleCustomAttributes = modNode.Document.ModuleDef.CustomAttributes.ToArray();

			if (importer.NewResources.Length != 0) {
				var module = modNode.Document.ModuleDef;
				var rsrcListNode = GetResourceListTreeNode(modNode);
				Debug.Assert(rsrcListNode != null);
				if (rsrcListNode != null) {
					var newNodes = new ResourceNode[importer.NewResources.Length];
					var treeNodeGroup = documentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.ResourceTreeNodeGroup);
					for (int i = 0; i < newNodes.Length; i++)
						newNodes[i] = (ResourceNode)documentTreeView.TreeView.Create(resourceNodeFactory.Value.Create(module, importer.NewResources[i], treeNodeGroup)).Data;
					resourceNodeCreator = new ResourceNodeCreator(rsrcListNode, newNodes);
				}
			}
		}