├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── Rakefile ├── knife-depsolver.gemspec └── lib ├── chef └── knife │ ├── depselector.rb │ └── depsolver.rb └── knife-depsolver └── version.rb /.gitignore: -------------------------------------------------------------------------------- 1 | pkg 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | ## 2.2.0 (2017-05-19) 4 | 5 | * Rename --print-trimmed-universe to --filter-universe 6 | * Remove --env-constraints-filter-universe option 7 | * Don't filter cookbook universe by run list when run list is empty 8 | * Add --version-pin-cookbooks option 9 | 10 | ## 2.1.0 (2017-05-15) 11 | 12 | * Replace --print-constrained-cookbook-set with --print-trimmed-universe 13 | 14 | ## 2.0.3 (2017-05-12) 15 | 16 | * Correctly print version if patch level was missing 17 | * Only set DepSelector::Debug.log.level if DepSelector::Debug is defined 18 | * Improve regex to avoid unwanted string replacement 19 | 20 | ## 2.0.2 (2017-05-11) 21 | 22 | * Set DepSelector log level to INFO 23 | * Add --print-constrained-cookbook-set option 24 | 25 | ## 2.0.1 (2017-05-02) 26 | 27 | * Minor change to file name timestamp format 28 | 29 | ## 2.0.0 (2017-05-02) 30 | 31 | * Set the node's environment to ensure accurate run_list expansion 32 | * Add --capture option to capture all relevant information for local depsolver usage 33 | * Add ability to use Chef DK's local depsolver to make calculations identical to a Chef Server 34 | * Add --timeout option 35 | * Add --csv-universe-to-json option for converting SQL captured cookbook universe to JSON 36 | * Add --env-constraints-filter-universe option 37 | 38 | ## 1.0.1 (2016-03-17) 39 | 40 | * Add error handling 41 | 42 | ## 1.0.0 (2016-03-17) 43 | 44 | * Initial release 45 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## knife-depsolver 2 | 3 | Knife plugin that calculates Chef cookbook dependencies for a given run_list. 4 | 5 | Some features of knife-depsolver: 6 | 7 | 1. Able to capture all relevant information and use Chef DK's embedded depsolver. 8 | 2. JSON output for easy parsing 9 | 3. API error handling provides very helpful information 10 | 4. Accepts cookbook version constraints directly in the run_list 11 | 5. Useful information such as environment cookbook version constraints, expanded run_list and elapsed time for depsolver request 12 | 6. Ordering of depsolver results is maintained rather than sorted so you see what really gets passed to the chef-client 13 | 14 | ### How Does Cookbook Dependency Solving Work? 15 | 16 | During a chef-client run the chef-client expands the node's run_list which means the chef-client recursively expands 17 | any existing role run_lists until the expanded run_list only consists of a list of cookbook recipes. 18 | 19 | Then chef-client sends the expanded run_list to the Chef Server's `/organizations/ORGNAME/environments/ENVNAME/cookbook_versions` 20 | API endpoint which is serviced by opscode-erchef. 21 | 22 | opscode-erchef gets the ORGNAME organization's cookbook universe (cookbook dependency info for every version of every cookbook) 23 | and the ENVNAME environment's cookbook version constraints from the database. 24 | 25 | opscode-erchef sends the expanded run_list, environment constraints and cookbook universe to a ruby process running the 26 | [depselector.rb script](https://github.com/chef/chef-server/blob/12.9.1/src/oc_erchef/apps/chef_objects/priv/depselector_rb/depselector.rb). 27 | 28 | This script uses the [dep_selector gem](https://github.com/chef/dep-selector) to build a dependency graph that filters out any 29 | cookbook versions that don't satisfy the environment cookbook version constraints. 30 | 31 | The dep_selector gem re-formulates the dependency graph and the solution constraints as a CSP and off-loads the hard work to 32 | [Gecode](http://www.gecode.org/), a fast, license-friendly solver written in C++. If Gecode returns a solution then that is used by 33 | opscode-erchef to send a list of cookbook file metadata back to the chef-client so it can synchronize its cookbook cache. 34 | 35 | ### Install 36 | 37 | ``` 38 | chef gem install knife-depsolver 39 | ``` 40 | 41 | *Currently NOT compatible with Windows Chef DK* 42 | 43 | ### Using knife-depsolver with Chef Server's depsolver 44 | 45 | Find the depsolver solution for a node's run_list. 46 | 47 | ``` 48 | knife depsolver -n demo-node 49 | ``` 50 | 51 | Find the depsolver solution for an arbitrary run_list. 52 | Specifying roles, recipes and even cookbook version constraints is allowed. 53 | 54 | ``` 55 | knife depsolver 'role[base],cookbook-B,cookbook-A::foo@3.1.4,cookbook-R' 56 | ``` 57 | 58 | The "-E " option can be added to use a specific environment's cookbook version constraints. 59 | 60 | ``` 61 | knife depsolver -E production -n demo-node 62 | OR 63 | knife depsolver -E production 'role[base],cookbook-B,cookbook-A::foo@3.1.4,cookbook-R' 64 | ``` 65 | 66 | ### Using knife-depsolver with Chef DK's embedded depsolver 67 | 68 | Mikael Lagerkvist is one of the authors of gecode, the constraint solver used by Chef's depsolver, and he says in the following mail list posts that "Debugging failures in constraint programs is unfortunately a very hard problem." 69 | 70 | http://www.mail-archive.com/users@gecode.org/msg00110.html 71 | 72 | https://www.mail-archive.com/users@gecode.org/msg00076.html 73 | 74 | In the first post he goes on to talk about the importance of troubleshooting the whole problem set. With regards to the cookbook depsolver this translates to the importance of troubleshooting the whole run list. When troubleshooting a depsolver issue it is best to keep the run list the same and make changes to the environment cookbook version constraints or possibly to the cookbook universe. 75 | 76 | knife-depsolver can provide many troubleshooting options by using the depsolver embedded in your workstation's Chef DK to make an identical calculation as the Chef Server. 77 | 78 | #### Use the appropriate version of Chef DK 79 | 80 | First, you need to make sure that your version of Chef DK is using the same version of the dep_selector gem as your version of Chef Server. If your Chef DK is using a different version of the dep_selector gem then knife-depsolver's calculations will not be identical to the Chef Server's calculations which will confuse troubleshooting efforts. 81 | 82 | | dep_selector gem | Chef Server | Chef DK | 83 | | ---------------- | ----------- | ---------- | 84 | | 1.0.3 | <= 12.8.0 | <= 0.16.28 | 85 | | 1.0.4 | >= 12.9.0 | >= 0.17.17 | 86 | 87 | #### --capture 88 | 89 | Once you are sure you are using the correct version of Chef DK and you have installed the knife-depsolver plugin you can use the "--capture" option which queries the Chef Server and creates a separate file on the workstation for each of the following pieces of information. 90 | 91 | 1. environment cookbook version constraints 92 | 2. cookbook universe 93 | 3. expanded run list 94 | 95 | The name of each file includes a creation timestamp and a SHA-1 checksum of the contents of the file. These can help during the troubleshooting process to make sure we know when the capture was done and whether anyone has modified the contents of the file. 96 | 97 | For example: 98 | 99 | ``` 100 | knife depsolver -E production -n demo-node --capture 101 | OR 102 | knife depsolver -E production 'role[base],cookbook-B,cookbook-A::foo@3.1.4,cookbook-R' --capture 103 | ``` 104 | 105 | #### --env-constraints, --universe and --expanded-run-list 106 | 107 | Now use the "--env-constraints", "--universe" and "--expanded-run-list" options to provide the information required for local depsolver calculations. 108 | 109 | For example: 110 | 111 | ``` 112 | knife depsolver --expanded-run-list expanded-run-list-2017-05-01-18.52.40-387d90499514747792a805213c30be13d830d31f.txt --universe my-org-universe-2017-05-01-18.52.40-1c8e59e23530b1e1a8e0b3b3cc5236a29c84e469.txt --env-constraints production-environment-2017-05-01-18.52.40-5f5843d819ecb0b174f308d76d4336bb7bbfacbf.txt 113 | ``` 114 | 115 | This makes it easy to modify the input files to see the impact on the depsolver. 116 | 117 | #### --timeout 118 | 119 | Sometimes it can help to give the depsolver more than the default five seconds to perform its calculations. This can be done by using the "--timeout " option to change the depsolver timeout. 120 | 121 | ``` 122 | knife depsolver --expanded-run-list expanded-run-list-2017-05-01-18.52.40-387d90499514747792a805213c30be13d830d31f.txt --universe my-org-universe-2017-05-01-18.52.40-1c8e59e23530b1e1a8e0b3b3cc5236a29c84e469.txt --env-constraints production-environment-2017-05-01-18.52.40-5f5843d819ecb0b174f308d76d4336bb7bbfacbf.txt --timeout 120 123 | ``` 124 | 125 | #### --filter-universe 126 | 127 | Combine the --universe and the --filter-universe options with --env-constraints and/or --expanded-run-list options to filter the cookbook universe based on the environment cookbook version constraints and/or the expanded run list. This provides the ability to focus only on relevant information that would be sent to the depsolver without actually triggering the depsolver calculation. This is especially helpful when the depsolver isn't returning any results because it can't calculate a solution in a reasonable amount of time. 128 | 129 | ``` 130 | knife depsolver --expanded-run-list expanded-run-list-2017-05-01-18.52.40-387d90499514747792a805213c30be13d830d31f.txt --universe my-org-universe-2017-05-01-18.52.40-1c8e59e23530b1e1a8e0b3b3cc5236a29c84e469.txt --env-constraints production-environment-2017-05-01-18.52.40-5f5843d819ecb0b174f308d76d4336bb7bbfacbf.txt --filter-universe > filtered-universe.txt 131 | ``` 132 | 133 | Now you can review the output to see if you can find anything that could be causing problems for the depsolver. You can make changes to the input files to see the impact on the list of cookbooks that would be sent to the depsolver. 134 | 135 | If necessary you could also use the results along with the --version-pin-cookbooks option to create an environment input file that pins a version for each cookbook. Then you can modify that set of version constraints and run the depsolver in an effort to get a solution in a reasonable amount of time or to isolate the problem. 136 | 137 | #### --version-pin-cookbooks 138 | 139 | The --version-pin-cookbooks option takes a filename as an argument. The file must be in the JSON format of a cookbook universe or filtered cookbook universe. The --version-pin-cookbooks option creates an environment JSON file with cookbook version constraints for that pin every cookbook to its latest version. This environment file can then be used with the --env-constraints option to provide a strictly constrained starting point when troubleshooting a depsolver issue. 140 | 141 | ``` 142 | knife depsolver --version-pin-cookbooks filtered-universe.txt > version-pinned-cookbooks.txt 143 | ``` 144 | 145 | #### /tmp/DepSelectorDebugOn 146 | 147 | If you really want to enable the dep_selector gem's debug level output then you can simply create the `touch /tmp/DepSelectorDebugOn` file on your workstation's disk. 148 | 149 | ``` 150 | touch /tmp/DepSelectorDebugOn 151 | ``` 152 | 153 | ### Chef Server < 12.4.0 154 | 155 | knife-depsolver requires cookbook universe data in order to use Chef DK's embedded depsolver. The "/universe" API endpoint was added in the Chef Server 12.4.0 release. 156 | 157 | If you are using a version of Chef Server older than 12.4.0 then you can run the following command on your Chef Server to extract the cookbook universe directly from the database in CSV format. 158 | 159 | ``` 160 | export ORGNAME=demo 161 | 162 | cat < universe.csv 163 | SELECT cvd.name, 164 | cvd.major || '.' || cvd.minor || '.' || cvd.patch AS version, 165 | updated_at, 166 | dependencies 167 | FROM cookbook_version_dependencies cvd 168 | INNER JOIN cookbooks ckbks 169 | ON cvd.org_id = ckbks.org_id 170 | AND cvd.name = ckbks.name 171 | INNER JOIN cookbook_versions cv 172 | ON ckbks.id = cv.cookbook_id 173 | AND cvd.major = cv.major 174 | AND cvd.minor = cv.minor 175 | AND cvd.patch = cv.patch 176 | WHERE cvd.org_id = (SELECT id 177 | FROM orgs 178 | WHERE name = '$ORGNAME' 179 | LIMIT 1) 180 | ORDER BY updated_at DESC; 181 | EOF 182 | ``` 183 | 184 | Then you can run the following command to convert it to the normal JSON format. 185 | 186 | ``` 187 | knife depsolver --csv-universe-to-json universe.csv 188 | ``` 189 | 190 | If the Chef Server doesn't have the "chef-server-ctl psql" command available then you can try replacing that line with the following. 191 | 192 | ``` 193 | cat < universe.csv 194 | ``` 195 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require "bundler/gem_tasks" 2 | -------------------------------------------------------------------------------- /knife-depsolver.gemspec: -------------------------------------------------------------------------------- 1 | $:.unshift(File.dirname(__FILE__) + '/lib') 2 | require 'knife-depsolver/version' 3 | 4 | Gem::Specification.new do |s| 5 | s.name = 'knife-depsolver' 6 | s.version = KnifeDepsolver::VERSION 7 | s.platform = Gem::Platform::RUBY 8 | s.extra_rdoc_files = ["README.md", "LICENSE", "CHANGELOG.md" ] 9 | s.summary = "Knife plugin that uses Chef Server to calculate cookbook dependencies for a given run_list." 10 | s.description = s.summary 11 | s.authors = [ "Jeremiah Snapp" ] 12 | s.email = "support@chef.io" 13 | s.homepage = "https://github.com/jeremiahsnapp/knife-depsolver" 14 | s.require_path = 'lib' 15 | s.files = %w(LICENSE README.md) + Dir.glob("lib/**/*") 16 | end 17 | -------------------------------------------------------------------------------- /lib/chef/knife/depselector.rb: -------------------------------------------------------------------------------- 1 | # I pulled and slightly modified this script from 2 | # https://github.com/chef/dep-selector/blob/master/scripts/depselector.rb 3 | # which was originally pulled and slightly modified from 4 | # https://github.com/chef/chef-server/blob/12.9.0/src/oc_erchef/apps/chef_objects/priv/depselector_rb/depselector.rb 5 | 6 | # Test script to take a dependency graph in JSON format and solve it 7 | # ensure that the Gemfile is in the cwd 8 | # Dir.chdir(File.dirname(__FILE__)) 9 | 10 | # require 'json' 11 | # require 'pp' 12 | require 'dep_selector' 13 | # require 'pry' 14 | 15 | def translate_constraint(constraint) 16 | case constraint 17 | when Symbol 18 | case constraint 19 | when :gt then ">" 20 | when :gte then ">=" 21 | when :lt then "<" 22 | when :lte then "<=" 23 | when :eq then "=" 24 | when :pes then "~>" 25 | else constraint.to_s 26 | end 27 | when NilClass 28 | "=" 29 | else 30 | constraint 31 | end 32 | end 33 | 34 | def constraint_to_str(constraint, constraint_version) 35 | return nil unless constraint_version 36 | "#{translate_constraint(constraint)} #{constraint_version}" 37 | end 38 | 39 | def solve(data) 40 | begin 41 | # create dependency graph from cookbooks 42 | graph = DepSelector::DependencyGraph.new 43 | 44 | env_constraints = data[:environment_constraints].inject({}) do |acc, env_constraint| 45 | name, version, constraint = env_constraint 46 | acc[name] = DepSelector::VersionConstraint.new(constraint_to_str(constraint, version)) 47 | acc 48 | end 49 | 50 | all_versions = [] 51 | 52 | data[:all_versions].each do | vsn| 53 | name, version_constraints = vsn 54 | version_constraints.each do |version_constraint| # todo: constraints become an array in ruby 55 | # due to the erlectricity conversion from 56 | # tuples 57 | version, constraints = version_constraint 58 | 59 | # filter versions based on environment constraints 60 | env_constraint = env_constraints[name] 61 | if (!env_constraint || env_constraint.include?(DepSelector::Version.new(version))) 62 | package_version = graph.package(name).add_version(DepSelector::Version.new(version)) 63 | constraints.each do |package_constraint| 64 | constraint_name, constraint_version, constraint = package_constraint 65 | version_constraint = DepSelector::VersionConstraint.new(constraint_to_str(constraint, constraint_version)) 66 | dependency = DepSelector::Dependency.new(graph.package(constraint_name), version_constraint) 67 | package_version.dependencies << dependency 68 | end 69 | end 70 | end 71 | 72 | # regardless of filter, add package reference to all_packages 73 | all_versions << graph.package(name) 74 | end 75 | 76 | run_list = data[:run_list].map do |run_list_item| 77 | item_name, item_constraint_version, item_constraint = run_list_item 78 | version_constraint = DepSelector::VersionConstraint.new(constraint_to_str(item_constraint, 79 | item_constraint_version)) 80 | DepSelector::SolutionConstraint.new(graph.package(item_name), version_constraint) 81 | end 82 | 83 | timeout_ms = data[:timeout_ms] 84 | selector = DepSelector::Selector.new(graph, (timeout_ms / 1000.0)) 85 | 86 | answer = begin 87 | solution = selector.find_solution(run_list, all_versions) 88 | packages = [] 89 | solution.each do |package, v| 90 | packages << [package, [v.major, v.minor, v.patch]] 91 | end 92 | [:ok, packages] 93 | rescue DepSelector::Exceptions::InvalidSolutionConstraints => e 94 | non_existent_cookbooks = e.non_existent_packages.inject([]) do |list, constraint| 95 | list << constraint.package.name 96 | end 97 | 98 | constrained_to_no_versions = e.constrained_to_no_versions.inject([]) do |list, constraint| 99 | list << constraint.to_s 100 | end 101 | 102 | error_detail = [[:non_existent_cookbooks, non_existent_cookbooks], 103 | [:constraints_not_met, constrained_to_no_versions]] 104 | 105 | [:error, :invalid_constraints, error_detail] 106 | rescue DepSelector::Exceptions::NoSolutionExists => e 107 | most_constrained_cookbooks = e.disabled_most_constrained_packages.inject([]) do |list, package| 108 | # WTF: this is the reported error format but I can't find this anywhere in the ruby code 109 | list << "#{package.name} = #{package.versions.first.to_s}" 110 | end 111 | 112 | non_existent_cookbooks = e.disabled_non_existent_packages.inject([]) do |list, package| 113 | list << package.name 114 | end 115 | 116 | error_detail = [[:message, e.message], 117 | [:unsatisfiable_run_list_item, e.unsatisfiable_solution_constraint.to_s], 118 | [:non_existent_cookbooks, non_existent_cookbooks], 119 | [:most_constrained_cookbooks, most_constrained_cookbooks]] 120 | 121 | [:error, :no_solution, error_detail] 122 | rescue DepSelector::Exceptions::TimeBoundExceeded, 123 | DepSelector::Exceptions::TimeBoundExceededNoSolution => e 124 | # While dep_selector differentiates between the two solutions, the opscode-chef 125 | # API returns the same error regardless of the timeout type. We'll swallow the 126 | # difference here and return a unified timeout to erchef 127 | [:error, :resolution_timeout] 128 | end 129 | rescue => e 130 | answer = [:error, :exception, e.message, [e.backtrace]] 131 | end 132 | 133 | answer 134 | end 135 | 136 | # data = JSON.parse!(File.read(ARGV[0]), symbolize_names: true) 137 | # pp data 138 | # pp solve(data) 139 | -------------------------------------------------------------------------------- /lib/chef/knife/depsolver.rb: -------------------------------------------------------------------------------- 1 | require 'chef/knife' 2 | require 'digest' 3 | 4 | module DepSelector 5 | class VersionConstraint 6 | attr_reader :missing_patch_level 7 | end 8 | end 9 | 10 | class Chef 11 | class Knife 12 | class Depsolver < Knife 13 | deps do 14 | end 15 | 16 | banner 'knife depsolver RUN_LIST' 17 | 18 | option :node, 19 | short: '-n', 20 | long: '--node NAME', 21 | description: 'Use the run list from a given node' 22 | 23 | option :timeout, 24 | short: '-t', 25 | long: '--timeout SECONDS', 26 | description: 'Set the local depsolver timeout. Only valid when using the --env-constraints and --universe options' 27 | 28 | option :capture, 29 | long: '--capture', 30 | description: 'Save the expanded run list, environment cookbook constraints and cookbook universe to files for local depsolving' 31 | 32 | option :env_constraints, 33 | long: '--env-constraints FILENAME', 34 | description: 'Use the environment cookbook constraints from FILENAME. REQUIRED when using the local depsolver.' 35 | 36 | option :universe, 37 | long: '--universe FILENAME', 38 | description: 'Use the cookbook universe from FILENAME. REQUIRED when using the local depsolver.' 39 | 40 | option :expanded_run_list, 41 | long: '--expanded-run-list FILENAME', 42 | description: 'Use the expanded run list from FILENAME. REQUIRED when using the local depsolver.' 43 | 44 | option :csv_universe_to_json, 45 | long: '--csv-universe-to-json FILENAME', 46 | description: 'Convert a CSV cookbook universe, FILENAME, to JSON.' 47 | 48 | option :filter_universe, 49 | long: '--filter-universe', 50 | description: 'Filter the cookbook universe by environment cookbook version constraints and an optional run list.' 51 | 52 | option :version_pin_cookbooks, 53 | long: '--version-pin-cookbooks FILENAME', 54 | description: 'Print the cookbooks and dependency data that would be sent to the depsolver.' 55 | 56 | def run 57 | begin 58 | DepSelector::Debug.log.level = Logger::INFO if defined?(DepSelector::Debug) 59 | use_local_depsolver = config[:universe] ? true : false 60 | if use_local_depsolver 61 | unless name_args.empty? 62 | puts "ERROR: Setting a run list on the command line is not compatible with the --universe option" 63 | exit! 64 | end 65 | if config[:node] 66 | puts "ERROR: The --node option is not compatible with the --universe option" 67 | exit! 68 | end 69 | if config[:environment] 70 | puts "ERROR: The --environment option is not compatible with the --universe option" 71 | exit! 72 | end 73 | if config[:capture] 74 | puts "ERROR: The --capture option is not compatible with the --universe option" 75 | exit! 76 | end 77 | else 78 | if (config[:env_constraints] || config[:expanded_run_list]) 79 | puts "ERROR: The --env-constraints and --expanded-run-list options require the --universe option to be set" 80 | exit! 81 | end 82 | if config[:timeout] 83 | msg("ERROR: The --timeout option requires the --env-constraints, --universe and --expanded-run-list options to be set") 84 | exit! 85 | end 86 | if config[:filter_universe] 87 | msg("ERROR: The --filter-universe option requires the --universe option and optionally the --env-constraints and/or --expanded-run-list options") 88 | exit! 89 | end 90 | end 91 | 92 | timeout = (config[:timeout].to_f * 1000).to_i if config[:timeout] 93 | timeout ||= 5 * 1000 94 | 95 | if config[:csv_universe_to_json] 96 | unless File.file?(config[:csv_universe_to_json]) 97 | msg("ERROR: #{config[:csv_universe_to_json]} does not exist or is not a file.") 98 | exit! 99 | end 100 | universe = Hash.new { |hash, key| hash[key] = Hash.new } 101 | IO.foreach(config[:csv_universe_to_json]) do |line| 102 | name, version, updated_at, dependencies = line.split(",", 4) 103 | universe[name][version] = {updated_at: updated_at, dependencies: JSON.parse(dependencies)} 104 | end 105 | 106 | universe_json = JSON.pretty_generate(universe) 107 | universe_filename = "universe-#{Time.now.strftime("%Y-%m-%d-%H.%M.%S")}-#{Digest::SHA1.hexdigest(universe_json)}.txt" 108 | IO.write(universe_filename, universe_json) 109 | puts "Cookbook universe saved to #{universe_filename}" 110 | exit! 111 | end 112 | 113 | if config[:version_pin_cookbooks] 114 | unless File.file?(config[:version_pin_cookbooks]) 115 | msg("ERROR: #{config[:version_pin_cookbooks]} does not exist or is not a file.") 116 | exit! 117 | end 118 | cookbooks = JSON.parse(IO.read(config[:version_pin_cookbooks])) 119 | version_pinned_cookbooks = Hash.new 120 | cookbooks.each do |cookbook_name, versions| 121 | max_version = versions.keys.max_by {|v| DepSelector::Version.new(v) } 122 | version_pinned_cookbooks[cookbook_name] = "= #{max_version}" if max_version 123 | end 124 | puts JSON.pretty_generate({name: "version-pinned-cookbooks", cookbook_versions: version_pinned_cookbooks}) 125 | exit! 126 | end 127 | 128 | if config[:node] 129 | node = Chef::Node.load(config[:node]) 130 | else 131 | node = Chef::Node.new 132 | node.name('depsolver-tmp-node') 133 | 134 | if config[:expanded_run_list] 135 | unless File.file?(config[:expanded_run_list]) 136 | msg("ERROR: #{config[:expanded_run_list]} does not exist or is not a file.") 137 | exit! 138 | end 139 | contents = JSON.parse(IO.read(config[:expanded_run_list])) 140 | if !(contents.key?('expanded_run_list') && contents['expanded_run_list'].is_a?(Array)) 141 | msg("ERROR: #{config[:expanded_run_list]} does not contain an expanded run list array.") 142 | exit! 143 | else 144 | expanded_run_list = contents['expanded_run_list'] 145 | expanded_run_list.each do |arg| 146 | node.run_list.add(arg) 147 | end 148 | end 149 | else 150 | run_list = name_args.map {|item| item.to_s.split(/,/) }.flatten.each{|item| item.strip! } 151 | run_list.delete_if {|item| item.empty? } 152 | 153 | run_list.each do |arg| 154 | node.run_list.add(arg) 155 | end 156 | end 157 | end 158 | 159 | # node.chef_environment must be set before expanding the run list in case the run list includes 160 | # roles with environment specific run lists 161 | node.chef_environment = config[:environment] if config[:environment] 162 | run_list_expansion = node.run_list.expand(node.chef_environment, 'server') 163 | expanded_run_list_with_versions = run_list_expansion.recipes.with_version_constraints_strings 164 | 165 | if config[:capture] 166 | if node.chef_environment == '_default' 167 | environment_cookbook_versions = Hash.new 168 | else 169 | environment_cookbook_versions = Chef::Environment.load(node.chef_environment).cookbook_versions 170 | end 171 | env = { name: node.chef_environment, cookbook_versions: environment_cookbook_versions } 172 | environment_constraints_json = JSON.pretty_generate(env) 173 | environment_constraints_filename = "#{node.chef_environment}-environment-#{Time.now.strftime("%Y-%m-%d-%H.%M.%S")}-#{Digest::SHA1.hexdigest(environment_constraints_json)}.txt" 174 | IO.write(environment_constraints_filename, environment_constraints_json) 175 | puts "Environment constraints saved to #{environment_constraints_filename}" 176 | 177 | begin 178 | universe = rest.get_rest("universe") 179 | universe_json = JSON.pretty_generate(universe) 180 | universe_filename = "" 181 | rest.url.to_s.match(".*/organizations/(.*)/?") { universe_filename = "#{$1}-" } 182 | universe_filename += "universe-#{Time.now.strftime("%Y-%m-%d-%H.%M.%S")}-#{Digest::SHA1.hexdigest(universe_json)}.txt" 183 | IO.write(universe_filename, universe_json) 184 | puts "Cookbook universe saved to #{universe_filename}" 185 | rescue Net::HTTPServerException 186 | puts "WARNING: The cookbook universe API endpoint is not available." 187 | puts "WARNING: Try capturing the cookbook universe using the SQL query found in the knife-depsolver README." 188 | puts "WARNING: Then convert the results using knife-depsolver's --csv-universe-to-json option" 189 | end 190 | exit 191 | end 192 | 193 | if config[:filter_universe] 194 | data = get_depsolver_data(node, expanded_run_list_with_versions, timeout) 195 | puts JSON.pretty_generate(filter_universe(data)) 196 | exit! 197 | end 198 | 199 | depsolver_results = Hash.new 200 | if use_local_depsolver 201 | data = get_depsolver_data(node, expanded_run_list_with_versions, timeout) 202 | 203 | depsolver_start_time = Time.now 204 | 205 | solution = solve(data) 206 | 207 | depsolver_finish_time = Time.now 208 | 209 | if solution.first == :ok 210 | solution.last.map { |ckbk| ckbk_name, ckbk_version = ckbk; depsolver_results[ckbk_name] = ckbk_version.join('.') } 211 | else 212 | status, error_type, error_detail = solution 213 | depsolver_error = { error_type => error_detail } 214 | end 215 | else 216 | begin 217 | chef_server_version = rest.get(server_url.sub(/organizations.*/, 'version')).split("\n")[0] 218 | rescue Net::HTTPServerException 219 | chef_server_version = "unknown" 220 | end 221 | 222 | depsolver_start_time = Time.now 223 | 224 | ckbks = rest.post_rest("environments/" + node.chef_environment + "/cookbook_versions", { "run_list" => expanded_run_list_with_versions }) 225 | 226 | depsolver_finish_time = Time.now 227 | 228 | ckbks.each do |name, ckbk| 229 | version = ckbk.is_a?(Hash) ? ckbk['version'] : ckbk.version 230 | depsolver_results[name] = version 231 | end 232 | end 233 | rescue Net::HTTPServerException => e 234 | api_error = {} 235 | api_error[:error_code] = e.response.code 236 | api_error[:error_message] = e.response.message 237 | begin 238 | api_error[:error_body] = JSON.parse(e.response.body) 239 | rescue JSON::ParserError 240 | end 241 | rescue => e 242 | msg("ERROR: #{e.message}") 243 | exit! 244 | ensure 245 | local_software = Hash.new 246 | %w(chef-dk chef dep_selector).each do |gem_name| 247 | begin 248 | local_software[gem_name] = Gem::Specification.find_by_name(gem_name).version 249 | rescue Gem::MissingSpecError 250 | end 251 | end 252 | 253 | results = {} 254 | results[:local_software] = local_software unless local_software.empty? 255 | if use_local_depsolver 256 | results[:depsolver] = "used local depsolver" 257 | else 258 | results[:depsolver] = {"used chef server" => chef_server_version} unless chef_server_version.nil? 259 | end 260 | results[:node] = node.name unless node.nil? || node.name.nil? 261 | results[:environment] = node.chef_environment unless node.chef_environment.nil? 262 | results[:run_list] = node.run_list unless node.nil? || node.run_list.nil? 263 | results[:expanded_run_list] = expanded_run_list_with_versions unless expanded_run_list_with_versions.nil? 264 | results[:depsolver_results] = depsolver_results unless depsolver_results.nil? || depsolver_results.empty? 265 | results[:depsolver_cookbook_count] = depsolver_results.count unless depsolver_results.nil? || depsolver_results.empty? 266 | results[:depsolver_elapsed_ms] = ((depsolver_finish_time - depsolver_start_time) * 1000).to_i unless depsolver_finish_time.nil? 267 | results[:depsolver_error] = depsolver_error unless depsolver_error.nil? 268 | results[:api_error] = api_error unless api_error.nil? 269 | 270 | if config[:capture] 271 | results_json = JSON.pretty_generate(results) 272 | expanded_run_list_filename = "expanded-run-list-#{Time.now.strftime("%Y-%m-%d-%H.%M.%S")}-#{Digest::SHA1.hexdigest(results_json)}.txt" 273 | IO.write(expanded_run_list_filename, results_json) 274 | puts "Expanded run list saved to #{expanded_run_list_filename}" 275 | else 276 | msg(JSON.pretty_generate(results)) 277 | end 278 | end 279 | end 280 | 281 | def get_depsolver_data(node, expanded_run_list_with_versions, timeout) 282 | if config[:env_constraints] 283 | unless File.file?(config[:env_constraints]) 284 | msg("ERROR: #{config[:env_constraints]} does not exist or is not a file.") 285 | exit! 286 | end 287 | env = JSON.parse(IO.read(config[:env_constraints])) 288 | if env['name'].to_s.empty? 289 | msg("ERROR: #{config[:env_constraints]} does not contain an environment name.") 290 | exit! 291 | else 292 | node.chef_environment = env['name'] 293 | end 294 | if !env['cookbook_versions'].is_a?(Hash) 295 | msg("ERROR: #{config[:env_constraints]} does not contain a Hash of cookbook version constraints.") 296 | exit! 297 | else 298 | environment_cookbook_versions = env['cookbook_versions'] 299 | end 300 | else 301 | environment_cookbook_versions = Hash.new 302 | end 303 | 304 | env_ckbk_constraints = environment_cookbook_versions.map do |ckbk_name, ckbk_constraint| 305 | [ckbk_name, ckbk_constraint.split.reverse].flatten 306 | end 307 | 308 | unless File.file?(config[:universe]) 309 | msg("ERROR: #{config[:universe]} does not exist or is not a file.") 310 | exit! 311 | end 312 | universe = JSON.parse(IO.read(config[:universe])) 313 | if !universe.is_a?(Hash) 314 | msg("ERROR: #{config[:universe]} does not contain a cookbook universe Hash.") 315 | exit! 316 | end 317 | 318 | all_versions = universe.map do |ckbk_name, ckbk_metadata| 319 | ckbk_versions = ckbk_metadata.map do |version, version_metadata| 320 | [version, version_metadata['dependencies'].map { |dep_ckbk_name, dep_ckbk_constraint| [dep_ckbk_name, dep_ckbk_constraint.split.reverse].flatten }] 321 | end 322 | [ckbk_name, ckbk_versions] 323 | end 324 | 325 | expanded_run_list_with_split_versions = expanded_run_list_with_versions.map do |run_list_item| 326 | name, version = run_list_item.split('@') 327 | name.sub!(/::.*/, '') 328 | version ? [name, version] : name 329 | end 330 | 331 | depsolver_data = {environment_constraints: env_ckbk_constraints, all_versions: all_versions, run_list: expanded_run_list_with_split_versions, timeout_ms: timeout} 332 | depsolver_data 333 | end 334 | 335 | def filter_universe(data) 336 | # create dependency graph from cookbooks 337 | graph = DepSelector::DependencyGraph.new 338 | 339 | env_constraints = data[:environment_constraints].inject({}) do |acc, env_constraint| 340 | name, version, constraint = env_constraint 341 | acc[name] = DepSelector::VersionConstraint.new(constraint_to_str(constraint, version)) 342 | acc 343 | end 344 | 345 | all_versions = [] 346 | 347 | data[:all_versions].each do | vsn| 348 | name, version_constraints = vsn 349 | version_constraints.each do |version_constraint| # todo: constraints become an array in ruby 350 | # due to the erlectricity conversion from 351 | # tuples 352 | version, constraints = version_constraint 353 | 354 | # filter versions based on environment constraints 355 | env_constraint = env_constraints[name] 356 | if (!env_constraint || env_constraint.include?(DepSelector::Version.new(version))) 357 | package_version = graph.package(name).add_version(DepSelector::Version.new(version)) 358 | constraints.each do |package_constraint| 359 | constraint_name, constraint_version, constraint = package_constraint 360 | version_constraint = DepSelector::VersionConstraint.new(constraint_to_str(constraint, constraint_version)) 361 | dependency = DepSelector::Dependency.new(graph.package(constraint_name), version_constraint) 362 | package_version.dependencies << dependency 363 | end 364 | end 365 | end 366 | 367 | # regardless of filter, add package reference to all_packages 368 | all_versions << graph.package(name) 369 | end 370 | 371 | run_list = data[:run_list].map do |run_list_item| 372 | item_name, item_constraint_version, item_constraint = run_list_item 373 | version_constraint = DepSelector::VersionConstraint.new(constraint_to_str(item_constraint, 374 | item_constraint_version)) 375 | DepSelector::SolutionConstraint.new(graph.package(item_name), version_constraint) 376 | end 377 | 378 | timeout_ms = data[:timeout_ms] 379 | selector = DepSelector::Selector.new(graph, (timeout_ms / 1000.0)) 380 | 381 | if run_list.empty? 382 | constrained_cookbook_set = selector.dep_graph.packages.values 383 | else 384 | constrained_cookbook_set = selector.send(:trim_unreachable_packages, selector.dep_graph, run_list) 385 | end 386 | filtered_universe = Hash.new { |h,k| h[k] = Hash.new { |h,k| h[k] = Hash.new { |h,k| h[k] = Hash.new } } } 387 | constrained_cookbook_set.each do |ckbk| 388 | ckbk.versions.each do |ckbk_version| 389 | filtered_universe[ckbk.name][ckbk_version.version]["dependencies"] = Hash.new 390 | ckbk_version.dependencies.each do |ckbk_version_dep| 391 | constraint = ckbk_version_dep.constraint 392 | constraint_version = constraint.missing_patch_level ? "#{constraint.version.major}.#{constraint.version.minor}" : "#{constraint.version}" 393 | filtered_universe[ckbk.name][ckbk_version.version]["dependencies"][ckbk_version_dep.package.name] = "#{constraint.op} #{constraint_version}" 394 | end 395 | end 396 | end 397 | filtered_universe 398 | end 399 | end 400 | end 401 | end 402 | -------------------------------------------------------------------------------- /lib/knife-depsolver/version.rb: -------------------------------------------------------------------------------- 1 | module KnifeDepsolver 2 | VERSION = "2.2.0" 3 | end 4 | --------------------------------------------------------------------------------