Debian Codegraph @

doc/articles/fractal.2.html

raw
1 ---
2 layout: default
3 title: Fractal Application (2/3)
4 srcroot: https://github.com/google/jsonnet/blob/master/case_studies
5 service_jsonnet: https://github.com/google/jsonnet/blob/master/case_studies/fractal/service.jsonnet
6 packer_jsonnet: https://github.com/google/jsonnet/blob/master/case_studies/fractal/lib/packer.libsonnet
7 terraform_jsonnet: https://github.com/google/jsonnet/blob/master/case_studies/fractal/lib/terraform.libsonnet
8 cassandra_jsonnet: https://github.com/google/jsonnet/blob/master/case_studies/fractal/lib/cassandra.libsonnet
9 template_jsonnet: https://github.com/google/jsonnet/blob/master/case_studies/fractal/credentials.libsonnet.TEMPLATE
10 makefile: https://github.com/google/jsonnet/blob/master/case_studies/fractal/Makefile
11 ---
12
13 <div class="hgroup">
14 <div class="hgroup-inline">
15 <div class="panel">
16 <h1 id=top>
17 <p class=jump_to_page_top>
18 Pages <a href="fractal.1.html">1</a>,
19 2,
20 <a href="fractal.3.html">3</a>
21 </p>
22 Fractal Application
23 </h1>
24 </div>
25 <div style="clear: both"></div>
26 </div>
27 </div>
28
29
30 <div class="hgroup">
31 <div class="hgroup-inline">
32 <div class="panel">
33 <h2 id=config>Configuration Structure</h2>
34 </div>
35 <div style="clear: both"></div>
36 </div>
37 </div>
38
39 <div class="hgroup">
40 <div class="hgroup-inline">
41 <div class="panel">
42 <p>
43 In this section we describe the ways in which Jsonnet aids with the configuration of the
44 Fractal application. These are the three main productivity benefits when using Jsonnet:
45 </p>
46 <ul>
47 <li>
48 Centralization: Bringing all configuration into the same place, where it can be
49 maintained as a single entity in a uniform format. This allows maintaining the
50 application as an application and not as a disparate set of components.
51 </li>
52 <li>
53 Error avoidance: Values that must be synchronized between different parts of the
54 configuration can be factored out to a single variable, so that they are easy to maintain
55 and never go out of sync. For example the Tile Generation Service contains an Nginx
56 configuration to listen on a particular port, but that port must also be open in the
57 firewall configuration, and known to the clients that need to connect to it. Specifying
58 this port only once makes it a lot easier to avoid errors when changing the port later on.
59 </li>
60 <li>
61 Brevity: Given a large number of similar definitions, Jsonnet's object model allows
62 abstracting the common parts into templates that can be instantiated very concisely. For
63 example all cloud instances have some common configuration, and the two HTTP services are
64 also very similar. Each instantiation of a template can override specific details in
65 order to express how it deviates from the norm. The net result is a reduction in the line
66 count as well as making those critical differences between definitions more clear and not
67 lost in a sea of repeated data.
68 </li>
69 </ul>
70 <p>
71 The configuration is logically separated into several files via <code>import</code>
72 constructs. This is to promote abstraction and re-usability (some of our templates could be
73 used by other applications, so are separated into libraries), as well as having a separate
74 credentials file (to avoid accidental checkin). Note that Jsonnet did not mandate this file
75 structure; other separations (or a giant single file) would also have been possible.
76 </p>
77 <p>
78 When the imports are realized, the result is a single configuration which yields a JSON
79 packer configuration for each image (*.packer.json) and the JSON Terraform configuration
80 (terraform.tf), using <a href="/implementation/commandline.html#multi">multiple file
81 output</a>. Those configurations in turn embed other configurations for the application
82 software that will run on the instances. The top-level structure of the generated
83 configuration is therefore as follows (with the content of each file elided for clarity).
84 </p>
85
86 <pre class=medium>{
87 "appserv.packer.json": ...,
88 "cassandra.packer.json": ...,
89 "tilegen.packer.json": ...,
90 "terraform.tf": ...
91 }</pre>
92 <p>
93 The configuration is built from the following input files:
94 </p>
95 <ul>
96 <li>
97 <a href="{{ page.service_jsonnet }}"><code>service.jsonnet</code></a>: The top level file
98 that imports the others. This is the filename that is given to the jsonnet command line
99 utility. In it are all the details that define the Fractal example application, as a list
100 of packer images and a Terraform configuration that creates cloud instances using those
101 images. Note the first few lines import the other Jsonnet files and store their contents
102 in top-level scoped variables (of the same names). When we access definitions from those
103 libraries (e.g. templates to override) we do so through the top-level variables.
104 </li>
105 <li>
106 <tt>credentials.jsonnet</tt>: User and superuser keys for Cassandra, and Google Cloud
107 Platform project name. You must create this file yourself, based on this <a href="{{
108 page.template_jsonnet }}">sample file</a>.
109 </li>
110 <li>
111 <a href="{{ page.packer_jsonnet }}"><code>lib/packer.jsonnet</code></a>: Some templates to
112 help with writing Packer configurations.
113 </li>
114 <li>
115 <a href="{{ page.terraform_jsonnet }}"><code>lib/terraform.jsonnet</code></a>: Some
116 templates to help with writing Terraform configurations.
117 </li>
118 <li>
119 <a href="{{ page.cassandra_jsonnet }}"><code>lib/cassandra.jsonnet</code></a>: Some
120 templates to help with writing Packer and Terraform configurations for Cassandra.
121 </li>
122 </ul>
123 <p>
124 Note that the Jsonnet template libraries also include some definitions not used in this
125 example application, e.g., PostgreSQL and MySQL templates. Those can be ignored.
126 </p>
127 <p>
128 To integrate Jsonnet with Packer and Terraform, a <a href="{{ page.makefile
129 }}"><code>Makefile</code></a> is used. This first runs Jsonnet on the configuration and
130 then runs Packer / Terraform on the resulting files (if they have changed). The choice of
131 'glue' tool is arbitrary, we could also have used a small Python script. We chose
132 <tt>make</tt> because it is well understood, available everywhere, and does three things
133 that we want: Invoke other programs, run things in parallel, and avoid repeating work that
134 is already complete. For example, Packer is only invoked if its configuration file has
135 changed, and the three image builds will proceed in parallel (they take a few minutes each).
136 </p>
137 <p>
138 Ignoring the re-usable templates, whitespace, and comments, the Jsonnet configuration is 217
139 lines (9.7kB). The generated Packer and Terraform files are 740 lines (25kB) in total.
140 This demonstrates the productivity benefits of using template expansion when writing
141 configurations.
142 </p>
143 </div>
144 <div style="clear: both"></div>
145 </div>
146 </div>
147
148
149 <div class="hgroup">
150 <div class="hgroup-inline">
151 <div class="panel">
152 <h3 id=config_whirlwind>Whirlwind Tour</h3>
153 </div>
154 <div style="clear: both"></div>
155 </div>
156 </div>
157
158 <div class="hgroup">
159 <div class="hgroup-inline">
160 <div class="panel">
161 <p>
162 The fractal example is a complete realistic application and therefore its configuration has
163 many technical details. In particular, it embeds configurations for various pieces of
164 off-the-shelf software that we don't want to go into in much depth. However we would like
165 to draw attention to some particular uses of Jsonnet within the configuration. We'll gladly
166 field specific questions on the <a
167 href="https://groups.google.com/forum/#!forum/jsonnet">mailing list</a>.
168 </p>
169 </div>
170 <div style="clear: both"></div>
171 </div>
172 </div>
173
174
175 <div class="hgroup">
176 <div class="hgroup-inline">
177 <div class="panel">
178 <h4 id="config_whirlwind_packer">Packer And Application Configuration</h4>
179 </div>
180 <div style="clear: both"></div>
181 </div>
182 </div>
183
184 <div class="hgroup">
185 <div class="hgroup-inline">
186 <div class="panel">
187 <p>
188 Each Packer configuration is, at its core, a list of imperative actions to be performed in
189 sequence by a VM, after which the disk is frozen to create the desired image. The actions
190 are called <i>provisioners</i>. Jsonnet is used to simplify the provisioner list by
191 eliminating duplication and encouraging abstraction. Generic templates for specific
192 off-the-shelf software are defined in re-usable libraries, which are then referenced from <a
193 href="{{ page.service_jsonnet }}"><code>service.jsonnet</code></a> and, as needed,
194 overridden with some fractal application details. Generic provisioners are also provided
195 for easy installation of packages via package managers, creation of specific files / dirs,
196 etc.
197 </p>
198 <p>
199 In addition, the <code>ImageMixin</code> object in <a href="{{ page.service_jsonnet
200 }}"><code>service.jsonnet</code></a> is used to factor out common fractal-specific
201 configuration from the three images. Note that it is a variable, so will not appear in the
202 output. Factored out image config includes the Google Cloud Platform project id and
203 filename of the service account key. Since all the images are derived ultimately from the
204 <code>GcpDebian</code> image (in <a href="{{ page.packer_jsonnet
205 }}"><code>lib/packer.jsonnet</code></a>), and this image includes <tt>apt</tt> &amp;
206 <tt>pip</tt> provisioners (discussed shortly), this is also a good place to ensure some
207 basic packages are installed on every image.
208 </p>
209 <pre class="medium">local ImageMixin = {
210 project_id: credentials.project,
211 account_file: "service_account_key.json",
212
213 // For debugging:
214 local network_debug = ["traceroute", "lsof", "iptraf", "tcpdump", "host", "dnsutils"],
215 aptPackages +: ["vim", "git", "psmisc", "screen", "strace" ] + network_debug,
216 }, </pre>
217 <p>
218 Both the application server's image configuration <tt>appserv.packer.json</tt> and the tile
219 generation service's image configuration <tt>tilegen.packer.json</tt> extend
220 <code>MyFlaskImage</code>, which exists merely to add the aforementioned
221 <code>ImageMixin</code> to the <code>GcpDebianNginxUwsgiFlaskImage</code> template from <a
222 href="{{ page.packer_jsonnet }}"><code>lib/packer.jsonnet</code></a>. That template builds
223 on the basic <code>GcpDebianImage</code> template from the same library, and adds all the
224 packages (and default configuration) for both Nginx and uWSGI:
225 </p>
226 <pre class="medium">local MyFlaskImage = packer.GcpDebianNginxUwsgiFlaskImage + ImageMixin,</pre>
227 <p>
228 In Jsonnet we use JSON as the canonical data model and convert to other formats as needed.
229 An example of this is the uWSGI configuration, an <a
230 href="https://en.wikipedia.org/wiki/INI_file">INI</a> file, which is specified in Jsonnet
231 under the <code>uwsgiConf</code> field in <code>GcpDebianNginxUwsgiFlaskImage</code>. The
232 JSON version is converted to INI by the call to <code>std.manifestIni</code> (documented <a
233 href="/docs/stdlib.html">here</a>) in the provisioner immediately below it. Representing
234 the INI file with the JSON object model (instead of as a string) allows elements of the
235 uWSGI configuration (such as the filename of the UNIX domain socket) to be easily kept in
236 sync with other elements of the configuration (Nginx also needs to know it). If the
237 application is configured with JSON, or even YAML, then no conversion is required. An
238 example of that is the default Cassandra configuration file held in the <code>conf</code>
239 field of <a href="{{ page.cassandra_jsonnet }}"><code>lib/cassandra.jsonnet</code></a>.
240 </p>
241 <p>
242 Looking back at <tt>appserv.packer.json</tt> and <tt>tilegen.packer.json</tt> in <a href="{{
243 page.service_jsonnet }}"><code>service.jsonnet</code></a>, while both use Nginx/uWSGI/Flask
244 there are some subtle differences. Since the HTTP request handlers are different in each
245 case, the module (uWSGI entrypoint) and also required packages are different. Firstly, the
246 tile generation image needs a provisioner to build the C++ code. Secondly, since the
247 application server talks to the Cassandra database using cassandra-driver, which interferes
248 with pre-forking, it is necessary to override the <code>lazy</code> field of the uWSGI
249 configuration in that image. This is an example of how an abstract template can unify two
250 similar parts of the configuration, while still allowing the overriding of small details as
251 needed. Note also that such precise manipulation of configuration details would be much
252 harder if the uWSGI configuration was represented as a single string instead of as a
253 structure within the object model.
254 </p>
255 <pre class="medium">"appserv.packer.json": MyFlaskImage {
256 name: "appserv-v20141222-0300",
257 module: "main", // Entrypoint in the Python code.
258 pipPackages +: ["httplib2", "cassandra-driver", "blist"],
259 uwsgiConf +: { lazy: "true" }, // cassandra-driver does not survive fork()
260 ...
261 },
262 </pre>
263 <p>
264 Going up to the top of the template hierarchy we have <code>GcpDebianImage</code> and
265 finally <code>GcpImage</code> in <a href="{{ page.packer_jsonnet
266 }}"><code>lib/packer.jsonnet</code></a>. The latter gives the Packer builder configuration
267 for Google Cloud Platform, bringing out some fields to the top level (essentially hiding the
268 <code>builder</code> sub-object). We can hide the builder configuration because we only
269 ever need one builder per image. We can support multiple cloud providers by deriving an
270 entire new Packer configuration at the top level, overriding as necessary to specialize for
271 that platform. The <code>GcpDebianImage</code> selects the base image (Backports) and adds
272 provisioners for apt and pip packages. The configuration of those provisioners (the list of
273 installed packages, and additional repositories / keys) is brought out to the top level of
274 the image configuration. By default, the lists are empty but sub-objects can override and
275 extend them as we saw with <tt>appserv.packer.json</tt>.
276 </p>
277 <p>
278 The actual provisioners <code>Apt</code> and <code>Pip</code> are defined further up <a
279 href="{{ page.packer_jsonnet }}"><code>lib/packer.jsonnet</code></a>. In their definitions,
280 one can see how the various shell commands are built up from the declarative lists of
281 repositories, package names, etc. Installing packages in a non-interactive context requires
282 a few extra switches and an environment variable, but the <code>Apt</code> provisioner
283 handles all that. Also note how these provisioners both derive from <code>RootShell</code>
284 (defined right at the top of the file) because those commands need to be run as root.
285 </p>
286 <p>
287 Note that everything discussed has been plain Jsonnet code. It is possible to create your
288 own provisioners (based on these or from scratch) in order to declaratively control packer
289 in new ways.
290 </p>
291 </div>
292 <div style="clear: both"></div>
293 </div>
294 </div>
295
296
297 <div class="hgroup">
298 <div class="hgroup-inline">
299 <div class="panel">
300 <h4 id="config_whirlwind_terraform">Terraform</h4>
301 </div>
302 <div style="clear: both"></div>
303 </div>
304 </div>
305
306 <div class="hgroup">
307 <div class="hgroup-inline">
308 <div class="panel">
309 <p>
310 The remainder of <a href="{{ page.service_jsonnet }}"><code>service.jsonnet</code></a>
311 generates the Terraform configuration that defines all the cloud resources that are required
312 to run the fractal web application. That includes the instances that actually run the
313 Packer images. It also includes the resources that configure network routing / firewalls,
314 load balancers, etc.
315 </p>
316 <p>
317 Terraform accepts two basic syntaxes, JSON and <a
318 href="https://github.com/hashicorp/hcl">HCL</a> (a more concise form of JSON). This
319 provides a data structure that specifies the resources required, but the model also has a
320 few computational features: Firstly, the structure has 'variables' which can be resolved by
321 <a href="https://en.wikipedia.org/wiki/String_interpolation">string interpolation</a> within
322 the resources. Also, all resources are also extended with a <tt>count</tt> parameter for
323 creating <i>n</i> replicas of that resource, and finally there is some support for importing
324 'modules', i.e., another Terraform configuration of resources (perhaps written by a third
325 party).
326 </p>
327 <p>
328 The interpolation feature is not just for variables, it is also used to reference attributes
329 of resources that are not known until after deployment (i.e., cannot be known during Jsonnet
330 execution time). For example, the generated IP address of a static IP resource called
331 <tt>foo</tt> can be referenced from a string in the definition of a resource <tt>bar</tt>
332 using the syntax <tt>${google_compute_address.foo.address}</tt>, which is resolved after the
333 deployment of <tt>foo</tt> in time for the deployment of <tt>bar</tt>.
334 </p>
335 <p>
336 We choose to emit JSON instead of HCL, as the latter would require conversion code. We also
337 do not make use of any of the Terraform language features, as Jsonnet provides similar or
338 greater capabilities in each of those domains, and doing it at the Jsonnet level allows
339 integration with the rest of the configuration. We do, however, use Terraform interpolation
340 syntax for resolving the "not known until deployment" attributes, e.g., in order to
341 configure the application server with the host:port endpoint of the tile processing service.
342 Such resolution cannot be performed by Jsonnet.
343 </p>
344 <p>
345 Going through <a href="{{ page.service_jsonnet }}"><code>service.jsonnet</code></a>, the
346 function <code>zone</code> is used to statically assign <a
347 href="https://cloud.google.com/compute/docs/zones">zones</a> to instances on a round robin
348 basis. All the instances extend from <code>FractalInstance</code>, which is parameterized
349 by the index <code>zone_hash</code> (it's actually just a function that takes zone_hash and
350 returns an instance template). It is this index that is used to compute the zone, as can be
351 seen in the body of <code>FractalInstance</code>. The zone is also a namespace for the
352 instance name, so when we list the instances behind each load balancer in the
353 <code>google_compute_target_pool</code> object, we compute the zone for each instance there
354 as well.
355 </p>
356 <pre class="medium">local zone(hash) =
357 local arr = [
358 "us-central1-a",
359 "us-central1-b",
360 "us-central1-f",
361 ];
362 arr[hash % std.length(arr)], </pre>
363 <p>
364 <code>FractalInstance</code> also specifies some default API access scopes and tags, as well
365 as the network over which the instances communicate. It extends <code>GcpInstance</code>
366 from <a href="{{ page.terraform_jsonnet }}"><code>lib/terraform.jsonnet</code></a>, which
367 brings default service account scopes, the network, and the startup script to the top level,
368 and provides some defaults for other parameters.
369 </p>
370 <p>
371 Back in <a href="{{ page.service_jsonnet }}"><code>service.jsonnet</code></a> we now have
372 the instance definitions themselves. These are arranged by image into clusters: application
373 server, db (Cassandra), and tile generation. Terraform expects the instances in the form of
374 a key/value map (i.e. a JSON object), since it identifies them internally with unique string
375 names. Thus the three clusters are each expressed as an object, and they are joined with
376 the object addition <code>+</code> operator.
377 </p>
378 <pre class="medium">google_compute_instance: {
379 ["appserv" + k]: ...
380 for k in [1, 2, 3]
381 } + {
382 db1: ...,
383 db2: ...,
384 db3: ...,
385 } + {
386 ["tilegen" + k]: ...
387 for k in [1, 2, 3, 4]
388 }</pre>
389 <p>
390 The <tt>appserv</tt> and <tt>tilegen</tt> replicas are given using an <a
391 href="/docs/tutorial.html#comprehension">object comprehension</a> in which the field name
392 and value are computed with <code>k</code> set to each index in the given list. The
393 variable <code>k</code> also ends up as an argument to <code>FractalInstance</code> and thus
394 defines the zone of the instance. In both cases, we also place a file
395 <tt>/var/www/conf.json</tt>. This is read on the instance by the application, at startup,
396 and used to configure the service. In the tilegen replicas the configuration comes from
397 <code>ApplicationConf</code> from the top of <a href="{{ page.service_jsonnet
398 }}"><code>service.jsonnet</code></a>. In the appserv instances, the same data is used, but
399 extended with some extra fields.
400 </p>
401 <pre class="medium">resource.FractalInstance(k) {
402 ...
403 conf:: ApplicationConf {
404 database_name: cassandraKeyspace,
405 database_user: cassandraUser,
406 database_pass: credentials.cassandraUserPass,
407 tilegen: "${google_compute_address.tilegen.address}",
408 db_endpoints: cassandraNodes,
409 },
410 startup_script +: [self.addFile(self.conf, "/var/www/conf.json")],
411 }</pre>
412 <p>
413 In both cases, the <a href="https://cloud.google.com/compute/docs/startupscript">startup
414 script</a> has added an extra line appended, computed by <code>self.addFile()</code>, a
415 method inherited from <code>GcpInstance</code> in <a href="{{ page.terraform_jsonnet
416 }}"><code>lib/terraform.jsonnet</code></a>. Examining its definition shows that it
417 generates a line of bash to actually add the file:
418 </p>
419 <pre class="medium">addFile(v, dest)::
420 "echo %s > %s" % [std.escapeStringBash(v), std.escapeStringBash(dest)], </pre>
421
422 <p>
423 Finally, the Cassandra cluster is deployed via an explicit list of three nodes (db1, db2,
424 db3). We attend to them individually, firstly because bringing up a Cassandra cluster from
425 scratch requires one node to have a special boot strapping role, and secondly because
426 database nodes are stateful and therefore less 'expendable' than application or tile server
427 nodes. All three nodes extend from the <code>CassandraInstance(i)</code> mixin, which is
428 where they get their common configuration. As with <code>FractalInstance(i)</code>, the
429 integer parameter is used to drive the zone. The bootstrap behavior of the first node is
430 enabled by extending <code>GcpStarterMixin</code> instead of <code>GcpTopUpMixin</code>.
431 The starter mixin has extra logic to initialize the database, which we pass in the form of a
432 <a href="https://cassandra.apache.org/doc/cql/CQL.html">CQL</a> script to create the
433 database and replication factor for one of its internal tables. There is some fancy
434 footwork required to get Cassandra into a stable state without exposing it to the network in
435 a passwordless state. All of that is thankfully hidden behind the two re-usable mixins in
436 <a href="{{ page.cassandra_jsonnet }}"><code>lib/cassandra.jsonnet</code></a>.
437 </p>
438 </div>
439 <div style="clear: both"></div>
440 </div>
441 </div>
442
443 <div class="hgroup">
444 <div class="hgroup-inline">
445 <div class="panel">
446 <p class=jump_to_page>
447 Pages <a href="fractal.1.html">1</a>,
448 2,
449 <a href="fractal.3.html">3</a>
450 </p>
451 </div>
452 <div style="clear: both"></div>
453 </div>
454 </div>